code stringlengths 2 1.05M |
|---|
import * as React from 'react';
import { expect } from 'chai';
import { createClientRender, describeConformanceV5, screen } from 'test/utils';
import Paper, { paperClasses } from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import MobileStepper, { mobileStepperClasses as classes } from '@material-ui/core/MobileStepper';
import KeyboardArrowRight from '../internal/svg-icons/KeyboardArrowRight';
import KeyboardArrowLeft from '../internal/svg-icons/KeyboardArrowLeft';
describe('<MobileStepper />', () => {
const render = createClientRender();
const defaultProps = {
steps: 2,
nextButton: (
<Button aria-label="next">
Next
<KeyboardArrowRight />
</Button>
),
backButton: (
<Button aria-label="back">
<KeyboardArrowLeft />
Back
</Button>
),
};
describeConformanceV5(<MobileStepper {...defaultProps} />, () => ({
classes,
inheritComponent: Paper,
render,
muiName: 'MuiMobileStepper',
testVariantProps: { variant: 'progress' },
testDeepOverrides: { slotName: 'dot', slotClassName: classes.dot },
testStateOverrides: { prop: 'position', value: 'static', styleKey: 'positionStatic' },
refInstanceof: window.HTMLDivElement,
skip: ['componentProp', 'componentsProp'],
}));
it('should render a Paper with 0 elevation', () => {
const { container } = render(<MobileStepper {...defaultProps} />);
expect(container.firstChild).to.have.class(paperClasses.elevation0);
});
it('should render with the bottom class if position prop is set to bottom', () => {
const { container } = render(<MobileStepper {...defaultProps} position="bottom" />);
expect(container.firstChild).to.have.class(classes.positionBottom);
});
it('should render with the top class if position prop is set to top', () => {
const { container } = render(<MobileStepper {...defaultProps} position="top" />);
expect(container.firstChild).to.have.class(classes.positionTop);
});
it('should render two buttons', () => {
render(<MobileStepper {...defaultProps} />);
expect(screen.getAllByRole('button')).to.have.lengthOf(2);
});
it('should render the back button', () => {
const { queryByTestId, getByRole } = render(<MobileStepper {...defaultProps} />);
const backButton = getByRole('button', { name: 'back' });
expect(backButton).not.to.equal(null);
expect(queryByTestId('KeyboardArrowLeftIcon')).not.to.equal(null);
});
it('should render next button', () => {
const { getByRole, queryByTestId } = render(<MobileStepper {...defaultProps} />);
const nextButton = getByRole('button', { name: 'next' });
expect(nextButton).not.to.equal(null);
expect(queryByTestId('KeyboardArrowRightIcon')).not.to.equal(null);
});
it('should render two buttons and text displaying progress when supplied with variant text', () => {
const { container } = render(
<MobileStepper {...defaultProps} variant="text" activeStep={1} steps={3} />,
);
expect(container.firstChild.textContent).to.equal('Back2 / 3Next');
});
it('should render dots when supplied with variant dots', () => {
const { container } = render(<MobileStepper {...defaultProps} variant="dots" />);
expect(container.querySelectorAll(`.${classes.dots}`)).to.have.lengthOf(1);
});
it('should render a dot for each step when using dots variant', () => {
const { container } = render(<MobileStepper {...defaultProps} variant="dots" />);
expect(container.querySelectorAll(`.${classes.dot}`)).to.have.lengthOf(2);
});
it('should render the first dot as active if activeStep is not set', () => {
const { container } = render(<MobileStepper {...defaultProps} variant="dots" />);
expect(container.querySelector(`.${classes.dot}`)).to.has.class(classes.dotActive);
});
it('should honor the activeStep prop', () => {
const { container } = render(<MobileStepper {...defaultProps} variant="dots" activeStep={1} />);
expect(container.querySelectorAll(`.${classes.dot}`)[1]).to.has.class(classes.dotActive);
});
it('should render a <LinearProgress /> when supplied with variant progress', () => {
render(<MobileStepper {...defaultProps} variant="progress" />);
expect(screen.queryByRole('progressbar')).not.to.equal(null);
});
it('should calculate the <LinearProgress /> value correctly', () => {
const { rerender } = render(<MobileStepper {...defaultProps} variant="progress" steps={3} />);
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).to.equal('0');
rerender(<MobileStepper {...defaultProps} variant="progress" steps={3} activeStep={1} />);
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).to.equal('50');
rerender(<MobileStepper {...defaultProps} variant="progress" steps={3} activeStep={2} />);
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).to.equal('100');
});
});
|
#!/usr/bin/env node
'use strict';
/**
* Third-party requires
*/
let chalk = require("chalk");
let stdin = process.openStdin();
// Retrieving options from CLI
let prefix = process.argv.filter(el => el.indexOf("--prefix=") > -1).pop();
prefix = prefix ? prefix.split("=").pop().toUpperCase() : "";
let color = process.argv.filter(el => el.indexOf("--color=") > -1).pop();
color = color ? color.split("=").pop() : "white";
// Intercepting outputs from previous command's stdout and rewriting it with style ;)
stdin.on('data', chunk => {
chunk = chunk.toString();
for (let line of chunk.split('\n')) {
if (line !== '') {
console.log(chalk[ color ](chalk.bold('[' + prefix + ']'), line));
}
}
});
|
/**
* Broadcast updates to client when the model changes
*/
'use strict';
var Oauth = require('./oauth.model');
exports.register = function(socket) {
Oauth.schema.post('save', function (doc) {
onSave(socket, doc);
});
Oauth.schema.post('remove', function (doc) {
onRemove(socket, doc);
});
}
function onSave(socket, doc, cb) {
socket.emit('oauth:save', doc);
}
function onRemove(socket, doc, cb) {
socket.emit('oauth:remove', doc);
} |
/**
* Created by lenovo on 2016-09-08.
*/
requirejs.config({
// pathsオプションの設定。"module/name": "path"を指定します。拡張子(.js)は指定しません。
paths: {
"jquery.showLoading": web_path + "/plugin/loading/js/jquery.showLoading.min",
"csrf": web_path + "/js/util/csrf",
"attribute_extensions": web_path + "/js/util/attribute_extensions",
"jquery.entropizer": web_path + "/plugin/jquery_entropizer/js/jquery-entropizer.min",
"entropizer": web_path + "/plugin/jquery_entropizer/js/entropizer.min"
},
// shimオプションの設定。モジュール間の依存関係を定義します。
shim: {
"jquery.showLoading": {
// jQueryに依存するのでpathsで設定した"module/name"を指定します。
deps: ["jquery"]
}
}
});
/*
捕获全局错误
*/
requirejs.onError = function (err) {
console.log(err.requireType);
if (err.requireType === 'timeout') {
console.log('modules: ' + err.requireModules);
}
throw err;
};
// require(["module/name", ...], function(params){ ... });
require(["jquery", "requirejs-domready", "bootstrap", "jquery.showLoading", "csrf", "attribute_extensions", "jquery.entropizer"], function ($, domready) {
domready(function () {
//This function is called once the DOM is ready.
//It will be safe to query the DOM and manipulate
//DOM nodes in this function.
/*
正则
*/
var valid_regex = {
student_number_valid_regex: /^\d{13,}$/,
email_valid_regex: /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+(([.-])[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/,
mobile_valid_regex: /^1[0-9]{10}/,
phone_verify_code_valid_regex: /^\w+$/,
password_valid_regex: /^[a-zA-Z0-9]\w{5,17}$/
};
/*
消息
*/
var msg = {
password_error_msg: '密码6-16位任意字母或数字,以及下划线',
confirm_password_error_msg: '密码不一致'
};
/**
* 显示遮罩
*/
function startLoading() {
$('#loading_region').showLoading();
}
/**
* 去除遮罩
*/
function endLoading() {
$('#loading_region').hideLoading();
}
/*
ajax url
*/
var ajax_url = {
password_reset: '/user/login/password/reset',
finish: '/user/login/password/reset/finish'
};
/*
错误验证
*/
function validErrorDom(inputId, errorId, msg) {
$(inputId).removeClass('has-success').addClass('has-error');
$(errorId).removeClass('hidden').text(msg);
}
/*
正确验证
*/
function validSuccessDom(inputId, errorId) {
$(inputId).removeClass('has-error').addClass('has-success');
$(errorId).addClass('hidden').text('');
}
/*
参数id
*/
var paramId = {
password: '#password',
confirmPassword: '#confirmPassword'
};
/*
参数
*/
var param = {
password: $(paramId.password).val().trim(),
confirmPassword: $(paramId.confirmPassword).val().trim()
};
/*
初始化参数
*/
function initParam() {
param.password = $(paramId.password).val().trim();
param.confirmPassword = $(paramId.confirmPassword).val().trim();
}
/*
验证form id
*/
var validId = {
valid_password: '#valid_password',
valid_confirm_password: '#valid_confirm_password'
};
/*
错误消息 id
*/
var errorMsgId = {
password_error_msg: '#password_error_msg',
confirm_password_error_msg: '#confirm_password_error_msg'
};
// 密码强度检测
$('#meter2').entropizer({
target: paramId.password,
update: function (data, ui) {
ui.bar.css({
'background-color': data.color,
'width': data.percent + '%'
});
}
});
/*
密码验证
*/
$(paramId.password).blur(function () {
initParam();
var password = param.password;
if (!valid_regex.password_valid_regex.test(password)) {
validErrorDom(validId.valid_password, errorMsgId.password_error_msg, msg.password_error_msg);
} else {
validSuccessDom(validId.valid_password, errorMsgId.password_error_msg);
}
});
/*
确认密码验证
*/
$(paramId.confirmPassword).blur(function () {
initParam();
var password = param.password;
var confirmPassword = param.confirmPassword;
if (!valid_regex.password_valid_regex.test(password)) {
validErrorDom(validId.valid_password, errorMsgId.password_error_msg, msg.password_error_msg);
} else {
validSuccessDom(validId.valid_password, errorMsgId.password_error_msg);
if (confirmPassword !== password) {
validErrorDom(validId.valid_confirm_password, errorMsgId.confirm_password_error_msg, msg.confirm_password_error_msg);
} else {
validSuccessDom(validId.valid_confirm_password, errorMsgId.confirm_password_error_msg)
}
}
});
/**
* 表单提交时检验
*/
$('#reset_password').click(function () {
startLoading();
validPassword();
});
/**
* 验证密码
*/
function validPassword() {
initParam();
var password = param.password;
var confirmPassword = param.confirmPassword;
if (!valid_regex.password_valid_regex.test(password)) {
validErrorDom(validId.valid_password, errorMsgId.password_error_msg, msg.password_error_msg);
// 去除遮罩
endLoading();
} else {
validSuccessDom(validId.valid_password, errorMsgId.password_error_msg);
if (confirmPassword !== password) {
validErrorDom(validId.valid_confirm_password, errorMsgId.confirm_password_error_msg, msg.confirm_password_error_msg);
// 去除遮罩
endLoading();
} else {
validSuccessDom(validId.valid_confirm_password, errorMsgId.confirm_password_error_msg);
$.post(web_path + ajax_url.password_reset, $('#reset_password_form').serialize(), function (data) {
if (data.state) {
window.location.href = web_path + ajax_url.finish;
} else {
$('#error_msg').removeClass('hidden').text(data.msg);
// 去除遮罩
endLoading();
}
});
}
}
}
});
}); |
var DATA = [
{
video: {
src: 'videos/reef_1920_4.webm'
},
size: 50,
pos: [-100,0,0]
},
{
video: {
src: 'videos/pano.webm'
},
size: 50,
pos: [100,0,0]
}
];
|
var fs = require('fs');
/*
* configures an ipc with the configurations specific to remote communincation
* @param ipc {IPC}: the ipc to be configured
*/
function configureRemoteIPC(ipc) {
ipc.config.maxRetries = 3;
ipc.config.retry = 600;
//ipc.config.silent = true;
}
function configureLocalIPC(ipc) {
ipc.config.sync = true;
//ipc.config.silent = true;
ipc.config.id = 'klyng_beacon';
ipc.config.maxRetries = 0;
}
// read and parse the configurations file
var configs_data = fs.readFileSync(__dirname + "/../config.json", "utf8");
var configs = JSON.parse(configs_data);
module.exports = {
klyngConfigs: configs,
configureRemoteIPC: configureRemoteIPC,
configureLocalIPC: configureLocalIPC
};
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var amock = require('./..');
var file = process.argv[2];
var qty = parseInt(process.argv[3], 10) || 20;
if (file) {
fs.readFile(file, 'utf8', function(err, data){
if (err){
console.log(err);
return;
}
amock(file, JSON.parse(data));
console.log(amock.getJSON(qty));
});
} else {
console.log('Nope. I need at least the file name...');
}
|
import angularMeteor from 'angular-meteor';
import { Players } from '/imports/api/players.js';
import { Teams } from '/imports/api/teams.js';
import { Games } from '/imports/api/games.js';
import { Goals } from '/imports/api/goals.js';
class GameScoreService {
constructor(playersService, teamsService) {
this.playersService = playersService;
this.teamsService = teamsService;
// Maximum movement of ELO in 1 match
this.maxEloMovement = 75;
}
revertScored(teamId, player, inprogress) {
// Team red
if (inprogress.teamRed._id == teamId) {
if (inprogress.teamRed.attacker._id == player) {
if (inprogress.teamRed.attacker.goals > 0) {
const remGoal = inprogress.teamRed.goals.pop();
Meteor.apply('removeGoal', [remGoal]);
inprogress.teamRed.attacker.goals--;
Games.update(inprogress._id, {
$inc: { teamRedScore: -1 },
$set: { teamRed: inprogress.teamRed }
});
}
} else {
if (inprogress.teamRed.defender.goals > 0) {
const remGoal = inprogress.teamRed.goals.pop();
Meteor.apply('removeGoal', [remGoal]);
inprogress.teamRed.defender.goals--;
Games.update(inprogress._id, {
$inc: { teamRedScore: -1 },
$set: { teamRed: inprogress.teamRed }
});
}
}
} else {
// Team blue
if (inprogress.teamBlue.attacker._id == player) {
if (inprogress.teamBlue.attacker.goals > 0) {
const remGoal = inprogress.teamBlue.goals.pop();
Meteor.apply('removeGoal', [remGoal]);
inprogress.teamBlue.attacker.goals--;
Games.update(inprogress._id, {
$inc: { teamBlueScore: -1 },
$set: { teamBlue: inprogress.teamBlue }
});
}
} else {
if (inprogress.teamBlue.defender.goals > 0) {
const remGoal = inprogress.teamBlue.goals.pop();
Meteor.apply('removeGoal', [remGoal]);
inprogress.teamBlue.defender.goals--;
Games.update(inprogress._id, {
$inc: { teamBlueScore: -1 },
$set: { teamBlue: inprogress.teamBlue }
});
}
}
}
}
scored(teamId, player, inprogress) {
if (inprogress.teamRed._id == teamId) // red scored
{
if (inprogress.teamRed.attacker._id == player) {
let goal = Meteor.apply('newGoal', [{ player, position: 'attacker', color: 'red', own: false, teamId: inprogress.teamRed._id }],
{ returnStubValue: true });
inprogress.teamRed.goals.push(goal);
inprogress.teamRed.attacker.goals++;
Games.update(inprogress._id, {
$inc: { teamRedScore: 1 },
$set: { teamRed: inprogress.teamRed }
});
} else {
let goal = Meteor.apply('newGoal', [{ player, position: 'defender', color: 'red', own: false, teamid: inprogress.teamRed._id }],
{ returnStubValue: true });
inprogress.teamRed.goals.push(goal);
inprogress.teamRed.defender.goals++;
Games.update(inprogress._id, {
$inc: { teamRedScore: 1 },
$set: { teamRed: inprogress.teamRed }
});
}
if (inprogress.teamRedScore++ > 5) {
var eloChange = this.updateELO(inprogress.teamRed._id, inprogress.teamBlue._id);
Games.update(inprogress._id, {
$set: {
winner: inprogress.teamRed._id,
endDate: new Date(),
eloChange: eloChange
}
});
console.log('red won!');
}
} else {
if (inprogress.teamBlue.attacker._id == player) {
let goal = Meteor.apply('newGoal', [{ player, position: 'attacker', color: 'blue', own: false, teamid: inprogress.teamBlue._id }],
{ returnStubValue: true });
inprogress.teamBlue.goals.push(goal);
inprogress.teamBlue.attacker.goals++;
Games.update(inprogress._id, {
$inc: { teamBlueScore: 1 },
$set: { teamBlue: inprogress.teamBlue }
});
} else {
let goal = Meteor.apply('newGoal', [{ player, position: 'defender', color: 'blue', own: false, teamid: inprogress.teamBlue._id }],
{ returnStubValue: true });
inprogress.teamBlue.goals.push(goal);
inprogress.teamBlue.defender.goals++;
Games.update(inprogress._id, {
$inc: { teamBlueScore: 1 },
$set: { teamBlue: inprogress.teamBlue }
});
}
if (inprogress.teamBlueScore++ > 5) {
var eloChange = this.updateELO(inprogress.teamBlue._id, inprogress.teamRed._id);
Games.update(inprogress._id, {
$set: {
winner: inprogress.teamBlue,
endDate: new Date(),
eloChange: eloChange
}
});
console.log('blue won!');
}
}
}
updateELO(winTeamId, loseTeamId) {
let winTeam = Teams.findOne({ _id: winTeamId });
let loseTeam = Teams.findOne({ _id: loseTeamId });
let eloChange = this.getTeamEloOnWin(winTeam, loseTeam).win;
this.playersService.eloInc(winTeam.players[0], eloChange);
this.playersService.eloInc(winTeam.players[1], eloChange);
this.playersService.eloInc(loseTeam.players[0], -eloChange);
this.playersService.eloInc(loseTeam.players[1], -eloChange);
let teamEloChanged = this.calculateELORatingChange(winTeam.teamElo, loseTeam.teamElo, this.maxEloMovement);
console.log('Team ELO change by: ', teamEloChanged);
this.teamsService.eloInc(winTeamId, teamEloChanged.win);
this.teamsService.eloInc(loseTeamId, teamEloChanged.loss);
return eloChange;
}
getTeamEloOnWin(winTeam, loseTeam) {
let eloChanged = this.calculateELORatingChange(
this.teamsService.getCombinedElo(winTeam),
this.teamsService.getCombinedElo(loseTeam),
this.maxEloMovement);
return eloChanged;
}
/**
* This method will calculate the change in a player's
* Elo rating after playing a single game against another player.
* The value K is the maximum change in rating.
**/
calculateELORatingChange(elo1, elo2, k) {
var percentage = 1 / (1 + Math.pow(10, (elo2 - elo1) / 400));
return {
win: Math.round(k * (1 - percentage)),
draw: Math.round(k * (.5 - percentage)),
loss: Math.round(k * (0 - percentage)),
percent: Math.round(percentage * 100)
};
}
}
export default angular.module('gameservice', [
angularMeteor
])
.service('gameScoreService', ['playersService', 'teamsService', GameScoreService]);
|
directives.directive('paCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) {
return function(scope, element, attrs) {
var stopTime;
function updateTime() {
element.text(dateFilter(new Date(), 'MM/dd/yyyy @ h:mma'));
}
updateTime();
// XXX Maybe change this so it syncs with clock and updates every minute
stopTime = $interval(updateTime, 1000);
element.on('$destroy', function() {
$interval.cancel(stopTime);
});
}
}]);
|
// Copyright 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
define(function(require) {
var chai = require('chai');
var sinonChai = require('test/sinon-chai');
chai.use(sinonChai);
var expect = chai.expect;
var sinon = require('test/sinon');
var Rules = require('rtp/rules');
var UnitBlueprint = require('rtp/unit-blueprint');
var ResourceBlueprint = require('rtp/resource-blueprint');
var ResourceQuantity = require('rtp/resource-quantity');
var BuildingBlueprint = require('rtp/building-blueprint');
describe('Rules', function() {
describe('instance', function() {
var rules;
beforeEach(function() {
rules = new Rules([new UnitBlueprint('unit', 'unit')],
[new ResourceBlueprint('gold', 'Gold', 'gold.png')],
[new BuildingBlueprint('farm', 'Farm', 'farm.png', null, [new ResourceQuantity(14, 'gold')])]);
});
it('can return a unit blueprint by id', function() {
var unitBlueprint = rules.getUnitBlueprintById('unit');
expect(unitBlueprint).to.be.an.instanceof(UnitBlueprint);
expect(unitBlueprint.id).to.equal('unit');
});
it('can return a resource blueprint by id', function() {
var resourceBlueprint = rules.getResourceBlueprintById('gold');
expect(resourceBlueprint).to.be.an.instanceof(ResourceBlueprint);
expect(resourceBlueprint.id).to.equal('gold');
});
it('can return a building blueprint by id', function() {
var buildingBlueprint = rules.getBuildingBlueprintById('farm');
expect(buildingBlueprint).to.be.an.instanceof(BuildingBlueprint);
expect(buildingBlueprint.id).to.equal('farm');
});
});
describe('deserialize', function() {
var rules;
beforeEach(function() {
rules = Rules.deserialize({
unitBlueprints: [{id: 'unit', name: 'unit', image: 'unit.png', maxPower: 20, movement: 17, modifiers: []}],
resourceBlueprints: [{id: 'gold', name: 'Gold', image: 'gold.png'}],
buildingBlueprints: [{id: 'farm', name: 'Farm', image: 'farm.png', production: null, constructionCost: [{quantity: 10, blueprint: 'gold'}]}]
});
});
it('works', function() {
expect(rules).to.be.an.instanceof(Rules);
expect(rules.unitBlueprints[0]).to.be.an.instanceof(UnitBlueprint);
expect(rules.unitBlueprints[0].name).to.equal('unit');
expect(rules.resourceBlueprints[0]).to.be.an.instanceof(ResourceBlueprint);
expect(rules.resourceBlueprints[0].name).to.equal('Gold');
expect(rules.buildingBlueprints[0]).to.be.an.instanceof(BuildingBlueprint);
expect(rules.buildingBlueprints[0].name).to.equal('Farm');
expect(rules.buildingBlueprints[0].constructionCost[0].blueprint).to.equal('gold');
});
it('completes serialization in finish deserialize', function() {
rules.finishDeserialize();
expect(rules.buildingBlueprints[0]).to.be.an.instanceof(BuildingBlueprint);
expect(rules.buildingBlueprints[0].constructionCost[0].blueprint).to.be.an.instanceof(ResourceBlueprint);
expect(rules.buildingBlueprints[0].constructionCost[0].blueprint.id).to.equal('gold');
});
});
});
});
|
// Generated on 2015-06-29 using generator-angular 0.11.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Deployment stuff
buildcontrol: {
options: {
dir: 'dist',
commit: true,
push: true,
message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%'
},
pages: {
options: {
remote: 'git@github.com:iliyan/knoby.git',
branch: 'gh-pages'
}
}
//, heroku: {
// options: {
// remote: 'git@heroku.com:example-heroku-webapp-1988.git',
// branch: 'master',
// tag: pkg.version
// }
//},
//local: {
// options: {
// remote: '../',
// branch: 'build'
// }
//}
},
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
server: {
options: {
map: true,
},
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
test: {
devDependencies: true,
src: '<%= karma.unit.configFile %>',
ignorePath: /\.\.\//,
fileTypes:{
js: {
block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/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.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
]
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer:server',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'wiredep',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
(function () {
// Including extend function so we aren't dependent upon JQuery.
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
function isPlainObject(obj) {
if (!obj || toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval)
return false;
var has_own_constructor = hasOwn.call(obj, 'constructor');
var has_is_property_of_method = hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method)
return false;
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
}
function extend() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && typeof target !== "function") {
target = {};
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) !== null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recur if we're merging plain objects or arrays
if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = Array.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && Array.isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
}
// Declare a global shotgun namespace.
window.shotgun = {
// Shotgun client shell.
ClientShell: function (options) {
var clientShell = this,
context = {},
// Default settings.
defaultSettings = {
namespace: 'shotgun',
debug: false
};
// Override default settings with supplied options.
var settings = clientShell.settings = extend(true, {}, defaultSettings, options);
// Instruct socket.io to connect to the server.
var socket = clientShell.socket = io.connect('/' + settings.namespace);
// Proxy any listeners onto the socket itself.
clientShell.on = function () {
socket.on.apply(socket, arguments);
return clientShell;
};
// Proxy any emit calls onto the socket itself.
clientShell.emit = function () {
socket.emit.apply(socket, arguments);
return clientShell;
};
function getCookies() {
var cookies = {};
if (document.cookie.length > 0)
document.cookie.split(';').forEach(function (cookie) {
var components = cookie.split('='),
name = components[0].trim(),
value = components[1];
if (name.indexOf(settings.namespace + '-') === 0) {
name = name.replace(settings.namespace + '-', '');
cookies[name] = decodeURIComponent(value);
}
});
return cookies;
}
clientShell
// Save context when it changes.
.on('contextChanged', function (contextData) {
context = contextData;
})
// Create a function for setting cookies in the browser.
.on('setCookie', function (name, value, days) {
var expiration = new Date();
expiration.setDate(expiration.getDate() + days);
value = encodeURIComponent(value) + ((days === null) ? "" : ";expires=" + expiration.toUTCString());
document.cookie = settings.namespace + '-' + name + "=" + value;
})
.on('getCookie', function (name, callback) {
// Create a cookies property on the context and fill it with all the cookies for this shell.
var cookies = getCookies();
callback(cookies[name]);
})
.on('getAllCookies', function (callback) {
var cookies = getCookies();
callback(cookies);
});
// Create an execute function that looks similar to the shotgun shell execute function for ease of use.
clientShell.execute = function (cmdStr, contextOverride, options) {
// If a context was passed in then override the stored context with it.
if (contextOverride) context = contextOverride;
socket.emit('execute', cmdStr, context, options);
return clientShell;
};
return clientShell;
}
};
})();
|
import { push } from 'react-router-redux';
import { REQUEST_RESULTS, RECEIVE_RESULTS, RECEIVE_FAILURE } from '../constants';
import { processParams, search } from './common';
export function requestResults() {
return {
type: REQUEST_RESULTS,
};
}
export function receiveResults(payload) {
return {
type: RECEIVE_RESULTS,
payload,
};
}
export function receiveFailure(error) {
return {
type: RECEIVE_FAILURE,
error,
};
}
function fetchResults(querystring) {
return (dispatch) => {
dispatch(requestResults(querystring));
return search(querystring)
.then(json => dispatch(receiveResults(json)))
.catch(e => dispatch(receiveFailure(e)));
};
}
function shouldFetchResults(state) {
const { results } = state;
if (results && results.isFetching) {
return false;
}
return true;
}
export function fetchResultsIfNeeded(params, options = { push: true }) {
return (dispatch, getState) => {
if (shouldFetchResults(getState())) {
const querystring = processParams(params);
if (options.push) dispatch(push(`/search?${querystring}`));
return dispatch(fetchResults(querystring));
}
return Promise.resolve([]);
};
}
|
import React from 'react'
// import DuckImage from '../assets/Duck.jpg'
import './AboutMe.scss'
export const AboutMe = () => (
<div>
<h3>About me</h3>
<div className="pageContainer">
<p>
Ipsum is unattractive, both inside and out. I fully understand why it’s former users left it for something else. They made a good decision. I think the only card she has is the Lorem card. An 'extremely credible source' has called my office and told me that Lorem Ipsum's birth certificate is a fraud. I'm speaking with myself, number one, because I have a very good brain and I've said a lot of things. I will write some great placeholder text – and nobody writes better placeholder text than me, believe me – and I’ll write it very inexpensively. I will write some great, great text on your website’s Southern border, and I will make Google pay for that text. Mark my words. We have so many things that we have to do better... and certainly ipsum is one of them.
Ipsum is the single greatest threat. We are not - we are not keeping up with other websites. My text is long and beautiful, as, it has been well documented, are various other parts of my website. An ‘extremely credible source’ has called my office and told me that Barack Obama’s placeholder text is a fraud.
placeholder text is gonna be HUGE. An 'extremely credible source' has called my office and told me that Lorem Ipsum's birth certificate is a fraud. We are going to make placeholder text great again. Greater than ever before.
concept of Lorem Ipsum was created by and for the Chinese in order to make U.S. design jobs non-competitive. You're telling the enemy exactly what you're going to do. No wonder you've been fighting Lorem Ipsum your entire adult life.
I’m the best thing that ever happened to placeholder text. My placeholder text, I think, is going to end up being very good with women. The best taco bowls are made in Trump Tower Grill. I love Hispanics!
</p>
</div>
{/* <img alt='This is a duck, because Redux!' className='duck' src={DuckImage} /> */}
</div>
)
export default AboutMe
|
'use strict';var _fs;
function _load_fs() {return _fs = _interopRequireDefault(require('fs'));}var _jestHasteMap;
function _load_jestHasteMap() {return _jestHasteMap = require('jest-haste-map');}function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
const FAIL = 0; // $FlowFixMe: Missing ESM export
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/const SUCCESS = 1;class TestSequencer {
constructor() {
this._cache = new Map();
}
_getCachePath(context) {const
config = context.config;
return (0, (_jestHasteMap || _load_jestHasteMap()).getCacheFilePath)(config.cacheDirectory, 'perf-cache-' + config.name);
}
_getCache(test) {const
context = test.context;
if (!this._cache.has(context) && context.config.cache) {
const cachePath = this._getCachePath(context);
if ((_fs || _load_fs()).default.existsSync(cachePath)) {
try {
this._cache.set(
context,
JSON.parse((_fs || _load_fs()).default.readFileSync(cachePath, 'utf8')));
} catch (e) {}
}
}
let cache = this._cache.get(context);
if (!cache) {
cache = {};
this._cache.set(context, cache);
}
return cache;
}
// When running more tests than we have workers available, sort the tests
// by size - big test files usually take longer to complete, so we run
// them first in an effort to minimize worker idle time at the end of a
// long test run.
//
// After a test run we store the time it took to run a test and on
// subsequent runs we use that to run the slowest tests first, yielding the
// fastest results.
sort(tests) {
const stats = {};
const fileSize = test =>
stats[test.path] || (stats[test.path] = (_fs || _load_fs()).default.statSync(test.path).size);
const hasFailed = (cache, test) =>
cache[test.path] && cache[test.path][0] === FAIL;
const time = (cache, test) => cache[test.path] && cache[test.path][1];
tests.forEach(test => test.duration = time(this._getCache(test), test));
return tests.sort((testA, testB) => {
const cacheA = this._getCache(testA);
const cacheB = this._getCache(testB);
const failedA = hasFailed(cacheA, testA);
const failedB = hasFailed(cacheB, testB);
const hasTimeA = testA.duration != null;
if (failedA !== failedB) {
return failedA ? -1 : 1;
} else if (hasTimeA != (testB.duration != null)) {
// Check if only one of two tests has timing information
return hasTimeA != null ? 1 : -1;
} else if (testA.duration != null && testB.duration != null) {
return testA.duration < testB.duration ? 1 : -1;
} else {
return fileSize(testA) < fileSize(testB) ? 1 : -1;
}
});
}
cacheResults(tests, results) {
const map = Object.create(null);
tests.forEach(test => map[test.path] = test);
results.testResults.forEach(testResult => {
if (testResult && map[testResult.testFilePath] && !testResult.skipped) {
const cache = this._getCache(map[testResult.testFilePath]);
const perf = testResult.perfStats;
cache[testResult.testFilePath] = [
testResult.numFailingTests ? FAIL : SUCCESS,
perf.end - perf.start || 0];
}
});
this._cache.forEach((cache, context) =>
(_fs || _load_fs()).default.writeFileSync(this._getCachePath(context), JSON.stringify(cache)));
}}
module.exports = TestSequencer; |
var should = require('should');
var Queue = require('../lib/queue');
describe('Queue', function () {
describe('#queue', function () {
it('Processes queue in order', function (done) {
var queue = new Queue();
var string = '';
var incrementString = function(i) {
return function() {
return string +=i ;
}
};
for (var i = 0; i < 10; i++) {
queue.queueCommand(incrementString(i));
}
queue.queueCommand(function () {
string = string + '10';
}).then(function (res) {
string.should.eql('012345678910');
done();
}).error(console.log);
});
it('should return promise that is resolved upon running complete', function (done) {
var queue = new Queue();
var toChange = 12;
var change = function () {
toChange = 10;
};
queue.queueCommand(change)
.then(function (res) {
toChange.should.eql(10);
done();
});
});
it('should return promise that is resolved directly when not running', function (done) {
var queue = new Queue();
queue.empty().then(function () {
done();
})
});
});
});
|
'use strict';
const jwt = require('jsonwebtoken');
function UserController (db) {
this.database = db;
this.model = db.User;
}
UserController.prototype = {
list,
read,
create,
logIn,
update,
destroy
};
module.exports = UserController;
// [GET] /user
function list (request, reply) {
this.model.findAsync({})
.then((users) => {
reply(users);
})
.catch((err) => {
reply.badImplementation(err.message);
});
}
// [GET] /user/{id}
function read (request, reply) {
const id = request.params.id;
this.model.findOneAsync({_id: id})
.then((user) => {
if (!user) {
reply.notFound();
return;
}
reply(user);
})
.catch((err) => {
reply.badImplementation(err.message);
});
}
// [POST] /user
function create (request, reply) {
const payload = request.payload;
this.model.createAsync(payload)
.then((user) => {
const token = getToken(user.id);
reply({
token: token
}).code(201);
})
.catch((err) => {
reply.badImplementation(err.message);
});
}
// [POST] /user/login
function logIn (request, reply) {
const credentials = request.payload;
this.model.findOneAsync({email: credentials.email})
.then((user) => {
if (!user) {
return reply.unauthorized('Email or Password invalid');
}
if (!user.validatePassword(credentials.password)) {
return reply.unauthorized('Email or Password invalid');
}
const token = getToken(user.id);
reply({
token: token
});
})
.catch((err) => {
reply.badImplementation(err.message);
});
}
// [PUT] /user
function update (request, reply) {
const id = request.params.id;
const payload = request.payload;
this.model.findOneAndUpdateAsync({_id: id}, {$set: payload}, {new: true})
.then((user) => {
reply(user);
})
.catch((err) => {
reply.badImplementation(err.message);
});
}
// [DELETE] /user
function destroy (request, reply) {
const id = request.auth.credentials.id;
this.model.removeAsync({_id: id})
.then(() => {
reply();
})
.catch((err) => {
reply.badImplementation(err.message);
});
}
function getToken (id) {
const secretKey = process.env.JWT || 'stubJWT';
return jwt.sign({
id: id
}, secretKey, {expiresIn: '18h'});
}
|
/**
* Game Controller
*/
function GameController(game)
{
var controller = this;
this.isPaused = false;
this.game = game;
this.clients = new Collection();
this.socketGroup = new SocketGroup(this.clients);
this.compressor = new Compressor();
this.waiting = null;
this.onGameStart = this.onGameStart.bind(this);
this.onGameStop = this.onGameStop.bind(this);
this.onDie = this.onDie.bind(this);
this.onPosition = this.onPosition.bind(this);
this.onAngle = this.onAngle.bind(this);
this.onPoint = this.onPoint.bind(this);
this.onScore = this.onScore.bind(this);
this.onRoundScore = this.onRoundScore.bind(this);
this.onProperty = this.onProperty.bind(this);
this.onBonusStack = this.onBonusStack.bind(this);
this.onBonusPop = this.onBonusPop.bind(this);
this.onBonusClear = this.onBonusClear.bind(this);
this.onRoundNew = this.onRoundNew.bind(this);
this.onRoundEnd = this.onRoundEnd.bind(this);
this.onPlayerLeave = this.onPlayerLeave.bind(this);
this.onClear = this.onClear.bind(this);
this.onBorderless = this.onBorderless.bind(this);
this.onEnd = this.onEnd.bind(this);
this.stopWaiting = this.stopWaiting.bind(this);
// Custom
this.onEraser = this.onEraser.bind(this);
this.callbacks = {
onReady: function () { controller.onReady(this); },
onMove: function (data) { controller.onMove(this, data); },
onPause: function (data) { controller.onPause(this, data); }
};
this.loadGame();
}
/**
* Waiting time
*
* @type {Number}
*/
GameController.prototype.waitingTime = 30000;
/**
* Load game
*/
GameController.prototype.loadGame = function()
{
this.game.on('game:start', this.onGameStart);
this.game.on('game:stop', this.onGameStop);
this.game.on('end', this.onEnd);
this.game.on('clear', this.onClear);
this.game.on('player:leave', this.onPlayerLeave);
this.game.on('round:new', this.onRoundNew);
this.game.on('round:end', this.onRoundEnd);
this.game.on('borderless', this.onBorderless);
this.game.bonusManager.on('bonus:pop', this.onBonusPop);
this.game.bonusManager.on('bonus:clear', this.onBonusClear);
for (var i = this.game.room.controller.clients.items.length - 1; i >= 0; i--) {
this.attach(this.game.room.controller.clients.items[i]);
}
this.waiting = setTimeout(this.stopWaiting, this.waitingTime);
};
/**
* Remove game
*
* @param {Game} game
*/
GameController.prototype.unloadGame = function()
{
this.game.removeListener('game:start', this.onGameStart);
this.game.removeListener('game:stop', this.onGameStop);
this.game.removeListener('end', this.onEnd);
this.game.removeListener('clear', this.onClear);
this.game.removeListener('player:leave', this.onPlayerLeave);
this.game.removeListener('round:new', this.onRoundNew);
this.game.removeListener('round:end', this.onRoundEnd);
this.game.removeListener('borderless', this.onBorderless);
this.game.bonusManager.removeListener('bonus:pop', this.onBonusPop);
this.game.bonusManager.removeListener('bonus:clear', this.onBonusClear);
for (var i = this.clients.items.length - 1; i >= 0; i--) {
this.detach(this.clients.items[i]);
}
};
/**
* Attach events
*
* @param {SocketClient} client
*/
GameController.prototype.attach = function(client)
{
if (this.clients.add(client)) {
this.attachEvents(client);
this.socketGroup.addEvent('game:spectators', this.countSpectators());
client.pingLogger.start();
}
};
/**
* Attach events
*
* @param {SocketClient} client
*/
GameController.prototype.detach = function(client)
{
this.detachEvents(client);
if (this.clients.remove(client)) {
for (var i = client.players.items.length - 1; i >= 0; i--) {
if (client.players.items[i].avatar) {
this.game.removeAvatar(client.players.items[i].avatar);
}
}
this.socketGroup.addEvent('game:spectators', this.countSpectators());
client.pingLogger.stop();
}
};
/**
* On player leave
*/
GameController.prototype.onPlayerLeave = function(data)
{
this.socketGroup.addEvent('game:leave', data.player.id);
};
/**
* Detach events
*
* @param {SocketClient} client
*/
GameController.prototype.attachEvents = function(client)
{
client.on('ready', this.callbacks.onReady);
if (!client.players.isEmpty()) {
client.on('player:move', this.callbacks.onMove);
client.on('player:pause', this.callbacks.onPause);
}
for (var avatar, i = client.players.items.length - 1; i >= 0; i--) {
avatar = client.players.items[i].getAvatar();
avatar.on('die', this.onDie);
avatar.on('position', this.onPosition);
avatar.on('angle', this.onAngle);
avatar.on('point', this.onPoint);
avatar.on('score', this.onScore);
avatar.on('score:round', this.onRoundScore);
avatar.on('property', this.onProperty);
avatar.bonusStack.on('change', this.onBonusStack);
// Custom
avatar.on('eraser', this.onEraser);
}
};
/**
* Detach events
*
* @param {SocketClient} client
*/
GameController.prototype.detachEvents = function(client)
{
var avatar;
client.removeListener('ready', this.callbacks.onReady);
if (!client.players.isEmpty()) {
client.removeListener('player:move', this.callbacks.onMove);
client.removeListener('player:pause', this.callbacks.onPause);
}
for (var i = client.players.items.length - 1; i >= 0; i--) {
avatar = client.players.items[i].avatar;
if (avatar) {
avatar.removeListener('die', this.onDie);
avatar.removeListener('position', this.onPosition);
avatar.removeListener('point', this.onPoint);
avatar.removeListener('score', this.onScore);
avatar.removeListener('score:round', this.onRoundScore);
avatar.removeListener('property', this.onProperty);
avatar.bonusStack.removeListener('change', this.onBonusStack);
// Custom
avatar.removeListener('eraser', this.onEraser);
}
}
};
/**
* On Eraser
*
* @param {Object} data
*/
GameController.prototype.onEraser = function(points, radius)
{
this.socketGroup.addEvent('eraser', [points, radius]);
};
/**
* Attach spectator
*
* @param {SocketClient} client
*/
GameController.prototype.attachSpectator = function(client)
{
var properties = {
angle: 'angle',
radius: 'radius',
color: 'color',
printing: 'printing',
score: 'score'
},
events = [['spectate', {
inRound: this.game.inRound,
rendered: this.game.rendered ? true : false,
maxScore: this.game.maxScore
}]],
avatar, data, bonus, i;
for (i = this.game.avatars.items.length - 1; i >= 0; i--) {
avatar = this.game.avatars.items[i];
events.push(['position', [avatar.id, this.compressor.compress(avatar.x), this.compressor.compress(avatar.y)]]);
for (var property in properties) {
if (properties.hasOwnProperty(property)) {
events.push(['property', {avatar: avatar.id, property: property, value: avatar[properties[property]]}]);
}
}
if (!avatar.alive) {
events.push(['die', {avatar: avatar.id}]);
}
}
if (this.game.inRound) {
for (i = this.game.bonusManager.bonuses.items.length - 1; i >= 0; i--) {
bonus = this.game.bonusManager.bonuses.items[i];
events.push(['bonus:pop', [
bonus.id,
this.compressor.compress(bonus.x),
this.compressor.compress(bonus.y),
bonus.constructor.name
]]);
}
} else {
this.socketGroup.addEvent('round:end', this.game.roundWinner ? this.game.roundWinner.id : null);
}
events.push(['game:spectators', this.countSpectators()]);
client.addEvents(events);
};
/**
* Count spectators
*
* @return {Number}
*/
GameController.prototype.countSpectators = function()
{
return this.clients.filter(function () { return !this.isPlaying(); }).count();
};
/**
* On game loaded
*
* @param {SocketClient} client
*/
GameController.prototype.onReady = function(client)
{
if (this.game.started) {
this.attachSpectator(client);
} else {
for (var avatar, i = client.players.items.length - 1; i >= 0; i--) {
avatar = client.players.items[i].getAvatar();
avatar.ready = true;
this.socketGroup.addEvent('ready', avatar.id);
}
this.checkReady();
}
};
/**
* Check if all players are ready
*/
GameController.prototype.checkReady = function()
{
if (this.game.isReady()) {
this.waiting = clearTimeout(this.waiting);
this.game.newRound();
}
};
/**
* Stop waiting for loading players
*/
GameController.prototype.stopWaiting = function()
{
if (this.waiting && !this.game.isReady()) {
this.waiting = clearTimeout(this.waiting);
var avatars = this.game.getLoadingAvatars();
for (var i = avatars.items.length - 1; i >= 0; i--) {
this.detach(avatars.items[i].player.client);
}
this.checkReady();
}
};
/**
* On move
*
* @param {SocketClient} client
* @param {Number} move
*/
GameController.prototype.onMove = function(client, data)
{
var player = client.players.getById(data.avatar);
if (player && player.avatar) {
player.avatar.updateAngularVelocity(data.move);
}
};
/**
* On pause
*
* @param {SocketClient} client
* @param {Number} move
*/
GameController.prototype.onPause = function(client, data)
{
var player = client.players.getById(data.avatar);
if (player && this.game.room.controller.isRoomMaster(client)) {
console.log("As the player is master, pause OK");
this.isPaused = !this.isPaused;
}
};
/**
* On point
*
* @param {Object} data
*/
GameController.prototype.onPoint = function(data)
{
if (data.important) {
this.socketGroup.addEvent('point', data.avatar.id);
}
};
/**
* On position
*
* @param {Avatar} avatar
*/
GameController.prototype.onPosition = function(avatar)
{
this.socketGroup.addEvent('position', [
avatar.id,
this.compressor.compress(avatar.x),
this.compressor.compress(avatar.y)
]);
};
/**
* On angle
*
* @param {Avatar} avatar
*/
GameController.prototype.onAngle = function(avatar)
{
this.socketGroup.addEvent('angle', [
avatar.id,
this.compressor.compress(avatar.angle)
]);
};
/**
* On die
*
* @param {Object} data
*/
GameController.prototype.onDie = function(data)
{
this.socketGroup.addEvent('die', [
data.avatar.id,
data.killer ? data.killer.id : null,
data.old
]);
};
/**
* On bonus pop
*
* @param {Bonus} bonus
*/
GameController.prototype.onBonusPop = function(bonus)
{
this.socketGroup.addEvent('bonus:pop', [
bonus.id,
this.compressor.compress(bonus.x),
this.compressor.compress(bonus.y),
bonus.constructor.name
]);
};
/**
* On bonus clear
*
* @param {Bonus} bonus
*/
GameController.prototype.onBonusClear = function(bonus)
{
this.socketGroup.addEvent('bonus:clear', bonus.id);
};
/**
* On score
*
* @param {Avatar} avatar
*/
GameController.prototype.onScore = function(avatar)
{
this.socketGroup.addEvent('score', [avatar.id, avatar.score]);
};
/**
* On round score
*
* @param {Avatar} avatar
*/
GameController.prototype.onRoundScore = function(avatar)
{
this.socketGroup.addEvent('score:round', [avatar.id, avatar.roundScore]);
};
/**
* On property
*
* @param {Object} data
*/
GameController.prototype.onProperty = function(data)
{
this.socketGroup.addEvent('property', [
data.avatar.id,
data.property,
data.value
]);
};
/**
* On bonus stack add
*
* @param {Object} data
*/
GameController.prototype.onBonusStack = function(data)
{
this.socketGroup.addEvent('bonus:stack', [
data.avatar.id,
data.method,
data.bonus.id,
data.bonus.constructor.name,
data.bonus.duration
]);
};
// Game events:
/**
* On game start
*
* @param {Object} data
*/
GameController.prototype.onGameStart = function(data)
{
if (this.game.room.config.isMapGame) {
this.onGenerateMap();
}
this.socketGroup.addEvent('game:start');
};
GameController.prototype.onGenerateMap = function() {
var mapSize = this.game.world.size;
var nbCircle = Math.random() * 10 + 5;
// an array to save your points
var points=[];
var world = this.game.world;
for (var i = 0; i < nbCircle; i++) {
var centerX= Math.random() * (mapSize - 10) + 5 ;
var centerY= Math.random() * (mapSize - 10) + 5 ;
var radius= Math.random() * 5;
var circlePoint = [];
for(var degree=0;degree<360;degree+=10){
var radians = degree * Math.PI/180;
var x = centerX + radius * Math.cos(radians);
var y = centerY + radius * Math.sin(radians);
points.push([x,y]);
circlePoint.push([x,y]);
}
this.socketGroup.addEvent('drawPoints', {points: circlePoint});
}
setTimeout(function() {world.addMap(points);}, 3000);
};
/**
* On game stop
*
* @param {Object} data
*/
GameController.prototype.onGameStop = function(data)
{
this.socketGroup.addEvent('game:stop');
};
/**
* On round new
*
* @param {Object} data
*/
GameController.prototype.onRoundNew = function(data)
{
this.socketGroup.addEvent('round:new');
};
/**
* On round end
*
* @param {Object} data
*/
GameController.prototype.onRoundEnd = function(data)
{
this.socketGroup.addEvent('round:end', data.winner ? data.winner.id : null);
};
/**
* On clear
*
* @param {Object} data
*/
GameController.prototype.onClear = function(data)
{
this.socketGroup.addEvent('clear');
};
/**
* On borderless
*
* @param {Object} data
*/
GameController.prototype.onBorderless = function(data)
{
this.socketGroup.addEvent('borderless', data);
};
/**
* On end
*
* @param {Object} data
*/
GameController.prototype.onEnd = function(data)
{
this.socketGroup.addEvent('end');
this.unloadGame();
};
|
"use strict";
var VElement = require("../vdom").___VElement;
module.exports = function (
tagName,
attrs,
key,
component,
childCount,
flags,
props
) {
return new VElement(tagName, attrs, key, component, childCount, flags, props);
};
|
var common = require('./_common.js');
var Test = common.Test;
var MIME = require('../index.js');
var namespace = 'MIME.decodeQuotedPrintable';
var tests = [
[
' \t=20_',
' \t _',
true,
null
],
[
' \t=20_',
' \t ',
false,
null
],
// TO DO: Add option to accept/reject illegal quoted-printable:
// [
// '\f',
// null,
// true,
// MIME.Error.QuotedPrintableBodyIllegal
// ],
// [
// '\f',
// null,
// false,
// MIME.Error.QuotedPrintableWordIllegal
// ]
];
tests.forEach(
function(test) {
var source = Buffer.from(test[0], 'utf-8');
var target = test[1];
var body = test[2];
var targetError = test[3];
var key = JSON.stringify(test[0]) + ': body=' + (body ? 1 : 0);
try {
var actual = MIME.decodeQuotedPrintable(source, body).toString('utf-8');
var actualError = null;
} catch (error) {
var actual = null;
var actualError = error.message;
}
Test.equal(actual, target, namespace, key);
Test.equal(actualError, targetError, namespace, key + ': error');
}
);
|
var class_tempo_test_1_1_instance_count =
[
[ "InstanceCount", "class_tempo_test_1_1_instance_count.html#a3e92a5fd6dd6caf4633742b22d740ff4", null ],
[ "value", "class_tempo_test_1_1_instance_count.html#a421f58f5cdbfeacc93976ae979f9bb40", null ]
]; |
console.error( //eslint-disable-line
new Error('[comon-micro-libs] PickerCE.js is NO LONGER SUPPORTED')
);
import Picker from "./Picker"
export {Picker};
export default Picker;
//import getCustomElementFromWidget from "../utils/getCustomElementFromWidget"
// import Picker from "./Picker"
//
// export const PickerCE = getCustomElementFromWidget({
// Widget: Picker,
// tagName: "cml-picker",
// className: "Picker-CE",
// liveProps: {
// choices(newValue, pickerWdg) {
// if (pickerWdg) {
// pickerWdg.setChoices(newValue);
// }
// },
//
// selected(newValue, pickerWdg) {
// if (pickerWdg) {
// pickerWdg.setSelected(newValue);
// }
// }
// }
// });
// export default PickerCE;
|
"use strict";
var FriendRequest = (function () {
function FriendRequest() {
}
return FriendRequest;
}());
exports.FriendRequest = FriendRequest;
//# sourceMappingURL=friend-request.js.map |
var EventEmitter = require('events').EventEmitter
var assign = require('object-assign')
var dispatcher = require('../dispatcher')
var constants = require('../constants/ChatConstants')
var CHANGE_EVENT = 'messageChange'
var messages = []
var selectedBuddyId
/**
* All the message state management in one place!
*/
var MessageStore = assign({}, EventEmitter.prototype, {
getMessages: function (id) {
var msgs = []
if (messages[id]) {
msgs = messages[id].data
}
return msgs
},
isDirty: function (id) {
return (messages[id] && messages[id].dirty)
},
getUnreadCount: function (id) {
var unread = 0
if (messages[id]) {
unread = (messages[id].data.length - 1) - messages[id].lastRead
}
return unread
},
getTotalUnreadCount: function () {
var unread = 0
messages.forEach(function (msg, i) {
unread += ((msg.data.length - 1) - msg.lastRead)
})
return unread
},
getSelectedBuddyId: function () {
return selectedBuddyId
},
emitChange: function () {
this.emit(CHANGE_EVENT)
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback)
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback)
},
dispatcherIndex: dispatcher.register(function (payload) {
var action = payload.action
switch (action.actionType) {
case constants.INCOMING_MESSAGE:
if (!messages[action.fromId]) {
// first message from this id
messages[action.fromId] = {
data: [action.message],
dirty: true,
lastRead: -1
}
} else {
messages[action.fromId].data.push(action.message)
messages[action.fromId].dirty = true
}
if (action.fromId === selectedBuddyId) {
messages[action.fromId].dirty = false
messages[action.fromId].lastRead = messages[action.fromId].data.length - 1
}
MessageStore.emitChange()
break
case constants.VIEW_MESSAGES:
if (messages[action.fromId]) {
messages[action.fromId].dirty = false
messages[action.fromId].lastRead = messages[action.fromId].data.length - 1
}
selectedBuddyId = action.fromId
MessageStore.emitChange()
break
case 'CLEAR_ALL': // for unit tests
messages = []
break
}
// needed for the promise in the dispatcher to indicate no errors
return true
})
})
module.exports = MessageStore
|
'use strict';
describe('app.version module', function() {
beforeEach(module('app.version'));
describe('version service', function() {
it('should return current version', inject(function(version) {
expect(version).toEqual('0.1');
}));
});
});
|
$(function(){
var pathname = window.location.pathname;
populateTable(pathname);
var input = document.getElementById("input-file");
$('#input-file').change(function(){
var file = input.files;
var cont = input.files.lenght;
// $('#form-upload').append($('<input type="text" , name="upFile", class="filestyle" value="'+fileName+'">'));
$(file).each(function(i){
$('#form-upload').append($('<input id="file_'+i+'" type="text" , name="upFile", class="col-md-10 col-sm-10 col-xs-10" value="'+file[i].name+'" disabled>'));
$('#form-upload').append($('<span id="file_'+i+'" class="col-md-2 col-sm-2 col-xs-2">'+filesize(file[i].size,{round: 0})+'</span>'));
});
});
var dest = pathname.replace('/p','');
$("#fileuploader").uploadFile({
url:"/upload"+dest,
fileName:"file",
autoSubmit: true,
showDone: false,
showDownload: false,
showProgress: true,
showPreview: true,
previewWidth: "100%",
dragdropWidth: "100%",
afterUploadAll:function(obj)
{
location.reload();
setInterval($.notify('Upload realizado com sucesso.', 'success'), 3000);
}
});
});
$('#modal-criarPasta').on('shown.bs.modal', function () {
$('#nomePasta').focus();
});
$('#form-upload').submit(function(){
var cont = $("#input-file")[0].files.length;
if(cont < 1){
$('#input-file').notify('Nenhum arquivo informado');
return false;
}
});
$('#modal-criarPasta #criar-pasta').submit(function(){
var nomePasta = $('#nomePasta').val();
if(!nomePasta){
$('#nomePasta').notify('Informe o nome da pasta', 'error');
return false;
}else{
criarPasta();
}
return false;
});
function excluirItem(data){
var url = $(data).attr('data-url');
$.confirm({
title: 'ATENÇÃO!',
content: 'Tem certeza que deseja excluir esse arquivo?',
buttons: {
Excluir: {
btnClass: 'btn-red',
action: function () {
$.get(url, function(){
location.reload();
});
}
},
cancelar: function () {
}
}
});
};
function criarPasta(){
var nomePasta = $('#nomePasta').val();
var url = window.location.pathname;
var pathname;
if(url == '/home' || url == 'home' ){
pathname = '/';
}else{
pathname = url.replace('/p','');
}
$.post('/pasta/criar', {nomePasta: nomePasta, pathname: pathname})
.done(function(data){
location.reload();
$('#modal-criarPasta').modal('hide');
$.notify('Pasta criada com sucesso', 'success');
});
};
function populateTable(pathname){
let tableContent = '';
var pasta = '/show/p/show';
if(pathname != '/home'){
pasta = '/show'+pathname;
}
$.get(pasta, function (data) {
if(!data){
$('#table').hide();
}else {
for(var item in data){
let nome = data[item].filename;
let dataFormatada = jQuery.format.date(data[item].data_upload, 'dd/MM/yyyy HH:mm:ss');
let tipo = data[item].ext;
let icon;
let tamanho;
let curl;
if(data[item].ext == '/'){
tamanho = '';
nome += '/';
tipo = 'directory';
icon = 'folder';
curl = '/p/'+nome;
} else {
tamanho = filesize(data[item].size,{round:0});
icon = 'file';
curl = '/download/'+nome;
}
//tableContent += '<tr id="tr-id-'+i+'" class="tr-class-'+i+'" data-title="bootstrap table">';
tableContent += '<tr id="tr-item">';
tableContent += '<td class="ext_'+tipo+'"></td>'
if(tipo == 'directory'){
tableContent += '<td><a onClick="showPasta(this)" class="btn btn-link" data-url="'+curl+'" href="'+curl+'">'+nome+'</a></td>';
}else{
tableContent += '<td><a href="'+curl+'">'+nome+'</a></td>';
}
// tableContent += '<td>'+tipo+'</td>';
tableContent += '<td>'+dataFormatada+'</td>';
tableContent += '<td>'+tamanho+'</td>';
tableContent += '<td><button type="button" data-url="/file/remove/'+data[item]._id+'" class="btn btn-danger btn-xs faa-parent animated-hover" onClick="excluirItem(this)" data-toggle="tooltip" data-placement="auto" title="Excluir"><i class="fa fa-trash-o fa-fw fa-2x faa-wrench faa-slow" /></button></td>';
tableContent += '</tr>';
}
$('#download table tbody').html(tableContent);
}
});
}; |
/**
@module ember
@submodule ember-application
*/
import DAG from 'dag-map';
import Container from 'container/container';
import Ember from "ember-metal"; // Ember.FEATURES, Ember.deprecate, Ember.assert, Ember.libraries, LOG_VERSION, Namespace, BOOTED
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import { runLoadHooks } from "ember-runtime/system/lazy_load";
import Namespace from "ember-runtime/system/namespace";
import DeferredMixin from "ember-runtime/mixins/deferred";
import DefaultResolver from "ember-application/system/resolver";
import { create } from "ember-metal/platform";
import run from "ember-metal/run_loop";
import { canInvoke } from "ember-metal/utils";
import Controller from "ember-runtime/controllers/controller";
import EnumerableUtils from "ember-metal/enumerable_utils";
import ObjectController from "ember-runtime/controllers/object_controller";
import ArrayController from "ember-runtime/controllers/array_controller";
import SelectView from "ember-handlebars/controls/select";
import EventDispatcher from "ember-views/system/event_dispatcher";
import jQuery from "ember-views/system/jquery";
import Route from "ember-routing/system/route";
import Router from "ember-routing/system/router";
import HashLocation from "ember-routing/location/hash_location";
import HistoryLocation from "ember-routing/location/history_location";
import AutoLocation from "ember-routing/location/auto_location";
import NoneLocation from "ember-routing/location/none_location";
import BucketCache from "ember-routing/system/cache";
// this is technically incorrect (per @wycats)
// it should work properly with:
// `import ContainerDebugAdapter from 'ember-extension-support/container_debug_adapter';` but
// es6-module-transpiler 0.4.0 eagerly grabs the module (which is undefined)
import ContainerDebugAdapter from "ember-extension-support/container_debug_adapter";
import {
K
} from 'ember-metal/core';
import EmberHandlebars from "ember-handlebars-compiler";
function props(obj) {
var properties = [];
for (var key in obj) {
properties.push(key);
}
return properties;
}
/**
An instance of `Ember.Application` is the starting point for every Ember
application. It helps to instantiate, initialize and coordinate the many
objects that make up your app.
Each Ember app has one and only one `Ember.Application` object. In fact, the
very first thing you should do in your application is create the instance:
```javascript
window.App = Ember.Application.create();
```
Typically, the application object is the only global variable. All other
classes in your app should be properties on the `Ember.Application` instance,
which highlights its first role: a global namespace.
For example, if you define a view class, it might look like this:
```javascript
App.MyView = Ember.View.extend();
```
By default, calling `Ember.Application.create()` will automatically initialize
your application by calling the `Ember.Application.initialize()` method. If
you need to delay initialization, you can call your app's `deferReadiness()`
method. When you are ready for your app to be initialized, call its
`advanceReadiness()` method.
You can define a `ready` method on the `Ember.Application` instance, which
will be run by Ember when the application is initialized.
Because `Ember.Application` inherits from `Ember.Namespace`, any classes
you create will have useful string representations when calling `toString()`.
See the `Ember.Namespace` documentation for more information.
While you can think of your `Ember.Application` as a container that holds the
other classes in your application, there are several other responsibilities
going on under-the-hood that you may want to understand.
### Event Delegation
Ember uses a technique called _event delegation_. This allows the framework
to set up a global, shared event listener instead of requiring each view to
do it manually. For example, instead of each view registering its own
`mousedown` listener on its associated element, Ember sets up a `mousedown`
listener on the `body`.
If a `mousedown` event occurs, Ember will look at the target of the event and
start walking up the DOM node tree, finding corresponding views and invoking
their `mouseDown` method as it goes.
`Ember.Application` has a number of default events that it listens for, as
well as a mapping from lowercase events to camel-cased view method names. For
example, the `keypress` event causes the `keyPress` method on the view to be
called, the `dblclick` event causes `doubleClick` to be called, and so on.
If there is a bubbling browser event that Ember does not listen for by
default, you can specify custom events and their corresponding view method
names by setting the application's `customEvents` property:
```javascript
var App = Ember.Application.create({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
```
By default, the application sets up these event listeners on the document
body. However, in cases where you are embedding an Ember application inside
an existing page, you may want it to set up the listeners on an element
inside the body.
For example, if only events inside a DOM element with the ID of `ember-app`
should be delegated, set your application's `rootElement` property:
```javascript
var App = Ember.Application.create({
rootElement: '#ember-app'
});
```
The `rootElement` can be either a DOM element or a jQuery-compatible selector
string. Note that *views appended to the DOM outside the root element will
not receive events.* If you specify a custom root element, make sure you only
append views inside it!
To learn more about the advantages of event delegation and the Ember view
layer, and a list of the event listeners that are setup by default, visit the
[Ember View Layer guide](http://emberjs.com/guides/understanding-ember/the-view-layer/#toc_event-delegation).
### Initializers
Libraries on top of Ember can add initializers, like so:
```javascript
Ember.Application.initializer({
name: 'api-adapter',
initialize: function(container, application) {
application.register('api-adapter:main', ApiAdapter);
}
});
```
Initializers provide an opportunity to access the container, which
organizes the different components of an Ember application. Additionally
they provide a chance to access the instantiated application. Beyond
being used for libraries, initializers are also a great way to organize
dependency injection or setup in your own application.
### Routing
In addition to creating your application's router, `Ember.Application` is
also responsible for telling the router when to start routing. Transitions
between routes can be logged with the `LOG_TRANSITIONS` flag, and more
detailed intra-transition logging can be logged with
the `LOG_TRANSITIONS_INTERNAL` flag:
```javascript
var App = Ember.Application.create({
LOG_TRANSITIONS: true, // basic logging of successful transitions
LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps
});
```
By default, the router will begin trying to translate the current URL into
application state once the browser emits the `DOMContentReady` event. If you
need to defer routing, you can call the application's `deferReadiness()`
method. Once routing can begin, call the `advanceReadiness()` method.
If there is any setup required before routing begins, you can implement a
`ready()` method on your app that will be invoked immediately before routing
begins.
```
@class Application
@namespace Ember
@extends Ember.Namespace
*/
var Application = Namespace.extend(DeferredMixin, {
_suppressDeferredDeprecation: true,
/**
The root DOM element of the Application. This can be specified as an
element or a
[jQuery-compatible selector string](http://api.jquery.com/category/selectors/).
This is the element that will be passed to the Application's,
`eventDispatcher`, which sets up the listeners for event delegation. Every
view in your application should be a child of the element you specify here.
@property rootElement
@type DOMElement
@default 'body'
*/
rootElement: 'body',
/**
The `Ember.EventDispatcher` responsible for delegating events to this
application's views.
The event dispatcher is created by the application at initialization time
and sets up event listeners on the DOM element described by the
application's `rootElement` property.
See the documentation for `Ember.EventDispatcher` for more information.
@property eventDispatcher
@type Ember.EventDispatcher
@default null
*/
eventDispatcher: null,
/**
The DOM events for which the event dispatcher should listen.
By default, the application's `Ember.EventDispatcher` listens
for a set of standard DOM events, such as `mousedown` and
`keyup`, and delegates them to your application's `Ember.View`
instances.
If you would like additional bubbling events to be delegated to your
views, set your `Ember.Application`'s `customEvents` property
to a hash containing the DOM event name as the key and the
corresponding view method name as the value. For example:
```javascript
var App = Ember.Application.create({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
```
@property customEvents
@type Object
@default null
*/
customEvents: null,
// Start off the number of deferrals at 1. This will be
// decremented by the Application's own `initialize` method.
_readinessDeferrals: 1,
init: function() {
if (!this.$) {
this.$ = jQuery;
}
this.__container__ = this.buildContainer();
this.Router = this.defaultRouter();
this._super();
this.scheduleInitialize();
Ember.libraries.registerCoreLibrary('Handlebars' + (EmberHandlebars.compile ? '' : '-runtime'), EmberHandlebars.VERSION);
Ember.libraries.registerCoreLibrary('jQuery', jQuery().jquery);
if ( Ember.LOG_VERSION ) {
Ember.LOG_VERSION = false; // we only need to see this once per Application#init
var nameLengths = EnumerableUtils.map(Ember.libraries, function(item) {
return get(item, "name.length");
});
var maxNameLength = Math.max.apply(this, nameLengths);
Ember.debug('-------------------------------');
Ember.libraries.each(function(name, version) {
var spaces = new Array(maxNameLength - name.length + 1).join(" ");
Ember.debug([name, spaces, ' : ', version].join(""));
});
Ember.debug('-------------------------------');
}
},
/**
Build the container for the current application.
Also register a default application view in case the application
itself does not.
@private
@method buildContainer
@return {Ember.Container} the configured container
*/
buildContainer: function() {
var container = this.__container__ = Application.buildContainer(this);
return container;
},
/**
If the application has not opted out of routing and has not explicitly
defined a router, supply a default router for the application author
to configure.
This allows application developers to do:
```javascript
var App = Ember.Application.create();
App.Router.map(function() {
this.resource('posts');
});
```
@private
@method defaultRouter
@return {Ember.Router} the default router
*/
defaultRouter: function() {
if (this.Router === false) { return; }
var container = this.__container__;
if (this.Router) {
container.unregister('router:main');
container.register('router:main', this.Router);
}
return container.lookupFactory('router:main');
},
/**
Automatically initialize the application once the DOM has
become ready.
The initialization itself is scheduled on the actions queue
which ensures that application loading finishes before
booting.
If you are asynchronously loading code, you should call
`deferReadiness()` to defer booting, and then call
`advanceReadiness()` once all of your code has finished
loading.
@private
@method scheduleInitialize
*/
scheduleInitialize: function() {
var self = this;
if (!this.$ || this.$.isReady) {
run.schedule('actions', self, '_initialize');
} else {
this.$().ready(function runInitialize() {
run(self, '_initialize');
});
}
},
/**
Use this to defer readiness until some condition is true.
Example:
```javascript
var App = Ember.Application.create();
App.deferReadiness();
// Ember.$ is a reference to the jQuery object/function
Ember.$.getJSON('/auth-token', function(token) {
App.token = token;
App.advanceReadiness();
});
```
This allows you to perform asynchronous setup logic and defer
booting your application until the setup has finished.
However, if the setup requires a loading UI, it might be better
to use the router for this purpose.
@method deferReadiness
*/
deferReadiness: function() {
Ember.assert("You must call deferReadiness on an instance of Ember.Application", this instanceof Application);
Ember.assert("You cannot defer readiness since the `ready()` hook has already been called.", this._readinessDeferrals > 0);
this._readinessDeferrals++;
},
/**
Call `advanceReadiness` after any asynchronous setup logic has completed.
Each call to `deferReadiness` must be matched by a call to `advanceReadiness`
or the application will never become ready and routing will not begin.
@method advanceReadiness
@see {Ember.Application#deferReadiness}
*/
advanceReadiness: function() {
Ember.assert("You must call advanceReadiness on an instance of Ember.Application", this instanceof Application);
this._readinessDeferrals--;
if (this._readinessDeferrals === 0) {
run.once(this, this.didBecomeReady);
}
},
/**
Registers a factory that can be used for dependency injection (with
`App.inject`) or for service lookup. Each factory is registered with
a full name including two parts: `type:name`.
A simple example:
```javascript
var App = Ember.Application.create();
App.Orange = Ember.Object.extend();
App.register('fruit:favorite', App.Orange);
```
Ember will resolve factories from the `App` namespace automatically.
For example `App.CarsController` will be discovered and returned if
an application requests `controller:cars`.
An example of registering a controller with a non-standard name:
```javascript
var App = Ember.Application.create();
var Session = Ember.Controller.extend();
App.register('controller:session', Session);
// The Session controller can now be treated like a normal controller,
// despite its non-standard name.
App.ApplicationController = Ember.Controller.extend({
needs: ['session']
});
```
Registered factories are **instantiated** by having `create`
called on them. Additionally they are **singletons**, each time
they are looked up they return the same instance.
Some examples modifying that default behavior:
```javascript
var App = Ember.Application.create();
App.Person = Ember.Object.extend();
App.Orange = Ember.Object.extend();
App.Email = Ember.Object.extend();
App.session = Ember.Object.create();
App.register('model:user', App.Person, { singleton: false });
App.register('fruit:favorite', App.Orange);
App.register('communication:main', App.Email, { singleton: false });
App.register('session', App.session, { instantiate: false });
```
@method register
@param fullName {String} type:name (e.g., 'model:user')
@param factory {Function} (e.g., App.Person)
@param options {Object} (optional) disable instantiation or singleton usage
**/
register: function() {
var container = this.__container__;
container.register.apply(container, arguments);
},
/**
Define a dependency injection onto a specific factory or all factories
of a type.
When Ember instantiates a controller, view, or other framework component
it can attach a dependency to that component. This is often used to
provide services to a set of framework components.
An example of providing a session object to all controllers:
```javascript
var App = Ember.Application.create();
var Session = Ember.Object.extend({ isAuthenticated: false });
// A factory must be registered before it can be injected
App.register('session:main', Session);
// Inject 'session:main' onto all factories of the type 'controller'
// with the name 'session'
App.inject('controller', 'session', 'session:main');
App.IndexController = Ember.Controller.extend({
isLoggedIn: Ember.computed.alias('session.isAuthenticated')
});
```
Injections can also be performed on specific factories.
```javascript
App.inject(<full_name or type>, <property name>, <full_name>)
App.inject('route', 'source', 'source:main')
App.inject('route:application', 'email', 'model:email')
```
It is important to note that injections can only be performed on
classes that are instantiated by Ember itself. Instantiating a class
directly (via `create` or `new`) bypasses the dependency injection
system.
**Note:** Ember-Data instantiates its models in a unique manner, and consequently
injections onto models (or all models) will not work as expected. Injections
on models can be enabled by setting `Ember.MODEL_FACTORY_INJECTIONS`
to `true`.
@method inject
@param factoryNameOrType {String}
@param property {String}
@param injectionName {String}
**/
inject: function() {
var container = this.__container__;
container.injection.apply(container, arguments);
},
/**
Calling initialize manually is not supported.
Please see Ember.Application#advanceReadiness and
Ember.Application#deferReadiness.
@private
@deprecated
@method initialize
**/
initialize: function() {
Ember.deprecate('Calling initialize manually is not supported. Please see Ember.Application#advanceReadiness and Ember.Application#deferReadiness');
},
/**
Initialize the application. This happens automatically.
Run any initializers and run the application load hook. These hooks may
choose to defer readiness. For example, an authentication hook might want
to defer readiness until the auth token has been retrieved.
@private
@method _initialize
*/
_initialize: function() {
if (this.isDestroyed) { return; }
// At this point, the App.Router must already be assigned
if (this.Router) {
var container = this.__container__;
container.unregister('router:main');
container.register('router:main', this.Router);
}
this.runInitializers();
runLoadHooks('application', this);
// At this point, any initializers or load hooks that would have wanted
// to defer readiness have fired. In general, advancing readiness here
// will proceed to didBecomeReady.
this.advanceReadiness();
return this;
},
/**
Reset the application. This is typically used only in tests. It cleans up
the application in the following order:
1. Deactivate existing routes
2. Destroy all objects in the container
3. Create a new application container
4. Re-route to the existing url
Typical Example:
```javascript
var App;
run(function() {
App = Ember.Application.create();
});
module('acceptance test', {
setup: function() {
App.reset();
}
});
test('first test', function() {
// App is freshly reset
});
test('second test', function() {
// App is again freshly reset
});
```
Advanced Example:
Occasionally you may want to prevent the app from initializing during
setup. This could enable extra configuration, or enable asserting prior
to the app becoming ready.
```javascript
var App;
run(function() {
App = Ember.Application.create();
});
module('acceptance test', {
setup: function() {
run(function() {
App.reset();
App.deferReadiness();
});
}
});
test('first test', function() {
ok(true, 'something before app is initialized');
run(function() {
App.advanceReadiness();
});
ok(true, 'something after app is initialized');
});
```
@method reset
**/
reset: function() {
this._readinessDeferrals = 1;
function handleReset() {
var router = this.__container__.lookup('router:main');
router.reset();
run(this.__container__, 'destroy');
this.buildContainer();
run.schedule('actions', this, function() {
this._initialize();
});
}
run.join(this, handleReset);
},
/**
@private
@method runInitializers
*/
runInitializers: function() {
var initializersByName = get(this.constructor, 'initializers');
var initializers = props(initializersByName);
var container = this.__container__;
var graph = new DAG();
var namespace = this;
var initializer;
for (var i = 0; i < initializers.length; i++) {
initializer = initializersByName[initializers[i]];
graph.addEdges(initializer.name, initializer.initialize, initializer.before, initializer.after);
}
graph.topsort(function (vertex) {
var initializer = vertex.value;
Ember.assert("No application initializer named '" + vertex.name + "'", initializer);
initializer(container, namespace);
});
},
/**
@private
@method didBecomeReady
*/
didBecomeReady: function() {
this.setupEventDispatcher();
this.ready(); // user hook
this.startRouting();
if (!Ember.testing) {
// Eagerly name all classes that are already loaded
Ember.Namespace.processAll();
Ember.BOOTED = true;
}
this.resolve(this);
},
/**
Setup up the event dispatcher to receive events on the
application's `rootElement` with any registered
`customEvents`.
@private
@method setupEventDispatcher
*/
setupEventDispatcher: function() {
var customEvents = get(this, 'customEvents');
var rootElement = get(this, 'rootElement');
var dispatcher = this.__container__.lookup('event_dispatcher:main');
set(this, 'eventDispatcher', dispatcher);
dispatcher.setup(customEvents, rootElement);
},
/**
If the application has a router, use it to route to the current URL, and
trigger a new call to `route` whenever the URL changes.
@private
@method startRouting
@property router {Ember.Router}
*/
startRouting: function() {
var router = this.__container__.lookup('router:main');
if (!router) { return; }
router.startRouting();
},
handleURL: function(url) {
var router = this.__container__.lookup('router:main');
router.handleURL(url);
},
/**
Called when the Application has become ready.
The call will be delayed until the DOM has become ready.
@event ready
*/
ready: K,
/**
@deprecated Use 'Resolver' instead
Set this to provide an alternate class to `Ember.DefaultResolver`
@property resolver
*/
resolver: null,
/**
Set this to provide an alternate class to `Ember.DefaultResolver`
@property resolver
*/
Resolver: null,
willDestroy: function() {
Ember.BOOTED = false;
// Ensure deactivation of routes before objects are destroyed
this.__container__.lookup('router:main').reset();
this.__container__.destroy();
},
initializer: function(options) {
this.constructor.initializer(options);
},
/**
@method then
@private
@deprecated
*/
then: function() {
Ember.deprecate('Do not use `.then` on an instance of Ember.Application. Please use the `.ready` hook instead.');
this._super.apply(this, arguments);
}
});
Application.reopenClass({
initializers: create(null),
/**
Initializer receives an object which has the following attributes:
`name`, `before`, `after`, `initialize`. The only required attribute is
`initialize, all others are optional.
* `name` allows you to specify under which name the initializer is registered.
This must be a unique name, as trying to register two initializers with the
same name will result in an error.
```javascript
Ember.Application.initializer({
name: 'namedInitializer',
initialize: function(container, application) {
Ember.debug('Running namedInitializer!');
}
});
```
* `before` and `after` are used to ensure that this initializer is ran prior
or after the one identified by the value. This value can be a single string
or an array of strings, referencing the `name` of other initializers.
An example of ordering initializers, we create an initializer named `first`:
```javascript
Ember.Application.initializer({
name: 'first',
initialize: function(container, application) {
Ember.debug('First initializer!');
}
});
// DEBUG: First initializer!
```
We add another initializer named `second`, specifying that it should run
after the initializer named `first`:
```javascript
Ember.Application.initializer({
name: 'second',
after: 'first',
initialize: function(container, application) {
Ember.debug('Second initializer!');
}
});
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
Afterwards we add a further initializer named `pre`, this time specifying
that it should run before the initializer named `first`:
```javascript
Ember.Application.initializer({
name: 'pre',
before: 'first',
initialize: function(container, application) {
Ember.debug('Pre initializer!');
}
});
// DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
Finally we add an initializer named `post`, specifying it should run after
both the `first` and the `second` initializers:
```javascript
Ember.Application.initializer({
name: 'post',
after: ['first', 'second'],
initialize: function(container, application) {
Ember.debug('Post initializer!');
}
});
// DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
// DEBUG: Post initializer!
```
* `initialize` is a callback function that receives two arguments, `container`
and `application` on which you can operate.
Example of using `container` to preload data into the store:
```javascript
Ember.Application.initializer({
name: 'preload-data',
initialize: function(container, application) {
var store = container.lookup('store:main');
store.pushPayload(preloadedData);
}
});
```
Example of using `application` to register an adapter:
```javascript
Ember.Application.initializer({
name: 'api-adapter',
initialize: function(container, application) {
application.register('api-adapter:main', ApiAdapter);
}
});
```
@method initializer
@param initializer {Object}
*/
initializer: function(initializer) {
// If this is the first initializer being added to a subclass, we are going to reopen the class
// to make sure we have a new `initializers` object, which extends from the parent class' using
// prototypal inheritance. Without this, attempting to add initializers to the subclass would
// pollute the parent class as well as other subclasses.
if (this.superclass.initializers !== undefined && this.superclass.initializers === this.initializers) {
this.reopenClass({
initializers: create(this.initializers)
});
}
Ember.assert("The initializer '" + initializer.name + "' has already been registered", !this.initializers[initializer.name]);
Ember.assert("An initializer cannot be registered without an initialize function", canInvoke(initializer, 'initialize'));
Ember.assert("An initializer cannot be registered without a name property", initializer.name !== undefined);
this.initializers[initializer.name] = initializer;
},
/**
This creates a container with the default Ember naming conventions.
It also configures the container:
* registered views are created every time they are looked up (they are
not singletons)
* registered templates are not factories; the registered value is
returned directly.
* the router receives the application as its `namespace` property
* all controllers receive the router as their `target` and `controllers`
properties
* all controllers receive the application as their `namespace` property
* the application view receives the application controller as its
`controller` property
* the application view receives the application template as its
`defaultTemplate` property
@private
@method buildContainer
@static
@param {Ember.Application} namespace the application to build the
container for.
@return {Ember.Container} the built container
*/
buildContainer: function(namespace) {
var container = new Container();
container.set = set;
container.resolver = resolverFor(namespace);
container.normalizeFullName = container.resolver.normalize;
container.describe = container.resolver.describe;
container.makeToString = container.resolver.makeToString;
container.optionsForType('component', { singleton: false });
container.optionsForType('view', { singleton: false });
container.optionsForType('template', { instantiate: false });
container.optionsForType('helper', { instantiate: false });
container.register('application:main', namespace, { instantiate: false });
container.register('controller:basic', Controller, { instantiate: false });
container.register('controller:object', ObjectController, { instantiate: false });
container.register('controller:array', ArrayController, { instantiate: false });
container.register('view:select', SelectView);
container.register('route:basic', Route, { instantiate: false });
container.register('event_dispatcher:main', EventDispatcher);
container.register('router:main', Router);
container.injection('router:main', 'namespace', 'application:main');
container.register('location:auto', AutoLocation);
container.register('location:hash', HashLocation);
container.register('location:history', HistoryLocation);
container.register('location:none', NoneLocation);
container.injection('controller', 'target', 'router:main');
container.injection('controller', 'namespace', 'application:main');
container.register('-bucket-cache:main', BucketCache);
container.injection('router', '_bucketCache', '-bucket-cache:main');
container.injection('route', '_bucketCache', '-bucket-cache:main');
container.injection('controller', '_bucketCache', '-bucket-cache:main');
container.injection('route', 'router', 'router:main');
container.injection('location', 'rootURL', '-location-setting:root-url');
// DEBUGGING
container.register('resolver-for-debugging:main', container.resolver.__resolver__, { instantiate: false });
container.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
container.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
// Custom resolver authors may want to register their own ContainerDebugAdapter with this key
container.register('container-debug-adapter:main', ContainerDebugAdapter);
return container;
}
});
/**
This function defines the default lookup rules for container lookups:
* templates are looked up on `Ember.TEMPLATES`
* other names are looked up on the application after classifying the name.
For example, `controller:post` looks up `App.PostController` by default.
* if the default lookup fails, look for registered classes on the container
This allows the application to register default injections in the container
that could be overridden by the normal naming convention.
@private
@method resolverFor
@param {Ember.Namespace} namespace the namespace to look for classes
@return {*} the resolved value for a given lookup
*/
function resolverFor(namespace) {
if (namespace.get('resolver')) {
Ember.deprecate('Application.resolver is deprecated in favor of Application.Resolver', false);
}
var ResolverClass = namespace.get('resolver') || namespace.get('Resolver') || DefaultResolver;
var resolver = ResolverClass.create({
namespace: namespace
});
function resolve(fullName) {
return resolver.resolve(fullName);
}
resolve.describe = function(fullName) {
return resolver.lookupDescription(fullName);
};
resolve.makeToString = function(factory, fullName) {
return resolver.makeToString(factory, fullName);
};
resolve.normalize = function(fullName) {
if (resolver.normalize) {
return resolver.normalize(fullName);
} else {
Ember.deprecate('The Resolver should now provide a \'normalize\' function', false);
return fullName;
}
};
resolve.__resolver__ = resolver;
return resolve;
}
export default Application;
|
(function() {
module("can/view");
test("multiple template types work", function(){
var expected = '<h3>helloworld</h3>';
can.each(["micro","ejs","jaml", "mustache"], function(ext){
var actual = can.view.render("//can/view/test/template." + ext, {
"message" :"helloworld"
}, {
helper: function(){
return "foo"
}
});
equal(can.trim(actual), expected, "Text rendered");
})
});
test("helpers work", function(){
var expected = '<h3>helloworld</h3><div>foo</div>';
can.each(["ejs", "mustache"], function(ext){
var actual = can.view.render("//can/view/test/helpers." + ext, {
"message" :"helloworld"
}, {
helper: function(){
return "foo"
}
});
equal(can.trim(actual), expected, "Text rendered");
})
});
test("buildFragment works right", function(){
can.append( can.$("#qunit-test-area"), can.view("//can/view/test//plugin.ejs",{}) )
ok(/something/.test( can.$("#something span")[0].firstChild.nodeValue ),"something has something");
can.remove( can.$("#something") );
});
test("async templates, and caching work", function(){
stop();
var i = 0;
can.view.render("//can/view/test//temp.ejs",{"message" :"helloworld"}, function(text){
ok(/helloworld\s*/.test(text), "we got a rendered template");
i++;
equals(i, 2, "Ajax is not synchronous");
start();
});
i++;
equals(i, 1, "Ajax is not synchronous")
})
test("caching works", function(){
// this basically does a large ajax request and makes sure
// that the second time is always faster
stop();
var startT = new Date(),
first;
can.view.render("//can/view/test//large.ejs",{"message" :"helloworld"}, function(text){
first = new Date();
ok(text, "we got a rendered template");
can.view.render("//can/view/test//large.ejs",{"message" :"helloworld"}, function(text){
var lap2 = (new Date()) - first,
lap1 = first-startT;
// ok( lap1 > lap2, "faster this time "+(lap1 - lap2) )
start();
})
})
})
test("hookup", function(){
can.view("//can/view/test//hookup.ejs",{})
})
test("inline templates other than 'tmpl' like ejs", function(){
var script = document.createElement('script');
script.setAttribute('type', 'test/ejs')
script.setAttribute('id', 'test_ejs')
script.text = '<span id="new_name"><%= name %></span>';
document.getElementById("qunit-test-area").appendChild(script);
var div = document.createElement('div');
div.appendChild(can.view('test_ejs', {name: 'Henry'}))
equal( div.getElementsByTagName("span")[0].firstChild.nodeValue , 'Henry');
});
//canjs issue #31
test("render inline templates with a #", function(){
var script = document.createElement('script');
script.setAttribute('type', 'test/ejs')
script.setAttribute('id', 'test_ejs')
script.text = '<span id="new_name"><%= name %></span>';
document.getElementById("qunit-test-area").appendChild(script);
var div = document.createElement('div');
div.appendChild(can.view('#test_ejs', {name: 'Henry'}));
//make sure we aren't returning the current document as the template
equals(div.getElementsByTagName("script").length, 0, "Current document was not used as template")
if(div.getElementsByTagName("span").length === 1) {
equal( div.getElementsByTagName("span")[0].firstChild.nodeValue , 'Henry');
}
});
test("object of deferreds", function(){
var foo = new can.Deferred(),
bar = new can.Deferred();
stop();
can.view.render("//can/view/test//deferreds.ejs",{
foo : typeof foo.promise == 'function' ? foo.promise() : foo,
bar : bar
}).then(function(result){
equals(result, "FOO and BAR");
start();
});
setTimeout(function(){
foo.resolve("FOO");
},100);
bar.resolve("BAR");
});
test("deferred", function(){
var foo = new can.Deferred();
stop();
can.view.render("//can/view/test//deferred.ejs",foo).then(function(result){
equals(result, "FOO");
start();
});
setTimeout(function(){
foo.resolve({
foo: "FOO"
});
},100);
});
test("hyphen in type", function(){
var script = document.createElement('script');
script.setAttribute('type', 'text/x-ejs')
script.setAttribute('id', 'hyphenEjs')
script.text = '\nHyphen\n';
document.getElementById("qunit-test-area").appendChild(script);
var div = document.createElement('div');
div.appendChild(can.view('hyphenEjs', {}))
ok( /Hyphen/.test(div.innerHTML) , 'has hyphen');
})
test("create template with string", function(){
can.view.ejs("fool", "everybody plays the <%= who %> <%= howOften %>");
var div = document.createElement('div');
div.appendChild(can.view('fool', {who: "fool", howOften: "sometimes"}));
ok( /fool sometimes/.test(div.innerHTML) , 'has fool sometimes'+div.innerHTML);
})
test("return renderer", function() {
var directResult = can.view.ejs('renderer_test', "This is a <%= test %>");
var renderer = can.view('renderer_test');
ok(can.isFunction(directResult), 'Renderer returned directly');
ok(can.isFunction(renderer), 'Renderer is a function');
equal(renderer({ test : 'working test' }), 'This is a working test', 'Rendered');
renderer = can.view("//can/view/test//template.ejs");
ok(can.isFunction(renderer), 'Renderer is a function');
equal(renderer({ message : 'Rendered!' }), '<h3>Rendered!</h3>', 'Synchronous template loaded and rendered');
// TODO doesn't get caught in Zepto for whatever reason
// raises(function() {
// can.view('jkflsd.ejs');
// }, 'Nonexistent template throws error');
});
test("nameless renderers (#162, #195)", 8, function() {
// EJS
var nameless = can.view.ejs('<h2><%= message %></h2>'),
data = {
message : 'HI!'
},
result = nameless(data),
node = result.childNodes[0];
ok('ownerDocument' in result, 'Result is a document fragment');
equal(node.tagName.toLowerCase(), 'h2', 'Got h2 rendered');
equal(node.innerHTML, data.message, 'Got EJS result rendered');
equal(nameless.render(data), '<h2>HI!</h2>', '.render EJS works and returns HTML');
// Mustache
nameless = can.view.mustache('<h3>{{message}}</h3>');
data = {
message : 'MUSTACHE!'
};
result = nameless(data);
node = result.childNodes[0]
ok('ownerDocument' in result, 'Result is a document fragment');
equal(node.tagName.toLowerCase(), 'h3', 'Got h3 rendered');
equal(node.innerHTML, data.message, 'Got Mustache result rendered');
equal(nameless.render(data), '<h3>MUSTACHE!</h3>', '.render Mustache works and returns HTML');
});
test("deferred resolves with data (#183, #209)", function(){
var foo = new can.Deferred();
var bar = new can.Deferred();
var original = {
foo : foo,
bar : bar
};
stop();
ok(can.isDeferred(original.foo), 'Original foo property is a Deferred');
can.view("//can/view/test//deferred.ejs", original).then(function(result, data){
ok(data, 'Data exists');
equal(data.foo, 'FOO', 'Foo is resolved');
equal(data.bar, 'BAR', 'Bar is resolved');
ok(can.isDeferred(original.foo), 'Original property did not get modified');
start();
});
setTimeout(function(){
foo.resolve('FOO');
},100);
setTimeout(function() {
bar.resolve('BAR');
}, 50);
});
test("Empty model displays __!!__ as input values (#196)", function() {
can.view.ejs("test196", "User id: <%= user.attr('id') || '-' %>" +
" User name: <%= user.attr('name') || '-' %>");
var frag = can.view('test196', {
user: new can.Observe()
});
var div = document.createElement('div');
div.appendChild(frag);
equal(div.innerHTML, 'User id: - User name: -', 'Got expected HTML content');
can.view('test196', {
user : new can.Observe()
}, function(frag) {
div = document.createElement('div');
div.appendChild(frag);
equal(div.innerHTML, 'User id: - User name: -', 'Got expected HTML content in callback as well');
});
});
test("Select live bound options don't contain __!!__", function() {
var domainList = new can.Observe.List([{
id: 1,
name: 'example.com'
}, {
id: 2,
name: 'google.com'
}, {
id: 3,
name: 'yahoo.com'
}, {
id: 4,
name: 'microsoft.com'
}]),
frag = can.view("//can/view/test/select.ejs", {
domainList: domainList
}),
div = document.createElement('div');
div.appendChild(frag);
can.append( can.$("#qunit-test-area"), div)
equal(div.outerHTML.match(/__!!__/g), null, 'No __!!__ contained in HTML content')
//equal(can.$('#test-dropdown')[0].outerHTML, can.$('#test-dropdown2')[0].outerHTML, 'Live bound select and non-live bound select the same');
});
test('Live binding on number inputs', function(){
var template = can.view.ejs('<input id="candy" type="number" value="<%== state.attr("number") %>" />');
var observe = new can.Observe({ number : 2 });
var frag = template({ state: observe });
can.append(can.$("#qunit-test-area"), frag);
var input = document.getElementById('candy');
equal(input.getAttribute('value'), 2, 'render workered');
observe.attr('number', 5);
equal(input.getAttribute('value'), 5, 'update workered');
})
test("Resetting a live-bound <textarea> changes its value to __!!__ (#223)", function() {
var template = can.view.ejs("<form><textarea><%= this.attr('test') %></textarea></form>"),
frag = template(new can.Observe({
test : 'testing'
})),
form, textarea;
can.append(can.$("#qunit-test-area"), frag);
form = document.getElementById('qunit-test-area').getElementsByTagName('form')[0];
textarea = form.children[0];
equal(textarea.value, 'testing', 'Textarea value set');
textarea.value = 'blabla';
equal(textarea.value, 'blabla', 'Textarea value updated');
form.reset();
equal(form.children[0].value, 'testing', 'Textarea value set back to original live-bound value');
});
})(); |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7zm-4 6h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"
}), 'ListTwoTone'); |
// main.js
L(function(){
var myClock = new jClock({
canvasId: 'j-clock',
clockHight: window.innerWidth * 0.3,
clockWidth: window.innerWidth * 0.3
});
}) |
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
save(proposal) {
this.store.createResource('proposals', proposal).then((resp) => {
this.transitionToRoute('proposals.details', resp);
});
}
}
});
|
const jsonMerger = require("../../dist");
const { testConfig } = require("../../__helpers__");
jest.mock("fs");
const fs = require("fs");
describe("when processing an object containing an $include operation", function () {
test("it should resolve to the file defined in the $include property", function () {
const files = {
"a.json": {
b: "This should be the value of /a/b",
},
};
const object = {
a: {
$include: "a.json",
},
};
fs.__setJsonMockFiles(files);
const result = jsonMerger.mergeObject(object, testConfig());
expect(result).toMatchSnapshot();
});
test("it should process the file content in the current scope", function () {
const files = {
"a.json": {
$expression: "$source.b",
},
};
const object = {
a: {
$include: "a.json",
},
b: "This should be the value of /a",
};
fs.__setJsonMockFiles(files);
const result = jsonMerger.mergeObject(object, testConfig());
expect(result).toMatchSnapshot();
});
test("and used in an source array item it should process the file content as array item source", function () {
const files = {
"move.json": {
$move: "-",
},
};
const object1 = {
a: [
"should be the third item",
"should be the first item",
"should be the second item",
],
};
const object2 = {
a: [
{
$include: "move.json",
},
],
};
fs.__setJsonMockFiles(files);
const result = jsonMerger.mergeObjects([object1, object2], testConfig());
expect(result).toMatchSnapshot();
});
});
|
module.exports = require('./lib/email-obj'); |
var lib2 = require("TestLib2");
var output = lib2.t2("abc"); |
'use strict';
let terms;
let categories;
let series;
const highChartConverter = (function ( $ ) {
return {
convertCategories: function () {
// initialize xaxis categories (months)
const months = [];
$.map(data, function ( datapoint, i ) {
months.push(datapoint["month"]);
});
return months;
},
convertSeries: function () {
// initialize series data
const series = [];
$.map(terms, function ( term, i ) {
const term_data = { "name": term, "data": [], "total_mentions": 0 }
// build data
$.map(data, function ( datapoint, i ) {
term_data["data"].push( datapoint["terms"][term]["percentage"] );
term_data["total_mentions"] += datapoint["terms"][term]["count"];
});
// calculate YOY change
let first = term_data["data"][term_data["data"].length-13];
let last = term_data["data"][term_data["data"].length-1]
// assign a floor to have more meaningful change calculation
if (first == 0) {
first = 1;
}
if (last == 0) {
last = 1;
}
term_data["change"] = (last - first) / first;
term_data["latest_mentions"] = last;
series.push(term_data);
});
return series;
},
}
}) ( jQuery );
const chartBuilder = (function ( $ ) {
function render( seriesData ) {
$('#chart').highcharts({
chart: {
type: 'line'
},
title: {
text: ''
},
xAxis: {
categories: categories,
labels: {
step: 3,
staggerLines: 1
}
},
yAxis: {
title: {
text: 'Percentage of posts'
},
min: 0
},
tooltip: {
},
series: seriesData
});
}
return {
renderTopTerms: function( numTerms ) {
render( series.slice( 0, numTerms ) );
},
renderComparison: function() {
const compareTerms = $(".term-compare").map(function(i, val) {
return val.value.toLowerCase();
}).get();
const compareSeries = series.filter(function(val, i) {
return compareTerms.includes(val.name.toLowerCase());
});
render( compareSeries );
}
}
}) ( jQuery );
$(function () {
data.reverse();
terms = Object.keys( data[0]["terms"] );
// transform raw data in to format consumable by highcharts
categories = highChartConverter.convertCategories();
series = highChartConverter.convertSeries();
// sort by cumulative popularity
series.sort(function(a,b){ return b.latest_mentions - a.latest_mentions });
// wire up top terms filter
$( "#topfilter" ).on( "change", function ( e ) {
chartBuilder.renderTopTerms( parseInt($(this).val()) );
});
// process url parameters if present
const url = new URL(window.location);
let comparisons = url.searchParams.getAll("compare");
if (comparisons.length > 0) {
if (comparisons.length < 4) {
comparisons = comparisons.concat(Array(4-comparisons.length).fill(""));
}
$("div#term_comparisons").empty();
comparisons.forEach(function(queryTerm) {
$("div#term_comparisons").append(
$("<div class=\"col\">").append(
$("<input/>", {
type: 'text',
name: 'compare',
value: queryTerm,
class: "term-compare form-control"
})
)
);
});
chartBuilder.renderComparison();
} else {
chartBuilder.renderTopTerms(5);
}
// wire up autocomplete
$( ".term-compare" ).autocomplete({
source: terms
});
});
|
/**
* @author amberovsky
*
* Исполнители
*/
var AvaritiaExecutor = {
/**
* @var {Integer} последний максимальный id згруженного заказа
*/
lastMaxOrderId: 0,
/**
* Инициализация страницы
*/
init: function () {
this
.checkNewOrders(this)
.initExecuteOrder();
},
/**
* Рисует строку с данными заказа
*
* @param {AvaritiaExecutor} $this
* @param {Object} orderData
*/
createOrderRow: function($this, orderData) {
var
table = $('#orders-list'),
tr = $('<tr></tr>').addClass('order-item'),
tdId = $('<td></td>').text(orderData.id),
tdPrice = $('<td></td>').addClass('text-center').text(orderData.price),
tdDescription = $('<td></td>').html('<textarea class="form-control" rows="10">' + orderData.text + '</textarea>'),
tdButton = $('<td></td>').addClass('text-right'),
button = $('<button></button>')
.addClass('btn')
.addClass('btn-sm')
.addClass('btn-primary')
.addClass('execute-order')
.data('orderId', orderData.id)
.text('Выполнить');
tdButton.html(button);
tr
.append(tdId)
.append(tdPrice)
.append(tdDescription)
.append(tdButton);
table.append(tr);
$this.lastMaxOrderId = Math.max($this.lastMaxOrderId, orderData.id);
},
/**
* Выполнение заказа
*/
initExecuteOrder: function () {
var $this = this;
$(document).on('click', '.execute-order', function () {
$this.showLoader();
var
orderId = $(this).data('orderId'),
orderTr = $(this).closest('tr');
api.cmd(
'/executor/execute',
{
orderId: orderId,
token: $('#token').val()
},
function (data) {
orderTr.remove();
$this.hideLoader();
$this.onRequestSuccess('Успешно выполнено');
$('#salary').html(data.salary);
},
function (errorMsg, data) {
if (data.deleted) {
orderTr.remove();
}
$this.onRequestFail(errorMsg);
}
);
});
},
/**
* Проверяет новые заказы и добавляет, если есть
*
* @return {AvaritiaExecutor}
*/
checkNewOrders: function ($this) {
api.cmd(
'/executor/checkNew',
{
fromId: $this.lastMaxOrderId + 1,
token: $('#token').val()
},
function (data) {
for (var i in data) {
if (data.hasOwnProperty(i)) {
$this.createOrderRow($this, data[i]);
}
}
setTimeout(function () { $this.checkNewOrders($this); }, 2000);
},
function (errorMsg) { $this.onRequestFail(errorMsg); }
);
return $this;
},
/**
* Показываем индикатор отправки запроса
*/
showLoader: function() {
$('.loader').addClass('visible');
},
/**
* Не показываем индикатор отправки запроса
*/
hideLoader: function() {
$('.loader').removeClass('visible');
},
/**
* Обработчик ошибки выполнения запроса
*
* @param {String|undefined} errorMsg сообщение ошибки, если есть
*/
onRequestFail: function(errorMsg) {
this.hideLoader();
if (errorMsg) {
$('#failMessage')
.show()
.text(errorMsg)
.fadeOut(2000, function () {
$('#failMessage').hide();
});
}
},
/**
* Обработчик успешного выполнения запроса
*/
onRequestSuccess: function($message) {
this.hideLoader();
$('#successMessage')
.show()
.text($message)
.fadeOut(2000, function () {
$('#successMessage').hide();
});
}
};
$( document ).ready(function() {
AvaritiaExecutor.init();
});
|
define([
'ui-components/rb-check-control'
], function (rbCheckControl) {
describe('rb-check-control-group', function () {
var $compile,
$rootScope,
$scope,
compileTemplate,
element,
isolatedScope,
options = [
{
label: 'One',
value: 'one'
},
{
label: 'Two',
value: 'two'
},
{
label: 'Three',
value: 'three'
}
];
beforeEach(angular.mock.module(
rbCheckControl.name
));
beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new({});
compileTemplate = function (template) {
element = $compile(template)($scope);
$scope.$apply();
isolatedScope = element.isolateScope();
};
}));
describe('option', function () {
it('should render three inputs with correct values', function () {
$scope.options = options;
compileTemplate('<rb-check-control-group options="options" ng-model="model"></rb-check-control-group>');
var inputs = element.find('input');
expect(inputs.length).toBe(3);
expect(inputs.eq(0).attr('value')).toBe('one');
expect(inputs.eq(1).attr('value')).toBe('two');
expect(inputs.eq(2).attr('value')).toBe('three');
});
it('should render three labels with correct values', function () {
$scope.options = options;
compileTemplate('<rb-check-control-group options="options" ng-model="model"></rb-check-control-group>');
var labels = element.find('label');
expect(labels.eq(0).html()).toContain('One');
expect(labels.eq(1).html()).toContain('Two');
expect(labels.eq(2).html()).toContain('Three');
});
});
describe('columns', function () {
it('should set the group to display in columns to be 2', function () {
$scope.options = options;
compileTemplate('<rb-check-control-group options="options" ng-model="model" columns="2">' +
'</rb-check-control-group>');
var groupBody = angular.element(element.find('div')[1]);
expect(groupBody.hasClass('u-columnCount2')).toBeTruthy();
});
it('should set the group to display in columns to be 3', function () {
$scope.options = options;
compileTemplate('<rb-check-control-group options="options" ng-model="model" columns="3">' +
'</rb-check-control-group>');
var groupBody = angular.element(element.find('div')[1]);
expect(groupBody.hasClass('u-columnCount3')).toBeTruthy();
});
});
describe('model binding', function () {
it('should check any values in ngModel', function () {
// Before render
$scope.options = options;
$scope.ngModel = ['two'];
compileTemplate(
'<rb-check-control-group options="options" ng-model="ngModel"></rb-check-control-group>'
);
var inputs = element.find('input');
expect(inputs.eq(1).attr('checked')).toBe('checked');
});
it('should update checked when ngModel changes', function () {
$scope.options = options;
$scope.ngModel = [];
compileTemplate(
'<rb-check-control-group options="options" ng-model="ngModel"></rb-check-control-group>'
);
//After render
$scope.ngModel.push('one');
$scope.$apply();
var inputs = element.find('input');
expect(inputs.eq(0).attr('checked')).toBe('checked');
});
it('should only have one instance of a value in the model', function () {
// Before render
$scope.ngModel = [];
$scope.options = [
{
label: 'One',
value: 'one'
},
{
label: 'One One',
value: 'one'
},
{
label: 'Two',
value: 'two'
}
];
compileTemplate(
'<rb-check-control-group options="options" ng-model="ngModel"></rb-check-control-group>'
);
isolatedScope.options[0].checked = true;
isolatedScope.options[1].checked = true;
$scope.$apply();
expect($scope.ngModel).toEqual(['one']);
});
});
describe('checkbox state', function () {
it('should update model when state changes', function () {
// Before render
$scope.ngModel = [];
$scope.options = [
{
label: 'One',
value: 'one'
},
{
label: 'Two',
value: 'two'
}
];
compileTemplate(
'<rb-check-control-group options="options" ng-model="ngModel"></rb-check-control-group>'
);
isolatedScope.options[0].checked = true;
$scope.$apply();
expect($scope.ngModel).toEqual(['one']);
});
it('should update model when state changes and preseve model from other groups', function () {
// Before render
$scope.ngModel = ['three'];
$scope.options = [
{
label: 'One',
value: 'one'
},
{
label: 'Two',
value: 'two'
}
];
compileTemplate(
'<rb-check-control-group options="options" ng-model="ngModel"></rb-check-control-group>'
);
isolatedScope.options[0].checked = true;
$scope.$apply();
expect($scope.ngModel).toEqual(['three', 'one']);
});
it('should update model and not remove values from other checkbox groups', function () {
// Before render
$scope.ngModel = ['test'];
$scope.options = [
{
label: 'One',
value: 'one'
},
{
label: 'Two',
value: 'two'
}
];
compileTemplate(
'<rb-check-control-group options="options" ng-model="ngModel"></rb-check-control-group>'
);
// Simulate model changing externally and removing something that was checked before.
isolatedScope.options[0].checked = true;
$scope.$apply();
$scope.ngModel = ['test'];
isolatedScope.options[0].checked = false;
isolatedScope.options[1].checked = true;
$scope.$apply();
expect($scope.ngModel).toEqual(['test', 'two']);
});
});
});
});
|
export default class Map {
constructor(container) {
this.container = container || document.getElementById('map')
// failure to init as there's no map
if (!this.container) { return false }
this.map = L.map(this.container, {attributionControl: false})
// defaulting location to Stanley Park if geolocation fails
this.lat = this.container.dataset.lat || 32.7507794
this.lng = this.container.dataset.lng || -114.7650004
// marker containers
this.markers = []
this.currentMarker = null
this.previousMarker = null
}
init() {
const apiToken = "pk.eyJ1IjoiZ3JvY2VyeSIsImEiOiJjajA1cTZjdzQwNWR5Mndwa2dqM2l3ZnI4In0.MoTpE4qEHYKKYyOcfhd1Rg"
this.map.setView([this.lat, this.lng], 13);
const layer = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=' + apiToken, {
maxZoom: 18,
minZoom: 3,
id: 'mapbox.streets'
})
this.map.addControl(layer)
this.map.addControl(L.control.scale())
}
loadMarkers() {
const markers_json = JSON.parse(this.container.dataset.markers)
// no markers to show, centering map on current location
if (markers_json.length == 0) {
this.geolocate()
return false
}
let iconDefault = this._getIcon()
for (let [index, marker_json] of markers_json.entries()) {
// selecting icon
let icon = iconDefault
if(marker_json.is_current){
icon = this._getIcon('yellow')
} else if (marker_json.is_planned){
icon = this._getIcon('gray')
} else if (index == 0) {
icon = this._getIcon('green')
} else if (markers_json.length - 1 == index && marker_json.is_finish == true) {
icon = this._getIcon('red')
}
// putting marker on map
let marker = L.marker([marker_json.lat, marker_json.lng], {
icon: icon,
title: marker_json.title
})
marker.bindPopup("<a href='" + marker_json.url + "'>"+ marker_json.title +"</a>")
marker.addTo(this.map)
// registering markers for the map
this.markers.push(marker)
if(marker_json.is_current){
this.currentMarker = marker
marker.openPopup()
}
if(marker_json.is_previous){ this.previousMarker = marker }
}
}
centerMarkers(){
let markers = []
if(this.currentMarker){markers.push(this.currentMarker)}
if(this.previousMarker){markers.push(this.previousMarker)}
if(markers.length == 0){markers = this.markers}
if(markers.length == 0){return false}
let group = new L.featureGroup(markers)
this.map.fitBounds(group.getBounds(), {maxZoom: 13, padding: [30, 30]})
}
addCrosshair() {
let marker = L.marker(this.map.getCenter(), {
icon: this._getIcon('yellow'),
clickable: false}
)
marker.addTo(this.map)
this.map.on('move', (e) => {
marker.setLatLng(this.map.getCenter())
})
}
addPath() {
let style = {
color: 'red',
weight: 2,
opacity: 0.5,
dashArray: '2, 5',
smoothFactor: 1
}
let trackJson = JSON.parse(this.container.dataset.track)
if(trackJson){
L.geoJSON(trackJson, {style: style}).addTo(this.map)
} else if (this.currentMarker && this.previousMarker) {
L.polyline([this.previousMarker.getLatLng(), this.currentMarker.getLatLng()], style).addTo(this.map)
}
}
geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((pos) => {
this.map.setView([pos.coords.latitude, pos.coords.longitude], 13)
})
}
}
syncFormFields() {
const lat_field = document.getElementById("waypoint_lat")
const long_field = document.getElementById("waypoint_lng")
this.map.on('moveend', (e) => {
let center = this.map.getCenter()
lat_field.value = center.lat
long_field.value = center.lng
})
}
_getIcon(color) {
if (color === undefined) { return new L.Icon.Default() }
return new CustomIcon({
iconRetinaUrl: "marker-icon-" + color + "-2x.png",
iconUrl: "marker-icon-" + color + ".png"
})
}
}
class CustomIcon extends L.Icon.Default {
constructor(options) {
options.imagePath = "/images/map/"
super(options)
}
}
|
/* globals QUnit */
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import Ember from 'ember';
moduleForComponent('ui-progress', 'Integration | Component | ui progress', {
integration: true
});
test('It updates the bar width on progress change', function(assert) {
this.set('progress', 0);
this.render(hbs`{{ui-progress progress=progress}}`);
const startWidth = this.$('.bar').width();
QUnit.stop();
this.set('progress', 50);
Ember.run.later(() => {
const finishWidth = this.$('.bar').width();
assert.ok(startWidth !== finishWidth);
QUnit.start();
}, 100);
});
|
import './flipIcon.tpl.jade';
Template.flipIcon.onCreated(function () {
this.data.data.name = this.data.data.name || "";
})
Template.flipIcon.helpers({
name() {
return this.data.name.substr(0,3);
},
isActive() {
return this.data.state ? "selected" : "";
},
color() {
return this.data.color || 'blue';
},
flipable() {
return this.data.update ? "flipable" : "";
}
});
Template.flipIcon.events({
"click .icon, click .icon-bg"(event, template){
if (this.data.update) {
this.data.update(!this.data.state);
}
}
});
/* options:
- color: materializecss color class
- name: first two characters of name are displayed
- state: <boolean> - wether or not it's selected
- update: <function> - if set, the icon is flipable and will call update with
the new status (<boolean>)
It will NOT switch the state by itself - you have to do that!
*/
|
var gulp = require('gulp'),
mini = require('gulp-minify'),
clean = require('gulp-clean-css'),
concat = require('gulp-concat'),
sass = require('gulp-sass');
paths = {
'style': {
sass: './src/scss/*.scss',
output: './src/css'
}
};
gulp.task('sass', function () {
gulp.src(paths.style.sass)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(paths.style.output));
});
gulp.task('clean', function() {
return gulp.src('./src/css/*.css')
.pipe(clean({
compatibility: 'ie8'
}))
.pipe(gulp.dest('./dist/css'));
});
gulp.task('minify', function() {
return gulp.src('./src/js/*.js')
.pipe(mini({
ext: {
min: '.min.js'
},
mangle: true
}))
.pipe(gulp.dest('./dist/js'));
});
gulp.task('concat', function () {
gulp.src([
'./node_modules/mk-ui/dist/js/core.min.js',
'./node_modules/mk-ui/dist/js/selectmenu.min.js',
'./dist/js/mk-selectmenu.min.js',
'./dist/js/nav.min.js',
'./dist/js/form.min.js'
])
.pipe(concat('lib.js'))
.pipe(gulp.dest('./dist/js'))
});
|
#include "common/helpers.js"
#include "common/mysql_helper.js"
#include "cmon/io.h"
/**
* show full processlist
* Format: hostAndPort
* hostAndPort : * for all hosts or 10.10.10.10:3306
*/
function main(hostAndPort) {
if (hostAndPort == #N/A)
hostAndPort = "*";
var result={};
result["status"] = {};
result["status"]["global"]={};
var hosts = cluster::mySqlNodes();
for (idx = 0; idx < hosts.size(); ++idx) {
host = hosts[idx];
if(hostAndPort != "*" && !hostMatchesFilter(host,hostAndPort))
continue;
map = host.toMap();
connected = map["connected"];
if (connected) {
ret = getValueMap(host, "SHOW GLOBAL VARIABLES");
if (ret != false && ret.size() > 0)
{
result["status"]["global"][idx]={};
result["status"]["global"][idx]["reported_by"]=host.toString();
for (i=0; i<ret.size(); ++i)
{
result["status"]["global"][idx][i]={};
result["status"]["global"][idx][i]["variable_name"]=ret[i][0];
result["status"]["global"][idx][i]["value"]=ret[i][1];
}
}
}
}
exit(result);
}
|
'use strict';
angular.module('myApp.setup-2', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/setup-2', {
templateUrl: 'setup-2/setup-2.html',
controller: 'setup-2Ctrl'
});
}])
.controller('setup-2Ctrl', function($scope, $http) {
$scope.interests = [
{name:'study' , acvtive:'no'},
{name:'excersice' , acvtive:'no'},
{name:'jog' , acvtive:'no'},
{name:'gender' , acvtive:'no'},
{name:'party' , acvtive:'no'},
{name:'movie' , acvtive:'no'},
{name:'hotel' , acvtive:'no'},
{name:'breakfast' , acvtive:'no'},
{name:'lunch' , acvtive:'no'},
{name:'dinner' , acvtive:'no'}
];
$scope.submitSetupTwo = function(){
var postBody = {"username":$scope.user.name,
"password":$scope.user.password,
"address":$scope.user.address,
"cell":$scope.user.cell,
"gender":$scope.user.gender,
"dob":$scope.user.dob
};
var data = {};
var endPoint = "/endpoint/goes/here";
var status = {};
var headers = {};
var config = {};
$http.post(endPoint , postBody).success(function(data, status, headers, config)
{
}).error(function(data)
{
});
},
$scope.getInterests = function(){
var postBody = {};
var data = {};
var endPoint = "/endpoint/goes/here";
var status = {};
var headers = {};
var config = {};
$http.post(endPoint , postBody).success(function(data, status, headers, config)
{
}).error(function(data)
{
});
}
}); |
process.env.NODE_ENV = 'test';
process.env.DEBUG = 'carcass:*';
require('should');
var gulp = require('gulp');
var gutil = require('gulp-util');
var coffee = require('gulp-coffee');
var coffeelint = require('gulp-coffeelint');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var coverage = require('gulp-coverage');
// Files.
var src = 'src/**/*.coffee';
var tests = 'test/*.mocha.js';
// Compile coffee scripts.
gulp.task('coffee', function() {
return gulp.src(src)
.pipe(coffee({
bare: true
}).on('error', gutil.log))
.pipe(gulp.dest('./'));
});
// Lint (or hint as an alias).
gulp.task('lint', ['coffeelint', 'jshint']);
gulp.task('hint', ['coffeelint', 'jshint']);
gulp.task('coffeelint', function() {
return gulp.src(src)
.pipe(coffeelint())
.pipe(coffeelint.reporter());
});
gulp.task('jshint', function() {
return gulp.src(['Gulpfile.js', tests])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// Run tests.
gulp.task('mocha', ['coffee', 'jshint'], function() {
return gulp.src(tests)
.pipe(coverage.instrument({
pattern: ['classes/**/*.js'],
debugDirectory: 'test/debug'
}))
.pipe(mocha({
reporter: 'spec'
}))
.pipe(coverage.report({
outFile: 'test/coverage.html'
}));
});
gulp.task('default', ['coffeelint', 'jshint', 'coffee', 'mocha']);
|
'use strict';
/* jasmine specs for controllers go here */
describe('controllers', function(){
beforeEach(module('atruestory.controllers'));
it('should ....', inject(function() {
//spec body
}));
it('should ....', inject(function() {
//spec body
}));
});
|
(function() {
'use strict';
// POST RELEASE
// TODO(jelbourn): Demo that uses moment.js
// TODO(jelbourn): make sure this plays well with validation and ngMessages.
// TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
// TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
// TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
// TODO(jelbourn): input behavior (masking? auto-complete?)
// TODO(jelbourn): UTC mode
// TODO(jelbourn): RTL
angular.module('material.components.datepicker')
.directive('mdDatepicker', datePickerDirective);
/**
* @ngdoc directive
* @name mdDatepicker
* @module material.components.datepicker
*
* @param {Date} ng-model The component's model. Expects a JavaScript Date object.
* @param {expression=} ng-change Expression evaluated when the model value changes.
* @param {Date=} md-min-date Expression representing a min date (inclusive).
* @param {Date=} md-max-date Expression representing a max date (inclusive).
* @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
* @param {String=} md-placeholder The date input placeholder value.
* @param {boolean=} ng-disabled Whether the datepicker is disabled.
* @param {boolean=} ng-required Whether a value is required for the datepicker.
*
* @description
* `<md-datepicker>` is a component used to select a single date.
* For information on how to configure internationalization for the date picker,
* see `$mdDateLocaleProvider`.
*
* This component supports [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
* Supported attributes are:
* * `required`: whether a required date is not set.
* * `mindate`: whether the selected date is before the minimum allowed date.
* * `maxdate`: whether the selected date is after the maximum allowed date.
*
* @usage
* <hljs lang="html">
* <md-datepicker ng-model="birthday"></md-datepicker>
* </hljs>
*
*/
function datePickerDirective() {
return {
template:
// Buttons are not in the tab order because users can open the calendar via keyboard
// interaction on the text input, and multiple tab stops for one component (picker)
// may be confusing.
'<md-button class="md-datepicker-button md-icon-button" type="button" ' +
'tabindex="-1" aria-hidden="true" ' +
'ng-click="ctrl.openCalendarPane($event)">' +
'<md-icon class="md-datepicker-calendar-icon" md-svg-icon="md-calendar"></md-icon>' +
'</md-button>' +
'<div class="md-datepicker-input-container" ' +
'ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
'<input class="md-datepicker-input" aria-haspopup="true" ' +
'ng-focus="ctrl.setFocused(true)" ng-blur="ctrl.setFocused(false)">' +
'<md-button type="button" md-no-ink ' +
'class="md-datepicker-triangle-button md-icon-button" ' +
'ng-click="ctrl.openCalendarPane($event)" ' +
'aria-label="{{::ctrl.dateLocale.msgOpenCalendar}}">' +
'<div class="md-datepicker-expand-triangle"></div>' +
'</md-button>' +
'</div>' +
// This pane will be detached from here and re-attached to the document body.
'<div class="md-datepicker-calendar-pane md-whiteframe-z1">' +
'<div class="md-datepicker-input-mask">' +
'<div class="md-datepicker-input-mask-opaque"></div>' +
'</div>' +
'<div class="md-datepicker-calendar">' +
'<md-calendar role="dialog" aria-label="{{::ctrl.dateLocale.msgCalendar}}" ' +
'md-min-date="ctrl.minDate" md-max-date="ctrl.maxDate"' +
'md-date-filter="ctrl.dateFilter"' +
'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
'</md-calendar>' +
'</div>' +
'</div>',
require: ['ngModel', 'mdDatepicker', '?^mdInputContainer'],
scope: {
minDate: '=mdMinDate',
maxDate: '=mdMaxDate',
placeholder: '@mdPlaceholder',
dateFilter: '=mdDateFilter'
},
controller: DatePickerCtrl,
controllerAs: 'ctrl',
bindToController: true,
link: function(scope, element, attr, controllers) {
var ngModelCtrl = controllers[0];
var mdDatePickerCtrl = controllers[1];
var mdInputContainer = controllers[2];
if (mdInputContainer) {
throw Error('md-datepicker should not be placed inside md-input-container.');
}
mdDatePickerCtrl.configureNgModel(ngModelCtrl);
}
};
}
/** Additional offset for the input's `size` attribute, which is updated based on its content. */
var EXTRA_INPUT_SIZE = 3;
/** Class applied to the container if the date is invalid. */
var INVALID_CLASS = 'md-datepicker-invalid';
/** Default time in ms to debounce input event by. */
var DEFAULT_DEBOUNCE_INTERVAL = 500;
/**
* Height of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_HEIGHT = 368;
/**
* Width of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_WIDTH = 360;
/**
* Controller for md-datepicker.
*
* @ngInject @constructor
*/
function DatePickerCtrl($scope, $element, $attrs, $compile, $timeout, $window,
$mdConstant, $mdTheming, $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF) {
/** @final */
this.$compile = $compile;
/** @final */
this.$timeout = $timeout;
/** @final */
this.$window = $window;
/** @final */
this.dateLocale = $mdDateLocale;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.$mdConstant = $mdConstant;
/* @final */
this.$mdUtil = $mdUtil;
/** @final */
this.$$rAF = $$rAF;
/**
* The root document element. This is used for attaching a top-level click handler to
* close the calendar panel when a click outside said panel occurs. We use `documentElement`
* instead of body because, when scrolling is disabled, some browsers consider the body element
* to be completely off the screen and propagate events directly to the html element.
* @type {!angular.JQLite}
*/
this.documentElement = angular.element(document.documentElement);
/** @type {!angular.NgModelController} */
this.ngModelCtrl = null;
/** @type {HTMLInputElement} */
this.inputElement = $element[0].querySelector('input');
/** @final {!angular.JQLite} */
this.ngInputElement = angular.element(this.inputElement);
/** @type {HTMLElement} */
this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
/** @type {HTMLElement} Floating calendar pane. */
this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
/** @type {HTMLElement} Calendar icon button. */
this.calendarButton = $element[0].querySelector('.md-datepicker-button');
/**
* Element covering everything but the input in the top of the floating calendar pane.
* @type {HTMLElement}
*/
this.inputMask = $element[0].querySelector('.md-datepicker-input-mask-opaque');
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Attributes} */
this.$attrs = $attrs;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @type {Date} */
this.date = null;
/** @type {boolean} */
this.isFocused = false;
/** @type {boolean} */
this.isDisabled;
this.setDisabled($element[0].disabled || angular.isString($attrs['disabled']));
/** @type {boolean} Whether the date-picker's calendar pane is open. */
this.isCalendarOpen = false;
/**
* Element from which the calendar pane was opened. Keep track of this so that we can return
* focus to it when the pane is closed.
* @type {HTMLElement}
*/
this.calendarPaneOpenedFrom = null;
this.calendarPane.id = 'md-date-pane' + $mdUtil.nextUid();
$mdTheming($element);
/** Pre-bound click handler is saved so that the event listener can be removed. */
this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
/** Pre-bound resize handler so that the event listener can be removed. */
this.windowResizeHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
// Unless the user specifies so, the datepicker should not be a tab stop.
// This is necessary because ngAria might add a tabindex to anything with an ng-model
// (based on whether or not the user has turned that particular feature on/off).
if (!$attrs['tabindex']) {
$element.attr('tabindex', '-1');
}
this.installPropertyInterceptors();
this.attachChangeListeners();
this.attachInteractionListeners();
var self = this;
$scope.$on('$destroy', function() {
self.detachCalendarPane();
});
}
/**
* Sets up the controller's reference to ngModelController.
* @param {!angular.NgModelController} ngModelCtrl
*/
DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl) {
this.ngModelCtrl = ngModelCtrl;
var self = this;
ngModelCtrl.$render = function() {
var value = self.ngModelCtrl.$viewValue;
if (value && !(value instanceof Date)) {
throw Error('The ng-model for md-datepicker must be a Date instance. ' +
'Currently the model is a: ' + (typeof value));
}
self.date = value;
self.inputElement.value = self.dateLocale.formatDate(value);
self.resizeInputElement();
self.updateErrorState();
};
};
/**
* Attach event listeners for both the text input and the md-calendar.
* Events are used instead of ng-model so that updates don't infinitely update the other
* on a change. This should also be more performant than using a $watch.
*/
DatePickerCtrl.prototype.attachChangeListeners = function() {
var self = this;
self.$scope.$on('md-calendar-change', function(event, date) {
self.ngModelCtrl.$setViewValue(date);
self.date = date;
self.inputElement.value = self.dateLocale.formatDate(date);
self.closeCalendarPane();
self.resizeInputElement();
self.updateErrorState();
});
self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
// TODO(chenmike): Add ability for users to specify this interval.
self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
DEFAULT_DEBOUNCE_INTERVAL, self));
};
/** Attach event listeners for user interaction. */
DatePickerCtrl.prototype.attachInteractionListeners = function() {
var self = this;
var $scope = this.$scope;
var keyCodes = this.$mdConstant.KEY_CODE;
// Add event listener through angular so that we can triggerHandler in unit tests.
self.ngInputElement.on('keydown', function(event) {
if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
self.openCalendarPane(event);
$scope.$digest();
}
});
$scope.$on('md-calendar-close', function() {
self.closeCalendarPane();
});
};
/**
* Capture properties set to the date-picker and imperitively handle internal changes.
* This is done to avoid setting up additional $watches.
*/
DatePickerCtrl.prototype.installPropertyInterceptors = function() {
var self = this;
if (this.$attrs['ngDisabled']) {
// The expression is to be evaluated against the directive element's scope and not
// the directive's isolate scope.
var scope = this.$scope.$parent;
if (scope) {
scope.$watch(this.$attrs['ngDisabled'], function(isDisabled) {
self.setDisabled(isDisabled);
});
}
}
Object.defineProperty(this, 'placeholder', {
get: function() { return self.inputElement.placeholder; },
set: function(value) { self.inputElement.placeholder = value || ''; }
});
};
/**
* Sets whether the date-picker is disabled.
* @param {boolean} isDisabled
*/
DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
this.isDisabled = isDisabled;
this.inputElement.disabled = isDisabled;
this.calendarButton.disabled = isDisabled;
};
/**
* Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
* - mindate: whether the selected date is before the minimum date.
* - maxdate: whether the selected flag is after the maximum date.
* - filtered: whether the selected date is allowed by the custom filtering function.
* - valid: whether the entered text input is a valid date
*
* The 'required' flag is handled automatically by ngModel.
*
* @param {Date=} opt_date Date to check. If not given, defaults to the datepicker's model value.
*/
DatePickerCtrl.prototype.updateErrorState = function(opt_date) {
var date = opt_date || this.date;
// Clear any existing errors to get rid of anything that's no longer relevant.
this.clearErrorState();
if (this.dateUtil.isValidDate(date)) {
// Force all dates to midnight in order to ignore the time portion.
date = this.dateUtil.createDateAtMidnight(date);
if (this.dateUtil.isValidDate(this.minDate)) {
var minDate = this.dateUtil.createDateAtMidnight(this.minDate);
this.ngModelCtrl.$setValidity('mindate', date >= minDate);
}
if (this.dateUtil.isValidDate(this.maxDate)) {
var maxDate = this.dateUtil.createDateAtMidnight(this.maxDate);
this.ngModelCtrl.$setValidity('maxdate', date <= maxDate);
}
if (angular.isFunction(this.dateFilter)) {
this.ngModelCtrl.$setValidity('filtered', this.dateFilter(date));
}
} else {
// The date is seen as "not a valid date" if there is *something* set
// (i.e.., not null or undefined), but that something isn't a valid date.
this.ngModelCtrl.$setValidity('valid', date == null);
}
// TODO(jelbourn): Change this to classList.toggle when we stop using PhantomJS in unit tests
// because it doesn't conform to the DOMTokenList spec.
// See https://github.com/ariya/phantomjs/issues/12782.
if (!this.ngModelCtrl.$valid) {
this.inputContainer.classList.add(INVALID_CLASS);
}
};
/** Clears any error flags set by `updateErrorState`. */
DatePickerCtrl.prototype.clearErrorState = function() {
this.inputContainer.classList.remove(INVALID_CLASS);
['mindate', 'maxdate', 'filtered', 'valid'].forEach(function(field) {
this.ngModelCtrl.$setValidity(field, true);
}, this);
};
/** Resizes the input element based on the size of its content. */
DatePickerCtrl.prototype.resizeInputElement = function() {
this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
};
/**
* Sets the model value if the user input is a valid date.
* Adds an invalid class to the input element if not.
*/
DatePickerCtrl.prototype.handleInputEvent = function() {
var inputString = this.inputElement.value;
var parsedDate = inputString ? this.dateLocale.parseDate(inputString) : null;
this.dateUtil.setDateTimeToMidnight(parsedDate);
// An input string is valid if it is either empty (representing no date)
// or if it parses to a valid date that the user is allowed to select.
var isValidInput = inputString == '' || (
this.dateUtil.isValidDate(parsedDate) &&
this.dateLocale.isDateComplete(inputString) &&
this.isDateEnabled(parsedDate)
);
// The datepicker's model is only updated when there is a valid input.
if (isValidInput) {
this.ngModelCtrl.$setViewValue(parsedDate);
this.date = parsedDate;
}
this.updateErrorState(parsedDate);
};
/**
* Check whether date is in range and enabled
* @param {Date=} opt_date
* @return {boolean} Whether the date is enabled.
*/
DatePickerCtrl.prototype.isDateEnabled = function(opt_date) {
return this.dateUtil.isDateWithinRange(opt_date, this.minDate, this.maxDate) &&
(!angular.isFunction(this.dateFilter) || this.dateFilter(opt_date));
};
/** Position and attach the floating calendar to the document. */
DatePickerCtrl.prototype.attachCalendarPane = function() {
var calendarPane = this.calendarPane;
calendarPane.style.transform = '';
this.$element.addClass('md-datepicker-open');
var elementRect = this.inputContainer.getBoundingClientRect();
var bodyRect = document.body.getBoundingClientRect();
// Check to see if the calendar pane would go off the screen. If so, adjust position
// accordingly to keep it within the viewport.
var paneTop = elementRect.top - bodyRect.top;
var paneLeft = elementRect.left - bodyRect.left;
// If ng-material has disabled body scrolling (for example, if a dialog is open),
// then it's possible that the already-scrolled body has a negative top/left. In this case,
// we want to treat the "real" top as (0 - bodyRect.top). In a normal scrolling situation,
// though, the top of the viewport should just be the body's scroll position.
var viewportTop = (bodyRect.top < 0 && document.body.scrollTop == 0) ?
-bodyRect.top :
document.body.scrollTop;
var viewportLeft = (bodyRect.left < 0 && document.body.scrollLeft == 0) ?
-bodyRect.left :
document.body.scrollLeft;
var viewportBottom = viewportTop + this.$window.innerHeight;
var viewportRight = viewportLeft + this.$window.innerWidth;
// If the right edge of the pane would be off the screen and shifting it left by the
// difference would not go past the left edge of the screen. If the calendar pane is too
// big to fit on the screen at all, move it to the left of the screen and scale the entire
// element down to fit.
if (paneLeft + CALENDAR_PANE_WIDTH > viewportRight) {
if (viewportRight - CALENDAR_PANE_WIDTH > 0) {
paneLeft = viewportRight - CALENDAR_PANE_WIDTH;
} else {
paneLeft = viewportLeft;
var scale = this.$window.innerWidth / CALENDAR_PANE_WIDTH;
calendarPane.style.transform = 'scale(' + scale + ')';
}
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
// If the bottom edge of the pane would be off the screen and shifting it up by the
// difference would not go past the top edge of the screen.
if (paneTop + CALENDAR_PANE_HEIGHT > viewportBottom &&
viewportBottom - CALENDAR_PANE_HEIGHT > viewportTop) {
paneTop = viewportBottom - CALENDAR_PANE_HEIGHT;
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
calendarPane.style.left = paneLeft + 'px';
calendarPane.style.top = paneTop + 'px';
document.body.appendChild(calendarPane);
// The top of the calendar pane is a transparent box that shows the text input underneath.
// Since the pane is floating, though, the page underneath the pane *adjacent* to the input is
// also shown unless we cover it up. The inputMask does this by filling up the remaining space
// based on the width of the input.
this.inputMask.style.left = elementRect.width + 'px';
// Add CSS class after one frame to trigger open animation.
this.$$rAF(function() {
calendarPane.classList.add('md-pane-open');
});
};
/** Detach the floating calendar pane from the document. */
DatePickerCtrl.prototype.detachCalendarPane = function() {
this.$element.removeClass('md-datepicker-open');
this.calendarPane.classList.remove('md-pane-open');
this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
if (this.isCalendarOpen) {
this.$mdUtil.enableScrolling();
}
if (this.calendarPane.parentNode) {
// Use native DOM removal because we do not want any of the angular state of this element
// to be disposed.
this.calendarPane.parentNode.removeChild(this.calendarPane);
}
};
/**
* Open the floating calendar pane.
* @param {Event} event
*/
DatePickerCtrl.prototype.openCalendarPane = function(event) {
if (!this.isCalendarOpen && !this.isDisabled) {
this.isCalendarOpen = true;
this.calendarPaneOpenedFrom = event.target;
// Because the calendar pane is attached directly to the body, it is possible that the
// rest of the component (input, etc) is in a different scrolling container, such as
// an md-content. This means that, if the container is scrolled, the pane would remain
// stationary. To remedy this, we disable scrolling while the calendar pane is open, which
// also matches the native behavior for things like `<select>` on Mac and Windows.
this.$mdUtil.disableScrollAround(this.calendarPane);
this.attachCalendarPane();
this.focusCalendar();
// Attach click listener inside of a timeout because, if this open call was triggered by a
// click, we don't want it to be immediately propogated up to the body and handled.
var self = this;
this.$mdUtil.nextTick(function() {
// Use 'touchstart` in addition to click in order to work on iOS Safari, where click
// events aren't propogated under most circumstances.
// See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
self.documentElement.on('click touchstart', self.bodyClickHandler);
}, false);
window.addEventListener('resize', this.windowResizeHandler);
}
};
/** Close the floating calendar pane. */
DatePickerCtrl.prototype.closeCalendarPane = function() {
if (this.isCalendarOpen) {
this.detachCalendarPane();
this.isCalendarOpen = false;
this.calendarPaneOpenedFrom.focus();
this.calendarPaneOpenedFrom = null;
this.ngModelCtrl.$setTouched();
this.documentElement.off('click touchstart', this.bodyClickHandler);
window.removeEventListener('resize', this.windowResizeHandler);
}
};
/** Gets the controller instance for the calendar in the floating pane. */
DatePickerCtrl.prototype.getCalendarCtrl = function() {
return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
};
/** Focus the calendar in the floating pane. */
DatePickerCtrl.prototype.focusCalendar = function() {
// Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
var self = this;
this.$mdUtil.nextTick(function() {
self.getCalendarCtrl().focus();
}, false);
};
/**
* Sets whether the input is currently focused.
* @param {boolean} isFocused
*/
DatePickerCtrl.prototype.setFocused = function(isFocused) {
if (!isFocused) {
this.ngModelCtrl.$setTouched();
}
this.isFocused = isFocused;
};
/**
* Handles a click on the document body when the floating calendar pane is open.
* Closes the floating calendar pane if the click is not inside of it.
* @param {MouseEvent} event
*/
DatePickerCtrl.prototype.handleBodyClick = function(event) {
if (this.isCalendarOpen) {
// TODO(jelbourn): way want to also include the md-datepicker itself in this check.
var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
if (!isInCalendar) {
this.closeCalendarPane();
}
this.$scope.$digest();
}
};
})();
|
var _ = require('lodash');
var should = require('should');
var helper = require('../support/spec_helper');
var async = require('async');
var ORM = require('../.');
describe("Hook", function() {
var db = null;
var Person = null;
var triggeredHooks = {};
var getTimestamp; // Calling it 'getTime' causes strangeness.
getTimestamp = function () { return Date.now(); };
// this next lines are failing...
// if (process.hrtime) {
// getTimestamp = function () { return parseFloat(process.hrtime().join('.')); };
// } else {
// getTimestamp = function () { return Date.now(); };
// }
var checkHook = function (hook) {
triggeredHooks[hook] = false;
return function () {
triggeredHooks[hook] = getTimestamp();
};
};
var setup = function (hooks) {
if (typeof hooks == "undefined") {
hooks = {
afterCreate : checkHook("afterCreate"),
beforeCreate : checkHook("beforeCreate"),
afterSave : checkHook("afterSave"),
beforeSave : checkHook("beforeSave"),
beforeValidation : checkHook("beforeValidation"),
beforeRemove : checkHook("beforeRemove"),
afterRemove : checkHook("afterRemove")
};
}
return function (done) {
Person = db.define("person", {
name : String
}, {
hooks : hooks
});
Person.settings.set("instance.returnAllErrors", false);
return helper.dropSync(Person, done);
};
};
before(function (done) {
helper.connect(function (connection) {
db = connection;
return done();
});
});
after(function () {
return db.close();
});
// there are a lot of timeouts in this suite and Travis or other test runners can
// have hickups that could force this suite to timeout to the default value (2 secs)
this.timeout(30000);
describe("after Model creation", function () {
before(setup({}));
it("can be changed", function (done) {
var triggered = false;
Person.afterCreate(function () {
triggered = true;
});
Person.create([{ name: "John Doe" }], function () {
triggered.should.be.true;
return done();
});
});
it("can be removed", function (done) {
var triggered = false;
Person.afterCreate(function () {
triggered = true;
});
Person.create([{ name: "John Doe" }], function () {
triggered.should.be.true;
triggered = false;
Person.afterCreate(); // clears hook
Person.create([{ name: "Jane Doe" }], function () {
triggered.should.be.false;
return done();
});
});
});
});
describe("beforeCreate", function () {
before(setup());
it("should trigger before creating instance", function (done) {
Person.create([{ name: "John Doe" }], function () {
triggeredHooks.afterCreate.should.be.a("number");
triggeredHooks.beforeCreate.should.be.a("number");
triggeredHooks.beforeCreate.should.not.be.above(triggeredHooks.afterCreate);
return done();
});
});
it("should allow modification of instance", function (done) {
Person.beforeCreate(function (next) {
this.name = "Hook Worked";
next();
});
Person.create([{ }], function (err, people) {
should.not.exist(err);
should.exist(people);
should.equal(people.length, 1);
should.equal(people[0].name, "Hook Worked");
// garantee it was correctly saved on database
Person.one({ name: "Hook Worked" }, function (err, person) {
should.not.exist(err);
should.exist(person);
return done();
});
});
});
describe("when setting properties", function () {
before(setup({
beforeCreate : function () {
this.name = "Jane Doe";
}
}));
it("should not be discarded", function (done) {
Person.create([{ }], function (err, items) {
should.equal(err, null);
items.should.be.a("object");
items.should.have.property("length", 1);
items[0].name.should.equal("Jane Doe");
// ensure it was really saved
Person.find({ name: "Hook Worked" }, { cache: false }, 1, function (err, people) {
should.not.exist(err);
should(Array.isArray(people));
return done();
});
});
});
});
describe("if hook method has 1 argument", function () {
var beforeCreate = false;
before(setup({
beforeCreate : function (next) {
setTimeout(function () {
beforeCreate = true;
return next();
}.bind(this), 200);
}
}));
it("should wait for hook to finish", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function () {
beforeCreate.should.be.true;
return done();
});
});
describe("if hook triggers error", function () {
before(setup({
beforeCreate : function (next) {
setTimeout(function () {
return next(new Error('beforeCreate-error'));
}, 200);
}
}));
it("should trigger error", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function (err) {
err.should.be.a("object");
err.message.should.equal("beforeCreate-error");
return done();
});
});
});
});
});
describe("afterCreate", function () {
before(setup());
it("should trigger after creating instance", function (done) {
Person.create([{ name: "John Doe" }], function () {
triggeredHooks.afterCreate.should.be.a("number");
triggeredHooks.beforeCreate.should.be.a("number");
triggeredHooks.afterCreate.should.not.be.below(triggeredHooks.beforeCreate);
return done();
});
});
});
describe("beforeSave", function () {
before(setup());
it("should trigger before saving an instance", function (done) {
Person.create([{ name: "John Doe" }], function () {
triggeredHooks.afterSave.should.be.a("number");
triggeredHooks.beforeSave.should.be.a("number");
triggeredHooks.beforeSave.should.not.be.above(triggeredHooks.afterSave);
return done();
});
});
it("should allow modification of instance", function (done) {
Person.beforeSave(function () {
this.name = "Hook Worked";
});
Person.create([{ name: "John Doe" }], function (err, people) {
should.not.exist(err);
should.exist(people);
should.equal(people.length, 1);
should.equal(people[0].name, "Hook Worked");
// garantee it was correctly saved on database
Person.find({ name: "Hook Worked" }, { cache: false }, 1, function (err, people) {
should.not.exist(err);
should(Array.isArray(people));
return done();
});
});
});
describe("when setting properties", function () {
before(setup({
beforeSave : function () {
this.name = "Jane Doe";
}
}));
it("should not be discarded", function (done) {
Person.create([{ }], function (err, items) {
should.equal(err, null);
items.should.be.a("object");
items.should.have.property("length", 1);
items[0].name.should.equal("Jane Doe");
// ensure it was really saved
Person.get(items[0][Person.id], function (err, Item) {
should.equal(err, null);
Item.name.should.equal("Jane Doe");
return done();
});
});
});
});
describe("if hook method has 1 argument", function () {
var beforeSave = false;
before(setup({
beforeSave : function (next) {
setTimeout(function () {
beforeSave = true;
return next();
}.bind(this), 200);
}
}));
it("should wait for hook to finish", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function () {
beforeSave.should.be.true;
return done();
});
});
describe("if hook triggers error", function () {
before(setup({
beforeSave : function (next) {
if (this.name == "John Doe") {
return next();
}
setTimeout(function () {
return next(new Error('beforeSave-error'));
}, 200);
}
}));
it("should trigger error when creating", function (done) {
this.timeout(500);
Person.create([{ name: "Jane Doe" }], function (err) {
err.should.be.a("object");
err.message.should.equal("beforeSave-error");
return done();
});
});
it("should trigger error when saving", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function (err, John) {
should.equal(err, null);
John[0].name = "Jane Doe";
John[0].save(function (err) {
err.should.be.a("object");
err.message.should.equal("beforeSave-error");
return done();
});
});
});
});
});
});
describe("afterSave", function () {
before(setup());
it("should trigger after saving an instance", function (done) {
Person.create([{ name: "John Doe" }], function () {
triggeredHooks.afterSave.should.be.a("number");
triggeredHooks.beforeSave.should.be.a("number");
triggeredHooks.afterSave.should.not.be.below(triggeredHooks.beforeSave);
return done();
});
});
});
describe("beforeValidation", function () {
before(setup());
it("should trigger before instance validation", function (done) {
Person.create([{ name: "John Doe" }], function () {
triggeredHooks.beforeValidation.should.be.a("number");
triggeredHooks.beforeCreate.should.be.a("number");
triggeredHooks.beforeSave.should.be.a("number");
triggeredHooks.beforeValidation.should.not.be.above(triggeredHooks.beforeCreate);
triggeredHooks.beforeValidation.should.not.be.above(triggeredHooks.beforeSave);
return done();
});
});
it("should allow modification of instance", function (done) {
Person.beforeValidation(function () {
this.name = "Hook Worked";
});
Person.create([{ name: "John Doe" }], function (err, people) {
should.not.exist(err);
should.exist(people);
should.equal(people.length, 1);
should.equal(people[0].name, "Hook Worked");
done();
});
});
describe("if hook method has 1 argument", function () {
var beforeValidation = false;
this.timeout(500);
before(setup({
beforeValidation : function (next) {
setTimeout(function () {
beforeValidation = true;
if (!this.name) return next("Name is missing");
return next();
}.bind(this), 200);
}
}));
beforeEach(function () {
beforeValidation = false;
});
it("should wait for hook to finish", function (done) {
Person.create([{ name: "John Doe" }], function () {
beforeValidation.should.be.true;
return done();
});
});
it("should trigger error if hook passes an error", function (done) {
Person.create([{ name: "" }], function (err) {
beforeValidation.should.be.true;
err.should.equal("Name is missing");
return done();
});
});
it("should trigger when calling #validate", function (done) {
var person = new Person();
person.validate(function (err, validationErrors) {
beforeValidation.should.be.true;
return done();
});
});
});
});
describe("afterLoad", function () {
var afterLoad = false;
before(setup({
afterLoad: function () {
afterLoad = true;
}
}));
it("should trigger when defining a model", function (done) {
var John = new Person({ name: "John" });
afterLoad.should.be.true;
return done();
});
describe("if hook method has 1 argument", function () {
var afterLoad = false;
before(setup({
afterLoad : function (next) {
setTimeout(function () {
afterLoad = true;
return next();
}.bind(this), 200);
}
}));
it("should wait for hook to finish", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function (err, items) {
afterLoad.should.be.true;
return done();
});
});
describe("if hook returns an error", function () {
before(setup({
afterLoad : function (next) {
return next(new Error("AFTERLOAD_FAIL"));
}
}));
it("should return error", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function (err, items) {
err.should.exist;
err.message.should.equal("AFTERLOAD_FAIL");
return done();
});
});
});
});
});
describe("afterAutoFetch", function () {
var afterAutoFetch = false;
before(setup({
afterAutoFetch: function () {
afterAutoFetch = true;
}
}));
it("should trigger when defining a model", function (done) {
var John = new Person({ name: "John" });
afterAutoFetch.should.be.true;
return done();
});
describe("if hook method has 1 argument", function () {
var afterAutoFetch = false;
before(setup({
afterAutoFetch : function (next) {
setTimeout(function () {
afterAutoFetch = true;
return next();
}.bind(this), 200);
}
}));
it("should wait for hook to finish", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function (err, items) {
afterAutoFetch.should.be.true;
return done();
});
});
describe("if hook returns an error", function () {
before(setup({
afterAutoFetch : function (next) {
return next(new Error("AFTERAUTOFETCH_FAIL"));
}
}));
it("should return error", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function (err, items) {
err.should.exist;
err.message.should.equal("AFTERAUTOFETCH_FAIL");
return done();
});
});
});
});
});
describe("beforeRemove", function () {
before(setup());
it("should trigger before removing an instance", function (done) {
Person.create([{ name: "John Doe" }], function (err, items) {
items[0].remove(function () {
triggeredHooks.afterRemove.should.be.a("number");
triggeredHooks.beforeRemove.should.be.a("number");
triggeredHooks.beforeRemove.should.not.be.above(triggeredHooks.afterRemove);
return done();
});
});
});
describe("if hook method has 1 argument", function () {
var beforeRemove = false;
before(setup({
beforeRemove : function (next) {
setTimeout(function () {
beforeRemove = true;
return next();
}.bind(this), 200);
}
}));
it("should wait for hook to finish", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function (err, items) {
items[0].remove(function () {
beforeRemove.should.be.true;
return done();
});
});
});
describe("if hook triggers error", function () {
before(setup({
beforeRemove : function (next) {
setTimeout(function () {
return next(new Error('beforeRemove-error'));
}, 200);
}
}));
it("should trigger error", function (done) {
this.timeout(500);
Person.create([{ name: "John Doe" }], function (err, items) {
items[0].remove(function (err) {
err.should.be.a("object");
err.message.should.equal("beforeRemove-error");
return done();
});
});
});
});
});
});
describe("afterRemove", function () {
before(setup());
it("should trigger after removing an instance", function (done) {
Person.create([{ name: "John Doe" }], function (err, items) {
items[0].remove(function () {
triggeredHooks.afterRemove.should.be.a("number");
triggeredHooks.beforeRemove.should.be.a("number");
triggeredHooks.afterRemove.should.not.be.below(triggeredHooks.beforeRemove);
return done();
});
});
});
});
describe("if model has autoSave", function () {
before(function (done) {
Person = db.define("person", {
name : String,
surname : String
}, {
autoSave : true,
hooks : {
afterSave : checkHook("afterSave")
}
});
Person.settings.set("instance.returnAllErrors", false);
return helper.dropSync(Person, done);
});
it("should trigger for single property changes", function (done) {
Person.create({ name : "John", surname : "Doe" }, function (err, John) {
should.equal(err, null);
triggeredHooks.afterSave.should.be.a("number");
triggeredHooks.afterSave = false;
John.surname = "Dean";
setTimeout(function () {
triggeredHooks.afterSave.should.be.a("number");
return done();
}, 200);
});
});
});
describe("instance modifications", function () {
before(setup({
beforeValidation: function () {
should.equal(this.name, "John Doe");
this.name = "beforeValidation";
},
beforeCreate: function () {
should.equal(this.name, "beforeValidation");
this.name = "beforeCreate";
},
beforeSave: function () {
should.equal(this.name, "beforeCreate");
this.name = "beforeSave";
}
}));
it("should propagate down hooks", function (done) {
Person.create([{ name: "John Doe" }], function (err, people) {
should.not.exist(err);
should.exist(people);
should.equal(people.length, 1);
should.equal(people[0].name, "beforeSave");
done();
});
});
});
});
|
'use strict';
module.exports = {
db: 'mongodb://localhost/mychat-dev',
app: {
title: 'myChat - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
}
}; |
'use strict';
module.exports = {
audio: [
{
name: 'soundtrack',
file: '/assets/sound/themeBTTF.mp3'
},
{
name: 'ringHit',
file: '/assets/sound/ringHit.wav'
},
{
name: 'bufferconcert',
file: '/assets/sound/concert-crowd.ogg'
}
]
};
|
var Module;
if (typeof Module === 'undefined') Module = eval('(function() { try { return Module || {} } catch(e) { return {} } })()');
if (!Module.expectedDataFileDownloads) {
Module.expectedDataFileDownloads = 0;
Module.finishedDataFileDownloads = 0;
}
Module.expectedDataFileDownloads++;
(function() {
var decrunchWorker = new Worker('crunch-worker.js');
var decrunchCallbacks = [];
decrunchWorker.onmessage = function(msg) {
decrunchCallbacks[msg.data.callbackID](msg.data.data);
console.log('decrunched ' + msg.data.filename + ' in ' + msg.data.time + ' ms, ' + msg.data.data.length + ' bytes');
decrunchCallbacks[msg.data.callbackID] = null;
};
function requestDecrunch(filename, data, callback) {
decrunchWorker.postMessage({
filename: filename,
data: new Uint8Array(data),
callbackID: decrunchCallbacks.length
});
decrunchCallbacks.push(callback);
}
var PACKAGE_PATH;
if (typeof window === 'object') {
PACKAGE_PATH = window['encodeURIComponent'](window.location.pathname.toString().substring(0, window.location.pathname.toString().lastIndexOf('/')) + '/');
} else {
// worker
PACKAGE_PATH = encodeURIComponent(location.pathname.toString().substring(0, location.pathname.toString().lastIndexOf('/')) + '/');
}
var PACKAGE_NAME = 'base.data';
var REMOTE_PACKAGE_BASE = 'base.data';
if (typeof Module['locateFilePackage'] === 'function' && !Module['locateFile']) {
Module['locateFile'] = Module['locateFilePackage'];
Module.printErr('warning: you defined Module.locateFilePackage, that has been renamed to Module.locateFile (using your locateFilePackage for now)');
}
var REMOTE_PACKAGE_NAME = typeof Module['locateFile'] === 'function' ?
Module['locateFile'](REMOTE_PACKAGE_BASE) :
((Module['filePackagePrefixURL'] || '') + REMOTE_PACKAGE_BASE);
var REMOTE_PACKAGE_SIZE = 6986781;
var PACKAGE_UUID = '174de9b6-2e82-4e2c-841a-d60bb4b89b9c';
function fetchRemotePackage(packageName, packageSize, callback, errback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', packageName, true);
xhr.responseType = 'arraybuffer';
xhr.onprogress = function(event) {
var url = packageName;
var size = packageSize;
if (event.total) size = event.total;
if (event.loaded) {
if (!xhr.addedTotal) {
xhr.addedTotal = true;
if (!Module.dataFileDownloads) Module.dataFileDownloads = {};
Module.dataFileDownloads[url] = {
loaded: event.loaded,
total: size
};
} else {
Module.dataFileDownloads[url].loaded = event.loaded;
}
var total = 0;
var loaded = 0;
var num = 0;
for (var download in Module.dataFileDownloads) {
var data = Module.dataFileDownloads[download];
total += data.total;
loaded += data.loaded;
num++;
}
total = Math.ceil(total * Module.expectedDataFileDownloads/num);
if (Module['setStatus']) Module['setStatus']('Downloading data... (' + loaded + '/' + total + ')');
} else if (!Module.dataFileDownloads) {
if (Module['setStatus']) Module['setStatus']('Downloading data...');
}
};
xhr.onload = function(event) {
var packageData = xhr.response;
callback(packageData);
};
xhr.send(null);
};
function handleError(error) {
console.error('package error:', error);
};
var fetched = null, fetchedCallback = null;
fetchRemotePackage(REMOTE_PACKAGE_NAME, REMOTE_PACKAGE_SIZE, function(data) {
if (fetchedCallback) {
fetchedCallback(data);
fetchedCallback = null;
} else {
fetched = data;
}
}, handleError);
function runWithFS() {
function assert(check, msg) {
if (!check) throw msg + new Error().stack;
}
Module['FS_createPath']('/', 'data', true, true);
Module['FS_createPath']('/', 'packages', true, true);
Module['FS_createPath']('/packages', 'textures', true, true);
Module['FS_createPath']('/packages', 'fonts', true, true);
Module['FS_createPath']('/packages', 'icons', true, true);
Module['FS_createPath']('/packages', 'particles', true, true);
Module['FS_createPath']('/packages', 'sounds', true, true);
Module['FS_createPath']('/packages/sounds', 'aard', true, true);
Module['FS_createPath']('/packages/sounds', 'q009', true, true);
Module['FS_createPath']('/packages/sounds', 'yo_frankie', true, true);
Module['FS_createPath']('/packages', 'gk', true, true);
Module['FS_createPath']('/packages/gk', 'lava', true, true);
Module['FS_createPath']('/packages', 'caustics', true, true);
Module['FS_createPath']('/packages', 'models', true, true);
Module['FS_createPath']('/packages/models', 'debris', true, true);
Module['FS_createPath']('/packages/models', 'projectiles', true, true);
Module['FS_createPath']('/packages/models/projectiles', 'grenade', true, true);
Module['FS_createPath']('/packages/models/projectiles', 'rocket', true, true);
Module['FS_createPath']('/packages', 'brushes', true, true);
Module['FS_createPath']('/packages', 'hud', true, true);
function DataRequest(start, end, crunched, audio) {
this.start = start;
this.end = end;
this.crunched = crunched;
this.audio = audio;
}
DataRequest.prototype = {
requests: {},
open: function(mode, name) {
this.name = name;
this.requests[name] = this;
Module['addRunDependency']('fp ' + this.name);
},
send: function() {},
onload: function() {
var byteArray = this.byteArray.subarray(this.start, this.end);
if (this.crunched) {
var ddsHeader = byteArray.subarray(0, 128);
var that = this;
requestDecrunch(this.name, byteArray.subarray(128), function(ddsData) {
byteArray = new Uint8Array(ddsHeader.length + ddsData.length);
byteArray.set(ddsHeader, 0);
byteArray.set(ddsData, 128);
that.finish(byteArray);
});
} else {
this.finish(byteArray);
}
},
finish: function(byteArray) {
var that = this;
Module['FS_createPreloadedFile'](this.name, null, byteArray, true, true, function() {
Module['removeRunDependency']('fp ' + that.name);
}, function() {
if (that.audio) {
Module['removeRunDependency']('fp ' + that.name); // workaround for chromium bug 124926 (still no audio with this, but at least we don't hang)
} else {
Module.printErr('Preloading file ' + that.name + ' failed');
}
}, false, true); // canOwn this data in the filesystem, it is a slide into the heap that will never change
this.requests[this.name] = null;
},
};
new DataRequest(0, 47850, 0, 0).open('GET', '/data/menus.cfg');
new DataRequest(47850, 52734, 0, 0).open('GET', '/data/guioverlay.png');
new DataRequest(52734, 66286, 0, 0).open('GET', '/data/background_decal.png');
new DataRequest(66286, 69197, 0, 0).open('GET', '/data/sounds.cfg');
new DataRequest(69197, 70419, 0, 0).open('GET', '/data/default_map_settings.cfg');
new DataRequest(70419, 73702, 0, 0).open('GET', '/data/hit.png');
new DataRequest(73702, 73838, 0, 0).open('GET', '/data/default_map_models.cfg');
new DataRequest(73838, 77121, 0, 0).open('GET', '/data/crosshair.png');
new DataRequest(77121, 80433, 0, 0).open('GET', '/data/teammate.png');
new DataRequest(80433, 97995, 0, 0).open('GET', '/data/background.png');
new DataRequest(97995, 187625, 0, 0).open('GET', '/data/stdshader.cfg');
new DataRequest(187625, 191871, 0, 0).open('GET', '/data/guiskin.png');
new DataRequest(191871, 322077, 0, 0).open('GET', '/data/logo.png');
new DataRequest(322077, 324909, 0, 0).open('GET', '/data/guislider.png');
new DataRequest(324909, 327316, 0, 0).open('GET', '/data/keymap.cfg');
new DataRequest(327316, 332200, 0, 0).open('GET', '/data/mapshot_frame.png');
new DataRequest(332200, 336131, 0, 0).open('GET', '/data/guicursor.png');
new DataRequest(336131, 339114, 0, 0).open('GET', '/data/loading_bar.png');
new DataRequest(339114, 423601, 0, 0).open('GET', '/data/glsl.cfg');
new DataRequest(423601, 427282, 0, 0).open('GET', '/data/loading_frame.png');
new DataRequest(427282, 428295, 0, 0).open('GET', '/data/stdlib.cfg');
new DataRequest(428295, 432061, 0, 0).open('GET', '/data/game_fps.cfg');
new DataRequest(432061, 432220, 0, 0).open('GET', '/data/background_detail.png');
new DataRequest(432220, 440724, 0, 0).open('GET', '/data/stdedit.cfg');
new DataRequest(440724, 440796, 0, 0).open('GET', '/data/font.cfg');
new DataRequest(440796, 446313, 0, 0).open('GET', '/data/brush.cfg');
new DataRequest(446313, 454478, 0, 0).open('GET', '/data/game_rpg.cfg');
new DataRequest(454478, 461695, 0, 0).open('GET', '/data/defaults.cfg');
new DataRequest(461695, 617698, 0, 0).open('GET', '/packages/textures/water.jpg');
new DataRequest(617698, 872871, 0, 0).open('GET', '/packages/textures/waterdudv.jpg');
new DataRequest(872871, 875907, 0, 0).open('GET', '/packages/textures/notexture.png');
new DataRequest(875907, 1053469, 0, 0).open('GET', '/packages/textures/waterfalln.jpg');
new DataRequest(1053469, 1090663, 0, 0).open('GET', '/packages/textures/waterfall.jpg');
new DataRequest(1090663, 1091334, 0, 0).open('GET', '/packages/textures/readme.txt');
new DataRequest(1091334, 1333504, 0, 0).open('GET', '/packages/textures/waterfalldudv.jpg');
new DataRequest(1333504, 1683327, 0, 0).open('GET', '/packages/textures/watern.jpg');
new DataRequest(1683327, 1769451, 0, 0).open('GET', '/packages/fonts/font.png');
new DataRequest(1769451, 1771693, 0, 0).open('GET', '/packages/fonts/default.cfg');
new DataRequest(1771693, 1776418, 0, 0).open('GET', '/packages/fonts/font_readme.txt');
new DataRequest(1776418, 1789796, 0, 0).open('GET', '/packages/icons/info.jpg');
new DataRequest(1789796, 1801906, 0, 0).open('GET', '/packages/icons/arrow_fw.jpg');
new DataRequest(1801906, 1817040, 0, 0).open('GET', '/packages/icons/frankie.jpg');
new DataRequest(1817040, 1835716, 0, 0).open('GET', '/packages/icons/server.jpg');
new DataRequest(1835716, 1848996, 0, 0).open('GET', '/packages/icons/radio_on.jpg');
new DataRequest(1848996, 1867199, 0, 0).open('GET', '/packages/icons/checkbox_on.jpg');
new DataRequest(1867199, 1880094, 0, 0).open('GET', '/packages/icons/cube.jpg');
new DataRequest(1880094, 1893151, 0, 0).open('GET', '/packages/icons/exit.jpg');
new DataRequest(1893151, 1909591, 0, 0).open('GET', '/packages/icons/checkbox_off.jpg');
new DataRequest(1909591, 1922659, 0, 0).open('GET', '/packages/icons/chat.jpg');
new DataRequest(1922659, 1926748, 0, 0).open('GET', '/packages/icons/menu.png');
new DataRequest(1926748, 1926845, 0, 0).open('GET', '/packages/icons/readme.txt');
new DataRequest(1926845, 1940341, 0, 0).open('GET', '/packages/icons/snoutx10k.jpg');
new DataRequest(1940341, 1959069, 0, 0).open('GET', '/packages/icons/radio_off.jpg');
new DataRequest(1959069, 1970731, 0, 0).open('GET', '/packages/icons/arrow_bw.jpg');
new DataRequest(1970731, 1989038, 0, 0).open('GET', '/packages/icons/action.jpg');
new DataRequest(1989038, 2007030, 0, 0).open('GET', '/packages/icons/menu.jpg');
new DataRequest(2007030, 2020534, 0, 0).open('GET', '/packages/icons/hand.jpg');
new DataRequest(2020534, 2078396, 0, 0).open('GET', '/packages/particles/lightning.jpg');
new DataRequest(2078396, 2082908, 0, 0).open('GET', '/packages/particles/smoke.png');
new DataRequest(2082908, 2084713, 0, 0).open('GET', '/packages/particles/spark.png');
new DataRequest(2084713, 2146865, 0, 0).open('GET', '/packages/particles/ball2.png');
new DataRequest(2146865, 2166370, 0, 0).open('GET', '/packages/particles/circle.png');
new DataRequest(2166370, 2185392, 0, 0).open('GET', '/packages/particles/muzzleflash2.jpg');
new DataRequest(2185392, 2201018, 0, 0).open('GET', '/packages/particles/blood.png');
new DataRequest(2201018, 2208433, 0, 0).open('GET', '/packages/particles/steam.png');
new DataRequest(2208433, 2941912, 0, 0).open('GET', '/packages/particles/explosion.png');
new DataRequest(2941912, 2942156, 0, 0).open('GET', '/packages/particles/readme.txt');
new DataRequest(2942156, 2945054, 0, 0).open('GET', '/packages/particles/base.png');
new DataRequest(2945054, 2947321, 0, 0).open('GET', '/packages/particles/blob.png');
new DataRequest(2947321, 3004485, 0, 0).open('GET', '/packages/particles/bullet.png');
new DataRequest(3004485, 3024386, 0, 0).open('GET', '/packages/particles/muzzleflash1.jpg');
new DataRequest(3024386, 3094578, 0, 0).open('GET', '/packages/particles/flames.png');
new DataRequest(3094578, 3094823, 0, 0).open('GET', '/packages/particles/readme.txt~');
new DataRequest(3094823, 3095684, 0, 0).open('GET', '/packages/particles/flare.jpg');
new DataRequest(3095684, 3115822, 0, 0).open('GET', '/packages/particles/muzzleflash3.jpg');
new DataRequest(3115822, 3441722, 0, 0).open('GET', '/packages/particles/lensflares.png');
new DataRequest(3441722, 3481558, 0, 0).open('GET', '/packages/particles/scorch.png');
new DataRequest(3481558, 3535490, 0, 0).open('GET', '/packages/particles/ball1.png');
new DataRequest(3535490, 3560960, 0, 1).open('GET', '/packages/sounds/aard/pain1.wav');
new DataRequest(3560960, 3570674, 0, 1).open('GET', '/packages/sounds/aard/die1.wav');
new DataRequest(3570674, 3582036, 0, 1).open('GET', '/packages/sounds/aard/land.wav');
new DataRequest(3582036, 3585730, 0, 1).open('GET', '/packages/sounds/aard/grunt2.wav');
new DataRequest(3585730, 3587434, 0, 1).open('GET', '/packages/sounds/aard/tak.wav');
new DataRequest(3587434, 3594080, 0, 1).open('GET', '/packages/sounds/aard/weapload.wav');
new DataRequest(3594080, 3605486, 0, 1).open('GET', '/packages/sounds/aard/grunt1.wav');
new DataRequest(3605486, 3614836, 0, 1).open('GET', '/packages/sounds/aard/pain3.wav');
new DataRequest(3614836, 3624246, 0, 1).open('GET', '/packages/sounds/aard/pain2.wav');
new DataRequest(3624246, 3634898, 0, 1).open('GET', '/packages/sounds/aard/die2.wav');
new DataRequest(3634898, 3642858, 0, 1).open('GET', '/packages/sounds/aard/pain5.wav');
new DataRequest(3642858, 3650838, 0, 1).open('GET', '/packages/sounds/aard/pain4.wav');
new DataRequest(3650838, 3662700, 0, 1).open('GET', '/packages/sounds/aard/bang.wav');
new DataRequest(3662700, 3675014, 0, 1).open('GET', '/packages/sounds/aard/itempick.wav');
new DataRequest(3675014, 3682680, 0, 1).open('GET', '/packages/sounds/aard/pain6.wav');
new DataRequest(3682680, 3686738, 0, 1).open('GET', '/packages/sounds/aard/outofammo.wav');
new DataRequest(3686738, 3690870, 0, 1).open('GET', '/packages/sounds/aard/jump.wav');
new DataRequest(3690870, 3718757, 0, 1).open('GET', '/packages/sounds/q009/minigun.ogg');
new DataRequest(3718757, 3843155, 0, 1).open('GET', '/packages/sounds/q009/shotgun3.ogg');
new DataRequest(3843155, 3901854, 0, 1).open('GET', '/packages/sounds/q009/rlauncher2.ogg');
new DataRequest(3901854, 4024537, 0, 1).open('GET', '/packages/sounds/q009/rifle3.ogg');
new DataRequest(4024537, 4050710, 0, 1).open('GET', '/packages/sounds/q009/teleport.ogg');
new DataRequest(4050710, 4184496, 0, 1).open('GET', '/packages/sounds/q009/ren.ogg');
new DataRequest(4184496, 4207824, 0, 1).open('GET', '/packages/sounds/q009/minigun2.ogg');
new DataRequest(4207824, 4226715, 0, 1).open('GET', '/packages/sounds/q009/jumppad.ogg');
new DataRequest(4226715, 4260402, 0, 1).open('GET', '/packages/sounds/q009/glauncher.ogg');
new DataRequest(4260402, 4280845, 0, 1).open('GET', '/packages/sounds/q009/weapswitch.ogg');
new DataRequest(4280845, 4310827, 0, 1).open('GET', '/packages/sounds/q009/explosion.ogg');
new DataRequest(4310827, 4435047, 0, 1).open('GET', '/packages/sounds/q009/rifle2.ogg');
new DataRequest(4435047, 4560127, 0, 1).open('GET', '/packages/sounds/q009/shotgun.ogg');
new DataRequest(4560127, 4586383, 0, 1).open('GET', '/packages/sounds/q009/minigun3.ogg');
new DataRequest(4586383, 4689449, 0, 1).open('GET', '/packages/sounds/q009/ren2.ogg');
new DataRequest(4689449, 4818486, 0, 1).open('GET', '/packages/sounds/q009/rifle.ogg');
new DataRequest(4818486, 4934925, 0, 1).open('GET', '/packages/sounds/q009/ren3.ogg');
new DataRequest(4934925, 4992862, 0, 1).open('GET', '/packages/sounds/q009/rlauncher.ogg');
new DataRequest(4992862, 5025484, 0, 1).open('GET', '/packages/sounds/q009/quaddamage_out.ogg');
new DataRequest(5025484, 5043359, 0, 1).open('GET', '/packages/sounds/q009/outofammo.ogg');
new DataRequest(5043359, 5169461, 0, 1).open('GET', '/packages/sounds/q009/shotgun2.ogg');
new DataRequest(5169461, 5196361, 0, 1).open('GET', '/packages/sounds/q009/pistol3.ogg');
new DataRequest(5196361, 5215801, 0, 0).open('GET', '/packages/sounds/q009/license.txt');
new DataRequest(5215801, 5217117, 0, 0).open('GET', '/packages/sounds/q009/readme.txt');
new DataRequest(5217117, 5244825, 0, 1).open('GET', '/packages/sounds/q009/quaddamage_shoot.ogg');
new DataRequest(5244825, 5302470, 0, 1).open('GET', '/packages/sounds/q009/rlauncher3.ogg');
new DataRequest(5302470, 5330852, 0, 1).open('GET', '/packages/sounds/q009/pistol2.ogg');
new DataRequest(5330852, 5366294, 0, 1).open('GET', '/packages/sounds/q009/glauncher2.ogg');
new DataRequest(5366294, 5399522, 0, 1).open('GET', '/packages/sounds/q009/glauncher3.ogg');
new DataRequest(5399522, 5427916, 0, 1).open('GET', '/packages/sounds/q009/pistol.ogg');
new DataRequest(5427916, 5447525, 0, 1).open('GET', '/packages/sounds/yo_frankie/amb_waterdrip_2.ogg');
new DataRequest(5447525, 5448155, 0, 0).open('GET', '/packages/sounds/yo_frankie/readme.txt');
new DataRequest(5448155, 5455568, 0, 1).open('GET', '/packages/sounds/yo_frankie/sfx_interact.ogg');
new DataRequest(5455568, 5479473, 0, 1).open('GET', '/packages/sounds/yo_frankie/watersplash2.ogg');
new DataRequest(5479473, 5536305, 1, 0).open('GET', '/packages/gk/lava/lava_cc.dds');
new DataRequest(5536305, 5652394, 1, 0).open('GET', '/packages/gk/lava/lava_nm.dds');
new DataRequest(5652394, 5676556, 0, 0).open('GET', '/packages/caustics/caust08.png');
new DataRequest(5676556, 5701035, 0, 0).open('GET', '/packages/caustics/caust17.png');
new DataRequest(5701035, 5726221, 0, 0).open('GET', '/packages/caustics/caust13.png');
new DataRequest(5726221, 5749545, 0, 0).open('GET', '/packages/caustics/caust06.png');
new DataRequest(5749545, 5773120, 0, 0).open('GET', '/packages/caustics/caust03.png');
new DataRequest(5773120, 5795990, 0, 0).open('GET', '/packages/caustics/caust05.png');
new DataRequest(5795990, 5820169, 0, 0).open('GET', '/packages/caustics/caust19.png');
new DataRequest(5820169, 5843444, 0, 0).open('GET', '/packages/caustics/caust23.png');
new DataRequest(5843444, 5866613, 0, 0).open('GET', '/packages/caustics/caust24.png');
new DataRequest(5866613, 5889819, 0, 0).open('GET', '/packages/caustics/caust25.png');
new DataRequest(5889819, 5913320, 0, 0).open('GET', '/packages/caustics/caust28.png');
new DataRequest(5913320, 5936874, 0, 0).open('GET', '/packages/caustics/caust26.png');
new DataRequest(5936874, 5961615, 0, 0).open('GET', '/packages/caustics/caust12.png');
new DataRequest(5961615, 5984813, 0, 0).open('GET', '/packages/caustics/caust04.png');
new DataRequest(5984813, 6008680, 0, 0).open('GET', '/packages/caustics/caust07.png');
new DataRequest(6008680, 6033223, 0, 0).open('GET', '/packages/caustics/caust31.png');
new DataRequest(6033223, 6057672, 0, 0).open('GET', '/packages/caustics/caust15.png');
new DataRequest(6057672, 6082724, 0, 0).open('GET', '/packages/caustics/caust14.png');
new DataRequest(6082724, 6106474, 0, 0).open('GET', '/packages/caustics/caust29.png');
new DataRequest(6106474, 6130638, 0, 0).open('GET', '/packages/caustics/caust11.png');
new DataRequest(6130638, 6154892, 0, 0).open('GET', '/packages/caustics/caust30.png');
new DataRequest(6154892, 6179433, 0, 0).open('GET', '/packages/caustics/caust18.png');
new DataRequest(6179433, 6179491, 0, 0).open('GET', '/packages/caustics/readme.txt');
new DataRequest(6179491, 6203374, 0, 0).open('GET', '/packages/caustics/caust09.png');
new DataRequest(6203374, 6227199, 0, 0).open('GET', '/packages/caustics/caust10.png');
new DataRequest(6227199, 6250643, 0, 0).open('GET', '/packages/caustics/caust22.png');
new DataRequest(6250643, 6275135, 0, 0).open('GET', '/packages/caustics/caust01.png');
new DataRequest(6275135, 6299654, 0, 0).open('GET', '/packages/caustics/caust00.png');
new DataRequest(6299654, 6323760, 0, 0).open('GET', '/packages/caustics/caust20.png');
new DataRequest(6323760, 6348117, 0, 0).open('GET', '/packages/caustics/caust16.png');
new DataRequest(6348117, 6371761, 0, 0).open('GET', '/packages/caustics/caust27.png');
new DataRequest(6371761, 6395877, 0, 0).open('GET', '/packages/caustics/caust02.png');
new DataRequest(6395877, 6419515, 0, 0).open('GET', '/packages/caustics/caust21.png');
new DataRequest(6419515, 6434291, 0, 0).open('GET', '/packages/models/debris/tris.md2');
new DataRequest(6434291, 6434534, 0, 0).open('GET', '/packages/models/debris/md2.cfg');
new DataRequest(6434534, 6626360, 0, 0).open('GET', '/packages/models/debris/skin.png');
new DataRequest(6626360, 6626498, 0, 0).open('GET', '/packages/models/projectiles/grenade/iqm.cfg');
new DataRequest(6626498, 6626654, 0, 0).open('GET', '/packages/models/projectiles/rocket/iqm.cfg');
new DataRequest(6626654, 6639891, 0, 0).open('GET', '/packages/models/projectiles/rocket/skin.jpg');
new DataRequest(6639891, 6643027, 0, 0).open('GET', '/packages/models/projectiles/rocket/rocket.iqm');
new DataRequest(6643027, 6650746, 0, 0).open('GET', '/packages/models/projectiles/rocket/normal.jpg');
new DataRequest(6650746, 6651406, 0, 0).open('GET', '/packages/models/projectiles/rocket/readme.txt');
new DataRequest(6651406, 6672174, 0, 0).open('GET', '/packages/models/projectiles/rocket/mask.jpg');
new DataRequest(6672174, 6672311, 0, 0).open('GET', '/packages/brushes/gradient_128.png');
new DataRequest(6672311, 6673307, 0, 0).open('GET', '/packages/brushes/circle_8_hard.png');
new DataRequest(6673307, 6674545, 0, 0).open('GET', '/packages/brushes/circle_32_solid.png');
new DataRequest(6674545, 6678877, 0, 0).open('GET', '/packages/brushes/circle_64_hard.png');
new DataRequest(6678877, 6680084, 0, 0).open('GET', '/packages/brushes/square_64_hard.png');
new DataRequest(6680084, 6681166, 0, 0).open('GET', '/packages/brushes/square_16_hard.png');
new DataRequest(6681166, 6682139, 0, 0).open('GET', '/packages/brushes/square_16_solid.png');
new DataRequest(6682139, 6683120, 0, 0).open('GET', '/packages/brushes/square_32_solid.png');
new DataRequest(6683120, 6684405, 0, 0).open('GET', '/packages/brushes/circle_32_soft.png');
new DataRequest(6684405, 6685400, 0, 0).open('GET', '/packages/brushes/circle_8_solid.png');
new DataRequest(6685400, 6687214, 0, 0).open('GET', '/packages/brushes/circle_64_soft.png');
new DataRequest(6687214, 6688327, 0, 0).open('GET', '/packages/brushes/circle_16_solid.png');
new DataRequest(6688327, 6690691, 0, 0).open('GET', '/packages/brushes/circle_128_solid.png');
new DataRequest(6690691, 6700326, 0, 0).open('GET', '/packages/brushes/noise_128.png');
new DataRequest(6700326, 6701318, 0, 0).open('GET', '/packages/brushes/circle_8_soft.png');
new DataRequest(6701318, 6702501, 0, 0).open('GET', '/packages/brushes/square_32_hard.png');
new DataRequest(6702501, 6703623, 0, 0).open('GET', '/packages/brushes/circle_16_hard.png');
new DataRequest(6703623, 6707183, 0, 0).open('GET', '/packages/brushes/circle_32_hard.png');
new DataRequest(6707183, 6710660, 0, 0).open('GET', '/packages/brushes/circle_128_soft.png');
new DataRequest(6710660, 6710789, 0, 0).open('GET', '/packages/brushes/gradient_64.png');
new DataRequest(6710789, 6710909, 0, 0).open('GET', '/packages/brushes/gradient_32.png');
new DataRequest(6710909, 6711915, 0, 0).open('GET', '/packages/brushes/square_64_solid.png');
new DataRequest(6711915, 6713006, 0, 0).open('GET', '/packages/brushes/circle_16_soft.png');
new DataRequest(6713006, 6717094, 0, 0).open('GET', '/packages/brushes/circle_128_hard.png');
new DataRequest(6717094, 6717153, 0, 0).open('GET', '/packages/brushes/readme.txt');
new DataRequest(6717153, 6719443, 0, 0).open('GET', '/packages/brushes/noise_64.png');
new DataRequest(6719443, 6721027, 0, 0).open('GET', '/packages/brushes/circle_64_solid.png');
new DataRequest(6721027, 6721130, 0, 0).open('GET', '/packages/brushes/gradient_16.png');
new DataRequest(6721130, 6737565, 0, 0).open('GET', '/packages/hud/ff.png');
new DataRequest(6737565, 6881309, 0, 0).open('GET', '/packages/hud/damage.png');
new DataRequest(6881309, 6881380, 0, 0).open('GET', '/packages/hud/readme.txt');
new DataRequest(6881380, 6986781, 0, 0).open('GET', '/packages/hud/items.png');
function processPackageData(arrayBuffer) {
Module.finishedDataFileDownloads++;
assert(arrayBuffer, 'Loading data file failed.');
var byteArray = new Uint8Array(arrayBuffer);
var curr;
// copy the entire loaded file into a spot in the heap. Files will refer to slices in that. They cannot be freed though.
var ptr = Module['_malloc'](byteArray.length);
Module['HEAPU8'].set(byteArray, ptr);
DataRequest.prototype.byteArray = Module['HEAPU8'].subarray(ptr, ptr+byteArray.length);
DataRequest.prototype.requests["/data/menus.cfg"].onload();
DataRequest.prototype.requests["/data/guioverlay.png"].onload();
DataRequest.prototype.requests["/data/background_decal.png"].onload();
DataRequest.prototype.requests["/data/sounds.cfg"].onload();
DataRequest.prototype.requests["/data/default_map_settings.cfg"].onload();
DataRequest.prototype.requests["/data/hit.png"].onload();
DataRequest.prototype.requests["/data/default_map_models.cfg"].onload();
DataRequest.prototype.requests["/data/crosshair.png"].onload();
DataRequest.prototype.requests["/data/teammate.png"].onload();
DataRequest.prototype.requests["/data/background.png"].onload();
DataRequest.prototype.requests["/data/stdshader.cfg"].onload();
DataRequest.prototype.requests["/data/guiskin.png"].onload();
DataRequest.prototype.requests["/data/logo.png"].onload();
DataRequest.prototype.requests["/data/guislider.png"].onload();
DataRequest.prototype.requests["/data/keymap.cfg"].onload();
DataRequest.prototype.requests["/data/mapshot_frame.png"].onload();
DataRequest.prototype.requests["/data/guicursor.png"].onload();
DataRequest.prototype.requests["/data/loading_bar.png"].onload();
DataRequest.prototype.requests["/data/glsl.cfg"].onload();
DataRequest.prototype.requests["/data/loading_frame.png"].onload();
DataRequest.prototype.requests["/data/stdlib.cfg"].onload();
DataRequest.prototype.requests["/data/game_fps.cfg"].onload();
DataRequest.prototype.requests["/data/background_detail.png"].onload();
DataRequest.prototype.requests["/data/stdedit.cfg"].onload();
DataRequest.prototype.requests["/data/font.cfg"].onload();
DataRequest.prototype.requests["/data/brush.cfg"].onload();
DataRequest.prototype.requests["/data/game_rpg.cfg"].onload();
DataRequest.prototype.requests["/data/defaults.cfg"].onload();
DataRequest.prototype.requests["/packages/textures/water.jpg"].onload();
DataRequest.prototype.requests["/packages/textures/waterdudv.jpg"].onload();
DataRequest.prototype.requests["/packages/textures/notexture.png"].onload();
DataRequest.prototype.requests["/packages/textures/waterfalln.jpg"].onload();
DataRequest.prototype.requests["/packages/textures/waterfall.jpg"].onload();
DataRequest.prototype.requests["/packages/textures/readme.txt"].onload();
DataRequest.prototype.requests["/packages/textures/waterfalldudv.jpg"].onload();
DataRequest.prototype.requests["/packages/textures/watern.jpg"].onload();
DataRequest.prototype.requests["/packages/fonts/font.png"].onload();
DataRequest.prototype.requests["/packages/fonts/default.cfg"].onload();
DataRequest.prototype.requests["/packages/fonts/font_readme.txt"].onload();
DataRequest.prototype.requests["/packages/icons/info.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/arrow_fw.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/frankie.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/server.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/radio_on.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/checkbox_on.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/cube.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/exit.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/checkbox_off.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/chat.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/menu.png"].onload();
DataRequest.prototype.requests["/packages/icons/readme.txt"].onload();
DataRequest.prototype.requests["/packages/icons/snoutx10k.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/radio_off.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/arrow_bw.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/action.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/menu.jpg"].onload();
DataRequest.prototype.requests["/packages/icons/hand.jpg"].onload();
DataRequest.prototype.requests["/packages/particles/lightning.jpg"].onload();
DataRequest.prototype.requests["/packages/particles/smoke.png"].onload();
DataRequest.prototype.requests["/packages/particles/spark.png"].onload();
DataRequest.prototype.requests["/packages/particles/ball2.png"].onload();
DataRequest.prototype.requests["/packages/particles/circle.png"].onload();
DataRequest.prototype.requests["/packages/particles/muzzleflash2.jpg"].onload();
DataRequest.prototype.requests["/packages/particles/blood.png"].onload();
DataRequest.prototype.requests["/packages/particles/steam.png"].onload();
DataRequest.prototype.requests["/packages/particles/explosion.png"].onload();
DataRequest.prototype.requests["/packages/particles/readme.txt"].onload();
DataRequest.prototype.requests["/packages/particles/base.png"].onload();
DataRequest.prototype.requests["/packages/particles/blob.png"].onload();
DataRequest.prototype.requests["/packages/particles/bullet.png"].onload();
DataRequest.prototype.requests["/packages/particles/muzzleflash1.jpg"].onload();
DataRequest.prototype.requests["/packages/particles/flames.png"].onload();
DataRequest.prototype.requests["/packages/particles/readme.txt~"].onload();
DataRequest.prototype.requests["/packages/particles/flare.jpg"].onload();
DataRequest.prototype.requests["/packages/particles/muzzleflash3.jpg"].onload();
DataRequest.prototype.requests["/packages/particles/lensflares.png"].onload();
DataRequest.prototype.requests["/packages/particles/scorch.png"].onload();
DataRequest.prototype.requests["/packages/particles/ball1.png"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/pain1.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/die1.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/land.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/grunt2.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/tak.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/weapload.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/grunt1.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/pain3.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/pain2.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/die2.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/pain5.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/pain4.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/bang.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/itempick.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/pain6.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/outofammo.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/aard/jump.wav"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/minigun.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/shotgun3.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/rlauncher2.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/rifle3.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/teleport.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/ren.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/minigun2.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/jumppad.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/glauncher.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/weapswitch.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/explosion.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/rifle2.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/shotgun.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/minigun3.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/ren2.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/rifle.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/ren3.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/rlauncher.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/quaddamage_out.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/outofammo.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/shotgun2.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/pistol3.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/license.txt"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/readme.txt"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/quaddamage_shoot.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/rlauncher3.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/pistol2.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/glauncher2.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/glauncher3.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/q009/pistol.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/yo_frankie/amb_waterdrip_2.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/yo_frankie/readme.txt"].onload();
DataRequest.prototype.requests["/packages/sounds/yo_frankie/sfx_interact.ogg"].onload();
DataRequest.prototype.requests["/packages/sounds/yo_frankie/watersplash2.ogg"].onload();
DataRequest.prototype.requests["/packages/gk/lava/lava_cc.dds"].onload();
DataRequest.prototype.requests["/packages/gk/lava/lava_nm.dds"].onload();
DataRequest.prototype.requests["/packages/caustics/caust08.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust17.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust13.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust06.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust03.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust05.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust19.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust23.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust24.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust25.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust28.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust26.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust12.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust04.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust07.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust31.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust15.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust14.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust29.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust11.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust30.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust18.png"].onload();
DataRequest.prototype.requests["/packages/caustics/readme.txt"].onload();
DataRequest.prototype.requests["/packages/caustics/caust09.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust10.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust22.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust01.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust00.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust20.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust16.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust27.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust02.png"].onload();
DataRequest.prototype.requests["/packages/caustics/caust21.png"].onload();
DataRequest.prototype.requests["/packages/models/debris/tris.md2"].onload();
DataRequest.prototype.requests["/packages/models/debris/md2.cfg"].onload();
DataRequest.prototype.requests["/packages/models/debris/skin.png"].onload();
DataRequest.prototype.requests["/packages/models/projectiles/grenade/iqm.cfg"].onload();
DataRequest.prototype.requests["/packages/models/projectiles/rocket/iqm.cfg"].onload();
DataRequest.prototype.requests["/packages/models/projectiles/rocket/skin.jpg"].onload();
DataRequest.prototype.requests["/packages/models/projectiles/rocket/rocket.iqm"].onload();
DataRequest.prototype.requests["/packages/models/projectiles/rocket/normal.jpg"].onload();
DataRequest.prototype.requests["/packages/models/projectiles/rocket/readme.txt"].onload();
DataRequest.prototype.requests["/packages/models/projectiles/rocket/mask.jpg"].onload();
DataRequest.prototype.requests["/packages/brushes/gradient_128.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_8_hard.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_32_solid.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_64_hard.png"].onload();
DataRequest.prototype.requests["/packages/brushes/square_64_hard.png"].onload();
DataRequest.prototype.requests["/packages/brushes/square_16_hard.png"].onload();
DataRequest.prototype.requests["/packages/brushes/square_16_solid.png"].onload();
DataRequest.prototype.requests["/packages/brushes/square_32_solid.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_32_soft.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_8_solid.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_64_soft.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_16_solid.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_128_solid.png"].onload();
DataRequest.prototype.requests["/packages/brushes/noise_128.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_8_soft.png"].onload();
DataRequest.prototype.requests["/packages/brushes/square_32_hard.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_16_hard.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_32_hard.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_128_soft.png"].onload();
DataRequest.prototype.requests["/packages/brushes/gradient_64.png"].onload();
DataRequest.prototype.requests["/packages/brushes/gradient_32.png"].onload();
DataRequest.prototype.requests["/packages/brushes/square_64_solid.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_16_soft.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_128_hard.png"].onload();
DataRequest.prototype.requests["/packages/brushes/readme.txt"].onload();
DataRequest.prototype.requests["/packages/brushes/noise_64.png"].onload();
DataRequest.prototype.requests["/packages/brushes/circle_64_solid.png"].onload();
DataRequest.prototype.requests["/packages/brushes/gradient_16.png"].onload();
DataRequest.prototype.requests["/packages/hud/ff.png"].onload();
DataRequest.prototype.requests["/packages/hud/damage.png"].onload();
DataRequest.prototype.requests["/packages/hud/readme.txt"].onload();
DataRequest.prototype.requests["/packages/hud/items.png"].onload();
Module['removeRunDependency']('datafile_base.data');
};
Module['addRunDependency']('datafile_base.data');
if (!Module.preloadResults) Module.preloadResults = {};
Module.preloadResults[PACKAGE_NAME] = {fromCache: false};
if (fetched) {
processPackageData(fetched);
fetched = null;
} else {
fetchedCallback = processPackageData;
}
}
if (Module['calledRun']) {
runWithFS();
} else {
if (!Module['preRun']) Module['preRun'] = [];
Module["preRun"].push(runWithFS); // FS is not initialized yet, wait for it
}
if (!Module['postRun']) Module['postRun'] = [];
Module["postRun"].push(function() {
decrunchWorker.terminate();
});
})();
|
import { silenceError, isHandled } from './inspect'
import { attachTrace } from './trace'
const UNHANDLED_REJECTION = 'unhandledRejection'
const HANDLED_REJECTION = 'rejectionHandled'
export default class ErrorHandler {
constructor (emitEvent, reportError) {
this.rejections = []
this.emit = emitEvent
this.reportError = reportError
}
track (rejected) {
const e = attachTrace(rejected.value, rejected.context)
if (!this.emit(UNHANDLED_REJECTION, rejected, e)) {
/* istanbul ignore else */
if (this.rejections.length === 0) {
setTimeout(reportErrors, 1, this.reportError, this.rejections)
}
this.rejections.push(rejected)
}
}
untrack (rejected) {
silenceError(rejected)
this.emit(HANDLED_REJECTION, rejected)
}
}
function reportErrors (report, rejections) {
try {
reportAll(rejections, report)
} finally {
rejections.length = 0
}
}
function reportAll (rejections, report) {
for (let i = 0; i < rejections.length; ++i) {
const rejected = rejections[i]
/* istanbul ignore else */
if (!isHandled(rejected)) {
report(rejected)
}
}
}
|
import React from 'react';
import SearchInput, {createFilter} from 'react-search-input';
class ItemsOptions extends React.Component {
constructor(props)
{
super(props);
this.state =
{
is_showing_options_modal: false
}
}
render()
{
return(
<div className="options__list">
</div>
);
}
}
export default ItemsOptions; |
/** A simple function
* This is a super simple function.
** It takes two numbers or something
* @a {string} - the string
* @b {number} - the number
* @returns {number} - the sum of a + b
*/
somenamespace.nested.test = function (a, b) {
}
/** Another simple function
*/
namespace.other = function (c, d) {
}
/** A regular function
* This is a regular function
*/
function sum(a, b) {
/** Uh-oh, it's an anon return function!
*/
return function (a, b) {
return a + b;
}
}
var thing = {
/** Function in a thing
* @namespace thing - this is only needed where it can't be deduced
*/
fn: function (s, d) {
}
};
/** A closure to keep state out of the global namespace */
(function () {
})();
/** A function assigned to a var */
var varFunction = function () {
}
/** Keep track of the magic number */
var myObject = 123;
/** This is an object constructor
* @constructor
*/
function Test() {
return {
/** Say foobar
* @memberof Test
* @return {undefined} - returns nothing
*/
foobar: function () {
}
};
}
/** This is an object constructor
* @constructor
* @attributes {object} - The attributes
* > name {string} - a string object
* > nested {object} - a nested object
* > subName {string} - nested property
*/
function Hello(attributes) {
} |
const React = require('react');
const sanfona = require('react-sanfona');
const Accordion = sanfona.Accordion;
const { UiComponentLoader } = require('./ui-module-util');
const EventEmitter = require('events');
class Navigation extends React.Component {
constructor(props) {
super(props);
this.props.ipcRenderer.on('find-hue-error', err => {
//console.log('find-hue-error',err);
});
this.mapAccordionitem = null;
this.uiComponentLoader = new UiComponentLoader(
this.props.uiConfigData,
__dirname,
'navigation/accordionitem'
);
this.uiComponentLoader
.load()
.sort()
.done();
}
render() {
let aryComponent = [],
ComponentClass = null;
for( let [ fileId, objs ] of this.uiComponentLoader.getComponents() ) {
ComponentClass = objs.componentClass;
aryComponent.push(
<ComponentClass
emitter={this.props.emitter}
myOperator={objs.operator}
key={fileId}
uiConfig={objs.config}
doLoadArticle={this.props.doLoadArticle}
/>
);
}
if( aryComponent.length ) {
return (
<div id="navigation">
<Accordion
allowMultiple={true}
className="accordion"
activeItems={aryComponent.map( ( value ,index ) => index )}
>
{aryComponent}
</Accordion>
</div>
);
}
else {
return <div id="navigation"/>;
}
}
}
Navigation.propTypes = {
'ipcRenderer': React.PropTypes.instanceOf(EventEmitter),
'doLoadArticle': React.PropTypes.func,
'uiConfigData': React.PropTypes.object,
'emitter': React.PropTypes.instanceOf(EventEmitter)
};
module.exports = Navigation;
|
/* eslint handle-callback-err: 0 */
'use strict'
import fs from 'fs'
import path from 'path'
import frontMatter from 'front-matter'
import yaml from 'js-yaml'
import Config from '../config'
import Gulp from 'gulp'
import Plugins from 'gulp-load-plugins'
const $ = Plugins()
const isProd = Config.environment === 'production'
Gulp.task('demos', () => Gulp.src([ `${Config.demos.src}/**/*` ])
.pipe($.size({ title: 'Demo files!', gzip: false, showFiles: true }))
.pipe(Gulp.dest(`${Config.demos.dist}`)))
Gulp.task('templates', ['demos'], () => {
const parseData = function (file) {
const content = frontMatter(String(file.contents))
file.contents = new Buffer(content.body)
return content.attributes
}
const getLayoutPath = function (name) {
return path.resolve(process.cwd(), `${Config.docs.layouts}/`, `${name}.pug`)
}
const wrapHtml = function (file, name) {
const html = String(file.contents)
const path = getLayoutPath(name)
file.contents = fs.readFileSync(path)
return { content: html }
}
return Gulp.src([ `${Config.docs.pages}/*` ])
.pipe($.plumber(Config.plumberHandler))
.pipe($.data((file) => require(Config.docs.config)))
.pipe($.data((file) => parseData(file)))
.pipe($.data((file) => {
return {
'base_url': isProd ? '/chef' : '',
'production': isProd ? Config.environment : '',
'min': isProd ? '.min' : ''
}
}))
.pipe($.data((file) => {
fs.readdir(Config.docs.data, (err, files) => {
let yamlData = []
files.forEach(file => {
yamlData.push(yaml.safeLoad(fs.readFileSync(`${Config.docs.data}/${file}`)))
})
return yamlData
})
}))
.pipe($.hb({
partials: `${Config.demos.src}/**/*.hbs`,
// helpers: `${Config.docs.data}`,
data: `${Config.docs.data}/*.json`
}))
.pipe($.data((file) => wrapHtml(file, file.data.layout)))
.pipe($.pug())
.pipe($.rename(path => {
if (path.basename !== 'index') {
path.dirname = path.basename
path.basename = 'index'
}
path.extname = '.html'
}))
.pipe(isProd ? $.htmlmin({ collapseWhitespace: true }) : $.jsbeautifier({ indent_level: 2 }))
.pipe(isProd ? $.util.noop() : $.size({ title: 'Templates!', gzip: false, showFiles: true }))
.pipe(Gulp.dest(`${Config.docs.dist}`))
.pipe($.plumber.stop())
})
|
(function() {
var module = QUnit.module;
var test = QUnit.test;
module("Collision");
test("Collision constructors", function(_) {
var newHitboxEvents = 0;
var e = Crafty.e("2D, Collision").bind("NewHitbox", function(newHitbox) {
newHitboxEvents++;
});
var poly = new Crafty.polygon([50, 0, 100, 100, 0, 100]);
e.collision(poly);
_.ok(e.map instanceof Crafty.polygon, "Hitbox is a polygon");
_.ok(e.map !== poly, "Hitbox is a clone of passed polygon");
var arr = [50, 0, 100, 100, 0, 100];
e.collision(arr);
_.ok(e.map instanceof Crafty.polygon, "Hitbox is a polygon");
_.ok(
e.map.points && e.map.points !== arr,
"Array used in hitbox is a clone of passed array"
);
e.collision(50, 0, 100, 100, 0, 100);
_.ok(e.map instanceof Crafty.polygon, "Hitbox is a polygon");
_.strictEqual(newHitboxEvents, 3, "NewHitBox event triggered 3 times");
});
test("hit", function(_) {
var e = Crafty.e("2D, Collision, solid").attr({ x: 0, y: 0, w: 25, h: 25 });
var f = Crafty.e("2D, Collision, solid").attr({
x: 255,
y: 255,
w: 25,
h: 25
});
var g = Crafty.e("2D, Collision, solid").attr({
x: 255,
y: 255,
w: 25,
h: 25
});
var h = Crafty.e("2D, Collision, plasma").attr({
x: 255,
y: 255,
w: 25,
h: 25
});
var results;
// check entity itself is not reported
results = e.hit("solid");
_.strictEqual(results, null, "empty collision results");
// check no reported hits given no intersections
results = e.hit("obj");
_.strictEqual(results, null, "empty collision results");
// check for hits given any-entity intersections
h.x = h.y = 0;
results = e.hit("obj");
_.strictEqual(results.length, 1, "exactly one collision result");
_.strictEqual(results[0].obj, h, "expected collision with entity h");
// check no reported hits with solid component
results = e.hit("solid");
_.strictEqual(results, null, "empty collision results");
// check for hits with solid entity
f.x = f.y = 0;
results = e.hit("solid");
_.strictEqual(results.length, 1, "exactly one collision result");
_.strictEqual(results[0].obj, f, "expected collision with entity f");
// check for hits with solid entities
g.x = g.y = 0;
results = e.hit("solid");
_.strictEqual(results.length, 2, "exactly two collision results");
var counter = 0;
for (var i = 0; i < 2; ++i) {
if (results[i].obj === f) counter++;
else if (results[i].obj === g) counter++;
}
_.strictEqual(counter, 2, "expected collisions with entity f and g");
// check no reported hits with solid component
f.x = f.y = g.x = g.y = 255;
results = e.hit("solid");
_.strictEqual(results, null, "empty collision results");
});
test("hit - collision type", function(_) {
var e = Crafty.e("2D, Collision, solid").attr({ x: 0, y: 0, w: 25, h: 25 });
var f = Crafty.e("2D, solid").attr({ x: 0, y: 0, w: 25, h: 25 });
var results;
// check for MBR type collision with other entity
results = e.hit("solid");
_.strictEqual(results.length, 1, "exactly one collision result");
_.strictEqual(results[0].obj, f, "expected collision with entity f");
_.strictEqual(results[0].type, "MBR", "expected collision type");
// check for SAT type collision with other entity
f.addComponent("Collision");
results = e.hit("solid");
_.strictEqual(results.length, 1, "exactly one collision result");
_.strictEqual(results[0].obj, f, "expected collision with entity f");
_.strictEqual(results[0].type, "SAT", "expected collision type");
_.ok("overlap" in results[0], "expected overlap value");
});
test("hit -- collision vs. non collision tests", function(_) {
var e1 = Crafty.e("2D, Collision").attr({ x: 0, y: 0, w: 2, h: 2 });
var e2 = Crafty.e("2D").attr({ x: 0, y: 0, w: 2, h: 2 });
var results = e1.hit("2D");
_.strictEqual(results.length, 1, "exactly one collision");
_.strictEqual(results[0].type, "MBR", "expected MBR collision type");
_.strictEqual(results[0].obj[0], e2[0], "expected collision with e2");
// Move e2 such that it should be returned by the broadphase search
// (i.e. it's in the same cell of the spatial hashmap)
// but doesn't actually overlap e1's MBR
e2.x = 3;
var newResults = e1.hit("2D");
_.ok(!newResults, 0, "No collisions");
});
test("onHit", function(_) {
var e = Crafty.e("2D, Collision").attr({ x: 0, y: 0, w: 25, h: 25 });
var f = Crafty.e("2D, Collision").attr({ x: 255, y: 255, w: 25, h: 25 });
var g = Crafty.e("2D, Collision, solid").attr({
x: 255,
y: 255,
w: 25,
h: 25
});
var expectedHitDatas = {},
onCallbacks = 0,
firstOnCallbacks = 0,
offCallbacks = 0;
e.onHit(
"solid",
function(hitDatas, isFirstCallback) {
// callbackOn
onCallbacks++;
if (isFirstCallback) firstOnCallbacks++;
_.strictEqual(
hitDatas.length,
Object.keys(expectedHitDatas).length,
"collision with exactly expected amount of entities"
);
for (var i = 0; i < hitDatas.length; ++i)
_.ok(
hitDatas[i].obj[0] in expectedHitDatas,
"collision with expected entity occurred"
);
},
function() {
// callbackOff
offCallbacks++;
}
);
// check initial state
// default state with no intersections, before update frame
_.strictEqual(
onCallbacks,
0,
"no collision callbacks yet before update frame"
);
_.strictEqual(
firstOnCallbacks,
0,
"no collision callbacks yet before update frame"
);
_.strictEqual(
offCallbacks,
0,
"no collision callbacks yet before update frame"
);
// check initial state
// default state with no intersections, after update frame
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 0, "no collision callbacks if no intersection");
_.strictEqual(
firstOnCallbacks,
0,
"no collision callbacks if no intersection"
);
_.strictEqual(offCallbacks, 0, "no collision callbacks if no intersection");
// check no callbacks
// intersection with f, but without required component
f.x = f.y = 0;
Crafty.timer.simulateFrames(1);
_.strictEqual(
onCallbacks,
0,
"no collision callbacks yet before update frame"
);
_.strictEqual(
firstOnCallbacks,
0,
"no collision callbacks yet before update frame"
);
_.strictEqual(
offCallbacks,
0,
"no collision callbacks yet before update frame"
);
// check no callbacks done before frame update
// intersection with f, with required component, before update frame
f.addComponent("solid");
_.strictEqual(
onCallbacks,
0,
"no collision callbacks yet before update frame"
);
_.strictEqual(
firstOnCallbacks,
0,
"no collision callbacks yet before update frame"
);
_.strictEqual(
offCallbacks,
0,
"no collision callbacks yet before update frame"
);
// check callbacks done after frame update
// intersection with f, with required component, after update frame
expectedHitDatas = {};
expectedHitDatas[f[0]] = true;
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 1, "one collision callbackOn occurred");
_.strictEqual(firstOnCallbacks, 1, "first collision callbackOn occurred");
_.strictEqual(offCallbacks, 0, "no collision callbackOff occurred yet");
// check that first callbackOn no longer triggered
// another frame while intersected with f
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 2, "another collision callbackOn occurred");
_.strictEqual(
firstOnCallbacks,
1,
"not another first collision callbackOn occurred"
);
_.strictEqual(offCallbacks, 0, "no collision callbackOff occurred yet");
// check no callbacks before frame update
// no more intersection with f, before update frame
f.x = f.y = 255;
_.strictEqual(
onCallbacks,
2,
"no collision callbacks yet before update frame"
);
_.strictEqual(
firstOnCallbacks,
1,
"no collision callbacks yet before update frame"
);
_.strictEqual(
offCallbacks,
0,
"no collision callbacks yet before update frame"
);
// check callbacks done after frame update
// no more intersection with f, after update frame
expectedHitDatas = {};
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 2, "no more on-collision callbacks occurred");
_.strictEqual(
firstOnCallbacks,
1,
"no more on-collision callbacks occurred"
);
_.strictEqual(offCallbacks, 1, "one off-collision callback occurred");
// check that no callbacks while ide
// no intersections, after another update frame
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 2, "no collision callbacks occurred while idle");
_.strictEqual(
firstOnCallbacks,
1,
"no collision callbacks occurred while idle"
);
_.strictEqual(
offCallbacks,
1,
"no collision callbacks occurred while idle"
);
// check callbacks properly called with new collision event
f.x = f.y = 0;
expectedHitDatas = {};
expectedHitDatas[f[0]] = true;
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 3, "again collision callbackOn occurred");
_.strictEqual(
firstOnCallbacks,
2,
"again first collision callbackOn occurred"
);
_.strictEqual(offCallbacks, 1, "no collision callbackOff occurred yet");
// check that another intersecting entity does not change semantics of callbacks
g.x = g.y = 0;
expectedHitDatas[g[0]] = true;
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 4, "again collision callbackOn occurred");
_.strictEqual(
firstOnCallbacks,
2,
"first collision callbackOn did not occur"
);
_.strictEqual(offCallbacks, 1, "no collision callbackOff occurred yet");
// check semantics of all intersecting entities leaving collision at same time
f.x = f.y = g.x = g.y = 255;
expectedHitDatas = {};
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 4, "no more on-collision callbacks occurred");
_.strictEqual(
firstOnCallbacks,
2,
"no more on-collision callbacks occurred"
);
_.strictEqual(offCallbacks, 2, "one off-collision callback occurred");
// check semantics of all entities entering collision at same time
f.x = f.y = g.x = g.y = 0;
expectedHitDatas = {};
expectedHitDatas[f[0]] = true;
expectedHitDatas[g[0]] = true;
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 5, "again collision callbackOn occurred");
_.strictEqual(
firstOnCallbacks,
3,
"again first collision callbackOn occurred"
);
_.strictEqual(offCallbacks, 2, "no collision callbackOff occurred yet");
// check that an intersecting entity leaving collision does not change semantics of callbacks
g.x = g.y = 255;
delete expectedHitDatas[g[0]];
Crafty.timer.simulateFrames(1);
_.strictEqual(onCallbacks, 6, "again collision callbackOn occurred");
_.strictEqual(
firstOnCallbacks,
3,
"first collision callbackOn did not occur"
);
_.strictEqual(offCallbacks, 2, "no collision callbackOff occurred yet");
});
// This test assumes that the "circles" are really octagons, as per Crafty.circle.
test("SAT overlap with circles", function(_) {
var e = Crafty.e("2D, Collision");
var c1 = new Crafty.circle(100, 100, 10);
var c2 = new Crafty.circle(100, 105, 10);
_.strictEqual(
e._SAT(c1, c2).overlap < -13.8 && e._SAT(c1, c2).overlap > -13.9,
true,
"Expected overlap to be about -13.86 ( or 15 cos[pi/8])"
);
});
// Testcase from issue #828 by VHonzik
test("SAT overlap with rectangles", function(_) {
var e = Crafty.e("2D, Collision");
var c1 = new Crafty.polygon([0, 1, 50, 1, 50, 51, 0, 51]);
var c2 = new Crafty.polygon([-10, -10, -10, 10, 10, 10, 10, -10]);
_.strictEqual(
e._SAT(c1, c2) !== false,
true,
"Polygons should test as overlapping"
);
});
test("adjustable boundary", function(_) {
var e = Crafty.e("2D").attr({
x: 10,
y: 10,
w: 10,
h: 10
});
// Four argument version
e.offsetBoundary(10, 1, 3, 0);
_.strictEqual(e._bx1, 10, "X1 boundary set");
_.strictEqual(e._bx2, 3, "X2 boundary set");
_.strictEqual(e._by1, 1, "Y1 boundary set");
_.strictEqual(e._by2, 0, "Y2 boundary set");
e._calculateMBR(10, 10, 0);
var mbr = e._mbr;
_.strictEqual(mbr._h, 11, "MBR height uses boundaries (11)");
_.strictEqual(mbr._w, 23, "MBR width uses boundaries (23)");
// One argument version
e.offsetBoundary(5);
_.strictEqual(e._bx1, 5, "X1 boundary set");
_.strictEqual(e._bx2, 5, "X2 boundary set");
_.strictEqual(e._by1, 5, "Y1 boundary set");
_.strictEqual(e._by2, 5, "Y2 boundary set");
});
test("Resizing 2D objects & hitboxes", function(_) {
var e = Crafty.e("2D, Collision");
e.attr({
x: 0,
y: 0,
w: 40,
h: 50
});
_.strictEqual(e.map.points[0], 0, "Before rotation: x_0 is 0");
_.strictEqual(e.map.points[1], 0, "y_0 is 0");
_.strictEqual(e.map.points[4], 40, "x_2 is 40");
_.strictEqual(e.map.points[5], 50, "y_2 is 50");
e.rotation = 90;
_.strictEqual(
Math.round(e.map.points[0]),
0,
"After rotation by 90 deg: x_0 is 0"
);
_.strictEqual(Math.round(e.map.points[1]), 0, "y_0 is 0");
_.strictEqual(Math.round(e.map.points[4]), -50, "x_2 is -50");
_.strictEqual(Math.round(e.map.points[5]), 40, "y_2 is 40");
// After rotation the MBR will have changed
_.strictEqual(Math.round(e._mbr._w), 50, "_mbr._w is 50");
_.strictEqual(Math.round(e._mbr._h), 40, "_mbr._h is 40");
_.strictEqual(Math.round(e._mbr._x), -50, "_mbr._x is -50");
_.strictEqual(Math.round(e._mbr._y), 0, "_mbr._y is 0");
e.collision(); // Check that regenerating the hitbox while rotated works correctly
_.strictEqual(
Math.round(e.map.points[0]),
0,
"After rotation and hitbox regeneration: x_0 is 0"
);
_.strictEqual(Math.round(e.map.points[1]), 0, "y_0 is 0");
_.strictEqual(Math.round(e.map.points[4]), -50, "x_2 is -50");
_.strictEqual(Math.round(e.map.points[5]), 40, "y_2 is 40");
// Check that changing the width when rotated resizes correctly for both hitbox and MBR
// Rotated by 90 degrees, changing the width of the entity should change the height of the hitbox/mbr
e.w = 100;
_.strictEqual(
Math.round(e.map.points[0]),
0,
"After rotation and increase in width: x_0 is 0"
);
_.strictEqual(Math.round(e.map.points[1]), 0, "y_0 is 0");
_.strictEqual(Math.round(e.map.points[4]), -50, "x_2 is -50");
_.strictEqual(Math.round(e.map.points[5]), 100, "y_2 is 100");
// After rotation the MBR will have changed
_.strictEqual(Math.round(e._mbr._w), 50, "_mbr._w is 50");
_.strictEqual(Math.round(e._mbr._h), 100, "_mbr._h is 100");
_.strictEqual(Math.round(e._mbr._x), -50, "_mbr._x is -50");
_.strictEqual(Math.round(e._mbr._y), 0, "_mbr._y is 0");
e.destroy();
});
test("cbr", function(_) {
var player = Crafty.e("2D, Collision").attr({
x: 0,
y: 50,
w: 100,
h: 150
});
var cbrObject = {};
player.cbr(cbrObject);
_.strictEqual(player.cbr()._x, 0, "X value");
_.strictEqual(cbrObject._x, 0, "X value");
_.strictEqual(player.cbr()._y, 50, "Y value");
_.strictEqual(cbrObject._y, 50, "Y value");
_.strictEqual(player.cbr()._w, 100, "W value");
_.strictEqual(cbrObject._w, 100, "W value");
_.strictEqual(player.cbr()._h, 150, "H value");
_.strictEqual(cbrObject._h, 150, "H value");
});
test("Hitboxes outside of entities (CBR)", function(_) {
var poly = new Crafty.polygon([-8, 6, 0, -8, 8, -14, 16, -8, 24, 6]);
var e = Crafty.e("2D, Collision")
.attr({
x: 50,
y: 50,
w: 16,
h: 16
})
.collision(poly);
_.ok(e._cbr !== null, "_cbr exists");
var cbr = e._cbr;
// Test whether cbr actually bounds hitbox+object
_.ok(cbr._x <= 42, "cbr x position correct");
_.ok(cbr._y <= 36, "cbr y position correct");
_.ok(cbr._x + cbr._w >= 74, "cbr width correct");
_.ok(cbr._y + cbr._h >= 66, "cbr height correct");
var x0 = cbr._x,
y0 = cbr._y;
e.x += 10;
e.y += 15;
_.strictEqual(cbr._x, x0 + 10, "cbr x position moves correctly");
_.strictEqual(cbr._y, y0 + 15, "cbr y position moves correctly");
});
test("CBRs on resize", function(_) {
var poly = new Crafty.polygon([0, 0, 0, 12, 12, 12, 12, 0]);
var e = Crafty.e("2D, Collision")
.attr({
x: 50,
y: 50,
w: 15,
h: 15
})
.collision(poly);
_.ok(e._cbr === null, "_cbr should not exist");
e.w = 10;
_.ok(e._cbr !== null, "_cbr should now exist after entity shrinks");
e.w = 20;
_.ok(e._cbr === null, "_cbr should not exist after entity grows again");
});
test("CBRs should be removed on removal of component", function(_) {
var poly = new Crafty.polygon([0, 0, 0, 12, 12, 12, 12, 0]);
var e = Crafty.e("2D, Collision")
.attr({
x: 50,
y: 50,
w: 10,
h: 10
})
.collision(poly);
_.ok(e._cbr !== null, "_cbr should exist to begin with");
e.removeComponent("Collision");
_.ok(e._cbr === null, "_cbr should now be removed along with Collision");
});
// Define variables to host test shapes
var trapezoid = null;
var yellow = null;
var parallelogram = null;
var green = null;
var purple = null;
var resetPositions = function() {
trapezoid.attr({ x: 300, y: 150 });
yellow.attr({ x: 50, y: 50 });
parallelogram.attr({ x: 350, y: 350 });
green.attr({ x: 100, y: 500 });
purple.attr({ x: 500, y: 500 });
};
var overlapEverything = function() {
trapezoid.x = green.x;
trapezoid.y = green.y;
purple.x = green.x;
purple.y = green.y;
yellow.x = green.x;
yellow.y = green.y;
parallelogram.x = green.x;
parallelogram.y = green.y;
};
var setHitChecks = function() {
// Start by canceling hit checks
green.ignoreHits();
// Now set them again
green.checkHits("Trapezoid, Yellow, Parallelogram, Purple");
};
var collisions = [];
var decollisions = [];
var getHitInfoNames = function(hitInfo) {
var result = [];
hitInfo.forEach(function(e) {
result.push(e.obj._entityName);
});
return result;
};
var getSingleHitInfoName = function(hitInfo) {
return getHitInfoNames(hitInfo)[0];
};
var getCollisionParticipants = function(collision) {
return [collision[0], getSingleHitInfoName(collision[1])];
};
module("Collision - complex setting", {
beforeEach: function() {
trapezoid = Crafty.e("Trapezoid, 2D, Collision")
.setName("Trapezoid")
.attr({ w: 200, h: 100 })
.collision(new Crafty.polygon([50, 0, 0, 100, 200, 100, 150, 0]));
yellow = Crafty.e("Yellow, 2D, Collision")
.setName("Yellow")
.attr({ w: 100, h: 100 })
.collision(new Crafty.polygon([0, 0, 0, 100, 100, 100, 100, 0]));
parallelogram = Crafty.e("Parallelogram, 2D, Collision")
.setName("Parallelogram")
.attr({ w: 100, h: 100 })
.collision(new Crafty.polygon([0, 0, 25, 100, 100, 100, 75, 0]));
green = Crafty.e("Green, 2D, Collision")
.setName("Green")
.attr({ w: 100, h: 100 })
.origin("center");
purple = Crafty.e("Purple, 2D, Collision")
.setName("Purple")
.attr({ w: 100, h: 100 })
.origin("center");
// Set up hit events
[trapezoid, yellow, parallelogram, green, purple].forEach(function(e) {
e.bind("HitOn", function(hitInfo) {
collisions.push([e._entityName, hitInfo]);
});
e.bind("HitOff", function(otherComponent) {
decollisions.push([e._entityName, otherComponent]);
});
});
collisions = [];
decollisions = [];
resetPositions();
setHitChecks();
}
});
test("HitOn fires when a tracked entity collides", function(_) {
var collision = null;
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
1,
"There should have been exactly 1 collision"
);
collision = collisions[0];
if (!collision) return;
_.deepEqual(
getCollisionParticipants(collision),
["Green", "Purple"],
"The purple and green blocks should have collided"
);
});
test("HitOn fires for each component type supplied as part of a list", function(_) {
overlapEverything();
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
4,
"There should have been exactly 4 collisions"
);
});
test("HitOn fires for each component type supplied as an individual argument", function(_) {
green.ignoreHits();
green.checkHits("Trapezoid", "Yellow", "Parallelogram", "Purple");
overlapEverything();
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
4,
"There should have been exactly 4 collisions"
);
});
test("HitOn contains info for multiple collisions", function(_) {
var collision = null;
green.x = purple.x;
green.y = purple.y;
yellow.x = green.x;
yellow.y = green.y;
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
2,
"There should have been exactly 2 collisions"
);
// Theoretically the code here should not care about the order of collisions
// in the array, but that is a hassle
collision = collisions[0];
if (collisions[0]) return;
_.deepEqual(
getCollisionParticipants(collision),
["Green", "Yellow"],
"The yellow and green blocks should have collided"
);
collision = collisions[1];
if (!collision) return;
_.deepEqual(
getCollisionParticipants(collision),
["Green", "Purple"],
"The purple and green blocks should have collided"
);
});
test("HitOn collision info contains collision data", function(_) {
var collision = null;
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
collision = collisions[0];
if (!collision) return;
_.strictEqual(
collision[1][0].type,
"SAT",
"The collision type should have been SAT"
);
_.strictEqual(
Math.abs(collision[1][0].overlap),
100,
"The collision overlap should have been 100%"
);
});
test("IgnoreHits causes hits not to be detected", function(_) {
green.ignoreHits();
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
_.strictEqual(collisions.length, 0, "There should have been no collisions");
});
test("IgnoreHits ignores specific components supplied as a list", function(_) {
green.ignoreHits("Trapezoid, Parallelogram");
overlapEverything();
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
2,
"There should have been exactly 2 collisions"
);
});
test("IgnoreHits ignores specific components supplied as arguments", function(_) {
green.ignoreHits("Trapezoid", "Parallelogram");
overlapEverything();
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
2,
"There should have been exactly 2 collisions"
);
});
test("IgnoreHits has no effect when irrelevant components are supplied", function(_) {
green.ignoreHits("All, Your, Base");
overlapEverything();
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
4,
"There should have been exactly 4 collisions"
);
});
test("Once a hit event is fired, it will not fire again while the collision persists", function(_) {
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(10);
_.strictEqual(
collisions.length,
1,
"There should have been exactly 1 collision"
);
});
test("HitOff fires when a tracked entity stops colliding", function(_) {
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
resetPositions();
Crafty.timer.simulateFrames(1);
_.strictEqual(
decollisions.length,
1,
"Exactly 1 collision should have stopped"
);
var decollision = decollisions[0];
if (!decollision) return;
_.deepEqual(
[decollision[0], decollision[1]],
["Green", "Purple"],
"The purple and green blocks should have stopped colliding"
);
});
test("HitOff events fires only once per terminated collision", function(_) {
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
resetPositions();
Crafty.timer.simulateFrames(10);
_.strictEqual(
decollisions.length,
1,
"Exactly 1 collision should have stopped"
);
});
test("Setting up a hit check multiple times has no effect", function(_) {
// None of the checks below should register as test initialization already registered this check
green.checkHits("Purple");
green.checkHits("Purple");
green.checkHits("Purple");
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
resetPositions();
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
1,
"There should have been exactly 1 collision"
);
_.strictEqual(
decollisions.length,
1,
"Exactly 1 collision should have stopped"
);
});
test("HitOn events fire for a collision after the original one", function(_) {
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
resetPositions();
Crafty.timer.simulateFrames(1);
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
2,
"Exactly 2 collisions should have occurred"
);
});
test("HitOn events fire for a collision underway if resetHitChecks is called", function(_) {
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(1);
green.resetHitChecks();
// Fire an additional frame to make sure resetting hit checks has no devious
// side effects.
Crafty.timer.simulateFrames(2);
_.strictEqual(
collisions.length,
2,
"Exactly 2 collisions should have occurred"
);
_.deepEqual(
getCollisionParticipants(collisions[0]),
["Green", "Purple"],
"The first collision should have been between the purple and green blocks"
);
_.deepEqual(
getCollisionParticipants(collisions[1]),
["Green", "Purple"],
"The second collision should have been between the purple and green blocks"
);
});
test("resetHitChecks without arguments resets all checks", function(_) {
overlapEverything();
Crafty.timer.simulateFrames(1);
green.resetHitChecks();
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
8,
"Exactly 8 collisions should have occurred"
);
});
test("resetHitChecks affects specific components specified as a list", function(_) {
overlapEverything();
Crafty.timer.simulateFrames(1);
green.resetHitChecks("Yellow, Purple");
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
6,
"Exactly 6 collisions should have occurred"
);
});
test("resetHitChecks affects specific components specified as arguments", function(_) {
overlapEverything();
Crafty.timer.simulateFrames(1);
green.resetHitChecks("Yellow", "Purple");
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
6,
"Exactly 6 collisions should have occurred"
);
});
test("resetHitChecks has no effect for components without hit checks", function(_) {
overlapEverything();
Crafty.timer.simulateFrames(1);
green.resetHitChecks("Banana", "Phone");
Crafty.timer.simulateFrames(1);
_.strictEqual(
collisions.length,
4,
"Exactly 4 collisions should have occurred"
);
});
test("resetHitChecks works from within a hit handler", function(_) {
var hitResetCallback = function() {
green.resetHitChecks();
};
green.bind("HitOn", hitResetCallback);
green.x = purple.x;
green.y = purple.y;
Crafty.timer.simulateFrames(2);
_.strictEqual(
collisions.length,
2,
"Exactly 2 collisions should have occurred"
);
green.unbind("HitOn", hitResetCallback);
});
})();
|
const express = require("express");
const app = express();
app.use(express.static(__dirname + "/dist"));
app.get("*", (req, res) => {
res.sendFile(__dirname + "./dist/index.html");
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('Server listening on ', PORT)
});
|
'use strict';
describe('Controller: AboutCtrl', function () {
// load the controller's module
beforeEach(module('weatherApp'));
var AboutCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AboutCtrl = $controller('AboutCtrl', {
$scope: scope
// place here mocked dependencies
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(AboutCtrl.awesomeThings.length).toBe(3);
});
});
|
/**
* Created by zhoujialin on 2016/5/4.
*/
// 组件模块化
const ReactDOM = require('react-dom');
const React = require('react');
const List = require('./lib/List');
ReactDOM.render(
<List/>,
document.getElementById('test')
); |
import Vue from '../node_modules/vue/dist/vue';
import App from './app.vue';
import './styles/styles.css';
import './styles/styles.scss';
new Vue({
el: '.todo',
components: { App }
}) |
module.exports = {
EMPTY: 0,
CROSS: 1,
ROUND: 2
} |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M5 14.5h14v-6H5v6zM11 .55V3.5h2V.55h-2zm8.04 2.5l-1.79 1.79 1.41 1.41 1.8-1.79-1.42-1.41zM13 22.45V19.5h-2v2.95h2zm7.45-3.91l-1.8-1.79-1.41 1.41 1.79 1.8 1.42-1.42zM3.55 4.46l1.79 1.79 1.41-1.41-1.79-1.79-1.41 1.41zm1.41 15.49l1.79-1.8-1.41-1.41-1.79 1.79 1.41 1.42z"
}), 'WbIridescent'); |
// Karma configuration
// Generated on Wed Nov 06 2013 00:03:21 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'src/bower_components/angular/angular.min.js',
'src/bower_components/angular-mocks/angular-mocks.js',
'src/*.js',
'test/*Spec.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
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, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
// browsers: ['Chrome', 'PhantomJS'],
browsers: ['Firefox'],
// 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: true
});
};
|
const tap = require('tap');
const expect = require('expect.js');
const testUtils = require('../../../../../../testUtils');
tap.mochaGlobals();
const describeTitle = 'bin/east create command with source dir';
describe(describeTitle, () => {
let commandResult;
let testEnv;
before(() => {
return Promise.resolve()
.then(() => testUtils.createEnv({
migratorParams: {
init: true,
configureParams: {
sourceDir: 'migrationsSource'
}
}
}))
.then((createdTestEnv) => {
testEnv = createdTestEnv;
});
});
after(() => testUtils.destroyEnv(testEnv));
it('should be done without error', () => {
return Promise.resolve()
.then(() => {
const binPath = testUtils.getBinPath('east');
return testUtils.execAsync(
`"${binPath}" create someMigrationName --source-dir migrationsSource`,
{cwd: testEnv.dir}
);
})
.then((result) => {
expect(result.stderr).not.ok();
commandResult = result;
});
});
it('stdout should match expected snapshot', () => {
tap.matchSnapshot(
testUtils.cleanSnapshotData(commandResult.stdout),
'output'
);
});
});
|
var mongoose = require('mongoose'),
UserModel = require('../data/models/User'),
PlaylistModel = require('../data/models/Playlist');
module.exports = function(config) {
mongoose.connect(config.db);
var db = mongoose.connection;
db.once('open', function(err) {
if (err) {
console.log('Database could not be opened: ' + err);
return;
}
console.log('Database up and running...')
});
db.on('error', function(err){
console.log('Database error: ' + err);
});
UserModel.init();
PlaylistModel.init();
}; |
Fr.Controller.create('offline','main/add', function(){
return{
render : function(done){
done({body: 'main/add'});
},
afterRender : function(done){
$('.nav a').click(function(){
Fr.offline.renderViewTo({ view: $(this).attr('href'), target: '#content', transition: 'slide-right' });
return false;
});
$('#post_form').submit(function(data){
post_data = {};
$('input').each(function(index, value){
var key = $(this)[0].name;
var val = $(this).val();
if($(this)[0].type != 'submit'){
post_data[key] = val;
}
});
$('textarea').each(function(index, value){
var key = $(this)[0].name;
var val = $(this).val();
post_data[key] = val;
});
Posts.create('na', post_data, function(create_handle){
Fr.offline.renderViewTo({ view: 'main/index', target: '#content', transition: 'slide-right' });
});
return false;
});
},
cleanUp : function(){
$('#post_form').unbind('submit');
$('.nav a').unbind('click');
}
};
});
|
/* */
var numeral = require('../../numeral'),
language = require('../../languages/fr-ch');
numeral.language('fr-ch', language);
exports['language:fr-ch'] = {
setUp: function (callback) {
numeral.language('fr-ch');
callback();
},
tearDown: function (callback) {
numeral.language('en');
callback();
},
format: function (test) {
test.expect(16);
var tests = [
[10000,'0,0.0000','10\'000.0000'],
[10000.23,'0,0','10\'000'],
[-10000,'0,0.0','-10\'000.0'],
[10000.1234,'0.000','10000.123'],
[-10000,'(0,0.0000)','(10\'000.0000)'],
[-0.23,'.00','-.23'],
[-0.23,'(.00)','(.23)'],
[0.23,'0.00000','0.23000'],
[1230974,'0.0a','1.2m'],
[1460,'0a','1k'],
[-104000,'0a','-104k'],
[1,'0o','1er'],
[52,'0o','52e'],
[23,'0o','23e'],
[100,'0o','100e'],
[1,'0[.]0','1']
];
for (var i = 0; i < tests.length; i++) {
test.strictEqual(numeral(tests[i][0]).format(tests[i][1]), tests[i][2], tests[i][1]);
}
test.done();
},
currency: function (test) {
test.expect(4);
var tests = [
[1000.234,'$0,0.00','CHF1\'000.23'],
[-1000.234,'($0,0)','(CHF1\'000)'],
[-1000.234,'$0.00','-CHF1000.23'],
[1230974,'($0.00a)','CHF1.23m']
];
for (var i = 0; i < tests.length; i++) {
test.strictEqual(numeral(tests[i][0]).format(tests[i][1]), tests[i][2], tests[i][1]);
}
test.done();
},
percentages: function (test) {
test.expect(4);
var tests = [
[1,'0%','100%'],
[0.974878234,'0.000%','97.488%'],
[-0.43,'0%','-43%'],
[0.43,'(0.000%)','43.000%']
];
for (var i = 0; i < tests.length; i++) {
test.strictEqual(numeral(tests[i][0]).format(tests[i][1]), tests[i][2], tests[i][1]);
}
test.done();
},
unformat: function (test) {
test.expect(9);
var tests = [
['10\'000.123',10000.123],
['(0.12345)',-0.12345],
['(CHF1.23m)',-1230000],
['10k',10000],
['-10k',-10000],
['23e',23],
['CHF10\'000.00',10000],
['-76%',-0.76],
['2:23:57',8637]
];
for (var i = 0; i < tests.length; i++) {
test.strictEqual(numeral().unformat(tests[i][0]), tests[i][1], tests[i][0]);
}
test.done();
}
}; |
import React from 'react';
import Router from 'react-router';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import routes from './views/routes';
import createRedux from './redux/create';
import { Provider } from 'redux/react';
import ApiClient from './ApiClient';
const history = new BrowserHistory();
const client = new ApiClient();
const dest = document.getElementById('content');
const redux = createRedux(client, window.__data);
const element = (<Provider redux={redux}>
{() => <Router history={history} children={routes}/> }
</Provider>);
React.render(element, dest);
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
const reactRoot = window.document.getElementById('content');
if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) {
console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
}
}
|
// All symbols in the Bopomofo block as per Unicode v3.2.0:
[
'\u3100',
'\u3101',
'\u3102',
'\u3103',
'\u3104',
'\u3105',
'\u3106',
'\u3107',
'\u3108',
'\u3109',
'\u310A',
'\u310B',
'\u310C',
'\u310D',
'\u310E',
'\u310F',
'\u3110',
'\u3111',
'\u3112',
'\u3113',
'\u3114',
'\u3115',
'\u3116',
'\u3117',
'\u3118',
'\u3119',
'\u311A',
'\u311B',
'\u311C',
'\u311D',
'\u311E',
'\u311F',
'\u3120',
'\u3121',
'\u3122',
'\u3123',
'\u3124',
'\u3125',
'\u3126',
'\u3127',
'\u3128',
'\u3129',
'\u312A',
'\u312B',
'\u312C',
'\u312D',
'\u312E',
'\u312F'
]; |
import { expect } from "chai";
import { createFile } from "./index";
describe("index", () => {
describe("createFile", () => {
it("should fail horribly", done => {
createFile()
.then(() => {
throw new Error("test should have failed");
})
.catch(error => {
expect(error).to.be.an("error");
done();
});
});
});
});
|
'use strict';
const { QueryBuilderOperation } = require('./QueryBuilderOperation');
class OnBuildKnexOperation extends QueryBuilderOperation {
constructor(name, opt) {
super(name, opt);
this.func = null;
}
onAdd(_, args) {
this.func = args[0];
return true;
}
onBuildKnex(knexBuilder, builder) {
return this.func.call(knexBuilder, knexBuilder, builder);
}
clone() {
const clone = super.clone();
clone.func = this.func;
return clone;
}
}
module.exports = {
OnBuildKnexOperation,
};
|
const { checkContextForAuth } = require('../../actions/SessionActions')
const { getUserById } = require('../../actions/UserActions')
const schema = `
currentUser: User
getUserById(id: Int!): User
`
const resolvers = {
currentUser: (root, input, context) => {
checkContextForAuth(context)
return getUserById(context.req.user.id)
},
getUserById: (root, { id }, context) => {
checkContextForAuth(context)
return getUserById(id)
}
}
module.exports = {
schema,
resolvers
}
|
export default {
SORT_DESC: 'desc',
SORT_ASC: 'asc',
SIZE_PER_PAGE: 10,
NEXT_PAGE: '>',
LAST_PAGE: '>>',
PRE_PAGE: '<',
FIRST_PAGE: '<<',
PAGE_START_INDEX: 1,
ROW_SELECT_BG_COLOR: '',
ROW_SELECT_NONE: 'none',
ROW_SELECT_SINGLE: 'radio',
ROW_SELECT_MULTI: 'checkbox',
CELL_EDIT_NONE: 'none',
CELL_EDIT_CLICK: 'click',
CELL_EDIT_DBCLICK: 'dbclick',
SIZE_PER_PAGE_LIST: [ 10, 25, 30, 50 ],
PAGINATION_SIZE: 5,
NO_DATA_TEXT: 'There is no data to display',
SHOW_ONLY_SELECT: 'Show Selected Only',
SHOW_ALL: 'Show All',
EXPORT_CSV_TEXT: 'Export to CSV',
INSERT_BTN_TEXT: 'New',
DELETE_BTN_TEXT: 'Delete',
SAVE_BTN_TEXT: 'Save',
CLOSE_BTN_TEXT: 'Close',
FILTER_DELAY: 500,
FILTER_TYPE: {
TEXT: 'TextFilter',
REGEX: 'RegexFilter',
SELECT: 'SelectFilter',
NUMBER: 'NumberFilter',
DATE: 'DateFilter',
CUSTOM: 'CustomFilter'
}
};
|
/*!
* fscloud
* Copyright(c) 2013 Gabriele Di Stefano <gabriele.ds@gmail.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var friend = require('friend')
, fs = friend.fs
, mime = require('mime')
, request = require('request')
, services = require('../../fscloud')
, storage = require('./')
;
/**
* Expose `Client`.
*/
var Client = exports.Client = function (options) {
options = options || {};
if(!options.provider){
options.provider = 'local';
}
if(options.local){
this.local = options.local;
}
services.Client.call(this, options);
this.authUrl = options.authUrl || 'localhost:3012/data';
this.serversUrl = options.serversUrl || 'localhost:3012/data';
//this.provider = 'rackspace';
};
// Extend from Client
friend.inherits(Client, services.Client);
/**
* container()
*/
Client.prototype.container = function(options){
if('string' === typeof options){
options = { local: options };
}
options = options || {};
options.client = this;
return new storage.Container(options);
};
Client.prototype.url = function () {
return this.serviceUrl.apply(this, ['storage'].concat(Array.prototype.slice.call(arguments)));
};
Client.prototype.ls = function (path, callback) {
};
Client.prototype.rm = function (path, callback) {
};
Client.prototype.cp = function (options, callback) {
};
/**
* getFile()
*/
Client.prototype.getFile = function(container, file, callback) {
this.request({
method: 'GET',
url: 'http://localhost:3012/ciao'
}, function (err, res, body) {
//callback(null, true, res);
//console.log('---', body)
//console.dir(typeof body === 'string' ? JSON.parse(body) : body)
});
};
/**
* getFiles()
*/
Client.prototype.getFiles = function(container, download, callback) {
};
/**
* removeFile()
*/
Client.prototype.removeFile = function(container, file, callback) {
// body...
};
/**
* removeFiles()
*/
Client.prototype.removeFiles = function(container, file, callback) {
// body...
};
/**
* upload()
*/
Client.prototype.upload = function(options, callback) {
options = options || {};
var container = options.container,
rstream,
lstream;
if (container instanceof storage.Container) {
container = container.name;
}
if (options.local) {
lstream = fs.createReadStream(options.local);
options.headers = options.headers || {};
options.headers['content-length'] = fs.statSync(options.local).size;
}
else if (options.stream) {
lstream = options.stream;
}
if (options.headers && !options.headers['content-type']) {
options.headers['content-type'] = mime.lookup(options.remote);
}
rstream = this.request({
method: 'PUT',
upload: true,
path: [container, options.remote],
headers: options.headers || {}
}, callback, function (body, res) {
callback(null, true, res);
});
if (lstream) {
lstream.pipe(rstream);
}
return rstream;
};
/**
* download()
*/
Client.prototype.download = function(options, callback) {
options = options || {};
var container = options.container,
lstream,
rstream;
if (container instanceof storage.Container) {
container = container.name;
}
if (options.local) {
lstream = fs.createWriteStream(options.local);
}
else if (options.stream) {
lstream = options.stream;
}
rstream = this.request({
path: [container, options.remote],
download: true
}, callback, function (body, res) {
callback(null, new (storage.File)(self, utile.mixin(res.headers, {
container: container,
name: options.remote
})));
});
if (lstream) {
rstream.pipe(lstream);
}
return rstream;
};
|
/*global ShapeCaptcha dat FontFaceObserver*/
const fontFamily = 'Indie Flower';
const fo = new FontFaceObserver(fontFamily);
fo.load().then(app, function () {
console.log(`Font ${fontFamily} is not available`);
});
function app() {
const $ = id => document.getElementById(id);
const guiContainer = $('guiContainer');
const trigger = $('trigger');
const submitButton = $('submitButton');
const areYou = $('areYou');
const options = {
timeout: 30, // sec
items: 5,
container: '',
font: 'Indie Flower',
bgColor: '#193441',
drawColor: '#91AA9D',
acceptColor: '#3E606F',
textColor: '#3E606F',
textBgColor: '#193441',
helperText: '',
drawLineWidth: 8,
successLineWidth: 8
};
const gui = new dat.GUI({ autoPlace: false });
guiContainer.appendChild(gui.domElement);
gui.add(options, 'container', { page: '', foobar:'#foobar' } );
gui.add(options, 'timeout', 0, 60).step(1);
gui.add(options, 'items', 1, 10).step(1);
gui.add(options, 'helperText');
gui.addColor(options, 'bgColor');
gui.addColor(options, 'drawColor');
gui.addColor(options, 'acceptColor');
gui.addColor(options, 'textColor');
gui.addColor(options, 'textBgColor');
gui.add(options, 'drawLineWidth', 2, 16).step(1);
gui.add(options, 'successLineWidth', 2, 16).step(1);
trigger.addEventListener('change', () => {
ShapeCaptcha.start(options).then(() => {
submitButton.disabled = false;
trigger.checked = true;
trigger.parentNode.style.color = 'green';
trigger.parentNode.style.fontWeight = 'bold';
areYou.style.display = 'none';
})
.catch(() => {
console.log('foooo');
trigger.checked = false;
areYou.style.display = 'inline';
});
});
}
|
$(document).ready(function () {
$(window).scrollPress();
});
|
$(function () {
function count($this) {
var current = parseInt($this.html(), 10);
$this.html(current += 10);
if (current <= $this.data('count')) {
setTimeout(function () { count($this) }, 1);
}
else {
$this.html($this.data('count'))
}
}
$(".count").each(function () {
$(this).data('count', parseInt($(this).html(), 10));
$(this).html('0');
count($(this));
});
}); |
/* @flow */
import React from 'react'
import {
AppRegistry,
StyleSheet,
ListView,
} from 'react-native'
import ItemCell from 'react-native-item-cell'
const items = React.createClass({
getInitialState: function() {
const itemsArray = [
'Item 1',
'Item 2',
'Item 3',
'Settings',
'It appears that the systematic use of complex symbols can be defined in such a way as to impose the extended c-command discussed in connection with (34).',
'With this clarification, any associated supporting element is unspecified with respect to a corpus of utterance tokens upon which conformity has been defined by the paired utterance test.'
]
const dataSource = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
})
return {
ds: dataSource.cloneWithRows(itemsArray)
}
},
_renderRow: function(rowData, sectionID, rowID, highlightRow) {
if (rowID === '1') {
return (
<ItemCell
subtitle='GraphQL is an amazing technology.'
value='7845643'
icon={require('./graphql.png')}>
Local assets icon
</ItemCell>
)
}
if (rowID === '5') {
return (
<ItemCell
icon={{uri: 'https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png'}}>
{`URL Icon - ${rowData}`}
</ItemCell>
)
}
if (rowID === '2') {
return (
<ItemCell showDisclosureIndicator={true} icon={require('./apsl.png')}>
Local image
</ItemCell>
)
}
if (rowID === '3') {
return (
<ItemCell icon={require('./rn.png')} value='Is awesome!'>
React Native
</ItemCell>
)
}
var disclosure = (rowID % 2 === 0) ? true : false;
return (
<ItemCell showDisclosureIndicator={disclosure}>
{rowData}
</ItemCell>
)
},
render: function() {
return (
<ListView
style={styles.container}
contentInset={{top: 0}}
automaticallyAdjustContentInsets={false}
dataSource={this.state.ds}
renderRow={this._renderRow}
/>
)
}
})
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#efedf4',
paddingTop: 20,
},
})
AppRegistry.registerComponent('items', () => items)
|
version https://git-lfs.github.com/spec/v1
oid sha256:f9f31a6bbe215a44bf4ba350fcba1becba81bc0e279f6afba135048ac17d1731
size 5414
|
/*
* VitalSigns
* Copyright 2013 Tom Frost
*/
var should = require('should'),
uptime = require('../../lib/monitors/uptime');
describe("Uptime monitor", function() {
it("should return sys and proc uptime", function() {
var mod = uptime.report();
mod.should.have.property('sys');
mod.should.have.property('proc');
});
it("should return positive values", function() {
var mod = uptime.report();
mod.sys.should.not.be.below(0);
mod.proc.should.not.be.below(0);
});
});
|
import React, { Component } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.scss';
import Link from '../Link';
class Footer extends Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">Home</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">Privacy</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/not-found">Not Found</Link>
</div>
</div>
);
}
}
export default withStyles(Footer, s);
|
export const RESET_ERROR_MESSAGE = 'RESET_ERROR_MESSAGE';
// Resets the currently visible error message.
export function resetErrorMessage() {
return {
type: RESET_ERROR_MESSAGE
};
}
|
import { _, assert, sinonsb } from "../../common";
import Cache from "../../../app/scripts/lib/util/cache";
describe("Cache", () => {
describe("#memoize", () => {
it("memoizes the result of given function", () => {
const cache = new Cache;
const val = cache.memoize("test", () => {
return 123;
});
assert(val === 123);
assert(cache.get("test") === 123);
});
});
describe("#memoizePromise", () => {
it("memoizes the returned Promise from given function", () => {
const cache = new Cache;
return cache.memoizePromise("test", () => {
return Promise.resolve(123);
}).then(resolved => {
assert(resolved === 123);
assert(cache.get("test") === 123);
});
});
it("does not cache rejected Promise", () => {
const cache = new Cache;
return cache.memoizePromise("test", () => {
return Promise.reject(new Error("error test"));
}).catch(err => {
assert(err.message === "error test");
assert(cache.get("test") === undefined);
});
});
});
describe("#get / #set", () => {
it("gets and sets value", () => {
sinonsb.stub(_, "now").returns(1234567890);
const cache = new Cache;
cache.set("test", 123);
assert(cache.get("test") === 123);
assert.deepEqual(cache.getEntry("test"), {
time: 1234567890,
value: 123,
});
});
it("with enabled = false", () => {
const cache = new Cache({ enabled: false });
cache.set("test", 123);
assert(cache.getEntry("test") === null);
});
});
describe("#remove", () => {
it("removes a cache", () => {
const cache = new Cache;
cache.set("test", 123);
cache.remove("test");
assert(_.isUndefined(cache.get("test")));
assert(cache.getEntry("test") === null);
});
});
describe("#flush", () => {
it("removes all caches", () => {
const cache = new Cache;
cache.set("test1", 123);
cache.set("test2", 456);
cache.flush();
assert(cache.getEntry("test1") === null);
assert(cache.getEntry("test2") === null);
});
});
describe("#flushExpired", () => {
it("returns whether the flush ", () => {
const nowStub = sinonsb.stub(_, "now");
const cache = new Cache({ expiresIn: 1000 });
nowStub.returns(0);
cache.set("test1", 123);
nowStub.returns(500);
cache.set("test2", 456);
nowStub.returns(1000);
cache.flushExpired();
assert(cache.getEntry("test1") === null);
assert(cache.getEntry("test2") !== null);
});
});
});
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import Login from './Login';
import Pro from './profile';
import React from 'react';
const title = 'Log In';
export default {
path: '/login',
action() {
return {
title,
component: <Login title={title} />,
};
},
};
const Profile = {
path: '/Profile',
action() {
return {
title: "Profile",
component: <Pro />,
};
}
};
export {Profile} |
(function(){
app.controller('bookmanager',['$scope','$http', 'NgTableParams','$uibModal', function($scope, $http, NgTableParams, $uibModal){
var bookmanager = this;
bookmanager.book = {};
this.books = null;
this.booksParams = null;
$http({
method: 'GET',
url: BASE + "api/books"
}).then(function(data){
bookmanager.books = data.data;
bookmanager.bookParams = new NgTableParams({count: 10}, {counts: [10,50,100], dataset: data.data});
bookmanager.selectedPageSizes = bookmanager.bookParams.count();
bookmanager.availablePageSizes = [5,10,15,20,25,30,40,50,100];
});
bookmanager.changePage = (nextPage) => {
bookmanager.bookParams.page(nextPage);
}
bookmanager.changePageSize = (newSize) => {
bookmanager.bookParams.count(newSize);
}
bookmanager.changePageSizes = (newSizes) => {
if(newSizes.indexOf(bookmanager.bookParams.count()) === -1){
newSizes.push(bookmanager.bookParams.count());
newSizes.sort();
}
bookmanager.bookParams.settings({counts: newSizes});
}
bookmanager.updateBook = (book) => {
let modalInstance = $uibModal.open({
controller: 'UpdateBookController',
controllerAs: 'UBC',
templateUrl: BASE + 'application/views/modals/UpdateBook.php',
resolve: {
book: () => {
return book;
}
}
});
modalInstance.result.then((updatedItem)=>{
angular.copy(updatedItem, book);
},()=>{
console.log("DISMISSED");
});
}
bookmanager.removeBook = (book) => {
console.log(JSON.stringify(book));
$http({
method: 'DELETE',
data: book.NO,
url: BASE + "api/books"
}).then(function(data){
bookmanager.books.splice(bookmanager.books.indexOf(book), 1);
bookmanager.bookParams.reload();
});
}
bookmanager.addBook = () => {
$http({
method: 'POST',
data: bookmanager.book,
url: BASE + "api/books"
}).then(function(data){
console.log(data);
bookmanager.book = {}
bookmanager.books.push(data.data);
bookmanager.bookParams.reload();
});
}
}]);
app.controller("UpdateBookController", ['$uibModalInstance', 'book', '$http', function($uibModalInstance, book, $http){
this.newBook = angular.copy(book),
this.update = ()=>{
$http({
method: 'PUT',
data: this.newBook,
url: BASE + "api/books"
}).then(function(data){
console.log(data);
});
$uibModalInstance.close(this.newBook);
}
this.cancel = ()=>{
$uibModalInstance.dismiss();
}
}]);
})(); |
/*!
Buttons for DataTables 1.2.0
©2016 SpryMedia Ltd - datatables.net/license
*/
(function(d){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(o){return d(o,window,document)}):"object"===typeof exports?module.exports=function(o,n){o||(o=window);if(!n||!n.fn.dataTable)n=require("datatables.net")(o,n).$;return d(n,o,o.document)}:d(jQuery,window,document)})(function(d,o,n,l){var i=d.fn.dataTable,u=0,v=0,k=i.ext.buttons,m=function(a,b){!0===b&&(b={});d.isArray(b)&&(b={buttons:b});this.c=d.extend(!0,{},m.defaults,b);b.buttons&&(this.c.buttons=b.buttons);
this.s={dt:new i.Api(a),buttons:[],listenKeys:"",namespace:"dtb"+u++};this.dom={container:d("<"+this.c.dom.container.tag+"/>").addClass(this.c.dom.container.className)};this._constructor()};d.extend(m.prototype,{action:function(a,b){var c=this._nodeToButton(a);if(b===l)return c.conf.action;c.conf.action=b;return this},active:function(a,b){var c=this._nodeToButton(a),e=this.c.dom.button.active,c=d(c.node);if(b===l)return c.hasClass(e);c.toggleClass(e,b===l?!0:b);return this},add:function(a,b){var c=
this.s.buttons;if("string"===typeof b){for(var e=b.split("-"),c=this.s,d=0,h=e.length-1;d<h;d++)c=c.buttons[1*e[d]];c=c.buttons;b=1*e[e.length-1]}this._expandButton(c,a,!1,b);this._draw();return this},container:function(){return this.dom.container},disable:function(a){a=this._nodeToButton(a);d(a.node).addClass(this.c.dom.button.disabled);return this},destroy:function(){d("body").off("keyup."+this.s.namespace);var a=this.s.buttons,b,c;b=0;for(c=a.length;b<c;b++)this.remove(a[b].node);this.dom.container.remove();
a=this.s.dt.settings()[0];b=0;for(c=a.length;b<c;b++)if(a.inst===this){a.splice(b,1);break}return this},enable:function(a,b){if(!1===b)return this.disable(a);var c=this._nodeToButton(a);d(c.node).removeClass(this.c.dom.button.disabled);return this},name:function(){return this.c.name},node:function(a){a=this._nodeToButton(a);return d(a.node)},remove:function(a){var b=this._nodeToButton(a),c=this._nodeToHost(a),e=this.s.dt;if(b.buttons.length)for(var g=b.buttons.length-1;0<=g;g--)this.remove(b.buttons[g].node);
b.conf.destroy&&b.conf.destroy.call(e.button(a),e,d(a),b.conf);this._removeKey(b.conf);d(b.node).remove();a=d.inArray(b,c);c.splice(a,1);return this},text:function(a,b){var c=this._nodeToButton(a),e=this.c.dom.collection.buttonLiner,e=c.inCollection&&e&&e.tag?e.tag:this.c.dom.buttonLiner.tag,g=this.s.dt,h=d(c.node),f=function(a){return"function"===typeof a?a(g,h,c.conf):a};if(b===l)return f(c.conf.text);c.conf.text=b;e?h.children(e).html(f(b)):h.html(f(b));return this},_constructor:function(){var a=
this,b=this.s.dt,c=b.settings()[0],e=this.c.buttons;c._buttons||(c._buttons=[]);c._buttons.push({inst:this,name:this.c.name});for(var c=0,g=e.length;c<g;c++)this.add(e[c]);b.on("destroy",function(){a.destroy()});d("body").on("keyup."+this.s.namespace,function(b){if(!n.activeElement||n.activeElement===n.body){var c=String.fromCharCode(b.keyCode).toLowerCase();a.s.listenKeys.toLowerCase().indexOf(c)!==-1&&a._keypress(c,b)}})},_addKey:function(a){a.key&&(this.s.listenKeys+=d.isPlainObject(a.key)?a.key.key:
a.key)},_draw:function(a,b){a||(a=this.dom.container,b=this.s.buttons);a.children().detach();for(var c=0,d=b.length;c<d;c++)a.append(b[c].inserter),b[c].buttons&&b[c].buttons.length&&this._draw(b[c].collection,b[c].buttons)},_expandButton:function(a,b,c,e){for(var g=this.s.dt,h=0,b=!d.isArray(b)?[b]:b,f=0,q=b.length;f<q;f++){var j=this._resolveExtends(b[f]);if(j)if(d.isArray(j))this._expandButton(a,j,c,e);else{var p=this._buildButton(j,c);if(p){e!==l?(a.splice(e,0,p),e++):a.push(p);if(p.conf.buttons){var s=
this.c.dom.collection;p.collection=d("<"+s.tag+"/>").addClass(s.className);p.conf._collection=p.collection;this._expandButton(p.buttons,p.conf.buttons,!0,e)}j.init&&j.init.call(g.button(p.node),g,d(p.node),j);h++}}}},_buildButton:function(a,b){var c=this.c.dom.button,e=this.c.dom.buttonLiner,g=this.c.dom.collection,h=this.s.dt,f=function(b){return"function"===typeof b?b(h,j,a):b};b&&g.button&&(c=g.button);b&&g.buttonLiner&&(e=g.buttonLiner);if(a.available&&!a.available(h,a))return!1;var q=function(a,
b,c,e){e.action.call(b.button(c),a,b,c,e);d(b.table().node()).triggerHandler("buttons-action.dt",[b.button(c),b,c,e])},j=d("<"+c.tag+"/>").addClass(c.className).attr("tabindex",this.s.dt.settings()[0].iTabIndex).attr("aria-controls",this.s.dt.table().node().id).on("click.dtb",function(b){b.preventDefault();!j.hasClass(c.disabled)&&a.action&&q(b,h,j,a);j.blur()}).on("keyup.dtb",function(b){b.keyCode===13&&!j.hasClass(c.disabled)&&a.action&&q(b,h,j,a)});"a"===c.tag.toLowerCase()&&j.attr("href","#");
e.tag?(g=d("<"+e.tag+"/>").html(f(a.text)).addClass(e.className),"a"===e.tag.toLowerCase()&&g.attr("href","#"),j.append(g)):j.html(f(a.text));!1===a.enabled&&j.addClass(c.disabled);a.className&&j.addClass(a.className);a.titleAttr&&j.attr("title",a.titleAttr);a.namespace||(a.namespace=".dt-button-"+v++);e=(e=this.c.dom.buttonContainer)&&e.tag?d("<"+e.tag+"/>").addClass(e.className).append(j):j;this._addKey(a);return{conf:a,node:j.get(0),inserter:e,buttons:[],inCollection:b,collection:null}},_nodeToButton:function(a,
b){b||(b=this.s.buttons);for(var c=0,d=b.length;c<d;c++){if(b[c].node===a)return b[c];if(b[c].buttons.length){var g=this._nodeToButton(a,b[c].buttons);if(g)return g}}},_nodeToHost:function(a,b){b||(b=this.s.buttons);for(var c=0,d=b.length;c<d;c++){if(b[c].node===a)return b;if(b[c].buttons.length){var g=this._nodeToHost(a,b[c].buttons);if(g)return g}}},_keypress:function(a,b){var c=function(e){for(var g=0,h=e.length;g<h;g++){var f=e[g].conf,q=e[g].node;if(f.key)if(f.key===a)d(q).click();else if(d.isPlainObject(f.key)&&
f.key.key===a&&(!f.key.shiftKey||b.shiftKey))if(!f.key.altKey||b.altKey)if(!f.key.ctrlKey||b.ctrlKey)(!f.key.metaKey||b.metaKey)&&d(q).click();e[g].buttons.length&&c(e[g].buttons)}};c(this.s.buttons)},_removeKey:function(a){if(a.key){var b=d.isPlainObject(a.key)?a.key.key:a.key,a=this.s.listenKeys.split(""),b=d.inArray(b,a);a.splice(b,1);this.s.listenKeys=a.join("")}},_resolveExtends:function(a){for(var b=this.s.dt,c,e,g=function(c){for(var e=0;!d.isPlainObject(c)&&!d.isArray(c);){if(c===l)return;
if("function"===typeof c){if(c=c(b,a),!c)return!1}else if("string"===typeof c){if(!k[c])throw"Unknown button type: "+c;c=k[c]}e++;if(30<e)throw"Buttons: Too many iterations";}return d.isArray(c)?c:d.extend({},c)},a=g(a);a&&a.extend;){if(!k[a.extend])throw"Cannot extend unknown button type: "+a.extend;var h=g(k[a.extend]);if(d.isArray(h))return h;if(!h)return!1;c=h.className;a=d.extend({},h,a);c&&a.className!==c&&(a.className=c+" "+a.className);var f=a.postfixButtons;if(f){a.buttons||(a.buttons=[]);
c=0;for(e=f.length;c<e;c++)a.buttons.push(f[c]);a.postfixButtons=null}if(f=a.prefixButtons){a.buttons||(a.buttons=[]);c=0;for(e=f.length;c<e;c++)a.buttons.splice(c,0,f[c]);a.prefixButtons=null}a.extend=h.extend}return a}});m.background=function(a,b,c){c===l&&(c=400);a?d("<div/>").addClass(b).css("display","none").appendTo("body").fadeIn(c):d("body > div."+b).fadeOut(c,function(){d(this).remove()})};m.instanceSelector=function(a,b){if(!a)return d.map(b,function(a){return a.inst});var c=[],e=d.map(b,
function(a){return a.name}),g=function(a){if(d.isArray(a))for(var f=0,q=a.length;f<q;f++)g(a[f]);else"string"===typeof a?-1!==a.indexOf(",")?g(a.split(",")):(a=d.inArray(d.trim(a),e),-1!==a&&c.push(b[a].inst)):"number"===typeof a&&c.push(b[a].inst)};g(a);return c};m.buttonSelector=function(a,b){for(var c=[],e=function(a,b,c){for(var d,g,f=0,h=b.length;f<h;f++)if(d=b[f])g=c!==l?c+f:f+"",a.push({node:d.node,name:d.conf.name,idx:g}),d.buttons&&e(a,d.buttons,g+"-")},g=function(a,b){var f,h,i=[];e(i,b.s.buttons);
f=d.map(i,function(a){return a.node});if(d.isArray(a)||a instanceof d){f=0;for(h=a.length;f<h;f++)g(a[f],b)}else if(null===a||a===l||"*"===a){f=0;for(h=i.length;f<h;f++)c.push({inst:b,node:i[f].node})}else if("number"===typeof a)c.push({inst:b,node:b.s.buttons[a].node});else if("string"===typeof a)if(-1!==a.indexOf(",")){i=a.split(",");f=0;for(h=i.length;f<h;f++)g(d.trim(i[f]),b)}else if(a.match(/^\d+(\-\d+)*$/))f=d.map(i,function(a){return a.idx}),c.push({inst:b,node:i[d.inArray(a,f)].node});else if(-1!==
a.indexOf(":name")){var k=a.replace(":name","");f=0;for(h=i.length;f<h;f++)i[f].name===k&&c.push({inst:b,node:i[f].node})}else d(f).filter(a).each(function(){c.push({inst:b,node:this})});else"object"===typeof a&&a.nodeName&&(i=d.inArray(a,f),-1!==i&&c.push({inst:b,node:f[i]}))},h=0,f=a.length;h<f;h++)g(b,a[h]);return c};m.defaults={buttons:["copy","excel","csv","pdf","print"],name:"main",tabIndex:0,dom:{container:{tag:"div",className:"dt-buttons"},collection:{tag:"div",className:"dt-button-collection"},
button:{tag:"a",className:"dt-button",active:"active",disabled:"disabled"},buttonLiner:{tag:"span",className:""}}};m.version="1.2.0";d.extend(k,{collection:{text:function(a){return a.i18n("buttons.collection","Collection")},className:"buttons-collection",action:function(a,b,c,e){var a=c.offset(),g=d(b.table().container()),h=!1;d("div.dt-button-background").length&&(h=d("div.dt-button-collection").offset(),d("body").trigger("click.dtb-collection"));e._collection.addClass(e.collectionLayout).css("display",
"none").appendTo("body").fadeIn(e.fade);var f=e._collection.css("position");h&&"absolute"===f?e._collection.css({top:h.top+5,left:h.left+5}):"absolute"===f?(e._collection.css({top:a.top+c.outerHeight(),left:a.left}),c=a.left+e._collection.outerWidth(),g=g.offset().left+g.width(),c>g&&e._collection.css("left",a.left-(c-g))):(a=e._collection.height()/2,a>d(o).height()/2&&(a=d(o).height()/2),e._collection.css("marginTop",-1*a));e.background&&m.background(!0,e.backgroundClassName,e.fade);setTimeout(function(){d("div.dt-button-background").on("click.dtb-collection",
function(){});d("body").on("click.dtb-collection",function(a){if(!d(a.target).parents().andSelf().filter(e._collection).length){e._collection.fadeOut(e.fade,function(){e._collection.detach()});d("div.dt-button-background").off("click.dtb-collection");m.background(false,e.backgroundClassName,e.fade);d("body").off("click.dtb-collection");b.off("buttons-action.b-internal")}})},10);if(e.autoClose)b.on("buttons-action.b-internal",function(){d("div.dt-button-background").click()})},background:!0,collectionLayout:"",
backgroundClassName:"dt-button-background",autoClose:!1,fade:400},copy:function(a,b){if(k.copyHtml5)return"copyHtml5";if(k.copyFlash&&k.copyFlash.available(a,b))return"copyFlash"},csv:function(a,b){if(k.csvHtml5&&k.csvHtml5.available(a,b))return"csvHtml5";if(k.csvFlash&&k.csvFlash.available(a,b))return"csvFlash"},excel:function(a,b){if(k.excelHtml5&&k.excelHtml5.available(a,b))return"excelHtml5";if(k.excelFlash&&k.excelFlash.available(a,b))return"excelFlash"},pdf:function(a,b){if(k.pdfHtml5&&k.pdfHtml5.available(a,
b))return"pdfHtml5";if(k.pdfFlash&&k.pdfFlash.available(a,b))return"pdfFlash"},pageLength:function(a){var a=a.settings()[0].aLengthMenu,b=d.isArray(a[0])?a[0]:a,c=d.isArray(a[0])?a[1]:a,e=function(a){return a.i18n("buttons.pageLength",{"-1":"Show all rows",_:"Show %d rows"},a.page.len())};return{extend:"collection",text:e,className:"buttons-page-length",autoClose:!0,buttons:d.map(b,function(a,b){return{text:c[b],action:function(b,c){c.page.len(a).draw()},init:function(b,c,d){var e=this,c=function(){e.active(b.page.len()===
a)};b.on("length.dt"+d.namespace,c);c()},destroy:function(a,b,c){a.off("length.dt"+c.namespace)}}}),init:function(a,b,c){var d=this;a.on("length.dt"+c.namespace,function(){d.text(e(a))})},destroy:function(a,b,c){a.off("length.dt"+c.namespace)}}}});i.Api.register("buttons()",function(a,b){b===l&&(b=a,a=l);return this.iterator(!0,"table",function(c){if(c._buttons)return m.buttonSelector(m.instanceSelector(a,c._buttons),b)},!0)});i.Api.register("button()",function(a,b){var c=this.buttons(a,b);1<c.length&&
c.splice(1,c.length);return c});i.Api.registerPlural("buttons().active()","button().active()",function(a){return a===l?this.map(function(a){return a.inst.active(a.node)}):this.each(function(b){b.inst.active(b.node,a)})});i.Api.registerPlural("buttons().action()","button().action()",function(a){return a===l?this.map(function(a){return a.inst.action(a.node)}):this.each(function(b){b.inst.action(b.node,a)})});i.Api.register(["buttons().enable()","button().enable()"],function(a){return this.each(function(b){b.inst.enable(b.node,
a)})});i.Api.register(["buttons().disable()","button().disable()"],function(){return this.each(function(a){a.inst.disable(a.node)})});i.Api.registerPlural("buttons().nodes()","button().node()",function(){var a=d();d(this.each(function(b){a=a.add(b.inst.node(b.node))}));return a});i.Api.registerPlural("buttons().text()","button().text()",function(a){return a===l?this.map(function(a){return a.inst.text(a.node)}):this.each(function(b){b.inst.text(b.node,a)})});i.Api.registerPlural("buttons().trigger()",
"button().trigger()",function(){return this.each(function(a){a.inst.node(a.node).trigger("click")})});i.Api.registerPlural("buttons().containers()","buttons().container()",function(){var a=d();d(this.each(function(b){a=a.add(b.inst.container())}));return a});i.Api.register("button().add()",function(a,b){1===this.length&&this[0].inst.add(b,a);return this.button(a)});i.Api.register("buttons().destroy()",function(){this.pluck("inst").unique().each(function(a){a.destroy()});return this});i.Api.registerPlural("buttons().remove()",
"buttons().remove()",function(){this.each(function(a){a.inst.remove(a.node)});return this});var r;i.Api.register("buttons.info()",function(a,b,c){var e=this;if(!1===a)return d("#datatables_buttons_info").fadeOut(function(){d(this).remove()}),clearTimeout(r),r=null,this;r&&clearTimeout(r);d("#datatables_buttons_info").length&&d("#datatables_buttons_info").remove();d('<div id="datatables_buttons_info" class="dt-button-info"/>').html(a?"<h2>"+a+"</h2>":"").append(d("<div/>")["string"===typeof b?"html":
"append"](b)).css("display","none").appendTo("body").fadeIn();c!==l&&0!==c&&(r=setTimeout(function(){e.buttons.info(!1)},c));return this});i.Api.register("buttons.exportData()",function(a){if(this.context.length){for(var b=new i.Api(this.context[0]),c=d.extend(!0,{},{rows:null,columns:"",modifier:{search:"applied",order:"applied"},orthogonal:"display",stripHtml:!0,stripNewlines:!0,decodeEntities:!0,trim:!0,format:{header:function(a){return e(a)},footer:function(a){return e(a)},body:function(a){return e(a)}}},
a),e=function(a){if("string"!==typeof a)return a;c.stripHtml&&(a=a.replace(/<[^>]*>/g,""));c.trim&&(a=a.replace(/^\s+|\s+$/g,""));c.stripNewlines&&(a=a.replace(/\n/g," "));c.decodeEntities&&(t.innerHTML=a,a=t.value);return a},a=b.columns(c.columns).indexes().map(function(a){return c.format.header(b.column(a).header().innerHTML,a)}).toArray(),g=b.table().footer()?b.columns(c.columns).indexes().map(function(a){var d=b.column(a).footer();return c.format.footer(d?d.innerHTML:"",a)}).toArray():null,h=
b.rows(c.rows,c.modifier).indexes().toArray(),h=b.cells(h,c.columns).render(c.orthogonal).toArray(),f=a.length,k=0<f?h.length/f:0,j=Array(k),m=0,l=0;l<k;l++){for(var o=Array(f),n=0;n<f;n++)o[n]=c.format.body(h[m],n,l),m++;j[l]=o}return{header:a,footer:g,body:j}}});var t=d("<textarea/>")[0];d.fn.dataTable.Buttons=m;d.fn.DataTable.Buttons=m;d(n).on("init.dt plugin-init.dt",function(a,b){if("dt"===a.namespace){var c=b.oInit.buttons||i.defaults.buttons;c&&!b._buttons&&(new m(b,c)).container()}});i.ext.feature.push({fnInit:function(a){var a=
new i.Api(a),b=a.init().buttons||i.defaults.buttons;return(new m(a,b)).container()},cFeature:"B"});return m});
|
var chalk = require('chalk');
module.exports = function(io, models){
var cleardb = require('../../app/models/dbConnection');
//Se importa el modelo
var Alumno = models.alumno;
var Deposito = models.deposito;
var Carrera = models.carrera;
var Usuario = models.usuario;
var Grupo = models.grupo;
var multer = require('multer');
var fs = require('fs');
var glob = require("glob");
var path = require('path');
var router = require('express').Router();
var DIR = './uploads/';
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, DIR)
},
/*filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname)) //Appending extension
}*/
});
var upload = multer({ storage: storage });
// POST /api/Alumno
/*
* Registra un nuevo objeto de esta entidad
*/
router.route('/Alumno')
.post(function(req, res) {
/*Usuario.create({
email: req.body.user.email,
password: req.body.user.password,
rol: "alumno",
})*/
console.log(chalk.red(req.body.email));
Usuario.findOrCreate({
where: {email: req.body.user.email},
defaults: {password: req.body.user.password, rol: 'alumno'}})
.spread((usuario, created) => {
console.log(usuario.get({
plain: true
}))
console.log(created)
if(created){
Alumno.create({
Nombre: req.body.alumno.Nombre,
ApellidoP: req.body.alumno.ApellidoP,
ApellidoM: req.body.alumno.ApellidoM,
FechaNac: req.body.alumno.FechaNac,
_carrera: req.body.alumno._carrera,
NumHijos: req.body.alumno.NumHijos,
Sexo: req.body.alumno.Sexo,
EstadoCivil: req.body.alumno.EstadoCivil,
PadreTutor: req.body.alumno.PadreTutor,
RFC: req.body.alumno.RFC,
Curp: req.body.alumno.Curp,
GrupoEtnico: req.body.alumno.GrupoEtnico,
TrabajoDeAlumno: req.body.alumno.TrabajoDeAlumno,
NumDependientes: req.body.alumno.NumDependientes,
Municipio: req.body.alumno.Municipio,
Estado: req.body.alumno.Estado,
Pais: req.body.alumno.Pais,
Extranjero: req.body.alumno.Extranjero,
PadresExtranjeros: req.body.alumno.PadresExtranjeros,
Peso: req.body.alumno.Peso,
Estatura: req.body.alumno.Estatura,
TipoSangre: req.body.alumno.TipoSangre,
AntecedMedicos: req.body.alumno.AntecedMedicos,
OtroAnteced: req.body.alumno.OtroAnteced,
discapacidad: req.body.alumno.discapacidad,
NumSeguroSocial: req.body.alumno.NumSeguroSocial,
Calle: req.body.alumno.Calle,
Colonia: req.body.alumno.Colonia,
Ciudad: req.body.alumno.Ciudad,
NumExterior: req.body.alumno.NumExterior,
CodPost: req.body.alumno.CodPost,
EstadoDomi: req.body.alumno.EstadoDomi,
TelefonoCasa: req.body.alumno.TelefonoCasa,
TelefonoCel: req.body.alumno.TelefonoCel,
Facebook: req.body.alumno.Facebook,
Preparatoria: req.body.alumno.Preparatoria,
Especialidad: req.body.alumno.Especialidad,
PromedioFinal: req.body.alumno.PromedioFinal,
Semestre: req.body.alumno.Semestre,
PreparatoriaEstado: req.body.alumno.PreparatoriaEstado,
TurnoParaEntrevist: req.body.alumno.TurnoParaEntrevist,
Medios: req.body.alumno.Medios,
NumInstitucionesConsidera: req.body.alumno.NumInstitucionesConsidera,
JustificacionDeEleccion: req.body.alumno.JustificacionDeEleccion
})
.then(function(alumnoCreado){
usuario.setAlumno(alumnoCreado);
io.sockets.emit('AlumnoCreado',alumnoCreado);
res.json(alumnoCreado);
})
}
else{
console.log(created);
res.json(created);
}
})
/*.then(function(usuario){
console.log(chalk.red("FECHA DE NACIMIENTO: ",req.body.alumno.FechaNac));
Alumno.create({
Nombre: req.body.alumno.Nombre,
ApellidoP: req.body.alumno.ApellidoP,
ApellidoM: req.body.alumno.ApellidoM,
FechaNac: req.body.alumno.FechaNac,
_carrera: req.body.alumno._carrera,
NumHijos: req.body.alumno.NumHijos,
Sexo: req.body.alumno.Sexo,
EstadoCivil: req.body.alumno.EstadoCivil,
PadreTutor: req.body.alumno.PadreTutor,
RFC: req.body.alumno.RFC,
Curp: req.body.alumno.Curp,
GrupoEtnico: req.body.alumno.GrupoEtnico,
TrabajoDeAlumno: req.body.alumno.TrabajoDeAlumno,
NumDependientes: req.body.alumno.NumDependientes,
Municipio: req.body.alumno.Municipio,
Estado: req.body.alumno.Estado,
Pais: req.body.alumno.Pais,
Extranjero: req.body.alumno.Extranjero,
PadresExtranjeros: req.body.alumno.PadresExtranjeros,
Peso: req.body.alumno.Peso,
Estatura: req.body.alumno.Estatura,
TipoSangre: req.body.alumno.TipoSangre,
AntecedMedicos: req.body.alumno.AntecedMedicos,
OtroAnteced: req.body.alumno.OtroAnteced,
discapacidad: req.body.alumno.discapacidad,
NumSeguroSocial: req.body.alumno.NumSeguroSocial,
Calle: req.body.alumno.Calle,
Colonia: req.body.alumno.Colonia,
Ciudad: req.body.alumno.Ciudad,
NumExterior: req.body.alumno.NumExterior,
CodPost: req.body.alumno.CodPost,
EstadoDomi: req.body.alumno.EstadoDomi,
TelefonoCasa: req.body.alumno.TelefonoCasa,
TelefonoCel: req.body.alumno.TelefonoCel,
Facebook: req.body.alumno.Facebook,
Preparatoria: req.body.alumno.Preparatoria,
Especialidad: req.body.alumno.Especialidad,
PromedioFinal: req.body.alumno.PromedioFinal,
Semestre: req.body.alumno.Semestre,
PreparatoriaEstado: req.body.alumno.PreparatoriaEstado,
TurnoParaEntrevist: req.body.alumno.TurnoParaEntrevist,
Medios: req.body.alumno.Medios,
NumInstitucionesConsidera: req.body.alumno.NumInstitucionesConsidera,
JustificacionDeEleccion: req.body.alumno.JustificacionDeEleccion
})
.then(function(alumnoCreado){
usuario.setAlumno(alumnoCreado);
io.sockets.emit('AlumnoCreado',alumnoCreado);
res.json(alumnoCreado);
})
})*/
});
// PUT /api/Alumno
/*
* Edita un objeto de esta entidad
*/
router.route('/Alumno')
.put(function(req, res) {
// Busca instancia existente en la base de datos
Alumno.findById(req.body._id)
.then(alumno => {
console.log(req.body.Nombre);
var Nombre = req.body.Nombre;
var ApellidoP = req.body.ApellidoP;
var ApellidoM = req.body.ApellidoM;
var FechaNac = req.body.FechaNac;
var noMatricula = req.body.noMatricula;
var NumHijos = req.body.NumHijos;
var Sexo = req.body.Sexo;
var EstadoCivil = req.body.EstadoCivil;
var PadreTutor = req.body.PadreTutor;
var RFC = req.body.RFC;
var Curp = req.body.Curp;
var GrupoEtnico = req.body.GrupoEtnico;
var TrabajoDeAlumno = req.body.TrabajoDeAlumno;
var NumDependientes = req.body.NumDependientes;
var Municipio = req.body.Municipio;
var Estado = req.body.Estado;
var Pais = req.body.Pais;
var Extranjero = req.body.Extranjero;
var PadresExtranjeros = req.body.PadresExtranjeros;
var Peso = req.body.Peso;
var Estatura = req.body.Estatura;
var TipoSangre = req.body.TipoSangre;
var AntecedMedicos = req.body.AntecedMedicos;
var OtroAnteced = req.body.OtroAnteced;
var discapacidad = req.body.discapacidad;
var NumSeguroSocial = req.body.NumSeguroSocial;
var Calle = req.body.Calle;
var Colonia = req.body.Colonia;
var Ciudad = req.body.Ciudad;
var NumExterior = req.body.NumExterior;
var CodPost = req.body.CodPost;
var EstadoDomi = req.body.EstadoDomi;
var TelefonoCasa = req.body.TelefonoCasa;
var TelefonoCel = req.body.TelefonoCel;
var Facebook = req.body.Facebook;
var Preparatoria = req.body.Preparatoria;
var Especialidad = req.body.Especialidad;
var PromedioFinal = req.body.PromedioFinal;
var Semestre = req.body.Semestre;
var PreparatoriaEstado = req.body.PreparatoriaEstado;
var TurnoParaEntrevist = req.body.TurnoParaEntrevist;
var Medios = req.body.Medios;
var NumInstitucionesConsidera = req.body.NumInstitucionesConsidera;
var JustificacionDeEleccion = req.body.JustificacionDeEleccion;
var tempCarreraID = alumnoEditado._carrera;
var _carrera = req.body._carrera;
console.log("CARRERA: "+_carrera);
alumno.updateAttributes({
Nombre: Nombre,
ApellidoP: ApellidoP,
ApellidoM: ApellidoM,
FechaNac: FechaNac,
noMatricula: noMatricula,
_carrera: _carrera,
NumHijos: NumHijos,
Sexo: Sexo,
EstadoCivil: EstadoCivil,
PadreTutor: PadreTutor,
RFC: RFC,
Curp: Curp,
GrupoEtnico: GrupoEtnico,
TrabajoDeAlumno: TrabajoDeAlumno,
NumDependientes: NumDependientes,
Municipio: Municipio,
Estado: Estado,
Pais: Pais,
Extranjero: Extranjero,
PadresExtranjeros: PadresExtranjeros,
Peso: Peso,
Estatura: Estatura,
TipoSangre: TipoSangre,
AntecedMedicos: AntecedMedicos,
OtroAnteced: OtroAnteced,
discapacidad: discapacidad,
NumSeguroSocial: NumSeguroSocial,
Calle: Calle,
Colonia: Colonia,
Ciudad: Ciudad,
NumExterior: NumExterior,
CodPost: CodPost,
EstadoDomi: EstadoDomi,
TelefonoCasa: TelefonoCasa,
TelefonoCel: TelefonoCel,
Facebook: Facebook,
Preparatoria: Preparatoria,
Especialidad: Especialidad,
PromedioFinal: PromedioFinal,
Semestre: Semestre,
PreparatoriaEstado: PreparatoriaEstado,
TurnoParaEntrevist: TurnoParaEntrevist,
Medios: Medios,
NumInstitucionesConsidera: NumInstitucionesConsidera,
JustificacionDeEleccion: JustificacionDeEleccion
})
.then(alumnoEditado =>{
io.sockets.emit('AlumnoEditado',alumnoEditado);
res.json(alumnoEditado);
})
})
});
// POST /api/Alumno/buscar
/*
* Buscador por nombre, carrera y/o grupo
*/
router.route('/Alumno/buscar')
.post(function(req, res) {
console.log(chalk.blue("POST /api/Alumno/buscar"));
console.log(chalk.blue('Nombre:')+chalk.red(req.body.Nombre));
console.log(chalk.blue('Carrera:')+chalk.red(req.body._carrera));
var nombre = req.body.Nombre;
//Listado de todas las Alumnos
Alumno.findAll({
/*$and:[
//Busca aquellos inscritos, al omitir aquellos que tengan campos nulos
{_carrera:req.body._carrera?req.body._carrera:{$ne:null}},
{_grupo:req.body._grupo?req.body._grupo:{$ne:null}},
{$or:[
{ApellidoM:regexNombre},
{ApellidoP:regexNombre},
{Nombre:regexNombre},
]}
]*/
where:{
$and:{
_carrera: req.body._carrera?req.body._carrera:{$ne:null},
_grupo:req.body._grupo?req.body._grupo:{$ne:null},
$or:{
Nombre:{
$like: '%'+nombre+'%'
},
ApellidoP:{
$like: '%'+nombre+'%'
},
ApellidoM:{
$like: '%'+nombre+'%'
}
}
}
},
include:[Grupo]
}).then(alumnos => {
res.json(alumnos);
});
});
// GET /api/Alumno/:soloPreinscritos
/*
* Entrega un listado completo de todos los alumnos preinscritos
*/
router.route('/Alumno/')
.get(function(req, res) {
//Listado de todas las Alumnos
Alumno.find().populate("_carrera").exec(function(err,Alumnos) {
//console.log(Alumnos);
if (err){console.log(chalk.red('Error: '+err));res.send(err);
}else{
res.json(Alumnos);
}
});
});
// GET /api/Alumno/:soloPreinscritos
/*
* Entrega un listado completo de todos los alumnos preinscritos
*/
router.route('/Alumno/soloPreinscritos')
.get(function(req, res) {
Alumno.findAll({
where: {
_grupo: null
}, include: [Carrera]
}).then(alumnos => {
console.log(alumnos);
res.json(alumnos);
});
});
// DELETE /api/Alumno:id
/*
* Elimina el registro identificado por el ID indicado
*/
router.route('/Alumno/:id')
.delete(function(req, res) {
var id = req.params.id;
console.log("IDE PARA BORRAR: ",req.params.id);
Alumno.destroy({
where: {
_id: id
}
})
.then(deletedAlumno => {
io.sockets.emit('AlumnoEliminado',deletedAlumno);
res.json(deletedAlumno);
});
});
// GET /api/Alumno:id
/*
* Entrega toda la informacion concreta dado
* un ID sobre un registro especifico de esta entidad
*/
router.route('/Alumno/:id')
.get(function(req, res) {
var id = req.params.id;
//Se busca por ID
Alumno.findOne({
where:{
_id:id
},
include:[Carrera,Grupo,Deposito,Usuario]
})
.then(alumno=>{
console.log(chalk.green(alumno.FechaNac));
res.json(alumno);
})
});
// GET //Alumno/getUser/:id
/*
* Entrega toda la informacion concreta dado
* un ID sobre un registro especifico de esta entidad, para los usuarios Alumno
*/
router.route('/Alumno/getUser/:id')
.get(function(req, res) {
var id = req.params.id;
console.log("SE ESTA BUSCANDO");
//Se busca por ID
Alumno.findOne({
where:{
_usuario:id
},
include:[Carrera,Grupo]
})
.then(alumno=>{
console.log(chalk.red(alumno));
res.json(alumno);
})
});
router.post('/Alumno/upload/:id', upload.single("file"), function(req, res, next) {
// req.body contains the text fields
console.log(req.params.id);
console.log(req.body.tipoDocumento);
console.log(req.file.mimetype);
var nombre = req.file.filename;
Alumno.find({
where:{
_id: req.params.id
}
})
.then(alumno=>{
fs.rename('./uploads/'+nombre, './documentos/'+req.body.tipoDocumento+'/'
+alumno.noMatricula+path.extname(req.file.originalname), function(err) {
if ( err ) console.log('ERROR: ' + err);
});
console.log("Fuera de callback");
res.json('file uploaded');
next();
})
/*fs.rename('./uploads/'+nombre, './documentos/'+req.body.tipoDocumento+'/'
+nombre+path.extname(req.file.originalname), function(err) {
if ( err ) console.log('ERROR: ' + err);
});
console.log("Fuera de callback");
res.json('file uploaded');
next();*/
});
router.route('/descargarDocumento/:id/:tipo')
.get(function (req, res) {
var formato = ['.jpg','.pdf','.png'];
console.log(req.params.id);
console.log(req.params.tipo);
Alumno.find({
where:{
_id: req.params.id
}
})
.then(alumno=>{
for(var i=0; j=2,i<=j; i++){
var existe = fs.existsSync('./documentos/'+req.params.tipo+'/'+alumno.noMatricula+formato[i])
if (existe == true){
res.download('./documentos/'+req.params.tipo+'/'+alumno.noMatricula+formato[i])
}
}
})
});
router.route('/verificarDocumento/:matricula')
.get(function (req, res) {
var formato = ['.jpg','.pdf','.png'];
var tipo = ["acta","constancia"];
console.log(req.params.matricula);
matricula = req.params.matricula;
var existencia = new Array();
for(var i=0; i<=1; i++){
for(var j=0; j<=2; j++){
var existe = fs.existsSync('./documentos/'+tipo[i]+'/'+matricula+formato[j])
existencia.push({tipo:tipo[i],existe:existe});
}
}
console.log(existencia);
res.json(existencia);
});
// GET /api/Alumno/registrarAlumno:id
/*
* Se confirma la inscripcion de un estudiante, registrandolo a un grupo
* por defecto, en caso de no existir grupo, crea uno y es registrado
*/
router.route('/Alumno/registrarAlumno/:id')
.get(function(req, res) {
var id = req.params.id;
var grupoDelAlumno;
console.log("ID DE BUSQUEDA: "+id)
Alumno.findById(id)
.then(alumno => {
console.log("DATOS DE ALUMNO: "+alumno);
Carrera.find({
where: {_id: alumno._carrera},
include: [Grupo]
})
//.populate('_grupos')
.then(carrera => {
console.log(chalk.red("CARRERAID: "+ carrera._id));
console.log("ESTOS SON LOS DATOS: "+carrera);
if(carrera.grupos.length===0){
Grupo.create({
nombre: carrera.abreviacion+'1-1',
_carrera: carrera._id,
})
}
console.log(chalk.green("DATOS DE CARRERA:",carrera))
alumno.updateAttributes({
_grupo: carrera.grupos[0]._id
})
Grupo.find({
where: {_id: carrera.grupos[0]._id},
include: [Alumno]
})
.then(grupo=>{
var noMatricula = alumno.createdAt.getFullYear().toString().substr(2,2);
noMatricula+='30';
noMatricula+=carrera.num*10;
console.log(noMatricula);
var numAlumnos = grupo.alumnos.length;
noMatricula+=numAlumnos<10?'0'+numAlumnos:numAlumnos;
//alumno.noMatricula = noMatricula;
console.log(chalk.red(alumno.noMatricula));
alumno.updateAttributes({
noMatricula: noMatricula
})
})
/*var grupo = carrera.grupos[0]
console.log("GRUPO: ",grupo);
var noMatricula = alumno.createdAt.getFullYear().toString().substr(2,2);
noMatricula+='30';
noMatricula+=carrera.num*10;
console.log(noMatricula);
var numAlumnos = grupo.alumnos.length;
noMatricula+=numAlumnos<10?'0'+numAlumnos:numAlumnos;
alumno.noMatricula = noMatricula;
console.log(chalk.red(alumno.noMatricula));*/
res.json(alumno);
})
});
});
return {router:router,model:Alumno}
}; |
'use strict';Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactcss = require('reactcss');
var _reactcss2 = _interopRequireDefault(_reactcss);
var SliderSwatch = (function (_ReactCSS$Component) {
_inherits(SliderSwatch, _ReactCSS$Component);
function SliderSwatch() {
_classCallCheck(this, SliderSwatch);
_get(Object.getPrototypeOf(SliderSwatch.prototype), 'constructor', this).call(this);
this.handleClick = this.handleClick.bind(this);
}
_createClass(SliderSwatch, [{
key: 'classes',
value: function classes() {
return {
'default': {
swatch: {
height: '12px',
background: 'hsl(' + this.props.hsl.h + ', 50%, ' + this.props.offset * 100 + '%)',
cursor: 'pointer'
}
},
'first': {
swatch: {
borderRadius: '2px 0 0 2px'
}
},
'last': {
swatch: {
borderRadius: '0 2px 2px 0'
}
},
active: {
swatch: {
transform: 'scaleY(1.8)',
borderRadius: '3.6px/2px'
}
}
};
}
}, {
key: 'handleClick',
value: function handleClick() {
this.props.onClick({ h: this.props.hsl.h, s: .5, l: this.props.offset });
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement('div', { style: this.styles().swatch, ref: 'swatch', onClick: this.handleClick });
}
}]);
return SliderSwatch;
})(_reactcss2['default'].Component);
exports.SliderSwatch = SliderSwatch;
exports['default'] = SliderSwatch; |
'use strict';
angular
.module('anguHttpInterceptor', [])
.provider('anguHttpInterceptor', httpInterceptorProvider)
.config(anguHttpInterceptorConfiguration)
function httpInterceptorProvider() {
// 4xx error codes
this.badRequest = null;
this.unauthorized = null;
this.paymentRequired = null;
this.forbidden = null;
this.notFound = null;
this.methodNotAllowed = null;
// 5xx error codes
this.internalServerError = null;
this.notImplemented = null;
this.badGatewayProxyError = null;
this.serviceUnavailable = null;
this.gatewayTimeout = null;
this.httpVersionNotSupported = null;
this.$get = httpInterceptor;
}
function httpInterceptor($q, $injector) {
var ctx = this;
return {
responseError: responseError
};
function responseError(response) {
switch(response.status) {
case 400:
ctx.badRequest && $injector.invoke(ctx.badRequest);
break;
case 401:
ctx.unauthorized && $injector.invoke(ctx.unauthorized);
break;
case 402:
ctx.paymentRequired && $injector.invoke(ctx.paymentRequired);
break;
case 403:
ctx.forbidden && $injector.invoke(ctx.forbidden);
break;
case 404:
ctx.notFound && $injector.invoke(ctx.notFound);
break;
case 405:
ctx.methodNotAllowed && $injector.invoke(ctx.methodNotAllowed);
break;
case 500:
ctx.internalServerError && $injector.invoke(ctx.internalServerError);
break;
case 501:
ctx.notImplemented && $injector.invoke(ctx.notImplemented);
break;
case 502:
ctx.badGatewayProxyError && $injector.invoke(ctx.badGatewayProxyError);
break;
case 503:
ctx.serviceUnavailable && $injector.invoke(ctx.serviceUnavailable);
break;
case 504:
ctx.gatewayTimeout && $injector.invoke(ctx.gatewayTimeout);
break;
case 505:
ctx.httpVersionNotSupported && $injector.invoke(ctx.httpVersionNotSupported);
break;
}
return $q.reject(response);
}
}
function anguHttpInterceptorConfiguration($httpProvider) {
$httpProvider.interceptors.push('anguHttpInterceptor');
}
|
import color from "color";
import { Platform, Dimensions, PixelRatio } from "react-native";
const deviceHeight = Dimensions.get("window").height;
const deviceWidth = Dimensions.get("window").width;
const platform = Platform.OS;
const platformStyle = "material";
export default {
platformStyle,
platform,
// AndroidRipple
androidRipple: true,
androidRippleColor: "rgba(256, 256, 256, 0.3)",
androidRippleColorDark: "rgba(0, 0, 0, 0.15)",
// Badge
badgeBg: "#ED1727",
badgeColor: "#fff",
// New Variable
badgePadding: platform === "ios" ? 3 : 0,
// Button
btnFontFamily: platform === "ios" ? "Roboto" : "Roboto_medium",
btnDisabledBg: "#b5b5b5",
btnDisabledClr: "#f1f1f1",
// CheckBox
CheckboxRadius: 0,
CheckboxBorderWidth: 2,
CheckboxPaddingLeft: 2,
CheckboxPaddingBottom: platform === "ios" ? 0 : 5,
CheckboxIconSize: platform === "ios" ? 18 : 14,
CheckboxIconMarginTop: platform === "ios" ? undefined : 1,
CheckboxFontSize: platform === "ios" ? 21 : 18,
DefaultFontSize: 17,
checkboxBgColor: "#039BE5",
checkboxSize: 20,
checkboxTickColor: "#fff",
// Segment
segmentBackgroundColor: "#3F51B5",
segmentActiveBackgroundColor: "#fff",
segmentTextColor: "#fff",
segmentActiveTextColor: "#3F51B5",
segmentBorderColor: "#fff",
segmentBorderColorMain: "#3F51B5",
// New Variable
get defaultTextColor() {
return this.textColor;
},
get btnPrimaryBg() {
return this.brandPrimary;
},
get btnPrimaryColor() {
return this.inverseTextColor;
},
get btnInfoBg() {
return this.brandInfo;
},
get btnInfoColor() {
return this.inverseTextColor;
},
get btnSuccessBg() {
return this.brandSuccess;
},
get btnSuccessColor() {
return this.inverseTextColor;
},
get btnDangerBg() {
return this.brandDanger;
},
get btnDangerColor() {
return this.inverseTextColor;
},
get btnWarningBg() {
return this.brandWarning;
},
get btnWarningColor() {
return this.inverseTextColor;
},
get btnTextSize() {
return platform === "ios" ? this.fontSizeBase * 1.1 : this.fontSizeBase - 1;
},
get btnTextSizeLarge() {
return this.fontSizeBase * 1.5;
},
get btnTextSizeSmall() {
return this.fontSizeBase * 0.8;
},
get borderRadiusLarge() {
return this.fontSizeBase * 3.8;
},
buttonPadding: 6,
get iconSizeLarge() {
return this.iconFontSize * 1.5;
},
get iconSizeSmall() {
return this.iconFontSize * 0.6;
},
// Card
cardDefaultBg: "#fff",
// Color
brandPrimary: "#3F51B5",
brandInfo: "#3F57D3",
brandSuccess: "#5cb85c",
brandDanger: "#d9534f",
brandWarning: "#f0ad4e",
brandSidebar: "#252932",
// Font
fontFamily: "Roboto",
fontSizeBase: 15,
get fontSizeH1() {
return this.fontSizeBase * 1.8;
},
get fontSizeH2() {
return this.fontSizeBase * 1.6;
},
get fontSizeH3() {
return this.fontSizeBase * 1.4;
},
// Footer
footerHeight: 55,
footerDefaultBg: "#3F51B5",
// FooterTab
tabBarTextColor: "#b3c7f9",
tabBarTextSize: platform === "ios" ? 14 : 11,
activeTab: "#fff",
sTabBarActiveTextColor: "#007aff",
tabBarActiveTextColor: "#fff",
tabActiveBgColor: undefined,
// Tab
tabDefaultBg: "#3F51B5",
topTabBarTextColor: "#b3c7f9",
topTabBarActiveTextColor: "#fff",
topTabActiveBgColor: undefined,
topTabBarBorderColor: "#fff",
topTabBarActiveBorderColor: "#fff",
// Header
toolbarBtnColor: "#fff",
toolbarDefaultBg: "#3F51B5",
toolbarHeight: platform === "ios" ? 76 : 56,
toolbarIconSize: platform === "ios" ? 20 : 22,
toolbarSearchIconSize: platform === "ios" ? 20 : 23,
toolbarInputColor: "#fff",
searchBarHeight: platform === "ios" ? 30 : 40,
toolbarInverseBg: "#222",
toolbarTextColor: "#fff",
toolbarDefaultBorder: "#3F51B5",
iosStatusbar: "light-content",
get statusBarColor() {
return color(this.toolbarDefaultBg).darken(0.2).hex();
},
// Icon
iconFamily: "Ionicons",
iconFontSize: platform === "ios" ? 30 : 28,
iconMargin: 7,
iconHeaderSize: platform === "ios" ? 29 : 24,
// InputGroup
inputFontSize: 17,
inputBorderColor: "#D9D5DC",
inputSuccessBorderColor: "#2b8339",
inputErrorBorderColor: "#ed2f2f",
get inputColor() {
return this.textColor;
},
get inputColorPlaceholder() {
return "#575757";
},
inputGroupMarginBottom: 10,
inputHeightBase: 50,
inputPaddingLeft: 5,
get inputPaddingLeftIcon() {
return this.inputPaddingLeft * 8;
},
// Line Height
btnLineHeight: 19,
lineHeightH1: 32,
lineHeightH2: 27,
lineHeightH3: 22,
iconLineHeight: platform === "ios" ? 37 : 30,
lineHeight: platform === "ios" ? 20 : 24,
// List
listBg: "#fff",
listBorderColor: "#c9c9c9",
listDividerBg: "#f4f4f4",
listItemHeight: 45,
listBtnUnderlayColor: "#DDD",
// Card
cardBorderColor: "#ccc",
// Changed Variable
listItemPadding: platform === "ios" ? 10 : 12,
listNoteColor: "#808080",
listNoteSize: 13,
// Progress Bar
defaultProgressColor: "#E4202D",
inverseProgressColor: "#1A191B",
// Radio Button
radioBtnSize: platform === "ios" ? 25 : 23,
radioSelectedColorAndroid: "#5067FF",
// New Variable
radioBtnLineHeight: platform === "ios" ? 29 : 24,
radioColor: "#7e7e7e",
get radioSelectedColor() {
return color(this.radioColor).darken(0.2).hex();
},
// Spinner
defaultSpinnerColor: "#45D56E",
inverseSpinnerColor: "#1A191B",
// Tabs
tabBgColor: "#F8F8F8",
tabFontSize: 15,
tabTextColor: "#222222",
// Text
textColor: "#000",
inverseTextColor: "#fff",
noteFontSize: 14,
// Title
titleFontfamily: platform === "ios" ? "Roboto" : "Roboto_medium",
titleFontSize: 19,
subTitleFontSize: 14,
subtitleColor: "#FFF",
// New Variable
titleFontColor: "#FFF",
// Other
borderRadiusBase: 2,
borderWidth: 1 / PixelRatio.getPixelSizeForLayoutSize(1),
contentPadding: 10,
get darkenHeader() {
return color(this.tabBgColor).darken(0.03).hex();
},
dropdownBg: "#000",
dropdownLinkColor: "#414142",
inputLineHeight: 24,
jumbotronBg: "#C9C9CE",
jumbotronPadding: 30,
deviceWidth,
deviceHeight,
// New Variable
inputGroupRoundedBorderRadius: 30
};
|
"use strict";
const {
add,
dec,
divide,
inc,
multiply,
subtract,
sum,
} = require('ramda');
module.exports = {
add,
dec,
divide,
inc,
multiply,
subtract,
sum,
};
module.exports.add = add;
module.exports.dec = dec;
module.exports.divide = divide;
module.exports.inc = inc;
module.exports.multiply = multiply;
module.exports.sum = sum;
module.exports.subtract = subtract; |
module.exports.policies = (function() {
var defaults = ['corsHeaders', 'isLoggedIn'],
admin = defaults.concat(['admin']);
return {
'*': defaults,
SystemController: {
index: []
},
TrackController: {
upload: ['corsHeaders']
},
AsyncController: {
list: admin
},
AccountRequestController: {
create: ['corsHeaders'],
find: admin,
findOne: admin,
destroy: admin
},
DeviceSerialController: {
destroy: admin
},
UserRolesController: {
find: defaults
},
DeviceStreamController: {
open: ['corsHeaders'],
destroy: admin,
find: admin
},
SessionController: {
logout: ['corsHeaders'],
link: []
},
UserController: {
create: ['corsHeaders'],
update: ['corsHeaders', 'userUpdatePermission']
},
RegistrationController: {
register: ['corsHeaders']
},
ClientAuthController: {
authenticate: ['corsHeaders']
},
InvitationsController: {
find: ['corsHeaders']
},
QueueController: {
findOne: ['corsHeaders'],
stream: ['corsHeaders'],
pop: ['corsHeaders']
},
DeviceStateController: {
update: ['corsHeaders']
}
};
})();
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var router_1 = require("@angular/router");
var calendardemo_1 = require("./calendardemo");
var CalendarDemoRoutingModule = (function () {
function CalendarDemoRoutingModule() {
}
return CalendarDemoRoutingModule;
}());
CalendarDemoRoutingModule = __decorate([
core_1.NgModule({
imports: [
router_1.RouterModule.forChild([
{ path: '', component: calendardemo_1.CalendarDemo }
])
],
exports: [
router_1.RouterModule
]
})
], CalendarDemoRoutingModule);
exports.CalendarDemoRoutingModule = CalendarDemoRoutingModule;
//# sourceMappingURL=calendardemo-routing.module.js.map |
/**
* BrowserSync
* Run the build task, and spin up a production server with BrowserSync
*/
// Tools
var gulp = require('gulp');
var browsersync = require('browser-sync');
var config = require('../../config').browsersync.production;
// Task (gulp browsersync:production)
gulp.task('browsersync:production', ['build:production'], function() {
browsersync(config);
});
|
/* ****************************************************************************
* Filename: jquery.chcanvas.js
* Version: 0.7.0, July 2013
* Tested jquery versions:
* - jQuery v0.1
* ****************************************************************************
* * DESCRIPTION:
* ****************************************************************************
*
* HTML5 image and audio preloader and use images in div elements or canvas
*
* ****************************************************************************
* * LICENSE:
* ****************************************************************************
*
* This project is build under the MIT License (MIT)
*
* Copyright (C) 2013
* * Christian Amenós - christian.amenos@gmail.com - http://christianamenos.es
*
* 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.
*
* ****************************************************************************
*/
(function($) {
var canvas = true;// 0 => canvas; 1 => div (canvas to print images)
var container = null;//element selected as canvas/container to print images on it
var context = null;
var autoprint = false;
var images = new Array();
var imagesToLoad = 0;
var imagesLoaded = 0;
var imagesLoadedCallback = null;
var audios = new Array();
var audiosToLoad = 0;
var audiosLoaded = 0;
var audiosLoadedCallback = null;
var autoloop = false;
var autoplay = false;
var removePreviousContent = true;
var cssBackground = true;
var extension = 'mp3';
//PRIVATE FUNCTIONS
/*****************************************************************************
* Description: this function will serve as a mere alias for console.log
* message. In case there is not such a cappability it will throw an alert.
* In params:
* @obj {object}: variable to be debugged
* Return: none
****************************************************************************/
function _log(obj) {
if (window.console) {
console.log(obj);
} else {
alert(obj);
}
}
function _increaseImagesLoaded() {
imagesLoaded++;
if (imagesLoaded === imagesToLoad && imagesLoadedCallback !== null) {
imagesLoadedCallback();
}
}
function _increaseAudiosLoaded() {
audiosLoaded++;
if (audiosLoaded === audiosToLoad && audiosLoadedCallback !== null) {
audiosLoadedCallback();
}
}
//PLUGIN CONSTRUCTOR
/*****************************************************************************
* @autoprint {bool}: if autoprint is set to true, the plugin will print the
* images on the selected element as soon as it gets all the elements loaded.
* @imagesCallback {function}: if set is the function that will be called when
* all the images are loaded.
* @audiosCallback {function}: if set is the function that will be called when
* all the audio files are loaded.
* @autoloop {bool}: if set is to true by default all audio files will be payed
* on loop mode.
* @removePreviousContent {bool}: if set is to true by default all content will
* be erased and the image will be appened in the container if is not a canvas
* element
* @cssBackground {bool}: if set is to true by default set the image as the
* background of the container if is not a canvas element (it's more mandatory
* than removePreviousContent attribute)
****************************************************************************/
jQuery.fn.setCanvas = function(options) {
//Default plugin's attributes
var defaults = {
autoprint: false,
autoplay: false,
imagesCallback: null,
audiosCallback: null,
autoloop: false,
removePreviousContent: true,
cssBackground: true
};
//Option settings. Overwritten if defined by the programmer
var o = jQuery.extend(defaults, options);
autoprint = o.autoprint;
imagesLoadedCallback = o.imagesCallback;
audiosLoadedCallback = o.audiosCallback;
autoplay = o.autoplay;
autoloop = o.autoloop;
removePreviousContent = o.removePreviousContent;
cssBackground = o.cssBackground;
/*
* If the selected element is detected as a canvas, the plugin will undestand
* that the will be necessary to use canvas printing functionalitites.
*
* Otherwise the element will be used as a container by default and the
* images will be appended on it.
*/
canvas = $(this).prop("tagName").toLowerCase() === 'canvas';
if (canvas) {
context = $(this)[0].getContext('2d');
} else {
container = $(this);
}
//we have to return the selected element with the changes on it
return this;
};
jQuery.fn.preloadImages = function(arrayOfImages) {
$(arrayOfImages).each(function(element) {
imagesToLoad++;
$('<img/>').attr('src', arrayOfImages[element]).on('load', function() {
this.filename = arrayOfImages[element];
images.push(this);
if (!canvas && autoprint) {
if (autoprint) {
if (cssBackground) {
$(container).css('background-image', 'url(' + this.src + ')');
$(container).css('background-position', 'center center');
$(container).css('background-repeat', 'no-repeat');
} else {
if (removePreviousContent) {
$(container).html();
}
$(container).append(this);
}
}
}
_increaseImagesLoaded();
});
});
return this;
};
jQuery.fn.preloadAudios = function(arrayOfAudios) {
//check the available audio type of data in order to see if the browser allows this kind of file and add the fileextension automatically
var aux = document.createElement('audio');
extension = 'mp3';
if (!(aux.canPlayType && aux.canPlayType('audio/mpeg;').replace(/no/, ''))) {
extension = 'ogg';
if (!(aux.canPlayType && aux.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''))) {
extension = 'wav';
}
}
$(arrayOfAudios).each(function(element) {
audiosToLoad++;
$('<audio/>').attr('src', arrayOfAudios[element] + '.' + extension).on('loadeddata', function() {
this.filename = arrayOfAudios[element];
audios.push(this);
if (autoplay) {
if (autoloop) {
$(this).loop = true;
}
$(this).play();
}
_increaseAudiosLoaded();
});
});
return this;
};
//print an image on canvas or in a div; depending on the image identifier
jQuery.fn.print = function(identifier, xPos, yPos, imageWidth, imageHeight, frameWidth, frameHeight, frameX, frameY) {
/*
* - identifier: is the filename
* - xPos: is the x position where we want to print the image
* - yPos: is the y position where we want to print the image
* - imageWidth: is the width in pixels of the original image
* - imageHeight: is the height in pixels of the original image
* - frameWidth: is the width of the frame on the original image
* - frameHeight: is the height of the frame on the original image
* - frameX: is the horizontal position of the frame to be displayed starts on 0
* - frameY: is the vertical position of the frame to be displayed starts on 0
*/
/* -----------------------------
* SIMPLE:
* -----------------------------
* drawImage(img,x,y);
* - img: image to print
* - x: coordinate x to print
* - y:coordinate y to print
* -----------------------------
* ADVANCED:
* -----------------------------
* drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
* - img: image to print
* - sx: x coordinate to start clipping (optional)
* - sy: y coordinate to start clipping (optional)
* - swidth: the width of the clipped image; width from the original image (optional)
* - sheight: the height of the clipped image; height from the original image (optional)
* - x: the x coordinate to place the image on the canvas
* - y: the y coordinate to place the image on the canvas
* - width: the final width of the image; reduces or scale the image (optional)
* - height: the final height of the image; reduces or scale the image (optional)
*/
img = null;
for (var i = 0; i < images.length; i++) {
if (identifier === images[i].filename) {
img = images[i];
break;
}
}
if (canvas) {
var simple = true;
if (typeof xPos === 'undefined') {
xPos = 0;
yPos = 0;
} else {
if (typeof yPos === 'undefined') {
yPos = xPos;
} else {
if (typeof imageWidth !== 'undefined') {
simple = false;
if (typeof imageHeight !== 'undefined') {
imageHeight = imageWidth;
} else {
if (typeof frameWidth !== 'undefined') {
frameWidth = imageWidth;
} else {
if (typeof frameHeight !== 'undefined') {
frameHeight = frameWidth;
} else {
if (typeof frameX !== 'undefined') {
frameX = 0;
}
if (typeof frameY !== 'undefined') {
frameY = 0;
}
}
}
}
}
}
}
if (simple) {
context.drawImage(img, xPos, yPos);
} else {
context.drawImage(img, frameWidth * frameX, frameWidth * frameY, frameWidth, frameHeight, xPos, yPos, frameWidth, frameHeight);
}
} else {
if (cssBackground) {
$(container).css('background-image', 'url(' + img.src + ')');
$(container).css('background-position', 'center center');
$(container).css('background-repeat', 'no-repeat');
} else {
if (removePreviousContent) {
$(container).html();
}
$(container).append(img);
}
}
};
//plays an audio file; from it's identifier
jQuery.fn.reproduce = function(identifier, loop) {
for (var i = 0; i < audios.length; i++) {
if (identifier === audios[i].filename) {
audio = audios[i];
break;
}
}
if (autoloop) {
audio.loop = true;
}
audio.play();
};
})(jQuery);
|
/**
* @fileoverview Tests for prefer-arrow-callback rule.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const rule = require("../../../lib/rules/prefer-arrow-callback");
const { RuleTester } = require("../../../lib/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const errors = [{
messageId: "preferArrowCallback",
type: "FunctionExpression"
}];
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6 } });
ruleTester.run("prefer-arrow-callback", rule, {
valid: [
"foo(a => a);",
"foo(function*() {});",
"foo(function() { this; });",
{ code: "foo(function bar() {});", options: [{ allowNamedFunctions: true }] },
"foo(function() { (() => this); });",
"foo(function() { this; }.bind(obj));",
"foo(function() { this; }.call(this));",
"foo(a => { (function() {}); });",
"var foo = function foo() {};",
"(function foo() {})();",
"foo(function bar() { bar; });",
"foo(function bar() { arguments; });",
"foo(function bar() { arguments; }.bind(this));",
"foo(function bar() { new.target; });",
"foo(function bar() { new.target; }.bind(this));",
"foo(function bar() { this; }.bind(this, somethingElse));"
],
invalid: [
{
code: "foo(function bar() {});",
output: "foo(() => {});",
errors
},
{
code: "foo(function() {});",
output: "foo(() => {});",
options: [{ allowNamedFunctions: true }],
errors
},
{
code: "foo(function bar() {});",
output: "foo(() => {});",
options: [{ allowNamedFunctions: false }],
errors
},
{
code: "foo(function() {});",
output: "foo(() => {});",
errors
},
{
code: "foo(nativeCb || function() {});",
output: "foo(nativeCb || (() => {}));",
errors
},
{
code: "foo(bar ? function() {} : function() {});",
output: "foo(bar ? () => {} : () => {});",
errors: [errors[0], errors[0]]
},
{
code: "foo(function() { (function() { this; }); });",
output: "foo(() => { (function() { this; }); });",
errors
},
{
code: "foo(function() { this; }.bind(this));",
output: "foo(() => { this; });",
errors
},
{
code: "foo(bar || function() { this; }.bind(this));",
output: "foo(bar || (() => { this; }));",
errors
},
{
code: "foo(function() { (() => this); }.bind(this));",
output: "foo(() => { (() => this); });",
errors
},
{
code: "foo(function bar(a) { a; });",
output: "foo((a) => { a; });",
errors
},
{
code: "foo(function(a) { a; });",
output: "foo((a) => { a; });",
errors
},
{
code: "foo(function(arguments) { arguments; });",
output: "foo((arguments) => { arguments; });",
errors
},
{
code: "foo(function() { this; });",
output: null, // No fix applied
options: [{ allowUnboundThis: false }],
errors
},
{
code: "foo(function() { (() => this); });",
output: null, // No fix applied
options: [{ allowUnboundThis: false }],
errors
},
{
code: "qux(function(foo, bar, baz) { return foo * 2; })",
output: "qux((foo, bar, baz) => { return foo * 2; })",
errors
},
{
code: "qux(function(foo, bar, baz) { return foo * bar; }.bind(this))",
output: "qux((foo, bar, baz) => { return foo * bar; })",
errors
},
{
code: "qux(function(foo, bar, baz) { return foo * this.qux; }.bind(this))",
output: "qux((foo, bar, baz) => { return foo * this.qux; })",
errors
},
{
code: "foo(function() {}.bind(this, somethingElse))",
output: "foo((() => {}).bind(this, somethingElse))",
errors
},
{
code: "qux(function(foo = 1, [bar = 2] = [], {qux: baz = 3} = {foo: 'bar'}) { return foo + bar; });",
output: "qux((foo = 1, [bar = 2] = [], {qux: baz = 3} = {foo: 'bar'}) => { return foo + bar; });",
errors
},
{
code: "qux(function(baz, baz) { })",
output: null, // Duplicate parameter names are a SyntaxError in arrow functions
errors
},
{
code: "qux(function( /* no params */ ) { })",
output: "qux(( /* no params */ ) => { })",
errors
},
{
code: "qux(function( /* a */ foo /* b */ , /* c */ bar /* d */ , /* e */ baz /* f */ ) { return foo; })",
output: "qux(( /* a */ foo /* b */ , /* c */ bar /* d */ , /* e */ baz /* f */ ) => { return foo; })",
errors
},
{
code: "qux(async function (foo = 1, bar = 2, baz = 3) { return baz; })",
output: "qux(async (foo = 1, bar = 2, baz = 3) => { return baz; })",
parserOptions: { ecmaVersion: 8 },
errors
},
{
code: "qux(async function (foo = 1, bar = 2, baz = 3) { return this; }.bind(this))",
output: "qux(async (foo = 1, bar = 2, baz = 3) => { return this; })",
parserOptions: { ecmaVersion: 8 },
errors
}
]
});
|
'use strict';
/* Filters */
angular.module('elevendanceFilters', []).filter('checkmark', function() {
return function(input) {
return input ? '\u2713' : '\u2718';
};
});
|
'use strict';
crop.factory('cropAreaSquare', ['cropArea', function(CropArea) {
var CropAreaSquare = function() {
CropArea.apply(this, arguments);
this._resizeCtrlBaseRadius = 10;
this._resizeCtrlNormalRatio = 0.75;
this._resizeCtrlHoverRatio = 1;
this._iconMoveNormalRatio = 0.9;
this._iconMoveHoverRatio = 1.2;
this._resizeCtrlNormalRadius = this._resizeCtrlBaseRadius * this._resizeCtrlNormalRatio;
this._resizeCtrlHoverRadius = this._resizeCtrlBaseRadius * this._resizeCtrlHoverRatio;
this._posDragStartX = 0;
this._posDragStartY = 0;
this._posResizeStartX = 0;
this._posResizeStartY = 0;
this._posResizeStartSize = 0;
this._resizeCtrlIsHover = -1;
this._areaIsHover = false;
this._resizeCtrlIsDragging = -1;
this._areaIsDragging = false;
};
CropAreaSquare.prototype = new CropArea();
CropAreaSquare.prototype.getType = function() {
return 'square';
};
CropAreaSquare.prototype._calcSquareCorners = function() {
var size = this.getSize(),
se = this.getSouthEastBound();
return [
[size.x, size.y], //northwest
[se.x, size.y], //northeast
[size.x, se.y], //southwest
[se.x, se.y] //southeast
];
};
CropAreaSquare.prototype._calcSquareDimensions = function() {
var size = this.getSize(),
se = this.getSouthEastBound();
return {
left: size.x,
top: size.y,
right: se.x,
bottom: se.y
};
};
CropAreaSquare.prototype._isCoordWithinArea = function(coord) {
var squareDimensions = this._calcSquareDimensions();
return (coord[0] >= squareDimensions.left && coord[0] <= squareDimensions.right && coord[1] >= squareDimensions.top && coord[1] <= squareDimensions.bottom);
};
CropAreaSquare.prototype._isCoordWithinResizeCtrl = function(coord) {
var resizeIconsCenterCoords = this._calcSquareCorners();
var res = -1;
for (var i = 0, len = resizeIconsCenterCoords.length; i < len; i++) {
var resizeIconCenterCoords = resizeIconsCenterCoords[i];
if (coord[0] > resizeIconCenterCoords[0] - this._resizeCtrlHoverRadius && coord[0] < resizeIconCenterCoords[0] + this._resizeCtrlHoverRadius &&
coord[1] > resizeIconCenterCoords[1] - this._resizeCtrlHoverRadius && coord[1] < resizeIconCenterCoords[1] + this._resizeCtrlHoverRadius) {
res = i;
break;
}
}
return res;
};
CropAreaSquare.prototype._drawArea = function(ctx, centerCoords, size) {
var hSize = size / 2;
ctx.rect(size.x, size.y, size.w, size.h);
};
CropAreaSquare.prototype.draw = function() {
CropArea.prototype.draw.apply(this, arguments);
// draw move icon
var center = this.getCenterPoint();
this._cropCanvas.drawIconMove([center.x, center.y], this._areaIsHover ? this._iconMoveHoverRatio : this._iconMoveNormalRatio);
// draw resize cubes
var resizeIconsCenterCoords = this._calcSquareCorners();
for (var i = 0, len = resizeIconsCenterCoords.length; i < len; i++) {
var resizeIconCenterCoords = resizeIconsCenterCoords[i];
this._cropCanvas.drawIconResizeCircle(resizeIconCenterCoords, this._resizeCtrlBaseRadius, this._resizeCtrlIsHover === i ? this._resizeCtrlHoverRatio : this._resizeCtrlNormalRatio);
}
};
CropAreaSquare.prototype.processMouseMove = function(mouseCurX, mouseCurY) {
var cursor = 'default';
var res = false;
this._resizeCtrlIsHover = -1;
this._areaIsHover = false;
if (this._areaIsDragging) {
this.setCenterPointOnMove({
x: mouseCurX - this._posDragStartX,
y: mouseCurY - this._posDragStartY
});
this._areaIsHover = true;
cursor = 'move';
res = true;
this._events.trigger('area-move');
} else if (this._resizeCtrlIsDragging > -1) {
var xMulti, yMulti;
switch (this._resizeCtrlIsDragging) {
case 0: // Top Left
xMulti = -1;
yMulti = -1;
cursor = 'nwse-resize';
break;
case 1: // Top Right
xMulti = 1;
yMulti = -1;
cursor = 'nesw-resize';
break;
case 2: // Bottom Left
xMulti = -1;
yMulti = 1;
cursor = 'nesw-resize';
break;
case 3: // Bottom Right
xMulti = 1;
yMulti = 1;
cursor = 'nwse-resize';
break;
}
var iFX = (mouseCurX - this._posResizeStartX) * xMulti,
iFY = (mouseCurY - this._posResizeStartY) * yMulti,
iFR;
if (iFX > iFY) {
iFR = this._posResizeStartSize.w + iFY;
} else {
iFR = this._posResizeStartSize.w + iFX;
}
var newSize = Math.max(this._minSize.w, iFR),
newNO = {},
newSE = {},
newSO = {},
newNE = {},
s = this.getSize(),
se = this.getSouthEastBound();
switch (this._resizeCtrlIsDragging) {
case 0: // Top Left
newNO.x = se.x - newSize;
newNO.y = se.y - newSize;
if(newNO.y > 0) {
this.setSizeByCorners(newNO, {
x: se.x,
y: se.y
});
}
cursor = 'nwse-resize';
break;
case 1: // Top Right
if(iFX >= 0 && iFY >= 0) {
//Move to top/right, increase
newNE.x = s.x + newSize;
newNE.y = se.y - newSize;
} else if(iFX < 0 || iFY < 0) {
//else decrease
newNE.x = s.x + newSize;
newNE.y = se.y - newSize;
}
if(newNE.y > 0) {
this.setSizeByCorners({
x: s.x,
y: newNE.y
}, {
x: newNE.x,
y: se.y
});
}
cursor = 'nesw-resize';
break;
case 2: // Bottom Left
if(iFX >= 0 && iFY >= 0) {
//Move to bottom/left, increase
newSO.x = se.x - newSize;
newSO.y = s.y + newSize;
} else if(iFX <= 0 || iFY <= 0) {
//else decrease
newSO.x = se.x - newSize;
newSO.y = s.y + newSize;
}
if(newSO.y < this._ctx.canvas.height) {
this.setSizeByCorners({
x: newSO.x,
y: s.y
}, {
x: se.x,
y: newSO.y
});
}
cursor = 'nesw-resize';
break;
case 3: // Bottom Right
newSE.x = s.x + newSize;
newSE.y = s.y + newSize;
if(newSE.y < this._ctx.canvas.height) {
this.setSizeByCorners({
x: s.x,
y: s.y
}, newSE);
}
cursor = 'nwse-resize';
break;
}
this._resizeCtrlIsHover = this._resizeCtrlIsDragging;
res = true;
this._events.trigger('area-resize');
} else {
var hoveredResizeBox = this._isCoordWithinResizeCtrl([mouseCurX, mouseCurY]);
if (hoveredResizeBox > -1) {
switch (hoveredResizeBox) {
case 0:
cursor = 'nwse-resize';
break;
case 1:
cursor = 'nesw-resize';
break;
case 2:
cursor = 'nesw-resize';
break;
case 3:
cursor = 'nwse-resize';
break;
}
this._areaIsHover = false;
this._resizeCtrlIsHover = hoveredResizeBox;
res = true;
} else if (this._isCoordWithinArea([mouseCurX, mouseCurY])) {
cursor = 'move';
this._areaIsHover = true;
res = true;
}
}
angular.element(this._ctx.canvas).css({
'cursor': cursor
});
return res;
};
CropAreaSquare.prototype.processMouseDown = function(mouseDownX, mouseDownY) {
var isWithinResizeCtrl = this._isCoordWithinResizeCtrl([mouseDownX, mouseDownY]);
if (isWithinResizeCtrl > -1) {
this._areaIsDragging = false;
this._areaIsHover = false;
this._resizeCtrlIsDragging = isWithinResizeCtrl;
this._resizeCtrlIsHover = isWithinResizeCtrl;
this._posResizeStartX = mouseDownX;
this._posResizeStartY = mouseDownY;
this._posResizeStartSize = this._size;
this._events.trigger('area-resize-start');
} else if (this._isCoordWithinArea([mouseDownX, mouseDownY])) {
this._areaIsDragging = true;
this._areaIsHover = true;
this._resizeCtrlIsDragging = -1;
this._resizeCtrlIsHover = -1;
var center = this.getCenterPoint();
this._posDragStartX = mouseDownX - center.x;
this._posDragStartY = mouseDownY - center.y;
this._events.trigger('area-move-start');
}
};
CropAreaSquare.prototype.processMouseUp = function( /*mouseUpX, mouseUpY*/ ) {
if (this._areaIsDragging) {
this._areaIsDragging = false;
this._events.trigger('area-move-end');
}
if (this._resizeCtrlIsDragging > -1) {
this._resizeCtrlIsDragging = -1;
this._events.trigger('area-resize-end');
}
this._areaIsHover = false;
this._resizeCtrlIsHover = -1;
this._posDragStartX = 0;
this._posDragStartY = 0;
};
return CropAreaSquare;
}]); |
Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
// This code only runs on the client
Meteor.subscribe("tasks");
Template.body.helpers({
tasks: function () {
if (Session.get("hideCompleted")) {
// If hide completed is checked, filter tasks
return Tasks.find({checked: {$ne: true}}, {sort: {createdAt: -1}});
} else {
// Otherwise, return all of the tasks
return Tasks.find({}, {sort: {createdAt: -1}});
}
},
hideCompleted: function () {
return Session.get("hideCompleted");
},
incompleteCount: function () {
return Tasks.find({checked: {$ne: true}}).count();
}
});
Template.body.events({
"submit .new-task": function (event) {
// Prevent default browser form submit
event.preventDefault();
// Get value from form element
var text = event.target.text.value;
// Insert a task into the collection
Meteor.call("addTask", text);
// Clear form
event.target.text.value = "";
},
"change .hide-completed input": function (event) {
Session.set("hideCompleted", event.target.checked);
}
});
Template.task.helpers({
isOwner: function () {
return this.owner === Meteor.userId();
}
});
Template.task.events({
"click .toggle-checked": function () {
// Set the checked property to the opposite of its current value
Meteor.call("setChecked", this._id, ! this.checked);
},
"click .delete": function () {
Meteor.call("deleteTask", this._id);
},
"click .toggle-private": function () {
Meteor.call("setPrivate", this._id, ! this.private);
}
});
Accounts.ui.config({
passwordSignupFields: "USERNAME_ONLY"
});
}
Meteor.methods({
addTask: function (text) {
// Make sure the user is logged in before inserting a task
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
Tasks.insert({
text: text,
createdAt: new Date(),
owner: Meteor.userId(),
username: Meteor.user().username
});
},
deleteTask: function (taskId) {
Tasks.remove(taskId);
},
setChecked: function (taskId, setChecked) {
Tasks.update(taskId, { $set: { checked: setChecked} });
},
setPrivate: function (taskId, setToPrivate) {
var task = Tasks.findOne(taskId);
// Make sure only the task owner can make a task private
if (task.owner !== Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
Tasks.update(taskId, { $set: { private: setToPrivate } });
}
});
if (Meteor.isServer) {
Meteor.publish("tasks", function () {
return Tasks.find({
$or: [
{ private: {$ne: true} },
{ owner: this.userId }
]
});
});
Meteor.startup(function () {
// code to run on server at startup
});
}
|
var Point = function(data, mission) {
this._marker = null;
this.mission = mission;
this.lat = parseFloat(data.lat);
this.long = parseFloat(data.long);
this.portal_name = data.portal_name;
this.draw = function()
{
var marker_data = {
position: { lat: this.lat, lng: this.long },
title: this.mission_series_name || data.portal_name || 'Unknown Portal',
map: Map
};
if(this.mission.series_id === null)
{
marker_data.icon = 'http://maps.google.com/mapfiles/ms/micons/pink.png';
} else {
marker_data.icon = Icons[parseFloat(this.mission.series_id) % Icons.length];
}
this._marker = new google.maps.Marker(marker_data);
};
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.