code
stringlengths 2
1.05M
|
---|
'use strict';
var ExitPairs = {
north: 'south',
south: 'north',
east: 'west',
west: 'east'
}
class Location {
constructor(name) {
this.generated = false
this.name = name
this.exits = {}
this.loot = []
this.enemies = []
}
link(exit, otherLocation) {
this.exits[exit] = otherLocation
otherLocation.exits[ExitPairs[exit]] = this
}
get description() {
let desc = `You are at ${this.name}.\n`
for(let exit in this.exits) {
desc += `To the ${exit} you see ${this.exits[exit].name}.\n`
}
for(let item of this.loot) {
desc += `There is a ${item.name} on the ground.\n`
}
for(let enemy of this.enemies) {
desc += `A ${enemy.name} stares at you menacingly.\n`
}
return desc.substring(0, desc.length-1)
}
}
|
var Vector = require('../dist/vectory.umd.js')
var test = require('tape')
if (typeof Symbol !== 'undefined' && Symbol.iterator && Vector.prototype[Symbol.iterator]) {
test('`Vector.prototype[Symbol.iterator]()` should return an iterator', function (t) {
var vector = new Vector(3, 4)
var iterator = vector[Symbol.iterator]()
t.ok(iterator)
t.true(typeof iterator.next === 'function')
t.deepEqual(iterator.next(), { done: false, value: 3 })
t.deepEqual(iterator.next(), { done: false, value: 4 })
t.deepEqual(iterator.next(), { done: true, value: void 0 })
t.end()
})
} else {
test.skip('`Vector.prototype[Symbol.iterator]()` should return an iterator', function (t) {})
}
|
/*
* grunt-request-upload
* https://github.com/xzf158/grunt-request-upload
*
* Copyright (c) 2015 Terry X
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp'],
},
// Configuration to be run (and then tested).
http_upload: {
default_options: {
options: {},
files: {
'tmp/default_options': ['test/fixtures/testing', 'test/fixtures/123'],
},
},
custom_options: {
options: {
separator: ': ',
punctuation: ' !!!',
},
files: {
'tmp/custom_options': ['test/fixtures/testing', 'test/fixtures/123'],
},
},
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js'],
},
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'request_upload', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
}; |
/**
* Created by dave on 15/11/16.
*/
function meetupLoginWindow(url) {
window.open(url, '_parent','location=no,menubar=no,scrollbars=no');
}
window.onload=function() {
document.getElementById("meetup-login").addEventListener("click", function () {
var url = "https://secure.meetup.com/oauth2/authorize"
var clientId = TWIG.loginClientId;
var responseType = "code";
var redirectUri = TWIG.connectUrl;
var urlString = url +
"?client_id=" + clientId +
"&response_type=" + responseType +
"&redirect_uri=" + redirectUri;
meetupLoginWindow(urlString);
});
} |
import React from 'react';
const Menu = ({ className, leftAction, rightAction, title }) => (
<div className={`${className} menu`} >
<div className="menu__action" >
{leftAction}
</div>
<div className="menu__title" >
{title}
</div>
<div className="menu__action" >
{rightAction}
</div>
</div>
);
Menu.propTypes = {
className: React.PropTypes.string,
leftAction: React.PropTypes.element,
rightAction: React.PropTypes.element,
title: React.PropTypes.string
};
export default Menu;
|
'use strict';
import { playState } from '../lib.js';
Template.connect.onCreated(() => {
let templateInstance = Template.instance();
templateInstance.playState = playState;
templateInstance.subscribe('Rooms');
templateInstance.subscribe('Words');
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><circle cx="19.5" cy="19.5" r="1.5" /><path d="M17 5.92L9 2v18H7v-1.73c-1.79.35-3 .99-3 1.73 0 1.1 2.69 2 6 2s6-.9 6-2c0-.99-2.16-1.81-5-1.97V8.98l6-3.06z" /></React.Fragment>
, 'GolfCourse');
|
import './keyboardShortcuts';
import './persistAppState';
import './controlBar';
import './customTheme';
import './desktopSettings';
import './errorHandler';
import './tray';
import './lastFM';
import './autoUpdater';
import './websocketAPI';
import './lyrics';
import './applicationMenu';
|
const User = require('./users');
const Role = require('./roles');
const Document = require('./documents');
Role.initialize(); // Create default roles.
module.exports = { User, Role, Document };
|
// @flow
import {
handleResult,
sendRequest,
} from './util';
export default function patents(): Object {
return {
fetch: (options: Object = {}): Promise<any> =>
new Promise((resolve: (data: Object) => void, reject: (reason: Error) => void): mixed =>
sendRequest(
'api.nasa.gov',
'/patents/content',
options,
resolve,
reject,
handleResult
)
),
};
}
|
import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import Panel from '../../shared/Panel';
import ShowMoreFooter from '../../shared/ShowMoreFooter';
import Row from './row';
import Chooser from './chooser';
const INITIAL_PAGE_SIZE = 5;
const PAGE_SIZE = 20;
class TeamMemberships extends React.PureComponent {
static displayName = "Member.Teams";
static propTypes = {
organizationMember: PropTypes.shape({
uuid: PropTypes.string.isRequired,
teams: PropTypes.shape({
count: PropTypes.number.isRequired,
edges: PropTypes.arrayOf(
PropTypes.shape({
node: PropTypes.object.isRequired
}).isRequired
).isRequired
}).isRequired
}),
relay: PropTypes.object.isRequired
};
state = {
loading: false
};
render() {
return (
<div>
<Chooser
organizationMember={this.props.organizationMember}
onChoose={this.handleTeamMemberAdd}
/>
<Panel>
{this.renderTeams()}
<ShowMoreFooter
connection={this.props.organizationMember.teams}
label="teams"
loading={this.state.loading}
onShowMore={this.handleShowMoreTeams}
/>
</Panel>
</div>
);
}
handleTeamMemberAdd = () => {
this.props.relay.forceFetch();
};
renderTeams() {
const teams = this.props.organizationMember.teams.edges;
if (!teams.length) {
return (
<div className="p3">
This user is not a member of any teams.
</div>
);
}
return teams.map(({ node }) => (
<Row
key={node.id}
teamMember={node}
/>
));
}
handleShowMoreTeams = () => {
this.setState({ loading: true });
let { teamsPageSize } = this.props.relay.variables;
teamsPageSize += PAGE_SIZE;
this.props.relay.setVariables(
{ teamsPageSize },
(readyState) => {
if (readyState.done) {
this.setState({ loading: false });
}
}
);
};
}
export default Relay.createContainer(TeamMemberships, {
initialVariables: {
teamsPageSize: INITIAL_PAGE_SIZE
},
fragments: {
organizationMember: () => Relay.QL`
fragment on OrganizationMember {
uuid
user {
id
}
teams(first: $teamsPageSize, order: NAME) {
${ShowMoreFooter.getFragment('connection')}
count
edges {
node {
id
${Row.getFragment('teamMember')}
}
}
}
${Chooser.getFragment('organizationMember')}
}
`
}
});
|
'use strict';
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var React = require('../react');
var FormTemplate = React.createClass({
displayName: 'FormTemplate',
render: function render() {
var _props = this.props;
var children = _props.children;
var props = _objectWithoutProperties(_props, ['children']);
return React.createElement(
'form',
props,
children
);
}
});
module.exports = FormTemplate; |
(function() {
var app = angular.module('discores', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/courses', {
templateUrl: '/views/courses.html',
controller: 'CourseCtrl',
controllerAs: 'courseCtrl'
})
.when('/players/:playerId/games', {
templateUrl:'views/player-games.html',
controller: 'PlayerGamesCtrl',
controllerAs: 'playerGamesCtrl'
})
.when('/players', {
templateUrl: '/views/players.html',
controller: 'PlayerCtrl',
controllerAs: 'playerCtrl'
})
.when('/game/results/:gameId', {
templateUrl: 'views/game-results.html',
controller: 'ResultsCtrl',
controllerAs: 'resultsCtrl'
})
.when('/game/:gameId/:holeNumber', {
templateUrl: 'views/play-game.html',
controller: 'PlayCtrl',
controllerAs: 'playCtrl'
})
.when('/game', {
templateUrl: '/views/create-game.html',
controller: 'GameCtrl',
controllerAs: 'gameCtrl'
})
.otherwise({
redirectTo: '/game'
});
}]);
app.controller('ResultsCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
var self = this;
self.game = null;
self.holes = [];
self.playersScores = [];
$http.get('/api/game/' + $routeParams.gameId)
.success(function(g) {
self.game = g;
for (var i = 0; i < self.game.course.numberOfHoles; i++) {
self.holes.push(i + 1);
}
self.game.players.forEach(function(p) {
var sum = self.game.scores[p.id].reduce(function(sum, h) {
sum += h;
return sum;
}, 0);
var result = '';
if (sum === self.game.course.par) {
result = 'E';
} else {
result = 0 - (self.game.course.par - sum);
if (result > 0) {
result = '+' + result;
}
}
self.playersScores.push({
'name': p.name,
'scores': self.game.scores[p.id],
'result': result
})
});
});
}]);
app.controller('PlayCtrl', ['$scope', '$http', '$routeParams', '$location', function($scope, $http, $routeParams, $location) {
var self = this;
self.game = null;
self.holeNumber = $routeParams.holeNumber;
if (self.holeNumber < 1) {
Materialize.toast(self.holeNumber + ' is not a valid hole.. Let\'s try 1 instead.', 3000, 'rounded');
$location.path('/game/' + $routeParams.gameId + '/' + 1);
return;
}
self.holeScores = {};
self.nextHoleBtnLabel = 'Next Hole';
self.prevHole = function() {
var prevHole = self.holeNumber - 1;
$location.path('/game/' + self.game.id + '/' + prevHole);
};
self.nextHole = function() {
if (self.holeNumber < 1) {
Materialize.toast('Oh no! Invalid hole number. Let\'s try hole 1.', 3000, 'rounded')
$location.path('/game/' + self.game.id + '/' + 1);
return;
}
// Save the current hole
self.game.players.forEach(function(p) {
self.game.scores[p.id][self.holeNumber-1] = self.holeScores[p.id];
});
$http.post('/api/game/update', self.game)
.success(function(game) {
self.holeNumber++;
if (self.holeNumber > self.game.course.numberOfHoles) {
$location.path('/game/results/' + game.id + '/');
} else {
$location.path('/game/' + game.id + '/' + self.holeNumber);
}
})
.error(function(e) {
Materialize.toast('Uh oh! Error moving to next hole :(', 3000, 'rounded');
});
};
self.removeStrokeForPlayer = function(playerId) {
self.holeScores[playerId]--;
};
self.addStrokeForPlayer = function(playerId) {
self.holeScores[playerId]++;
};
$http.get('/api/game/' + $routeParams.gameId)
.success(function(g) {
self.game = g;
if (self.holeNumber > self.game.course.numberOfHoles) {
var lastHole = self.game.course.numberOfHoles;
Materialize.toast(self.holeNumber + ' is not a valid hole.. Let\'s try the last hole instead.', 3000, 'rounded');
$location.path('/game/' + $routeParams.gameId + '/' + lastHole);
return;
}
if (self.game.course.numberOfHoles == self.holeNumber) {
self.nextHoleBtnLabel = 'Finish Game';
}
self.game.players.forEach(function(p) {
self.holeScores[p.id] = self.game.scores[p.id][self.holeNumber-1] || 0;
});
});
}]);
app.controller('PlayerGamesCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
var self = this;
self.games = [];
self.playerId = $routeParams.playerId;
self.playerNameLabel = null;
$http.get('/api/players/' + self.playerId)
.success(function(data) {
self.playerNameLabel = data.name + "'s Games";
});
$http.get('/api/players/' + self.playerId + '/games/')
.success(function(data) {
self.games = data.map(function(g) {
var sum = g.scores[self.playerId].reduce(function(sum, h) {
sum += h;
return sum;
}, 0);
g.myResult = 0 - (g.course.par - sum);
if (g.myResult == 0) {
g.myResult = 'E';
} else if (g.myResult > 0) {
g.myResult = '+' + g.myResult;
}
return g;
});
});
}]);
app.controller('GameCtrl', ['$scope', '$http', '$routeParams', '$location', function ($scope, $http, $routeParams, $location) {
var self = this;
$scope.$parent.tab = 0;
self.selectedCourse = null;
self.selectedPlayers = [];
self.newPlayer = null;
self.startGame = function() {
if (!self.selectedPlayers.length || !self.selectedCourse) {
return;
}
var courseName = self.selectedCourse.name;
var playersNames = _.pluck(self.selectedPlayers, 'name').join(',');
console.log('Starting game at ' + courseName + ' with ' + playersNames);
// Begin the game and change the view
var newGame = {
course: self.selectedCourse,
players: self.selectedPlayers
};
$http.post('/api/game', newGame)
.success(function(game) {
// Change window location
$location.path('/game/' + game.id + '/' + 1);
})
.error(function(e) {
Materialize.toast('Whoops! Error beginning game', 3000, 'rounded');
});
};
self.addPlayer = function() {
if (!self.newPlayer || !self.newPlayer.name) {
return;
}
var playerExists = _.find(self.selectedPlayers, function(p) {
return p.id === self.newPlayer.id;
});
if (playerExists) {
Materialize.toast('Player already playing!', 3000, 'rounded');
return;
}
self.selectedPlayers.push(self.newPlayer);
self.newPlayer = null;
}
self.removePlayer = function(player) {
if (!player) return;
self.selectedPlayers = self.selectedPlayers.filter(function(p) {
return p.id !== player.id;
});
}
$http.get('/api/players')
.success(function(data) {
self.allPlayers = data;
});
$http.get('/api/courses')
.success(function(data) {
self.allCourses = data;
});
}]);
app.controller('CourseCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
var self = this;
$scope.$parent.tab = 1;
self.courses = [];
self.newName = '';
self.newPar = '';
self.newNumberOfHoles = '';
self.save = function() {
if (!self.newName || self.newPar < 1 || self.newNumberOfHoles < 1) {
return;
}
var courseToSave = {
'name': self.newName,
'par': self.newPar,
'numberOfHoles': self.newNumberOfHoles
};
$http.post('/api/courses', courseToSave)
.success(function() {
self.courses.push(courseToSave);
})
.error(function(e) {
Materialize.toast('OH NOES! Error saving course', 3000, 'rounded');
});
};
$http.get('/api/courses')
.success(function(data) {
self.courses.length = 0;
data.forEach(function(c) {
self.courses.push(c);
});
});
}]);
app.controller('PlayerCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
var self = this;
$scope.$parent.tab = 2;
self.players = [];
self.newPlayerName = '';
self.save = function() {
if (!self.newPlayerName) return;
var playerToSave = { 'name': self.newPlayerName };
$http.post('/api/players', playerToSave)
.success(function() {
self.players.push(playerToSave);
})
.error(function(e) {
Materialize.toast('Welp... Error saving player', 3000, 'rounded');
});
self.newPlayerName = '';
};
$http.get('/api/players')
.success(function(data) {
self.players.length = 0;
data.forEach(function(p) {
self.players.push(p);
});
});
}]);
})();
|
// Declare app level module which depends on views, and components
var tripPlannerApp = angular.module('webApp', [
'ngRoute',
'ngResource',
'firebase'
]);
tripPlannerApp.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
}).
when('/welcome',{
templateUrl: 'partials/search.html',
controller: 'searchCtrl'
}).
when('/place/:placeId', {
templateUrl: 'partials/place.html',
controller: 'placeCtrl'
}).
when('/register', {
templateUrl: 'partials/register.html',
controller: 'RegisterCtrl'
}).
when('/activities', {
templateUrl: 'partials/activities.html',
controller: 'tripCtrl'
})
.otherwise({redirectTo: '/home'});
}]);
|
const path = require('path');
const webpack = require('webpack');
module.exports = {
// mode: 'production',
// mode: 'development',
mode: 'none',
entry: './test_browser/setup.js',
plugins: [
new webpack.ProgressPlugin(),
],
output: {
path: path.resolve(__dirname, 'test_browser/public'),
filename: 'index.js',
library: {
type: 'umd',
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
},
{
test: /\.css/,
use: [
'style-loader', {
loader: 'css-loader',
},
],
},
],
},
}
|
/*
Your previous Ruby content is preserved below:
Make a Game!
Pseudocode
Adventure Game
inputs: receive user commands to guide through the story
outputs: different story structured off user input
steps:
Initialize player
initialize player commands
give player options
put out story based on input.
end game.
*/
var playerOne = new Object();
var playerCommand = prompt("Type (begin) to start.", ">");
var welcome = "Welcome Traveler! You have been thrust into a strange world of magic and danger! Tread lightly or lose your life to it! Ready to (start)?";
if (playerCommand == "begin"){
alert(welcome);
playerCommand = prompt("Great! Just ahead are three paths. One path is a narrow path with vines and webs along the sides leading into what appears to be total darkness, you carry a light on your person. The second path quickly climbs steeply into the sky leading up to a range of snow-capped mountains, the air is thin and brisk. The third and final path leads to an open field with bright colored daisies and wispy looking clouds, all seems calm.", "Choose one.(first path, second path, third path)");
switch(playerCommand) {
case 'first path':
player = prompt("You enter the path and use your light. Upon further inspection the path dips down a few steps, revealing precious gems and a small group of what appears to be bugs amongst them. The bugs are small in size but great in number. They seem to be swarming on the rocks. What next?(Pick up Gems, Move on, Examine)");
switch(player) {
case 'Pick up Gems':
alert("You stoop down to pick up the gems and the swarm shoots up your arm. It feels like a million tiny pin pricks as the black mass approaches your eye at an almost blinding speed. Ironically the speed blinded you. Everything is black now. You feel the crushing darkness on your body as the mass finishes you off. You have died.");
case 'Move on':
alert("You blatantly ignore the bugs on the ground and step over them. Futher inspection of the path shows the remains of other travelers. You glance over their remains and see some of the bugs where the eyes of the skeletons should be. There is a light ahead. You exit the vines and webs. Unharmed. You live out your days on a mediocre wage and die alone.");
case 'Examine':
alert("You bring your light closer to get a better look at the ground before you. The closer you get the more the bugs disperse. They continue to flee your light till only the gems remain. You take them with glee and live a long and fruitful life.");
};
case 'second path':
playerCommand = prompt("You start the long climb up the moutainside. The air grows thinner and thinner. You wish you brought warmer clothes as you lose feeling in your toes.", "(Keep Going)? or (Turn Back)?");
switch(player) {
case 'Keep Going':
alert("You continue foolishly up the mountains side. To what end? Why even climb a mountain. Especially poorly dressed. The cold should've bothered you.");
case 'Turn Back':
alert("You turn back avoiding the peril. This was a short journey.");
};
case 'third path':
alert("You walk out into the field. All is quiet. The sky is so clear some would say it had a diamond like quality. There is a woman here. She approaches you slowly, she says her name is Lucy. You are never seen again.");
};
};
/*
What was the most difficult part of this challenge?
-The most difficult part of this challenge was deciding what direction I wanted to go in.
What did you learn about creating objects and functions that interact with one another?
-I learned that when creating branching paths the amount of information that can be processed is ridiculous.
Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
-I learned about the switch method which I used to refactor my if statements but I lost that data.
How can you access and manipulate properties of objects?
- You can add to them by simply adding .property to your object
*/
|
/**
* Test case for index.
* Runs with mocha.
*/
'use strict'
const index = require('../lib/index.js')
const assert = require('assert')
describe('index', () => {
before(() => {
})
after(() => {
})
it('Eval props.', () => {
assert.ok(Object.keys(index).length > 0)
for (let name of Object.keys(index)) {
assert.ok(index[ name ], `${name} should exists`)
}
})
})
/* global describe, before, after, it */
|
/* global visit, andThen, currentPath */
import {
describe,
it,
beforeEach,
afterEach
} from 'mocha'
import { expect } from 'chai'
import startApp from '../helpers/start-app'
import Ember from 'ember'
describe('Acceptance: Application', function () {
let application
beforeEach(function () {
application = startApp()
})
afterEach(function () {
Ember.run(application, 'destroy')
})
it('can visit /', function () {
visit('/')
andThen(function () {
expect(currentPath()).to.equal('demo')
})
})
it('can visit /palette', function () {
visit('/palette')
andThen(function () {
expect(currentPath()).to.equal('palette')
})
})
it('can visit /typography', function () {
visit('/typography')
andThen(function () {
expect(currentPath()).to.equal('typography')
})
})
it('can visit /icons', function () {
visit('/icons')
andThen(function () {
expect(currentPath()).to.equal('icons')
})
})
it('can visit /area', function () {
visit('/area')
andThen(function () {
expect(currentPath()).to.equal('area')
})
})
it('can visit /button', function () {
visit('/button')
andThen(function () {
expect(currentPath()).to.equal('button')
})
})
it('can visit /checkbox', function () {
visit('/checkbox')
andThen(function () {
expect(currentPath()).to.equal('checkbox')
})
})
it('can visit /field', function () {
visit('/field')
andThen(function () {
expect(currentPath()).to.equal('field')
})
})
it('can visit /password', function () {
visit('/password')
andThen(function () {
expect(currentPath()).to.equal('password')
})
})
it('can visit /layout', function () {
visit('/layout')
andThen(function () {
expect(currentPath()).to.equal('layout')
})
})
it('can visit /link', function () {
visit('/link')
andThen(function () {
expect(currentPath()).to.equal('link.index')
})
})
})
|
'use strict';
import gulp from 'gulp';
import gulpGhPages from 'gulp-gh-pages';
gulp.task('deploy', ['prod'], function() {
var options = {};
if (process.env.CI)
{
var GH_TOKEN = process.env.GH_TOKEN
options.remoteUrl = `https://${GH_TOKEN}@github.com/megabytemb/Wall-Clock.git`
}
// Any deployment logic should go here
return gulp.src('./build/**/*')
.pipe(gulpGhPages(options));
}); |
/* global VK:false */
'use strict';
import Vue from 'vue';
import VueFlashMessage from 'vue-flash-message';
import VueCookie from 'vue-cookies';
function getIsVkApp() {
function inIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
if (vars.isVkUser) {
return inIframe();
}
return false;
}
window.urls = {};
Vue.use(VueFlashMessage, {
messageOptions: {
timeout: 1500,
important: true,
},
});
Vue.use(VueCookie);
Vue.options.delimiters = ['[[', ']]'];
new Vue({
el: '#menu',
methods: {
changeLanguage: function() {
$('#language-form').submit();
},
invite: function() {
VK.callMethod('showInviteBox');
},
},
});
vars.isVkApp = getIsVkApp();
if (vars.isVkApp) {
$('.vk-app-show').show();
$('#content').addClass('vk');
} else {
$('.vk-app-hide').show();
}
vars.ratySettings = {
hints: [
gettext('Awful'),
gettext('Bad'),
gettext('Regular'),
gettext('Good'),
gettext('Awesome'),
],
cancelHint: gettext('Cancel rating'),
noRatedMsg: gettext('No rating yet'),
cancel: true,
starType: 'i',
score: function() {
return $(this).data('rating');
},
};
|
import SearchForm from './SearchForm';
export default SearchForm;
|
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
define([
'./../KmlElements',
'../KmlObject'
], function (KmlElements,
KmlObject) {
"use strict";
/**
* Constructs an Schema. Application usually don't call this constructor. It is called by {@link KmlFile} as
* Objects from KmlFile are read. It is concrete implementation.
* @alias Schema
* @constructor
* @classdesc Contains the data associated with Kml Schema
* @param options {Object}
* @param options.objectNode {Node} Node representing the Kml Schema.
* @throws {ArgumentError} If either the node is null or undefined.
* @see https://developers.google.com/kml/documentation/kmlreference#itemicon
* @augments KmlObject
*/
var Schema = function (options) {
KmlObject.call(this, options);
};
Schema.prototype = Object.create(KmlObject.prototype);
/**
* @inheritDoc
*/
Schema.prototype.getTagNames = function () {
return ['Schema'];
};
KmlElements.addKey(Schema.prototype.getTagNames()[0], Schema);
return Schema;
}); |
import React from 'react';
const ContactPageDesktop = (props) =>{
return(
<div className="" />
);
};
export default ContactPageDesktop;
|
version https://git-lfs.github.com/spec/v1
oid sha256:736d46ec1073a05ce09019d87f853401913744fe6803355110aeeb3621753713
size 34018
|
game.PlayerEntity = me.Entity.extend({
init: function (x, y, settings) {
this.setSuper(x, y);
this.setPlayerTimers();
this.setAttributes();
this.type = "PlayerEntity";
this.setFlags();
//makes screen follow player
me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
this.addAnimation();
//sets current animation for game start
this.renderable.setCurrentAnimation("idle");
},
setSuper: function (x, y) {
this._super(me.Entity, 'init', [x, y, {
image: "player",
width: 64,
height: 64,
spritewidth: "64",
spriteheight: "64",
getShape: function () {
return(new me.Rect(0, 0, 64, 64)).toPolygon();
}
}]);
},
setPlayerTimers: function () {
this.now = new Date().getTime();
this.lastHit = this.now;
this.lastSpear = this.now;
this.lastAttack = new Date().getTime();
},
setAttributes: function () {
this.body.setVelocity(game.data.playerMoveSpeed += game.data.exp2, 20);
this.health = game.data.playerHealth += game.data.exp4;
this.attack = game.data.playerAttack += game.data.exp3;
},
setFlags: function () {
this.facing = "right";
this.dead = false;
this.attacking = false;
},
addAnimation: function () {
//adds animations for name, frames and speed
this.renderable.addAnimation("idle", [78]);
this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
},
update: function (delta) {
this.now = new Date().getTime();
this.dead = this.checkIfDead();
this.checkKeyPressesAndMove();
this.checkAbilityKeys();
this.setAnimation();
me.collision.check(this, true, this.collideHandler.bind(this), true);
this.body.update(delta);
this._super(me.Entity, "update", [delta]);
return true;
},
checkIfDead: function () {
if (this.health <= 0) {
return true;
}
return false;
},
checkKeyPressesAndMove: function () {
//control for moving right
if (me.input.isKeyPressed("right")) {
this.moveRight();
}
//control for moving left
else if (me.input.isKeyPressed("left")) {
this.moveLeft();
}
//for when mario stands still
else {
this.body.vel.x = 0;
}
//control for jumping
if (me.input.isKeyPressed('jump')) {
this.jump();
}
this.attacking = me.input.isKeyPressed('attack');
},
moveRight: function () {
this.body.vel.x += this.body.accel.x * me.timer.tick;
this.facing = "right";
this.flipX(true);
},
moveLeft: function () {
this.body.vel.x -= this.body.accel.x * me.timer.tick;
this.facing = "left";
this.flipX(false);
},
jump: function () {
// make sure we are not already jumping or falling
if (!this.body.jumping && !this.body.falling) {
// set current vel to the maximum defined value
this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
this.body.jumping = true;
}
},
checkAbilityKeys: function () {
if (me.input.isKeyPressed("ability1")) {
// this.speedBurst();
} else if (me.input.isKeyPressed("ability2")) {
//this.eatCreep();
} else if (me.input.isKeyPressed("ability3")) {
this.throwSpear();
}
},
throwSpear: function () {
if ((this.now - this.lastSpear) >= game.data.spearTimer * 1000 && game.data.ability3 >= 0) {
this.lastSpear = this.now;
var spear = me.pool.pull("spear", this.pos.x, this.pos.y, {}, this.facing);
me.game.world.addChild(spear, 10);
}
},
setAnimation: function () {
if (this.attacking) {
if (!this.renderable.isCurrentAnimation("attack")) {
//sets animation to attack than to idle
this.renderable.setCurrentAnimation("attack", "idle");
//begin from first animation
this.renderable.setAnimationFrame();
}
} else if (this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
if (!this.renderable.isCurrentAnimation("walk")) {
this.renderable.setCurrentAnimation("walk");
this.renderable.setAnimationFrame();
}
} else if (!this.renderable.isCurrentAnimation("attack")) {
this.renderable.setCurrentAnimation("idle");
}
},
loseHealth: function (damage) {
this.health = this.health - damage;
// console.log(this.health);
},
collideHandler: function (response) {
//console.log(this.health);
//collisions with the enemy base
if (response.b.type === 'EnemyBaseEntity') {
this.collideWithEnemyBase(response);
//player collisions with creeps
} else if (response.b.type === "EnemyCreep") {
this.collideWithEnemyCreep(response);
} else if (response.b.type === "PlayerCreep") {
this.collideWithPlayerCreep(response);
}
},
collideWithEnemyBase: function (response) {
var ydif = this.pos.y - response.b.pos.y;
var xdif = this.pos.x - response.b.pos.x;
//collision from the top
if (ydif < -40 && xdif > 70 && xdif < -35) {
this.body.falling = false;
this.body.vel.y = -1;
}
//collision from the left
else if (xdif > -35 && this.facing === "right" && (xdif < 0) && ydif > -50) {
this.body.vel.x = 0;
//collision from the right
} else if (xdif < 70 && this.facing === "left" && (xdif > 0) && ydif > -50) {
this.body.vel.x = 0;
}
//collision from the top
else if (ydif < -40) {
this.body.falling = false;
this.body.vel.y = -1;
}
if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer) {
this.lastHit = this.now;
response.b.loseHealth(game.data.playerAttack);
}
},
collideWithEnemyCreep: function (response) {
var xdif = this.pos.x - response.b.pos.x;
var ydif = this.pos.y - response.b.pos.y;
this.stopMovement(xdif);
if (this.checkAttack(xdif, ydif)) {
this.hitCreep(response);
}
},
collideWithPlayerCreep: function (response) {
},
stopMovement: function (xdif) {
if (xdif > 0) {
this.pos.x = this.pos.x + 1;
if (this.facing === "left") {
this.body.vel.x = 0;
}
} else {
this.pos.x = this.pos.x - 1;
if (this.facing === "right") {
this.body.vel.x = 0;
}
}
},
checkAttack: function (xdif, ydif) {
if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer
&& (Math.abs(ydif) <= 40) &&
(((xdif > 0) && this.facing === "left") || ((xdif < 0) && this.facing === "right"))
) {
this.lastHit = this.now;
//if creep health is less than attack
return true;
}
return false;
},
hitCreep: function (response) {
if (response.b.health <= game.data.playerAttack) {
//adds gold for a creep kill
game.data.gold += 1;
console.log("current gold: " + game.data.gold);
}
response.b.loseHealth(game.data.playerAttack);
}
}); |
/*!
* Bootstrap v3.3.2 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if ("undefined" == typeof jQuery) throw new Error("Bootstrap's JavaScript requires jQuery"); +
function(a) {
"use strict";
var b = a.fn.jquery.split(" ")[0].split(".");
if (b[0] < 2 && b[1] < 9 || 1 == b[0] && 9 == b[1] && b[2] < 1) throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")
} (jQuery),
+
function(a) {
"use strict";
function b() {
var a = document.createElement("bootstrap"),
b = {
WebkitTransition: "webkitTransitionEnd",
MozTransition: "transitionend",
OTransition: "oTransitionEnd otransitionend",
transition: "transitionend"
};
for (var c in b) if (void 0 !== a.style[c]) return {
end: b[c]
};
return ! 1
}
a.fn.emulateTransitionEnd = function(b) {
var c = !1,
d = this;
a(this).one("bsTransitionEnd",
function() {
c = !0
});
var e = function() {
c || a(d).trigger(a.support.transition.end)
};
return setTimeout(e, b),
this
},
a(function() {
a.support.transition = b(),
a.support.transition && (a.event.special.bsTransitionEnd = {
bindType: a.support.transition.end,
delegateType: a.support.transition.end,
handle: function(b) {
return a(b.target).is(this) ? b.handleObj.handler.apply(this, arguments) : void 0
}
})
})
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
return this.each(function() {
var c = a(this),
e = c.data("bs.alert");
e || c.data("bs.alert", e = new d(this)),
"string" == typeof b && e[b].call(c)
})
}
var c = '[data-dismiss="alert"]',
d = function(b) {
a(b).on("click", c, this.close)
};
d.VERSION = "3.3.2",
d.TRANSITION_DURATION = 150,
d.prototype.close = function(b) {
function c() {
g.detach().trigger("closed.bs.alert").remove()
}
var e = a(this),
f = e.attr("data-target");
f || (f = e.attr("href"), f = f && f.replace(/.*(?=#[^\s]*$)/, ""));
var g = a(f);
b && b.preventDefault(),
g.length || (g = e.closest(".alert")),
g.trigger(b = a.Event("close.bs.alert")),
b.isDefaultPrevented() || (g.removeClass("in"), a.support.transition && g.hasClass("fade") ? g.one("bsTransitionEnd", c).emulateTransitionEnd(d.TRANSITION_DURATION) : c())
};
var e = a.fn.alert;
a.fn.alert = b,
a.fn.alert.Constructor = d,
a.fn.alert.noConflict = function() {
return a.fn.alert = e,
this
},
a(document).on("click.bs.alert.data-api", c, d.prototype.close)
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
return this.each(function() {
var d = a(this),
e = d.data("bs.button"),
f = "object" == typeof b && b;
e || d.data("bs.button", e = new c(this, f)),
"toggle" == b ? e.toggle() : b && e.setState(b)
})
}
var c = function(b, d) {
this.$element = a(b),
this.options = a.extend({},
c.DEFAULTS, d),
this.isLoading = !1
};
c.VERSION = "3.3.2",
c.DEFAULTS = {
loadingText: "loading..."
},
c.prototype.setState = function(b) {
var c = "disabled",
d = this.$element,
e = d.is("input") ? "val": "html",
f = d.data();
b += "Text",
null == f.resetText && d.data("resetText", d[e]()),
setTimeout(a.proxy(function() {
d[e](null == f[b] ? this.options[b] : f[b]),
"loadingText" == b ? (this.isLoading = !0, d.addClass(c).attr(c, c)) : this.isLoading && (this.isLoading = !1, d.removeClass(c).removeAttr(c))
},
this), 0)
},
c.prototype.toggle = function() {
var a = !0,
b = this.$element.closest('[data-toggle="buttons"]');
if (b.length) {
var c = this.$element.find("input");
"radio" == c.prop("type") && (c.prop("checked") && this.$element.hasClass("active") ? a = !1 : b.find(".active").removeClass("active")),
a && c.prop("checked", !this.$element.hasClass("active")).trigger("change")
} else this.$element.attr("aria-pressed", !this.$element.hasClass("active"));
a && this.$element.toggleClass("active")
};
var d = a.fn.button;
a.fn.button = b,
a.fn.button.Constructor = c,
a.fn.button.noConflict = function() {
return a.fn.button = d,
this
},
a(document).on("click.bs.button.data-api", '[data-toggle^="button"]',
function(c) {
var d = a(c.target);
d.hasClass("btn") || (d = d.closest(".btn")),
b.call(d, "toggle"),
c.preventDefault()
}).on("focus.bs.button.data-api blur.bs.button.data-api", '[data-toggle^="button"]',
function(b) {
a(b.target).closest(".btn").toggleClass("focus", /^focus(in)?$/.test(b.type))
})
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
return this.each(function() {
var d = a(this),
e = d.data("bs.carousel"),
f = a.extend({},
c.DEFAULTS, d.data(), "object" == typeof b && b),
g = "string" == typeof b ? b: f.slide;
e || d.data("bs.carousel", e = new c(this, f)),
"number" == typeof b ? e.to(b) : g ? e[g]() : f.interval && e.pause().cycle()
})
}
var c = function(b, c) {
this.$element = a(b),
this.$indicators = this.$element.find(".carousel-indicators"),
this.options = c,
this.paused = this.sliding = this.interval = this.$active = this.$items = null,
this.options.keyboard && this.$element.on("keydown.bs.carousel", a.proxy(this.keydown, this)),
"hover" == this.options.pause && !("ontouchstart" in document.documentElement) && this.$element.on("mouseenter.bs.carousel", a.proxy(this.pause, this)).on("mouseleave.bs.carousel", a.proxy(this.cycle, this))
};
c.VERSION = "3.3.2",
c.TRANSITION_DURATION = 600,
c.DEFAULTS = {
interval: 5e3,
pause: "hover",
wrap: !0,
keyboard: !0
},
c.prototype.keydown = function(a) {
if (!/input|textarea/i.test(a.target.tagName)) {
switch (a.which) {
case 37:
this.prev();
break;
case 39:
this.next();
break;
default:
return
}
a.preventDefault()
}
},
c.prototype.cycle = function(b) {
return b || (this.paused = !1),
this.interval && clearInterval(this.interval),
this.options.interval && !this.paused && (this.interval = setInterval(a.proxy(this.next, this), this.options.interval)),
this
},
c.prototype.getItemIndex = function(a) {
return this.$items = a.parent().children(".item"),
this.$items.index(a || this.$active)
},
c.prototype.getItemForDirection = function(a, b) {
var c = this.getItemIndex(b),
d = "prev" == a && 0 === c || "next" == a && c == this.$items.length - 1;
if (d && !this.options.wrap) return b;
var e = "prev" == a ? -1 : 1,
f = (c + e) % this.$items.length;
return this.$items.eq(f)
},
c.prototype.to = function(a) {
var b = this,
c = this.getItemIndex(this.$active = this.$element.find(".item.active"));
return a > this.$items.length - 1 || 0 > a ? void 0 : this.sliding ? this.$element.one("slid.bs.carousel",
function() {
b.to(a)
}) : c == a ? this.pause().cycle() : this.slide(a > c ? "next": "prev", this.$items.eq(a))
},
c.prototype.pause = function(b) {
return b || (this.paused = !0),
this.$element.find(".next, .prev").length && a.support.transition && (this.$element.trigger(a.support.transition.end), this.cycle(!0)),
this.interval = clearInterval(this.interval),
this
},
c.prototype.next = function() {
return this.sliding ? void 0 : this.slide("next")
},
c.prototype.prev = function() {
return this.sliding ? void 0 : this.slide("prev")
},
c.prototype.slide = function(b, d) {
var e = this.$element.find(".item.active"),
f = d || this.getItemForDirection(b, e),
g = this.interval,
h = "next" == b ? "left": "right",
i = this;
if (f.hasClass("active")) return this.sliding = !1;
var j = f[0],
k = a.Event("slide.bs.carousel", {
relatedTarget: j,
direction: h
});
if (this.$element.trigger(k), !k.isDefaultPrevented()) {
if (this.sliding = !0, g && this.pause(), this.$indicators.length) {
this.$indicators.find(".active").removeClass("active");
var l = a(this.$indicators.children()[this.getItemIndex(f)]);
l && l.addClass("active")
}
var m = a.Event("slid.bs.carousel", {
relatedTarget: j,
direction: h
});
return a.support.transition && this.$element.hasClass("slide") ? (f.addClass(b), f[0].offsetWidth, e.addClass(h), f.addClass(h), e.one("bsTransitionEnd",
function() {
f.removeClass([b, h].join(" ")).addClass("active"),
e.removeClass(["active", h].join(" ")),
i.sliding = !1,
setTimeout(function() {
i.$element.trigger(m)
},
0)
}).emulateTransitionEnd(c.TRANSITION_DURATION)) : (e.removeClass("active"), f.addClass("active"), this.sliding = !1, this.$element.trigger(m)),
g && this.cycle(),
this
}
};
var d = a.fn.carousel;
a.fn.carousel = b,
a.fn.carousel.Constructor = c,
a.fn.carousel.noConflict = function() {
return a.fn.carousel = d,
this
};
var e = function(c) {
var d, e = a(this),
f = a(e.attr("data-target") || (d = e.attr("href")) && d.replace(/.*(?=#[^\s]+$)/, ""));
if (f.hasClass("carousel")) {
var g = a.extend({},
f.data(), e.data()),
h = e.attr("data-slide-to");
h && (g.interval = !1),
b.call(f, g),
h && f.data("bs.carousel").to(h),
c.preventDefault()
}
};
a(document).on("click.bs.carousel.data-api", "[data-slide]", e).on("click.bs.carousel.data-api", "[data-slide-to]", e),
a(window).on("load",
function() {
a('[data-ride="carousel"]').each(function() {
var c = a(this);
b.call(c, c.data())
})
})
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
var c, d = b.attr("data-target") || (c = b.attr("href")) && c.replace(/.*(?=#[^\s]+$)/, "");
return a(d)
}
function c(b) {
return this.each(function() {
var c = a(this),
e = c.data("bs.collapse"),
f = a.extend({},
d.DEFAULTS, c.data(), "object" == typeof b && b); ! e && f.toggle && "show" == b && (f.toggle = !1),
e || c.data("bs.collapse", e = new d(this, f)),
"string" == typeof b && e[b]()
})
}
var d = function(b, c) {
this.$element = a(b),
this.options = a.extend({},
d.DEFAULTS, c),
this.$trigger = a(this.options.trigger).filter('[href="#' + b.id + '"], [data-target="#' + b.id + '"]'),
this.transitioning = null,
this.options.parent ? this.$parent = this.getParent() : this.addAriaAndCollapsedClass(this.$element, this.$trigger),
this.options.toggle && this.toggle()
};
d.VERSION = "3.3.2",
d.TRANSITION_DURATION = 350,
d.DEFAULTS = {
toggle: !0,
trigger: '[data-toggle="collapse"]'
},
d.prototype.dimension = function() {
var a = this.$element.hasClass("width");
return a ? "width": "height"
},
d.prototype.show = function() {
if (!this.transitioning && !this.$element.hasClass("in")) {
var b, e = this.$parent && this.$parent.children(".panel").children(".in, .collapsing");
if (! (e && e.length && (b = e.data("bs.collapse"), b && b.transitioning))) {
var f = a.Event("show.bs.collapse");
if (this.$element.trigger(f), !f.isDefaultPrevented()) {
e && e.length && (c.call(e, "hide"), b || e.data("bs.collapse", null));
var g = this.dimension();
this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded", !0),
this.$trigger.removeClass("collapsed").attr("aria-expanded", !0),
this.transitioning = 1;
var h = function() {
this.$element.removeClass("collapsing").addClass("collapse in")[g](""),
this.transitioning = 0,
this.$element.trigger("shown.bs.collapse")
};
if (!a.support.transition) return h.call(this);
var i = a.camelCase(["scroll", g].join("-"));
this.$element.one("bsTransitionEnd", a.proxy(h, this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])
}
}
}
},
d.prototype.hide = function() {
if (!this.transitioning && this.$element.hasClass("in")) {
var b = a.Event("hide.bs.collapse");
if (this.$element.trigger(b), !b.isDefaultPrevented()) {
var c = this.dimension();
this.$element[c](this.$element[c]())[0].offsetHeight,
this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded", !1),
this.$trigger.addClass("collapsed").attr("aria-expanded", !1),
this.transitioning = 1;
var e = function() {
this.transitioning = 0,
this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")
};
return a.support.transition ? void this.$element[c](0).one("bsTransitionEnd", a.proxy(e, this)).emulateTransitionEnd(d.TRANSITION_DURATION) : e.call(this)
}
}
},
d.prototype.toggle = function() {
this[this.$element.hasClass("in") ? "hide": "show"]()
},
d.prototype.getParent = function() {
return a(this.options.parent).find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]').each(a.proxy(function(c, d) {
var e = a(d);
this.addAriaAndCollapsedClass(b(e), e)
},
this)).end()
},
d.prototype.addAriaAndCollapsedClass = function(a, b) {
var c = a.hasClass("in");
a.attr("aria-expanded", c),
b.toggleClass("collapsed", !c).attr("aria-expanded", c)
};
var e = a.fn.collapse;
a.fn.collapse = c,
a.fn.collapse.Constructor = d,
a.fn.collapse.noConflict = function() {
return a.fn.collapse = e,
this
},
a(document).on("click.bs.collapse.data-api", '[data-toggle="collapse"]',
function(d) {
var e = a(this);
e.attr("data-target") || d.preventDefault();
var f = b(e),
g = f.data("bs.collapse"),
h = g ? "toggle": a.extend({},
e.data(), {
trigger: this
});
c.call(f, h)
})
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
b && 3 === b.which || (a(e).remove(), a(f).each(function() {
var d = a(this),
e = c(d),
f = {
relatedTarget: this
};
e.hasClass("open") && (e.trigger(b = a.Event("hide.bs.dropdown", f)), b.isDefaultPrevented() || (d.attr("aria-expanded", "false"), e.removeClass("open").trigger("hidden.bs.dropdown", f)))
}))
}
function c(b) {
var c = b.attr("data-target");
c || (c = b.attr("href"), c = c && /#[A-Za-z]/.test(c) && c.replace(/.*(?=#[^\s]*$)/, ""));
var d = c && a(c);
return d && d.length ? d: b.parent()
}
function d(b) {
return this.each(function() {
var c = a(this),
d = c.data("bs.dropdown");
d || c.data("bs.dropdown", d = new g(this)),
"string" == typeof b && d[b].call(c)
})
}
var e = ".dropdown-backdrop",
f = '[data-toggle="dropdown"]',
g = function(b) {
a(b).on("click.bs.dropdown", this.toggle)
};
g.VERSION = "3.3.2",
g.prototype.toggle = function(d) {
var e = a(this);
if (!e.is(".disabled, :disabled")) {
var f = c(e),
g = f.hasClass("open");
if (b(), !g) {
"ontouchstart" in document.documentElement && !f.closest(".navbar-nav").length && a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click", b);
var h = {
relatedTarget: this
};
if (f.trigger(d = a.Event("show.bs.dropdown", h)), d.isDefaultPrevented()) return;
e.trigger("focus").attr("aria-expanded", "true"),
f.toggleClass("open").trigger("shown.bs.dropdown", h)
}
return ! 1
}
},
g.prototype.keydown = function(b) {
if (/(38|40|27|32)/.test(b.which) && !/input|textarea/i.test(b.target.tagName)) {
var d = a(this);
if (b.preventDefault(), b.stopPropagation(), !d.is(".disabled, :disabled")) {
var e = c(d),
g = e.hasClass("open");
if (!g && 27 != b.which || g && 27 == b.which) return 27 == b.which && e.find(f).trigger("focus"),
d.trigger("click");
var h = " li:not(.divider):visible a",
i = e.find('[role="menu"]' + h + ', [role="listbox"]' + h);
if (i.length) {
var j = i.index(b.target);
38 == b.which && j > 0 && j--,
40 == b.which && j < i.length - 1 && j++,
~j || (j = 0),
i.eq(j).trigger("focus")
}
}
}
};
var h = a.fn.dropdown;
a.fn.dropdown = d,
a.fn.dropdown.Constructor = g,
a.fn.dropdown.noConflict = function() {
return a.fn.dropdown = h,
this
},
a(document).on("click.bs.dropdown.data-api", b).on("click.bs.dropdown.data-api", ".dropdown form",
function(a) {
a.stopPropagation()
}).on("click.bs.dropdown.data-api", f, g.prototype.toggle).on("keydown.bs.dropdown.data-api", f, g.prototype.keydown).on("keydown.bs.dropdown.data-api", '[role="menu"]', g.prototype.keydown).on("keydown.bs.dropdown.data-api", '[role="listbox"]', g.prototype.keydown)
} (jQuery),
+
function(a) {
"use strict";
function b(b, d) {
return this.each(function() {
var e = a(this),
f = e.data("bs.modal"),
g = a.extend({},
c.DEFAULTS, e.data(), "object" == typeof b && b);
f || e.data("bs.modal", f = new c(this, g)),
"string" == typeof b ? f[b](d) : g.show && f.show(d)
})
}
var c = function(b, c) {
this.options = c,
this.$body = a(document.body),
this.$element = a(b),
this.$backdrop = this.isShown = null,
this.scrollbarWidth = 0,
this.options.remote && this.$element.find(".modal-content").load(this.options.remote, a.proxy(function() {
this.$element.trigger("loaded.bs.modal")
},
this))
};
c.VERSION = "3.3.2",
c.TRANSITION_DURATION = 300,
c.BACKDROP_TRANSITION_DURATION = 150,
c.DEFAULTS = {
backdrop: !0,
keyboard: !0,
show: !0
},
c.prototype.toggle = function(a) {
return this.isShown ? this.hide() : this.show(a)
},
c.prototype.show = function(b) {
var d = this,
e = a.Event("show.bs.modal", {
relatedTarget: b
});
this.$element.trigger(e),
this.isShown || e.isDefaultPrevented() || (this.isShown = !0, this.checkScrollbar(), this.setScrollbar(), this.$body.addClass("modal-open"), this.escape(), this.resize(), this.$element.on("click.dismiss.bs.modal", '[data-dismiss="modal"]', a.proxy(this.hide, this)), this.backdrop(function() {
var e = a.support.transition && d.$element.hasClass("fade");
d.$element.parent().length || d.$element.appendTo(d.$body),
d.$element.show().scrollTop(0),
d.options.backdrop && d.adjustBackdrop(),
d.adjustDialog(),
e && d.$element[0].offsetWidth,
d.$element.addClass("in").attr("aria-hidden", !1),
d.enforceFocus();
var f = a.Event("shown.bs.modal", {
relatedTarget: b
});
e ? d.$element.find(".modal-dialog").one("bsTransitionEnd",
function() {
d.$element.trigger("focus").trigger(f)
}).emulateTransitionEnd(c.TRANSITION_DURATION) : d.$element.trigger("focus").trigger(f)
}))
},
c.prototype.hide = function(b) {
b && b.preventDefault(),
b = a.Event("hide.bs.modal"),
this.$element.trigger(b),
this.isShown && !b.isDefaultPrevented() && (this.isShown = !1, this.escape(), this.resize(), a(document).off("focusin.bs.modal"), this.$element.removeClass("in").attr("aria-hidden", !0).off("click.dismiss.bs.modal"), a.support.transition && this.$element.hasClass("fade") ? this.$element.one("bsTransitionEnd", a.proxy(this.hideModal, this)).emulateTransitionEnd(c.TRANSITION_DURATION) : this.hideModal())
},
c.prototype.enforceFocus = function() {
a(document).off("focusin.bs.modal").on("focusin.bs.modal", a.proxy(function(a) {
this.$element[0] === a.target || this.$element.has(a.target).length || this.$element.trigger("focus")
},
this))
},
c.prototype.escape = function() {
this.isShown && this.options.keyboard ? this.$element.on("keydown.dismiss.bs.modal", a.proxy(function(a) {
27 == a.which && this.hide()
},
this)) : this.isShown || this.$element.off("keydown.dismiss.bs.modal")
},
c.prototype.resize = function() {
this.isShown ? a(window).on("resize.bs.modal", a.proxy(this.handleUpdate, this)) : a(window).off("resize.bs.modal")
},
c.prototype.hideModal = function() {
var a = this;
this.$element.hide(),
this.backdrop(function() {
a.$body.removeClass("modal-open"),
a.resetAdjustments(),
a.resetScrollbar(),
a.$element.trigger("hidden.bs.modal")
})
},
c.prototype.removeBackdrop = function() {
this.$backdrop && this.$backdrop.remove(),
this.$backdrop = null
},
c.prototype.backdrop = function(b) {
var d = this,
e = this.$element.hasClass("fade") ? "fade": "";
if (this.isShown && this.options.backdrop) {
var f = a.support.transition && e;
if (this.$backdrop = a('<div class="modal-backdrop ' + e + '" />').prependTo(this.$element).on("click.dismiss.bs.modal", a.proxy(function(a) {
a.target === a.currentTarget && ("static" == this.options.backdrop ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this))
},
this)), f && this.$backdrop[0].offsetWidth, this.$backdrop.addClass("in"), !b) return;
f ? this.$backdrop.one("bsTransitionEnd", b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION) : b()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass("in");
var g = function() {
d.removeBackdrop(),
b && b()
};
a.support.transition && this.$element.hasClass("fade") ? this.$backdrop.one("bsTransitionEnd", g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION) : g()
} else b && b()
},
c.prototype.handleUpdate = function() {
this.options.backdrop && this.adjustBackdrop(),
this.adjustDialog()
},
c.prototype.adjustBackdrop = function() {
this.$backdrop.css("height", 0).css("height", this.$element[0].scrollHeight)
},
c.prototype.adjustDialog = function() {
var a = this.$element[0].scrollHeight > document.documentElement.clientHeight;
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && a ? this.scrollbarWidth: "",
paddingRight: this.bodyIsOverflowing && !a ? this.scrollbarWidth: ""
})
},
c.prototype.resetAdjustments = function() {
this.$element.css({
paddingLeft: "",
paddingRight: ""
})
},
c.prototype.checkScrollbar = function() {
this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight,
this.scrollbarWidth = this.measureScrollbar()
},
c.prototype.setScrollbar = function() {
var a = parseInt(this.$body.css("padding-right") || 0, 10);
this.bodyIsOverflowing && this.$body.css("padding-right", a + this.scrollbarWidth)
},
c.prototype.resetScrollbar = function() {
this.$body.css("padding-right", "")
},
c.prototype.measureScrollbar = function() {
var a = document.createElement("div");
a.className = "modal-scrollbar-measure",
this.$body.append(a);
var b = a.offsetWidth - a.clientWidth;
return this.$body[0].removeChild(a),
b
};
var d = a.fn.modal;
a.fn.modal = b,
a.fn.modal.Constructor = c,
a.fn.modal.noConflict = function() {
return a.fn.modal = d,
this
},
a(document).on("click.bs.modal.data-api", '[data-toggle="modal"]',
function(c) {
var d = a(this),
e = d.attr("href"),
f = a(d.attr("data-target") || e && e.replace(/.*(?=#[^\s]+$)/, "")),
g = f.data("bs.modal") ? "toggle": a.extend({
remote: !/#/.test(e) && e
},
f.data(), d.data());
d.is("a") && c.preventDefault(),
f.one("show.bs.modal",
function(a) {
a.isDefaultPrevented() || f.one("hidden.bs.modal",
function() {
d.is(":visible") && d.trigger("focus")
})
}),
b.call(f, g, this)
})
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
return this.each(function() {
var d = a(this),
e = d.data("bs.tooltip"),
f = "object" == typeof b && b; (e || "destroy" != b) && (e || d.data("bs.tooltip", e = new c(this, f)), "string" == typeof b && e[b]())
})
}
var c = function(a, b) {
this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null,
this.init("tooltip", a, b)
};
c.VERSION = "3.3.2",
c.TRANSITION_DURATION = 150,
c.DEFAULTS = {
animation: !0,
placement: "top",
selector: !1,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: "hover focus",
title: "",
delay: 0,
html: !1,
container: !1,
viewport: {
selector: "body",
padding: 0
}
},
c.prototype.init = function(b, c, d) {
this.enabled = !0,
this.type = b,
this.$element = a(c),
this.options = this.getOptions(d),
this.$viewport = this.options.viewport && a(this.options.viewport.selector || this.options.viewport);
for (var e = this.options.trigger.split(" "), f = e.length; f--;) {
var g = e[f];
if ("click" == g) this.$element.on("click." + this.type, this.options.selector, a.proxy(this.toggle, this));
else if ("manual" != g) {
var h = "hover" == g ? "mouseenter": "focusin",
i = "hover" == g ? "mouseleave": "focusout";
this.$element.on(h + "." + this.type, this.options.selector, a.proxy(this.enter, this)),
this.$element.on(i + "." + this.type, this.options.selector, a.proxy(this.leave, this))
}
}
this.options.selector ? this._options = a.extend({},
this.options, {
trigger: "manual",
selector: ""
}) : this.fixTitle()
},
c.prototype.getDefaults = function() {
return c.DEFAULTS
},
c.prototype.getOptions = function(b) {
return b = a.extend({},
this.getDefaults(), this.$element.data(), b),
b.delay && "number" == typeof b.delay && (b.delay = {
show: b.delay,
hide: b.delay
}),
b
},
c.prototype.getDelegateOptions = function() {
var b = {},
c = this.getDefaults();
return this._options && a.each(this._options,
function(a, d) {
c[a] != d && (b[a] = d)
}),
b
},
c.prototype.enter = function(b) {
var c = b instanceof this.constructor ? b: a(b.currentTarget).data("bs." + this.type);
return c && c.$tip && c.$tip.is(":visible") ? void(c.hoverState = "in") : (c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c)), clearTimeout(c.timeout), c.hoverState = "in", c.options.delay && c.options.delay.show ? void(c.timeout = setTimeout(function() {
"in" == c.hoverState && c.show()
},
c.options.delay.show)) : c.show())
},
c.prototype.leave = function(b) {
var c = b instanceof this.constructor ? b: a(b.currentTarget).data("bs." + this.type);
return c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c)),
clearTimeout(c.timeout),
c.hoverState = "out",
c.options.delay && c.options.delay.hide ? void(c.timeout = setTimeout(function() {
"out" == c.hoverState && c.hide()
},
c.options.delay.hide)) : c.hide()
},
c.prototype.show = function() {
var b = a.Event("show.bs." + this.type);
if (this.hasContent() && this.enabled) {
this.$element.trigger(b);
var d = a.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]);
if (b.isDefaultPrevented() || !d) return;
var e = this,
f = this.tip(),
g = this.getUID(this.type);
this.setContent(),
f.attr("id", g),
this.$element.attr("aria-describedby", g),
this.options.animation && f.addClass("fade");
var h = "function" == typeof this.options.placement ? this.options.placement.call(this, f[0], this.$element[0]) : this.options.placement,
i = /\s?auto?\s?/i,
j = i.test(h);
j && (h = h.replace(i, "") || "top"),
f.detach().css({
top: 0,
left: 0,
display: "block"
}).addClass(h).data("bs." + this.type, this),
this.options.container ? f.appendTo(this.options.container) : f.insertAfter(this.$element);
var k = this.getPosition(),
l = f[0].offsetWidth,
m = f[0].offsetHeight;
if (j) {
var n = h,
o = this.options.container ? a(this.options.container) : this.$element.parent(),
p = this.getPosition(o);
h = "bottom" == h && k.bottom + m > p.bottom ? "top": "top" == h && k.top - m < p.top ? "bottom": "right" == h && k.right + l > p.width ? "left": "left" == h && k.left - l < p.left ? "right": h,
f.removeClass(n).addClass(h)
}
var q = this.getCalculatedOffset(h, k, l, m);
this.applyPlacement(q, h);
var r = function() {
var a = e.hoverState;
e.$element.trigger("shown.bs." + e.type),
e.hoverState = null,
"out" == a && e.leave(e)
};
a.support.transition && this.$tip.hasClass("fade") ? f.one("bsTransitionEnd", r).emulateTransitionEnd(c.TRANSITION_DURATION) : r()
}
},
c.prototype.applyPlacement = function(b, c) {
var d = this.tip(),
e = d[0].offsetWidth,
f = d[0].offsetHeight,
g = parseInt(d.css("margin-top"), 10),
h = parseInt(d.css("margin-left"), 10);
isNaN(g) && (g = 0),
isNaN(h) && (h = 0),
b.top = b.top + g,
b.left = b.left + h,
a.offset.setOffset(d[0], a.extend({
using: function(a) {
d.css({
top: Math.round(a.top),
left: Math.round(a.left)
})
}
},
b), 0),
d.addClass("in");
var i = d[0].offsetWidth,
j = d[0].offsetHeight;
"top" == c && j != f && (b.top = b.top + f - j);
var k = this.getViewportAdjustedDelta(c, b, i, j);
k.left ? b.left += k.left: b.top += k.top;
var l = /top|bottom/.test(c),
m = l ? 2 * k.left - e + i: 2 * k.top - f + j,
n = l ? "offsetWidth": "offsetHeight";
d.offset(b),
this.replaceArrow(m, d[0][n], l)
},
c.prototype.replaceArrow = function(a, b, c) {
this.arrow().css(c ? "left": "top", 50 * (1 - a / b) + "%").css(c ? "top": "left", "")
},
c.prototype.setContent = function() {
var a = this.tip(),
b = this.getTitle();
a.find(".tooltip-inner")[this.options.html ? "html": "text"](b),
a.removeClass("fade in top bottom left right")
},
c.prototype.hide = function(b) {
function d() {
"in" != e.hoverState && f.detach(),
e.$element.removeAttr("aria-describedby").trigger("hidden.bs." + e.type),
b && b()
}
var e = this,
f = this.tip(),
g = a.Event("hide.bs." + this.type);
return this.$element.trigger(g),
g.isDefaultPrevented() ? void 0 : (f.removeClass("in"), a.support.transition && this.$tip.hasClass("fade") ? f.one("bsTransitionEnd", d).emulateTransitionEnd(c.TRANSITION_DURATION) : d(), this.hoverState = null, this)
},
c.prototype.fixTitle = function() {
var a = this.$element; (a.attr("title") || "string" != typeof a.attr("data-original-title")) && a.attr("data-original-title", a.attr("title") || "").attr("title", "")
},
c.prototype.hasContent = function() {
return this.getTitle()
},
c.prototype.getPosition = function(b) {
b = b || this.$element;
var c = b[0],
d = "BODY" == c.tagName,
e = c.getBoundingClientRect();
null == e.width && (e = a.extend({},
e, {
width: e.right - e.left,
height: e.bottom - e.top
}));
var f = d ? {
top: 0,
left: 0
}: b.offset(),
g = {
scroll: d ? document.documentElement.scrollTop || document.body.scrollTop: b.scrollTop()
},
h = d ? {
width: a(window).width(),
height: a(window).height()
}: null;
return a.extend({},
e, g, h, f)
},
c.prototype.getCalculatedOffset = function(a, b, c, d) {
return "bottom" == a ? {
top: b.top + b.height,
left: b.left + b.width / 2 - c / 2
}: "top" == a ? {
top: b.top - d,
left: b.left + b.width / 2 - c / 2
}: "left" == a ? {
top: b.top + b.height / 2 - d / 2,
left: b.left - c
}: {
top: b.top + b.height / 2 - d / 2,
left: b.left + b.width
}
},
c.prototype.getViewportAdjustedDelta = function(a, b, c, d) {
var e = {
top: 0,
left: 0
};
if (!this.$viewport) return e;
var f = this.options.viewport && this.options.viewport.padding || 0,
g = this.getPosition(this.$viewport);
if (/right|left/.test(a)) {
var h = b.top - f - g.scroll,
i = b.top + f - g.scroll + d;
h < g.top ? e.top = g.top - h: i > g.top + g.height && (e.top = g.top + g.height - i)
} else {
var j = b.left - f,
k = b.left + f + c;
j < g.left ? e.left = g.left - j: k > g.width && (e.left = g.left + g.width - k)
}
return e
},
c.prototype.getTitle = function() {
var a, b = this.$element,
c = this.options;
return a = b.attr("data-original-title") || ("function" == typeof c.title ? c.title.call(b[0]) : c.title)
},
c.prototype.getUID = function(a) {
do a += ~~ (1e6 * Math.random());
while (document.getElementById(a));
return a
},
c.prototype.tip = function() {
return this.$tip = this.$tip || a(this.options.template)
},
c.prototype.arrow = function() {
return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
},
c.prototype.enable = function() {
this.enabled = !0
},
c.prototype.disable = function() {
this.enabled = !1
},
c.prototype.toggleEnabled = function() {
this.enabled = !this.enabled
},
c.prototype.toggle = function(b) {
var c = this;
b && (c = a(b.currentTarget).data("bs." + this.type), c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c))),
c.tip().hasClass("in") ? c.leave(c) : c.enter(c)
},
c.prototype.destroy = function() {
var a = this;
clearTimeout(this.timeout),
this.hide(function() {
a.$element.off("." + a.type).removeData("bs." + a.type)
})
};
var d = a.fn.tooltip;
a.fn.tooltip = b,
a.fn.tooltip.Constructor = c,
a.fn.tooltip.noConflict = function() {
return a.fn.tooltip = d,
this
}
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
return this.each(function() {
var d = a(this),
e = d.data("bs.popover"),
f = "object" == typeof b && b; (e || "destroy" != b) && (e || d.data("bs.popover", e = new c(this, f)), "string" == typeof b && e[b]())
})
}
var c = function(a, b) {
this.init("popover", a, b)
};
if (!a.fn.tooltip) throw new Error("Popover requires tooltip.js");
c.VERSION = "3.3.2",
c.DEFAULTS = a.extend({},
a.fn.tooltip.Constructor.DEFAULTS, {
placement: "right",
trigger: "click",
content: "",
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
}),
c.prototype = a.extend({},
a.fn.tooltip.Constructor.prototype),
c.prototype.constructor = c,
c.prototype.getDefaults = function() {
return c.DEFAULTS
},
c.prototype.setContent = function() {
var a = this.tip(),
b = this.getTitle(),
c = this.getContent();
a.find(".popover-title")[this.options.html ? "html": "text"](b),
a.find(".popover-content").children().detach().end()[this.options.html ? "string" == typeof c ? "html": "append": "text"](c),
a.removeClass("fade top bottom left right in"),
a.find(".popover-title").html() || a.find(".popover-title").hide()
},
c.prototype.hasContent = function() {
return this.getTitle() || this.getContent()
},
c.prototype.getContent = function() {
var a = this.$element,
b = this.options;
return a.attr("data-content") || ("function" == typeof b.content ? b.content.call(a[0]) : b.content)
},
c.prototype.arrow = function() {
return this.$arrow = this.$arrow || this.tip().find(".arrow")
},
c.prototype.tip = function() {
return this.$tip || (this.$tip = a(this.options.template)),
this.$tip
};
var d = a.fn.popover;
a.fn.popover = b,
a.fn.popover.Constructor = c,
a.fn.popover.noConflict = function() {
return a.fn.popover = d,
this
}
} (jQuery),
+
function(a) {
"use strict";
function b(c, d) {
var e = a.proxy(this.process, this);
this.$body = a("body"),
this.$scrollElement = a(a(c).is("body") ? window: c),
this.options = a.extend({},
b.DEFAULTS, d),
this.selector = (this.options.target || "") + " .nav li > a",
this.offsets = [],
this.targets = [],
this.activeTarget = null,
this.scrollHeight = 0,
this.$scrollElement.on("scroll.bs.scrollspy", e),
this.refresh(),
this.process()
}
function c(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.scrollspy"),
f = "object" == typeof c && c;
e || d.data("bs.scrollspy", e = new b(this, f)),
"string" == typeof c && e[c]()
})
}
b.VERSION = "3.3.2",
b.DEFAULTS = {
offset: 10
},
b.prototype.getScrollHeight = function() {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
},
b.prototype.refresh = function() {
var b = "offset",
c = 0;
a.isWindow(this.$scrollElement[0]) || (b = "position", c = this.$scrollElement.scrollTop()),
this.offsets = [],
this.targets = [],
this.scrollHeight = this.getScrollHeight();
var d = this;
this.$body.find(this.selector).map(function() {
var d = a(this),
e = d.data("target") || d.attr("href"),
f = /^#./.test(e) && a(e);
return f && f.length && f.is(":visible") && [[f[b]().top + c, e]] || null
}).sort(function(a, b) {
return a[0] - b[0]
}).each(function() {
d.offsets.push(this[0]),
d.targets.push(this[1])
})
},
b.prototype.process = function() {
var a, b = this.$scrollElement.scrollTop() + this.options.offset,
c = this.getScrollHeight(),
d = this.options.offset + c - this.$scrollElement.height(),
e = this.offsets,
f = this.targets,
g = this.activeTarget;
if (this.scrollHeight != c && this.refresh(), b >= d) return g != (a = f[f.length - 1]) && this.activate(a);
if (g && b < e[0]) return this.activeTarget = null,
this.clear();
for (a = e.length; a--;) g != f[a] && b >= e[a] && (!e[a + 1] || b <= e[a + 1]) && this.activate(f[a])
},
b.prototype.activate = function(b) {
this.activeTarget = b,
this.clear();
var c = this.selector + '[data-target="' + b + '"],' + this.selector + '[href="' + b + '"]',
d = a(c).parents("li").addClass("active");
d.parent(".dropdown-menu").length && (d = d.closest("li.dropdown").addClass("active")),
d.trigger("activate.bs.scrollspy")
},
b.prototype.clear = function() {
a(this.selector).parentsUntil(this.options.target, ".active").removeClass("active")
};
var d = a.fn.scrollspy;
a.fn.scrollspy = c,
a.fn.scrollspy.Constructor = b,
a.fn.scrollspy.noConflict = function() {
return a.fn.scrollspy = d,
this
},
a(window).on("load.bs.scrollspy.data-api",
function() {
a('[data-spy="scroll"]').each(function() {
var b = a(this);
c.call(b, b.data())
})
})
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
return this.each(function() {
var d = a(this),
e = d.data("bs.tab");
e || d.data("bs.tab", e = new c(this)),
"string" == typeof b && e[b]()
})
}
var c = function(b) {
this.element = a(b)
};
c.VERSION = "3.3.2",
c.TRANSITION_DURATION = 150,
c.prototype.show = function() {
var b = this.element,
c = b.closest("ul:not(.dropdown-menu)"),
d = b.data("target");
if (d || (d = b.attr("href"), d = d && d.replace(/.*(?=#[^\s]*$)/, "")), !b.parent("li").hasClass("active")) {
var e = c.find(".active:last a"),
f = a.Event("hide.bs.tab", {
relatedTarget: b[0]
}),
g = a.Event("show.bs.tab", {
relatedTarget: e[0]
});
if (e.trigger(f), b.trigger(g), !g.isDefaultPrevented() && !f.isDefaultPrevented()) {
var h = a(d);
this.activate(b.closest("li"), c),
this.activate(h, h.parent(),
function() {
e.trigger({
type: "hidden.bs.tab",
relatedTarget: b[0]
}),
b.trigger({
type: "shown.bs.tab",
relatedTarget: e[0]
})
})
}
}
},
c.prototype.activate = function(b, d, e) {
function f() {
g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded", !1),
b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded", !0),
h ? (b[0].offsetWidth, b.addClass("in")) : b.removeClass("fade"),
b.parent(".dropdown-menu") && b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded", !0),
e && e()
}
var g = d.find("> .active"),
h = e && a.support.transition && (g.length && g.hasClass("fade") || !!d.find("> .fade").length);
g.length && h ? g.one("bsTransitionEnd", f).emulateTransitionEnd(c.TRANSITION_DURATION) : f(),
g.removeClass("in")
};
var d = a.fn.tab;
a.fn.tab = b,
a.fn.tab.Constructor = c,
a.fn.tab.noConflict = function() {
return a.fn.tab = d,
this
};
var e = function(c) {
c.preventDefault(),
b.call(a(this), "show")
};
a(document).on("click.bs.tab.data-api", '[data-toggle="tab"]', e).on("click.bs.tab.data-api", '[data-toggle="pill"]', e)
} (jQuery),
+
function(a) {
"use strict";
function b(b) {
return this.each(function() {
var d = a(this),
e = d.data("bs.affix"),
f = "object" == typeof b && b;
e || d.data("bs.affix", e = new c(this, f)),
"string" == typeof b && e[b]()
})
}
var c = function(b, d) {
this.options = a.extend({},
c.DEFAULTS, d),
this.$target = a(this.options.target).on("scroll.bs.affix.data-api", a.proxy(this.checkPosition, this)).on("click.bs.affix.data-api", a.proxy(this.checkPositionWithEventLoop, this)),
this.$element = a(b),
this.affixed = this.unpin = this.pinnedOffset = null,
this.checkPosition()
};
c.VERSION = "3.3.2",
c.RESET = "affix affix-top affix-bottom",
c.DEFAULTS = {
offset: 0,
target: window
},
c.prototype.getState = function(a, b, c, d) {
var e = this.$target.scrollTop(),
f = this.$element.offset(),
g = this.$target.height();
if (null != c && "top" == this.affixed) return c > e ? "top": !1;
if ("bottom" == this.affixed) return null != c ? e + this.unpin <= f.top ? !1 : "bottom": a - d >= e + g ? !1 : "bottom";
var h = null == this.affixed,
i = h ? e: f.top,
j = h ? g: b;
return null != c && c >= e ? "top": null != d && i + j >= a - d ? "bottom": !1
},
c.prototype.getPinnedOffset = function() {
if (this.pinnedOffset) return this.pinnedOffset;
this.$element.removeClass(c.RESET).addClass("affix");
var a = this.$target.scrollTop(),
b = this.$element.offset();
return this.pinnedOffset = b.top - a
},
c.prototype.checkPositionWithEventLoop = function() {
setTimeout(a.proxy(this.checkPosition, this), 1)
},
c.prototype.checkPosition = function() {
if (this.$element.is(":visible")) {
var b = this.$element.height(),
d = this.options.offset,
e = d.top,
f = d.bottom,
g = a("body").height();
"object" != typeof d && (f = e = d),
"function" == typeof e && (e = d.top(this.$element)),
"function" == typeof f && (f = d.bottom(this.$element));
var h = this.getState(g, b, e, f);
if (this.affixed != h) {
null != this.unpin && this.$element.css("top", "");
var i = "affix" + (h ? "-" + h: ""),
j = a.Event(i + ".bs.affix");
if (this.$element.trigger(j), j.isDefaultPrevented()) return;
this.affixed = h,
this.unpin = "bottom" == h ? this.getPinnedOffset() : null,
this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix", "affixed") + ".bs.affix")
}
"bottom" == h && this.$element.offset({
top: g - b - f
})
}
};
var d = a.fn.affix;
a.fn.affix = b,
a.fn.affix.Constructor = c,
a.fn.affix.noConflict = function() {
return a.fn.affix = d,
this
},
a(window).on("load",
function() {
a('[data-spy="affix"]').each(function() {
var c = a(this),
d = c.data();
d.offset = d.offset || {},
null != d.offsetBottom && (d.offset.bottom = d.offsetBottom),
null != d.offsetTop && (d.offset.top = d.offsetTop),
b.call(c, d)
})
})
} (jQuery); |
var webpackConfig = require('./config/webpack.test');
module.exports = function (config) {
var _config = {
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
{pattern: './config/karma-shim.js', watched: false}
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'./config/karma-shim.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
// webpack-dev-middleware configuration
stats: 'errors-only'
},
coverageReporter: {
dir: 'coverage/',
reporters: [
{type: 'text-summary'},
{type: 'html'}
]
},
webpackServer: {
noInfo: true // please don't spam the console when running in karma!
},
// test results reporter to use
// possible values: 'dots', 'progress', 'mocha'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha', 'coverage'],
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'], // you can also use Chrome
// Continuous Integration mode
singleRun: false
};
config.set(_config);
};
|
Analytics.Scene.Search = Class.create(Analytics.Util.Details, {
initialize : function ($super, args)
{
$super(args);
this.dataHandler = this.handleData.bind(this);
this.errorHandler = this.handleError.bind(this);
this.filterHandle = this.handleFilter.bind(this);
this.filterChangeHandle = this.handleFilterChange.bind(this);
this.tapHandle = this.handleTap.bind(this);
this.items = [];
},
setup : function ($super)
{
$super();
this.controller.setupWidget(
'search-list',
{
itemTemplate: 'traffic/data-item',
emptyTemplate: 'empty-item',
swipeToDelete: false,
reorderable: false,
renderLimit: 50,
filterFunction: this.filterHandle
}
);
Mojo.Event.listen(this.controller.get('search-list'), Mojo.Event.listTap, this.tapHandle);
Mojo.Event.listen(this.controller.get('search-list'), Mojo.Event.filterImmediate, this.filterChangeHandle);
this.spacerDiv = this.controller.get('empty_spacer');
},
aboutToActivate : function ($super, callback)
{
$super();
},
activate : function ($super)
{
this.controller.get('search-title').update(this.item.title + ' / ' + $L('Search Engines'));
$super();
},
deactivate : function ($super)
{
$super();
},
cleanup : function ($super)
{
this.items = null;
this.handleFilter = null;
this.dataHandler = null;
this.errorHandler = null;
this.spacerDiv = null;
$super();
},
refresh : function ()
{
this.store.invalidate(this.item.id, 'search');
this.items = [];
this.showSpinner();
this.getData();
},
getData : function ()
{
if (this.store.isValid(this.item.id, 'search', this.period, this.startDate, this.endDate)) {
this.render();
}
else {
if (!this.store.get(this.item.id, 'oauth_token')) {
this.getAuth();
}
else {
this.api.getData({
oauth_token: this.store.get(this.item.id, 'oauth_token'),
oauth_secret: this.store.get(this.item.id, 'oauth_secret'),
profileId: this.item.profileId,
metrics: 'ga:visits,ga:pageviews,ga:bounces,ga:timeOnPage,ga:newVisits',
dimensions: 'ga:medium,ga:referralPath,ga:source',
filters: 'ga:medium==organic',
sort: '-ga:visits',
period: this.period,
dateFrom: this.startDate,
dateTo: this.endDate,
onSuccess: this.dataHandler,
onError: this.errorHandler
});
}
}
},
handleData : function (result, startDate, endDate)
{
this.store.set(this.item.id, 'period', this.period);
this.store.set(this.item.id, 'startDate', startDate);
this.store.set(this.item.id, 'endDate', endDate);
if (startDate && endDate) {
this.setTitle(startDate, endDate);
this.startDate = startDate;
this.endDate = endDate;
}
this.store.set(this.item.id, 'search', result);
this.render();
},
handleError : function (error)
{
console.log(Object.toJSON(error));
},
handleFilter : function (filterString, listWidget, offset, count)
{
var items = [];
if (filterString.length > 0)
{
items = this.items.findAll(function (item) {
return item.source.toLowerCase().include(filterString.toLowerCase());
}, this);
}
else
{
items = this.items;
}
this.controller.get('search-list').mojo.noticeUpdatedItems(0, items);
this.controller.get('search-list').mojo.setLength(items.length);
this.controller.get('search-list').mojo.setCount(items.length);
},
handleFilterChange : function (evt)
{
if (evt.filterString.blank()) {
this.spacerDiv.show();
} else {
this.spacerDiv.hide();
}
},
handleTap : function (evt)
{
this.controller.showDialog({
template : 'dialog',
assistant : new Analytics.Scene.TrafficDialog(this, evt.item)
});
},
render : function ()
{
this.items = [];
this.store.get(this.item.id, 'search').each(function (item, index) {
this.items.push({
translation: Analytics.Util.ListTranslation,
source: item['ga:source'],
path: item['ga:referralPath'],
type: item['ga:medium'],
visits: Mojo.Format.formatNumber(Number(item['ga:visits'])),
pv: Mojo.Format.formatNumber(Number(item['ga:pageviews'])/Number(item['ga:visits']), {fractionDigits: 2}),
bounce: Mojo.Format.formatPercent((Number(item['ga:bounces']) / Number(item['ga:visits'])) * 100),
time: this.secondsToTime(Number(item['ga:timeOnPage'])/(Number(item['ga:visits']))),
newVisits: Mojo.Format.formatPercent((Number(item['ga:newVisits']) / Number(item['ga:visits'])) * 100)
});
}, this);
this.controller.get('search-list').mojo.noticeUpdatedItems(0, this.items);
this.controller.get('search-list').mojo.setLength(this.items.length);
this.controller.get('search-list').mojo.setCount(this.items.length);
this.hideSpinner();
},
sortByPagviews : function (a, b) {
var x = Number(a.pageview);
var y = Number(b.pageview);
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
}); |
(function() {
'use strict';
var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
del = require('del'),
browserSync = require('browser-sync'),
reload = browserSync.reload;
/** Configuration & Helper Methods **/
var config = (function () {
var cfg = {};
cfg.port = 3000;
cfg.exitOnError = true;
cfg.env = 'debug';
cfg.destDir = function () {
return ['./dist/', cfg.env].join('');
};
cfg.handleError = function (error) {
var errorMessage = $.util.colors.red(error);
$.util.log(errorMessage);
if (config.exitOnError) { // stops plugin errors killing the Watch task
process.exit(1);
}
};
cfg.isDebug = function () {
return cfg.env === 'debug';
};
cfg.uglifySettings = {
mangle: false
};
return cfg;
})();
// Default Task
gulp.task('default', ['watch']);
// Watch Tasks
gulp.task('watch', ['build:debug', 'connect'], function() {
config.exitOnError = false;
gulp.watch('./src/**/*.scss', ['scss']);
gulp.watch('./src/**/*.js', ['js']);
gulp.watch('./src/index.html', ['index']);
});
/*** Build ***/
gulp.task('build:debug', function(done) {
config.env = 'debug';
$.sequence('clean:debug', ['js', 'scss', 'img'], 'index', done);
});
gulp.task('build:release', function(done) {
config.env = 'release';
$.sequence('clean:release', ['js', 'scss', 'img'], 'index', done);
});
/*** Clean ***/
gulp.task('clean:debug', function(done) {
config.env = 'debug';
del(config.destDir(), {
force: true
}, done);
});
gulp.task('clean:release', function(done) {
config.env = 'release';
del(config.destDir(), {
force: true
}, done);
});
gulp.task('scss', function () {
return $.rubySass('src/assets/scss/main.scss', {
style: (config.isDebug()) ? 'expanded' : 'compressed',
loadPath: ['./bower_components/susy/sass']
})
.on('error', config.handleError)
.pipe(gulp.dest(config.destDir() + '/css'))
.pipe(reload({
stream: true
}));
});
gulp.task('img', function () {
return gulp
.src('./src/assets/img/*.{jpg, png, gif, svg}')
.pipe(gulp.dest(config.destDir() + '/img'))
.pipe(reload({
stream: true
}));
});
gulp.task('js', function() {
return gulp
.src(['./src/assets/js/*.js'])
.pipe($.if(!config.isDebug(), $.concat('app.js')))
.pipe($.if(!config.isDebug(), $.uglify(config.uglifySettings)))
.pipe(gulp.dest(config.destDir() + '/js'))
.pipe(reload({
stream: true
}));
});
gulp.task('index', function() {
var sources = gulp
.src(['./**/*.css', './**/*.js'], {
read: false,
cwd: config.destDir()
});
return gulp
.src('./src/index.html')
.pipe($.inject(sources))
.pipe(gulp.dest(config.destDir()))
.pipe(reload({
stream: true
}));
});
/*** Serve & Reload ***/
gulp.task('browser-sync', function() {
browserSync({
logLevel: 'silent',
open: false
});
});
gulp.task('connect', ['build:debug'], function() {
$.connect.server({
port: 3000,
root: config.destDir(),
proxy: 'localhost:3000'
});
return gulp
.src(config.destDir() + '/index.html')
.pipe($.open('', {
url: 'http://localhost:3000'
}));
});
})(); |
import qs from 'query-string';
import _ from 'lodash';
const LOAD = 'my-app/movies/LOAD';
const LOAD_SUCCESS = 'my-app/movies/LOAD_SUCCESS';
const LOAD_FAIL = 'my-app/movies/LOAD_FAIL';
const DISPLAY = 'my-app/movies/DISPLAY';
const PLAY = 'my-app/movies/PLAY';
const CLOSE = 'my-app/movies/CLOSE';
const GET_MEDIA = 'my-app/movies/GET_MEDIA';
const GET_MEDIA_SUCCESS = 'my-app/movies/GET_MEDIA_SUCCESS';
const GET_MEDIA_FAIL = 'my-app/movies/GET_MEDIA_FAIL';
const initialState = {
loaded: false,
data: {}
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case LOAD:
return {
...state,
loading: true
};
case LOAD_SUCCESS:
let data;
action.result.orders && action.result.orders.forEach(order => {
if (!state.data[order] || action.result.offset >= state.data[order].length) {
data = _.merge(state.data, {[order]: action.result.data[order]}, (a, b) => {
if (Array.isArray(a)) {
return a.concat(b);
}
});
}
});
return {
...state,
loading: false,
loaded: true,
data: data || state.data,
displaying: null
};
case LOAD_FAIL:
return {
...state,
loading: false,
loaded: false,
error: action.error
};
case GET_MEDIA:
return {
...state,
getting: true,
getted: false
};
case GET_MEDIA_SUCCESS:
return {
...state,
getting: false,
getted: true,
media: action.result
};
case GET_MEDIA_FAIL:
return {
...state,
getting: false,
getted: false,
error: action.error
};
case DISPLAY:
if (state.displaying && action.movie.id === state.displaying.id) {
return {
...state,
playUrls: null
};
}
return {
...state,
playUrls: null,
displaying: action.movie
};
case PLAY:
return {
...state,
playUrls: action.urls,
displaying: null,
error: action.error
};
case CLOSE:
return {
...state,
displaying: null,
playUrls: null
};
default:
return state;
}
}
export function isLoaded(globalState) {
return globalState.movies && globalState.movies.loaded;
}
export function load(requireObject = {order: '', limit: '', offset: ''}) {
const {order, limit, offset} = requireObject;
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client) => client.get('/movie/load?' + qs.stringify({order: order || '', limit: limit || '', offset: offset || ''}))
};
}
export function loadAll() {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client) => client.get('/movie/load/all')
};
}
export function display(movie) {
return {
type: DISPLAY,
movie: movie
};
}
export function getMedia(id) {
return {
types: [GET_MEDIA, GET_MEDIA_SUCCESS, GET_MEDIA_FAIL],
promise: (client) => client.get('/movie/play/' + id)
};
}
export function play(media) {
let urls;
let err;
if (media.permanent_url && media.permanent_url.length !== 0) {
urls = media.permanent_url;
} else if (media.temporary_url && media.temporary_url.length !== 0) {
urls = media.temporary_url;
} else {
err = 'NO WORKING URL!';
}
return {
type: PLAY,
urls: urls || [],
error: err || ''
};
}
export function close() {
return {
type: CLOSE
};
}
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import styles from './ExampleStandard.scss';
import Notification from './Notification';
import {LOCAL_NOTIFICATION, GLOBAL_NOTIFICATION, STICKY_NOTIFICATION, DEFAULT_TIMEOUT} from '../../src/Notification';
import Label from '../../src/Label';
import ToggleSwitch from '../../src/ToggleSwitch';
import RadioGroup from '../../src/RadioGroup';
import Input from '../../src/Input';
class ExampleStandard extends Component {
static propTypes = {
onChange: PropTypes.func,
theme: PropTypes.string
};
state = {
notification: {
show: true,
type: GLOBAL_NOTIFICATION,
size: 'big',
timeout: DEFAULT_TIMEOUT,
zIndex: 10000
},
actionButton: {
type: 'button',
text: 'Thanks',
link: 'https://www.wix.com'
}
};
setComponentState(componentName, obj) {
this.setState(prevState => {
prevState[componentName] = {...this.state[componentName], ...obj};
Object.keys(prevState[componentName])
.forEach(k => !prevState[componentName][k] && delete prevState[componentName][k]);
return prevState;
});
}
setNotificationSize(actionButtonType) {
const actionButtonIsShown = actionButtonType !== 'none';
const size = actionButtonIsShown && actionButtonType === 'button' ? 'big' : 'small';
this.setComponentState('notification', {size});
}
render() {
const params = {...this.state};
params.notification.theme = this.props.theme;
return (
<form className={styles.form}>
<div className={styles.output}>
<Notification {...params} onChange={this.props.onChange}/>
</div>
<div className={styles.input}>
<div className={styles.option}>
<div className={styles.flex}>
<Label>This text will be covered by a local notification</Label>
</div>
<hr/>
</div>
<div className={styles.option}>
<Label>Show Notification</Label>
<div className={styles.flex}>
<ToggleSwitch
size="small"
checked={this.state.notification.show}
onChange={() => this.setComponentState('notification', {show: !this.state.notification.show})}
/>
</div>
</div>
<div className={styles.option}>
<Label>Type</Label>
<div className={styles.flex}>
<RadioGroup
display="horizontal"
value={this.state.notification.type}
onChange={type => this.setComponentState('notification', {type})}
>
<RadioGroup.Radio value={GLOBAL_NOTIFICATION}>Global (push the content)</RadioGroup.Radio>
<RadioGroup.Radio value={LOCAL_NOTIFICATION}>Local (on top of the content)</RadioGroup.Radio>
<RadioGroup.Radio value={STICKY_NOTIFICATION}>Sticky (at screen top)</RadioGroup.Radio>
</RadioGroup>
</div>
</div>
{
this.state.notification.type !== GLOBAL_NOTIFICATION ?
<div className={styles.option}>
<Label>Timeout in ms (for local notifications)</Label>
<div className={styles.column}>
<Input
placeholder="Set the timeout" size="small" type="number"
value={this.state.notification.timeout}
onChange={e => this.setComponentState('notification', {timeout: Number(e.target.value)})}
/>
</div>
</div> :
null
}
<div className={styles.option}>
<Label>Button Type</Label>
<div className={styles.flex}>
<RadioGroup
display="horizontal"
value={this.state.actionButton.type}
onChange={type => {
this.setComponentState('actionButton', {type});
this.setNotificationSize(type);
}}
>
<RadioGroup.Radio value="button">Button</RadioGroup.Radio>
<RadioGroup.Radio value="textLink">TextLink</RadioGroup.Radio>
<RadioGroup.Radio value="none">None</RadioGroup.Radio>
</RadioGroup>
</div>
</div>
{
(this.state.actionButton.type === 'none') ? null :
<div>
{
this.state.actionButton.type !== 'textLink' ? null :
<div className={styles.option}>
<Label>Link</Label>
<div className={styles.flex}>
<Input
value={this.state.actionButton.link} size="small"
onChange={event => this.setComponentState('actionButton', {link: event.target.value})}
/>
</div>
</div>
}
<div className={styles.option}>
<Label>Text</Label>
<div className={styles.flex}>
<Input
value={this.state.actionButton.text} size="small"
onChange={event => this.setComponentState('actionButton', {text: event.target.value})}
/>
</div>
</div>
</div>
}
</div>
<div className={styles.option}>
<Label>z-index (optional)</Label>
<div className={styles.column}>
<Input
placeholder="optional z-index" size="small" type="number"
value={this.state.notification.zIndex}
onChange={e => this.setComponentState('notification', {zIndex: Number(e.target.value)})}
/>
</div>
</div>
</form>
);
}
}
export default ExampleStandard;
|
angular.module('<%= directiveModule %>'<%= newModule %>)
.directive('<%= _.camelize(directiveName) %>', function() {
return {
restrict: 'E',
replace: true,
scope: {
},
templateUrl: 'view.html',
link: function(scope, element, attrs, fn) {
}
};
});
|
(function () {
var module = angular.module('gooey', []);
module.factory('RecursionHelper', function ($compile) {
return {
compile: function (element) {
var contents = element.contents().remove();
var compiledContents;
return function (scope, element) {
if(!compiledContents){
compiledContents = $compile(contents);
}
compiledContents(scope, function (clone) {
element.append(clone);
});
};
}
};
});
module.directive('gyMain', function () {
return {
restrict: 'E',
replace: true,
templateUrl: 'templates/main.html',
controller: function ($scope) {
$scope.rootPanel = {
rows: ['main 1', 'main 2'],
subpanel: {
position: 'bottom',
height: 100,
panel: {
rows: ['main bottom 1', 'main bottom 2'],
subpanel: {
position: 'left',
width: 200,
panel: {
rows: ['main bottom left 1', 'main bottom left 2']
}
}
}
}
};
}
};
});
module.directive('gyPanel', function (RecursionHelper) {
return {
restrict: 'E',
replace: true,
templateUrl: 'templates/panel.html',
scope: { panel: '=' },
controller: function ($scope) {
$scope.mainPanelClass = function () {
var subpanel = $scope.panel.subpanel;
if (subpanel) {
switch (subpanel.position) {
case 'left': return 'gy-right';
case 'right': return 'gy-left';
case 'top': return 'gy-bottom';
case 'bottom': return 'gy-top';
}
}
return 'fill';
};
$scope.mainPanelStyle = function () {
var subpanel = $scope.panel.subpanel;
if (subpanel) {
switch (subpanel.position) {
case 'left': return { 'left': (subpanel.width + 1) + 'px' };
case 'right': return { 'right': (subpanel.width + 1) + 'px' };
case 'top': return { 'top': (subpanel.height + 1) + 'px' };
case 'bottom': return { 'bottom': (subpanel.height + 1) + 'px' };
}
}
return {};
};
$scope.subpanelClass = function () {
var subpanel = $scope.panel.subpanel;
if (subpanel) {
switch (subpanel.position) {
case 'left': return 'gy-left gy-border-right';
case 'right': return 'gy-right gy-border-left';
case 'top': return 'gy-top gy-border-bottom';
case 'bottom': return 'gy-bottom gy-border-top';
}
}
return '';
};
$scope.subpanelStyle = function () {
var subpanel = $scope.panel.subpanel;
if (subpanel) {
switch (subpanel.position) {
case 'left':
case 'right':
return { 'width': subpanel.width + 'px' };
case 'top':
case 'bottom':
return { 'height': subpanel.height + 'px' };
}
}
return {};
};
},
compile: function (element) {
return RecursionHelper.compile(element);
}
};
});
})();
|
$().ready(function(){
function baseState(){
wiz = new Wizard();
wiz.addAllYN();
//add a help pane and place it there
wiz.notePane.append($(".x-wrapper").outerHTML());
wiz.setXClose();
wiz.notePane.append(" Click ‘Design an amiRNA’ if you want to identify optimal amiRNA guide sequences that target your gene(s) of interest. Click ‘Generate oligos’ if you already have an amiRNA guide sequence and you just want to generate oligos compatible with cloning in a BsaI-ccdB vector containing the Arabidopsis MIR390a foldback.");
//if it has children you probably want to append.
wiz.textPane.append("Do you need to design an amiRNA or do you already have a guide sequence and need to generate oligos for cloning?");
wiz.setYesText("Design an amiRNA");
wiz.setNoText("Generate Oligos");
wiz.setYes(cb_designAmiRNA1);
wiz.setNo(cb_generateOligos1);
}
function cb_designAmiRNA1(){
wiz = new Wizard(wiz);
wiz.addAllYN();
wiz.textPane.append("Will you use your amiRNA in one of the following species?");
wiz.textPane.append($("#species").html());
wiz.notePane.append($(".x-wrapper").outerHTML());
wiz.notePane.append("Select a species and click ‘Yes’ if you are going to express your amiRNA in any of the species listed. Click ‘No’ if you are going to express your amiRNA in another species. If you want us to add a new species contact us at [email protected]");
wiz.setXClose();
wiz.setYes(cb_designAmiRNA2); //make sure it saves the species
wiz.setNo(cb_generateOligos2);
$(wiz.yesButton).text("Yes");
$(wiz.noButton).text("No");
wiz.setBack(function(){
cb_revertState(wiz);
});
}
function cb_designAmiRNA2(){
wiz.species = $("#database option:selected").text();
wiz.speciesId = $("#database option:selected").val();
wiz = new Wizard(wiz);
wiz.restoreFormFields(); //gets species/speciesid
wiz.addAllYN();
//wiz.helpPane.text("Click ‘Annotated transcript(s)’ if you have gene ID(s). Click ‘Unannotated/exogenous transcript(s)’ if you want to target transcripts that do not have an assigned gene ID or are not found in the selected reference transcriptome.");
wiz.notePane.append($(".x-wrapper").outerHTML());
wiz.notePane.append("Click ‘Annotated transcript(s)’ if you have gene ID(s). Click ‘Unannotated/exogenous transcript(s)’ if you want to target transcripts that do not have an assigned gene ID or are not found in the selected reference transcriptome.");
wiz.setXClose();
wiz.textPane.append("Do you want to target annotated transcript(s) (Option 1) or unannotated/exogenous transcript(s)? (Option 2)");
wiz.setYesText("Option 1");
wiz.setNoText("Option 2");
//work in progress
//wiz.noButton.css("font-size", "16px").css("height", height);
wiz.setYes(cb_designAmiRNA3_annotated);
wiz.setNo(cb_designAmiRNA3_unannotated);
wiz.setBack(function(){ cb_revertState(wiz); });
}
function cb_designAmiRNA3_annotated(){
wiz = new Wizard(wiz);
wiz.restoreFormFields();
wiz.addAllNB();
$("#sequence").val(""); //clear form?
$("#gene").val("");
wiz.textPane.append("Enter a target gene ID. Click the '+' button for entering additional target gene IDs to target multiple genes.");
wiz.textPane.append( $("#transcript-lookup").outerHTML() );
wiz.textPane.find( $("#transcript-lookup").addClass("transcript-lookup") );
wiz.addPlusButton( ".transcript-lookup" );
wiz.setNext(cb_designAmiRNA4_a);
wiz.setBack(function(){ cb_revertState(wiz); });
}
function cb_designAmiRNA3_unannotated(){
wiz = new Wizard(wiz);
wiz.restoreFormFields();
wiz.addAllNB();
$("#sequence").val("");
$("#gene").val("");
wiz.textPane.append("Enter or paste FASTA sequence(s) of target transcript(s)");
wiz.textPane.append( $("#wizard-transcript").outerHTML() );
wiz.textPane.find( $("#wizard-transcript").addClass("wizard-transcript") );
wiz.textPane.after($(".result").outerHTML());
$("#wizard-pane").find(".result").removeClass("result").addClass("my-result");
wiz.setNext(function(){
var fasta = wiz.textPane.find("#sequence").val().split("\n");
wiz.wizardPane.find(".my-result").removeClass("alert alert-danger").addClass("hidden").text("");
if (fasta.length < 2 || fasta.length % 2 != 0){
wiz.wizardPane.find(".my-result").removeClass("hidden").addClass("alert alert-danger").text("Please insert a fasta sequence");
return;
}
for (var i = 0; i < fasta.length; i++){
if ( i % 2 === 0){
if (fasta[i].substr(0,1) != ">"){
wiz.wizardPane.find(".my-result").removeClass("hidden").addClass("alert alert-danger").text("Please insert a valid fasta sequence");
return;
}
} else{
//reserved for potential alphabet test
}
}
cb_designAmiRNA4_u();
});
wiz.setBack(function() { cb_revertState(wiz); });
}
//annotated
function cb_designAmiRNA4_a(){
var transid = "";
wiz.textPane.find(".gene").each(function(){
transid += $(this).val() + ",";
});
transid = transid.substring(0, transid.length-1);
if (transid != "") {
wiz.transcriptId = transid;
}
wiz = new Wizard(wiz);
wiz.restoreFormFields();
wiz.addAllYN();
wiz.notePane.append($(".x-wrapper").outerHTML());
wiz.notePane.append("Clicking ‘Yes’ will activate a target prediction module. Results that have predicted undesired targets will be discarded. Click ‘No’ to deactivate the target prediction module.");
wiz.setXClose();
wiz.textPane.append("Do you want the results to be automatically filtered based on target specificity?");
wiz.setYes(function(){
wiz.filtered = true;
cb_designAmiRNAFinal();
});
wiz.setNo(function(){
wiz.filtered = false;
cb_designAmiRNAFinal();
});
wiz.setBack(function(){
//rebind the plus button as well
cb_revertState(wiz);
wiz.filtered = undefined;
wiz.textPane = $("#wizard-text"); //kind of a hack
wiz.addPlusButton( ".transcript-lookup" );
wiz.transcriptId = "";
});
}
//unannotated
function cb_designAmiRNA4_u(){
var trans = "";
wiz.textPane.find(".sequence").each(function(){
trans += $(this).val() + ",";
});
trans = trans.substring(0, trans.length-1);
if ( trans != "") {
wiz.transcript = trans;
}
wiz = new Wizard(wiz);
wiz.restoreFormFields();
wiz.addAllYN();
wiz.notePane.append($(".x-wrapper").outerHTML());
wiz.notePane.append("");
wiz.setXClose();
wiz.textPane.append("Do you want the results to be automatically filtered based on target specificity?");
wiz.setYes(function(){
wiz.filtered = true;
cb_designAmiRNAFinal();
});
wiz.setNo(function(){
wiz.filtered = false;
cb_designAmiRNAFinal();
});
wiz.setBack(function(){
cb_revertState(wiz);
wiz.textPane = $("#wizard-text"); //still a hack
wiz.addPlusButton( ".wizard-transcript" );
wiz.transcript = "";
wiz.filtered = undefined;
});
}
function cb_designAmiRNAFinal(){
wiz = new Wizard(wiz);
wiz.restoreFormFields();
wiz.addAllNB();
wiz.textPane.append("<h5>Species: " +wiz.species+ "</h5>");
//foreach
if(wiz.transcriptId !== ""){
var csv = wiz.transcriptId.split(",");
for(var i = 0; i < csv.length; i++){
wiz.textPane.append("<h5>Transcript ID: " +csv[i]+ "</h5>");
}
} else{
wiz.textPane.append("<h5>Transcript: " + wiz.transcript);
}
wiz.textPane.after($(".result").outerHTML());
$("#wizard-pane").find(".result").removeClass("result").addClass("my-result");
wiz.setNextText("Submit");
wiz.setNext(cb_submit);
wiz.setBack( function(){ cb_revertState(wiz) } );
}
function cb_submit(){
$('.my-result').removeClass('hidden alert alert-danger alert-success');
$('.my-result').addClass('alert alert-warning');
$('.my-result').html('<img src="'+ $("#gifloader").val() + '"/>' );
$.post( $("#rnamaker_amirnarequest").val(), { transcript: wiz.transcript, transcriptId: wiz.transcriptId, species: wiz.speciesId, filtered: wiz.filtered } )
.success(function(data){
$('.my-result').removeClass('hidden alert alert-danger alert-warning');
$('.my-result').addClass("alert alert-success");
$('.my-result').text("Success!");
$("#next").animate({
backgroundColor: "#7CB02C",
color: "#fff"
}, 1000 );
$("#next").attr("href", $("#tokensplain").val() + "/" + data );
wiz.setNextText("Click to see Results");
$("#next").unbind("click");
wiz.setNext(function(){
window.location = $("#tokensplain").val() + "/" + data;
});
console.log(data);
})
.error(function( xhr, statusText, err){
$('.my-result').removeClass('hidden alert alert-success alert-warning');
$('.my-result').addClass("alert alert-danger");
if (xhr.responseText != ""){
$('.my-result').html(xhr.responseText);
}
})
}
function cb_generateOligos1(){
wiz = new Wizard(wiz);
wiz.addAllNB();
wiz.textPane.append("Enter or paste an amiRNA sequence. Click the '+' button for entering additional amiRNA sequences.");
wiz.textPane.append($("#oligo-form").outerHTML());
wiz.textPane.find("#oligo-form").addClass("oligo-form");
wiz.addPlusButton(".oligo-form");
wiz.wizardPane.find(".add").click(function(){
$(".name").click(toInputTransform);
$('.oligo-form').last().find(".oligo-seq").removeClass("alert alert-warning alert-danger input-warning input-danger");
});
wiz.textPane.after($(".result").outerHTML());
$("#wizard-pane").find(".result").removeClass("result").addClass("my-result");
$(".name").click(toInputTransform);
$('.modal').click(function(){
if (!$(event.target).hasClass('name')) {
$(".modified").each(function(){
var val = $(this).val()
$(this).replaceWith("<label class='name' style='border-bottom: 1px dashed #000;text-decoration: none;'>" + val + "</label>");
$(".name").click(toInputTransform);
});
}
});
function toInputTransform(){
var cur = $(this).text();
if (cur == ""){
var cur = $(this).val();
}
$(this).replaceWith("<input type='text' class='form-control name modified' value='" + cur + "' placeholder='" + cur +"'/>") ;
}
wiz.setNextText("Submit");
wiz.setNext( function() {
var errors = oligoValidityCheck(".oligo-seq");
if (!errors){
cb_oligoSubmit();
}
else {
console.log(errors);
}
});
wiz.setBack( function() { $(".modal").unbind("click"); cb_revertState(wiz) });
}
function cb_oligoSubmit(){
var seq = "";
var name = "";
var fasta = "";
if (wiz.textPane.find(".oligo-seq").length > 0){
wiz.textPane.find(".name").each(function(){
name+= $(this).text() + ",";
});
wiz.textPane.find(".oligo-seq").each(function(){
seq += $(this).val() + ",";
});
name = name.substr(0, name.length - 1);
seq = seq.substr(0, seq.length - 1);
}
else{
fasta = wiz.textPane.find(".oligo-fasta").val();
}
$('.my-result').removeClass('hidden alert alert-danger alert-success');
$('.my-result').addClass('alert alert-warning');
$('.my-result').html('<img src="'+ $("#gifloader").val() + '"/>' );
$.post( $("#oligodesigner").val(), { seq: seq, name: name, fasta: fasta } )
.success(function(data){
$('.my-result').removeClass('hidden alert alert-danger alert-warning');
$('.my-result').addClass("alert alert-success");
$('.my-result').text("Success!");
$("#next").animate({
color: "#fff"
}, 1000 );
console.log(data);
$("#next").attr("href", $("#oligotokensplain").val() + "/" + data );
wiz.setNextText("Click to see Results");
$("#next").unbind("click");
wiz.setNext(function(){
window.location = $("#oligotokensplain").val() + "/" + data;
});
})
.error(function( xhr, statusText, err){
$('.my-result').removeClass('hidden alert alert-success alert-warning');
$('.my-result').addClass("alert alert-danger");
if (xhr.responseText != ""){
$('.my-result').html(xhr.responseText);
}
})
}
//Same as generateOligos1 except it uses fasta instead of line-by-line name/sequence pairs.
function cb_generateOligos2(){
wiz = new Wizard(wiz);
wiz.addAllNB();
wiz.textPane.append("Enter or paste FASTA sequence(s) of target transcript(s)")
wiz.textPane.append($("#oligo-fasta-form").outerHTML());
wiz.textPane.find("#oligo-fasta-form").prepend("<label for='oligo-fasta-form'>amiRNA fasta</label>");
wiz.textPane.find("#oligo-fasta-form").addClass("oligo-fasta-form");
wiz.wizardPane.find(".add").click(function(){
$('.oligo-fasta-form').last().find(".oligo-fasta").removeClass("alert alert-warning alert-danger input-warning input-danger");
});
wiz.textPane.after($(".result").outerHTML());
$("#wizard-pane").find(".result").removeClass("result").addClass("my-result");
wiz.setNextText("Submit");
wiz.setNext( function() {
var errors = oligoFastaValidityCheck(".oligo-fasta");
//check result and continue if not false.
if (!errors) {
cb_oligoSubmit();
} else{
console.log(errors);
}
});
wiz.setBack( function() { cb_revertState(wiz) });
}
//checks the validity of each input oligo
function oligoValidityCheck(classname){
try{
prevErrors = errors;
prevWarnings = warnings;
}catch(err){
prevErrors = "";
prevWarnings = "";
}
errors = "";
warnings = "";
errorsExist = true;
wiz.textPane.find(classname).each(function(){
var seq = $(this).val();
result = wiz.wizardPane.find(".my-result");
var color = "none";
$(this).removeClass("alert alert-warning alert-danger input-warning input-danger");
var current = result.text();
if(seq.length != 21){
errors += "Error: Your input sequence is not 21 NT in length<br/>";
color = "red";
}
if(seq.match("^[ATCGUatcgu]+$") != seq){
errors += "Error: Your sequence contains characters that are not A,T,C,G, or U<br/>";
color = "red";
}
if (seq.substr(0,1).toUpperCase() !== "T" && seq.substr(0,1).toUpperCase() !== "U"){
warnings += "Warning: We recommend a T or U on the 5' end. <br/>";
color == "none" ? color = "yellow" : "";
}
if (seq.substr(18,1).toUpperCase() !== "C"){
warnings += "Warning: We recommend a C at amiRNA position 19, in order to have a 5' G on the miR*<br/>";
color == "none" ? color = "yellow" : "";
}
if (color == "red"){
$(this).addClass("alert alert-danger input-danger");
} else if (color == "yellow"){
$(this).addClass("alert alert-warning input-warning");
}
if (errors != ""){
result.removeClass("hidden alert-warning");
result.addClass("alert alert-danger");
result.html(errors + warnings);
errorsExist = true;
} else if (warnings != ""){
result.removeClass("hidden alert-danger");
errorsExist = true;
result.addClass("alert alert-warning");
if ( prevWarnings == warnings && prevErrors == ""){
errorsExist = false;
}
result.html(warnings);
} else{
result.removeClass("alert alert-danger alert-warning").addClass("hidden");
errorsExist = false;
}
});
return errorsExist;
}
//checks the validity of each entry in the fasta format, also checks fasta format.
function oligoFastaValidityCheck(classname){
try{
prevErrors = errors;
prevWarnings = warnings;
}catch(err){
prevErrors = "";
prevWarnings = "";
}
errors = "";
warnings = "";
errorsExist = true;
//keep same sequence rules
//find text box, iterate over each group of 2, first is name second is sequence.
var fasta = wiz.textPane.find(classname).val();
var fastaSplits = fasta.split("\n");
if (fastaSplits.length % 2 != 0 || fastaSplits.length < 2 ){
errors += "<strong>Error: Your input is not fasta format.</strong><br/><br/>";
}
for (var i = 0; i < fastaSplits.length; i+=2){
var seq = fastaSplits[i+1];
var name = fastaSplits[i];
wiz.textPane.find(classname).removeClass("alert alert-warning alert-danger input-warning input-danger");
result = wiz.wizardPane.find(".my-result");
var color = "none";
wiz.textPane.find(classname).removeClass("alert alert-warning alert-danger input-warning input-danger");
if(name.substr(0,1) != ">"){
errors += "Error: One of your fasta headers does not begin with '>': " + name + "<br/>";
color = "red";
}
if(seq.length != 21){
errors += "Error: Your input sequence is not 21 NT in length: " + name + "<br/>";
color = "red";
}
if(seq.match("^[ATCGUatcgu]+$") != seq){
errors += "Error: Your sequence contains characters that are not A,T,C,G, or U: " + name + "<br/>";
color = "red";
}
if (seq.substr(0,1).toUpperCase() !== "T" && seq.substr(0,1).toUpperCase() !== "U"){
warnings += "Warning: We recommend a T or U on the 5' end: "+ name + "<br/>";
color == "none" ? color = "yellow" : "";
}
if (seq.substr(18,1).toUpperCase() !== "C"){
warnings += "Warning: We recommend a C at amiRNA position 19, in order to have a 5' G on the miR*: "+ name + "<br/>";
color == "none" ? color = "yellow" : "";
}
if (color == "red"){
wiz.textPane.find(classname).addClass("alert alert-danger input-danger");
} else if (color == "yellow"){
wiz.textPane.find(classname).addClass("alert alert-warning input-warning");
}
if (errors != ""){
result.removeClass("hidden alert-warning");
result.addClass("alert alert-danger");
result.html(errors + warnings);
errorsExist = true;
} else if (warnings != ""){
result.removeClass("hidden alert-danger");
result.addClass("alert alert-warning");
errorsExist = true;
if ( prevWarnings == warnings && prevErrors == ""){
errorsExist = false;
}
result.html(warnings);
} else{
result.removeClass("alert alert-danger alert-warning").addClass("hidden");
errorsExist = false;
}
}
return errorsExist;
}
//initialize
baseState();
$("#close-clear").click(function(){
baseState();
});
$(".help").click(function(){
if($("#wizard-note").text() != ""){
$("#wizard-note").fadeIn(1000);
}
});
});
|
import {metadata} from 'aurelia-metadata';
import {Container} from 'aurelia-dependency-injection';
import {TemplateRegistryEntry} from 'aurelia-loader';
import {ValueConverterResource} from 'aurelia-binding';
import {BindingBehaviorResource} from 'aurelia-binding';
import {HtmlBehaviorResource} from './html-behavior';
import {viewStrategy, TemplateRegistryViewStrategy} from './view-strategy';
import {ViewResources} from './view-resources';
import {ResourceLoadContext} from './instructions';
import {_hyphenate} from './util';
/**
* Represents a module with view resources.
*/
export class ResourceModule {
/**
* Creates an instance of ResourceModule.
* @param moduleId The id of the module that contains view resources.
*/
constructor(moduleId: string) {
this.id = moduleId;
this.moduleInstance = null;
this.mainResource = null;
this.resources = null;
this.viewStrategy = null;
this.isInitialized = false;
this.onLoaded = null;
}
/**
* Initializes the resources within the module.
* @param container The dependency injection container usable during resource initialization.
*/
initialize(container: Container): void {
let current = this.mainResource;
let resources = this.resources;
let vs = this.viewStrategy;
if (this.isInitialized) {
return;
}
this.isInitialized = true;
if (current !== undefined) {
current.metadata.viewStrategy = vs;
current.initialize(container);
}
for (let i = 0, ii = resources.length; i < ii; ++i) {
current = resources[i];
current.metadata.viewStrategy = vs;
current.initialize(container);
}
}
/**
* Registrers the resources in the module with the view resources.
* @param registry The registry of view resources to regiser within.
* @param name The name to use in registering the default resource.
*/
register(registry:ViewResources, name?:string): void {
let main = this.mainResource;
let resources = this.resources;
if (main !== undefined) {
main.register(registry, name);
name = null;
}
for (let i = 0, ii = resources.length; i < ii; ++i) {
resources[i].register(registry, name);
name = null;
}
}
/**
* Loads any dependencies of the resources within this module.
* @param container The DI container to use during dependency resolution.
* @param loadContext The loading context used for loading all resources and dependencies.
* @return A promise that resolves when all loading is complete.
*/
load(container: Container, loadContext?: ResourceLoadContext): Promise<void> {
if (this.onLoaded !== null) {
return this.onLoaded;
}
let main = this.mainResource;
let resources = this.resources;
let loads;
if (main !== undefined) {
loads = new Array(resources.length + 1);
loads[0] = main.load(container, loadContext);
for (let i = 0, ii = resources.length; i < ii; ++i) {
loads[i + 1] = resources[i].load(container, loadContext);
}
} else {
loads = new Array(resources.length);
for (let i = 0, ii = resources.length; i < ii; ++i) {
loads[i] = resources[i].load(container, loadContext);
}
}
this.onLoaded = Promise.all(loads);
return this.onLoaded;
}
}
/**
* Represents a single view resource with a ResourceModule.
*/
export class ResourceDescription {
/**
* Creates an instance of ResourceDescription.
* @param key The key that the resource was exported as.
* @param exportedValue The exported resource.
* @param resourceTypeMeta The metadata located on the resource.
*/
constructor(key: string, exportedValue: any, resourceTypeMeta?: Object) {
if (!resourceTypeMeta) {
resourceTypeMeta = metadata.get(metadata.resource, exportedValue);
if (!resourceTypeMeta) {
resourceTypeMeta = new HtmlBehaviorResource();
resourceTypeMeta.elementName = _hyphenate(key);
metadata.define(metadata.resource, resourceTypeMeta, exportedValue);
}
}
if (resourceTypeMeta instanceof HtmlBehaviorResource) {
if (resourceTypeMeta.elementName === undefined) {
//customeElement()
resourceTypeMeta.elementName = _hyphenate(key);
} else if (resourceTypeMeta.attributeName === undefined) {
//customAttribute()
resourceTypeMeta.attributeName = _hyphenate(key);
} else if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) {
//no customeElement or customAttribute but behavior added by other metadata
HtmlBehaviorResource.convention(key, resourceTypeMeta);
}
} else if (!resourceTypeMeta.name) {
resourceTypeMeta.name = _hyphenate(key);
}
this.metadata = resourceTypeMeta;
this.value = exportedValue;
}
/**
* Initializes the resource.
* @param container The dependency injection container usable during resource initialization.
*/
initialize(container: Container): void {
this.metadata.initialize(container, this.value);
}
/**
* Registrers the resource with the view resources.
* @param registry The registry of view resources to regiser within.
* @param name The name to use in registering the resource.
*/
register(registry: ViewResources, name?: string): void {
this.metadata.register(registry, name);
}
/**
* Loads any dependencies of the resource.
* @param container The DI container to use during dependency resolution.
* @param loadContext The loading context used for loading all resources and dependencies.
* @return A promise that resolves when all loading is complete.
*/
load(container: Container, loadContext?: ResourceLoadContext): Promise<void> | void {
return this.metadata.load(container, this.value, loadContext);
}
}
/**
* Analyzes a module in order to discover the view resources that it exports.
*/
export class ModuleAnalyzer {
/**
* Creates an instance of ModuleAnalyzer.
*/
constructor() {
this.cache = {};
}
/**
* Retrieves the ResourceModule analysis for a previously analyzed module.
* @param moduleId The id of the module to lookup.
* @return The ResouceModule if found, undefined otherwise.
*/
getAnalysis(moduleId: string): ResourceModule {
return this.cache[moduleId];
}
/**
* Analyzes a module.
* @param moduleId The id of the module to analyze.
* @param moduleInstance The module instance to analyze.
* @param mainResourceKey The name of the main resource.
* @return The ResouceModule representing the analysis.
*/
analyze(moduleId: string, moduleInstance: any, mainResourceKey?: string): ResourceModule {
let mainResource;
let fallbackValue;
let fallbackKey;
let resourceTypeMeta;
let key;
let exportedValue;
let resources = [];
let conventional;
let vs;
let resourceModule;
resourceModule = this.cache[moduleId];
if (resourceModule) {
return resourceModule;
}
resourceModule = new ResourceModule(moduleId);
this.cache[moduleId] = resourceModule;
if (typeof moduleInstance === 'function') {
moduleInstance = {'default': moduleInstance};
}
if (mainResourceKey) {
mainResource = new ResourceDescription(mainResourceKey, moduleInstance[mainResourceKey]);
}
for (key in moduleInstance) {
exportedValue = moduleInstance[key];
if (key === mainResourceKey || typeof exportedValue !== 'function') {
continue;
}
resourceTypeMeta = metadata.get(metadata.resource, exportedValue);
if (resourceTypeMeta) {
if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) {
//no customeElement or customAttribute but behavior added by other metadata
HtmlBehaviorResource.convention(key, resourceTypeMeta);
}
if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) {
//no convention and no customeElement or customAttribute but behavior added by other metadata
resourceTypeMeta.elementName = _hyphenate(key);
}
if (!mainResource && resourceTypeMeta instanceof HtmlBehaviorResource && resourceTypeMeta.elementName !== null) {
mainResource = new ResourceDescription(key, exportedValue, resourceTypeMeta);
} else {
resources.push(new ResourceDescription(key, exportedValue, resourceTypeMeta));
}
} else if (viewStrategy.decorates(exportedValue)) {
vs = exportedValue;
} else if (exportedValue instanceof TemplateRegistryEntry) {
vs = new TemplateRegistryViewStrategy(moduleId, exportedValue);
} else {
if (conventional = HtmlBehaviorResource.convention(key)) {
if (conventional.elementName !== null && !mainResource) {
mainResource = new ResourceDescription(key, exportedValue, conventional);
} else {
resources.push(new ResourceDescription(key, exportedValue, conventional));
}
metadata.define(metadata.resource, conventional, exportedValue);
} else if (conventional = ValueConverterResource.convention(key)) {
resources.push(new ResourceDescription(key, exportedValue, conventional));
metadata.define(metadata.resource, conventional, exportedValue);
} else if (conventional = BindingBehaviorResource.convention(key)) {
resources.push(new ResourceDescription(key, exportedValue, conventional));
metadata.define(metadata.resource, conventional, exportedValue);
} else if (!fallbackValue) {
fallbackValue = exportedValue;
fallbackKey = key;
}
}
}
if (!mainResource && fallbackValue) {
mainResource = new ResourceDescription(fallbackKey, fallbackValue);
}
resourceModule.moduleInstance = moduleInstance;
resourceModule.mainResource = mainResource;
resourceModule.resources = resources;
resourceModule.viewStrategy = vs;
return resourceModule;
}
}
|
/**
* #config
*
* Copyright (c)2011, by Branko Vukelic
*
* Configuration methods and settings for Daimyo. All startup configuration
* settings are set using the `config.configure()` and `config.option()`
* methods. Most options can only be set once, and subsequent attempts to set
* them will result in an error. To avoid this, pass the
* `allowMultipleSetOption` option to `config.configure()` and set it to
* `true`. (The option has a long name to prevent accidental usage.)
*
* @author Branko Vukelic <[email protected]>
* @license MIT (see LICENSE)
*/
var config = exports;
var util = require('util');
var DaimyoError = require('./error');
var samurayKeyRe = /^[0-9a-f]{24}$/;
var isConfigured = false;
config.DAIMYO_VERSION = '0.1.5';
/**
* ## settings
* *Master configuration settings for Daimyo*
*
* The `settings` object contains all the core configuration options that
* affect the way certain things work (or not), and the Samurai gateway
* credentials. You should _not_ access this object directly. The correct way
* to access and set the settings is through either ``configure()`` or
* ``option()`` methods.
*
* Settings are expected to contain following keys with their default values:
*
* + _merchantKey_: Samurai gateway Merchant Key (default: `''`)
* + _apiPassword_: Samurai gateway API Password (default: `''`)
* + _processorId_: Processor (gateway) ID; be sure to set this to a sandbox
* ID for testing (default: `''`)
* + _currency_: Default currency for all transactions (can be overriden by
* specifying the appropriate options in transaction objects)
* + _allowedCurrencies_: Array containing the currencies that can be used
* in transactions. (default: ['USD'])
* + _sandbox_: All new payment methods will be sandbox payment methods
* (default: false)
* + _enabled_: Whether to actually make requests to gateway (default: true)
* + _debug_: Whether to log to STDOUT; it is highly recommended that
* you disable this in production, to remain PCI comliant, and to
* avoid performance issues (default: true)
*
* Only `currency` option can be set multiple times. All other options can only
* be set once using the ``config.configure()`` method.
*
* The ``apiVersion`` setting is present for conveinence and is should be
* treated as a constant (i.e., read-only).
*/
var settings = {};
settings.merchantKey = '';
settings.apiPassword = '';
settings.processorId = '';
settings.currency = 'USD';
settings.allowedCurrencies = ['USD'];
settings.sandbox = false;
settings.enabled = true; // Does not make any actual API calls if false
settings.debug = false; // Enables *blocking* debug output to STDOUT
settings.apiVersion = 1; // Don't change this... unless you need to
settings.allowMultipleSetOption = false;
/**
* ## config.debug(message)
* *Wrapper around `util.debug` to log items in debug mode*
*
* This method is typically used by Daimyo implementation to output debug
* messages. There is no need to call this method outside of Daimyo.
*
* Note that any debug messages output using this function will block
* execution temporarily. It is advised to disable debug setting in production
* to prevent this logger from running.
*
* @param {Object} message Object to be output as a message
* @private
*/
config.debug = debug = function(message) {
if (settings.debug) {
util.debug(message);
}
};
/**
* ## config.configure(opts)
* *Set global Daimyo configuration options*
*
* This method should be used before using any of the Daimyo's functions. It
* sets the options in the `settings` object, and performs basic validation
* of the options before doing so.
*
* Unless you also pass it the `allowMultipleSetOption` option with value set
* to `true`, you will only be able to call this method once. This is done to
* prevent accidental calls to this method to modify critical options that may
* affect the security and/or correct operation of your system.
*
* This method depends on ``config.option()`` method to set the individual
* options.
*
* If an invalid option is passed, it will throw an error.
*
* @param {Object} Configuration options
*/
config.configure = function(opts) {
debug('Configuring Daimyo with: \n' + util.inspect(opts));
if (!opts.merchantKey || !opts.apiPassword || !opts.processorId) {
throw new DaimyoError('system', 'Incomplete Samurai API credentials', opts);
}
Object.keys(opts).forEach(function(key) {
config.option(key, opts[key]);
});
isConfigured = true;
};
/**
* ## config.option(name, [value])
* *Returns or sets a single configuration option*
*
* If value is not provided this method returns the value of the named
* configuration option key. Otherwise, it sets the value and returns it.
*
* Setting values can only be set once for most options. An error will be
* thrown if you try to set an option more than once. This restriction exist
* to prevent accidental and/or malicious manipulation of critical Daimyo
* configuration options.
*
* During testing, you may set the `allowMultipleSetOption` to `true` in order
* to enable multiple setting of protected options. Note that once this option
* is set to `false` it can no longer be set to true.
*
* Samurai API credentials are additionally checked for consistency. If they
* do not appear to be valid keys, an error will be thrown.
*
* @param {String} option Name of the option key
* @param {Object} value New value of the option
* @returns {Object} Value of the `option` key
*/
config.option = function(option, value) {
if (typeof value !== 'undefined') {
debug('Setting Daimyo key `' + option + '` to `' + value.toString() + '`');
// Do not allow an option to be set twice unless it's `currency`
if (isConfigured &&
!settings.allowMultipleSetOption &&
option !== 'currency') {
throw new DaimyoError(
'system',
'Option ' + option + ' is already locked',
option);
}
switch (option) {
case 'merchantKey':
case 'apiPassword':
case 'processorId':
// Throw if doesn't look like valid key
if (!samurayKeyRe.exec(value)) {
throw new DaimyoError('system', 'Invalid setting', option);
}
settings[option] = value;
break;
case 'currency':
settings[option] = value;
break;
case 'sandbox':
case 'enabled':
case 'debug':
case 'allowMultipleSetOption':
settings[option] = Boolean(value);
break;
case 'allowedCurrencies':
if (!Array.isArray(value)) {
throw new DaimyoError('system', 'Allowed currencies must be an array', null);
}
if (value.indexOf(settings.currency) < 0) {
value.push(settings.currency);
}
settings.allowedCurrencies = value;
break;
default:
// Do not allow unknown options to be set
throw new DaimyoError('system', 'Unrecognized configuration option', option);
}
}
return settings[option];
};
|
/*
** Bind Keys and events to the spaceShip's controllers
** e.g. if someone presses space, create a bullet object
*/
function setupControls() {
$(document).keydown(function (e) {
if (isMovement(e.which)) {
spaceship.move(e.which);
}
if (isShoot(e.which)) {
spaceship.shoot();
}
});
$(document).keyup(function (e) {
if (isMovement(e.which)) {
spaceship.stopMove();
}
});
function isMovement(code) {
return code >= 37 && code <= 40;
}
function isShoot(code) {
return code === 32;
}
}
//Call update functions of all game objects
function updatePositions() {
gameObjects.forEach(function (o) { o.update(); });
}
//Call draw functions of all game objects
function drawObjects() {
gameObjects.forEach(function (o) { o.draw(); });
}
|
import React from 'react';
export default function D3Axis({
tickData, className, onSelectedAxisItem
}){
return React.createElement('g', {className: ['d3-axis', className].filter(x => x).join(' ')},
tickData.map(({id, transform, line: {x1, y1, x2, y2}, text: {x, y, dx, dy, anchor='middle', t}, className: tickClass }, i) => {
return React.createElement('g', {
key: i,
className: ['tick', tickClass, onSelectedAxisItem ? 'actionable' : undefined].filter(x=>x).join(' '),
transform,
onClick(){
onSelectedAxisItem(id)
}},
React.createElement('line', {x1, y1, x2, y2}),
React.createElement('text', {x, y, dx, dy, textAnchor: anchor}, t)
)
})
)
}
|
import React from 'react';
import Friend from './friend';
import * as I from 'immutable';
function FriendsList({ friendships, isVisible = true, onProfileClick }) {
if (!isVisible) {
return null;
}
return (
<div className="flex flex-wrap">
{
friendships.map((friendship, i) => {
return <Friend key={i} userInfo={friendship.get('friend')} onProfileClick={onProfileClick}/>;
})
}
</div>
);
}
FriendsList.propTypes = {
friendships: React.PropTypes.instanceOf(I.List),
isVisible: React.PropTypes.bool,
onProfileClick: React.PropTypes.func,
};
export default FriendsList;
|
/**
* Gorgon the scripting capable network server for Node JS
*
* @package Gorgon
* @author Ryan Rentfro
* @license MIT
* @url https://github.com/manufacturing-industry
*/
/**
* Build Script: BuildUpdate
*
* @note Updates the system build settings
* @param grunt
*/
module.exports = function(grunt) {
grunt.file.setBase('../../');
var pkg = grunt.file.readJSON('package.json');
/*
* THE BUILD CONFIGURATION
*/
grunt.initConfig({
gitinfo: {
commands: {
'commitTotal': ['rev-list', '--count', 'master']
}
},
json_generator: {
your_target: {
dest: pkg.buildConfig.buildDataFile,
options: {
name: pkg.productName,
minorVersion: parseFloat(pkg.minorVersion) + parseFloat(1),
buildName: pkg.buildConfig.buildName,
buildNumber: "<%= gitinfo.commitTotal %>",
buildType: pkg.buildConfig.buildType,
publicVersion: pkg.publicVersion
}
}
},
update_json: {
options: {
src: pkg.buildConfig.buildDataFile,
indent: '\t'
},
package: {
dest: 'package.json',
fields: {
'minorVersion': null,
'buildNumber': null
}
}
}
});
/*
* LOAD THE PLUGINS FOR TASKS
*/
grunt.loadNpmTasks('grunt-update-json');
grunt.loadNpmTasks('grunt-json-generator');
grunt.loadNpmTasks('grunt-gitinfo');
/*
* THE DEFAULT GRUNT TASK
*/
grunt.registerTask('default', function(target)
{
//Run the tasks
grunt.task.run('gitinfo', 'json_generator', 'update_json');
});
}; |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M20.12 12.04c.5-.05.88-.48.88-.99 0-.59-.51-1.06-1.1-1-1.5.15-2.9.61-4.16 1.3l1.48 1.48c.9-.41 1.87-.69 2.9-.79zm.88 3.05c0-.61-.54-1.09-1.14-1-.38.06-.75.16-1.11.28l1.62 1.62c.37-.15.63-.49.63-.9zM13.97 4.14c.06-.59-.4-1.11-1-1.11-.5 0-.94.37-.99.87-.1 1.03-.38 2.01-.79 2.91l1.48 1.48c.69-1.26 1.15-2.66 1.3-4.15zm-4.04.02c.1-.6-.39-1.14-1-1.14-.41 0-.75.26-.9.62l1.62 1.62c.13-.35.22-.72.28-1.1zm10.51 14.72L5.12 3.56a.9959.9959 0 00-1.41 0c-.39.39-.39 1.02 0 1.41l2.15 2.15c-.59.41-1.26.7-1.99.82-.48.1-.84.5-.84 1 0 .61.54 1.09 1.14 1 1.17-.19 2.23-.68 3.13-1.37L8.73 10c-1.34 1.1-3 1.82-4.81 1.99-.5.05-.88.48-.88.99 0 .59.51 1.06 1.1 1 2.28-.23 4.36-1.15 6.01-2.56l2.48 2.48c-1.4 1.65-2.33 3.72-2.56 6-.06.59.4 1.11 1 1.11.5 0 .94-.37.99-.87.18-1.82.9-3.48 1.99-4.82l1.43 1.43c-.69.9-1.18 1.96-1.37 3.13-.1.6.39 1.14 1 1.14.49 0 .9-.36.98-.85.12-.73.42-1.4.82-1.99l2.13 2.13c.39.39 1.02.39 1.41 0 .38-.41.38-1.04-.01-1.43z"
}), 'LeakRemoveRounded'); |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M12 4c-4.41 0-8 3.59-8 8s3.59 8 8 8 8-3.59 8-8-3.59-8-8-8z",
opacity: ".3"
}), h("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"
})), 'LensTwoTone'); |
var gulp = require('gulp'),
browserSync = require('browser-sync'),
sass = require('gulp-ruby-sass'),
// sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
minifycss = require('gulp-minify-css'),
rename = require('gulp-rename'),
postcss = require('gulp-postcss'),
imageResize = require('gulp-image-resize'),
parallel = require("concurrent-transform"),
os = require("os"),
cp = require('child_process');
var messages = {
jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
/**
* Build the Jekyll Site
*/
gulp.task('jekyll-build', function (done) {
browserSync.notify(messages.jekyllBuild);
return cp.spawn('jekyll', ['build', '--config=_config.yml'], {stdio: 'inherit'})
.on('close', done);
});
/**
* Rebuild Jekyll & do page reload
*/
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
browserSync.reload();
});
/**
* Wait for jekyll-build, then launch the Server
*/
gulp.task('browser-sync', ['styles', 'jekyll-build'], function() {
browserSync({
server: {
baseDir: '_site'
},
startPath: "/index.html"
});
});
// To support opacity in IE 8
var opacity = function(css) {
css.eachDecl(function(decl, i) {
if (decl.prop === 'opacity') {
decl.parent.insertAfter(i, {
prop: '-ms-filter',
value: '"progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (parseFloat(decl.value) * 100) + ')"'
});
}
});
};
/**
* Compile files from sass into both assets/css (for live injecting) and site (for future jekyll builds)
*/
gulp.task('styles', function() {
return sass('_scss/', { style: 'expanded' })
.pipe(autoprefixer({browsers: ['last 2 versions', 'Firefox ESR', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1']}))
.pipe(postcss([opacity]))
.pipe(gulp.dest('assets/css'))
.pipe(rename({suffix: '.min'}))
.pipe(minifycss())
.pipe(gulp.dest('assets/css'));
});
/**
* Automatically resize post feature images and turn them into thumbnails
*/
gulp.task("thumbnails", function () {
gulp.src("assets/images/hero/*.{jpg,png}")
.pipe(parallel(
imageResize({ width : 350 }),
os.cpus().length
))
.pipe(gulp.dest("assets/images/thumbnail"));
});
/**
* Watch scss files for changes & recompile
* Watch html/md files, run jekyll & reload BrowserSync
*/
gulp.task('watch', function() {
gulp.watch('_scss/**/*.scss', ['styles']);
gulp.watch('assets/images/hero/*.{jpg,png}', ['thumbnails']);
gulp.watch(['*.html', '*.txt', 'about/**', '_posts/*.markdown', 'assets/javascripts/**/**.js', 'assets/images/**', 'assets/fonts/**', '_layouts/**','_includes/**', 'assets/css/**'], ['jekyll-rebuild']);
});
/**
* Default task, running just `gulp` will compile the sass,
* compile the jekyll site, launch BrowserSync & watch files.
*/
gulp.task('default', ['styles', 'thumbnails', 'browser-sync', 'watch'], function() {
});
|
/*if (color in colorObj){
// Haz algo
}*/
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var cookieToObj = require('cookie');
var bodyParser = require('body-parser');
var fs = require('fs');
var uuid = require('uuid');
var shortId = require('shortid');
var uaParser = require('ua-parser-js');
var dbUrl = process.env.FACILCOPY_DB_URL;
var MongoClient = require('mongodb').MongoClient;
var mongoDbObj;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
MongoClient.connect(dbUrl, function(err, db) {
if (err)
console.log(err);
else {
console.logIt("Connected to MongoDB");
mongoDbObj = {db: db,
rooms: db.collection('rooms')
};
};
});
var socketLocalStorage = {};
var devices = [];
var routes = require('./routes/index');
var users = require('./routes/users');
var rmkey = fs.readFileSync('remotepaster-key.pem');
var rmcert = fs.readFileSync('remotepaster-cert.pem');
var options = {
key: rmkey,
cert: rmcert
};
// Para ayudar a diferenciar los logs
console.logIt = function(str){
console.log("BEGIN----");
console.log(str);
console.log("----END");
}
var socket_io = require('socket.io');
var app = express();
var io = socket_io();
app.io = io;
// var p2p = require('socket.io-p2p-server').Server;
// io.use(p2p);
var insertDocument = function(filter, doc) {
try {
mongoDbObj.rooms.updateOne(filter, {$set: doc}, {upsert: true});
} catch (e) {
throw (e);
}
};
/*var getDevicesInRoom = function(room, callback) {
var myCursor = mongoDbObj.rooms.find( {"room": room})
.toArray(function(err, result) {
if (err) {
return console.log("Error Getting Device List")
}
callback(result);
});
}*/
var getDevicesInRoom = function(room, callback) {
let tempArray = [];
var myCursor = mongoDbObj.rooms.find( {"room": room});
myCursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
tempArray.push(doc);
} else {
console.logIt("Error Getting devices " + err);
}
callback(tempArray);
});
}
/*var io = require('socket.io')({
'close timeout': 606024
}, server);
io.use(p2pserver);*/
io.on('connection', function(socket){
console.logIt('Socket connected: '+socket.id);
var firstTime = false;
if (socket.handshake.headers.cookie){
let cookie = socket.handshake.headers.cookie;
// Is a Reconnection
firstTime = true;
socket.reconnection = true; // Just to mark it
// to prevent the disconnect event change the
// status to offline
/*let oldSocketId = cookieToObj.parse(cookie).io;
insertDocument({ 'socketId': oldSocketId }, {
'socketId': socket.id,
'status': 'online'
});*/
}
socket.on('disconnect', function() {
console.logIt("Socket Disconnected");
insertDocument({ 'socketId': socket.id }, {
'status': 'offline'
});
let room = Object.keys(socket.adapter.rooms)[0];
getDevicesInRoom(room, function(result) {
socket.broadcast.to(room).emit('updateData', result);
});
});
socket.on('leave-default-room', function (){
this.leave(this.id);
});
socket.on('get-device-id', function(){
console.logIt("Sending device id");
socket.emit('device-id', shortId.generate());
});
socket.on('joinmeto', function (data){
let socket = this;
let roomObj = {};
var room = data.room;
var deviceId = data.deviceId;
console.logIt('joinmeto: '+ data.room);
this.join(data.room);
var ua = uaParser(this.handshake.headers['user-agent']);
var desc = ua.browser.name + ' On ' + ua.os.name;
console.logIt(data);
roomObj = {
'room': room,
'deviceId': deviceId,
'description': desc,
'socketId': this.id,
'status': 'online'
}
insertDocument({
'room': room,
'deviceId': deviceId
}, roomObj);
console.logIt(roomObj);
this.emit('joinedToRoom');
this.broadcast.to(room).emit('other-device-joined-room');
});
socket.on("get-device-list", function(data) {
// let room = Object.keys(this.adapter.rooms)[0];
let room = data.room;
console.logIt("get-device-list, room: " + room);
getDevicesInRoom(room, function(result) {
console.logIt("Update Data");
console.logIt(result);
socket.emit('updateData', result);
});
});
socket.on('to-room', function (data){
let room = data.room
this.broadcast.to(room).emit('message', {
msg: data.text
// sender: socketLocalStorage[thisRoom][data.id].desc
});
console.logIt('send to room');
});
/*socket.on('disconnect', function() {
let socket = this;
insertDocument({ 'socketId': socket.id }, {
'status': 'offline'
});
var _socket = this;
var thisRoom = this.adapter.rooms;
var id = this.id;
thisRoom = Object.keys(thisRoom)[0];
console.logIt('User disconnected: '+ id + ' from this room: '+ thisRoom);
io.to(thisRoom).emit('user-disconnected', {id: id}, {});
if (thisRoom !== undefined)
socketLocalStorage.update(_socket);
});*/
});
/*io.on('emit-to-room', function (data){
socket.to(data.room).emit('test');
});*/
/*myhttp.listen(3334, function(){
console.logIt('Http server listening on *:3334');
});*/
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/getuuid', function (req, res){
var roomUuid;
// roomUuid = shortId.generate();
roomUuid = uuid.v4();
res.send(uuid.v4());
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
(function($) {
'use strict';
function getURL(s) {
return 'https://localhost:3131/' + s + '.js';
}
$.ajax({
url: getURL(location.hostname.replace(/^www\./, '')),
dataType: 'text',
success: function (data) {
$(function () { eval(data); });
},
error: function () {
console.error('No dotjs server found at https://localhost:3131.');
}
});
})(jQuery);
|
(function() {
'use strict';
/* @ngInject */
angular
.module('mappifyApp', ['mappify','ngRoute','examples'])
.config(routeConfig)
.config(logConfig)
.controller('MainCtrl', MainCtrl);
/* @ngInject */
function MainCtrl($scope, $location) {
$scope.menuClass = function (page) {
return $location.path() === page ? 'active' : '';
};
}
/* @ngInject */
function routeConfig ($routeProvider) {
// Define fallback route
$routeProvider
.when('/', {
templateUrl: 'template/home.tpl.html'
})
.otherwise({redirectTo:'/'});
}
function logConfig($logProvider){
$logProvider.debugEnabled(true);
}
})();
|
import React from "react";
import { shallow } from "enzyme";
import { TableHeadColumn } from "components/DataTable/Elements";
const createWrapper = (props = {}, render = shallow) => {
return render(<TableHeadColumn {...props} />);
};
describe("TableHeadColumn", () => {
let props;
let wrapper;
beforeEach(() => {
props = {};
wrapper = createWrapper(props, shallow);
});
it("should render", () => {
expect(wrapper).toMatchSnapshot();
});
});
|
/**
* Main application file
*/
'use strict';
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
var adbmon = require('./components/adbmon');
var waitForMongo = require('wait-for-mongo');
function run() {
// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
// Populate DB with sample data
if(config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io')({
'browser client gzip': true,
'browser client etag': true,
'browser client minification': true,
'log level': 1,
'transports':['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']
}).listen(server);
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);
// for after db seeding
setTimeout(adbmon.trackDevice, 1000);
// Start server
server.listen(config.port, config.ip, function () {
console.log('\n\n\n===========================================================' +
'\n= Express Server Started (port:%d), in %s mode =' +
'\n===========================================================\n',
config.port, app.get('env'));
});
// Expose app
exports = module.exports = app;
}
waitForMongo("mongodb://localhost/comet", {timeout: 1000 * 60* 2}, function(err) {
if(err) {
console.log('timeout exceeded');
} else {
console.log('mongodb comes online');
run();
}
});
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/* criteria2IDBQuery.js */
(function (cxt) {
"use strict";
var createQueryParameterFromConditionsAndIndices =
require("./lib/createQueryParameterFromConditionsAndIndices.js")
.createQueryParameterFromConditionsAndIndices,
analyzeConditionsFromCriteria =
require("./lib/analyzeConditionsFromCriteria.js").analyzeConditionsFromCriteria,
createIndicesFromObjectStore =
require("./lib/createIndicesFromObjectStore.js").createIndicesFromObjectStore;
/**
* @public
* @function
* @param {Kriteria} criteria -
* @param {IDBObjectStore} store -
* @param {Object} hint -
* @returns {Array<Object<IDBObjectStore|Index store, Array method, Array keypath,
* Array value1, Array value2, Function filter>>}
*/
var createQueryParameter = function createQueryParameter(criteria, store, hint) {
return createQueryParameterFromConditionsAndIndices(
analyzeConditionsFromCriteria(criteria, false),
createIndicesFromObjectStore(store),
hint && hint.priority ? hint.priority : []
);
};
/**
* @public
* @function
* @param {Object} param - query parameter
* @param {IDBKeyRange} keyrange - IDBKeyRange
* @returns {IDBKeyRange}
*/
var createIDBKeyRange = function createIDBKeyRange(param, keyrange) {
var idb_keyrange = keyrange || (0, eval)("this").IDBKeyRange,
range = null;
if(!idb_keyrange) {
throw new Error("IDBKeyRange is not available.");
}
if(!param.method) {
return null;
}
switch(param.method[0]) {
case "only":
if(param.value1.length === 1) {
range = idb_keyrange[param.method[0]](param.value1[0]);
} else {
range = idb_keyrange[param.method[0]](param.value1);
}
break;
case "upperBound":
if(param.value1.length === 1) {
range = idb_keyrange[param.method[0]](param.value1[0], param.method[1]);
} else {
range = idb_keyrange[param.method[0]](param.value1, param.method[1]);
}
break;
case "lowerBound":
if(param.value2.length === 1) {
range = idb_keyrange[param.method[0]](param.value2[0], param.method[1]);
} else {
range = idb_keyrange[param.method[0]](param.value2, param.method[1]);
}
break;
case "bound":
if(param.value1.length === 1) {
range = idb_keyrange[param.method[0]](
param.value1[0],
param.value2[0],
param.method[1],
param.method[2]
);
} else {
range = idb_keyrange[param.method[0]](
param.value1,
param.value2,
param.method[1],
param.method[2]
);
}
break;
default:
break;
}
return range;
};
cxt.criteria2IDBQuery = {
createQueryParameter: createQueryParameter,
createIDBKeyRange: createIDBKeyRange
};
})((0, eval)("this").window || this);
},{"./lib/analyzeConditionsFromCriteria.js":4,"./lib/createIndicesFromObjectStore.js":5,"./lib/createQueryParameterFromConditionsAndIndices.js":6}],2:[function(require,module,exports){
/* IndexAggregator.js */
(function(cxt) {
"use strict";
/**
* @public
* @class
*/
var IndexAggregator = function IndexAggregator() {
this._keys = [];
this._priority_keys = [];
};
/**
* @public
* @function
* @param {Index[]} indices -
* @returns {void}
*/
IndexAggregator.prototype.init = function(indices, priority_keys) {
for(var i = 0, l = indices.length; i < l; i = i + 1) {
this.set(indices[i]);
}
if(Array.isArray(priority_keys)) {
this._priority_keys = priority_keys;
} else if(priority_keys !== "" && priority_keys !== null && priority_keys !== void 0) {
this._priority_keys = [priority_keys];
}
};
/**
* @public
* @function
* @param {Index} index -
* @returns {void}
*/
IndexAggregator.prototype.set = function(index) {
this._keys[this._keys.length] = {};
var p = this._keys.length - 1;
if(index.keyPath === null) {
this._keys[p] = [];
} else if(Array.isArray(index.keyPath)) {
for(var i = 0, l = index.keyPath.length; i < l; i = i + 1) {
this._keys[p][index.keyPath[i]] = 0;
}
} else {
this._keys[p][index.keyPath] = 0;
}
};
/**
* @publuc
* @function
* @key {String} key -
* @returns {void}
*/
IndexAggregator.prototype.calc = function(key) {
for(var i = 0, l = this._keys.length; i < l; i = i + 1) {
if(this._keys[i][key] !== void 0) {
this._keys[i][key] = 1;
}
}
};
/**
* @public
* @function
* @returns {IndexAggregator}
*/
IndexAggregator.prototype.clone = function clone() {
var ret = new IndexAggregator();
ret._keys = [];
ret._priority_keys = [];
for(var i = 0, l = this._keys.length; i < l; i = i + 1) {
if(!ret._keys[i]) {
ret._keys[i] = {};
}
for(var j in this._keys[i]) {
ret._keys[i][j] = 0;
}
}
for(i = 0, l = this._priority_keys.length; i < l; i = i + 1) {
ret._priority_keys[i] = this._priority_keys[i];
}
return ret;
};
/**
* @public
* @function
* @returns {Integer}
*/
IndexAggregator.prototype.getResult = function getResult() {
var target_nums = [];
for(var i = 0, l = this._keys.length; i < l; i = i + 1) {
var count = 0,
sum = 0,
priority_num = 0;
for(var j in this._keys[i]) {
count = count + 1;
sum = sum + this._keys[i][j];
if(~this._priority_keys.indexOf(j)) {
priority_num = priority_num + 1;
}
}
if(count !== 0 && count === sum) {
target_nums[target_nums.length] = {
index: i,
match_num: sum,
priority_num: priority_num
};
}
}
target_nums.sort(function(a, b) {
if(a.priority_num < b.priority_num) {
return 1;
} else if(a.priority_num > b.priority_num) {
return -1;
} else if(a.match_num < b.match_num) {
return 1;
} else if(a.match_num > b.match_num) {
return -1;
} else {
return 0;
}
});
return target_nums;
};
cxt.IndexAggregator = IndexAggregator;
})(this);
},{}],3:[function(require,module,exports){
/* Query.js */
(function(cxt) {
"use strict";
/**
* @public
* @class
*/
var Query = function Query() {
this.keys = [];
this.conditions = [];
};
/**
* @public
* @function
* @param {Condition} condition -
* @returns {void}
*/
Query.prototype.addKeysFromCondition = function addKeysFromCondition(condition) {
if(condition.key_type === "value" &&
!~this.keys.indexOf(condition.left_key)) {
this.keys[this.keys.length] = condition.left_key;
}
};
/**
* @public
* @function
* @param {Condition} condition -
* @param {Boolean} not_flg
* @returns {void}
*/
Query.prototype.addCondition = function addCondition(condition, not_flg) {
this.addKeysFromCondition(condition);
if(not_flg) {
this.conditions = this.conditions.concat(condition.clone().not().normalize());
} else {
this.conditions = this.conditions.concat(condition.clone().normalize());
}
};
/**
* @public
* @function
* @param {Query} query -
* @returns {Query}
*/
Query.prototype.merge = function merge(query) {
var i = 0, l = 0;
for(i = 0, l = query.keys.length; i < l; i = i + 1) {
if(!~this.keys.indexOf(query.keys[i])) {
this.keys[this.keys.length] = query.keys[i];
}
}
for(i = 0, l = query.conditions.length; i < l; i = i + 1) {
this.conditions[this.conditions.length] = query.conditions[i].clone();
}
return this;
};
/**
* @public
* @function
* @returns {Query}
*/
Query.prototype.clone = function clone() {
var ret = new Query();
ret.keys = this.keys.concat();
for(var i = 0, l = this.conditions.length; i < l; i = i + 1) {
ret.conditions[i] = this.conditions[i].clone();
}
return ret;
};
/**
* @public
* @function
* @returns {Array<Query>}
*/
Query.prototype.not = function not() {
var ret = [];
for(var i = 0, l = this.conditions.length; i < l; i = i + 1) {
var new_query = new Query();
new_query.addCondition(this.conditions[i], true);
ret[ret.length] = new_query;
}
return ret;
};
cxt.Query = Query;
})(this);
},{}],4:[function(require,module,exports){
/* analyzeConditionsFromCriteria.js */
(function (cxt) {
"use strict";
var Kriteria = require("kriteria").Kriteria || (0, eval)("this").Kriteria,
Query = require("./Query.js").Query;
/**
* @public
* @function
* @param {Kriteria} criteria -
* @param {Kriteria} parent_not_flg -
* @returns {Array}
*/
var analyzeConditionsFromCriteria = function analyzeConditionsFromCriteria(criteria, parent_not_flg) {
var conditionAnd = [],
conditionOr = [],
current_not_flg = !!(criteria._not_flg ^ parent_not_flg),
condition = null,
queries = [],
subqueries = [],
query = null,
i = 0, l = 0;
// when doesn't have not flag, and-condition process to and-conditon,
// and or-conditon process to or-condition.
// when has not_flg, and-condition process to or-condition,
// and or-condition process to and-condition.
// !(A and B) is (!A or !B)
// !(A or B) is (!A and !B)
if(!current_not_flg) {
conditionAnd = criteria.getConditionAnd();
conditionOr = criteria.getConditionOr();
} else {
conditionAnd = criteria.getConditionOr();
conditionOr = criteria.getConditionAnd();
}
if(conditionAnd.length > 0) {
query = new Query();
for(i = 0, l = conditionAnd.length; i < l; i = i + 1) {
condition = conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
subqueries = combination(
subqueries,
analyzeConditionsFromCriteria(condition.criteria, current_not_flg)
);
} else if(
!current_not_flg && (condition.operator === "in" || condition.operator === "not_between") ||
current_not_flg && (condition.operator === "not_in" || condition.operator === "between")
) {
// each condition register to each query
// operator 'in' or !'not_in' or 'between' or !'not_between' change to
// 'eq', 'ne', 'gt', 'ge', 'lt', 'le'
subqueries = combination(subqueries, createNomalizedCondition(condition, current_not_flg));
} else {
// condition register a query as one condition
query.addCondition(condition, current_not_flg);
}
}
queries = queries.concat(combination([query], subqueries));
}
if(conditionOr.length > 0) {
for(i = 0, l = conditionOr.length; i < l; i = i + 1) {
condition = conditionOr[i];
if (condition.criteria instanceof Kriteria) {
queries = queries.concat(analyzeConditionsFromCriteria(condition.criteria, current_not_flg));
} else if(
!current_not_flg && (condition.operator === "in" || condition.operator === "not_between") ||
current_not_flg && (condition.operator === "not_in" || condition.operator === "between")
) {
// each condition register to each query
// operator 'in' or !'not_in' or 'between' or !'not_between' change to
// 'eq', 'ne', 'gt', 'ge', 'lt', 'le'
queries = queries.concat(createNomalizedCondition(condition, current_not_flg));
} else {
// condition register a query as one condition
query = new Query();
query.addCondition(condition, current_not_flg);
queries = queries.concat([query]);
}
}
}
return queries;
};
/**
* @private
* @function
* @param {Array<Condition>} arr1 -
* @param {Array<Condition>} arr2 -
* @returns {Array<Condition>}
*/
var combination = function combination(arr1, arr2) {
var ret = [];
if(arr1.length > 0 && arr2.length) {
for(var i = 0, l = arr1.length; i < l; i = i + 1) {
for(var j = 0, ll = arr2.length; j < ll; j = j + 1) {
ret[ret.length] = arr1[i].clone().merge(arr2[j]);
}
}
} else if(arr1.length === 0) {
ret = arr2.concat();
} else { // arr2.length === 0
ret = arr1.concat();
}
return ret;
};
/**
* @private
* @function
* @param {Condition} condition -
* @param {Boolean} flg_not -
* @retuns {Query[]}
*/
var createNomalizedCondition = function createNomalizedCondition(condition, flg_not) {
var normalized = condition.normalize(),
subqueries = [];
for(var i = 0, l = normalized.length; i < l; i = i + 1) {
var subquery = new Query();
if(flg_not) {
subquery.addCondition(normalized[i].not());
} else {
subquery.addCondition(normalized[i]);
}
subqueries[subqueries.length] = subquery;
}
return subqueries;
};
cxt.analyzeConditionsFromCriteria = analyzeConditionsFromCriteria;
}(this));
},{"./Query.js":3,"kriteria":7}],5:[function(require,module,exports){
/* createIndicesFromObjectStore.js */
(function (cxt) {
"use strict";
/**
* @public
* @function
* @param {IDBObjectStore} store -
* @returns Array<IDBObjectStore|Index>
*/
var createIndicesFromObjectStore = function createIndicesFromObjectStore(store) {
var indices = [store];
for(var i = 0, l = store.indexNames.length; i < l; i = (i + 1)|0) {
indices[indices.length] = store.index(store.indexNames[i]);
}
return indices;
};
cxt.createIndicesFromObjectStore = createIndicesFromObjectStore;
}(this));
},{}],6:[function(require,module,exports){
/* createQueryParameterFromConditionsAndIndices.js */
(function (cxt) {
"use strict";
var Kriteria = require("kriteria").Kriteria || (0, eval)("this").Kriteria,
IndexAggregator = require("./IndexAggregator.js").IndexAggregator;
/**
* @public
* @function
* @param {Array} conditions -
* @param {Array<Index>} indices -
* @returns {Object[]}
* {Mixed(IDBObjectStore|IDBIndex)} store
* {Array<String|Boolean>} method
* {String[]} keypath
* {*[]} value1
* {*[]} value2
* {Function} filter
*/
var createQueryParameterFromConditionsAndIndices =
function createQueryParameterFromConditionsAndIndices(
conditions,
indices,
priority_keys)
{
var aggregator = new IndexAggregator(),
i = 0, l = 0,
j = 0, l2 = 0,
k = 0, l3 = 0,
key = "",
ret = [];
aggregator.init(indices, priority_keys);
for(i = 0, l = conditions.length; i < l; i = i + 1) {
var condition = conditions[i],
agg = aggregator.clone();
var no_index_result = {
store: indices[0],
method: null,
keypath: null,
value1: null,
value2: null,
filter: Kriteria.parse({ and: condition.conditions }).matcher()
};
// condition から、keyPath の使用数が多い index を計算する
var targetIndicesNums = calculateIndex(agg, condition);
if(targetIndicesNums.length === 0) {
ret[ret.length] = no_index_result;
} else {
var target_keypath = [],
value = [[], []],
method = [],
method_level = [],
index = 0;
for(j = 0, l2 = targetIndicesNums.length; j < l2; j = j + 1) {
var targetIndicesNum = targetIndicesNums[j].index,
data = [];
index = indices[targetIndicesNum];
target_keypath = [];
value = [[], []];
method_level = [];
method = [];
for(k = 0, l3 = condition.conditions.length; k < l3; k = k + 1) {
var cond = condition.conditions[k],
idx = index.keyPath.indexOf(cond.left_key);
if(~idx) {
// condition から各keyに対してフラグを設定する
analyzeConditionAndSetData(cond, idx, data);
}
}
for(key in data) {
// 上記で設定したフラグからメソッドを決定する
analizeDataAndSetMethod(
data[key], key, {
method: method,
value: value,
method_level: method_level,
target_keypath: target_keypath
}
);
}
// only は bound で表現可能(過分は出るが不足はなし)。
// bound は lowerbound または upperBound で表現可能(同上)。
// lowerBound および upperBound は互いに表現不可能のため、両方が存在する場合は対象のインデックスは
// 条件に対し使用不可であるとし、別のインデックスを対象とする
if(isMethodCollision(method)) {
continue;
} else {
break;
}
}
if(j === targetIndicesNums.length) {
target_keypath = [];
value = [[], []];
method_level = [];
method = [];
}
if(method.length > 0) {
var target_method = [],
max_method_level = 0;
// 使用するメソッドを検索
// lowerBound, upperBound -> level 3
// bound -> level 2
// only -> level 1
// 最大のレベルのものを選択する
for(k = 0, l3 = method.length; k < l3; k = k + 1) {
if(method[k] !== void 0 && method_level[k] > max_method_level) {
target_method = method[k].concat();
max_method_level = method_level[k];
}
}
ret[ret.length] = {
store: index,
method: target_method,
keypath: target_keypath,
value1: value[0],
value2: value[1],
filter: Kriteria.parse({ and: condition.conditions }).matcher()
};
} else {
ret[ret.length] = no_index_result;
}
}
}
return ret;
};
/**
* @private
* @function
* @params {IndexAggregator} agg -
* @params {Object} condition -
* @returns {Number[]}
*/
var calculateIndex = function calculateIndex(agg, condition) {
for(var j = 0, l2 = condition.keys.length; j < l2; j = j + 1) {
for(var k = 0, l3 = condition.conditions.length; k < l3; k = k + 1) {
var ope = condition.conditions[k].operator;
// key_type が 'value' のものが対象('key' のものは対象外)
// operator が 'ne', 'match', 'not_match' の場合は対象外
if(condition.conditions[k].left_key === condition.keys[j] &&
condition.conditions[k].key_type === "value" &&
ope !== "ne" && ope !== "match" && ope !== "not_match") {
// key の使用数を計算
agg.calc(condition.keys[j]);
}
}
}
return agg.getResult();
};
/**
* @private
* @function
* @params {Object} condition -
* @params {Number} idx -
* @params {Object} data - output
* @returns {void}
*/
var analyzeConditionAndSetData = function analyzeConditionAndSetData(condition, idx, data) {
var key = condition.left_key;
if(!data[key]) {
data[key] = {
keypath_index: idx,
val1: null,
val2: null,
flg_eq: false,
flg_lt: false,
flg_le: false,
flg_gt: false,
flg_ge: false
};
}
switch(condition.operator) {
case "eq":
data[key].flg_eq = true;
data[key].flg_lt = false;
data[key].flg_le = false;
data[key].flg_gt = false;
data[key].flg_ge = false;
data[key].val1 = condition.right_key[0];
data[key].val2 = condition.right_key[0];
break;
case "ne":
break;
case "lt":
if(!data[key].flg_eq) {
data[key].flg_lt = true;
if(data[key].val2 === null || data[key].val2 > condition.right_key[0]) {
data[key].val2 = condition.right_key[0];
}
}
break;
case "le":
if(!data[key].flg_eq) {
data[key].flg_le = true;
data[key].flg_lt = false;
if(data[key].val2 === null || data[key].val2 > condition.right_key[0]) {
data[key].val2 = condition.right_key[0];
}
}
break;
case "gt":
if(!data[key].flg_eq) {
data[key].flg_gt = true;
if(data[key].val1 === null || data[key].val1 < condition.right_key[0]) {
data[key].val1 = condition.right_key[0];
}
}
break;
case "ge":
if(!data[key].flg_eq) {
data[key].flg_ge = true;
data[key].flg_gt = false;
if(data[key].val1 === null || data[key].val1 < condition.right_key[0]) {
data[key].val1 = condition.right_key[0];
}
}
break;
case "match":
case "not_match":
break;
}
};
/**
* @private
* @function
* @params {Object} data -
* @params {String} key -
* @params {Object} out - output
* @returns {void}
*/
var analizeDataAndSetMethod = function analizeDataAndSetMethod(data, key, out) {
var method = out.method,
value = out.value,
method_level = out.method_level,
target_keypath = out.target_keypath;
if(data.keypath_index >= 0) {
if(method_level[data.keypath_index] === void 0) {
method_level[data.keypath_index] = 0;
}
if(data.flg_ge) {
if(data.flg_le) {
method[data.keypath_index] = ["bound", false, false];
value[0][data.keypath_index] = data.val1;
value[1][data.keypath_index] = data.val2;
method_level[data.keypath_index] = 2;
} else if(data.flg_lt) {
method[data.keypath_index] = ["bound", true, false];
value[0][data.keypath_index] = data.val1;
value[1][data.keypath_index] = data.val2;
method_level[data.keypath_index] = 2;
} else if(method_level[data.keypath_index] <= 1) {
method[data.keypath_index] = ["lowerBound", false];
value[1][data.keypath_index] = data.val1;
method_level[data.keypath_index] = 3;
}
} else if(data.flg_gt) {
if(data.flg_le) {
method[data.keypath_index] = ["bound", false, true];
value[0][data.keypath_index] = data.val1;
value[1][data.keypath_index] = data.val2;
method_level[data.keypath_index] = 2;
} else if(data.flg_lt) {
method[data.keypath_index] = ["bound", true, true];
value[0][data.keypath_index] = data.val1;
value[1][data.keypath_index] = data.val2;
method_level[data.keypath_index] = 2;
} else if(method_level[data.keypath_index] <= 1) {
method[data.keypath_index] = ["lowerBound", true];
value[1][data.keypath_index] = data.val1;
method_level[data.keypath_index] = 3;
}
} else if(data.flg_le) {
method[data.keypath_index] = ["upperBound", false];
value[0][data.keypath_index] = data.val2;
method_level[data.keypath_index] = 3;
} else if(data.flg_lt) {
method[data.keypath_index] = ["upperBound", true];
value[0][data.keypath_index] = data.val2;
method_level[data.keypath_index] = 3;
} else if(data.flg_eq) {
method[data.keypath_index] = ["only"];
value[0][data.keypath_index] = data.val1;
value[1][data.keypath_index] = data.val2;
method_level[data.keypath_index] = 1;
}
target_keypath[data.keypath_index] = key;
}
};
/**
* @private
* @function
* @params {Object[]} method -
* @returns {Boolean}
*/
var isMethodCollision = function isMethodCollision(method) {
var has_lowerbound = false,
has_upperbound = false;
for(var i = 0, l = method.length; i < l; i = i + 1) {
switch(method[i][0]) {
case "lowerBound":
has_lowerbound = true;
break;
case "upperBound":
has_upperbound = true;
break;
}
}
return has_lowerbound && has_upperbound ? true : false;
};
cxt.createQueryParameterFromConditionsAndIndices = createQueryParameterFromConditionsAndIndices;
}(this));
},{"./IndexAggregator.js":2,"kriteria":7}],7:[function(require,module,exports){
/* Kriteria.js */
(function(cxt, global) {
"use strict";
var getProperty = require("./lib/getProperty.js").getProperty,
matchPrefix = require("./lib/matchPrefix.js").matchPrefix,
Condition = require("./lib/Condition.js").Condition,
evaluation = require("./lib/evaluation.js").evaluation,
kref = require("./lib/keys_reference.js").keysReference;
/**
* @public
* @class
*/
var Kriteria = function Kriteria() {
this._conditionAnd = [];
this._conditionOr = [];
this._not_flg = false;
};
Kriteria._name_ = "Kriteria";
/**
* @public
* @function
* @returns {Condition[]}
*/
Kriteria.prototype.getConditionAnd = function getConditionAnd() {
return this._conditionAnd;
};
/**
* @public
* @function
* @returns {Condition[]}
*/
Kriteria.prototype.getConditionOr = function getConditionAOr() {
return this._conditionOr;
};
/**
* @private
* @property
* @description
*/
Kriteria._JS_OPERATOR = {
eq: "===",
ne: "!==",
lt: "<",
le: "<=",
gt: ">",
ge: ">="
};
/**
* @public
* @function
* @param {Condition} condition -
* @returns {void}
* @description
*/
Kriteria.prototype.addAnd = function addAnd(condition) {
this._conditionAnd[this._conditionAnd.length] = condition;
};
/**
* @public
* @function
* @param {Condition} condition -
* @returns {void}
* @description
*/
Kriteria.prototype.addOr = function addOr(condition) {
this._conditionOr[this._conditionOr.length] = condition;
};
/**
* @public
* @function
* @param {Mixed(String|Kriteria|Function)} key - key name or Kriteria instance or Kriteria reqired function
* @returns {Function} evaluation || {Kriteria}
* @description
*/
Kriteria.prototype.and = function and(key) {
var key_type = typeof key,
cri = null;
if(
key_type === "string" ||
key instanceof String ||
key_type === "number" ||
key instanceof Number
) {
return evaluation("and", key, this);
} else if(key instanceof Kriteria) {
cri = key;
this.addAnd(new Condition("", "", [], "", cri));
return this;
} else if(typeof key === "function") {
cri = new Kriteria();
key(cri);
this.addAnd(new Condition("", "", [], "", cri));
return this;
} else {
throw new Error("invalid type of argument. (" + key_type + ")");
}
};
/**
* @public
* @function
* @param {Mixed(String|Kriteria|Function)} key - key name or Kriteria instance or Kriteria reqired function
* @returns {Mixed(Function|Kriteria)}
* @description
*/
Kriteria.prototype.or = function or(key) {
var key_type = typeof key,
cri = null;
if(key_type === "string" ||
key instanceof String ||
key_type === "number" ||
key instanceof Number
) {
return evaluation("or", key, this);
} else if(key instanceof Kriteria) {
cri = key;
this.addOr(new Condition("", "", [], "", cri));
return this;
} else if(typeof key === "function") {
cri = new Kriteria();
key(cri);
this.addOr(new Condition("", "", [], "", cri));
return this;
} else {
throw new Error("invalid type of argument. (" + key_type + ")");
}
};
/**
* @public
* @function
* @returns {Kriteria}
* @description
*/
Kriteria.prototype.not = function not() {
this._not_flg = !this._not_flg;
return this;
};
/**
* @public
* @static
* @function
* @param {Object} conditions -
* {Condition[]} conditions.and -
* {Condition[]} conditions.or -
* @returns {Kriteria}
* @description
*/
Kriteria.parse = function parse(conditions) {
var ret = new Kriteria(),
i = "";
for(i in conditions.and) {
ret.addAnd(conditions.and[i]);
}
for(i in conditions.or) {
ret.andOr(conditions.or[i]);
}
if(conditions.not) {
ret.not();
}
return ret;
};
/**
* @public
* @function
* @param {Object} data -
* @returns {Boolean}
* @description
*/
Kriteria.prototype.match = function match(data) {
var i = 0, l = 0,
j = 0, l2 = 0,
left_key = "",
operator = "",
right_key = [],
key_type = "",
left_value = null,
right_value = [],
result = false,
condition = null,
tmp_right_value = null;
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
condition = this._conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
result = condition.criteria.match(data);
// and条件は1つでもfalseがあったら、結果はfalse
if(!result) {
break;
}
} else {
left_key = condition.left_key;
operator = condition.operator;
right_key = condition.right_key;
key_type = condition.key_type;
left_value = getProperty(data, left_key);
if(key_type === "value") {
right_value = right_key;
} else if(key_type === "key") {
tmp_right_value = getProperty(data, right_key[0]);
if(Array.isArray(tmp_right_value)) {
if(operator === "match" || operator === "not_match") {
right_value = [];
for(j = 0, l2 = tmp_right_value.length; j < l2; j = j + 1) {
if(tmp_right_value[j] === null
|| tmp_right_value[j] === void 0
|| tmp_right_value[j] === "") {
right_value[j] = tmp_right_value[j];
} else {
right_value[j] = new RegExp(tmp_right_value[j]);
}
}
} else {
right_value = tmp_right_value;
}
} else {
if(operator === "match" || operator === "not_match") {
if(tmp_right_value === null
|| tmp_right_value === void 0
|| tmp_right_value === "") {
right_value = tmp_right_value;
} else {
right_value = [new RegExp(tmp_right_value)];
}
} else {
right_value = [tmp_right_value];
}
}
}
if(
right_value === void 0
|| !!~right_value.indexOf(void 0)
|| left_value === void 0
) {
// valueがundefinedの場合はfalse
result = false;
} else {
// 上記以外は比較演算
result = this._compare(left_value, operator, right_value);
}
// and条件は1つでもfalseがあったら、結果はfalse
if(!result) {
break;
}
}
}
// and条件ですべて一致した場合
if(result) {
return !!(true ^ this._not_flg);
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
condition = this._conditionOr[i];
if(condition.criteria instanceof Kriteria) {
result = condition.criteria.match(data);
if(result) {
return !!(true ^ this._not_flg);
}
} else {
left_key = condition.left_key;
operator = condition.operator;
right_key = condition.right_key;
key_type = condition.key_type;
left_value = getProperty(data, left_key);
if(key_type === "value") {
right_value = right_key;
} else if(key_type === "key") {
tmp_right_value = getProperty(data, right_key[0]);
if(Array.isArray(tmp_right_value)) {
if(operator === "match" || operator === "not_match") {
right_value = [];
for(j = 0, l2 = tmp_right_value.length; j < l2; j = j + 1) {
if(tmp_right_value[j] === null
|| tmp_right_value[j] === void 0
|| tmp_right_value[j] === "") {
right_value[j] = tmp_right_value[j];
} else {
right_value[j] = new RegExp(tmp_right_value[j]);
}
}
} else {
right_value = tmp_right_value;
}
} else {
if(operator === "match" || operator === "not_match") {
if(tmp_right_value === null
|| tmp_right_value === void 0
|| tmp_right_value !== "") {
right_value = tmp_right_value;
} else {
right_value = [new RegExp(tmp_right_value)];
}
} else {
right_value = [tmp_right_value];
}
}
}
if(
right_value === void 0
|| !!~right_value.indexOf(void 0)
|| left_value === void 0
) {
// valueがundefinedの場合はfalse
result = false;
} else {
// 上記以外は比較演算
result = this._compare(left_value, operator, right_value);
}
// or条件は1つでもtrueがあったら、結果はtrue
if(result) {
return !!(true ^ this._not_flg);
}
}
}
// 上記以外はfalse
return !!(false ^ this._not_flg);
};
/**
* @private
* @function
* @param {Mixed(String|Number)} value1 -
* @param {String} operator -
* @param {Array} value2 -
* @returns {Boolean}
* @description
*/
Kriteria.prototype._compare = function _compare(value1, operator, value2) {
var result = false;
switch(operator) {
case "eq":
result = (value2[0] === value1);
break;
case "ne":
result = (value2[0] !== value1);
break;
case "lt":
result = (value2[0] > value1);
break;
case "le":
result = (value2[0] >= value1);
break;
case "gt":
result = (value2[0] < value1);
break;
case "ge":
result = (value2[0] <= value1);
break;
case "in":
result = !!~value2.indexOf(value1);
break;
case "not_in":
result = !~value2.indexOf(value1);
break;
case "between":
result = (value2[0] <= value1 && value2[1] >= value1);
break;
case "not_between":
result = (value2[0] > value1 || value2[1] < value1);
break;
case "match":
if(value2[0] === null) {
if(value1 === null || value1 === void 0) {
result = true;
} else {
result = false;
}
} else if(value1 === null) {
result = false;
} else if(value2[0] === "") {
result = value1 === "" ? true : false;
} else {
result = value2[0].test(value1);
}
break;
case "not_match":
if(value2[0] === null) {
if(value1 === null || value1 === void 0) {
result = false;
} else {
result = true;
}
} else if(value1 === null) {
result = true;
} else if(value2[0] === "") {
result = value1 === "" ? false : true;
} else {
result = !value2[0].test(value1);
}
break;
}
return result;
};
/**
* @public
* @function
* @returns {Function}
* @description
*/
Kriteria.prototype.matcher = function matcher() {
/* eslint no-new-func: 0 */
return new Function("$", "return " + this._createMatchingExpression());
};
/**
* @private
* @function
* @returns {String}
* @description
*/
Kriteria.prototype._createMatchingExpression = function _createMatchingExpression() {
var i = 0, l = 0,
expAnd = [],
expOr = [],
retAnd = "",
retOr = "",
condition = null,
ret = "";
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
condition = this._conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
expAnd[expAnd.length] = "(" + condition.criteria._createMatchingExpression() + ")";
} else {
expAnd[expAnd.length] = this._createExpression(condition);
}
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
condition = this._conditionOr[i];
if(condition.criteria instanceof Kriteria) {
expOr[expOr.length] = "(" + condition.criteria._createMatchingExpression() + ")";
} else {
expOr[expOr.length] = this._createExpression(condition);
}
}
retAnd = expAnd.join(" && ");
retOr = expOr.join(" || ");
if(retAnd && retOr) {
ret = retAnd + " || " + retOr + " ";
} else if(!retOr) {
ret = retAnd;
} else if(!retAnd) {
ret = retOr;
}
if(this._not_flg) {
ret = "!(" + ret + ")";
}
return ret;
};
/**
* @private
* @function
* @param {Condition} condition -
* @returns {String}
* @description
*/
Kriteria.prototype._createExpression = function _createExpression(condition) {
return "(" +
this._createJsExpressionOfKeyIsNotUndefined(condition.left_key) +
" && " +
(
condition.key_type === "key" ?
this._createJsExpressionOfKeyIsNotUndefined(condition.right_key[0]) + " && " :
""
) +
this._createJsExpression(condition) +
")";
};
/**
* @private
* @function
* @param {Condition}
* @returns {String}
* @description
*/
Kriteria.prototype._createJsExpression = function _createJsExpression(condition) {
var left_key = kref("$", condition.left_key.split(".")),
operator = condition.operator,
right_key = condition.right_key,
key_type = condition.key_type,
_operator = Kriteria._JS_OPERATOR[operator],
$_right_key = kref("$", right_key[0]).toString();
if(_operator) {
/* 演算子が eq, ne, lt, le, gt, ge のいずれか
[left_key] [operator] "[right_key]"
[left_key] [operator] $.[right_key]
*/
return left_key + " " + _operator + " " +
this._toStringExpressionFromValue(right_key[0], key_type);
} else if(operator === "in") {
/* in 演算子
!!~[[right_key]].indexOf([left_key])
(Array.isArray($.[right_key]) ? !!~$.[right_key].indexOf([left_key]) : $.[right_key] === [left_key])
*/
if(key_type === "value") {
return "!!~" + this._toStringExpressionFromArray(right_key) + ".indexOf(" + left_key + ")";
} else {
return "(Array.isArray(" + $_right_key + ") ? " +
"!!~" + $_right_key + ".indexOf(" + left_key + "): " +
$_right_key + " === " + left_key + ")";
}
} else if(operator === "not_in") {
/* not_in 演算子
*/
if(key_type === "value") {
return "!~" + this._toStringExpressionFromArray(right_key) + ".indexOf(" + left_key + ")";
} else {
return "(Array.isArray(" + $_right_key + ") ? " +
"!~" + $_right_key + ".indexOf(" + left_key + "): " +
$_right_key + " !== " + left_key + ")";
}
} else if(operator === "between") {
/* between 演算子
*/
return left_key + " >= " + this._toStringExpressionFromValue(right_key[0], key_type) +
" && " +
left_key + " <= " + this._toStringExpressionFromValue(right_key[1], key_type);
} else if(operator === "not_between") {
/* not_between 演算子
*/
return left_key + " < " + this._toStringExpressionFromValue(right_key[0], key_type) +
" || " +
left_key + " > " + this._toStringExpressionFromValue(right_key[1], key_type);
} else if(operator === "match") {
/* match 演算子
*/
if(right_key[0] === void 0) {
return false;
} else if(right_key[0] === null) {
return "(" + left_key + " === null ? true : false)";
} else if(right_key[0] === "") {
return "(" + left_key + " === '' ? true : false)";
} else {
//return "(" + left_key + " !== null && " + right_key[0] + ".test(" + left_key + "))";
return "(" + right_key[0] + ".test(" + left_key + "))";
}
} else if(operator === "not_match") {
/* not_match 演算子
*/
if(right_key[0] === void 0) {
return false;
} else if(right_key[0] === null) {
return "(" + left_key + " === null ? false : true)";
} else if(right_key[0] === "") {
return "(" + left_key + " === '' ? false : true)";
} else {
//return "(" + left_key + " !== null && !" + right_key[0] + ".test(" + left_key + "))";
return "(!" + right_key[0] + ".test(" + left_key + "))";
}
} else {
return null;
}
};
/**
* @private
* @function
* @param {String} key -
* @returns {String}
* @description
*/
Kriteria.prototype._createJsExpressionOfKeyIsNotUndefined =
function _createJsExpressionOfKeyIsNotUndefined(key) {
var keys = key.split("."),
work_keys = [],
ret = [];
for(var i = 0, l = keys.length; i < l; i = i + 1) {
work_keys[work_keys.length] = keys[i];
ret[ret.length] = kref("$", work_keys).toString() + " !== void 0";
}
return ret.join(" && ");
};
/**
* @private
* @function
* @param {String} key -
* @returns {String}
* @description
*/
Kriteria.prototype._createJSExpressionOfKeyIsUndefined =
function _createJSExpressionOfKeyIsUndefined(key) {
var keys = key.split("."),
work_keys = [],
ret = [];
for(var i = 0, l = keys.length; i < l; i = i + 1) {
work_keys[work_keys.length] = keys[i];
var $_work_keys = kref("$", work_keys);
ret[ret.length] = $_work_keys + " === void 0";
ret[ret.length] = $_work_keys + " === null";
}
return ret.join(" || ");
};
/**
* @private
* @function
* @param {Array} arr -
* @returns {String}
* @description
*/
Kriteria.prototype._toStringExpressionFromArray = function _toStringExpressionFromArray(arr) {
var ret = [];
for(var i = 0, l = arr.length; i < l; i = i + 1) {
ret[ret.length] = this._toStringExpressionFromValue(arr[i], "value");
}
return "[" + ret.join(", ") + "]";
};
/**
* @private
* @function
* @param {Mixed(String|Number)} value -
* @param {String} type -
* @returns {String}
* @description
*/
Kriteria.prototype._toStringExpressionFromValue =
function _toStringExpressionFromValue(value, type) {
if(type === "value" && (typeof value === "string" || value instanceof String)) {
return '"' + value + '"';
} else if(type === "key") {
return kref("$", value.split(".")).toString();
} else {
return value + '';
}
};
/**
* @public
* @function
* @param {String[]} prefixes -
* @returns {Object.<Kriteria>}
*/
Kriteria.prototype.splitByKeyPrefixes = function splitByKeyPrefixes(prefixes) {
if(!Array.isArray(prefixes) || prefixes.length === 0) {
return null;
}
var ret = {},
condition = null,
splited_criteria = null,
matchPrefixes = [],
left_key = "",
right_key = "",
key_type = "",
match1 = true,
match2 = true,
added = true,
key = "",
i = 0, l = 0,
j = 0, l2 = 0;
for(i = 0, l = prefixes.length; i < l; i = i + 1) {
ret[prefixes[i]] = new Kriteria();
}
ret.else = new Kriteria();
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
condition = this._conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
splited_criteria = condition.criteria.splitByKeyPrefixes(prefixes);
for(key in splited_criteria) {
if(splited_criteria[key] !== null) {
ret[key].and(splited_criteria[key]);
}
}
} else {
matchPrefixes = [];
left_key = condition.left_key;
right_key = condition.right_key[0];
key_type = condition.key_type;
added = false;
for(j = 0, l2 = prefixes.length; j < l2; j = j + 1) {
matchPrefixes[matchPrefixes.length] = prefixes[j];
match1 = matchPrefix(left_key, matchPrefixes);
if(key_type === "key") {
match2 = matchPrefix(right_key, matchPrefixes);
}
if(
(key_type === "value" && match1) ||
(key_type === "key" && match1 && match2)
) {
ret[prefixes[j]].addAnd(condition);
added = true;
break;
}
}
if(!added) {
ret.else.addAnd(condition);
}
}
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
condition = this._conditionOr[i];
if(condition.criteria instanceof Kriteria) {
splited_criteria = condition.criteria.splitByKeyPrefixes(prefixes);
for(key in splited_criteria) {
if(splited_criteria[key] !== null) {
ret[key].or(splited_criteria[key]);
}
}
} else {
matchPrefixes = [];
left_key = condition.left_key;
right_key = condition.right_key[0];
key_type = condition.key_type;
added = false;
for(j = 0, l2 = prefixes.length; j < l2; j = j + 1) {
matchPrefixes[matchPrefixes.length] = prefixes[j];
match1 = matchPrefix(left_key, matchPrefixes);
if(key_type === "key") {
match2 = matchPrefix(right_key, matchPrefixes);
}
if(
(key_type === "value" && match1) ||
(key_type === "key" && match1 && match2)
) {
ret[prefixes[j]].addOr(condition);
added = true;
break;
}
}
if(!added) {
ret.else.addOr(condition);
}
}
}
for(key in ret) {
if(ret[key].getConditionAnd().length > 0 || ret[key].getConditionOr().length > 0) {
ret[key]._not_flg = this._not_flg;
} else {
ret[key] = null;
}
}
return ret;
};
/**
* @public
* @function
* @param {Kriteria} kri -
* @param {Boolean} unique -
* @returns {Kriteria}
*/
Kriteria.prototype.merge = function merge(kri, unique) {
var new_kriteria = new Kriteria(),
kri_cond_and = kri.getConditionAnd(),
kri_cond_or = kri.getConditionOr(),
cond1 = null,
match = false,
i = 0, l = 0,
j = 0, l2 = 0;
if(this._not_flg !== kri._not_flg) {
throw new Error("Kriteria#merge - collision to not flag.");
}
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
new_kriteria.addAnd(this._conditionAnd[i]);
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
new_kriteria.addOr(this._conditionOr[i]);
}
if(!unique) {
for(i = 0, l = kri_cond_and.length; i < l; i = i + 1) {
new_kriteria.addAnd(kri_cond_and[i]);
}
for(i = 0, l = kri_cond_or.length; i < l; i = i + 1) {
new_kriteria.addOr(kri_cond_or[i]);
}
} else {
for(i = 0, l = kri_cond_and.length; i < l; i = i + 1) {
cond1 = kri_cond_and[i];
match = false;
for(j = 0, l2 = this._conditionAnd.length; j < l2; j = j + 1) {
if(cond1.compareTo(this._conditionAnd[j]) === 0) {
match = true;
break;
}
}
if(!match) {
new_kriteria.addAnd(cond1);
}
}
for(i = 0, l = kri_cond_or.length; i < l; i = i + 1) {
cond1 = kri_cond_or[i];
match = false;
for(j = 0, l2 = this._conditionOr.length; j < l2; j = j + 1) {
if(cond1.compareTo(this._conditionOr[j]) === 0) {
match = true;
break;
}
}
if(!match) {
new_kriteria.addOr(cond1);
}
}
}
return new_kriteria;
};
/**
* @public
* @function
* @param {Kriteria} kri -
* @returns {Number}
* 0 - equal
* 1 - greater
* -1 - less
*/
Kriteria.prototype.compareTo = function compareTo(kri) {
var sort_func = function(a, b) {
return a.compareTo(b);
},
kri_cond_and = kri.getConditionAnd(),
kri_cond_or = kri.getConditionOr(),
cond1 = null,
cond2 = null,
compared = true,
len1 = 0, len2 = 0,
i = 0, l = 0;
this._conditionAnd.sort(sort_func);
kri_cond_and.sort(sort_func);
this._conditionOr.sort(sort_func);
kri_cond_or.sort(sort_func);
if(this._not_flg && !kri._not_flg) {
return -1;
} else if(!this._not_flg && kri._not_flg) {
return 1;
}
len1 = this._conditionAnd.length;
len2 = kri_cond_and.length;
l = len1 > len2 ? len1 : len2;
for(i = 0; i < l; i = i + 1) {
cond1 = this._conditionAnd[i];
cond2 = kri_cond_and[i];
if(!cond1) {
return -1;
} else if(!cond2) {
return 1;
}
compared = cond1.compareTo(cond2);
if(compared !== 0) {
return compared;
}
}
len1 = this._conditionOr.length;
len2 = kri_cond_or.length;
l = len1 > len2 ? len1 : len2;
for(i = 0; i < l; i = i + 1) {
cond1 = this._conditionOr[i];
cond2 = kri_cond_or[i];
if(!cond1) {
return -1;
} else if(!cond2) {
return 1;
}
compared = cond1.compareTo(cond2);
if(compared !== 0) {
return compared;
}
}
return 0;
};
/**
* @public
* @function
* @param {String[]} prefixes -
* @returns {Kriteria}
*/
Kriteria.prototype.removePrefixes = function removePrefixes(prefixes) {
var rex = null,
condition = null,
i = 0, l = 0;
if(prefixes === null || prefixes === void 0 || !Array.isArray(prefixes) || prefixes.length === 0) {
return this;
}
rex = new RegExp("^(" + prefixes.join("|") + ").");
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
condition = this._conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
condition.criteria.removePrefixes(prefixes);
} else {
condition.left_key = condition.left_key.replace(rex, "");
if(condition.key_type === "key") {
condition.right_key[0] = condition.right_key[0].replace(rex, "");
}
}
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
condition = this._conditionOr[i];
if(condition.criteria instanceof Kriteria) {
condition.criteria.removePrefixes(prefixes);
} else {
condition.left_key = condition.left_key.replace(rex, "");
if(condition.key_type === "key") {
condition.right_key[0] = condition.right_key[0].replace(rex, "");
}
}
}
return this;
};
cxt.Kriteria = Kriteria;
global.Kriteria = Kriteria;
}(this, (0, eval)("this").window || this));
},{"./lib/Condition.js":8,"./lib/evaluation.js":9,"./lib/getProperty.js":10,"./lib/keys_reference.js":11,"./lib/matchPrefix.js":12}],8:[function(require,module,exports){
/* Condition.js */
(function (cxt) {
"use strict";
/**
* @public
* @class
* @param {String} left_key -
* @param {String} operator -
* @param {Mixed(Array<any>|any)} right_key -
* @param {String} key_type -
* @param {Kriteria} criteria
* @description
*/
var Condition = function Condition(left_key, operator, right_key, key_type, criteria) {
this.left_key = left_key;
this.operator = operator;
this.right_key = (Array.isArray(right_key) || right_key === void 0 || right_key === null) ?
right_key : [right_key];
this.key_type = key_type;
this.criteria = criteria;
};
/**
* @public
* @function
* @returns {Condition}
* @description
*/
Condition.prototype.clone = function clone() {
return new Condition(this.left_key, this.operator, this.right_key.concat(), this.key_type, this.criteria);
};
/**
* @public
* @function
* @returns {Conditons}
* @description
*/
Condition.prototype.not = function not() {
switch(this.operator) {
case "eq":
this.operator = "ne";
break;
case "ne":
this.operator = "eq";
break;
case "lt":
this.operator = "ge";
break;
case "le":
this.operator = "gt";
break;
case "gt":
this.operator = "le";
break;
case "ge":
this.operator = "lt";
break;
case "in":
this.operator = "not_in";
break;
case "not_in":
this.operator = "in";
break;
case "between":
this.operator = "not_between";
break;
case "not_between":
this.operator = "between";
break;
case "match":
this.operator = "not_match";
break;
case "not_match":
this.operator = "match";
break;
}
return this;
};
/**
* @public
* @function
* @returns Array<Condition>
*/
Condition.prototype.normalize = function normalize() {
var ret = [],
i = 0, l = 0;
if(this.key_type === "value") {
switch(this.operator) {
case "in":
for(i = 0, l = this.right_key.length; i < l; i = i + 1) {
ret[ret.length] = new Condition(
this.left_key, "eq", [this.right_key[i]], this.key_type, null)
;
}
break;
case "not_in":
for(i = 0, l = this.right_key.length; i < l; i = i + 1) {
ret[ret.length] = new Condition(
this.left_key, "ne", [this.right_key[i]], this.key_type, null
);
}
break;
case "between":
ret[ret.length] = new Condition(
this.left_key, "ge", [this.right_key[0]], this.key_type, null
);
ret[ret.length] = new Condition(
this.left_key, "le", [this.right_key[1]], this.key_type, null
);
break;
case "not_between":
ret[ret.length] = new Condition(
this.left_key, "lt", [this.right_key[0]], this.key_type, null
);
ret[ret.length] = new Condition(
this.left_key, "gt", [this.right_key[1]], this.key_type, null
);
break;
default:
ret[ret.length] = this.clone();
break;
}
} else {
ret[ret.length] = this.clone();
}
return ret;
};
/**
* @public
* @function
* @param {Condition} cond -
* @returns {Number}
* 0 - equal
* 1 - greater
* -1 - less
*/
Condition.prototype.compareTo = function compareTo(cond) {
if(this.criteria && !cond.criteria) {
return 1;
} else if(!this.criteria && cond.criteria) {
return -1;
} else if(this.criteria && cond.criteria) {
return this.criteria.compareTo(cond.criteria);
} else if(this.left_key > cond.left_key) {
return 1;
} else if(this.left_key < cond.left_key) {
return -1;
} else if(this.operator > cond.operator) {
return 1;
} else if(this.operator < cond.operator) {
return -1;
} else if(this.key_type > cond.key_type) {
return 1;
} else if(this.key_type < cond.key_type) {
return -1;
} else {
for(var i = 0, l = this.right_key.length; i < l; i = i + 1) {
if(this.right_key[i] > cond.right_key[i]) {
return 1;
} else if(this.right_key[i] < cond.right_key[i]) {
return -1;
}
}
return 0;
}
};
cxt.Condition = Condition;
})(this);
},{}],9:[function(require,module,exports){
/* evaluation.js */
(function (cxt){
"use strict";
var Condition = require('./Condition.js').Condition;
/**
* @public
* @function
* @param {String} type -
* @param {String} left_key -
* @param {Kriteria} criteria -
* @returns {Object<[eq|ne|lt|le|gt|ge|in|not_in].[key|value]>|between}
* @description
*/
var evaluation = function evaluation(type, left_key, criteria) {
return {
eq: {
key: function(value) {
_setToCriteria(criteria, type, "eq", left_key, "key", [value]);
return criteria;
},
value: function(value) {
_setToCriteria(criteria, type, "eq", left_key, "value", [value]);
return criteria;
}
},
ne: {
key: function(value) {
_setToCriteria(criteria, type, "ne", left_key, "key", [value]);
return criteria;
},
value: function(value) {
_setToCriteria(criteria, type, "ne", left_key, "value", [value]);
return criteria;
}
},
lt: {
key: function(value) {
_setToCriteria(criteria, type, "lt", left_key, "key", [value]);
return criteria;
},
value: function(value) {
_setToCriteria(criteria, type, "lt", left_key, "value", [value]);
return criteria;
}
},
le: {
key: function(value) {
_setToCriteria(criteria, type, "le", left_key, "key", [value]);
return criteria;
},
value: function(value) {
_setToCriteria(criteria, type, "le", left_key, "value", [value]);
return criteria;
}
},
gt: {
key: function(value) {
_setToCriteria(criteria, type, "gt", left_key, "key", [value]);
return criteria;
},
value: function(value) {
_setToCriteria(criteria, type, "gt", left_key, "value", [value]);
return criteria;
}
},
ge: {
key: function(value) {
_setToCriteria(criteria, type, "ge", left_key, "key", [value]);
return criteria;
},
value: function(value) {
_setToCriteria(criteria, type, "ge", left_key, "value", [value]);
return criteria;
}
},
in: {
key: function() {
_setToCriteria(criteria, type, "in", left_key, "key", [arguments[0]]);
return criteria;
},
value: function() {
_setToCriteria(
criteria,
type,
"in",
left_key,
"value",
Array.isArray(arguments[0]) ? arguments[0] : [].slice.apply(arguments)
);
return criteria;
}
},
not_in: {
key: function() {
_setToCriteria(criteria, type, "not_in", left_key, "key", [arguments[0]]);
return criteria;
},
value: function() {
_setToCriteria(
criteria,
type,
"not_in",
left_key,
"value",
Array.isArray(arguments[0]) ? arguments[0] : [].slice.apply(arguments)
);
return criteria;
}
},
between: function(value1, value2) {
_setToCriteria(criteria, type, "between", left_key, "value", [value1, value2]);
return criteria;
},
not_between: function(value1, value2) {
_setToCriteria(criteria, type, "not_between", left_key, "value", [value1, value2]);
return criteria;
},
match: function(value) {
var _value = value instanceof RegExp ? value :
value === null ? null :
value === void 0 ? void 0 :
value === "" ? "" : new RegExp(value);
_setToCriteria(criteria, type, "match", left_key, "value", [_value]);
return criteria;
},
not_match: function(value) {
var _value = value instanceof RegExp ? value :
value === null ? null :
value === void 0 ? void 0 :
value === "" ? "" : new RegExp(value);
_setToCriteria(criteria, type, "not_match", left_key, "value", [_value]);
return criteria;
}
};
};
/**
* @private
* @function
* @param {Kriteria} criteria -
* @param {String} type -
* @param {String} operator -
* @param {String} key_name -
* @param {Array<String>} values -
* @returns {void}
* @description
*/
var _setToCriteria = function _setToCriteria(criteria, type, operator, key_name, key_type, values) {
if(type.toLowerCase() === "and") {
criteria.addAnd(new Condition(key_name, operator, values, key_type, null));
} else if(type.toLowerCase() === "or") {
criteria.addOr(new Condition(key_name, operator, values, key_type, null));
} else {
throw new Error(
"invalid type: " + type +
"(at key_name:" + key_name + ", key_type: " + key_type + ", operator:" + operator + ")"
);
}
};
cxt.evaluation = evaluation;
})(this);
},{"./Condition.js":8}],10:[function(require,module,exports){
/* getProperty.js */
(function (cxt) {
'use strict';
var getProperty = function getProperty(obj, key) {
var keys = key.split('.'),
ret = obj;
for(var i = 0, l = keys.length; i < l; i += 1) {
if(
typeof ret === "string" ||
ret instanceof String ||
typeof ret === "number" ||
ret instanceof Number
) {
return void 0;
} else if(keys[i] in ret) {
ret = ret[keys[i]];
} else {
return void 0;
}
}
return ret;
};
cxt.getProperty = getProperty;
})(this);
},{}],11:[function(require,module,exports){
/* keys_reference.js */
(function(global, cxt) {
"use strict";
var KeysReferenceInstance = function KeysReferenceInstance(target) {
this._target = target;
this._q = "'";
this._keys = [];
};
KeysReferenceInstance.prototype.toString = function toString() {
var ret = this._target,
keys = this._keys,
q = this._q;
for(var i = 0, l = keys.length; i < l; i = i + 1) {
ret = ret + "[" + q + keys[i] + q + "]";
}
return ret;
};
KeysReferenceInstance.prototype.setQuote = function setQuote(q) {
if(isString(q)) {
this._q = q;
}
};
KeysReferenceInstance.prototype.add = function add(key) {
this._keys[this._keys.length] = key;
};
var keysReference = function keysReference(obj, keys, opt) {
var ins = new KeysReferenceInstance(obj);
if(opt && isString(opt.q)) {
ins.setQuote(opt.q);
}
if(Array.isArray(keys)) {
for(var i = 0, l = keys.length; i < l; i = i + 1) {
ins.add(keys[i]);
}
} else {
ins.add(keys);
}
return ins;
};
var isString = function isString(obj) {
return typeof obj === "string" || obj instanceof String;
};
//global.keysReference = keysReference;
cxt.keysReference = keysReference;
}((0, eval)("this"), this));
},{}],12:[function(require,module,exports){
/* matchPrefix.js */
(function(cxt) {
"use strict";
/**
* @public
* @function
* @param {String} str -
* @param {String[]} prefixes -
* @returns {Boolean}
*/
var matchPrefix = function matchPrefix(str, prefixes) {
if(prefixes.length === 0) {
return true;
}
for(var i = 0, l = prefixes.length; i < l; i = i + 1) {
if(str.indexOf(prefixes[i] + ".") === 0) {
return true;
}
}
return false;
};
cxt.matchPrefix = matchPrefix;
}(this));
},{}]},{},[1]);
|
/**
_ __ __ __ __ ____ _ ____ _____ __ ______ __ __
| | \/ | \/ |/ () \ | |__| ===|_ _| \ \/ / () | | |
|_|_|\/|_|_|\/|_/__/\__\ |____|____| |_| |__|\____/\___/
**/
var returned, mocks;
var ImmaLetYou = function(opts) {
this.baseUrl = opts.baseUrl || '';
this.defaultMock = opts.defaultMock || {};
};
ImmaLetYou.prototype.finish = function(path) {
mocks = {};
this.path = path;
return this;
};
ImmaLetYou.prototype.ofAllTime = function() {
var path = this.baseUrl + this.path;
require(path);
var name = require.resolve(path);
delete require.cache[name];
return returned;
};
ImmaLetYou.prototype.but = function(path, mock) {
mocks[path] = mock;
return this;
};
var define = function(callback) {
var mockRequire = function(path) {
return mocks[path] || sinon.stub();
};
returned = callback(mockRequire);
};
global.define = define;
module.exports = ImmaLetYou; |
import Vue from 'vue'
import Vuex from 'vuex'
import form from './modules/form'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
form
}
})
|
const serverFile = `${__dirname}'/app/server.js`;
import(serverFile);
|
'use strict';
const internals = {};
internals.secret = process.env.JWT_SECRET || 'SecretPassword123';
internals.validate = function (decoded, request, callback) {
// check if the user is valid, expiration date, etc
if (decoded.id === 1) {
return callback(null, true);
}
// invalid user
return callback(null, false);
};
module.exports = {
secret: internals.secret,
validate: internals.validate
};
|
"use strict";
const NumberUtil = require("../number-util.js");
const parseAddress = require("../parse-addr.js");
const jquery_plugin_class = require("./jquery_plugin_class");
jquery_plugin_class("Z80AddressSpecifier");
/**
* Z80 address specification controll panel(jquery plugin)
* @constructor
*
* @param {HTMLElement} element
* The DOM element to create widget.
*
* @param {object|undefined} opt
* An option for this widget.
*/
function Z80AddressSpecifier(element, opt) {
this._element = element;
this._opt = {};
if(opt) {
this.create(opt);
}
}
window.Z80AddressSpecifier = Z80AddressSpecifier;
module.exports = Z80AddressSpecifier;
/**
* Create this widget.
*
* @param {object|undefined} opt
* An option for this widget.
*
* @return {undefined}
*/
Z80AddressSpecifier.prototype.create = function(opt) {
let $root = $(this._element).css("width", "550px");
const IDC = "z80-addr-spec";
if($root.hasClass(IDC)) {
return;
}
$root.addClass(IDC);
opt = opt || {};
Object.keys(this._opt).forEach(key=>{
if(key in opt) {
this._opt[key] = opt[key];
}
});
const getReg = regName => {
return new Promise( (resolve, reject) => {
try {
$root.trigger("queryregister", [ regName, value => {
resolve(value);
}]);
} catch(err) {
reject(err);
}
});
};
[
{"H":"B","L": "C"},
{"H":"D","L": "E"},
{"H":"H","L": "L"},
"PC", "SP", "IX", "IY"
].forEach(regs => {
var pair = ((typeof(regs) === "string") ? false : true);
var name16 = (pair ? regs.H + regs.L : regs);
var getRegValue = (pair ?
(regs => {
let value = 0;
return getReg(regs.H).then(value_H => {
value = value_H * 256;
return getReg(regs.L);
}).then( value_L => {
return value + value_L;
});
}) : (regs => { return getReg(regs); }));
$root
.append($("<button/>")
.attr("id", "btnShowMem" + name16)
.attr("type", "button").css("width", "50px").html(name16)
.click(() => {
getRegValue(regs).then(value => {
$("#txtShowMemAddr").val( NumberUtil.HEX(value, 4) + "H" );
$root.trigger("notifyaddress", value);
}).catch(err=> {
console.error(err.stack);
});
}));
});
$root.append($("<input/>")
.attr("id", "txtShowMemAddr").attr("type", "text")
.attr("value", "0000h").css("width", "80px")
.attr("title",
"16進数(最後にhまたはH)の他、プログラム中のラベルも使えます。"
+ "10進数、8進数(0から始まる数字)もOK"))
.append($("<button/>")
.attr("id", "btnShowMemAddr")
.attr("type", "button").css("width", "80px").html("表示更新")
.click(() => {
var addrToken = $("#txtShowMemAddr").val();
var addr = parseAddress.parseAddress(addrToken);
if(addr != null) {
$root.trigger("notifyaddress", addr);
}
}));
};
|
/*! tether-drop 1.2.2 */
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(["tether"], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('tether'));
} else {
root.Drop = factory(root.Tether);
}
}(this, function(Tether) {
/* global Tether */
'use strict';
var _bind = Function.prototype.bind;
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
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(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _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 { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; 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 _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) subClass.__proto__ = superClass; }
var _Tether$Utils = Tether.Utils;
var extend = _Tether$Utils.extend;
var addClass = _Tether$Utils.addClass;
var removeClass = _Tether$Utils.removeClass;
var hasClass = _Tether$Utils.hasClass;
var Evented = _Tether$Utils.Evented;
function sortAttach(str) {
var _str$split = str.split(' ');
var _str$split2 = _slicedToArray(_str$split, 2);
var first = _str$split2[0];
var second = _str$split2[1];
if (['left', 'right'].indexOf(first) >= 0) {
var _ref = [second, first];
first = _ref[0];
second = _ref[1];
}
return [first, second].join(' ');
}
function removeFromArray(arr, item) {
var index = undefined;
var results = [];
while ((index = arr.indexOf(item)) !== -1) {
results.push(arr.splice(index, 1));
}
return results;
}
var clickEvents = ['click'];
if ('ontouchstart' in document.documentElement) {
clickEvents.push('touchstart');
}
var transitionEndEvents = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'otransitionend',
'transition': 'transitionend'
};
var transitionEndEvent = '';
for (var _name in transitionEndEvents) {
if (({}).hasOwnProperty.call(transitionEndEvents, _name)) {
var tempEl = document.createElement('p');
if (typeof tempEl.style[_name] !== 'undefined') {
transitionEndEvent = transitionEndEvents[_name];
}
}
}
var MIRROR_ATTACH = {
left: 'right',
right: 'left',
top: 'bottom',
bottom: 'top',
middle: 'middle',
center: 'center'
};
var allDrops = {};
// Drop can be included in external libraries. Calling createContext gives you a fresh
// copy of drop which won't interact with other copies on the page (beyond calling the document events).
function createContext() {
var options = arguments[0] === undefined ? {} : arguments[0];
var drop = function drop() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new (_bind.apply(DropInstance, [null].concat(args)))();
};
extend(drop, {
createContext: createContext,
drops: [],
defaults: {}
});
var defaultOptions = {
classPrefix: 'drop',
defaults: {
position: 'bottom left',
openOn: 'click',
beforeClose: null,
constrainToScrollParent: true,
constrainToWindow: true,
classes: '',
remove: false,
tetherOptions: {}
}
};
extend(drop, defaultOptions, options);
extend(drop.defaults, defaultOptions.defaults, options.defaults);
if (typeof allDrops[drop.classPrefix] === 'undefined') {
allDrops[drop.classPrefix] = [];
}
drop.updateBodyClasses = function () {
// There is only one body, so despite the context concept, we still iterate through all
// drops which share our classPrefix.
var anyOpen = false;
var drops = allDrops[drop.classPrefix];
var len = drops.length;
for (var i = 0; i < len; ++i) {
if (drops[i].isOpened()) {
anyOpen = true;
break;
}
}
if (anyOpen) {
addClass(document.body, drop.classPrefix + '-open');
} else {
removeClass(document.body, drop.classPrefix + '-open');
}
};
var DropInstance = (function (_Evented) {
function DropInstance(opts) {
_classCallCheck(this, DropInstance);
_get(Object.getPrototypeOf(DropInstance.prototype), 'constructor', this).call(this);
this.options = extend({}, drop.defaults, opts);
this.target = this.options.target;
if (typeof this.target === 'undefined') {
throw new Error('Drop Error: You must provide a target.');
}
if (this.options.classes && this.options.addTargetClasses !== false) {
addClass(this.target, this.options.classes);
}
drop.drops.push(this);
allDrops[drop.classPrefix].push(this);
this._boundEvents = [];
this.bindMethods();
this.setupElements();
this.setupEvents();
this.setupTether();
}
_inherits(DropInstance, _Evented);
_createClass(DropInstance, [{
key: '_on',
value: function _on(element, event, handler) {
this._boundEvents.push({ element: element, event: event, handler: handler });
element.addEventListener(event, handler);
}
}, {
key: 'bindMethods',
value: function bindMethods() {
this.transitionEndHandler = this._transitionEndHandler.bind(this);
}
}, {
key: 'setupElements',
value: function setupElements() {
var _this = this;
this.drop = document.createElement('div');
addClass(this.drop, drop.classPrefix);
if (this.options.classes) {
addClass(this.drop, this.options.classes);
}
this.content = document.createElement('div');
addClass(this.content, drop.classPrefix + '-content');
if (typeof this.options.content === 'function') {
var generateAndSetContent = function generateAndSetContent() {
// content function might return a string or an element
var contentElementOrHTML = _this.options.content.call(_this, _this);
if (typeof contentElementOrHTML === 'string') {
_this.content.innerHTML = contentElementOrHTML;
} else if (typeof contentElementOrHTML === 'object') {
_this.content.innerHTML = '';
_this.content.appendChild(contentElementOrHTML);
} else {
throw new Error('Drop Error: Content function should return a string or HTMLElement.');
}
};
generateAndSetContent();
this.on('open', generateAndSetContent.bind(this));
} else if (typeof this.options.content === 'object') {
this.content.appendChild(this.options.content);
} else {
this.content.innerHTML = this.options.content;
}
this.drop.appendChild(this.content);
}
}, {
key: 'setupTether',
value: function setupTether() {
// Tether expects two attachment points, one in the target element, one in the
// drop. We use a single one, and use the order as well, to allow us to put
// the drop on either side of any of the four corners. This magic converts between
// the two:
var dropAttach = this.options.position.split(' ');
dropAttach[0] = MIRROR_ATTACH[dropAttach[0]];
dropAttach = dropAttach.join(' ');
var constraints = [];
if (this.options.constrainToScrollParent) {
constraints.push({
to: 'scrollParent',
pin: 'top, bottom',
attachment: 'together none'
});
} else {
// To get 'out of bounds' classes
constraints.push({
to: 'scrollParent'
});
}
if (this.options.constrainToWindow !== false) {
constraints.push({
to: 'window',
attachment: 'together'
});
} else {
// To get 'out of bounds' classes
constraints.push({
to: 'window'
});
}
var opts = {
element: this.drop,
target: this.target,
attachment: sortAttach(dropAttach),
targetAttachment: sortAttach(this.options.position),
classPrefix: drop.classPrefix,
offset: '0 0',
targetOffset: '0 0',
enabled: false,
constraints: constraints,
addTargetClasses: this.options.addTargetClasses
};
if (this.options.tetherOptions !== false) {
this.tether = new Tether(extend({}, opts, this.options.tetherOptions));
}
}
}, {
key: 'setupEvents',
value: function setupEvents() {
var _this2 = this;
if (!this.options.openOn) {
return;
}
if (this.options.openOn === 'always') {
setTimeout(this.open.bind(this));
return;
}
var events = this.options.openOn.split(' ');
if (events.indexOf('click') >= 0) {
var openHandler = function openHandler(event) {
_this2.toggle(event);
event.preventDefault();
};
var closeHandler = function closeHandler(event) {
if (!_this2.isOpened()) {
return;
}
// Clicking inside dropdown
if (event.target === _this2.drop || _this2.drop.contains(event.target)) {
return;
}
// Clicking target
if (event.target === _this2.target || _this2.target.contains(event.target)) {
return;
}
_this2.close(event);
};
for (var i = 0; i < clickEvents.length; ++i) {
var clickEvent = clickEvents[i];
this._on(this.target, clickEvent, openHandler);
this._on(document, clickEvent, closeHandler);
}
}
if (events.indexOf('hover') >= 0) {
(function () {
var onUs = false;
var over = function over(event) {
onUs = true;
_this2.open(event);
};
var outTimeout = null;
var out = function out(event) {
onUs = false;
if (typeof outTimeout !== 'undefined') {
clearTimeout(outTimeout);
}
outTimeout = setTimeout(function () {
if (!onUs) {
_this2.close(event);
}
outTimeout = null;
}, 50);
};
_this2._on(_this2.target, 'mouseover', over);
_this2._on(_this2.drop, 'mouseover', over);
_this2._on(_this2.target, 'mouseout', out);
_this2._on(_this2.drop, 'mouseout', out);
})();
}
}
}, {
key: 'isOpened',
value: function isOpened() {
if (this.drop) {
return hasClass(this.drop, drop.classPrefix + '-open');
}
}
}, {
key: 'toggle',
value: function toggle(event) {
if (this.isOpened()) {
this.close(event);
} else {
this.open(event);
}
}
}, {
key: 'open',
value: function open(event) {
var _this3 = this;
if (this.isOpened()) {
return;
}
if (!this.drop.parentNode) {
document.body.appendChild(this.drop);
}
if (typeof this.tether !== 'undefined') {
this.tether.enable();
}
addClass(this.drop, drop.classPrefix + '-open');
addClass(this.drop, drop.classPrefix + '-open-transitionend');
setTimeout(function () {
if (_this3.drop) {
addClass(_this3.drop, drop.classPrefix + '-after-open');
}
});
if (typeof this.tether !== 'undefined') {
this.tether.position();
}
this.trigger('open');
drop.updateBodyClasses();
}
}, {
key: '_transitionEndHandler',
value: function _transitionEndHandler(e) {
if (e.target !== e.currentTarget) {
return;
}
if (!hasClass(this.drop, drop.classPrefix + '-open')) {
removeClass(this.drop, drop.classPrefix + '-open-transitionend');
}
this.drop.removeEventListener(transitionEndEvent, this.transitionEndHandler);
}
}, {
key: 'beforeCloseHandler',
value: function beforeCloseHandler(event) {
var shouldClose = true;
if (!this.isClosing && typeof this.options.beforeClose === 'function') {
this.isClosing = true;
shouldClose = this.options.beforeClose(event, this) !== false;
}
this.isClosing = false;
return shouldClose;
}
}, {
key: 'close',
value: function close(event) {
if (!this.isOpened()) {
return;
}
if (!this.beforeCloseHandler(event)) {
return;
}
removeClass(this.drop, drop.classPrefix + '-open');
removeClass(this.drop, drop.classPrefix + '-after-open');
this.drop.addEventListener(transitionEndEvent, this.transitionEndHandler);
this.trigger('close');
if (typeof this.tether !== 'undefined') {
this.tether.disable();
}
drop.updateBodyClasses();
if (this.options.remove) {
this.remove(event);
}
}
}, {
key: 'remove',
value: function remove(event) {
this.close(event);
if (this.drop.parentNode) {
this.drop.parentNode.removeChild(this.drop);
}
}
}, {
key: 'position',
value: function position() {
if (this.isOpened() && typeof this.tether !== 'undefined') {
this.tether.position();
}
}
}, {
key: 'destroy',
value: function destroy() {
this.remove();
if (typeof this.tether !== 'undefined') {
this.tether.destroy();
}
for (var i = 0; i < this._boundEvents.length; ++i) {
var _boundEvents$i = this._boundEvents[i];
var element = _boundEvents$i.element;
var _event = _boundEvents$i.event;
var handler = _boundEvents$i.handler;
element.removeEventListener(_event, handler);
}
this._boundEvents = [];
this.tether = null;
this.drop = null;
this.content = null;
this.target = null;
removeFromArray(allDrops[drop.classPrefix], this);
removeFromArray(drop.drops, this);
}
}]);
return DropInstance;
})(Evented);
return drop;
}
var Drop = createContext();
document.addEventListener('DOMContentLoaded', function () {
Drop.updateBodyClasses();
});
return Drop;
})); |
const browser = typeof window !== 'undefined';
const qs = require('querystring');
const Package = require('../package.json');
const transport = browser ? require('./browser') : require('./node');
/**
* Snekfetch
* @extends Stream.Readable
* @extends Promise
*/
class Snekfetch extends (transport.extension || Object) {
/**
* @typedef {object} snekfetchOptions
* @memberof Snekfetch
* @property {object} [headers] Headers to initialize the request with
* @property {object|string|Buffer} [data] Data to initialize the request with
* @property {string|Object} [query] Query to intialize the request with
* @property {string} [formData] Form data to initialize the request with
* @property {boolean} [followRedirects = false] If the request should follow redirects
* @property {number} [version = 1] The http version to use [1 or 2]
* @property {external:Agent} [agent] Whether to use an http agent
*/
/**
* Create a request.
* Usually you'll want to do `Snekfetch#method(url [, options])` instead of
* `new Snekfetch(method, url [, options])`
* @param {string} method HTTP method
* @param {string} url URL
* @param {Snekfetch.snekfetchOptions} opts Options
*/
constructor(method, url, opts = { headers: null, data: null, formData: null, query: null, version: 1 }) {
super();
this.options = opts;
this.request = transport.buildRequest.call(this, method, url, opts);
if (opts.query) this.query(opts.query);
if (opts.data) this.send(opts.data);
if (opts.formData) this._formData = opts.formData;
}
/**
* Add a query param to the request
* @param {string|Object} name Name of query param or object to add to query
* @param {string} [value] If name is a string value, this will be the value of the query param
* @returns {Snekfetch} This request
*/
query(name, value) {
if (this.response) throw new Error('Cannot modify query after being sent!');
if (!this.request.query) this.request.query = browser ? new URLSearchParams() : {};
if (name !== null && typeof name === 'object') {
for (const [k, v] of Object.entries(name)) this.query(k, v);
} else if (browser) {
this.request.query.set(name, value);
} else {
this.request.query[name] = value;
}
return this;
}
/**
* Add a header to the request
* @param {string|Object} name Name of query param or object to add to headers
* @param {string} [value] If name is a string value, this will be the value of the header
* @returns {Snekfetch} This request
*/
set(name, value) {
if (this.response) throw new Error('Cannot modify headers after being sent!');
if (name !== null && typeof name === 'object') {
for (const key of Object.keys(name)) this.set(key, name[key]);
} else {
this.request.setHeader(name, value);
}
return this;
}
/**
* Attach a form data object
* @param {string} name Name of the form attachment
* @param {string|Object|Buffer} data Data for the attachment
* @param {string} [filename] Optional filename if form attachment name needs to be overridden
* @returns {Snekfetch} This request
*/
attach(name, data, filename) {
if (this.response) throw new Error('Cannot modify data after being sent!');
const form = this._getFormData();
this.set('Content-Type', `multipart/form-data; boundary=${form.boundary}`);
form.append(name, data, filename);
this.data = form;
return this;
}
/**
* Send data with the request
* @param {string|Buffer|Object} data Data to send
* @returns {Snekfetch} This request
*/
send(data) {
if (this.response) throw new Error('Cannot modify data after being sent!');
if (transport.shouldSendRaw(data)) {
this.data = data;
} else if (data !== null && typeof data === 'object') {
const header = this._getRequestHeader('content-type');
let serialize;
if (header) {
if (header.includes('json')) serialize = JSON.stringify;
else if (header.includes('urlencoded')) serialize = qs.stringify;
} else {
this.set('Content-Type', 'application/json');
serialize = JSON.stringify;
}
this.data = serialize(data);
} else {
this.data = data;
}
return this;
}
then(resolver, rejector) {
return transport.finalizeRequest.call(this, {
data: this._formData ?
this._formData.end ? this._formData.end() : this._formData :
this.data || null,
})
.then(({ response, raw, redirect, headers }) => {
if (redirect) {
let method = this.request.method;
if ([301, 302].includes(response.statusCode)) {
if (method !== 'HEAD') method = 'GET';
this.data = null;
} else if (response.statusCode === 303) {
method = 'GET';
}
const redirectHeaders = {};
if (this.request._headerNames) {
for (const name of Object.keys(this.request._headerNames)) {
if (name.toLowerCase() === 'host') continue;
redirectHeaders[this.request._headerNames[name]] = this.request._headers[name];
}
} else {
const hds = this.request._headers || this.request.headers;
for (const name of Object.keys(hds)) {
if (name.toLowerCase() === 'host') continue;
const header = hds[name];
redirectHeaders[header.name] = header.value;
}
}
return new Snekfetch(method, redirect, {
data: this.data,
formData: this._formData,
headers: redirectHeaders,
agent: this.options._req.agent,
});
}
const statusCode = response.statusCode || response.status;
/**
* @typedef {Object} SnekfetchResponse
* @memberof Snekfetch
* @prop {HTTP.Request} request
* @prop {?string|object|Buffer} body Processed response body
* @prop {string} text Raw response body
* @prop {boolean} ok If the response code is >= 200 and < 300
* @prop {number} status HTTP status code
* @prop {string} statusText Human readable HTTP status
*/
const res = {
request: this.request,
get body() {
delete res.body;
const type = this.headers['content-type'];
if (type && type.includes('application/json')) {
try {
res.body = JSON.parse(res.text);
} catch (err) {
res.body = res.text;
}
} else if (type && type.includes('application/x-www-form-urlencoded')) {
res.body = qs.parse(res.text);
} else {
res.body = raw;
}
return res.body;
},
text: raw.toString(),
ok: statusCode >= 200 && statusCode < 400,
headers: headers || response.headers,
status: statusCode,
statusText: response.statusText || transport.STATUS_CODES[response.statusCode],
};
if (res.ok) {
return res;
} else {
const err = new Error(`${res.status} ${res.statusText}`.trim());
Object.assign(err, res);
return Promise.reject(err);
}
})
.then(resolver, rejector);
}
catch(rejector) {
return this.then(null, rejector);
}
/**
* End the request
* @param {Function} [cb] Optional callback to handle the response
* @returns {Promise} This request
*/
end(cb) {
return this.then(
(res) => cb ? cb(null, res) : res,
(err) => cb ? cb(err, err.status ? err : null) : err
);
}
_read() {
this.resume();
if (this.response) return;
this.catch((err) => this.emit('error', err));
}
_shouldUnzip(res) {
if (res.statusCode === 204 || res.statusCode === 304) return false;
if (res.headers['content-length'] === '0') return false;
return /^\s*(?:deflate|gzip)\s*$/.test(res.headers['content-encoding']);
}
_shouldRedirect(res) {
return this.options.followRedirects !== false && [301, 302, 303, 307, 308].includes(res.statusCode);
}
_getFormData() {
if (!this._formData) this._formData = new transport.FormData();
return this._formData;
}
_addFinalHeaders() {
if (!this.request) return;
if (!this._getRequestHeader('user-agent')) {
this.set('User-Agent', `snekfetch/${Snekfetch.version} (${Package.repository.url.replace(/\.?git/, '')})`);
}
if (this.request.method !== 'HEAD') this.set('Accept-Encoding', 'gzip, deflate');
if (this.data && this.data.end) this.set('Content-Length', this.data.length);
}
get response() {
return this.request ? this.request.res || this.request._response || null : null;
}
_getRequestHeader(header) {
// https://github.com/jhiesey/stream-http/pull/77
try {
return this.request.getHeader(header);
} catch (err) {
return null;
}
}
}
Snekfetch.version = Package.version;
/**
* @dynamic this.METHODS
* @method Snekfetch.((THIS)lowerCase)
* @param {string} url The url to request
* @param {Snekfetch.snekfetchOptions} [opts] Options
* @returns {Snekfetch}
*/
Snekfetch.METHODS = transport.METHODS.concat('BREW').filter((m) => m !== 'M-SEARCH');
for (const method of Snekfetch.METHODS) {
Snekfetch[method.toLowerCase()] = (url, opts) => new Snekfetch(method, url, opts);
}
module.exports = Snekfetch;
/**
* @external Agent
* @see {@link https://nodejs.org/api/http.html#http_class_http_agent}
*/
|
'use strict';
function buildTemplate(data) {
return `
<div style="max-width:800px;position:relative;margin:20px auto;padding:15px;border:2px solid black;box-shadow:0 0 5px 2px lightgray;letter-spacing:1px;">
<div style="text-align:center;">
<h1 style="font-size:40px; font-size:40px; padding-bottom:5px; margin-top:15px; border-bottom:1px solid #cacaca;">Password Reset</h1>
<h2 style="font-size:28px">...follow the link to reset your password.</h2>
</div>
<h4 style="font-size="18px"></h4>
<div style="text-align:center;">
<b>The link will expire within 24 hours.</b>
</div>
<div style="text-align:center;margin:20px 0;">
<a style="padding: 6px 12px;font-size: 20px;line-height: 1.42857143;border-radius: 3px;background: #278ECA;color: white;text-decoration: none;" href="https://www.battle-comm.net/App/#/reset-password/${data.token}">Reset Password</a>
</div>
<div style="text-align:center; border-top:1px solid #cacaca; padding:20px 0 0;">
<img src="https://www.battle-comm.net/images/BC_Web_Logo.png">
</div>
</div>
`
}
module.exports = buildTemplate;
|
app.service("edhrecService", function($http, $q, analyticsService, config) {
var MAX_TOP_RECS = 12;
var MAX_CUTS = 15;
var API_REF = "kevin";
var DECK_RECOMMENDATIONS_URL = config.BACKEND_URL + "/rec";
var COMMANDER_RECOMMENDATIONS_URL = config.BACKEND_URL + "/cmdr";
var GENERATE_DECK_URL = config.BACKEND_URL + "/cmdrdeck";
var RANDOM_COMMANDER_URL = config.BACKEND_URL + "/randomcmdr";
var RECENT_DECKS_URL = config.BACKEND_URL + "/recent";
var searchTypes = {
COMMANDER: "commander",
SAMPLE_COMMANDER: "sample_commander",
RANDOM_COMMANDER: "random_commander",
SAMPLE_DECK: "sample_deck",
TAPPED_OUT: "tapped_out",
MTG_SALVATION: "mtg_salvation",
UNKNOWN: "unknown"
};
var cardTypes = {
CREATURE: "Creature",
LAND: "Land",
ARTIFACT: "Artifact",
ENCHANTMENT: "Enchantment",
INSTANT: "Instant",
SORCERY: "Sorcery",
PLANESWALKER: "Planeswalker"
};
this.getDeckRecommendations = function(deckUrl) {
var sampleDeck = deckUrl == config.SAMPLE_TAPPED_OUT_DECK_URL ||
deckUrl == config.SAMPLE_MTG_SALVATION_FORUM_URL;
var searchType = searchTypes.UNKNOWN;
if (sampleDeck) {
searchType = searchTypes.SAMPLE_DECK;
} else if (deckUrl.toLowerCase().indexOf("tappedout") > -1) {
searchType = searchTypes.TAPPED_OUT;
} else if (deckUrl.toLowerCase().indexOf("mtgsalvation") > -1) {
searchType = searchTypes.MTG_SALVATION;
}
var url = DECK_RECOMMENDATIONS_URL + "?to=" + deckUrl + "&ref=" + API_REF;
return this.getRecommendations_(deckUrl, searchType, url)
.then($.proxy(function(recommendations) {
return recommendations;
}, this), function(error) {
var message = "Error generating recommendations.";
if (error.status == 500 && searchType == searchTypes.TAPPED_OUT) {
message += " Please verify your deck isn't marked as private, " +
"your deck link looks like http://tappedout.net/mtg-decks/your-deck-name, " +
"and that the commander field is filled in on your deck.";
}
message += " Status code: " + error.status;
return $q.reject(message);
});
};
this.getCommanderRecommendations = function(commander) {
// If user has been redirected from clicking the "Random" button, then use
// the cached recommendations.
if (this.lastRandomResult_ && this.lastRandomResult_.commander == commander) {
var deferred = $q.defer();
deferred.resolve(this.parseRecommendationsResponse_(this.lastRandomResult_));
this.lastRandomResult_ = null;
return deferred.promise;
}
var searchType = commander == config.SAMPLE_COMMANDER ? searchTypes.SAMPLE_COMMANDER : searchTypes.COMMANDER;
var url = COMMANDER_RECOMMENDATIONS_URL + "?commander=" + commander;
return this.getRecommendations_(commander, searchType, url)
.then($.proxy(function(recommendations) {
return recommendations;
}, this), function(error) {
return $q.reject("Error generating recommendations. Please verify you typed " +
"in a valid commander or deck link. Status code: " + error.status);
});
};
this.getRecommendations_ = function(query, searchType, url) {
var start = (new Date()).getTime();
return $http.get(url).then($.proxy(function(result) {
var latency = (new Date()).getTime() - start;
analyticsService.recordSearchEvent(query, searchType, result.status, latency);
return this.parseRecommendationsResponse_(result.data);
}, this), function(error) {
var latency = (new Date()).getTime() - start;
analyticsService.recordSearchEvent(query, searchType, error.status, latency);
return $q.reject(error);
});
}
this.parseRecommendationsResponse_ = function(data) {
var recommendations = this.createCollection_();
recommendations.commander = data.commander; // Only returned on commander searches
recommendations.cards = [];
recommendations.top = [];
if (data.cuts) {
recommendations.cuts = data.cuts.slice(0, MAX_CUTS);
} else {
recommendations.cuts = [];
}
// API returns cstats in the stats field on commander searches
recommendations.stats = data.commander ? null : data.stats;
recommendations.kstats = data.kstats; // Only returned on deck searches
recommendations.cstats = data.commander ? data.stats : data.cstats;
for (var i = 0; i < data.recs.length; i++) {
var card = data.recs[i];
recommendations.cards.push({
name: card.card_info.name,
count: 1
});
var land = this.isType_(card, cardTypes.LAND);
if (recommendations.top.length < MAX_TOP_RECS && !land) {
recommendations.top.push(card);
} else {
this.addCard_(card, recommendations);
}
}
return recommendations;
}
this.generateDeck = function(commander) {
var url = GENERATE_DECK_URL + "?commander=" + commander;
var start = (new Date()).getTime();
return $http.get(url).then($.proxy(function(result) {
var latency = (new Date()).getTime() - start;
analyticsService.recordGenerateDeckEvent(result.status, latency);
return this.parseGenerateDeckResponse_(result.data);
}, this), function(error) {
var latency = (new Date()).getTime() - start;
analyticsService.recordGenerateDeckEvent(commander, error.status, latency);
return $q.reject("Error generating deck. Status code: " + error.status);
});
};
this.parseGenerateDeckResponse_ = function(data) {
var deck = this.createCollection_();
deck.commander = data.commander;
deck.stats = data.stats;
deck.basics = data.basics;
deck.cards = [{
name: data.commander,
count: 1
}];
for (var i = 0; i < data.cards.length; i++) {
var card = data.cards[i];
deck.cards.push({
name: card.card_info.name,
count: 1
});
this.addCard_(card, deck);
}
for (var i = 0; i < deck.basics.length; i++) {
deck.cards.push({
name: deck.basics[i][0],
count: deck.basics[i][1]
});
deck.lands.push({
card_info: {
name: deck.basics[i][0]
}
});
}
deck.cards.sort(this.cardsCompareFunction_);
return deck;
};
this.cardsCompareFunction_ = function(a, b) {
if (a.name > b.name) {
return 1;
}
if (a.name < b.name) {
return -1;
}
return 0;
};
this.createCollection_ = function() {
return {
creatures: [],
artifacts: [],
enchantments: [],
instants: [],
sorceries: [],
planeswalkers: [],
lands: []
};
}
this.addCard_ = function(card, collection) {
if (this.isType_(card, cardTypes.LAND)) {
collection.lands.push(card);
} else if (this.isType_(card, cardTypes.CREATURE)) {
collection.creatures.push(card);
} else if (this.isType_(card, cardTypes.ARTIFACT)) {
collection.artifacts.push(card);
} else if (this.isType_(card, cardTypes.ENCHANTMENT)) {
collection.enchantments.push(card);
} else if (this.isType_(card, cardTypes.INSTANT)) {
collection.instants.push(card);
} else if (this.isType_(card, cardTypes.SORCERY)) {
collection.sorceries.push(card);
} else if (this.isType_(card, cardTypes.PLANESWALKER)) {
collection.planeswalkers.push(card);
}
};
this.isType_ = function(card, type) {
if (card == null || card.card_info == null) {
return false;
}
return $.inArray(type, card.card_info.types) > -1;
};
this.getRandomCommander = function() {
var url = RANDOM_COMMANDER_URL;
var start = (new Date()).getTime();
return $http.get(url).then($.proxy(function(result) {
var latency = (new Date()).getTime() - start;
analyticsService.recordSearchEvent(
null, searchTypes.RANDOM_COMMANDER, result.status, latency);
this.lastRandomResult_ = result.data;
return result.data.commander;
}, this), function(error) {
var latency = (new Date()).getTime() - start;
analyticsService.recordSearchEvent(
null, searchTypes.RANDOM_COMMANDER, result.status, latency);
return $q.reject("Error generating random commander. Status code: " + error.status);
});
};
this.getRecentDecks = function(max) {
return $http.get(RECENT_DECKS_URL).then(function(result) {
var recentDecks = [];
for (var i = 0; i < max; i++) {
if (i >= result.data.length) {
break;
}
recentDecks.push(JSON.parse(result.data[i]));
}
return recentDecks;
}, function(error) {
return $q.reject(error);
});
}
});
|
'use strict';
/*
trucolor
Color Output
*/
var Output, SGRcomposer, _package, colorLevel, colorOptions, colorOptionsSelected, converter, ref, terminalFeatures;
_package = require('../package.json');
terminalFeatures = require('term-ng');
converter = require('color-convert');
SGRcomposer = require('sgr-composer');
colorOptionsSelected = _package.config.cli.selected;
colorOptions = _package.config.cli[colorOptionsSelected];
colorLevel = (ref = terminalFeatures.color.level) != null ? ref : 0;
Output = (function() {
function Output(color_, styles_, options_) {
var ref1, ref2, sgr, style;
if (options_ == null) {
options_ = {};
}
this.hasRGB = false;
if (color_ != null) {
styles_.color = (function() {
switch (false) {
case !/^[#][0-9a-f]{6}$/i.test(color_):
this.hasRGB = true;
return converter.hex.rgb(color_);
case !Array.isArray(color_):
this.hasRGB = true;
return color_;
case color_ !== 'reset' && color_ !== 'normal':
this.hasReset = true;
return color_;
default:
throw new Error("Unrecognised color: " + color_);
}
}).call(this);
}
if ((global.trucolor_CLI_type != null) && ((ref1 = global.trucolor_CLI_type) !== 'default' && ref1 !== colorOptionsSelected)) {
colorOptionsSelected = global.trucolor_CLI_type;
colorOptions = _package.config.cli[colorOptionsSelected];
}
this._buffer = new SGRcomposer((ref2 = options_.force) != null ? ref2 : colorLevel, styles_);
console.info(this.hasRGB ? (style = (style = this._buffer.style) ? (sgr = this._buffer.sgr(), " + " + sgr["in"] + style + sgr.out) : '', "Color:\tR:" + this._buffer.red + "\tG:" + this._buffer.green + "\tB:" + this._buffer.blue + "\t" + (this.toSwatch()) + style) : this.hasReset ? "Reset: " + this._buffer.color + " " + (this.toSwatch()) : (sgr = this._buffer.sgr(), "Style: " + sgr["in"] + this._buffer.style + sgr.out));
}
Output.prototype.valueOf = function() {
var style, styling;
if (global.trucolor_CLI_type != null) {
styling = ((function() {
var i, len, ref1, results;
ref1 = this._buffer.styleArray;
results = [];
for (i = 0, len = ref1.length; i < len; i++) {
style = ref1[i];
results.push(colorOptions[style]);
}
return results;
}).call(this)).join(' ');
if (styling.length) {
styling += ' ';
}
if (this.hasRGB) {
switch (colorOptions.color) {
case 'hex':
return "" + styling + this._buffer.hex;
default:
return this._buffer.red + " " + this._buffer.green + " " + this._buffer.blue;
}
} else if (this.hasReset) {
switch (this._buffer.color) {
case 'normal':
return colorOptions.normal;
default:
return colorOptions.reset;
}
} else {
return this._buffer.sgr()["in"];
}
} else if (this.hasRGB) {
return this._buffer.hex;
} else if (this.hasReset) {
return this._buffer.color;
} else {
return this._buffer.sgr()["in"];
}
};
Output.prototype.toString = function() {
if (this.hasRGB) {
return ("rgb(" + this._buffer.red + ", " + this._buffer.green + ", " + this._buffer.blue) + ')';
} else if (this.hasReset) {
return this._buffer.color;
} else {
return colorOptions.reset;
}
};
Output.prototype.toSwatch = function() {
var sgr;
sgr = this._buffer.sgr(['bold', 'italic', 'underline', 'invert']);
if (colorLevel > 0) {
return sgr["in"] + "\u2588\u2588" + sgr.out;
} else {
return '';
}
};
Output.prototype.toSGR = function() {
return this._buffer.sgr();
};
return Output;
})();
module.exports = Output;
|
'use strict'
const logger = require('winston')
// 멀티 프로세스로 구성 시 PROCESS_TYPE 으로 구분하여 해당 config file 로드
const type = process.env.PROCESS_TYPE
logger.info(`Starting '${type}' process`, { pid: process.pid })
if (type === 'web') {
require('./web')
} else if (type === 'web_backoffice') {
require('./web_backoffice')
} else if (type === 'web_mobile') {
require('./web_mobile')
} else {
throw new Error(`
${type} is an unsupported process type.
Use one of: 'web'!
`)
}
|
// @flow
import {ActionType} from '../../types' // eslint-disable-line no-unused-vars
import 'isomorphic-fetch'
import * as api from '../../app/api'
import * as types from './forecastHourlyActionTypes'
const getForecastHourly:ActionType = (query:number):ActionType => ({
type: types.GET_FORECAST_HOURLY,
payload: new Promise((resolve, reject) => {
fetch(api.forecast(query)).then(response => {
resolve(response.json())
})
})
})
const setForecastHourlyActiveReportType:ActionType = (type:string):ActionType => ({
type: types.SET_FORECAST_HOURLY_ACTIVE_REPORT_TYPE,
payload: type
})
export { getForecastHourly, setForecastHourlyActiveReportType }
|
/* jshint node: true */
var CoreObject = require('core-object');
var Promise = require('ember-cli/lib/ext/promise');
var fs = require('fs');
var crypto = require('crypto');
var execSync12 = require('child_process').execSync;
var execSync10 = require('sync-exec');
var _ = require('underscore');
var request = require('request');
module.exports = CoreObject.extend({
_plugin: null,
init: function(options) {
this._plugin = options.plugin;
this.context = options.context;
},
readConfig: function(key) {
return this._plugin.readConfig(key);
},
log: function(text) {
return this._plugin.log(text);
},
gitInfo: function() {
var sha, branch;
if (typeof execSync12 === 'function') {
// node 0.12.x+
sha = execSync12('git rev-parse HEAD').toString().trim();
branch = execSync12('git rev-parse --abbrev-ref HEAD').toString().trim();
} else {
// node 0.10.x
sha = execSync10('git rev-parse HEAD').stdout.trim();
branch = execSync10('git rev-parse --abbrev-ref HEAD').stdout.trim();
}
return {
sha: sha,
branch: branch
};
},
notify: function() {
var index = this.getIndexContent(),
git = this.gitInfo(),
signature = this.sign(index),
data = {
app_name: this.readConfig('app'),
branch: git.branch,
sha: git.sha,
signature: signature,
html: index
},
plugin = this;
// notify the backend
return new Promise(function(resolve, reject) {
var endpoint = plugin.readConfig('endpoint'),
febEndpoint = endpoint.match(/\/front_end_builds\/builds$/) ?
endpoint :
endpoint + '/front_end_builds/builds';
var requestOptions = _.extend({
method: 'POST',
uri: febEndpoint,
form: data
}, plugin.readConfig('requestOptions'));
plugin.log('Notifying ' + endpoint + '...');
request(requestOptions, function(error, response, body) {
if (error) {
plugin.log('Unable to reach endpoint ' + endpoint + ': ' + error.message, { color: 'red' });
plugin.log(body, { color: 'red' });
reject(error.message);
} else {
var code = response.statusCode;
if (code.toString().charAt(0) === '4') {
return reject('Rejected with code ' + code + '\n' + body);
}
plugin.log('Successfully deployed to front end builds server', { color: 'green' });
resolve(body);
}
});
});
},
sign: function(index) {
var algo = 'RSA-SHA256',
keyFile = this.readConfig('privateKey');
return crypto
.createSign(algo)
.update(index)
.sign(fs.readFileSync(keyFile), 'base64');
},
getIndexContent: function() {
var distDir = this.context.distDir,
index = distDir + '/index.html';
return fs.readFileSync(index).toString();
},
});
|
import React from 'react';
import PropTypes from '../../prop_types';
import { mixin } from '../../utils/decorators';
import InputBase from './input_base';
import {
CssClassMixin,
} from '../../mixins';
import InputMasked from './input_masked';
@mixin(
CssClassMixin,
)
export default class InputText extends InputBase {
static propTypes = {
...InputBase.propTypes,
type: PropTypes.string,
};
static defaultProps = {
...InputBase.defaultProps,
type: 'text',
themeClassKey: 'input.text',
};
static ommitedProps = [
'originalName', 'originalId', 'renderLabel', 'formStyle',
'clearTheme',
];
prepareProps() {
return _.omit(this.propsWithoutCSS(), InputText.ommitedProps);
}
render() {
const { children, ...props } = this.propsWithoutCSS(); // eslint-disable-line no-unused-vars
return (
<input
{...this.prepareProps()}
value={this.state.value}
placeholder={this.getPlaceholder()}
className={this.inputClassName()}
onChange={this.handleChange}
onFocus={this.handleFocus}
ref={ref => { this.input = ref; }}
/>
);
}
}
|
(function() {
'use strict';
//noinspection JSUnusedLocalSymbols
let $list = $('.appearance-list');
const { GUIDE, AppearancePage } = window;
let copyHash = !$.LocalStorage.get('leavehash'),
$toggler = $('#toggle-copy-hash'),
$togglerLabel;
window.copyHashToggler = function() {
if (!$toggler.length)
return;
$togglerLabel = $toggler.next();
$toggler.on('click', function() {
copyHash = $toggler.prop('checked');
if (!copyHash)
$.LocalStorage.set('leavehash', 1);
else $.LocalStorage.remove('leavehash');
});
$toggler.prop('checked', copyHash).triggerHandler('click');
$toggler.enable().parent().removeClass('disabled');
};
window.copyHashEnabled = function() {
return copyHash;
};
$('ul.colors').children('li').find('.valid-color').off('mousedown touchstart click').on('click', function(e) {
e.preventDefault();
let $this = $(this),
copy = $this.html().trim();
if (e.shiftKey){
let rgb = $.RGBAColor.parse(copy),
$cg = $this.closest('li'),
path = [
(
!AppearancePage
? $cg.parents('li').children().last().children('strong').text().trim()
: $content.children('h1').text()
),
$cg.children().first().html().replace(/(:\s+)?(<span.*)?$/, ''),
$this.next().find('.label').html(),
];
return $.Dialog.info(`RGB values for color ${copy}`, `<div class="align-center">${path.join(' › ')}<br><span style="font-size:1.2em">rgb(<code class="color-red">${rgb.red}</code>, <code class="color-green">${rgb.green}</code>, <code class="color-darkblue">${rgb.blue}</code>)</span></div>`);
}
if (!copyHash) copy = copy.replace('#', '');
$.copy(copy, e);
}).filter(':not(.ctxmenu-bound)').ctxmenu(
[
{
text: `Copy HEX color code`, icon: 'clipboard', 'default': true, click: function() {
$(this).triggerHandler('click');
},
},
{
text: 'View RGB values', icon: 'brush', click: function() {
$(this).triggerHandler({
type: 'click',
shiftKey: true,
});
},
},
],
function($el) {
return `Color: ${$el.attr('title') || $el.next().children('.label').text()}`;
},
).on('mousedown', function(e) {
if (e.shiftKey)
e.preventDefault();
});
$('.get-swatch').off('click').on('click', getSwatch);
window.copyHashToggler();
function getSwatch(e) {
e.preventDefault();
let token = window.location.search.match(/token=[a-f\d-]+(&|$)/i);
if (token)
token = '?' + token[0];
else token = '';
//jshint -W040
let $li = $(this).closest('[id^=p]'),
appearanceID = $li.attr('id').substring(1),
ponyName = (
!AppearancePage
? $li.find('.appearance-name').first()
: $content.children('h1')
).text().trim(),
pressAi = navigator && navigator.userAgent && /Macintosh/i.test(navigator.userAgent)
? '<kbd>fn</kbd><kbd>\u2318</kbd><kbd>F12</kbd> for Big Sur, previous versions use <kbd>\u2318</kbd><kbd>F12</kbd>'
: '<kbd>Ctrl</kbd><kbd>F12</kbd>',
$instr = $.mk('div').html(
`<div class='hidden section ai'>
<h4>How to import swatches to Adobe Illustrator</h4>
<ul>
<li>Because Illustrator uses a proprietary format for swatch files, you must download a script <a href='/dist/Import%20Swatches%20from%20JSON.jsx?v=1.5' download='Import Swatches from JSON.jsx' class='btn typcn typcn-download'>by clicking here</a> to be able to import them from our site. Be sure to save it to an easy to find location because you'll need to browser for it every time you want to import colors.</li>
<li>Once you have the script, <a href="/cg/v/${appearanceID}s.json${token}" class="btn blue typcn typcn-download">click here</a> to download the <code>.json</code> file that you'll need to use for the import.</li>
<li>Now that you have the 2 files, open Illustrator, create/open a document, then go to <strong>File › Scripts › Other Script</strong> (or press ${pressAi}) then find the file with the <code>.jsx</code> extension (the one you first downloaded). A dialog will appear telling you what to do next.</li>
<li>Optional: If you'd like to make using the script faster, you can place it in the <code>…\\Adobe<wbr>\\Adobe Illustrator *<wbr>\\Presets<wbr>\\*<wbr>\\Scripts</code> folder, and after an Illustrator restart it'll be available as one of the options in the <strong>File › Scripts</strong> submenu.</li>
</ul>
<div class="responsive-embed">
<iframe src="https://www.youtube.com/embed/oobQZ2xiDB8" allowfullscreen async defer></iframe>
</div>
</div>
<div class='hidden section inkscape'>
<h4>How to import swatches to Inkscape</h4>
<p>Download <a href='/cg/v/${appearanceID}s.gpl${token}' class='btn blue typcn typcn-download'>this file</a> and place it in the <code>…\\Inkscape<wbr>\\<wbr>share<wbr>\\<wbr>palettes</code> folder. If you don't plan on using the other swatches, deleting them should make your newly imported swatch easier to find.</p>
<p>You will most likely have to restart Inkscape for the swatch to show up in the <em>Swatches</em> (<kbd>F6</kbd>) tool window's menu.</p>
<div class="responsive-embed">
<iframe src="https://www.youtube.com/embed/zmaJhbIKQqM" allowfullscreen async defer></iframe>
</div>
</div>`,
),
$appSelect = $.mk('select')
.attr('required', true)
.html('<option value="" selected style="display:none">Choose one</option><option value="inkscape">Inkscape</option><option value="ai">Adobe Illustrator</option>')
.on('change', function() {
let $sel = $(this),
val = $sel.val(),
$els = $sel.parent().next().children().addClass('hidden');
if (val)
$els.filter('.' + val).removeClass('hidden');
}),
$SwatchDlForm = $.mk('form').attr('id', 'swatch-save').append(
$.mk('label').attr('class', 'align-center').append(
'<span>Choose your drawing program:</span>',
$appSelect,
),
$instr,
);
$.Dialog.info(`Download swatch file for ${ponyName}`, $SwatchDlForm);
}
const $searchForm = $('#search-form');
$searchForm.on('reset', function(e) {
e.preventDefault();
let $this = $(this);
$this.find('input[name=q]').val('');
$this.trigger('submit');
});
const $searchInput = $searchForm.children('input');
const appearanceAutocompleteCache = new window.KeyValueCache();
if ($searchInput.length){
const focused = $searchInput.is(':focus');
$searchInput.autocomplete(
{
hint: false,
minLength: 1,
},
[
{
name: 'appearance',
debounce: 200,
source: (q, callback) => {
if (appearanceAutocompleteCache.has(q))
return callback(appearanceAutocompleteCache.get(q));
$.API.get(`/cg/appearances`, { q, guide: GUIDE }, data => {
callback(appearanceAutocompleteCache.set(q, data));
});
},
templates: {
header: () => `<div class="aa-header">
Highlight suggestions with <kbd><span class="typcn typcn-arrow-up"/></kbd>
<kbd><span class="typcn typcn-arrow-down"/></kbd>, then press <kbd>Enter</kbd> to accept.
Pressing <kbd>Enter</kbd> without highlighting a result will take you to the search results page.
</div>`,
suggestion: data => {
return $('<a>').attr('href', data.url).append(
`<img src="${data.image}" alt="search suggestion" class="ac-appearance-image">`,
$('<div class="ac-appearance-label" />').text(data.label),
).prop('outerHTML');
},
},
},
],
);
if (focused)
$searchInput.focus();
$searchInput.on('autocomplete:selected', function(event, suggestion, dataset, context) {
if (context && context.selectionMethod === 'click'){
return;
}
if (suggestion.url){
$searchForm.find(':input').prop('disabled', true);
window.location.href = suggestion.url;
}
});
}
})();
|
$(function() {
$('select[name=ccmMultilingualChooseLanguage]').change(function() {
$(this).parent().submit();
});
});
var asd = 22
var rr = qweqwe |
{
"no-static-navigation-found": "No static navigation found. Create page 'navigation' first.",
"click here and enter page title": "This page needs a title.",
"tags-description": "add tags as comma separated list",
"click here and enter new content...": "Get involved. Add something already...",
"home": "Home",
"all-pages": "All Pages",
"add-page": "Add Page",
"all-tags": "All Tags",
"version-history": "Version History",
"latest-pages": "Latest",
"recent-changes": "Changes",
"new-page": "New Page",
"move-this-page": "Move this page",
"delete-this-page": "Delete this page",
"search": "Search",
"sub-pages": "Child pages",
"attachments": "Attachments",
"drop-files-here": "Drop files",
"images": "Images",
"drop-images-and-other-media": "",
"versions": "Versions",
"show-versions": "Show versions",
"last-modified-by": "last modified by",
"changes": "Changes",
"tasks": "Actions",
"tags": "Tags",
"Versions": "Versions",
"title": "Title",
"modified-by": "modified by",
"date-modified": "date modified",
"back-to-page": "back to page",
"Version for": "Version for",
"previous": "Previous",
"next": "Next",
"version-for": "Version for %s",
"uri": "URI",
"content": "Content",
"restore": "Restore",
"All Pages": "All Pages",
"list": "list",
"cover": "cover",
"Page Versions": "Page Versions",
"latest-page-versions": "latest-page-versions",
"search-results": "Search Results",
"identify-yourself": "Who are you?",
"provide-username": "",
"username": "Name",
"You must give a name": "You must give a name",
"username-placeholder": "Sparklepony Von Unicorn",
"save-changes": "Save changes",
"page-saved": "Page saved",
"page-could-not-be-saved": "Page could not be saved, please try again later",
"successfully-uploaded": "Successfully uploaded",
"error-500": "Internal Server Error",
"error-415": "Unsupported media type",
"error-404": "Not found",
"error-400": "Bad request",
"page-conflict-title": "Page could not be saved",
"page-conflict-description": "Another user saved this page in the meantime. Do you want to reload the page and lose all your changes?",
"button-confirm": "Confirm",
"button-cancle": "Cancel",
"link-title": "Link title",
"unsupported-drop": "What're you trying to do?",
"move-page": "Move Page",
"new-path": "New path",
"error-target-path-exists": "Target path exists already. Can not move the page",
"page-moved": "Page succesfully moved",
"language": "Language",
"delete-page": "Delete page",
"restore-page": "Restore page",
"deleted-pages": "Archive",
"archive-description": "To restore a page open it and choose restore from the tasks menu",
"no-deleted-pages": "There are currently no archived pages.",
"page-status-deleted": "This page is deleted. To restore it click restore from the tasks menu.",
"no-versions-yet": "No versions yet",
"help": "Help",
"pages": "Pages",
"more": "More"
} |
var Router = require('../_base/__Router');
var RankTeamView = require('./views/RankTeam');
var RankPersonView = require('./views/RankPerson');
exports = module.exports = Router.extend({
routes: {
'rank/person': 'rankPerson',
'rank/team': 'rankTeam',
},
rankPerson: function(id){
if(!this.logined){
window.location.hash = 'login';
return;
}
//this.appEvents.trigger('set:brand','个人排行榜');
var rankPersonView = new RankPersonView({
router: this,
el: '#content',
id: id,
});
this.appEvents.trigger('changeView',rankPersonView);
rankPersonView.trigger('load');
},
rankTeam: function(id){
if(!this.logined){
window.location.hash = 'login';
return;
}
//this.appEvents.trigger('set:brand','营业厅排行榜');
var rankTeamView = new RankTeamView({
router: this,
el: '#content',
id: id,
});
this.appEvents.trigger('changeView',rankTeamView);
rankTeamView.trigger('load');
},
}); |
define(["lodash", "backbone", "jquery", "js/enum", "js/views/header", "js/models/dataAccessor"],
function(_, Backbone, $, Enum, HeaderView, DataAccessor) {
var game = {
eventsBus: _.extend({}, Backbone.Events),
db: null,
router: null,
status: Enum.GameStatus.LOADING,
initializeDfd: new $.Deferred()
};
_.extend(game, {
VERSION: "0.2",
initialize: function (router) {
var header = new HeaderView({ el: $("#header").get(0) });
this.router = router;
this.printVersionInfo();
header.render();
if (!this.checkBrowser()) {
return router.navigate("error/" + Enum.GameErrorTypes.OLD_BROWSER, { trigger: true });
}
this.eventsBus.on("header.toggleInstructions", _.bind(header.toggleInstructions, header));
this.db = new DataAccessor({ encrypter: CryptoJS });
this.initializeDB()
.done(function () {
game.status = Enum.GameStatus.READY;
game.initializeUser().then(function (user) {
game.db.saveCurrentUserName(user.get("name"));
game.eventsBus.trigger("levels.loaded");
game.initializeDfd.resolve();
});
})
.fail(function () {
return router.navigate("error/" + Enum.GameErrorTypes.NO_LEVELS_LOADED, { trigger: true });
});
},
onInitialize: function (callback) {
$.when(this.initializeDfd).done(callback);
},
printVersionInfo: function () {
var log = console && console.log || function () {};
log.call(console, "===========================");
log.call(console, "= Backbone: " + Backbone.VERSION);
log.call(console, "= Lodash: " + _.VERSION);
log.call(console, "= jQuery: " + $.fn.jquery);
log.call(console, "= Link It: " + this.VERSION);
log.call(console, "===========================");
},
checkBrowser: function () {
return !! (window.indexedDB && window.localStorage);
},
initializeDB: function () {
return this.db.initDB()
.then(function () {
if (game.db.getLevelsCount() < 1) {
//no levels - let's try to load them!
return game.db.fetchLevels().then(function () {
game.eventsBus.trigger("levels.loaded");
});
}
});
},
initializeUser: function () {
return this.db.initUser(this.db.getCurrentUserName());
},
navigateToLevel: function (levelNum) {
var router = this.router,
db = this.db;
return this.db.getCurrentUserActiveLevel().then(function (activeLevel) {
if (levelNum <= activeLevel) {
if (db.getLevelsCount() >= levelNum) {
router.navigate("level/" + levelNum);
router.hideCurrentView();
return router.showLevelView(levelNum);
} else {
return router.navigate("gameOver", { trigger: true });
}
} else {
return router.navigate("error/" + Enum.GameErrorTypes.PAGE_NOT_FOUND, { trigger: true });
}
}, function (e) {
return router.navigate("error/" + Enum.GameErrorTypes.USER_ERROR, { trigger: true });
});
},
updateActiveLevel: function (passedLevelIndex) {
var db = this.db;
return db.getCurrentUserActiveLevel().then(function (activeLevel) {
if (activeLevel === passedLevelIndex) {
return db.setCurrentUserActiveLevel(passedLevelIndex + 1);
} else {
return passedLevelIndex + 1;
}
});
}
});
return game;
}); |
import React, {Component, PropTypes} from 'react';
export default class GreetingsEmbeddedDoc extends Component {
static propTypes = {
iFrameSource: PropTypes.string.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
};
render() {
const {width, height, iFrameSource} = this.props;
const styles = require('./GreetingsEmbeddedDoc.scss');
return (
<div className={`${styles.container}`}>
<iframe
width={width}
height={height}
src={iFrameSource}
></iframe>
</div>
);
}
}
|
'use strict';
var express = require('express');
var router = express.Router();
var async = require('async');
var User = require('../../models/User');
var passport = require('../../passport');
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) return res.json({ok: true, user: null});
async.waterfall([
function(done) {
req.login(user, function(err) {
if (err) return done(err);
return done(null, user);
});
}
], function(err, user) {
if (err) return res.json({ok: true, user: null});
return res.json({ok: true, user: user.toJSON()});
});
})(req, res, next);
});
router.post('/logout', function(req, res) {
req.logout();
return res.json({ok: true});
});
router.post('/signup', function(req, res) {
var username = req.param('username');
var password = req.param('password');
var nickname = req.param('nickname');
var email = req.param('email');
if (!username || !password || !nickname || !email) return res.json({ok: false});
async.waterfall([
function(done) {
User.register(username, password, nickname, email, function(err, user) {
if (err) return done(err);
return done(null, user);
});
},
function(user, done) {
user.issueVerificationCode(function (err, user) {
if (err) return done(err);
return done(null, user);
});
},
function(user, done) {
Email.sendVerificationEmail(user, function (err, info) {
if (err) return done(err);
return done(null, user);
});
},
function(user, done) {
req.login(user, function(err) {
if (err) return done(err);
return done(null, user);
});
}
], function(err, user) {
if (!err) return res.json({ok: true, user: user.toJSON()});
User.findOneAndRemove({username: username}, function(err) {
return res.json({ok: true, user: null});
});
});
});
router.get('/check', function(req, res) {
return res.json({ok: true, user: req.isAuthenticated() ? req.user.toJSON() : null});
});
module.exports = router;
|
$(document).ready(function() {
/** VARIABLES **/
var sidebarCollapsed = false;
var sliderActive = false;
/* FUNCTIONS */
var collapseSidebar = function (speed, easing, target) {
var totalWidth = $('.jumbojumba').find('.row').width(),
totalMinusBtn = totalWidth - totalWidth*0.05,
contentWidth = 0, sidebarWidth = 0;
if (sidebarCollapsed) {
contentWidth = '66.6%';
sidebarWidth = 'initial';
} else {
contentWidth = totalMinusBtn;
}
// run simultaneously 3 effects
$('.main-content').animate({ width: contentWidth }, {
duration: speed,
easing: easing,
queue: false,
complete: function () {
var cell = $(target).find('.collapse-slider-cell');
if (cell.html() === '»') {
cell.html('«');
} else {
cell.html('»');
}
sliderActive = false;
}
});
$('.sidebar').animate({ width: sidebarWidth }, {
duration: speed,
easing: easing,
queue: false,
complete: function () {
if (sidebarCollapsed) {
sidebarCollapsed = false;
} else {
sidebarCollapsed = true;
}
}
});
$('.sidebar').toggle({
duration: speed,
easing: easing,
queue: false,
complete: function () {
fireEvent($(this), 'shown');
}
});
};
var switchHover = function () {
$('.sidebar').animate({opacity: 0.3}, 'fast');
};
var switchLeave = function () {
$('.sidebar').animate({opacity: 1}, 'fast');
};
function fireEvent(target, type) {
if ($(target).length > 0) {
var shownEvent = $.Event(type);
$(target).trigger(shownEvent);
}
}
/** EVENTS **/
$('.collapse-slider-switch').hover(switchHover, switchLeave);
$('.collapse-slider-switch').click(function() {
$(this).blur();
if (sliderActive) {
return;
}
sliderActive = true;
collapseSidebar('slow', 'swing', this);
});
$('.sidebar').on('show shown', function (event) {
switchLeave();
});
}); |
// make a new list
// add an item with an amount to the list
// update the list
// remove an item from the list
// print the list (nicely if able)
var list = {};
addItem = function (new_item, amount) {
list[new_item] = amount;
}
removeItem = function (item) {
delete list[item];
}
newNumber = function (item, newNumber) {
list[item] = newNumber;
}
showList = function () {
console.log("Grocery List:");
console.log(list);
}
// What concepts did you solidify in working on this challenge? (reviewing the passing of information, objects, constructors, etc.)
// I really like these kinds of challenges. It's nice to just focus on syntax since that's what I think normally trips me up.
// This challenge was pretty heavy on setting up functions.
// What was the most difficult part of this challenge?
// I think that manipulating how the output would look was hardest. I wanted to keep it organized without taking up a lot of room.
// Did an array or object make more sense to use and why?
// I kept it as an object because I thought that it was better than an array just like in the original challenge. I wanted to keep the quantities organized.
|
const fs = require('fs');
const functions = require('./functions.js');
const rimraf = require("rimraf");
const path = require('path');
const variables = require("./variables.js");
const defaultSite = variables.defaultSite;
const fileUpload = require('express-fileupload');
const imagemagick = require('imagemagick');
/**
* @module content
*/
module.exports = (app) => {
/**
* @function
* GET service to obtain the list of content types of a site
* @param {string} - idSite - Name of the site
* @return {array} ARRAY with the content types names
*/
app.get('/site/:id/content/contentTypes', function (req, res) {
var site = req.params.id,
siteURL = functions.getURLSite(site),
contentTypes = [];
if(fs.existsSync(siteURL + '/content_manager')){
dirContentSite = fs.readdirSync(siteURL + '/content_manager');
}
dirContentSite.forEach(function(element,index){
if(element.split('.').length <= 1){
contentTypes.push({"value":element,"label":element});
}
});
return res.status(200).send(contentTypes);
});
/**
* @function
* GET service to obtain the detail of a content
* @param {string} - idSite - Name of the site
* @param {string} - contentType - Name of the contentType of the content
* @param {string} - idContent - ID of the content
* @return {json} JSON with the detail of the content
*/
app.get('/site/:id/content/detail/:contentType/:idContent', function (req, res) {
var site = req.params.id,
siteURL = functions.getURLSite(site),
idContent = req.params.idContent,
contentType = req.params.contentType,
contentConfig = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/config.json'));
contentConfigValues = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/' + idContent + '/config.json'));
configValues = contentConfigValues.configValues;
contentTypes = [];
if(fs.existsSync(siteURL + '/content_manager')){
dirContentSite = fs.readdirSync(siteURL + '/content_manager');
}
dirContentSite.forEach(function(element,index){
if(element.split('.').length <= 1){
contentTypes.push({"value":element,"label":element});
}
});
delete contentConfigValues['configValues'];
return res.status(200).send(Object.assign(contentConfig,contentConfigValues,{"contentTypes":contentTypes},{"content":configValues}));
});
/**
* @function
* GET service to obtain the detail of a content type
* @param {string} - idSite - Name of the site
* @param {string} - contentType - Name of the contentType
* @return {json} JSON with the detail of the content type
*/
app.get('/site/:id/content/detail/:contentType', function (req, res) {
var site = req.params.id,
siteURL = functions.getURLSite(site),
contentType = req.params.contentType,
contentTypeConfig = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/config.json'));
return res.status(200).send(contentTypeConfig);
});
/**
* @function
* POST service to obtain the detail of a content type
* @param {string} - idSite - Name of the site
* @param {string} - contentType - Name of the contentType
* @return {json} JSON with the detail of the content type
*/
app.post('/site/:id/content/detail', function (req, res) {
var site = req.params.id,
siteURL = functions.getURLSite(site),
contentType = req.body.contentType,
contentTypeConfig = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/config.json'));
return res.status(200).send(contentTypeConfig);
});
/**
* @function
* GET service to obtain a list of contents for a component, checking the content which the component is using at this moment
* @param {string} - id - Name of the site
* @param {string} - idComponent - ID of the component
* @return {json} JSON with a list of contents
*/
app.get('/site/:id/contents/:idComponent', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var dirContentSite = [];
var contents = [];
var idComponent = req.params.idComponent;
var sitemap = JSON.parse(fs.readFileSync(siteURL + '/sitemap.json').toString());
var componentDetail = functions.getDetailComponentByID(idComponent, sitemap.pages);
if(fs.existsSync(siteURL + '/content_manager')){
dirContentSite = fs.readdirSync(siteURL + '/content_manager');
}
dirContentSite.forEach(function(contentType,index){
if(contentType.split('.').length <= 1){
fs.readdirSync(siteURL + '/content_manager/' + contentType).forEach(function(element,i){
if(element.split('.').length <= 1 && element != 'empty_content'){
var file = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/' + element + '/config.json'));
file['contentType']= contentType;
file['checked'] = componentDetail.content.idContent == element ? true : false;
contents.push(file);
}
})
}
})
contents = { "content": contents };
return res.status(200).send(contents);
});
/**
* @function
* GET service to obtain a list of contents
* @param {string} - id - Name of the site
* @return {json} JSON with a list of contents
*/
app.get('/site/:id/contents', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var dirContentSite = [];
var contents = [];
var filter_contentType = req.query.filter && req.query.filter.where && req.query.filter.where.and[0] && req.query.filter.where.and[0].contentType ? req.query.filter.where.and[0].contentType : false;
if(fs.existsSync(siteURL + '/content_manager')){
dirContentSite = fs.readdirSync(siteURL + '/content_manager');
}
dirContentSite.forEach(function(contentType,index){
if(contentType.split('.').length <= 1){
fs.readdirSync(siteURL + '/content_manager/' + contentType).forEach(function(element,i){
if(element.split('.').length <= 1 && element != 'empty_content'){
var file = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/' + element + '/config.json'));
file['contentType']= contentType;
if(filter_contentType && file['contentType'] == filter_contentType){
contents.push(file);
}
else if(!filter_contentType){
contents.push(file);
}
}
})
}
})
var filter_order = req.query.filter && req.query.filter.order ? req.query.filter.order : 0;
contents = contents.sort(function (a, b) {
if (a[filter_order] > b[filter_order]) {
return 1;
}
if (a[filter_order] < b[filter_order]) {
return -1;
}
// a must be equal to b
return 0;
});
return res.status(200).send(contents);
});
/**
* @function
* Service to create a new content
* @param {string} - id - Name of the site
* @param {string} - contentType - ContentType of the content
* @param {number} - name - Name of the content
*/
app.post('/site/:id/content/add', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var contentType = req.body.contentType;
var name = req.body.name;
var createdDate = new Date().toGMTString();
var id = 'content_' + parseInt(Math.random() * (99999 - 0) + 0);
var configContentType = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/config.json'));
var configValues = {"contentType":contentType};
configContentType.config.forEach(function(el,index){
configValues[el.name] = req.body[el.name];
});
fs.mkdirSync(siteURL + '/content_manager/'+contentType+'/' + id);
var config = {
"id":id,
"name":name,
"createdDate":createdDate,
"configValues": configValues
}
var mixinContent = "mixin "+id+"(content)\n";
mixinContent +=" include view.html";
var includeContents = fs.readFileSync(siteURL + '/content_manager/'+contentType+'/include.pug').toString() + '\n';
includeContents += 'include ./'+ id +'/mixin.pug';
fs.writeFileSync(siteURL + '/content_manager/'+contentType+'/include.pug', includeContents,function(err){});
fs.writeFileSync(siteURL + '/content_manager/'+contentType+'/'+ id +'/config.json', JSON.stringify(config,null,4),function(err){});
fs.writeFileSync(siteURL + '/content_manager/'+contentType+'/'+ id +'/mixin.pug', mixinContent ,function(err){});
functions.buildContentTemplate('--site ' + site + ' --contentType ' + contentType + ' --contentID ' + id , res)
});
/**
* @function
* Service to edit a content
* @param {string} - id - Name of the site
* @param {string} - contentType - ContentType of the content
* @param {number} - name - Name of the content
*/
app.post('/site/:id/content/edit', function (req, res) {
if(req.body.id != 'empty_content'){
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var contentType = req.body.contentType;
var id = req.body.id;
var name = req.body.name;
var htmlContent = req.body.htmlContent;
var modifiedDate = new Date().toGMTString();
var configContentType = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/config.json'));
var configValues = {"contentType":contentType};
var config = JSON.parse(fs.readFileSync(siteURL + '/content_manager/'+contentType+'/' + id + '/config.json'));
configContentType.config.forEach(function(el,index){
configValues[el.name] = req.body[el.name];
});
config['name'] = name;
config['modifiedDate'] = modifiedDate;
config['configValues'] = configValues;
fs.writeFileSync(siteURL + '/content_manager/'+contentType+'/'+ id +'/config.json', JSON.stringify(config,null,4),function(err){});
functions.execGulpTask('gulp buildContentTemplate --site '+site+' --contentType '+contentType+' --contentID ' + id + ' & gulp deploySites --env dev --site ' + site + ' & gulp removeTMP', res, '', "Modificar el contenido <strong>" + name + "</strong>");
};
});
/**
* @function
* Service to delete a content
* @param {string} - id - Name of the site
* @param {string} - id - ID of the content
* @param {number} - contentType - Name of the content type
*/
app.post('/site/:id/content/delete', function (req, res) {
if(req.body.id != 'empty_content'){
var site = req.params.id;
var contentId = req.body.id;
var contentType = req.body.contentType;
functions.deleteContent(site,contentId,contentType);
functions.deploySites('--env dev --site ' + site, res, '',"Eliminar el contenido <strong>" + contentId + "</strong>");
}
});
/**
* @function
* Service to add a content type
* @param {string} - id - Name of the site
* @param {string} - name - Name of the content type
* @param {string} - template - Template code of the content type
* @param {json} - config - JSON with the config of the content type
*/
app.post('/site/:id/content/contentType/add', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var contentTypeName = req.body.name.replace(/ /g, "");
var contentTypeTemplate = req.body.template;
var config = {"config":req.body.config};
fs.mkdirSync(siteURL + '/content_manager/'+contentTypeName);
var mixinContent = "include ./include.pug\n\n";
mixinContent += "mixin content_"+contentTypeName+"(contentName)\n";
mixinContent +=" +#{contentName}";
var includeContents = fs.readFileSync(siteURL + '/content_manager/include_contents.pug').toString() + '\n';
includeContents += 'include ./'+ contentTypeName +'/mixin.pug';
fs.writeFileSync(siteURL + '/content_manager/include_contents.pug', includeContents,function(err){});
fs.writeFileSync(siteURL + '/content_manager/'+contentTypeName+'/include.pug','',function(err){});
fs.writeFileSync(siteURL + '/content_manager/'+contentTypeName+'/config.json', JSON.stringify(config,null,4),function(err){});
fs.writeFileSync(siteURL + '/content_manager/'+contentTypeName+'/mixin.pug', mixinContent ,function(err){});
fs.writeFileSync(siteURL + '/content_manager/'+contentTypeName+'/template.pug', contentTypeTemplate ,function(err){});
return res.status(200).send();
});
/**
* @function
* Service to modify a content type
* @param {string} - id - Name of the site
* @param {string} - name - Name of the content type
* @param {string} - template - Template code of the content type
* @param {json} - config - JSON with the config of the content type
*/
app.post('/site/:id/content/contentType/edit', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var contentTypeName = req.body.name;
var contentTypeTemplate = req.body.template;
var config = {"config":req.body.config};
fs.writeFileSync(siteURL + '/content_manager/'+contentTypeName+'/config.json', JSON.stringify(config,null,4),function(err){});
fs.writeFileSync(siteURL + '/content_manager/'+contentTypeName+'/template.pug', contentTypeTemplate ,function(err){});
functions.execGulpTask('gulp buildContentTemplate --site '+site+' --contentType '+contentTypeName+ ' & gulp deploySites --env dev --site ' + site + ' & gulp removeTMP', res, '','Editar el tipo de contenido <strong>' + contentTypeName + '</strong>');
});
/**
* @function
* Service to delete a content type, including his contents. If a component use a content that belongs to content type, his content is modified to default content and content type
* @param {string} - id - Name of the site
* @param {string} - contentTypeName - Name of the content type
*/
app.post('/site/:id/content/contentType/delete/', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var contentTypeName = req.body.contentTypeName;
//Borramos primero las referencias al tipo de contenido
var sitemap = fs.readFileSync(siteURL + '/sitemap.json').toString();
sitemap = JSON.parse(sitemap.replace('"contentType": "'+contentTypeName+'"','"contentType": "content"'));
fs.writeFileSync(siteURL + '/sitemap.json', JSON.stringify(sitemap,null,4));
//Borramos las referencias a los contenidos asociados al tipo de contenido
if(fs.existsSync(siteURL + '/content_manager/' + contentTypeName)){
dirContentTypeSite = fs.readdirSync(siteURL + '/content_manager/' + contentTypeName);
}
dirContentTypeSite.forEach(function(content,index){
if(content.split('.').length <= 1){
functions.deleteContent(site,content,contentTypeName);
}
});
var includeContents = fs.readFileSync(siteURL + '/content_manager/include_contents.pug').toString();
includeContents = includeContents.replace('include ./'+contentTypeName+'/mixin.pug','')
fs.writeFileSync(siteURL + '/content_manager/include_contents.pug', includeContents,function(err){});
rimraf(siteURL + '/content_manager/'+contentTypeName,function () {
console.log("ELIMINADO TIPO CONTENIDO -> " + contentTypeName);
});
functions.deploySites('--env dev --site ' + site, res, '', "Eliminar el tipo de contenido <strong>" + contentTypeName + "</strong>");
});
/**
* @function
* GET service to obtain the detail of a content type
* @param {string} - id - Name of the site
* @param {string} - contentTypeName - Name of the content type
* @return {json} JSON with the detail of the content type
*/
app.get('/site/:id/content/contentType/detail/:contentTypeName', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var contentTypeName = req.params.contentTypeName;
var config = JSON.parse(fs.readFileSync(siteURL + '/content_manager/config.json'));
var content = JSON.parse(fs.readFileSync(siteURL + '/content_manager/' + contentTypeName + '/config.json'));
var template = fs.readFileSync(siteURL + '/content_manager/' + contentTypeName + '/template.pug').toString();
return res.status(200).send(Object.assign(config,{"content":content},{"template":template},{"name":contentTypeName}));
});
/**
* @function
* GET service to obtain the general config for all the content types
* @param {string} - id - Name of the site
* @return {json} JSON with the config of all content types
*/
app.get('/site/:id/content/contentType/config', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var config = JSON.parse(fs.readFileSync(siteURL + '/content_manager/config.json'));
return res.status(200).send(config);
});
/**
* @function
* GET service to obtain a list of media files
* @param {string} - id - Name of the site
* @return {json} JSON with a list of media files
*/
app.get('/site/:id/content/media', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var dirContentSite = [];
var contents = [];
if(fs.existsSync(siteURL + '/media')){
dirContentSite = fs.readdirSync(siteURL + '/media');
}
else{
fs.mkdirSync(siteURL + '/media');
dirContentSite = fs.readdirSync(siteURL + '/media');
}
for(var index=0; index < dirContentSite.length; index++){
var file = dirContentSite[index].split('.');
var filename = dirContentSite[index];
var file_details = {};
var stats = fs.statSync(siteURL + '/media/' + filename);
if(filename.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i)){
file_details["name"] = filename,
file_details["size"] = stats.size,
file_details["extension"] = path.extname(siteURL + '/media/' + filename);
contents.push(file_details);
}
}
return res.status(200).send(contents);
});
/**
* @function
* POST service to upload a media file
* @param {string} - id - Name of the site
* @param {file} - Array of files
* @return {json} JSON with the filename uploaded
*/
app.post('/site/:id/content/media/upload', fileUpload() ,async function(req, res) {
var file_name = '';
try{
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var file = JSON.parse(JSON.stringify(req.files))
console.log(req.files);
Object.keys(file).forEach(function(el){
file_name = file[el].name
if(fs.existsSync(siteURL + '/media/' + file_name)){
return res.status(200).send(
{
"filename":file_name,
"error":{
"code":"FILE_EXIST_ERROR"
}
}
)
}
if(!file_name.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i)){
return res.status(200).send(
{
"filename":file_name,
"error":{
"code":"FILE_FORMAT_ERROR"
}
}
)
}
var buffer = new Buffer.from(file[el].data.data)
//uncomment await if you want to do stuff after the file is created
/*await*/
fs.writeFile(siteURL + '/media/' + file_name, buffer, async(err) => {
console.log("Successfully Written to File.");
console.log("end : " + new Date())
});
fs.writeFile('app/development/sites/'+site+'/es/media/' + file_name, buffer, async(err) => {
console.log("Successfully Written to File.");
console.log("end : " + new Date())
});
fs.writeFile('app/development/sites/'+site+'/en/media/' + file_name, buffer, async(err) => {
console.log("Successfully Written to File.");
console.log("end : " + new Date())
});
return res.status(200).send({"filename":file_name});
});
}
catch(e){
console.log(e);
res.status(200).send(
{
"filename":file_name,
"error":{
"code":"FILE_UPLOAD_ERROR"
}
}
)
};
});
/**
* @function
* POST service to delete a media file
* @param {string} - id - Name of the site
* @param {string} - filename - Name of the file to be deleted
*/
app.post('/site/:id/content/media/delete', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var filename = req.body.filename;
if(!fs.existsSync(siteURL + '/media/' + filename)){
res.status(412).send(
{
"code":"412",
"statusCode":"FILE_DELETE_NOT_EXIST_ERROR"
}
)
}
fs.unlinkSync(siteURL + '/media/' + filename);
fs.unlinkSync('app/development/sites/'+site+'/es/media/' + filename);
fs.unlinkSync('app/development/sites/'+site+'/en/media/' + filename);
res.status(200).send();
});
/**
* @function
* GET service to obtain the detail of a media file
* @param {string} - id - Name of the site
* @param {string} - filename - Name of the media file
* @return {json} JSON with the detail of the file
*/
app.get('/site/:id/content/media/detail/:filename', function (req, res) {
var site = req.params.id;
var siteURL = functions.getURLSite(site);
var filename = req.params.filename;
var file_details = {}
if(!fs.existsSync(siteURL + '/media/' + filename)){
res.status(412).send(
{
"code":"412",
"statusCode":"FILE_DETAIL_NOT_EXIST_ERROR"
}
)
}
imagemagick.identify(siteURL + '/media/' + filename, function(err, features){
file_details["width"] = features.width;
file_details["height"] = features.height;
file_details["format"] = features.format;
file_details["dateCreate"] = features.properties["date:create"];
var stats = fs.statSync(siteURL + '/media/' + filename);
file_details["name"] = filename,
file_details["size"] = stats.size,
file_details["extension"] = path.extname(siteURL + '/media/' + filename),
file_details["url_dev"] = 'pro',
file_details["url_pro"] = 'dev';
return res.status(200).send(file_details);
})
});
} |
version https://git-lfs.github.com/spec/v1
oid sha256:0f688dcbf550debc116cb45a2dde98a1e960118dfd5085032807a22fbed32a5e
size 15107
|
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'
import elementEnLocale from 'element-ui/lib/locale/lang/en' // element-ui lang
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'// element-ui lang
import enLocale from './en'
import zhLocale from './zh'
Vue.use(VueI18n)
const messages = {
en: {
...enLocale,
...elementEnLocale
},
zh: {
...zhLocale,
...elementZhLocale
}
}
const i18n = new VueI18n({
// set locale
// options: en | zh | es
locale: Cookies.get('language') || 'zh',
// set locale messages
messages
})
export default i18n
|
/*
The MIT License (MIT)
Copyright (c) 2014 David Winterbourne, Winterbourne Enterprises, LLC, dba Kaidad
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
/* Filters */
myAppFilters.filter('interpolate', ['version', function (version) {
return function (text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}]);
myAppFilters.filter('mediaItemsFilter', function() {
return function(items, prefix) {
var filtered = [];
angular.forEach(items, function(item) {
if (item.mimeType.indexOf(prefix) === 0) {
filtered.push(item);
}
});
return filtered;
}
});
|
/**
* Module dependencies.
*/
var stylus = require('stylus')
, nib = require('../')
, fs = require('fs');
// test cases
var cases = fs.readdirSync('test/cases').filter(function(file){
return ~file.indexOf('.styl');
}).map(function(file){
return file.replace('.styl', '');
});
describe('integration', function(){
cases.forEach(function(test){
var name = test.replace(/[-.]/g, ' ');
it(name, function(){
var path = 'test/cases/' + test + '.styl';
var styl = fs.readFileSync(path, 'utf8').replace(/\r/g, '');
var css = fs.readFileSync('test/cases/' + test + '.css', 'utf8').replace(/\r/g, '').trim();
var style = stylus(styl)
.use(nib())
.set('filename', path)
.define('url', stylus.url());
if (~test.indexOf('compress')) style.set('compress', true);
style.render(function(err, actual){
if (err) throw err;
actual.trim().should.equal(css);
});
})
});
}) |
import React from 'react';
class AdminMenu extends React.Component {
componentDidMount() {
console.log('AdminMenu');
};
render() {
return (
<div id='admin-Menu'>
<h1>AdminMenu</h1>
</div>
);
}
};
export default AdminMenu;
|
const path = require('path')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const webpack = require('webpack')
const TerserJSPlugin = require('terser-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = function ({ runtime }) {
const assetDirs = [
`${runtime.assetsSourceDir}`,
].concat((runtime.extraAssetsSourceDirs || []))
const moduleDirs = [
runtime.assetsSourceDir,
'node_modules',
path.join(runtime.npmRoot, 'node_modules'),
path.join(runtime.lanyonDir, 'node_modules'),
].concat(runtime.extraAssetsSourceDirs || [])
const browsers = runtime.browsers || ['> 1%', 'ie 10', 'ie 8', 'safari 4']
const webpackRules = () => {
const rules = []
rules.push({
test: /\.woff2?(\?v=\d+\.\d+\.\d+)?$/,
use : [
{
loader : 'url-loader',
options: {
limit : 10000,
mimetype: 'application/font-woff',
},
},
],
})
rules.push({
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use : [
{
loader : 'url-loader',
options: {
limit : 10000,
mimetype: 'image/svg+xml',
},
},
],
})
rules.push({
test: /\.(png|webp|gif|jpe?g|ttf(\?v=\d+\.\d+\.\d+)?)$/,
use : [
{
loader : 'url-loader',
options: {
limit : 8096,
mimetype: 'application/octet-stream',
},
},
],
})
rules.push({
test: /\.(eot|cur)(\?v=\d+\.\d+\.\d+)?$/,
use : [
'file-loader',
],
})
rules.push({
test: /\.worker\.js$/,
use : [
'worker-loader',
],
})
rules.push({
test: /([\\/]bootstrap-sass[\\/]assets[\\/]javascripts[\\/]|[\\/]jquery\..*\.js$)/,
use : [
{
loader : 'imports-loader',
options: {
imports: [
'default jquery $',
],
// Disabled for Webpack5
// this: '>window',
},
},
],
})
rules.push({
test: /\.(sa|sc|c)ss$/,
use : [
MiniCssExtractPlugin.loader,
{
loader : 'cache-loader',
options: {
cacheDirectory: `${runtime.cacheDir}/cache-loader`,
},
},
'css-loader',
'resolve-url-loader',
{
loader : 'postcss-loader',
options: {
postcssOptions: {
sourceMap: true,
ident : 'postcss',
plugins : [
['postcss-preset-env', { browsers }],
],
},
},
},
{
loader : 'sass-loader',
options: {
sassOptions: {
// We can't do anything about deprecations in dependency code
quietDeps: true,
},
},
},
],
})
rules.push({
test : /\.(js|jsx)$/,
include: assetDirs,
exclude: [
/[\\/](node_modules|js-untouched)[\\/]/,
],
use: [
'thread-loader',
{
loader : 'babel-loader',
options: {
babelrc : false,
cacheCompression: false,
cacheDirectory : `${runtime.cacheDir}/babel-loader`,
presets : [
[require.resolve('@babel/preset-env'), {
targets: { browsers },
}],
require.resolve('@babel/preset-react'),
],
plugins: [
[require.resolve('@babel/plugin-proposal-decorators'), { legacy: true }],
require.resolve('@babel/plugin-proposal-class-properties'),
require.resolve('react-hot-loader/babel'),
require.resolve('nanohtml'),
],
},
},
],
})
return rules
}
const webpackPlugins = () => {
const plugins = []
const defines = {
'process.env.LANYON_ENV': JSON.stringify(runtime.lanyonEnv),
'process.env.NODE_ENV' : JSON.stringify(process.env.NODE_ENV),
'process.env.ENDPOINT' : JSON.stringify(process.env.ENDPOINT),
}
if (runtime.customEnv) {
for (const [key, value] of Object.entries(runtime.customEnv)) {
defines[`process.env.${key}`] = JSON.stringify(value)
}
}
plugins.push(new webpack.DefinePlugin(defines))
runtime.entries.forEach(entry => {
plugins.push(new HtmlWebpackPlugin({
inject : false,
cache : true,
scriptLoading : 'blocking', // worth an experiment: 'defer'
filename : `${runtime.projectDir}/_includes/_generated_assets/${entry}-${runtime.lanyonEnv}-head.html`,
chunks : [entry],
templateContent: runtime.headAssetTemplate ? runtime.headAssetTemplate : ({ htmlWebpackPlugin }) => `${htmlWebpackPlugin.tags.headTags}`,
}))
plugins.push(new HtmlWebpackPlugin({
inject : false,
cache : true,
scriptLoading : 'blocking', // worth an experiment: 'defer'
filename : `${runtime.projectDir}/_includes/_generated_assets/${entry}-${runtime.lanyonEnv}-body.html`,
chunks : [entry],
templateContent: runtime.bodyAssetTemplate ? runtime.bodyAssetTemplate : ({ htmlWebpackPlugin }) => `${htmlWebpackPlugin.tags.bodyTags}`,
}))
})
// plugins.push({
// apply: (compiler) => {
// compiler.hooks.afterEmit.tap('AfterEmitPlugin', async (compilation) => {
// const files = await globby(`${runtime.cacheDir}/_generated_assets/*`)
// const targetDir = `${runtime.projectDir}/_includes/_generated_assets/`
// console.log({ files, targetDir })
// })
// },
// })
plugins.push(new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename : runtime.isDev ? `[name].css` : `[name].[contenthash].css`,
chunkFilename: runtime.isDev ? `[name].css` : `[name].[contenthash].[chunkhash].chunk.css`,
ignoreOrder : true, // <-- add this to avoid: "Order in extracted chunk undefined" ¯\_(ツ)_/¯ https://github.com/redbadger/website-honestly/issues/128
}))
if (runtime.isDev) {
plugins.push(new webpack.HotModuleReplacementPlugin())
}
if (runtime.analyze) {
plugins.push(new BundleAnalyzerPlugin({
analyzerMode: 'static',
logLevel : 'info',
openAnalyzer: true,
}))
}
return plugins
}
const webpackCfg = {
mode : runtime.isDev ? 'development' : 'production',
bail : true,
module : { rules: webpackRules() },
plugins : webpackPlugins(),
// Disabled for Webpack5
node : false,
recordsPath : runtime.recordsPath,
target : 'web',
optimization: {
minimize : !runtime.isDev,
minimizer : !runtime.isDev ? [new TerserJSPlugin({}), new CssMinimizerPlugin({})] : [],
splitChunks: !runtime.isDev
? {
chunks: 'all',
}
: false,
},
output: {
publicPath : runtime.publicPath,
path : runtime.assetsBuildDir,
filename : runtime.isDev ? `[name].js` : `[name].[contenthash].js`,
chunkFilename: runtime.isDev ? `[name].js` : `[name].[contenthash].[chunkhash].chunk.js`,
},
devtool: (function dynamicDevtool () {
// https://webpack.js.org/guides/build-performance/#devtool
if (runtime.isDev) {
return 'eval-cheap-module-source-map'
}
return 'source-map'
}()),
resolveLoader: {
modules: [
path.join(runtime.lanyonDir, 'node_modules'),
path.join(runtime.npmRoot, 'node_modules'),
path.join(runtime.projectDir, 'node_modules'),
],
},
resolve: {
modules : moduleDirs,
descriptionFiles: ['package.json'],
mainFields : ['browser', 'main'],
mainFiles : ['index'],
aliasFields : ['browser'],
extensions : ['.js'],
enforceExtension: false,
fallback : {
stream: require.resolve('stream-browserify'),
},
// Disabled for Webpack5
// enforceModuleExtension: false,
alias: runtime.alias,
},
entry: (function dynamicEntries () {
const entries = {}
runtime.entries.forEach(entry => {
entries[entry] = []
if (runtime.isDev) {
// Push HMR to all entrypoints
entries[entry].push('webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true&overlay=true')
}
entries[entry].push(path.join(runtime.assetsSourceDir, `${entry}.js`))
})
return entries
}()),
}
return webpackCfg
}
|
import { observable } from 'mobx';
import $ from 'jquery'
class AppState {
@observable timer = 0;
@observable videoList = []
@observable selectedVideo = {}
constructor() {
setInterval(() => {
this.timer += 1;
}, 1000);
}
resetTimer() {
this.timer = 0;
}
selectVideo(video) {
this.selectedVideo = video
}
fetchYoutubeVideos(query) {
$.ajax({
method: 'GET',
url: 'https://www.googleapis.com/youtube/v3/search',
data: {
part: 'snippet',
type: 'video',
videoEmbeddable: 'true',
contentType: 'application/json',
q: query,
maxResults: 10,
key: 'AIzaSyC08ULv9IlOoF4vSZvkyX4E3lviClgnqjM',
},
success: (response) => {
this.videoList = response.items
},
error: (response) => {
this.errors = {
fetchingVideosError: 'There was an error fetching the videos'
}
}
})
}
}
export default AppState;
|
/* */
"format register";
export class BreezePropertyObserver {
constructor(owner, obj, propertyName){
this.owner = owner;
this.obj = obj;
this.propertyName = propertyName;
this.callbacks = [];
this.isSVG = false;
}
getValue(){
return this.obj[this.propertyName];
}
setValue(newValue){
this.obj[this.propertyName] = newValue;
}
trigger(newValue, oldValue){
var callbacks = this.callbacks,
i = callbacks.length;
while(i--) {
callbacks[i](newValue, oldValue);
}
}
subscribe(callback){
return this.owner.subscribe(this, callback);
}
}
export class BreezeObjectObserver {
constructor(obj){
this.obj = obj;
this.observers = {};
}
subscribe(propertyObserver, callback){
var callbacks = propertyObserver.callbacks;
callbacks.push(callback);
if(!this.observing){
this.observing = true;
this.subscription = this.obj.entityAspect.propertyChanged.subscribe(
args => {
this.handleChanges([{name: args.propertyName, object: args.entity, type: 'update', oldValue: args.oldValue}]);
});
}
return function(){
callbacks.splice(callbacks.indexOf(callback), 1);
if (callbacks.length > 0)
return;
this.obj.entityAspect.propertyChanged.unsubscribe(this.subscription);
this.observing = false;
}.bind(this);
}
getObserver(propertyName){
var propertyObserver = this.observers[propertyName]
|| (this.observers[propertyName] = new BreezePropertyObserver(this, this.obj, propertyName));
return propertyObserver;
}
handleChanges(changeRecords){
var updates = {},
observers = this.observers,
i = changeRecords.length;
while(i--) {
var change = changeRecords[i],
name = change.name;
if(!(name in updates)){
var observer = observers[name];
updates[name] = true;
if(observer){
observer.trigger(change.object[name], change.oldValue);
}
}
}
}
} |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
id: String,
name: String,
tasks: [{
id: Number,
source: Number
}],
members: [{
name: String,
admin: Boolean
}]
});
var Board = mongoose.model('Board', BoardSchema);
module.exports = Board; |
var rek = require('rekuire');
var config = rek('discord-rss-config-runtime.json');
const controllerCmds = require('../commands/controller/controllerCmds.js')
const loadCommand = (file) => require(`../commands/${file}.js`)
const checkPerm = require('../util/checkPerm.js')
const commandList = require('../util/commandList.json')
const channelTracker = require('../util/channelTracker.js')
function isBotController (command, author) {
var controllerList = config.botSettings.controllerIds
if (!controllerList || (typeof controllerList === "object" && controllerList.length === 0)) return false;
else if (typeof controllerList !== "object" || (typeof controllerList === "object" && controllerList.length === undefined)) {
console.log(`Could not execute command "${command} due to incorrectly defined bot controller."`);
return false;
}
for (var x in controllerList) {
if (controllerList[x] === author) return true;
}
return false
}
function logCommand(message, command) {
return console.log(`Commands: (${message.guild.id}, ${message.guild.name}) => Used ${command}.`)
}
module.exports = function (bot, message) {
if (!message.member || !message.member.hasPermission("MANAGE_CHANNELS") || message.author.bot) return;
var m = message.content.split(" ")
let command = m[0].substr(config.botSettings.prefix.length)
if (channelTracker.hasActiveMenus(message.channel.id)) return;
// for regular commands
for (var cmd in commandList) {
if (cmd === command && checkPerm(bot, message, commandList[cmd].reqPerm)) {
logCommand(message, command);
return loadCommand(command)(bot, message, command);
}
}
// for bot controller commands
if (controllerCmds[command] && checkPerm(bot, message, 'SEND_MESSAGES')) {
if (!isBotController(command, message.author.id)) return;
return controllerCmds[command](bot, message);
}
}
|
/**
* jquery.scrollfix v1.0
*
* author: szm
* email: [email protected]
* github: https://github.com/SUpermin6u/scrollFix
*
* Free to use under the MIT license.
*/
(function($) {
/**
* when scroll to the certain place, will fixed there
* @param {jQuery Selector} $selector selector to do the scrollfix
* @param {Object} absoluteCss style before fixed
* @param {Object} fixedCss style after fixed
*/
var scrollFix = function($selector,absoluteCss,fixedCss){
var isBarFixed = false;
var $bar = $selector;
if(!$bar.length){return;}
var aCss = absoluteCss || {
'position':'absolute',
'top':'auto'
}
var fCss = fixedCss || {
'position':'fixed',
'top':0
}
$bar.css(aCss);
var barOffsetTop = $bar.offset().top;
$(window).scroll(function(){
var top = $('body').scrollTop() || $('html').scrollTop();
if(top > barOffsetTop && !isBarFixed){
$bar.css(fCss);
isBarFixed = true;
}
if(top <= barOffsetTop&& isBarFixed){
$bar.css(aCss);
isBarFixed = false;
}
});
$(window).scroll();
}
})(jQuery);
|
function playingCards(params) {
const VALID_CARDS = [2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A]
const VALID_SUITS = {
S : '\u2660',
H : '\u2665',
D : '\u2666',
C : '\u2663'
}
}
|
'use strict';
const fs = require('fs');
const path = require('path');
const gutil = require('gulp-util');
const assert = require('power-assert');
const stylestats = require('../');
describe('gulp-stylestats', function () {
it('should log css statistics', function (done) {
let count = 0;
let stream = stylestats();
let fp = path.join(__dirname, 'fixtures/test.css');
stream.on('data', function (newFile) {
count++;
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should create css statistics', function (done) {
let count = 0;
let stream = stylestats({
outfile: true
});
let fp = path.join(__dirname, 'fixtures/test.css');
let dest = path.join(__dirname, 'fixtures/test.txt');
stream.on('data', function (file) {
count++;
assert.equal(file.path, dest);
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should log multiple css statistics', function (done) {
let count = 0;
let stream = stylestats();
let fp1 = path.join(__dirname, 'fixtures/test.css');
let fp2 = path.join(__dirname, 'fixtures/kite.css');
stream.on('data', function (newFile) {
count++;
});
stream.on('end', function (error) {
assert.strictEqual(count, 2);
done();
});
stream.write(new gutil.File({
path: fp1,
contents: fs.readFileSync(fp1)
}));
stream.write(new gutil.File({
path: fp2,
contents: fs.readFileSync(fp2)
}));
stream.end();
});
it('should log css statistics as JSON', function (done) {
let count = 0;
let stream = stylestats({
type: 'json'
});
let fp = path.join(__dirname, 'fixtures/test.css');
stream.on('data', function (newFile) {
count++;
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should create css statistics as JSON', function (done) {
let count = 0;
let stream = stylestats({
type: 'json',
outfile: true
});
let fp = path.join(__dirname, 'fixtures/test.css');
let dest = path.join(__dirname, 'fixtures/test.json');
stream.on('data', function (file) {
count++;
assert.equal(file.path, dest);
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should log css statistics as CSV', function (done) {
let count = 0;
let stream = stylestats({
type: 'csv'
});
let fp = path.join(__dirname, 'fixtures/test.css');
stream.on('data', function (newFile) {
count++;
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should create css statistics as CSV', function (done) {
let count = 0;
let stream = stylestats({
type: 'csv',
outfile: true
});
let fp = path.join(__dirname, 'fixtures/test.css');
let dest = path.join(__dirname, 'fixtures/test.csv');
stream.on('data', function (file) {
count++;
assert.equal(file.path, dest);
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should log css statistics as HTML', function (done) {
let count = 0;
let stream = stylestats({
type: 'html'
});
let fp = path.join(__dirname, 'fixtures/test.css');
stream.on('data', function (data) {
count++;
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should create css statistics as HTML', function (done) {
let count = 0;
let stream = stylestats({
type: 'html',
outfile: true
});
let fp = path.join(__dirname, 'fixtures/test.css');
let dest = path.join(__dirname, 'fixtures/test.html');
stream.on('data', function (file) {
count++;
assert.equal(file.path, dest);
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should log css statistics as Markdown', function (done) {
let count = 0;
let stream = stylestats({
type: 'md'
});
let fp = path.join(__dirname, 'fixtures/test.css');
stream.on('data', function (data) {
count++;
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should create css statistics as Markdown', function (done) {
let count = 0;
let stream = stylestats({
type: 'md',
outfile: true
});
let fp = path.join(__dirname, 'fixtures/test.css');
let dest = path.join(__dirname, 'fixtures/test.md');
stream.on('data', function (file) {
count++;
assert.equal(file.path, dest);
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should log css statistics as custom template format', function (done) {
let count = 0;
let stream = stylestats({
type: 'template',
templateFile: path.join(__dirname, 'fixtures/template.hbs')
});
let fp = path.join(__dirname, 'fixtures/test.css');
stream.on('data', function (data) {
count++;
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should create css statistics as custom template format', function (done) {
let count = 0;
let stream = stylestats({
type: 'template',
templateFile: path.join(__dirname, 'fixtures/template.hbs'),
outfile: true
});
let fp = path.join(__dirname, 'fixtures/test.css');
let dest = path.join(__dirname, 'fixtures/test.html');
stream.on('data', function (file) {
count++;
assert.equal(file.path, dest);
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
it('should create css statistics as custom template format with specific extension', function (done) {
let count = 0;
let stream = stylestats({
type: 'template',
templateFile: path.join(__dirname, 'fixtures/template.hbs'),
extension: '.foo',
outfile: true
});
let fp = path.join(__dirname, 'fixtures/test.css');
let dest = path.join(__dirname, 'fixtures/test.foo');
stream.on('data', function (file) {
count++;
assert.equal(file.path, dest);
});
stream.on('end', function (error) {
assert.strictEqual(count, 1);
done();
});
stream.write(new gutil.File({
path: fp,
contents: fs.readFileSync(fp)
}));
stream.end();
});
});
|
#!/usr/bin/env node
// @flow
process.env.NODE_ENV = 'test';
process.env.BABEL_ENV = 'test';
process.on('unhandledRejection', err => {
throw err;
});
const jest = require('jest');
const fs = require('fs');
const path = require('path');
const argv = process.argv.slice(2);
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
argv.push('--watch');
} else {
argv.push('--forceExit');
}
const setupTestsFile = fs.existsSync(path.resolve(process.cwd(), 'src/setupTests.js'))
? '<rootDir>/src/setupTests.js'
: undefined;
argv.push(
'--config',
JSON.stringify({
collectCoverageFrom: ['src/**/*.{js,jsx}'],
setupFiles: [path.resolve(__dirname, './polyfills/server.js')],
setupTestFrameworkScriptFile: setupTestsFile,
testMatch: [
'<rootDir>/src/**/__tests__/**/*.js?(x)',
'<rootDir>/src/**/?(*.)(spec|test).js?(x)',
],
testEnvironment: 'node',
testURL: 'http://localhost',
transform: {
'^.+\\.(js|jsx)$': path.resolve(__dirname, 'jest/babelTransform.js'),
'^.+\\.css$': path.resolve(__dirname, 'jest/cssTransform.js'),
'^(?!.*\\.(js|jsx|css|json)$)': path.resolve(__dirname, 'jest/fileTransform.js'),
},
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'],
}),
);
jest.run(argv);
|
module.exports = function(grunt) {
require('load-grunt-config')(grunt, {
config: {
info: grunt.file.readJSON('bower.json'),
name: 'notice'
}
});
};
|
$(document).ready(function () {
"use strict";
var fn = {
// Launch Functions
Launch: function () {
window.app = {};
fn.App();
fn.Gui();
},
Gui: function() {
// init gui in a clear state
window.app.gui = PiMillGui();
window.app.gui.init();
},
App: function() {
window.app.socket = PiMillClient();
window.app.socket.connect();
}
};
$(document).ready(function () {
fn.Launch();
});
}); |
/*
*
* Css5
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { createStructuredSelector } from 'reselect';
import makeSelectCss5 from './selectors';
import Cube from './cube';
import Ball from './ball';
export class Css5 extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<Helmet
title="Css5"
meta={[
{ name: 'description', content: 'Description of Css5' },
]}
/>
<Ball />
</div>
);
}
}
Css5.propTypes = {
dispatch: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
Css5: makeSelectCss5(),
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Css5);
|
/** Components that are used in .mdx files */
import RandomImage from './RandomImage';
import FeaturedPost from './FeaturedPost';
export { RandomImage, FeaturedPost };
|
import React from 'react'
import PropTypes from 'prop-types'
import CompanionInfo from './companion-info/CompanionInfo'
import AddFilesInfo from './add-files-info/AddFilesInfo'
const InfoBoxes = ({ isRoot, isCompanion, filesExist }) => (
<div>
{ isRoot && isCompanion && <CompanionInfo /> }
{ isRoot && !filesExist && !isCompanion && <AddFilesInfo /> }
</div>
)
InfoBoxes.propTypes = {
isRoot: PropTypes.bool.isRequired,
isCompanion: PropTypes.bool.isRequired,
filesExist: PropTypes.bool.isRequired
}
export default InfoBoxes
|
// Author: [email protected] (https://github.com/technet/brackets.coffeescriptcompiler, http://tutewall.com)
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, $ */
define(function (require, exports, module) {
"use strict";
var CF_DOMAIN_NAME = "technet.csdomain",
DOMAIN_PATH = "node/cfdomain",
CF_VERSION = "getVersion",
CF_COMPILE = "compile";
var ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
DocumentManager = brackets.getModule('document/DocumentManager'),
FileUtils = brackets.getModule('file/FileUtils'),
FileSystem = brackets.getModule('filesystem/FileSystem'),
AppInit = brackets.getModule("utils/AppInit"),
NodeDomain = brackets.getModule("utils/NodeDomain");
var cfDomain = new NodeDomain(CF_DOMAIN_NAME, ExtensionUtils.getModulePath(module, DOMAIN_PATH));
var REGX_CSOPTIONS_TAG = /cfcoptions/i,
REGX_CSOPTIONS = /\{.*\}/;
function writeJSFile(fileData) {
var destFile = FileSystem.getFileForPath(fileData.destFilePath);
FileUtils.writeText(destFile, fileData.jsCode, true);
// Possible Issue: https://github.com/adobe/brackets/issues/8115
}
function compile(fileData) {
cfDomain.exec(CF_COMPILE, fileData.csCode, fileData.compileOptions)
.done(function (jsCode) {
fileData.jsCode = jsCode;
writeJSFile(fileData);
})
.fail(function (error) {
fileData.jsCode = error;
writeJSFile(fileData);
});
}
function setDefaultOptions(fileData) {
}
function setOptions(optionObject, fileData) {
if (optionObject.out) {
var trimmedOut = optionObject.out.trim();
if (trimmedOut.length > 0) {
fileData.destFilePath = fileData.sourceFolder + ((/\.js$/i).test(trimmedOut) ? trimmedOut : (((/\/$/).test(trimmedOut) ? trimmedOut : trimmedOut + "/") + FileUtils.getFilenameWithoutExtension(fileData.fileName) + ".js"));
}
}
}
function getOptionsFromText(fileData, document) {
var i = 0,
found = false,
eof = false;
var lineData;
var optionString;
while (!found && !eof) {
lineData = document.getLine(i++);
if (lineData !== undefined) {
var trimmed = lineData.trim();
if (trimmed.length > 0 && trimmed.charAt(0) === '#' && REGX_CSOPTIONS_TAG.test(trimmed)) {
optionString = REGX_CSOPTIONS.exec(trimmed);
found = true;
} else if (trimmed.length > 0) {
eof = true; // Don't check beyond first non empty line to figure out compile options
}
} else {
eof = true;
}
}
if (found && optionString) {
try {
var optionObject = JSON.parse(optionString);
setOptions(optionObject, fileData);
} catch (ex) {
setDefaultOptions(fileData);
}
} else {
setDefaultOptions(fileData);
}
}
function compileAndSave(document) {
var text = document.getText();
var fileData = {};
fileData.compileOptions = {};
fileData.csCode = text;
fileData.sourcefilePath = document.file.fullPath;
fileData.sourceFolder = FileUtils.getDirectoryPath(fileData.sourcefilePath);
fileData.destFilePath = FileUtils.getFilenameWithoutExtension(fileData.sourcefilePath) + ".js";
fileData.fileName = FileUtils.getBaseName(fileData.sourcefilePath);
getOptionsFromText(fileData, document);
compile(fileData);
}
function onDocumentSavedEventHandler(event, document) {
var documentFile = document.file;
var filePath = documentFile.fullPath;
if (FileUtils.getFileExtension(filePath).toLowerCase() === "coffee") {
// We have found coffeescript file, it's time to compile...
compileAndSave(document);
}
}
AppInit.appReady(function () {
$(DocumentManager).on('documentSaved', onDocumentSavedEventHandler);
});
});
|
/**
* JavaScript project for accessing and normalizing the accelerometer and gyroscope data on mobile devices
*
* @author Doruk Eker <[email protected]>
* @copyright Doruk Eker <http://dorukeker.com>
* @version 2.0.6
* @license MIT License | http://opensource.org/licenses/MIT
*/
(function(root, factory) {
var e = {
GyroNorm: factory(),
};
if (typeof define === 'function' && define.amd) {
define(function() {
return e;
});
} else if (typeof module === 'object' && module.exports) {
module.exports = e;
} else {
root.GyroNorm = e.GyroNorm;
}
}(this, function() {
/* Constants */
var GAME = 'game';
var WORLD = 'world';
var DEVICE_ORIENTATION = 'deviceorientation';
var ACCELERATION = 'acceleration';
var ACCELERATION_INCLUDING_GRAVITY = 'accelerationinludinggravity';
var ROTATION_RATE = 'rotationrate';
/*-------------------------------------------------------*/
/* PRIVATE VARIABLES */
var _interval = null; // Timer to return values
var _isCalibrating = false; // Flag if calibrating
var _calibrationValue = 0; // Alpha offset value
var _gravityCoefficient = 0; // Coefficient to normalze gravity related values
var _isRunning = false; // Boolean value if GyroNorm is tracking
var _isReady = false; // Boolean value if GyroNorm is is initialized
var _do = null; // Object to store the device orientation values
var _dm = null; // Object to store the device motion values
/* OPTIONS */
var _frequency = 50; // Frequency for the return data in milliseconds
var _gravityNormalized = true; // Flag if to normalize gravity values
var _orientationBase = GAME; // Can be GyroNorm.GAME or GyroNorm.WORLD. GyroNorm.GAME returns orientation values with respect to the head direction of the device. GyroNorm.WORLD returns the orientation values with respect to the actual north direction of the world.
var _decimalCount = 2; // Number of digits after the decimals point for the return values
var _logger = null; // Function to callback on error. There is no default value. It can only be set by the user on gn.init()
var _screenAdjusted = false; // If set to true it will return screen adjusted values. (e.g. On a horizontal orientation of a mobile device, the head would be one of the sides, instead of the actual head of the device.)
var _values = {
do: {
alpha: 0,
beta: 0,
gamma: 0,
absolute: false
},
dm: {
x: 0,
y: 0,
z: 0,
gx: 0,
gy: 0,
gz: 0,
alpha: 0,
beta: 0,
gamma: 0
}
}
/*-------------------------------------------------------*/
/* PUBLIC FUNCTIONS */
/*
*
* Constructor function
*
*/
var GyroNorm = function(options) {}
/* Constants */
GyroNorm.GAME = GAME;
GyroNorm.WORLD = WORLD;
GyroNorm.DEVICE_ORIENTATION = DEVICE_ORIENTATION;
GyroNorm.ACCELERATION = ACCELERATION;
GyroNorm.ACCELERATION_INCLUDING_GRAVITY = ACCELERATION_INCLUDING_GRAVITY;
GyroNorm.ROTATION_RATE = ROTATION_RATE;
/*
*
* Initialize GyroNorm instance function
*
* @param object options - values are as follows. If set in the init function they overwrite the default option values
* @param int options.frequency
* @param boolean options.gravityNormalized
* @param boolean options.orientationBase
* @param boolean options.decimalCount
* @param function options.logger
* @param function options.screenAdjusted
*
*/
GyroNorm.prototype.init = function(options) {
// Assign options that are passed with the constructor function
if (options && options.frequency) _frequency = options.frequency;
if (options && typeof options.gravityNormalized === 'boolean') _gravityNormalized = options.gravityNormalized;
if (options && options.orientationBase) _orientationBase = options.orientationBase;
if (options && typeof options.decimalCount === 'number' && options.decimalCount >= 0) _decimalCount = parseInt(options.decimalCount);
if (options && options.logger) _logger = options.logger;
if (options && options.screenAdjusted) _screenAdjusted = options.screenAdjusted;
var deviceOrientationPromise = new FULLTILT.getDeviceOrientation({ 'type': _orientationBase }).then(function(controller) {
_do = controller;
});
var deviceMotionPromise = new FULLTILT.getDeviceMotion().then(function(controller) {
_dm = controller;
// Set gravity coefficient
_gravityCoefficient = (_dm.getScreenAdjustedAccelerationIncludingGravity().z > 0) ? -1 : 1;
});
return Promise.all([deviceOrientationPromise, deviceMotionPromise]).then(function() {
_isReady = true;
});
}
/*
*
* Stops all the tracking and listening on the window objects
*
*/
GyroNorm.prototype.end = function() {
try {
_isReady = false;
this.stop();
_dm.stop();
_do.stop();
} catch(err){
log(err);
}
}
/*
*
* Starts tracking the values
*
* @param function callback - Callback function to read the values
*
*/
GyroNorm.prototype.start = function(callback) {
if (!_isReady) {
log({ message: 'GyroNorm is not initialized yet. First call the "init()" function.', code: 1 });
return;
}
_interval = setInterval(function() {
callback(snapShot());
}, _frequency);
_isRunning = true;
}
/*
*
* Stops tracking the values
*
*/
GyroNorm.prototype.stop = function() {
if (_interval) {
clearInterval(_interval);
_isRunning = false;
}
}
/*
*
* Toggles if to normalize gravity related values
*
* @param boolean flag
*
*/
GyroNorm.prototype.normalizeGravity = function(flag) {
_gravityNormalized = (flag) ? true : false;
}
/*
*
* Sets the current head direction as alpha = 0
* Can only be used if device orientation is being tracked, values are not screen adjusted, value type is GyroNorm.EULER and orientation base is GyroNorm.GAME
*
* @return: If head direction is set successfully returns true, else false
*
*/
GyroNorm.prototype.setHeadDirection = function() {
if (_screenAdjusted || _orientationBase === WORLD) {
return false;
}
_calibrationValue = _do.getFixedFrameEuler().alpha;
return true;
}
/*
*
* Sets the log function
*
*/
GyroNorm.prototype.startLogging = function(logger) {
if (logger) {
_logger = logger;
}
}
/*
*
* Sets the log function to null which stops the logging
*
*/
GyroNorm.prototype.stopLogging = function() {
_logger = null;
}
/*
*
* Returns if certain type of event is available on the device
*
* @param string _eventType - possible values are "deviceorientation" , "devicemotion" , "compassneedscalibration"
*
* @return true if event is available false if not
*
*/
GyroNorm.prototype.isAvailable = function(_eventType) {
var doSnapShot = _do.getScreenAdjustedEuler();
var accSnapShot = _dm.getScreenAdjustedAcceleration();
var accGraSnapShot = _dm.getScreenAdjustedAccelerationIncludingGravity();
var rotRateSnapShot = _dm.getScreenAdjustedRotationRate();
switch (_eventType) {
case DEVICE_ORIENTATION:
return ((doSnapShot.alpha && doSnapShot.alpha !== null) && (doSnapShot.beta && doSnapShot.beta !== null) && (doSnapShot.gamma && doSnapShot.gamma !== null));
break;
case ACCELERATION:
return (accSnapShot && accSnapShot.x && accSnapShot.y && accSnapShot.z);
break;
case ACCELERATION_INCLUDING_GRAVITY:
return (accGraSnapShot && accGraSnapShot.x && accGraSnapShot.y && accGraSnapShot.z);
break;
case ROTATION_RATE:
return (rotRateSnapShot && rotRateSnapShot.alpha && rotRateSnapShot.beta && rotRateSnapShot.gamma);
break;
default:
return {
deviceOrientationAvailable: ((doSnapShot.alpha && doSnapShot.alpha !== null) && (doSnapShot.beta && doSnapShot.beta !== null) && (doSnapShot.gamma && doSnapShot.gamma !== null)),
accelerationAvailable: (accSnapShot && accSnapShot.x && accSnapShot.y && accSnapShot.z),
accelerationIncludingGravityAvailable: (accGraSnapShot && accGraSnapShot.x && accGraSnapShot.y && accGraSnapShot.z),
rotationRateAvailable: (rotRateSnapShot && rotRateSnapShot.alpha && rotRateSnapShot.beta && rotRateSnapShot.gamma)
}
break;
}
}
/*
*
* Returns boolean value if the GyroNorm is running
*
*/
GyroNorm.prototype.isRunning = function() {
return _isRunning;
}
/*-------------------------------------------------------*/
/* PRIVATE FUNCTIONS */
/*
*
* Utility function to round with digits after the decimal point
*
* @param float number - the original number to round
*
*/
function rnd(number) {
return Math.round(number * Math.pow(10, _decimalCount)) / Math.pow(10, _decimalCount);
}
/*
*
* Starts calibration
*
*/
function calibrate() {
_isCalibrating = true;
_calibrationValues = new Array();
}
/*
*
* Takes a snapshot of the current deviceo orientaion and device motion values
*
*/
function snapShot() {
var doSnapShot = {};
if (_screenAdjusted) {
doSnapShot = _do.getScreenAdjustedEuler();
} else {
doSnapShot = _do.getFixedFrameEuler();
}
var accSnapShot = _dm.getScreenAdjustedAcceleration();
var accGraSnapShot = _dm.getScreenAdjustedAccelerationIncludingGravity();
var rotRateSnapShot = _dm.getScreenAdjustedRotationRate();
var alphaToSend = 0;
if (_orientationBase === GAME) {
alphaToSend = doSnapShot.alpha - _calibrationValue;
alphaToSend = (alphaToSend < 0) ? (360 - Math.abs(alphaToSend)) : alphaToSend;
} else {
alphaToSend = doSnapShot.alpha;
}
var snapShot = {
do: {
alpha: rnd(alphaToSend),
beta: rnd(doSnapShot.beta),
gamma: rnd(doSnapShot.gamma),
absolute: _do.isAbsolute()
},
dm: {
x: rnd(accSnapShot.x),
y: rnd(accSnapShot.y),
z: rnd(accSnapShot.z),
gx: rnd(accGraSnapShot.x),
gy: rnd(accGraSnapShot.y),
gz: rnd(accGraSnapShot.z),
alpha: rnd(rotRateSnapShot.alpha),
beta: rnd(rotRateSnapShot.beta),
gamma: rnd(rotRateSnapShot.gamma)
}
};
// Normalize gravity
if (_gravityNormalized) {
snapShot.dm.gx *= _gravityCoefficient;
snapShot.dm.gy *= _gravityCoefficient;
snapShot.dm.gz *= _gravityCoefficient;
snapShot.dm.x *= _gravityCoefficient;
snapShot.dm.y *= _gravityCoefficient;
snapShot.dm.z *= _gravityCoefficient;
}
return snapShot;
}
/*
*
* Starts listening to orientation event on the window object
*
*/
function log(err) {
if (_logger) {
if (typeof(err) == 'string') {
err = { message: err, code: 0 }
}
_logger(err);
}
}
return GyroNorm;
}));
|
var CachedObjectVO = function() {
this.id = null;
this.initialize = function(id) {
try {
if (id !== null)
this.id = id;
} catch(error) {
Utils.alert("CachedObjectVO/constructor Error: "+error.message,Utils.LOG_LEVEL_ERROR);
}
};
};
CachedObjectVO = new Class(new CachedObjectVO());
|
// var Task = Backbone.Model.extend({
// url : function(){
// var base = 'tasks';
// if (this.isNew()) return base;
// return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
// }
// }); |
version https://git-lfs.github.com/spec/v1
oid sha256:7442a5df94d8841110ff99d08aed99d88f5f15d6c399dc5e8ed022bbad4f541a
size 148
|
var express = require('express');
var http = require('http');
var personApiRouter = require('./routes/apiRouter');
var bodyParser = require('body-parser');
var app = express();
app
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: true}))
// provide simple REST API endpoints via a dedicated api apiRouter
.use('/api', personApiRouter)
// serve up the public folder as static content
.use('/', express.static('./public'));
module.exports = app;
// run the server
http.createServer(app).listen(80);
|
var artistsM = angular.module('ArtistsM', ['WebserviceModule', 'SpireFactoryModule']);
artistsM.service("ArtistsService", ['Webservice','SpireFactory','$rootScope',
function(Webservice, SpireFactory, $rootScope){
var ArtistsService = this;
this.artistsArray = [];
this.artistsHash = {};
/*Set Artists stuff*/
this.setArtistsArrayAndHash = function(){
Webservice.getArtists(true)
.success(function(data, status){
ArtistsService.artistsArray = SpireFactory.getArtistArray(data);
ArtistsService.artistsHash = SpireFactory.getArtistHash(data);
$rootScope.$broadcast("setArtists");
})
.error(function(data, status){
Webservice.handleHttpError(data, status);
});
};
this.setArtistsArrayAndHash();
}]); |
(function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == "function" && require;
if (!u && a)return a(o, !0);
if (i)return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw f.code = "MODULE_NOT_FOUND", f
}
var l = n[o] = {exports: {}};
t[o][0].call(l.exports, function (e) {
var n = t[o][1][e];
return s(n ? n : e)
}, l, l.exports, e, t, n, r)
}
return n[o].exports
}
var i = typeof require == "function" && require;
for (var o = 0; o < r.length; o++)s(r[o]);
return s
})({
1: [function (require, module, exports) {
'use strict';
$.extend(true, window, {Slick: {Plugins: {ColGroup: ColGroup}}});
function ColGroup() {
var _uid = void 0, _handler = new Slick.EventHandler(), _cache = {};
function toArray(list) {
var i, array = [];
for (i=0; i<list.length;i++) {array[i] = list[i];}
return array;
}
function init(grid) {
_uid = grid.getContainerNode().className.match(/(?: |^)slickgrid_(\d+)(?!\w)/)[1];
_handler.subscribe(grid.onColumnsResized, handleColumnsResized);
var cache = _cache[_uid] = {};
cache.grid = grid;
cache.headerScrollerEl = grid.getContainerNode().querySelector('.slick-header');
var headerColumns = toArray(cache.headerScrollerEl.querySelectorAll('.slick-header-columns')),
filteredColumns = headerColumns && headerColumns.length ? headerColumns.filter(function(col) {
return col.children && col.children.length > 0 ? true : false;
}) : null;
cache.origHeadersEl = filteredColumns && filteredColumns.length > 0 ? filteredColumns[0] :
cache.headerScrollerEl.querySelectorAll('.slick-header-columns');
var originalColumnDef = grid.getColumns(), v = measureVCellPaddingAndBorder();
cache.origHeadersEl.style.height = v.height + v.heightDiff + 'px';
cache.origHeadersEl.style.overflow = 'visible';
grid.setColumns = function (originalSetColumns) {
return function (columnsDef) {
_uid = this.getContainerNode().className.match(/(?: |^)slickgrid_(\d+)(?!\w)/)[1];
var cache = _cache[_uid];
cache.columnsDef = columnsDef;
cache.innerColumnsDef = genInnerColumnsDef(columnsDef);
cache.columnsDefByLevel = genColumnsDefByLevel(grid.getColumns());
originalSetColumns(cache.innerColumnsDef);
createColumnGroupHeaderRow();
createColumnGroupHeaders();
applyColumnGroupWidths();
};
}(grid.setColumns);
grid.getColumns = function () {
return _cache[_uid].columnsDef;
};
grid.destroy = function (originalDestroy) {
return function () {
var styleEl = _cache[_uid].styleEl;
styleEl.parentNode.removeChild(styleEl);
originalDestroy();
};
}(grid.destroy);
[
'invalidate',
'render'
].forEach(function (fnName) {
grid[fnName] = function (origFn) {
return function () {
origFn(arguments);
applyColumnGroupWidths();
};
}(grid[fnName]);
});
if (grid.getOptions()['explicitInitialization']) {
grid.init = function (originalInit) {
return function () {
_uid = this.getContainerNode().className.match(/(?: |^)slickgrid_(\d+)(?!\w)/)[1];
originalInit();
measureHCellPaddingAndBorder = memoizeMeasureHCellPaddingAndBorder();
grid.setColumns(originalColumnDef);
createCssRules();
};
}(grid.init);
} else {
measureHCellPaddingAndBorder = memoizeMeasureHCellPaddingAndBorder();
grid.setColumns(originalColumnDef);
createCssRules();
}
}
function handleColumnsResized() {
applyColumnGroupWidths();
}
var measureHCellPaddingAndBorder;
function memoizeMeasureHCellPaddingAndBorder() {
var headerColumnWidthDiff = void 0;
return function () {
if (headerColumnWidthDiff != null)
return headerColumnWidthDiff;
var h = [
'paddingLeft',
'paddingRight',
'borderLeftWidth',
'borderRightWidth'
],
$r = $(_cache[_uid].origHeadersEl),
$el = $('<div class="ui-state-default slick-header-column" id="" style="visibility:hidden">-</div>').appendTo($r),
widthDiff = 0;
h.forEach(function (val) {
widthDiff += parseFloat($el.css(val)) || 0;
});
$el.remove();
headerColumnWidthDiff = widthDiff;
return headerColumnWidthDiff;
};
}
function measureVCellPaddingAndBorder() {
var v = [
'borderTopWidth',
'borderBottomWidth',
'paddingTop',
'paddingBottom'
], $canvas = $(_cache[_uid].grid.getCanvasNode()), $r = $('<div class="slick-row" />').appendTo($canvas), $el = $('<div class="slick-cell" id="" style="visibility:hidden">-</div>').appendTo($r), height = void 0, heightDiff = 0;
height = parseFloat($el.css('height'));
v.forEach(function (val) {
heightDiff += parseFloat($el.css(val)) || 0;
});
$r.remove();
return {
height: height,
heightDiff: heightDiff
};
}
function applyColumnGroupWidths() {
var cache = _cache[_uid],
origHeadersWidth = getHeadersWidth(),
groupHeadersEl = cache.groupHeadersEl,
maxLevel = groupHeadersEl.length;
for (var r = 0; r < maxLevel; r++) {
groupHeadersEl[r].style.width = origHeadersWidth;
}
var hPadding = measureHCellPaddingAndBorder();
setWidthRecursively(cache.columnsDef);
function setWidthRecursively(columnsDef) {
var level = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];
var offsetsByLevel = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
for (var c = 0, C = columnsDef.length; c < C; c++) {
var column = columnsDef[c], columnSelector = '#slickgrid_' + (_uid + String(column.id).replace(/(#|,|\.)/g, '\\$1')),
columnEl = cache.headerScrollerEl.querySelector(columnSelector);
if (hasChildren(column)) {
setWidthRecursively(column.children, level + 1, offsetsByLevel);
var width = 0;
for (var c2 = 0, C2 = column.children.length; c2 < C2; c2++) {
var _columnSelector = '#slickgrid_' + (_uid + String(column.children[c2].id).replace(/(#|,|\.)/g, '\\$1')), _columnEl = cache.headerScrollerEl.querySelector(_columnSelector);
width += _columnEl.offsetWidth;
}
columnEl.style.width = width - hPadding + 'px';
columnEl.style.marginLeft = (offsetsByLevel[level] || 0) + 'px';
offsetsByLevel[level] = 0;
} else {
for (var l = level; l < maxLevel; l++) {
offsetsByLevel[l] = (offsetsByLevel[l] || 0) + columnEl.offsetWidth;
}
}
}
}
}
function getHeadersWidth() {
return _cache[_uid].origHeadersEl.style.width;
}
function createColumnGroupHeaderRow() {
var cache = _cache[_uid], headerScrollerEl = cache.headerScrollerEl, groupHeadersEl = cache.groupHeadersEl = cache.groupHeadersEl || [], columnsDefByLevel = cache.columnsDefByLevel;
for (var i = 0, len = groupHeadersEl.length; i < len; i++) {
headerScrollerEl.removeChild(cache.groupHeadersEl[i]);
}
var fragment = document.createDocumentFragment();
for (var _i = 0, _len = columnsDefByLevel.length; _i < _len - 1; _i++) {
var tmp = document.createElement('div');
tmp.innerHTML = '<div class="slick-header-columns slick-header-columns-groups" style="left: -1000px" unselectable="on"></div>';
groupHeadersEl[_i] = tmp.childNodes[0];
fragment.appendChild(groupHeadersEl[_i]);
}
headerScrollerEl.insertBefore(fragment, cache.headerScrollerEl.firstChild);
}
function createColumnGroupHeaders() {
var cache = _cache[_uid], columnsDefByLevel = cache.columnsDefByLevel;
for (var r = 0, R = cache.groupHeadersEl.length; r < R; r++) {
var toCreateColumnsDef = columnsDefByLevel[r], columnsGroupHtml = '';
for (var c = 0, C = toCreateColumnsDef.length; c < C; c++) {
var column = toCreateColumnsDef[c];
if (hasChildren(column)) {
columnsGroupHtml += '\n<div class="ui-state-default slick-header-column slick-header-columns-group ' + (column.headerCssClass || '') + '"\n id="slickgrid_' + (_uid + column.id) + '"\n title="' + column.toolTip + '">\n <span class="slick-column-name">' + (hasChildren(column) ? column.name || '' : '') + '</span>\n</div>';
} else {
var tipColumn = cache.origHeadersEl.querySelector('#slickgrid_' + (_uid + String(column.id).replace(/(#|,|\.)/g, '\\$1')));
if (tipColumn) {
tipColumn.className += ' h' + (columnsDefByLevel.length - r);
}
}
}
cache.groupHeadersEl[r].innerHTML = columnsGroupHtml;
}
cache.grid.resizeCanvas();
}
function createCssRules() {
var cache = _cache[_uid], v = measureVCellPaddingAndBorder(), rules = ['.hidden {visibility: hidden;}'], maxLevel = cache.columnsDefByLevel.length;
for (var i = 1; i <= maxLevel; i++) {
rules.push('\n.slick-header-column.h' + i + ' {\n margin: ' + (1 - i) * (v.height + v.heightDiff) + 'px 0 0 0;\n font-size: inherit;\n height: ' + (i * (v.height + v.heightDiff) - v.heightDiff * 2 + 1) + 'px;\n}');
}
var styleEl = cache.styleEl = $('<style type="text/css" rel="stylesheet" />').appendTo($('head'))[0];
if (styleEl.styleSheet) {
styleEl.styleSheet.cssText = rules.join(' ');
} else {
styleEl.appendChild(document.createTextNode(rules.join(' ')));
}
}
function genColumnsDefByLevel(columns) {
var depth = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];
var acc = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2];
for (var i = 0, len = columns.length; i < len; i++) {
var column = columns[i];
acc[depth] = acc[depth] || [];
acc[depth].push(column);
if (hasChildren(column)) {
genColumnsDefByLevel(column.children, depth + 1, acc);
}
}
return acc;
}
function genInnerColumnsDef(columns) {
var acc = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
var first = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
for (var i = 0, len = columns.length; i < len; i++) {
var column = columns[i];
if (!hasChildren(column)) {
acc.push(column);
} else {
genInnerColumnsDef(column.children, acc, false);
}
}
return acc;
}
function hasChildren(column) {
return column.children && column.children.length > 0 && Object.prototype.toString.apply(column.children) === '[object Array]' || false;
}
$.extend(this, {init: init});
}
}, {}]
}, {}, [1]);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.