code stringlengths 2 1.05M |
|---|
var twilio = require('twilio'),
express = require('express'),
orderPizza = require('./orderpizza'),
kegapi = require('./kegapi'),
sendText = require('./sendText');
var app = express();
var textResponse = function(request, response) {
console.log('got here');
if (twilio.validateExpressRequest(request, '08b1eaf92fd66749470c93088253c7b4', { url: 'http://samshreds.com:7890/text' })) {
response.header('Content-Type', 'text/xml');
var body = request.param('Body').trim();
var from = request.param('From');
console.log(body);
response.send('<Response><Sms>LOL.</Sms></Response>');
} else {
response.statusCode = 403;
response.render('forbidden');
}
};
app.get('/text', textResponse);
app.listen('7890', function() {
console.log('Visit http://localhost:7890/ in your browser to see your TwiML document!');
});
setInterval(function() {
kegapi.getDrinks(function(volume) {
if(volume > 0) {
sendText('+16107616189', 'I noticed you have been drinking from the keg a lot! Do you want some pizza?.', function() {});
orderPizza();
}
});
}, 60000);
|
var group__cobalt__core__thread__info =
[
[ "XNBREAK", "group__cobalt__core__thread__info.html#ga6aa575e1a99b9c931d3b1feb8bc7a36f", null ],
[ "XNCANCELD", "group__cobalt__core__thread__info.html#gac0c8d3c13b2ea3ceb9c8b474b9e52f01", null ],
[ "XNDESCENT", "group__cobalt__core__thread__info.html#gae94044c60457321110d1b53db4df6320", null ],
[ "XNKICKED", "group__cobalt__core__thread__info.html#gab6ee242aa7e0f98235c5099cd345984c", null ],
[ "XNLBALERT", "group__cobalt__core__thread__info.html#gac9a2238978202123c8f045d1529c59a2", null ],
[ "XNMOVED", "group__cobalt__core__thread__info.html#ga2cb10fa1e4e888e3e23798b42deb1608", null ],
[ "XNPIALERT", "group__cobalt__core__thread__info.html#gab657db6c8e6a0444a27104bc983da285", null ],
[ "XNRMID", "group__cobalt__core__thread__info.html#gab07d9dea73645dbba353dc2452c15b40", null ],
[ "XNROBBED", "group__cobalt__core__thread__info.html#gad28db508d297929d6a0ec30964639d65", null ],
[ "XNSYSRST", "group__cobalt__core__thread__info.html#ga94d1dbd5288133810ab4d27c63f39ff1", null ],
[ "XNTIMEO", "group__cobalt__core__thread__info.html#gaa11d7fc754db50d3a1f1e41611d324e9", null ],
[ "XNWAKEN", "group__cobalt__core__thread__info.html#ga53e49fa49b312e5266b31d66f7465d44", null ]
]; |
(function () {
'use strict';
angular
.module('app')
.controller('ServiceCenterIndexController', ServiceCenterIndexController);
ServiceCenterIndexController.$inject = ['$log'];
/* @ngInject */
function ServiceCenterIndexController($log) {
/* jshint validthis: true */
var vm = this;
vm.activate = activate;
vm.title = 'ServiceCenterIndexController';
activate();
////////////////
function activate() {
$log.info('Activated ServiceCenterIndexController');
}
}
})(); |
//http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-match-all-query.html
var ESQ = require('../esq');
var esq = new ESQ();
esq.query('match_all', { });
console.log(JSON.stringify(esq.getQuery(), null, 2));
esq = new ESQ();
esq.query('match_all', { boost: 1.2 });
console.log(JSON.stringify(esq.getQuery(), null, 2));
|
var group__manhattan__space__container =
[
[ "distance", "group__manhattan__space__container.html#ga750b3a1e76a42ec52d2cadcc5ab8ff73", null ],
[ "norm", "group__manhattan__space__container.html#gaed3fca875aa3c37c377abaab63d55e3b", null ],
[ "squared_distance", "group__manhattan__space__container.html#ga27c404a932fab3cd47727b40e7d79d57", null ],
[ "squared_norm", "group__manhattan__space__container.html#ga11c6b9eb892c37485974210579cc548e", null ]
]; |
'use strict';
export default class StudentEventsCtrl {
/*@ngInject*/
constructor($scope, $location, User, SectionEvent) {
SectionEvent.getAll({onlyUserSections:'me',withEventInfo:true,withSection:true},(events)=>{
$scope.events = events;
$scope.eventsArray = Object.keys(events)
.map(eventId => events[eventId])
.filter(evnt => evnt._id)
.reduce((a,b) => a.concat(b), []);
});
$scope.goToEvent = (event) => {
$location.path("/events/" + event._id);
};
}
}
|
var _ = require('lodash');
var fs = require('fs');
var formatData = require('./format-data');
var moment = require('moment')
module.exports = function (smocks) {
var harOptions = smocks.options && smocks.options.har;
return function (request, reply, respondWithConfig) {
var data = request.payload;
if (data.contents) {
var contents = JSON.parse(data.contents);
var fileName = data.fileName;
var callData = extractCalls(contents, harOptions);
var harIndex = -1;
smocks.state.userState(request)['__har'] = {
startIndex: 0,
fileName: fileName,
index: harIndex,
calls: callData.calls,
minTime: callData.minTime,
maxTime: callData.maxTime
};
}
reply(respondWithConfig ? formatData(smocks, request) : {});
};
};
var urlMatch = /^[^:]*:?\/?\/?[^/]+([^\?]*)\??(.*)/;
function extractCalls(harContents, harOptions) {
var minTime = -1;
var maxTime = -1;
var id = 1;
var calls = _.compact(harContents.log.entries.map(function (data) {
var type = data.response.content.mimeType;
// we're only going to do html and json
if (type === 'application/json') {
try {
var urlInfo = data.request.url.match(urlMatch);
var startTime = Math.floor(moment.utc(data.startedDateTime).valueOf());
if (minTime === -1 || minTime > startTime) {
minTime = startTime;
}
var endTime = startTime + data.time;
if (maxTime === -1 || maxTime < endTime) {
maxTime = endTime;
}
var rtn = {
id: id + '',
type: type,
time: Math.floor(data.time),
startTime: startTime,
method: data.request.method.toUpperCase(),
path: harOptions && harOptions.pathMapper ? harOptions.pathMapper(urlInfo[1]) : urlInfo[1],
queryString: data.request.queryString,
response: {
status: data.response.status,
headers: data.response.headers,
content: data.response.content
}
}
id++;
return rtn;
} catch (e) {}
}
}));
return {
minTime: minTime,
maxTime: maxTime,
calls: calls
}
}
|
/**
* @fileoverview Driver script for speech processing.
* @author aravart@cs.wisc.edu (Ara Vartanian), dliang@cs.wisc.edu (David Liang)
*/
goog.provide('SpeechGames');
goog.provide('SpeechGames.Speech');
goog.require('Blockly.Workspace');
goog.require('SpeechBlocks.Controller');
goog.require('SpeechBlocks.Interpreter');
goog.require('Turtle.Answers');
/**
* A global reference to the current workspace's controller.
* @public {SpeechBlocks.Controller}
*/
SpeechGames.controller = null;
/**
* A global reference to the workspace itself.
* @public {Blockly.Workspace}
*/
SpeechGames.workspace = null;
/**
* A global reference to the interpreter.
* @public {Blockly.Interpreter}
*/
SpeechGames.interpreter = null;
/**
* Maximum number of levels. Common to all apps.
* @public @const
*/
SpeechGames.MAX_LEVEL = 12;
/**
* User's current level (e.g. 5).
* @public
*/
SpeechGames.LEVEL = null;
/**
* Bind a function to a button's click event.
* On touch-enabled browsers, ontouchend is treated as equivalent to onclick.
* @param {!Element|string} el Button element or ID thereof.
* @param {!Function} func Event handler to bind.
* @public
*/
SpeechGames.bindClick = function(el, func) {
if (typeof el == 'string') {
el = document.getElementById(el);
}
el.addEventListener('click', func, true);
el.addEventListener('touchend', func, true);
};
/**
* Instantiates a speech object, used for controlling speech input to interpreter.
* @public
* @constructor
*/
SpeechGames.Speech = function() {
this.oldQ = null;
this.parseTimer = null;
this.previousRecognitionTime = null;
this.output = null;
this.timeout = null;
this.animating = false;
this.listening = false;
this.recognition = null;
this.mic_animate = 'assets/img/mic-animate.gif';
this.mic = 'assets/img/mic.gif';
this.parseTimer = null;
// this.misrecognized = [];
this.corrector_ = new Corrector();
};
/**
* Sets the interval that ensures the mic is lietning (when applicable).
* @private
*/
SpeechGames.Speech.prototype.setMicInterval_ = function() {
if (!window.location.origin.includes("file")) {
if (this.interval) {
clearInterval(this.interval);
}
this.interval = setInterval(function() {
if (!this.listening) {
this.listening = true;
this.startDictation_();
}
}.bind(this), 100);
} else {
console.log("Cannot use speech from local files!");
}
};
/**
* Hard replacements for certain phrases.
* @param {string} speech Utterance to be corrected.
* @return {string} The corrected utterance.
* @private
*/
SpeechGames.Speech.prototype.correctSpeech_ = function(speech) {
var workspaceState = SpeechGames.controller.workspaceState_;
var blockIds = Object.values(workspaceState.blockIds.map_.map_);
var blockValuesetMap = workspaceState.blockValuesetMap;
var blockTypeMap = new goog.structs.Map();
blockTypeMap.set('controls_if', 'if');
blockTypeMap.set('controls_repeat_ext', 'repeat');
blockTypeMap.set('turtle_turn_internal', 'turn');
blockTypeMap.set('turtle_move', 'move');
blockTypeMap.set('turtle_pen', 'pen');
blockTypeMap.set('turtle_repeat_internal', 'repeat');
blockTypeMap.set('turtle_colour_internal', 'color');
var blockTypes = Turtle.blockTypes[SpeechGames.LEVEL].slice(0);
for (var i = 0; i < blockTypes.length; i++) {
if (blockTypeMap.containsKey(blockTypes[i])) {
blockTypes[i] = blockTypeMap.get(blockTypes[i]);
}
}
return this.corrector_.correct(speech, blockIds, blockValuesetMap, blockTypes);
};
/**
* Restarts the listening for a new utterance.
* @private
*/
SpeechGames.Speech.prototype.startDictation_ = function() {
if (window.hasOwnProperty('webkitSpeechRecognition')) {
if (this.recognition) {
this.recognition.stop();
}
this.recognition = new webkitSpeechRecognition();
this.recognition.continuous = false;
this.recognition.interimResults = false;
this.recognition.lang = 'en-US';
this.recognition.onstart = function() {
this.listening = true;
if (!this.animating) {
this.animating = true;
document.getElementById('microphone').src = this.mic_animate;
}
}.bind(this);
this.recognition.onresult = function(e) {
this.recognition.stop();
this.rawSpeech = e.results[0][0].transcript.toLowerCase();
$('#q').val(this.rawSpeech);
this.parseSpeech_();
}.bind(this);
this.recognition.onerror = function(e) {
this.listening = false;
}.bind(this);
this.recognition.onend = function(e) {
this.listening = false;
}.bind(this);
this.recognition.start();
}
};
/**
* Toggles the listening from the microphone.
* @private
*/
SpeechGames.Speech.prototype.toggleDictation_ = function() {
if (this.listening) {
this.listening = !this.listening;
this.recognition.stop();
this.recognition = null;
this.animating = false;
document.getElementById('microphone').src = this.mic;
clearInterval(this.interval);
this.interval = null;
} else {
document.getElementById('microphone').src = this.mic_animate;
this.setMicInterval_();
}
};
/**
* Parses the input and sends the result to SpeechGames.interpreter. Then outputs the response
* to the user interface.
* @private
*/
SpeechGames.Speech.prototype.parseSpeech_ = function() {
this.previousRecognitionTime = Date.now();
this.oldQ = $('#q').val();
var result = false;
this.rawSpeech = $('#q').val();
try {
this.correctedSpeech = this.correctSpeech_(this.rawSpeech);
$('#q').val(this.correctedSpeech);
this.output = parser.parse(this.correctedSpeech);
this.response = this.interpretSpeech_(this.output);
clearTimeout(this.timeout);
this.result = true;
$("#user-message").hide().text('I heard "' + this.correctedSpeech + '"').fadeIn(200);
} catch (e) {
console.log(e);
if (e instanceof SpeechBlocks.UserError) {
$('#user-message').text(e.message);
} else {
$('#parse-message').attr('class', 'message error').text(this.buildErrorMessage_(e));
if (this.rawSpeech !== '') {
$('#user-message').hide().text('Sorry, I didn\'t understand.').fadeIn(200);
clearTimeout(this.timeout);
this.timeout = setTimeout(function(){
$('#user-message').hide().text("Awaiting your command!").fadeIn(200);
}.bind(this), 5000);
}
}
}
return result;
};
/**
* Calls the SpeechGames.interpreter's interpret function.
* @return {string} Response for user (i.e. 'Added a move block.').
* @private
*/
SpeechGames.Speech.prototype.interpretSpeech_ = function(parsedSpeech) {
if (parsedSpeech !== undefined) {
return SpeechGames.interpreter.interpret(parsedSpeech);
}
};
/**
* Schedule's the parsing to occur after a second of inactivity.
* @private
*/
SpeechGames.Speech.prototype.scheduleParse_ = function() {
if ($('#q').val() !== this.oldQ) {
if (this.parseTimer !== null) {
clearTimeout(this.parseTimer);
this.parseTimer = null;
}
this.parseTimer = setTimeout(function() {
this.parseSpeech_();
this.parseTimer = null;
}.bind(this), 1000);
}
};
/**
* Builds an error message.
* @param {exception} e Exception from which to build the error message.
* @return {exception} The error message.
*/
SpeechGames.Speech.prototype.buildErrorMessage_ = function(e) {
return e.location !== undefined ? 'Line ' + e.location.start.line + ', column ' + e.location.start.column + ': ' + e.message : e.message;
};
/**
* Extracts a parameter from the URL.
* If the parameter is absent default_value is returned.
* @param {!string} name The name of the parameter.
* @param {!string} defaultValue Value to return if paramater not found.
* @return {string} The parameter value or the default value if not found.
*/
SpeechGames.getStringParamFromURL_ = function(name, defaultValue) {
var val =
window.location.search.match(new RegExp('[?&]' + name + '=([^&]+)'));
return val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : defaultValue;
};
/**
* Extracts a numeric parameter from the URL.
* If the parameter is absent or less than min_value, min_value is
* returned. If it is greater than max_value, max_value is returned.
* @param {!string} name The name of the parameter.
* @param {!number} minValue The minimum legal value.
* @param {!number} maxValue The maximum legal value.
* @return {number} A number in the range [min_value, max_value].
*/
SpeechGames.getNumberParamFromURL_ = function(name, minValue, maxValue) {
var val = Number(SpeechGames.getStringParamFromURL_(name, 'NaN'));
return isNaN(val) ? minValue : goog.math.clamp(minValue, val, maxValue);
};
/**
* Generates code from the blockly workspace.
* @private
*/
SpeechGames.createCode_ = function() {
Blockly.JavaScript.addReservedWords('code');
return Blockly.JavaScript.workspaceToCode(SpeechGames.workspace);
};
/**
* Shows the generated code.
* @private
*/
SpeechGames.showCode_ = function() {
var modalEl = document.createElement('generatedCode');
modalEl.style.width = '400px';
modalEl.style.height = '300px';
modalEl.style.margin = '100px auto';
modalEl.style.backgroundColor = '#ff';
modalEl.textContent = createCode_();
mui.overlay('on', modalEl);
};
/**
* Gets a parameter from the url.
* @param {!string} name Name of the param (i.e. debug)
* @param {string} url Optional url, otherwise window url is used.
*/
SpeechGames.getParameterByName_ = function(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return '';
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
};
/**
* Gets all params except for level flag from the url.
* @return {string} extraParams Extra params, besides level.
*/
SpeechGames.getExtraParams = function() {
var href = window.location.href;
var extraParams = href.substring(href.indexOf('?')).replace('?level='+SpeechGames.LEVEL, '');
if (!extraParams.includes('?microphone') && SpeechGames.speech.listening) {
extraParams += '&?microphone=1';
} else {
if (!SpeechGames.speech.listening) {
extraParams = extraParams.replace('&?microphone=1','');
}
}
if (extraParams[0] != '&') {
extraParams = '&' + extraParams;
}
return extraParams;
}
/**
* Edit toolbox xml.
* @param {$document} document Index of speech games
* @param {array} blockTypes Block types to be included in the toolbox XML
*/
SpeechGames.editToolboxXml_ = function(document, blockTypes) {
var $xmls = document.getElementsByTagName('xml');
var $toolbox = $xmls.toolbox.children;
for(var i = 0; i < $toolbox.length; ) {
if (!blockTypes.includes($toolbox[i].getAttribute('type')))
$toolbox[i].remove();
else
i++;
}
}
/**
* Initializes all of the SpeechGames objects and begins listening.
*/
$(document).ready(function() {
SpeechGames.LEVEL = SpeechGames.getNumberParamFromURL_('level', 1, SpeechGames.MAX_LEVEL);
blockTypes = Turtle.blockTypes[SpeechGames.LEVEL];
SpeechGames.editToolboxXml_(document, blockTypes);
SpeechGames.speech = new SpeechGames.Speech();
SpeechGames.workspace = Blockly.inject('blocklyDiv', {
media: 'lib/google-blockly/media/',
trashcan: false,
scrollbars: false,
toolbox: document.getElementById('toolbox')
});
SpeechGames.controller = new SpeechBlocks.Controller(
SpeechGames.workspace,
SpeechGames.getParameterByName_('animate'));
SpeechGames.interpreter = new SpeechBlocks.Interpreter(SpeechGames.controller, blockTypes);
if (SpeechGames.getParameterByName_('microphone')) {
SpeechGames.speech.setMicInterval_();
}
if (SpeechGames.getParameterByName_('debug')) {
$('#q').css('visibility','visible');
} else {
$('#debug').hide();
}
// listen for mouse clicks, key presses
$('#q')
.change(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
.mousedown(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
.mouseup(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
.click(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
.keydown(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
.keyup(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
.keypress(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech));
// if microphone icon clicked
$('#microphone')
.click(SpeechGames.speech.toggleDictation_.bind(SpeechGames.speech));
$("#user-message").hide().text("Awaiting your command!").fadeIn(500);
// }
// $('#runButton').on('click', run);
// $('#showButton').on('click', showCode_);
// $('#debugButton').on('click', function() {
// $('#debug').toggle();
// });
// $('#buttonRow').hide();
$('#levelDescription').text(Turtle.descriptions[SpeechGames.LEVEL]);
});
|
var express = require('express');
var bodyparser = require('body-parser');
var status = require('http-status');
var _ = require('underscore');
module.exports = function(wagner) {
var api = express.Router();
api.use(bodyparser.json());
api.get('/category/id/:id', wagner.invoke(function(Category) {
return function(req, res) {
Category.findOne({ _id: req.params.id }, function(error, category) {
if (error) {
return res.status(status.INTERNAL_SERVER_ERROR).json({ error: error.toString() });
}
if (!category) {
return res.status(status.NOT_FOUND).json({ error: 'Not found' });
}
res.json({ category: category });
});
};
}));
api.get('/category/parent/:id', wagner.invoke(function(Category) {
return function(req, res) {
Category.find({ parent: req.params.id }).sort({ _id: 1 }).exec(function(error, categories) {
if (error) {
return res.status(status.INTERNAL_SERVER_ERROR).json({ error: error.toString() });
}
res.json({ categories: categories });
});
};
}));
api.get('/product/id/:id', wagner.invoke(function(Product) {
return function(req, res) {
Product.findOne({ _id: req.params.id }, handleOne.bind(null, 'product', res));
};
}));
api.get('/product/category/:id', wagner.invoke(function(Product) {
return function(req, res) {
var sort = { name: 1 };
if (req.query.price === "1") {
sort = { 'internal.approximatePriceUSD': 1 };
} else if (req.query.price === "-1") {
sort = { 'internal.approximatePriceUSD': -1 };
}
Product.find({ 'category.ancestors': req.params.id }).sort(sort).exec(handleMany.bind(null, 'products', res));
};
}));
api.get('/product/text/:query', wagner.invoke(function(Product) {
return function(req, res) {
Product.find(
{ $text : { $search : req.params.query } },
{ score : { $meta: 'textScore' } }).
sort({ score : { $meta : 'textScore' } }).
limit(10).
exec(handleMany.bind(null, 'products', res));
};
}));
api.put('/me/cart', wagner.invoke(function(User) {
return function(req, res) {
try {
var cart = req.body.data.cart;
} catch (e) {
return res.status(status.BAD_REQUEST).json({ error: 'No cart specified' });
}
req.user.data.cart = cart;
req.user.save(function(error, user) {
if (error) {
return res.status(status.INTERNAL_SERVER_ERROR).json({ error: error.toString() });
}
return res.json({ user: user });
});
};
}));
api.get('/me', function(req, res) {
if (!req.user) {
return res.status(status.UNAUTHORIZED).json({ error: 'Not logged in' });
}
req.user.populate({ path: 'data.cart.product', model: 'Product' }, handleOne.bind(null, 'user', res));
});
api.post('/checkout', wagner.invoke(function(User, Stripe) {
return function(req, res) {
if (!req.user) {
return res.status(status.UNAUTHORIZED).json({ error: 'Not logged in' });
}
// Popoluate the products in the user's cart
req.user.populate({ path: 'data.cart.product', model: 'Product'}, function(error, user) {
// Sum up the total price in USD
var totalCostUSD = 0;
_.each(user.data.cart, function(item) {
totalCostUSD += item.product.internal.approximatePriceUSD * item.quantity;
});
// And create a charge in stripe corresponding to the price
Stripe.charges.create({
// Stripe wants price in cents, so multiply by 100 and round up
amount: Math.ceil(totalCostUSD * 100),
currency: 'usd',
source: req.body.stripeToken,
description: 'Example charge'
},
function(err, charge) {
if (err && err.type == 'StripeCardError') {
return res.status(status.BAD_REQUEST).json({ error: err.toString() });
}
if (err) {
console.log(err);
return res.status(status.INTERNAL_SERVER_ERROR).json({ error: err.toString() });
}
req.user.data.cart = [];
req.user.save(function() {
// Ignore any errors - if we failed to empty the user's cart that's not necessarily a failure
// If successful, return the charge id
return res.json({ id: charge.id });
});
});
});
}
}));
return api;
};
function handleOne(property, res, error, result) {
if (error) {
return res.status(status.INTERNAL_SERVER_ERROR).json({ error: error.toString() });
}
if (!result) {
return res.status(status.NOT_FOUND).json({ error: 'Not found' });
}
var json = {};
json[property] = result;
res.json(json);
}
function handleMany(property, res, error, result) {
if (error) {
return res.status(status.INTERNAL_SERVER_ERROR).json({ error: error.toString() });
}
var json = {};
json[property] = result;
res.json(json);
}
|
'use strict';
/**
* @module core/lib/server
*/
// Setup HAPI
const Hapi = require('hapi');
const path = require('path');
const bell = require('bell');
const authCookie = require('hapi-auth-cookie');
const inert = require('inert');
const vision = require('vision');
const scooter = require('scooter');
const yar = require('yar');
const good = require('good');
const pug = require('pug');
const lout = require('lout');
const boom = require('boom');
// Setup server before loading plugins
const server = new Hapi.Server();
module.exports.server = server;
// Nicest plugins
const nicestWelcome = require('../modules/welcome/plugin');
const nicestDocumentation = require('../modules/documentation/plugin');
const nicestRecipe = require('../modules/recipe/plugin');
const nicestUser = require('../modules/user/plugin');
const nicestTeam = require('../modules/team/plugin');
const nicestCourse = require('../modules/course/plugin');
const nicestGithub = require('../modules/github/plugin');
const nicestImportExport = require('../modules/import-export/plugin');
const nicestErrorPage = require('../modules/error-page/plugin');
const nicestCodeProject = require('../modules/code-project/plugin');
const nicestMangeCodeProject = require('../modules/manage-code-project/plugin');
const mongoose = require('mongoose');
// Server has initial not been configured
let isSetup = false;
/**
* Sets up the Hapi server
* @param {Object} configuration - host name
* @returns {Object} Hapi server instance
*/
function setup (configuration) {
if (!isSetup) {
isSetup = true;
server.path(path.join(__dirname, '..'));
server.realm.modifiers.route.prefix = configuration.server.prefix;
server.connection({
host: configuration.server.hostname,
port: configuration.server.port,
routes: {files: {relativeTo: path.join(__dirname, '..')}}
});
server.register(
[
{register: inert},
{register: vision},
{register: bell},
{register: authCookie},
{register: scooter},
{
options: {
auth: {
mode: 'required',
strategy: 'session'
},
endpoint: '/apis',
filterRoutes (route) {
const search = new RegExp(`^${configuration.server.prefix}/recipe/`);
return !search.test(route.path);
}
},
register: lout
},
{
options: {
cookieOptions: {
isHttpOnly: true,
isSecure: configuration.authentication.https,
password: configuration.authentication.token
}
},
register: yar
},
{
options: {
ops: {interval: 2147483647},
reporters: {
error: [
{
args: [
{
error: '*',
log: '*'
}
],
module: 'good-squeeze',
name: 'Squeeze'
},
{
module: 'good-squeeze',
name: 'SafeJson'
},
{
args: [
'error.log'
],
module: 'good-file'
}
],
response: [
{
args: [
{response: '*'}
],
module: 'good-squeeze',
name: 'Squeeze'
},
{
module: 'good-squeeze',
name: 'SafeJson'
},
{
args: [
'request.log'
],
module: 'good-file'
}
]
}
},
register: good
}
],
(registrationErr) => {
if (registrationErr) {
console.log(registrationErr);
}
server
.auth
.strategy('session', 'cookie', true, {
cookie: 'session-auth',
isSecure: configuration.authentication.https,
password: configuration.authentication.token,
redirectTo: `${configuration.server.prefix}/login`
});
server
.auth
.strategy('github', 'bell', {
clientId: configuration.authentication.github.client,
clientSecret: configuration.authentication.github.secret,
forceHttps: configuration.authentication.https,
isSecure: configuration.authentication.https,
password: configuration.authentication.token,
provider: 'github'
});
server.route({
config: {
auth: 'github',
plugins: {lout: false}
},
handler (request, reply) {
const {User} = mongoose.models;
if (request.auth.isAuthenticated) {
User.findOne(
{
'modules.github.username': request.auth.credentials.profile.username,
role: {$in: ['admin', 'instructor']}
},
(findErr, user) => {
if (findErr || user === null) {
reply(boom.unauthorized('You do not have permission to view this page'));
} else {
request
.cookieAuth
.set(request.auth.credentials);
reply.redirect(configuration.server.prefix);
}
}
);
} else {
reply(boom.unauthorized(`Authentication failed due to: ${request.auth.error.message}`));
}
},
method: ['GET', 'POST'],
path: '/login'
});
}
);
// Pug templating service
server.views({
context: {prefix: configuration.server.prefix},
engines: {pug: {module: pug}}
});
// Load nicest plugins
server.register(
[
{register: nicestWelcome},
{register: nicestDocumentation},
{register: nicestRecipe},
{register: nicestUser},
{register: nicestTeam},
{register: nicestCourse},
{register: nicestGithub},
{register: nicestImportExport},
{register: nicestErrorPage},
{register: nicestCodeProject},
{register: nicestMangeCodeProject}
],
(err) => {
if (err) {
console.log(err);
}
}
);
}
return server;
}
module.exports.setup = setup;
|
import parse from 'co-parse';
var models = require('cartling-models');
var helpers = require('../helpers');
import helpers from '../helpers';
const common = helpers.common;
const errors = common.errors;
export default async function() {
try {
let req = this.req;
let res = this.res;
let id = common.util.getId(this);
let cart = await Cart.get(id);
await cart.fetchItems();
res.json(cart);
} catch(err) {
errors.sendError(res, err);
}
};
|
module.exports.tt8750 = function(){
this.bind = function(port){
}
}
|
import * as React from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Slider from '@material-ui/core/Slider';
function valuetext(value) {
return `${value}°C`;
}
export default function DiscreteSlider() {
return (
<Box sx={{ width: 300 }}>
<Typography id="discrete-slider" gutterBottom>
Temperature
</Typography>
<Slider
defaultValue={30}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider"
valueLabelDisplay="auto"
step={10}
marks
min={10}
max={110}
/>
<Typography id="discrete-slider-disabled" gutterBottom>
Disabled
</Typography>
<Slider
defaultValue={30}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider-disabled"
valueLabelDisplay="auto"
step={10}
marks
min={10}
max={110}
disabled
/>
</Box>
);
}
|
// This file is part of Indico.
// Copyright (C) 2002 - 2022 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
angular
.module('nd', ['ndDirectives', 'ndFilters', 'ndServices', 'nd.regform'])
.controller('AppCtrl', function($scope) {
// Main application controller.
// This is a good place for logic not specific to the template or route
// such as menu logic or page title wiring.
});
|
var app = require('./app');
var rq= require('supertest').agent(app.listen(4000));
describe('404',function(){
describe('when get /',function () {
it('should return 404 page',function (done) {
rq.get('/').expect(404).expect(/Page not found/,done);
});
});
});
|
//MyWidget Script
/**************************
Add a link for a CSS file that styles .mywidget
Add a script tag that points to CDN version of jQuery 1.*
Add a script tag that loads your script file from http://m.edumedia.ca/
**************************/
document.addEventListener("DOMContentLoaded", function(){
var w = $("#wrapper").width( );
console.log(w);
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("href", "main.css");
//loads the CSS file and applies it to the page
var scriptsLoaded = 0;
var jq = document.createElement("script");
jq.addEventListener("load", function(){
scriptsLoaded++;
if(scriptsLoaded === 2){
//call the function in My widget script to load the JSON and build the widget
buildWidget(".mywidget");
console.log("both scripts loaded");
}
});
document.querySelector("head").appendChild(jq);
jq.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js");
var script = document.createElement("script");
script.addEventListener("load", function(){
scriptsLoaded++;
if(scriptsLoaded === 2){
//call the function in My widget script to load the JSON and build the widget
buildWidget(".mywidget");
console.log("both scripts loaded");
}
});
document.querySelector("head").appendChild(script);
script.setAttribute("src","js/widget.js");
}); |
(function (dust) {
dust.helpers = dust.helpers || {};
dust.helpers.stringify = function (chunk, context, bodies, params) {
var value = dust.helpers.tap(params.value, chunk, context),
space = parseInt(dust.helpers.tap(params.space, chunk, context)) || 0;
try {
return chunk.write(JSON.stringify(JSON.parse(value), null, space));
} catch (e) {
return chunk.write('value is not valid JSON');
}
};
if (typeof exports !== 'undefined') {
module.exports = dust;
}
}(
typeof exports !== 'undefined' ? require('dustjs-linkedin') : dust
));
|
var fs = require('fs');
fs.readFile('input.txt', 'utf8', function(err, contents) {
var lines = contents.split('\n');
var packageStrings = [];
// ensure we don't get any empty lines (like a trailing newline)
lines.forEach(function(line) {
if (line.length) { packageStrings.push(line) };
});
calculateWrappingPaper(packageStrings);
});
var calculateWrappingPaper = function(packageStrings) {
var packages = [];
packageStrings.forEach(function(pkgString) {
packages.push(parseDimensions(pkgString));
});
console.log('Square Feet of Wrapping Paper: ' + sumAreas(packages));
console.log('Feet of Ribbon: ' + sumRibbonLength(packages));
};
// take a package string in the form of 'lxwxh' and parse it
// into its consituent integers
var parseDimensions = function(pkg) {
var split = pkg.split('x');
var box = {};
// basic sanity check
if (split.length !== 3) {
console.error('Parsed an invalid package: ' + pkg +'. Expecting format "lxwxh"!')
}
box.l = parseInt(split[0]);
box.w = parseInt(split[1]);
box.h = parseInt(split[2]);
box.smallestSideArea = findSmallestSideArea([box.l, box.w, box.h]);
box.shortestDistanceAround = findShortestDistance([box.l, box.w, box.h])
box.wrappingArea = calculateWrappingArea(box);
box.ribbonLength = calculateRibbonLength(box);
return box;
};
// given an array of [l,w,h], calculate the area of the smallest side and return it
var findSmallestSideArea = function(dimensions) {
var area;
var max = Math.max.apply(Math, dimensions);
var maxIndex = dimensions.indexOf(max);
// remove the largest size from the dimensions array
dimensions.splice(maxIndex, 1);
// return the area by multiplying the remaining sides
return dimensions[0] * dimensions[1];
};
// given a box with l,w,h and smallestArea calculate how much paper is
// required to wrap the box
var calculateWrappingArea = function(box) {
// surface area of a box = 2*l*w + 2*w*h + 2*h*l
var surfaceArea = 2 * ((box.l * box.w) + (box.w * box.h) + (box.h * box.l));
// required wrapping paper = surface area + slack of smallest side's area
return surfaceArea + box.smallestSideArea;
};
var findShortestDistance = function(dimensions) {
var area;
var max = Math.max.apply(Math, dimensions);
var maxIndex = dimensions.indexOf(max);
// remove the largest size from the dimensions array
dimensions.splice(maxIndex, 1);
return 2 * (dimensions[0] + dimensions[1]);
};
// bow length = shortestDistanceAround + cubic volume of the box (l*w*h)
var calculateRibbonLength = function(box) {
var volume = box.l * box.w * box.h;
return box.shortestDistanceAround + volume;
};
// sum the wrappingAreas of all packages
var sumAreas = function(packages) {
var sum = 0;
packages.forEach(function(box) {
sum += box.wrappingArea;
});
return sum;
};
// sum the required ribbonLength of all packages
sumRibbonLength = function(packages) {
var sum = 0;
packages.forEach(function(box) {
sum += box.ribbonLength;
});
return sum;
}
|
console.log('Hello from a fellow script');
|
"use strict";
describe("wu.keys", (function() {
it("should iterate over keys", (function() {
assert.eqSet(new Set(["foo", "bar", "baz"]), wu.keys({
foo: 1,
bar: 2,
baz: 3
}));
}));
}));
|
'use strict';
/* Directives */
angular.module('myApp.directives', [])
.directive('appVersion', function (version) {
return function(scope, elm, attrs) {
elm.text(version);
};
})
.directive('modal', function () {
return {
templateUrl: './app/common/modal.html',
// template: '<div class="modal fade">' +
// '<div class="modal-dialog">' +
// '<div class="modal-content">' +
// '<div class="modal-header">' +
// '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
// '<h4 class="modal-title">{{ title }}</h4>' +
// '</div>' +
// '<div class="modal-body" ng-transclude></div>' +
// '</div>' +
// '</div>' +
// '</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
|
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'mk',
dictionary: {},
format: {
days: ['Недела', 'Понеделник', 'Вторник', 'Среда', 'Четврток', 'Петок', 'Сабота'],
shortDays: ['Нед', 'Пон', 'Вто', 'Сре', 'Чет', 'Пет', 'Саб'],
months: [
'Јануари', 'Февруари', 'Март', 'Април', 'Мај', 'Јуни',
'Јули', 'Август', 'Септември', 'Октомври', 'Ноември', 'Декември'
],
shortMonths: [
'Јан', 'Фев', 'Мар', 'Апр', 'Мај', 'Јун',
'Јул', 'Авг', 'Сеп', 'Окт', 'Нов', 'Дек'
],
date: '%d/%m/%Y'
}
};
|
// Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "57448aa1-9515-4176-a106-5cb9be8550e1",
authority: "https://fs.msidlab8.com/adfs/",
knownAuthorities: ["fs.msidlab8.com"]
},
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["openid", "profile"],
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
};
|
'use strict'
const {BadRequestError} = require('jsonapi-errors/lib/errors')
module.exports = function idParamParser (req, res, next, id) {
const idInt = parseInt(id, 10)
if (isNaN(idInt)) return next(new BadRequestError(`param ${id}`))
req.id = idInt
next()
}
|
/*! abbr-fill.js | (c) 2014 Daniel Imms | github.com/Tyriar/abbr-fill.js/blob/master/LICENSE */
var abbrFill = (function (findAndWrap) {
'use strict';
var config;
function init (configuration) {
if (!configuration || !configuration.terms || !configuration.selector) {
return;
}
config = configuration;
var nodes = document.querySelectorAll(config.selector);
for (var i = 0; i < nodes.length; i++) {
applyAbbrs(nodes[i]);
}
}
function applyAbbrs(node) {
for (var term in config.terms) {
if (config.terms.hasOwnProperty(term)) {
// This will only match the first instance if there are two instances of
// the term separated by a space. Since it is quite an unlikely scenario
// and probably not desirable to wrap both anyway it's allowed.
// For example: "ABC ABC" -> "<abbr title="...">ABC</abbr> ABC
//matchText(node, new RegExp('(^|\\s)' + term + '($|\\s|\\.|,)', 'g'),
// wrapElement);
var abbrs = findAndWrap(node, term, 'abbr');
if (!abbrs.length) {
continue;
}
for (var i = 0; i < abbrs.length; i++) {
abbrs[i].title = config.terms[term];
}
}
}
}
return init;
})(findAndWrap);
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router>
<App />
</Router>
</Provider>
, document.querySelector('.container'));
|
define(["sprd/manager/IConfigurationManager"], function (Base) {
return Base.inherit("sprd.manager.ITextConfigurationManager", {
initializeConfiguration: function (configuration, callback) {
}
});
}); |
// Generated by CoffeeScript 1.3.3
(function() {
describe('Scouter', function() {
it('can properly score the specificity of W3C\'s examples', function() {
var score, scouter, selector, selectors, _results;
scouter = new Scouter();
selectors = {
'*': 0,
'LI': 1,
'UL LI': 2,
'UL OL+LI': 3,
'H1 + *[REL=up]': 11,
'UL OL LI.red': 13,
'LI.red.level': 21,
'#x34y': 100,
'#s12:not(F00)': 101
};
_results = [];
for (selector in selectors) {
score = selectors[selector];
_results.push(expect(scouter.score(selector)).toBe(score));
}
return _results;
});
return it('can sort an array of selectors', function() {
var scouter, selectors, sortedSelectors;
scouter = new Scouter();
selectors = ['.header h1', 'h1', '.header', '.header h1 > em'];
sortedSelectors = ['.header h1 > em', '.header h1', '.header', 'h1'];
return expect(scouter.sort(selectors)).toEqual(sortedSelectors);
});
});
}).call(this);
|
/*
* 定义购物车模型
* [购物车]: 顾客 产品 订单账单 发货数据
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
//地址模型,用于发货信息和账单信息的一部分
var AddressSchema = new Schema({
name: String,
address: String,
city: String,
state: String,
zip: String
}, {_id: false}); //禁止id自动分配,因为并不需要根据ID查找地址
mongoose.model('Address', AddressSchema);
//账单模型:跟踪信用卡信息和账单信息
var BillingSchema = new Schema({
carttype: {type: String, enum: ['Visa', 'MasterCard', 'Amex']},
name: String,
number: String,
expiremonth: Number,
expireyear: Number,
address: [AddressSchema]
}, {_id: false});
mongoose.model('Billing', BillingSchema);
//产品模型:存储产品信息的模型
var ProductSchema = new Schema({
name: String,
imagefile: String,
description: String,
price: Number,
instock: Number
});
mongoose.model('Product', ProductSchema);
//数量模型
var ProductQuantitySchema = new Schema({
quantity: Number,
product: [ProductSchema]
}, {_id: false});
mongoose.model('ProductQuantity', ProductQuantitySchema);
//订单模型
var OrderSchema = new Schema({
userid: String,
items: [ProductQuantitySchema],
shipping: [AddressSchema],
billing: [BillingSchema],
status: {type: String, default: "Pending"},
timestamp: {type: Date, default: Date.now}
});
mongoose.model('Order', OrderSchema);
//顾客模型
var CutsomerSchema = new Schema({
userid: {type: String, unique: true, required: true},
shipping: [AddressSchema],
billing: [BillingSchema],
cart: [ProductQuantitySchema]
});
mongoose.model('Customer', CutsomerSchema); |
var searchData=
[
['data',['Data',['../classowncloudsharp_1_1_types_1_1_o_c_s.html#ad64d4fa0e0f73ba19a0eb97b9d30f2bd',1,'owncloudsharp::Types::OCS']]],
['defaultenable',['DefaultEnable',['../classowncloudsharp_1_1_types_1_1_app_info.html#a21fbeb14bcd6b6783ef68231f9230f42',1,'owncloudsharp::Types::AppInfo']]],
['description',['Description',['../classowncloudsharp_1_1_types_1_1_app_info.html#a3fe8c924b76d206ea155ff7df8afa08b',1,'owncloudsharp::Types::AppInfo']]],
['displayname',['DisplayName',['../classowncloudsharp_1_1_types_1_1_user.html#a9b885e34f7c1e695e5d9867931b64d9c',1,'owncloudsharp::Types::User']]],
['displaynameowner',['DisplaynameOwner',['../classowncloudsharp_1_1_types_1_1_advanced_share_properties.html#add275aead35226f84b36e447e4104f0d',1,'owncloudsharp::Types::AdvancedShareProperties']]],
['documentation',['Documentation',['../classowncloudsharp_1_1_types_1_1_app_info.html#ae9ef7fbc3cdcf9f49cd7372d13249225',1,'owncloudsharp::Types::AppInfo']]]
];
|
'use strict';
var gulp = require('gulp'),
fs = require("fs"),
runSequence = require('run-sequence'),
gulpsync = require('gulp-sync')(gulp),
inline = require('inline-html'),
replace = require('gulp-string-replace'),
sass = require('gulp-sass'),
concat = require('gulp-concat'),
rename = require("gulp-rename"),
gulpCopy = require('gulp-copy'),
browserSync = require('browser-sync'),
uglify = require('gulp-uglify'),
uglifycss = require('gulp-uglifycss'),
html2string = require('gulp-html2string'),
sourcemaps = require('gulp-sourcemaps');
// Init browser
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "./dist"
}
});
});
// Refresh browser
gulp.task('reload', [], function (done) {
browserSync.reload();
done();
});
// Transpile SCSS
gulp.task('sass', [], function() {
return gulp.src( './src/component.scss' )
.pipe( sass().on('error', sass.logError) )
.pipe( sourcemaps.init() )
.pipe( uglifycss() )
.pipe( sourcemaps.write() )
.pipe( gulp.dest( './dist/css' ) );
});
// Compile templata
gulp.task('html2js', function () {
return gulp.src('./src/template.html')
.pipe( html2string({ base: './src/template.html', createObj: true, objName: 'TEMPLATE' }) )
.pipe(rename({extname: '.js'}))
.pipe(gulp.dest('./src/template'));
});
// Minify JS
gulp.task('concat', ['html2js'] , function(done) {
return gulp.src( ['./src/component.js', './src/template/template.js'] )
.pipe( concat('main.js') )
.pipe( sourcemaps.init() )
.pipe( uglify() )
.pipe( sourcemaps.write() )
.pipe( gulp.dest( './dist/js' ) );
});
// Secuence js
gulp.task('js', function() {
runSequence(
['html2js'],
['concat'],
['reload']
)
});
// Copy HTML
gulp.task('copy-html', [], function() {
return gulp.src( './src/index.html' )
.pipe( gulp.dest( './dist' ) )
});
// watch files
gulp.task('watch', [], function() {
gulp.watch( './src/component.js', ['js'] );
gulp.watch( './src/template.html', [ 'js'] );
gulp.watch( './src/component.scss', ['sass', 'reload'] );
gulp.watch( './src/index.html', ['copy-html', 'reload'] );
});
gulp.task( 'default', runSequence(
[ 'html2js', 'copy-html'],
['js', 'sass'],
['watch'],
['browser-sync'],
['reload' ]
) );
|
import Ember from 'ember';
import { module, test } from 'qunit';
import SocketsService from 'dummy/services/websockets';
var component;
var ConsumerComponent;
var originalWebSocket;
var mockServerFoo;
var mockServerBar;
module('Sockets Service - socketFor', {
setup() {
originalWebSocket = window.WebSocket;
window.WebSocket = MockSocket;
var service = SocketsService.create();
[mockServerFoo, mockServerBar] = [new MockServer('ws://localhost:7000/'), new MockServer('ws://localhost:7001/')]; // jshint ignore:line
ConsumerComponent = Ember.Component.extend({
socketService: service,
socket: null,
willDestroy() {
this.socketService.closeSocketFor('ws://localhost:7000/');
this.socketService.closeSocketFor('ws://localhost:7001/');
}
});
},
teardown() {
window.WebSocket = originalWebSocket;
Ember.run(() => {
component.destroy();
mockServerFoo.close();
mockServerBar.close();
});
}
});
test('that socketFor works correctly', assert => {
var done = assert.async();
assert.expect(2);
component = ConsumerComponent.extend({
init() {
this._super.apply(this, arguments);
var socketService = this.socketService;
assert.deepEqual(socketService.socketFor('ws://localhost:7000/'), socketService.socketFor('ws://localhost:7000/'));
assert.notDeepEqual(socketService.socketFor('ws://localhost:7000/'), socketService.socketFor('ws://localhost:7001/'));
done();
}
}).create();
});
|
(function() {
var icon = localStorage["toolbar_icon"] || 'dark';
chrome.browserAction.setIcon({
path: {
'dark': 'icon19',
'light': 'icon19_light'
}[icon] + '.png'
});
}());
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('button clicked');
_gaq.push(['_trackEvent', 'chrome', 'loaded']);
chrome.tabs.sendRequest(tab.id, {
action: 'initOrRestore'
}, function(loaded) {
var msg = loaded ? 'inited' : 'restored';
console.log(msg);
});
});
chrome.extension.onRequest.addListener(function(request, sender, callback) {
console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
if (request.action === 'getJSON') {
request.data = request.data || {};
// because of Chrome policy, JSONP won't work but XMLHttpRequest can cross-origin
request.url = request.url.replace(/callback=\?/g, '');
wf$.getJSON(request.url, request.data, function(data) {
if (callback) {
callback(data);
}
});
}
if (request.action === 'capture') {
var options = request.options || {};
if (options.format) {
options.format = options.format.replace(/^image\//, '');
}
if (options.quality > 0 && options.quality <=1) {
options.quality = options.quality * 100;
}
chrome.tabs.captureVisibleTab(options, callback);
}
});
|
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var d3 = require('d3');
var Registry = require('../registry');
var Plots = require('../plots/plots');
var Lib = require('../lib');
var clearGlCanvases = require('../lib/clear_gl_canvases');
var Color = require('../components/color');
var Drawing = require('../components/drawing');
var Titles = require('../components/titles');
var ModeBar = require('../components/modebar');
var Axes = require('../plots/cartesian/axes');
var alignmentConstants = require('../constants/alignment');
var axisConstraints = require('../plots/cartesian/constraints');
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = require('../plots/cartesian/autorange').doAutoRange;
var SVG_TEXT_ANCHOR_START = 'start';
var SVG_TEXT_ANCHOR_MIDDLE = 'middle';
var SVG_TEXT_ANCHOR_END = 'end';
exports.layoutStyles = function(gd) {
return Lib.syncOrAsync([Plots.doAutoMargin, lsInner], gd);
};
function overlappingDomain(xDomain, yDomain, domains) {
for(var i = 0; i < domains.length; i++) {
var existingX = domains[i][0];
var existingY = domains[i][1];
if(existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
continue;
}
if(existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
return true;
}
}
return false;
}
function lsInner(gd) {
var fullLayout = gd._fullLayout;
var gs = fullLayout._size;
var pad = gs.p;
var axList = Axes.list(gd, '', true);
var i, subplot, plotinfo, ax, xa, ya;
fullLayout._paperdiv.style({
width: (gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroWidth && !gd.layout.width) ? '100%' : fullLayout.width + 'px',
height: (gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroHeight && !gd.layout.height) ? '100%' : fullLayout.height + 'px'
})
.selectAll('.main-svg')
.call(Drawing.setSize, fullLayout.width, fullLayout.height);
gd._context.setBackground(gd, fullLayout.paper_bgcolor);
exports.drawMainTitle(gd);
ModeBar.manage(gd);
// _has('cartesian') means SVG specifically, not GL2D - but GL2D
// can still get here because it makes some of the SVG structure
// for shared features like selections.
if(!fullLayout._has('cartesian')) {
return gd._promises.length && Promise.all(gd._promises);
}
function getLinePosition(ax, counterAx, side) {
var lwHalf = ax._lw / 2;
if(ax._id.charAt(0) === 'x') {
if(!counterAx) return gs.t + gs.h * (1 - (ax.position || 0)) + (lwHalf % 1);
else if(side === 'top') return counterAx._offset - pad - lwHalf;
return counterAx._offset + counterAx._length + pad + lwHalf;
}
if(!counterAx) return gs.l + gs.w * (ax.position || 0) + (lwHalf % 1);
else if(side === 'right') return counterAx._offset + counterAx._length + pad + lwHalf;
return counterAx._offset - pad - lwHalf;
}
// some preparation of axis position info
for(i = 0; i < axList.length; i++) {
ax = axList[i];
var counterAx = ax._anchorAxis;
// clear axis line positions, to be set in the subplot loop below
ax._linepositions = {};
// stash crispRounded linewidth so we don't need to pass gd all over the place
ax._lw = Drawing.crispRound(gd, ax.linewidth, 1);
// figure out the main axis line and main mirror line position.
// it's easier to follow the logic if we handle these separately from
// ax._linepositions, which are only used by mirror=allticks
// for non-main-subplot ticks, and mirror=all(ticks)? for zero line
// hiding logic
ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side);
ax._mainMirrorPosition = (ax.mirror && counterAx) ?
getLinePosition(ax, counterAx,
alignmentConstants.OPPOSITE_SIDE[ax.side]) : null;
}
// figure out which backgrounds we need to draw,
// and in which layers to put them
var lowerBackgroundIDs = [];
var backgroundIds = [];
var lowerDomains = [];
// no need to draw background when paper and plot color are the same color,
// activate mode just for large splom (which benefit the most from this
// optimization), but this could apply to all cartesian subplots.
var noNeedForBg = (
Color.opacity(fullLayout.paper_bgcolor) === 1 &&
Color.opacity(fullLayout.plot_bgcolor) === 1 &&
fullLayout.paper_bgcolor === fullLayout.plot_bgcolor
);
for(subplot in fullLayout._plots) {
plotinfo = fullLayout._plots[subplot];
if(plotinfo.mainplot) {
// mainplot is a reference to the main plot this one is overlaid on
// so if it exists, this is an overlaid plot and we don't need to
// give it its own background
if(plotinfo.bg) {
plotinfo.bg.remove();
}
plotinfo.bg = undefined;
} else {
var xDomain = plotinfo.xaxis.domain;
var yDomain = plotinfo.yaxis.domain;
var plotgroup = plotinfo.plotgroup;
if(overlappingDomain(xDomain, yDomain, lowerDomains)) {
var pgNode = plotgroup.node();
var plotgroupBg = plotinfo.bg = Lib.ensureSingle(plotgroup, 'rect', 'bg');
pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]);
backgroundIds.push(subplot);
} else {
plotgroup.select('rect.bg').remove();
lowerDomains.push([xDomain, yDomain]);
if(!noNeedForBg) {
lowerBackgroundIDs.push(subplot);
backgroundIds.push(subplot);
}
}
}
}
// now create all the lower-layer backgrounds at once now that
// we have the list of subplots that need them
var lowerBackgrounds = fullLayout._bgLayer.selectAll('.bg')
.data(lowerBackgroundIDs);
lowerBackgrounds.enter().append('rect')
.classed('bg', true);
lowerBackgrounds.exit().remove();
lowerBackgrounds.each(function(subplot) {
fullLayout._plots[subplot].bg = d3.select(this);
});
// style all backgrounds
for(i = 0; i < backgroundIds.length; i++) {
plotinfo = fullLayout._plots[backgroundIds[i]];
xa = plotinfo.xaxis;
ya = plotinfo.yaxis;
if(plotinfo.bg) {
plotinfo.bg
.call(Drawing.setRect,
xa._offset - pad, ya._offset - pad,
xa._length + 2 * pad, ya._length + 2 * pad)
.call(Color.fill, fullLayout.plot_bgcolor)
.style('stroke-width', 0);
}
}
if(!fullLayout._hasOnlyLargeSploms) {
for(subplot in fullLayout._plots) {
plotinfo = fullLayout._plots[subplot];
xa = plotinfo.xaxis;
ya = plotinfo.yaxis;
// Clip so that data only shows up on the plot area.
var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot';
var plotClip = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) {
s.classed('plotclip', true)
.append('rect');
});
plotinfo.clipRect = plotClip.select('rect').attr({
width: xa._length,
height: ya._length
});
Drawing.setTranslate(plotinfo.plot, xa._offset, ya._offset);
var plotClipId;
var layerClipId;
if(plotinfo._hasClipOnAxisFalse) {
plotClipId = null;
layerClipId = clipId;
} else {
plotClipId = clipId;
layerClipId = null;
}
Drawing.setClipUrl(plotinfo.plot, plotClipId, gd);
// stash layer clipId value (null or same as clipId)
// to DRY up Drawing.setClipUrl calls on trace-module and trace layers
// downstream
plotinfo.layerClipId = layerClipId;
}
}
var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop,
leftYLineWidth, rightYLineWidth;
var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight,
connectYBottom, connectYTop;
var extraSubplot;
function xLinePath(y) {
return 'M' + xLinesXLeft + ',' + y + 'H' + xLinesXRight;
}
function xLinePathFree(y) {
return 'M' + xa._offset + ',' + y + 'h' + xa._length;
}
function yLinePath(x) {
return 'M' + x + ',' + yLinesYTop + 'V' + yLinesYBottom;
}
function yLinePathFree(x) {
return 'M' + x + ',' + ya._offset + 'v' + ya._length;
}
function mainPath(ax, pathFn, pathFnFree) {
if(!ax.showline || subplot !== ax._mainSubplot) return '';
if(!ax._anchorAxis) return pathFnFree(ax._mainLinePosition);
var out = pathFn(ax._mainLinePosition);
if(ax.mirror) out += pathFn(ax._mainMirrorPosition);
return out;
}
for(subplot in fullLayout._plots) {
plotinfo = fullLayout._plots[subplot];
xa = plotinfo.xaxis;
ya = plotinfo.yaxis;
/*
* x lines get longer where they meet y lines, to make a crisp corner.
* The x lines get the padding (margin.pad) plus the y line width to
* fill up the corner nicely. Free x lines are excluded - they always
* span exactly the data area of the plot
*
* | XXXXX
* | XXXXX
* |
* +------
* x1
* -----
* x2
*/
var xPath = 'M0,0';
if(shouldShowLinesOrTicks(xa, subplot)) {
leftYLineWidth = findCounterAxisLineWidth(xa, 'left', ya, axList);
xLinesXLeft = xa._offset - (leftYLineWidth ? (pad + leftYLineWidth) : 0);
rightYLineWidth = findCounterAxisLineWidth(xa, 'right', ya, axList);
xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? (pad + rightYLineWidth) : 0);
xLinesYBottom = getLinePosition(xa, ya, 'bottom');
xLinesYTop = getLinePosition(xa, ya, 'top');
// save axis line positions for extra ticks to reference
// each subplot that gets ticks from "allticks" gets an entry:
// [left or bottom, right or top]
extraSubplot = (!xa._anchorAxis || subplot !== xa._mainSubplot);
if(extraSubplot && (xa.mirror === 'allticks' || xa.mirror === 'all')) {
xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop];
}
xPath = mainPath(xa, xLinePath, xLinePathFree);
if(extraSubplot && xa.showline && (xa.mirror === 'all' || xa.mirror === 'allticks')) {
xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop);
}
plotinfo.xlines
.style('stroke-width', xa._lw + 'px')
.call(Color.stroke, xa.showline ?
xa.linecolor : 'rgba(0,0,0,0)');
}
plotinfo.xlines.attr('d', xPath);
/*
* y lines that meet x axes get longer only by margin.pad, because
* the x axes fill in the corner space. Free y axes, like free x axes,
* always span exactly the data area of the plot
*
* | | XXXX
* y2| y1| XXXX
* | | XXXX
* |
* +-----
*/
var yPath = 'M0,0';
if(shouldShowLinesOrTicks(ya, subplot)) {
connectYBottom = findCounterAxisLineWidth(ya, 'bottom', xa, axList);
yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad : 0);
connectYTop = findCounterAxisLineWidth(ya, 'top', xa, axList);
yLinesYTop = ya._offset - (connectYTop ? pad : 0);
yLinesXLeft = getLinePosition(ya, xa, 'left');
yLinesXRight = getLinePosition(ya, xa, 'right');
extraSubplot = (!ya._anchorAxis || subplot !== ya._mainSubplot);
if(extraSubplot && (ya.mirror === 'allticks' || ya.mirror === 'all')) {
ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight];
}
yPath = mainPath(ya, yLinePath, yLinePathFree);
if(extraSubplot && ya.showline && (ya.mirror === 'all' || ya.mirror === 'allticks')) {
yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight);
}
plotinfo.ylines
.style('stroke-width', ya._lw + 'px')
.call(Color.stroke, ya.showline ?
ya.linecolor : 'rgba(0,0,0,0)');
}
plotinfo.ylines.attr('d', yPath);
}
Axes.makeClipPaths(gd);
return gd._promises.length && Promise.all(gd._promises);
}
function shouldShowLinesOrTicks(ax, subplot) {
return (ax.ticks || ax.showline) &&
(subplot === ax._mainSubplot || ax.mirror === 'all' || ax.mirror === 'allticks');
}
/*
* should we draw a line on counterAx at this side of ax?
* It's assumed that counterAx is known to overlay the subplot we're working on
* but it may not be its main axis.
*/
function shouldShowLineThisSide(ax, side, counterAx) {
// does counterAx get a line at all?
if(!counterAx.showline || !counterAx._lw) return false;
// are we drawing *all* lines for counterAx?
if(counterAx.mirror === 'all' || counterAx.mirror === 'allticks') return true;
var anchorAx = counterAx._anchorAxis;
// is this a free axis? free axes can only have a subplot side-line with all(ticks)? mirroring
if(!anchorAx) return false;
// in order to handle cases where the user forgot to anchor this axis correctly
// (because its default anchor has the same domain on the relevant end)
// check whether the relevant position is the same.
var sideIndex = alignmentConstants.FROM_BL[side];
if(counterAx.side === side) {
return anchorAx.domain[sideIndex] === ax.domain[sideIndex];
}
return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex];
}
/*
* Is there another axis intersecting `side` end of `ax`?
* First look at `counterAx` (the axis for this subplot),
* then at all other potential counteraxes on or overlaying this subplot.
* Take the line width from the first one that has a line.
*/
function findCounterAxisLineWidth(ax, side, counterAx, axList) {
if(shouldShowLineThisSide(ax, side, counterAx)) {
return counterAx._lw;
}
for(var i = 0; i < axList.length; i++) {
var axi = axList[i];
if(axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) {
return axi._lw;
}
}
return 0;
}
exports.drawMainTitle = function(gd) {
var fullLayout = gd._fullLayout;
var textAnchor = getMainTitleTextAnchor(fullLayout);
var dy = getMainTitleDy(fullLayout);
Titles.draw(gd, 'gtitle', {
propContainer: fullLayout,
propName: 'title.text',
placeholder: fullLayout._dfltTitle.plot,
attributes: {
x: getMainTitleX(fullLayout, textAnchor),
y: getMainTitleY(fullLayout, dy),
'text-anchor': textAnchor,
dy: dy
}
});
};
function getMainTitleX(fullLayout, textAnchor) {
var title = fullLayout.title;
var gs = fullLayout._size;
var hPadShift = 0;
if(textAnchor === SVG_TEXT_ANCHOR_START) {
hPadShift = title.pad.l;
} else if(textAnchor === SVG_TEXT_ANCHOR_END) {
hPadShift = -title.pad.r;
}
switch(title.xref) {
case 'paper':
return gs.l + gs.w * title.x + hPadShift;
case 'container':
default:
return fullLayout.width * title.x + hPadShift;
}
}
function getMainTitleY(fullLayout, dy) {
var title = fullLayout.title;
var gs = fullLayout._size;
var vPadShift = 0;
if(dy === '0em' || !dy) {
vPadShift = -title.pad.b;
} else if(dy === alignmentConstants.CAP_SHIFT + 'em') {
vPadShift = title.pad.t;
}
if(title.y === 'auto') {
return gs.t / 2;
} else {
switch(title.yref) {
case 'paper':
return gs.t + gs.h - gs.h * title.y + vPadShift;
case 'container':
default:
return fullLayout.height - fullLayout.height * title.y + vPadShift;
}
}
}
function getMainTitleTextAnchor(fullLayout) {
var title = fullLayout.title;
var textAnchor = SVG_TEXT_ANCHOR_MIDDLE;
if(Lib.isRightAnchor(title)) {
textAnchor = SVG_TEXT_ANCHOR_END;
} else if(Lib.isLeftAnchor(title)) {
textAnchor = SVG_TEXT_ANCHOR_START;
}
return textAnchor;
}
function getMainTitleDy(fullLayout) {
var title = fullLayout.title;
var dy = '0em';
if(Lib.isTopAnchor(title)) {
dy = alignmentConstants.CAP_SHIFT + 'em';
} else if(Lib.isMiddleAnchor(title)) {
dy = alignmentConstants.MID_SHIFT + 'em';
}
return dy;
}
exports.doTraceStyle = function(gd) {
var calcdata = gd.calcdata;
var editStyleCalls = [];
var i;
for(i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var cd0 = cd[0] || {};
var trace = cd0.trace || {};
var _module = trace._module || {};
// See if we need to do arraysToCalcdata
// call it regardless of what change we made, in case
// supplyDefaults brought in an array that was already
// in gd.data but not in gd._fullData previously
var arraysToCalcdata = _module.arraysToCalcdata;
if(arraysToCalcdata) arraysToCalcdata(cd, trace);
var editStyle = _module.editStyle;
if(editStyle) editStyleCalls.push({fn: editStyle, cd0: cd0});
}
if(editStyleCalls.length) {
for(i = 0; i < editStyleCalls.length; i++) {
var edit = editStyleCalls[i];
edit.fn(gd, edit.cd0);
}
clearGlCanvases(gd);
exports.redrawReglTraces(gd);
}
Plots.style(gd);
Registry.getComponentMethod('legend', 'draw')(gd);
return Plots.previousPromises(gd);
};
exports.doColorBars = function(gd) {
for(var i = 0; i < gd.calcdata.length; i++) {
var cdi0 = gd.calcdata[i][0];
if((cdi0.t || {}).cb) {
var trace = cdi0.trace;
var cb = cdi0.t.cb;
if(Registry.traceIs(trace, 'contour')) {
cb.line({
width: trace.contours.showlines !== false ?
trace.line.width : 0,
dash: trace.line.dash,
color: trace.contours.coloring === 'line' ?
cb._opts.line.color : trace.line.color
});
}
var moduleOpts = trace._module.colorbar;
var containerName = moduleOpts.container;
var opts = (containerName ? trace[containerName] : trace).colorbar;
cb.options(opts)();
}
}
return Plots.previousPromises(gd);
};
// force plot() to redo the layout and replot with the modified layout
exports.layoutReplot = function(gd) {
var layout = gd.layout;
gd.layout = undefined;
return Registry.call('plot', gd, '', layout);
};
exports.doLegend = function(gd) {
Registry.getComponentMethod('legend', 'draw')(gd);
return Plots.previousPromises(gd);
};
exports.doTicksRelayout = function(gd) {
Axes.draw(gd, 'redraw');
if(gd._fullLayout._hasOnlyLargeSploms) {
Registry.subplotsRegistry.splom.updateGrid(gd);
clearGlCanvases(gd);
exports.redrawReglTraces(gd);
}
exports.drawMainTitle(gd);
return Plots.previousPromises(gd);
};
exports.doModeBar = function(gd) {
var fullLayout = gd._fullLayout;
ModeBar.manage(gd);
for(var i = 0; i < fullLayout._basePlotModules.length; i++) {
var updateFx = fullLayout._basePlotModules[i].updateFx;
if(updateFx) updateFx(gd);
}
return Plots.previousPromises(gd);
};
exports.doCamera = function(gd) {
var fullLayout = gd._fullLayout;
var sceneIds = fullLayout._subplots.gl3d;
for(var i = 0; i < sceneIds.length; i++) {
var sceneLayout = fullLayout[sceneIds[i]];
var scene = sceneLayout._scene;
var cameraData = sceneLayout.camera;
scene.setCamera(cameraData);
}
};
exports.drawData = function(gd) {
var fullLayout = gd._fullLayout;
var calcdata = gd.calcdata;
var i;
// remove old colorbars explicitly
for(i = 0; i < calcdata.length; i++) {
var trace = calcdata[i][0].trace;
if(trace.visible !== true || !trace._module.colorbar) {
fullLayout._infolayer.select('.cb' + trace.uid).remove();
}
}
clearGlCanvases(gd);
// loop over the base plot modules present on graph
var basePlotModules = fullLayout._basePlotModules;
for(i = 0; i < basePlotModules.length; i++) {
basePlotModules[i].plot(gd);
}
exports.redrawReglTraces(gd);
// styling separate from drawing
Plots.style(gd);
// show annotations and shapes
Registry.getComponentMethod('shapes', 'draw')(gd);
Registry.getComponentMethod('annotations', 'draw')(gd);
// Mark the first render as complete
fullLayout._replotting = false;
return Plots.previousPromises(gd);
};
// Draw (or redraw) all regl-based traces in one go,
// useful during drag and selection where buffers of targeted traces are updated,
// but all traces need to be redrawn following clearGlCanvases.
//
// Note that _module.plot for regl trace does NOT draw things
// on the canvas, they only update the buffers.
// Drawing is perform here.
//
// TODO try adding per-subplot option using gl.SCISSOR_TEST for
// non-overlaying, disjoint subplots.
//
// TODO try to include parcoords in here.
// https://github.com/plotly/plotly.js/issues/3069
exports.redrawReglTraces = function(gd) {
var fullLayout = gd._fullLayout;
if(fullLayout._has('regl')) {
var fullData = gd._fullData;
var cartesianIds = [];
var polarIds = [];
var i, sp;
if(fullLayout._hasOnlyLargeSploms) {
fullLayout._splomGrid.draw();
}
// N.B.
// - Loop over fullData (not _splomScenes) to preserve splom trace-to-trace ordering
// - Fill list if subplot ids (instead of fullLayout._subplots) to handle cases where all traces
// of a given module are `visible !== true`
for(i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if(trace.visible === true) {
if(trace.type === 'splom') {
fullLayout._splomScenes[trace.uid].draw();
} else if(trace.type === 'scattergl') {
Lib.pushUnique(cartesianIds, trace.xaxis + trace.yaxis);
} else if(trace.type === 'scatterpolargl') {
Lib.pushUnique(polarIds, trace.subplot);
}
}
}
for(i = 0; i < cartesianIds.length; i++) {
sp = fullLayout._plots[cartesianIds[i]];
if(sp._scene) sp._scene.draw();
}
for(i = 0; i < polarIds.length; i++) {
sp = fullLayout[polarIds[i]]._subplot;
if(sp._scene) sp._scene.draw();
}
}
};
exports.doAutoRangeAndConstraints = function(gd) {
var fullLayout = gd._fullLayout;
var axList = Axes.list(gd, '', true);
var matchGroups = fullLayout._axisMatchGroups || [];
var ax;
for(var i = 0; i < axList.length; i++) {
ax = axList[i];
cleanAxisConstraints(gd, ax);
doAutoRange(gd, ax);
}
enforceAxisConstraints(gd);
groupLoop:
for(var j = 0; j < matchGroups.length; j++) {
var group = matchGroups[j];
var rng = null;
var id;
for(id in group) {
ax = Axes.getFromId(gd, id);
if(ax.autorange === false) continue groupLoop;
if(rng) {
if(rng[0] < rng[1]) {
rng[0] = Math.min(rng[0], ax.range[0]);
rng[1] = Math.max(rng[1], ax.range[1]);
} else {
rng[0] = Math.max(rng[0], ax.range[0]);
rng[1] = Math.min(rng[1], ax.range[1]);
}
} else {
rng = ax.range;
}
}
for(id in group) {
ax = Axes.getFromId(gd, id);
ax.range = rng.slice();
ax._input.range = rng.slice();
ax.setScale();
}
}
};
// An initial paint must be completed before these components can be
// correctly sized and the whole plot re-margined. fullLayout._replotting must
// be set to false before these will work properly.
exports.finalDraw = function(gd) {
Registry.getComponentMethod('shapes', 'draw')(gd);
Registry.getComponentMethod('images', 'draw')(gd);
Registry.getComponentMethod('annotations', 'draw')(gd);
// TODO: rangesliders really belong in marginPushers but they need to be
// drawn after data - can we at least get the margin pushing part separated
// out and done earlier?
Registry.getComponentMethod('rangeslider', 'draw')(gd);
// TODO: rangeselector only needs to be here (in addition to drawMarginPushers)
// because the margins need to be fully determined before we can call
// autorange and update axis ranges (which rangeselector needs to know which
// button is active). Can we break out its automargin step from its draw step?
Registry.getComponentMethod('rangeselector', 'draw')(gd);
};
exports.drawMarginPushers = function(gd) {
Registry.getComponentMethod('legend', 'draw')(gd);
Registry.getComponentMethod('rangeselector', 'draw')(gd);
Registry.getComponentMethod('sliders', 'draw')(gd);
Registry.getComponentMethod('updatemenus', 'draw')(gd);
};
|
app.factory('ProjectSvc', function($routeParams, $rootScope, $q, $location, AppConst,
ProjectRes, TagSvc, MessageSvc, AppSvc, gettextCatalog, AppLang) {
var service = {};
service.item = {};
service.list = [];
service.countItemsOnRow = 2;
service.limitOnHome = 3;
service.limit = 10;
service.begin = 0;
$rootScope.$on('project.init.meta', function(event, current, previous) {
service.initMeta();
});
service.setMeta = function() {
if (service.projectName !== undefined) {
AppSvc.setTitle([service.item['title_' + AppLang.getCurrent()], service.title]);
AppSvc.setDescription(service.item['description_' + AppLang.getCurrent()]);
AppSvc.setUrl('project/' + service.projectName);
if (service.item.images.length > 0)
AppSvc.setImage(service.item.images[0].src_url);
} else {
AppSvc.setTitle([service.title]);
AppSvc.setDescription(service.description);
AppSvc.setUrl('project');
}
};
service.initMeta = function() {
service.projectName = $routeParams.projectName;
service.title = gettextCatalog.getString(AppConst.project.strings.title);
service.description = gettextCatalog.getString(AppConst.project.strings.description);
};
service.init = function(reload) {
service.initMeta();
$q.all([
//TagSvc.load(),
service.load()
]).then(function(responseList) {
service.setMeta();
}, function() {});
};
service.goList = function() {
$location.path(AppLang.getUrlPrefix() + '/project');
};
service.goItem = function(projectName) {
$location.path(AppLang.getUrlPrefix() + '/project/' + projectName);
};
service.updateItemOnList = function(item) {
for (var i = 0; i < service.list.length; i++) {
if (item.id === service.list[i].id) {
angular.extend(service.list[i], angular.copy(item));
}
}
};
service.doCreate = function(item) {
service.slugName(item.name);
ProjectRes.actionCreate(item).then(
function(response) {
if (response.reload_source.tag === true)
TagSvc.load(true);
service.item = angular.copy(response.data[0]);
service.list.push(service.item);
MessageSvc.info('project/create/success', {
values: [item.title]
});
service.goItem(service.item.name);
}
);
};
service.doUpdate = function(item) {
service.slugName(item.name);
$rootScope.$broadcast('show-errors-check-validity');
ProjectRes.actionUpdate(item).then(
function(response) {
if (response.reload_source.tag === true)
TagSvc.load(true);
service.item = angular.copy(response.data[0]);
service.updateItemOnList(service.item);
MessageSvc.info('project/update/success', {
values: [item.title]
});
service.goItem(service.item.name);
}
);
};
service.doDelete = function(item) {
MessageSvc.confirm('project/delete/confirm', {
values: [item.title]
},
function() {
ProjectRes.actionDelete(item).then(
function(response) {
for (var i = 0; i < service.list.length; i++) {
if (service.list[i].id == item.id) {
service.list.splice(i, 1);
break;
}
}
MessageSvc.info('project/delete/success', {
values: [item.title]
});
service.clearItem();
service.goList();
}
);
});
};
service.doDeleteImage = function(index) {
service.item.images.splice(index, 1);
};
service.doAddImage = function(text) {
if (text === undefined)
text = '';
if (service.item.images === undefined)
service.item.images = [];
service.item.images.push({
id: chance.guid(),
title: text
});
};
service.slugName = function(value) {
if (service.item.id === undefined)
service.item.name = getSlug(value, {
lang: AppLang.getCurrent(),
uric: true
});
};
service.clearItem = function() {
service.item = {};
/*service.title = '';
service.name = '';
service.description = '';
service.url = '';
service.text = '';
service.html = '';
service.markdown = '';*/
service.item.type = 1;
service.item.tags = [];
service.item.images = [];
};
service.load = function(reload) {
var deferred = $q.defer();
if (service.projectName !== undefined) {
if (service.item.name !== service.projectName)
ProjectRes.getItem(service.projectName).then(
function(response) {
service.item = angular.copy(response.data[0]);
deferred.resolve(service.item);
},
function(response) {
service.clearItem();
deferred.resolve(service.item);
}
);
else
deferred.resolve(service.item);
} else {
if (service.loaded !== true || reload === true) {
service.loaded = true;
ProjectRes.getList().then(function(response) {
service.list = angular.copy(response.data);
deferred.resolve(service.list);
}, function(response) {
service.list = [];
deferred.resolve(service.list);
});
} else
deferred.resolve(service.list);
}
return deferred.promise;
};
return service;
}); |
export default String('\n\
uniform vec3 ambientLightColor;\n\
\n\
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\
\n\
vec3 irradiance = ambientLightColor;\n\
\n\
#ifndef PHYSICALLY_CORRECT_LIGHTS\n\
\n\
irradiance *= PI;\n\
\n\
#endif\n\
\n\
return irradiance;\n\
\n\
}\n\
\n\
#if NUM_DIR_LIGHTS > 0\n\
\n\
struct DirectionalLight {\n\
vec3 direction;\n\
vec3 color;\n\
\n\
int shadow;\n\
float shadowBias;\n\
float shadowRadius;\n\
vec2 shadowMapSize;\n\
};\n\
\n\
uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\
\n\
void getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\
\n\
directLight.color = directionalLight.color;\n\
directLight.direction = directionalLight.direction;\n\
directLight.visible = true;\n\
\n\
}\n\
\n\
#endif\n\
\n\
\n\
#if NUM_POINT_LIGHTS > 0\n\
\n\
struct PointLight {\n\
vec3 position;\n\
vec3 color;\n\
float distance;\n\
float decay;\n\
\n\
int shadow;\n\
float shadowBias;\n\
float shadowRadius;\n\
vec2 shadowMapSize;\n\
};\n\
\n\
uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\
\n\
// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\
void getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\
\n\
vec3 lVector = pointLight.position - geometry.position;\n\
directLight.direction = normalize( lVector );\n\
\n\
float lightDistance = length( lVector );\n\
\n\
directLight.color = pointLight.color;\n\
directLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\
directLight.visible = ( directLight.color != vec3( 0.0 ) );\n\
\n\
}\n\
\n\
#endif\n\
\n\
\n\
#if NUM_SPOT_LIGHTS > 0\n\
\n\
struct SpotLight {\n\
vec3 position;\n\
vec3 direction;\n\
vec3 color;\n\
float distance;\n\
float decay;\n\
float coneCos;\n\
float penumbraCos;\n\
\n\
int shadow;\n\
float shadowBias;\n\
float shadowRadius;\n\
vec2 shadowMapSize;\n\
};\n\
\n\
uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\
\n\
// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\
void getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\
\n\
vec3 lVector = spotLight.position - geometry.position;\n\
directLight.direction = normalize( lVector );\n\
\n\
float lightDistance = length( lVector );\n\
float angleCos = dot( directLight.direction, spotLight.direction );\n\
\n\
if ( angleCos > spotLight.coneCos ) {\n\
\n\
float spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\
\n\
directLight.color = spotLight.color;\n\
directLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\
directLight.visible = true;\n\
\n\
} else {\n\
\n\
directLight.color = vec3( 0.0 );\n\
directLight.visible = false;\n\
\n\
}\n\
}\n\
\n\
#endif\n\
\n\
\n\
#if NUM_RECT_AREA_LIGHTS > 0\n\
\n\
struct RectAreaLight {\n\
vec3 color;\n\
vec3 position;\n\
vec3 halfWidth;\n\
vec3 halfHeight;\n\
};\n\
\n\
// Pre-computed values of LinearTransformedCosine approximation of BRDF\n\
// BRDF approximation Texture is 64x64\n\
uniform sampler2D ltcMat; // RGBA Float\n\
uniform sampler2D ltcMag; // Alpha Float (only has w component)\n\
\n\
uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n\
\n\
#endif\n\
\n\
\n\
#if NUM_HEMI_LIGHTS > 0\n\
\n\
struct HemisphereLight {\n\
vec3 direction;\n\
vec3 skyColor;\n\
vec3 groundColor;\n\
};\n\
\n\
uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\
\n\
vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\
\n\
float dotNL = dot( geometry.normal, hemiLight.direction );\n\
float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\
\n\
vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\
\n\
#ifndef PHYSICALLY_CORRECT_LIGHTS\n\
\n\
irradiance *= PI;\n\
\n\
#endif\n\
\n\
return irradiance;\n\
\n\
}\n\
\n\
#endif\n\
\n\
\n\
#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\
\n\
vec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {\n\
\n\
vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\
\n\
#ifdef ENVMAP_TYPE_CUBE\n\
\n\
vec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\
\n\
// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\n\
// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\n\
\n\
#ifdef TEXTURE_LOD_EXT\n\
\n\
vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\
\n\
#else\n\
\n\
// force the bias high to get the last LOD level as it is the most blurred.\n\
vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\
\n\
#endif\n\
\n\
envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\
\n\
#elif defined( ENVMAP_TYPE_CUBE_UV )\n\
\n\
vec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\
vec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\
\n\
#else\n\
\n\
vec4 envMapColor = vec4( 0.0 );\n\
\n\
#endif\n\
\n\
return PI * envMapColor.rgb * envMapIntensity;\n\
\n\
}\n\
\n\
// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\n\
float getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\
\n\
//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\n\
//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\
\n\
float maxMIPLevelScalar = float( maxMIPLevel );\n\
float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\
\n\
// clamp to allowable LOD ranges.\n\
return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\
\n\
}\n\
\n\
vec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\
\n\
#ifdef ENVMAP_MODE_REFLECTION\n\
\n\
vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\
\n\
#else\n\
\n\
vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\
\n\
#endif\n\
\n\
reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\
\n\
float specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\
\n\
#ifdef ENVMAP_TYPE_CUBE\n\
\n\
vec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\
\n\
#ifdef TEXTURE_LOD_EXT\n\
\n\
vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\
\n\
#else\n\
\n\
vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\
\n\
#endif\n\
\n\
envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\
\n\
#elif defined( ENVMAP_TYPE_CUBE_UV )\n\
\n\
vec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\
vec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\
\n\
#elif defined( ENVMAP_TYPE_EQUIREC )\n\
\n\
vec2 sampleUV;\n\
sampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\
sampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\
\n\
#ifdef TEXTURE_LOD_EXT\n\
\n\
vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\
\n\
#else\n\
\n\
vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\
\n\
#endif\n\
\n\
envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\
\n\
#elif defined( ENVMAP_TYPE_SPHERE )\n\
\n\
vec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\
\n\
#ifdef TEXTURE_LOD_EXT\n\
\n\
vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\
\n\
#else\n\
\n\
vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\
\n\
#endif\n\
\n\
envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\
\n\
#endif\n\
\n\
return envMapColor.rgb * envMapIntensity;\n\
\n\
}\n\
\n\
#endif\n\
').replace( /[ \t]*\/\/.*\n/g, '' ).replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' ).replace( /\n{2,}/g, '\n' ); |
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & sisane-server
* sisane is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* 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';
moduloTipousuario.controller('TipousuarioPListController', ['$scope', '$routeParams', '$location', 'serverService', 'tipousuarioService', '$uibModal',
function ($scope, $routeParams, $location, serverService, tipousuarioService, $uibModal) {
$scope.fields = tipousuarioService.getFields();
$scope.obtitle = tipousuarioService.getObTitle();
$scope.icon = tipousuarioService.getIcon();
$scope.ob = tipousuarioService.getTitle();
$scope.title = "Listado de " + $scope.obtitle;
$scope.op = "plist";
$scope.numpage = serverService.checkDefault(1, $routeParams.page);
$scope.rpp = serverService.checkDefault(10, $routeParams.rpp);
$scope.neighbourhood = serverService.getGlobalNeighbourhood();
$scope.order = "";
$scope.ordervalue = "";
$scope.filter = "id";
$scope.filteroperator = "like";
$scope.filtervalue = "";
$scope.filterParams = serverService.checkNull($routeParams.filter)
$scope.orderParams = serverService.checkNull($routeParams.order)
$scope.sfilterParams = serverService.checkNull($routeParams.sfilter)
$scope.filterExpression = serverService.getFilterExpression($routeParams.filter, $routeParams.sfilter);
$scope.status = null;
$scope.debugging = serverService.debugging();
$scope.url = $scope.ob + '/' + $scope.op;
function getDataFromServer() {
serverService.promise_getCount($scope.ob, $scope.filterExpression).then(function (response) {
if (response.status == 200) {
$scope.registers = response.data.message;
$scope.pages = serverService.calculatePages($scope.rpp, $scope.registers);
if ($scope.numpage > $scope.pages) {
$scope.numpage = $scope.pages;
}
return serverService.promise_getPage($scope.ob, $scope.rpp, $scope.numpage, $scope.filterExpression, $routeParams.order);
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).then(function (response) {
if (response.status == 200) {
$scope.page = response.data.message;
$scope.status = "";
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
}
getDataFromServer();
}]);
|
import {inject} from 'aurelia-framework';
import {EditSessionFactory} from '../editing/edit-session-factory';
import {CurrentFileChangedEvent} from '../editing/current-file-changed-event';
import {QueryString} from '../editing/query-string';
import {defaultGist} from '../github/default-gist';
import {Importer} from '../import/importer';
import {Focus} from './focus';
import alertify from 'alertify';
@inject(EditSessionFactory, Importer, QueryString, Focus)
export class App {
editSession = null;
constructor(editSessionFactory, importer, queryString, focus) {
this.editSessionFactory = editSessionFactory;
this.importer = importer;
this.queryString = queryString;
this.focus = focus;
addEventListener('beforeunload', ::this.beforeUnload);
}
beforeUnload(event) {
if (this.editSession && this.editSession.dirty) {
event.returnValue = 'You have unsaved work in this Gist.';
}
}
currentFileChanged(event) {
if (event.file.name === '') {
this.focus.set('filename');
} else {
this.focus.set('editor');
}
}
setEditSession(editSession) {
if (this.fileChangedSub) {
this.fileChangedSub.dispose();
}
this.editSession = editSession;
this.fileChangedSub = editSession.subscribe(CurrentFileChangedEvent, ::this.currentFileChanged);
this.editSession.resetWorker().then(::this.editSession.run);
}
activate() {
return this.queryString.read()
.then(gist => this.setEditSession(this.editSessionFactory.create(gist)));
}
newGist() {
this.queryString.clear();
this.setEditSession(this.editSessionFactory.create(defaultGist));
}
import(urlOrId) {
this.importer.import(urlOrId)
.then(gist => {
this.queryString.write(gist, true);
return this.editSessionFactory.create(gist);
})
.then(::this.setEditSession)
.then(() => alertify.success('Import successful.'), reason => alertify.error(reason));
}
}
|
import Component from '@ember/component';
import EObject, {
computed,
observer,
get,
set
} from '@ember/object';
import { htmlSafe } from '@ember/string';
import { debounce, next, throttle } from '@ember/runloop';
import { inject as service } from '@ember/service';
import { A } from '@ember/array';
import $ from 'jquery';
import layout from '../templates/components/emoji-picker';
import ClickOutsideMixin from 'ember-click-outside/mixin';
const O = EObject.create.bind(EObject);
import {
EMOJI_PROP_NAMES_TONE,
EMOJI_PROP_NAMES_TONE_TONE,
EMOJI_CATEGORIES_ARRAY,
} from "ember-emojione/-private/utils/constants";
const EMOJI_PICKER_SCROLLABLE_ELEMENT = '.eeo-emojiPicker-scrollable';
export default Component.extend(ClickOutsideMixin, {
selectAction: undefined,
toneSelectAction: () => {},
closeAction: () => {},
shouldCloseOnSelect: false,
disableAutoFocus: false,
textNoEmojiFound: "No emoji found",
textSearch: "Search",
textClearSearch: "Clear search",
emojiService: service('emoji'),
layout,
classNames: ['eeo-emojiPicker'],
_filterInput: '',
filterInput: '',
scrollableId: computed(function () {
return Math.random().toString(36).substr(2, 5);
}),
$scrollable: computed(function () {
return $(this.element).find(EMOJI_PICKER_SCROLLABLE_ELEMENT);
}),
$filterInput: computed(function () {
return $(this.element).find('.eeo-emojiPicker-filter-input');
}),
emoji: computed(
'emojiService.currentSkinTone',
EMOJI_PROP_NAMES_TONE,
function () {
const currentSkinTone = this.get('emojiService.currentSkinTone');
const emojiPropName = `emojiService.emoji__tone_${currentSkinTone}`;
return this.get(emojiPropName);
}
),
categorySections: computed('emojiService.categories', function () {
const objs =
this
.get('emojiService.categories')
.map(category => O({
category,
style: htmlSafe("")
}));
return A(objs);
}),
emojiByCategoryIdFiltered: computed(
'filterInput',
'emojiService.currentSkinTone',
'emojiService.categories.@each.id',
EMOJI_PROP_NAMES_TONE_TONE,
function () {
const emojiCategories = this.get('emojiService.categories');
const filterStrs = this.get('filterInput').split(' ');
return emojiCategories.reduce((result, category) => {
const categoryId = category.get('id');
const emoji = this._getEmojiForCategoryId(categoryId);
let visibleCount = 0;
emoji.forEach(emojo => {
const isVisible =
filterStrs
? filterStrs.every(str => get(emojo, 'filterable').indexOf(str) > -1)
: true;
set(emojo, 'isVisible', isVisible);
if (isVisible) visibleCount++;
});
result.set(categoryId, {emoji, visibleCount});
return result;
}, O());
}
),
filteredEmojiCount: computed('emojiByCategoryIdFiltered', function () {
return EMOJI_CATEGORIES_ARRAY.reduce((count, category) => {
return count + this.get(`emojiByCategoryIdFiltered.${category}.visibleCount`);
}, 0);
}),
_applyFilterInput(filterInput) {
if (this.get('isDestroying') || this.get('isDestroyed')) return;
this.setProperties({filterInput});
next(() => this._updateScroll());
},
_updateScroll() {
if (this.get('isDestroying') || this.get('isDestroyed')) return;
const $scrollable = this.get('$scrollable');
const parHeight = $scrollable.innerHeight();
this
.get('categorySections')
.forEach(section => {
const id = section.category.get('id');
const $category = $(this.element)
.find(`.eeo-emojiPicker-category._${id} .eeo-emojiPicker-category-emoji`);
if (!$category.length) {
section.set('style', htmlSafe(''));
return;
}
const catTop = $category.position().top;
const catHeight = $category.outerHeight();
const catBottom = catTop + catHeight;
const left = (-catTop) / catHeight;
const right = (catBottom - parHeight) / catHeight;
const style = htmlSafe(`left: ${left * 100}%; right: ${right * 100}%;`);
section.setProperties({style});
});
},
_getEmojiForCategoryId(categoryId) {
const currentSkinTone = this.get('emojiService.currentSkinTone');
const emojiPropName = `emojiService.${categoryId}__tone_${currentSkinTone}`;
return this.get(emojiPropName);
},
_focusOnSearch() {
if (this.get('disableAutoFocus')) return;
this.get('$filterInput').focus();
},
didInsertElement() {
this._super(...arguments);
this._updateScroll();
$(this.element)
.find(EMOJI_PICKER_SCROLLABLE_ELEMENT)
.on('scroll.eeo', () => throttle(this, this._updateScroll, 200, false));
next(() => this.addClickOutsideListener());
},
willDestroyElement() {
this._super(...arguments);
$(this.element)
.find(EMOJI_PICKER_SCROLLABLE_ELEMENT)
.off('scroll.eeo');
this.removeClickOutsideListener();
},
clickOutside() {
this.closeAction();
},
_applyFilterInputDebounced: observer('_filterInput', function () {
const filterInput = this.get('_filterInput');
debounce(this, this._applyFilterInput, filterInput, 200, false);
}),
_restoreBarOnShow: observer('isVisible', function () {
if (!this.get('isVisible')) return;
next(() => {
this._updateScroll();
this._focusOnSearch();
});
}),
actions: {
selectEmojo(emojo, shouldFocus = true) {
this.selectAction(emojo, {shouldFocus});
if (this.get('shouldCloseOnSelect')) {
this.closeAction(true);
}
},
inputFilteringText(_filterInput) {
this.setProperties({_filterInput});
},
selectFirstFilteredEmojo() {
let emojo = null;
const emojiByCategoryIdFiltered = this.get('emojiByCategoryIdFiltered');
EMOJI_CATEGORIES_ARRAY
.map(categoryName => emojiByCategoryIdFiltered.get(categoryName))
.filter(categoryHash => get(categoryHash, 'visibleCount'))
.find(categoryHash => {
return emojo = get(categoryHash, 'emoji').find(emojo => get(emojo, 'isVisible'));
});
if (emojo) this.send('selectEmojo', emojo, false);
},
clearFilterOrClose() {
if (this.get('filterInput.length')) {
this.send('inputFilteringText', '');
return;
}
this.closeAction(true);
}
}
});
|
import { connect } from 'react-redux';
import { setDefaultSettings } from 'src/actions';
import { Start } from './start';
const mapStateToProps = (state) => {
return {
user: state.user //eslint-disable-line
};
};
const mapDispatchToProps = (dispatch) => {
return {
onMenuClick: (menu) => { //eslint-disable-line
dispatch(setDefaultSettings());
}
};
};
const StartContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Start);
export default StartContainer;
|
import _ from 'lodash';
import { EventEmitter } from 'events';
import { ActionTypes } from '../constants/ActorAppConstants';
import Dispatcher from '../dispatcher/ActorAppDispatcher';
const CHANGE_EVENT = 'change';
let modalOpen = false;
const CreateGroupStore = _.assign(EventEmitter.prototype, {
emitChange: () => {
CreateGroupStore.emit(CHANGE_EVENT);
},
addChangeListener: (cb) => {
CreateGroupStore.on(CHANGE_EVENT, cb);
},
removeChangeListener: (cb) => {
CreateGroupStore.removeListener(CHANGE_EVENT, cb);
},
isModalOpen: () => {
return modalOpen;
}
});
CreateGroupStore.dispatchToken = Dispatcher.register((action) => {
switch (action.type) {
case ActionTypes.CREATE_GROUP_MODAL_OPEN:
modalOpen = true;
CreateGroupStore.emitChange();
break;
case ActionTypes.CREATE_GROUP_MODAL_CLOSE:
modalOpen = false;
CreateGroupStore.emitChange();
}
});
export default CreateGroupStore;
|
var searchData=
[
['file',['File',['../classsol_1_1_file.html#adadcbaa4e64c50bf4416b77318c90b1f',1,'sol::File::File(const std::string &filename, const std::string &mode)'],['../classsol_1_1_file.html#a6ec6975155acae9a784ee39252ccd974',1,'sol::File::File()=default']]],
['fillbuffer',['fillBuffer',['../classsol_1_1_audio.html#aef8ec1c7845f21b9c99fbe5f5c91144b',1,'sol::Audio']]],
['filter',['Filter',['../classsol_1_1_filter.html#ae150f88a367fbac22875fdfe1473f5a9',1,'sol::Filter']]],
['flipflop',['flipflop',['../structsol_1_1_vec2.html#afb3995ae1b0be7c66e55556b796b68a0',1,'sol::Vec2']]],
['framebuffer',['Framebuffer',['../classsol_1_1_framebuffer.html#a494d491b79efe568626b025624595da6',1,'sol::Framebuffer']]]
];
|
import {style} from './ProgressBar.scss';
import React from 'react';
//
// Component
// -----------------------------------------------------------------------------
class ProgressBarView extends React.Component {
constructor(props) {
super(props);
}
static defaultProps = {
progress: 0,
showText: false
};
static propTypes = {
progress: React.PropTypes.number.isRequired,
showText: React.PropTypes.bool.isRequired
};
//
// Render
// -----------------------------------------------------------------------------
render() {
const {progress, showText} = this.props;
const rounded = Math.round(progress);
return (
<div className={style}>
<div className='progress'>
<div className='progress-bar' role='progressbar' aria-valuenow={rounded}
aria-valuemax='100' style={{width: `${rounded}%`}}>
{showText ? `${rounded}%` : null}
</div>
</div>
</div>
);
}
}
export default ProgressBarView
|
// 用户歌单
module.exports = (query, request) => {
const data = {
uid: query.uid,
limit: query.limit || 30,
offset: query.offset || 0,
includeVideo: true,
}
return request('POST', `https://music.163.com/api/user/playlist`, data, {
crypto: 'weapi',
cookie: query.cookie,
proxy: query.proxy,
realIP: query.realIP,
})
}
|
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
bookmarklet = require('./bookmarklet');
gulp.task('bookmark-it', function () {
gulp.src('./src/**/*.js')
.pipe(uglify())
.pipe(bookmarklet())
.pipe(gulp.dest('./dist/'));
});
gulp.task('default', [
'bookmark-it'
]);
|
'use strict';
const Boom = require('boom');
const Joi = require('joi');
const util = require('util');
// Minimum 8 chars total with at least one upper case, one lower case and a digit
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d\W]{8,255}$/;
module.exports.list = {
tags: ['api', 'users'],
description: 'List users',
notes: 'List users with pagination',
auth: {scope: [ 'admin' ]},
validate: {
query: {
name: Joi.string(),
isActive: Joi.boolean(),
scope: Joi.string().valid(['admin', 'user']),
fields: Joi.string(),
sort: Joi.string().default('_id'),
limit: Joi.number().default(20),
page: Joi.number().default(1)
}
},
handler: function (request, reply) {
const User = request.server.plugins['hapi-mongo-models'].User;
const filterByKeys = ['isActive', 'firstName', 'scope'];
// pass only 'search' criteria
const criteria = filterByKeys.reduce((result, key) => {
if (request.query[key]) {
result[key] = request.query[key];
}
return result;
}, {});
const fields = request.query.fields;
const sort = request.query.sort;
const limit = request.query.limit;
const page = request.query.page;
User.pagedFind(criteria, fields, sort, limit, page, (err, results) => {
if (err) return reply(err);
reply(results);
});
}
};
module.exports.create = {
tags: ['api', 'users'],
description: 'Create a new user',
notes: 'Create a new user (non-admin) with first & last name, email and password.',
auth: false,
validate: {
payload: {
firstName: Joi.string().min(2).max(255).required(),
lastName: Joi.string().min(2).max(255).required(),
email: Joi.string().email().required(),
password: Joi.string().regex(passwordRegex).required(),
passwordConfirmation: Joi.string().min(8).max(200).required().valid(Joi.ref('password'))
}
},
handler: function (request, reply) {
const User = request.server.plugins['hapi-mongo-models'].User;
User.findByEmail(request.payload.email, (err, user) => {
if (err) return reply(err);
if (user) return reply(Boom.conflict('Email already in use.'));
let data = {
firstName: request.payload.firstName,
lastName:request.payload.lastName,
email: request.payload.email,
password: User.generatePasswordHash(request.payload.password)
};
// Use the local strategy
User.create(data, 'local', (onCreateError, newUser) => {
if (onCreateError) {
console.log(onCreateError);
return reply(onCreateError);
}
let response = newUser.profile;
response._id = newUser._id;
response.email = newUser.email;
response.timeCreated = newUser.timeCreated;
reply(response).code(201);
});
});
}
};
module.exports.viewProfile = {
tags: ['api', 'users'],
description: 'My profile',
notes: 'User can request his own profile data on this route',
auth: {scope: ['user', 'admin']},
handler: function (request, reply) {
const User = request.server.plugins['hapi-mongo-models'].User;
const fields = User.fieldsAdapter('profile email _id timeCreated');
const id = request.auth.credentials.id.toString();
// Example how to use promises with Mongo Models:
util
.promisify(User.findById)
.apply(User, [id, fields])
.then(user => reply(user))
.catch(err => reply(err));
}
};
module.exports.updateProfile = {
tags: ['api', 'users'],
description: 'Update user',
auth: {scope: ['user', 'admin']},
notes: 'Logged in user is able to update his own profile: names and image',
validate: {
payload: Joi.object()
.keys({
firstName: Joi.string().min(2).max(255).required(),
lastName: Joi.string().min(2).max(255).required(),
image: Joi.string().uri().optional()
})
},
handler: function (request, reply) {
const User = request.server.plugins['hapi-mongo-models'].User;
const id = request.auth.credentials.id.toString();
const update = request.payload;
User.findByIdAndUpdate(id, { $set: update }, (err, user) => {
if (err) return reply(err);
if (!user) return reply(Boom.notFound('User not found'));
delete user.password;
reply(user);
});
}
};
module.exports.updatePassword = {
tags: ['api', 'users'],
description: 'Update user',
auth: {scope: ['admin', 'user']},
notes: 'Logged in user is able to update his own password',
validate: {
payload: Joi.object()
.keys({
oldPassword: Joi.string().regex(passwordRegex).optional(),
newPassword: Joi.string().regex(passwordRegex).optional(),
newPasswordConfirmation: Joi.string().valid(Joi.ref('newPassword'))
})
.with('oldPassword', 'newPassword', 'newPasswordConfirmation')
},
handler: function (request, reply) {
const User = request.server.plugins['hapi-mongo-models'].User;
const id = request.auth.credentials.id.toString();
/* TODO: Limit to 3 failed attempts (with wrong old password) in a single day
TODO: Send an email that the password had been changed or has 3 failed attempts
TODO: More logging: The server should always log attempts to change passwords whether they are successful or not. It should log the user's information but not any passwords entered or their hashes. It should note whether the change succeeded or failed.
TODO: Add reCAPTCHA
*/
User.findById(id, (err, user) => {
if (err) return reply(err);
if (!user || !User.validPassword(request.payload.oldPassword, user.password)) {
return reply(Boom.badRequest('Sorry, provided old password is incorrect'));
}
const update = {
password: User.generatePasswordHash(request.payload.newPassword)
};
User.findByIdAndUpdate(id, { $set: update }, (err, user) => {
if (err) return reply(err);
if (!user) return reply(Boom.notFound('User not found'));
delete user.password;
reply(user);
});
});
}
};
module.exports.get = {
tags: ['api', 'users'],
description: 'Get user',
notes: 'Read single user\'s data',
auth: {scope: [ 'admin' ]},
validate: {
params: {
id: Joi.string()
}
},
handler: function (request, reply) {
const User = request.server.plugins['hapi-mongo-models'].User;
const fields = User.fieldsAdapter('_id email profile scope isActive timeCreated');
const id = request.params.id;
util
.promisify(User.findById)
.apply(User, [ id ])
.then(user => reply(user))
.catch(err => reply(err));
}
};
module.exports.update = {
tags: ['api', 'users'],
description: 'Update user',
auth: {scope: [ 'admin' ]},
notes: 'Update user\'s data by Administrator',
validate: {
params: {
id: Joi.string() // TODO: Add lib for validation mongoDB object IDs
},
payload: Joi.object()
.keys({
firstName: Joi.string().min(2).max(255),
lastName: Joi.string().min(2).max(255),
// email: Joi.string().email(),
image: Joi.string().uri().optional(),
isActive: Joi.boolean(),
scope: Joi.string().valid(['admin', 'user'])
})
},
handler: function (request, reply) {
const User = request.server.plugins['hapi-mongo-models'].User;
const id = request.params.id;
const update = request.payload;
// TODO: If changing email -> check it for uniqueness
User.findByIdAndUpdate(id, { $set: update }, (err, user) => {
if (err) return reply(err);
if (!user) return reply(Boom.notFound('User not found'));
reply(user);
});
}
};
module.exports.delete = {
tags: ['api', 'users'],
description: 'Delete user',
notes: 'Delete user by ID',
auth: {scope: [ 'admin' ]},
validate: {
params: {
id: Joi.string()
}
},
handler: function (request, reply) {
const User = request.server.plugins['hapi-mongo-models'].User;
const id = request.params.id;
// This is not 'soft delete' btw
User.findByIdAndDelete(id, (err, user) => {
if (err) return reply(err);
if (!user) return reply(Boom.notFound('User not found'));
reply();
});
}
};
|
/*shortkeys.js*/function shortkeys(c,e,f){if(c.indexOf("+")===-1){return false}var a,d=c.split("+");document.onkeydown=function(b){switch(d[0].toLowerCase()){case"ctrl":a=b.ctrlKey;break;case"alt":a=b.altKey;break;case"shift":a=b.shiftKey;break;case"meta":a=b.metaKey;break}if(b.keyCode==d[1].toUpperCase().charCodeAt(0)&&a){e.apply(this,f);return false}}} |
#!/usr/bin/env node
const assert = require('assert');
const converter = require('../lib/index.js');
const src = `body
font 14px/1.5 Helvetica, arial, sans-serif
& #logo
border-radius 5px;
.foo
min-width()
height(1px, 2px)
// single line comment
.bar
width 42
/* block comment */
.baz
&_mod
position absolute
.bar_2
width 123px;
.bar_3
width: 123px
.bar_4
width: 123px;
.bar_5
&:hover
color red
.bar-{$index}
color red
.bar_6
color $color
.bar_7
.bar_8
color red
`;
const expected = `body {
font: 14px/1.5 Helvetica, arial, sans-serif;
& #logo {
border-radius: 5px;
}
}
.foo {
@mixin min-width;
@mixin height 1px, 2px;
}
// single line comment;
.bar {
width: 42;
}
/* block comment */;
.baz {
&_mod {
position: absolute;
}
}
.bar_2 {
width: 123px;
}
.bar_3 {
width: 123px;
}
.bar_4 {
width: 123px;
}
.bar_5 {
&:hover {
color: red;
}
}
.bar-\${index} {
color: red;
}
.bar_6 {
color: $color;
}
.bar_7 {
& .bar_8 {
color: red;
}
}
`;
assert.equal(expected, converter(src));
|
import { sequelize, Sequelize } from './index';
import HocSinh from './hocsinh-model';
import LopHoc from './lophoc-model';
const HocSinh_LopHoc = sequelize.define('HOCSINH_LOPHOC', {
maHocSinh: {
type: Sequelize.INTEGER,
primaryKey: true,
notNull: true,
field: 'MA_HOC_SINH'
},
maLopHoc: {
type: Sequelize.INTEGER,
primaryKey: true,
notNull: true,
field: 'MA_LOP_HOC'
},
tongHK1: {
type: Sequelize.DECIMAL(4, 2),
field: 'TONG_HK1'
},
tongHK2: {
type: Sequelize.DECIMAL(4, 2),
field: 'TONG_HK2'
},
tongCaNam: {
type: Sequelize.DECIMAL(4, 2),
field: 'TONG_CA_NAM'
},
passed: {
type: Sequelize.BOOLEAN,
defaultValue: false,
field: 'PASSED'
}
});
HocSinh.hasMany(HocSinh_LopHoc, { foreignKey: 'maHocSinh', sourceKey: 'hocSinh_pkey' });
HocSinh_LopHoc.belongsTo(HocSinh, { foreignKey: 'maHocSinh', targetKey: 'hocSinh_pkey' });
LopHoc.hasMany(HocSinh_LopHoc, { foreignKey: 'maLopHoc', sourceKey: 'maLop_pkey' });
HocSinh_LopHoc.belongsTo(LopHoc, { foreignKey: 'maLopHoc', targetKey: 'maLop_pkey' });
export default HocSinh_LopHoc; |
module.exports = {
"env": {
"es6": true,
"node": true
},
"plugins": [
"markdown"
],
"parserOptions": { "ecmaVersion": 2017 },
"extends": "eslint:recommended",
"rules": {
"accessor-pairs": "error",
"array-bracket-spacing": [
"error",
"never"
],
"array-callback-return": "off",
"arrow-body-style": "off",
"arrow-parens": [
"error",
"as-needed"
],
"arrow-spacing": [
"error",
{
"after": true,
"before": true
}
],
"block-scoped-var": "error",
"block-spacing": "error",
"brace-style": [
"error",
"1tbs"
],
"callback-return": "error",
"camelcase": "off",
"comma-dangle": "error",
"comma-spacing": "off",
"comma-style": [
"error",
"last"
],
"complexity": "error",
"computed-property-spacing": [
"error",
"never"
],
"consistent-return": "off",
"consistent-this": "off",
"curly": "error",
"default-case": "off",
"dot-location": [
"error",
"property"
],
"dot-notation": [
"error",
{
"allowKeywords": true
}
],
"eol-last": "off",
"eqeqeq": "off",
"func-names": "off",
"func-style": "off",
"generator-star-spacing": "error",
"global-require": "off",
"guard-for-in": "error",
"handle-callback-err": "error",
"id-blacklist": "error",
"id-length": "off",
"id-match": "error",
"indent": "off",
"init-declarations": "off",
"jsx-quotes": "error",
"key-spacing": "off",
"keyword-spacing": [
"error",
{
"after": true,
"before": true
}
],
"linebreak-style": [
"error",
"unix"
],
"lines-around-comment": "off",
"max-depth": "error",
"max-len": "off",
"max-nested-callbacks": "error",
"max-params": "off",
"max-statements": "off",
"max-statements-per-line": "error",
"new-parens": "error",
"newline-after-var": "off",
"newline-before-return": "off",
"newline-per-chained-call": "off",
"no-alert": "error",
"no-array-constructor": "error",
"no-bitwise": "off",
"no-caller": "error",
"no-catch-shadow": "error",
"no-cond-assign": [
"error",
"except-parens"
],
"no-confusing-arrow": [
"error",
{"allowParens": true}
],
"no-continue": "error",
"no-div-regex": "error",
"no-duplicate-imports": "error",
"no-else-return": "off",
"no-empty-function": "off",
"no-eq-null": "error",
"no-eval": "error",
"no-extend-native": "error",
"no-extra-bind": "off",
"no-extra-label": "error",
"no-extra-parens": "off",
"no-floating-decimal": "error",
"no-implicit-coercion": [
"error",
{
"boolean": false,
"number": false,
"string": false
}
],
"no-implicit-globals": "error",
"no-implied-eval": "error",
"no-inline-comments": "off",
"no-inner-declarations": [
"error",
"functions"
],
"no-invalid-this": "off",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-lonely-if": "off",
"no-loop-func": "error",
"no-magic-numbers": "off",
"no-mixed-requires": "off",
"no-multi-spaces": "off",
"no-multi-str": "error",
"no-multiple-empty-lines": "off",
"no-native-reassign": "error",
"no-negated-condition": "off",
"no-nested-ternary": "off",
"no-new": "error",
"no-new-func": "error",
"no-new-object": "error",
"no-new-require": "error",
"no-new-wrappers": "error",
"no-octal-escape": "error",
"no-param-reassign": "off",
"no-path-concat": "error",
"no-plusplus": "off",
"no-process-env": "off",
"no-process-exit": "off",
"no-proto": "error",
"no-prototype-builtins": "error",
"no-restricted-globals": "error",
"no-restricted-imports": "error",
"no-restricted-modules": "error",
"no-restricted-syntax": "error",
"no-return-assign": [
"error",
"except-parens"
],
"no-script-url": "error",
"no-self-compare": "error",
"no-sequences": "off",
"no-shadow": "off",
"no-shadow-restricted-names": "error",
"no-spaced-func": "off",
"no-sync": "off",
"no-ternary": "off",
"no-throw-literal": "error",
"no-trailing-spaces": "error",
"no-undef-init": "error",
"no-undefined": "off",
"no-underscore-dangle": "off",
"no-unmodified-loop-condition": "off",
"no-unneeded-ternary": "off",
"no-unsafe-finally": "error",
"no-unused-expressions": "off",
"no-use-before-define": "off",
"no-useless-call": "off",
"no-useless-computed-key": "error",
"no-useless-concat": "off",
"no-useless-constructor": "error",
"no-useless-escape": "error",
"no-useless-rename": "error",
"no-var": "error",
"no-void": "error",
"no-warning-comments": "error",
"no-whitespace-before-property": "error",
"no-with": "error",
"object-curly-spacing": ["error", "never"],
"object-property-newline": "off",
"object-shorthand": ["error", "always"],
"one-var": ["error", {"var": "always", "let": "always", "const": "never"}],
"one-var-declaration-per-line": "off",
"operator-assignment": "off",
"operator-linebreak": [
"error",
"after"
],
"padded-blocks": "off",
"prefer-arrow-callback": "error",
"prefer-const": "off",
"prefer-reflect": "off",
"prefer-rest-params": "off",
"prefer-spread": "off",
"prefer-template": "off",
"quote-props": "off",
"quotes": [
"error",
"single",
{ "avoidEscape": true }
],
"radix": [
"error",
"always"
],
"require-jsdoc": "off",
"require-yield": "error",
"semi": "error",
"semi-spacing": "off",
"sort-imports": "error",
"sort-vars": "off",
"space-before-blocks": "off",
"space-before-function-paren": "error",
"space-in-parens": [
"error",
"never"
],
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "off",
"strict": "error",
"template-curly-spacing": [
"error",
"never"
],
"unicode-bom": [
"error",
"never"
],
"valid-jsdoc": "off",
"vars-on-top": "off",
"wrap-iife": "error",
"wrap-regex": "error",
"yield-star-spacing": "error"
}
}; |
/**
* This module formats precise time differences as a vague/fuzzy
* time, e.g. '3 weeks ago', 'just now' or 'in 2 hours'.
*/
/*globals define, module */
(function (globals) {
'use strict';
var times = {
year: 31557600000, // 1000 ms * 60 s * 60 m * 24 h * 365.25 d
month: 2629800000, // 31557600000 ms / 12 m
week: 604800000, // 1000 ms * 60 s * 60 m * 24 h * 7 d
day: 86400000, // 1000 ms * 60 s * 60 m * 24 h
hour: 3600000, // 1000 ms * 60 s * 60 m
minute: 60000 // 1000 ms * 60 s
},
languages = {
nl: {
year: [ 'jaar', 'jaar' ],
month: [ 'maand', 'maanden' ],
week: [ 'week', 'weken' ],
day: [ 'dag', 'dagen' ],
hour: [ 'uur', 'uur' ],
minute: [ 'minuut', 'minuten' ],
past: function (vagueTime, unit) {
return vagueTime + ' ' + unit + ' geleden';
},
future: function (vagueTime, unit) {
return 'over ' + vagueTime + ' ' + unit;
},
defaults: {
past: 'juist nu',
future: 'binnenkort'
}
}
},
defaultLanguage = 'nl',
functions = {
get: getVagueTime
};
exportFunctions();
/**
* Public function `get`.
*
* Returns a vague time, such as '3 weeks ago', 'just now' or 'in 2 hours'.
*
* @option [from] {Date} The origin time. Defaults to `Date.now()`.
* @option [to] {Date} The target time. Defaults to `Date.now()`.
* @option [units] {string} If `from` or `to` are timestamps rather than date
* instances, this indicates the units that they are
* measured in. Can be either `ms` for milliseconds
* or `s` for seconds. Defaults to `ms`.
* @option [lang] {string} The output language. Default is specified as a
* build option.
*/
function getVagueTime (options) {
var units = normaliseUnits(options.units),
now = Date.now(),
from = normaliseTime(options.from, units, now),
to = normaliseTime(options.to, units, now),
difference = from - to,
type;
if (difference >= 0) {
type = 'past';
} else {
type = 'future';
difference = -difference;
}
return estimate(difference, type, options.lang);
}
function normaliseUnits (units) {
if (typeof units === 'undefined') {
return 'ms';
}
if (units === 's' || units === 'ms') {
return units;
}
throw new Error('Invalid units');
}
function normaliseTime(time, units, defaultTime) {
if (typeof time === 'undefined') {
return defaultTime;
}
if (typeof time === 'string') {
time = parseInt(time, 10);
}
if (isNotDate(time) && isNotTimestamp(time)) {
throw new Error('Invalid time');
}
if (typeof time === 'number' && units === 's') {
time *= 1000;
}
return time;
}
function isNotDate (date) {
return Object.prototype.toString.call(date) !== '[object Date]' || isNaN(date.getTime());
}
function isNotTimestamp (timestamp) {
return typeof timestamp !== 'number' || isNaN(timestamp);
}
function estimate (difference, type, language) {
var time, vagueTime, lang = languages[language] || languages[defaultLanguage];
for (time in times) {
if (times.hasOwnProperty(time) && difference >= times[time]) {
vagueTime = Math.floor(difference / times[time]);
return lang[type](vagueTime, lang[time][(vagueTime > 1)+0]);
}
}
return lang.defaults[type];
}
function exportFunctions () {
if (typeof define === 'function' && define.amd) {
define(function () {
return functions;
});
} else if (typeof module !== 'undefined' && module !== null) {
module.exports = functions;
} else {
globals.vagueTime = functions;
}
}
}(this));
|
'use strict';
var mean = require('meanio');
exports.render = function(req, res) {
var modules = [];
// Preparing angular modules list with dependencies
for (var name in mean.modules) {
modules.push({
name: name,
module: 'mean.' + name,
angularDependencies: mean.modules[name].angularDependencies
});
}
function isAdmin() {
return req.user && req.user.roles.indexOf('admin') !== -1;
}
// Send some basic starting info to the view
res.render('index', {
user: req.user ? {
name: req.user.name,
_id: req.user._id,
username: req.user.username,
roles: req.user.roles
} : {},
modules: modules,
isAdmin: isAdmin,
adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin')
});
};
exports.landing = function(req, res) {
var modules = [];
// Preparing angular modules list with dependencies
for (var name in mean.modules) {
modules.push({
name: name,
module: 'mean.' + name,
angularDependencies: mean.modules[name].angularDependencies
});
}
// Send some basic starting info to the view
if(req.isAuthenticated()) {
return res.redirect('/');
}
res.render('landing');
};
|
window.onload = function(){
var defaultTriggerInterval = 1;
var defaultBlockDuration = 1;
function loadOptions() {
chrome.storage.local.get("settings", function(showObj){
console.log(showObj);
var triggerInterval = showObj.settings.triggerInterval;
if (!triggerInterval) {
triggerInterval = defaultTriggerInterval;
}
var blockDuration = showObj.settings.blockDuration;
if (!blockDuration) {
blockDuration = defaultBlockDuration;
}
document.getElementById("triggerInterval").value = triggerInterval;
document.getElementById("blockDuration").value = blockDuration;
})
}
loadOptions();
document.getElementById("saveButton").addEventListener("click",function() {
var extensionStorageShow ={};
var select1 = document.getElementById("triggerInterval");
console.log(select1.value);
extensionStorageShow.triggerInterval = select1.value;
var select2 = document.getElementById("blockDuration");
extensionStorageShow.blockDuration = select2.value;
var extensionStorage = {
settings:extensionStorageShow
}
chrome.storage.local.set(extensionStorage);
alert("Your changes are saved");
});
};
|
/**
* Created by Ehbraheem on 17/03/2017.
*/
(function () {
angular
.module("pay.payment")
.component("paymentForm", {
templateUrl : templateUrl,
controller : PaymentController,
bindings: {
price : '<',
product : '<'
}
});
templateUrl.$inject = ["pay.config.APP_CONFIG"];
function templateUrl (APP_CONFIG) {
return APP_CONFIG.payment_form;
}
PaymentController.$inject = ["$scope", "pay.payment.Pay", "pay.config.APP_CONFIG"];
function PaymentController ($scope, Pay, APP_CONFIG) {
var $ctrl = this;
$ctrl.email = "";
// $ctrl.makePayment = makePayment;
$ctrl.persistDetails = persistDetails;
$ctrl.$onInit = function () {
console.log("price is",$ctrl.price);
$ctrl.orderId = Pay.getOrderId($ctrl.price);
};
$ctrl.$postLink = persistDetails();
return;
///////////////////////////////////
function orderId() {
console.log("price is",$ctrl.price);
Pay.getOrderId($ctrl.price);
}
function persistDetails() {
console.log("am Called");
var payDetails = {};
payDetails.orderId = $ctrl.orderId;
payDetails.price = $ctrl.price;
payDetails.product = $ctrl.product;
payDetails.email = $ctrl.email;
console.log(payDetails);
return Pay.setPaymentDetails(payDetails);
}
// function makePayment() {
// var formParams = APP_CONFIG.paymentParams;
// formParams.email = $ctrl.email;
// formParams.amt = $ctrl.price;
// formParams.prd = $ctrl.product;
//
// Pay.makePay(formParams).then(
// function () {
// console.log("success");
// },
// handleError
// )
// }
//
// function handleError(response) {
// console.log(response);
// }
}
})(); |
/*
* VenoBox - jQuery Plugin
* version: 1.6.0
* @requires jQuery
*
* Examples at http://lab.veno.it/venobox/
* License: MIT License
* License URI: https://github.com/nicolafranchini/VenoBox/blob/master/LICENSE
* Copyright 2013-2015 Nicola Franchini - @nicolafranchini
*
*/
(function($){
var autoplay, bgcolor, blocknum, blocktitle, border, core, container, content, dest,
evitacontent, evitanext, evitaprev, extraCss, figliall, framewidth, frameheight,
infinigall, items, keyNavigationDisabled, margine, numeratio, overlayColor, overlay,
prima, title, thisgall, thenext, theprev, type,
finH, sonH, nextok, prevok;
$.fn.extend({
//plugin name - venobox
venobox: function(options) {
// default option
var defaults = {
framewidth: '',
frameheight: '',
border: '0',
bgcolor: '#fff',
titleattr: 'title', // specific attribute to get a title (e.g. [data-title]) - thanx @mendezcode
numeratio: false,
infinigall: false,
overlayclose: true // disable overlay click-close - thanx @martybalandis
};
var option = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
// Prevent double initialization - thanx @matthistuff
if(obj.data('venobox')) {
return true;
}
obj.addClass('vbox-item');
obj.data('framewidth', option.framewidth);
obj.data('frameheight', option.frameheight);
obj.data('border', option.border);
obj.data('bgcolor', option.bgcolor);
obj.data('numeratio', option.numeratio);
obj.data('infinigall', option.infinigall);
obj.data('overlayclose', option.overlayclose);
obj.data('venobox', true);
obj.click(function(e){
e.stopPropagation();
e.preventDefault();
obj = $(this);
overlayColor = obj.data('overlay');
framewidth = obj.data('framewidth');
frameheight = obj.data('frameheight');
// set data-autoplay="true" for vimeo and youtube videos - thanx @zehfernandes
autoplay = obj.data('autoplay') || false;
border = obj.data('border');
bgcolor = obj.data('bgcolor');
nextok = false;
prevok = false;
keyNavigationDisabled = false;
// set a different url to be loaded via ajax using data-href="" - thanx @pixeline
dest = obj.data('href') || obj.attr('href');
extraCss = obj.data( 'css' ) || "";
$('body').addClass('vbox-open');
core = '<div class="vbox-overlay ' + extraCss + '" style="background:'+ overlayColor +'"><div class="vbox-preloader">Loading...</div><div class="vbox-container"><div class="vbox-content"></div></div><div class="vbox-title"></div><div class="vbox-num">0/0</div><div class="vbox-close">X</div><div class="vbox-next">next</div><div class="vbox-prev">prev</div></div>';
$('body').append(core);
overlay = $('.vbox-overlay');
container = $('.vbox-container');
content = $('.vbox-content');
blocknum = $('.vbox-num');
blocktitle = $('.vbox-title');
content.html('');
content.css('opacity', '0');
checknav();
overlay.css('min-height', $(window).outerHeight());
// fade in overlay
overlay.animate({opacity:1}, 250, function(){
if(obj.data('type') == 'iframe'){
loadIframe();
}else if (obj.data('type') == 'inline'){
loadInline();
}else if (obj.data('type') == 'ajax'){
loadAjax();
}else if (obj.data('type') == 'vimeo'){
loadVimeo(autoplay);
}else if (obj.data('type') == 'youtube'){
loadYoutube(autoplay);
} else {
content.html('<img src="'+dest+'">');
preloadFirst();
}
});
/* -------- CHECK NEXT / PREV -------- */
function checknav(){
thisgall = obj.data('gall');
numeratio = obj.data('numeratio');
infinigall = obj.data('infinigall');
items = $('.vbox-item[data-gall="' + thisgall + '"]');
if(items.length > 1 && numeratio === true){
blocknum.html(items.index(obj)+1 + ' / ' + items.length);
blocknum.show();
}else{
blocknum.hide();
}
thenext = items.eq( items.index(obj) + 1 );
theprev = items.eq( items.index(obj) - 1 );
if(obj.attr(option.titleattr)){
title = obj.attr(option.titleattr);
blocktitle.show();
}else{
title = '';
blocktitle.hide();
}
if (items.length > 1 && infinigall === true) {
nextok = true;
prevok = true;
if(thenext.length < 1 ){
thenext = items.eq(0);
}
if(items.index(obj) < 1 ){
theprev = items.eq( items.index(items.length) );
}
} else {
if(thenext.length > 0 ){
$('.vbox-next').css('display', 'block');
nextok = true;
}else{
$('.vbox-next').css('display', 'none');
nextok = false;
}
if(items.index(obj) > 0 ){
$('.vbox-prev').css('display', 'block');
prevok = true;
}else{
$('.vbox-prev').css('display', 'none');
prevok = false;
}
}
}
/* -------- NAVIGATION CODE -------- */
var gallnav = {
prev: function() {
if (keyNavigationDisabled) {
return;
} else {
keyNavigationDisabled = true;
}
overlayColor = theprev.data('overlay');
framewidth = theprev.data('framewidth');
frameheight = theprev.data('frameheight');
border = theprev.data('border');
bgcolor = theprev.data('bgcolor');
dest = theprev.data('href') || theprev.attr('href');
autoplay = theprev.data('autoplay');
if(theprev.attr(option.titleattr)){
title = theprev.attr(option.titleattr);
}else{
title = '';
}
if (overlayColor === undefined ) {
overlayColor = "";
}
content.animate({ opacity:0}, 500, function(){
overlay.css('background',overlayColor);
if (theprev.data('type') == 'iframe') {
loadIframe();
} else if (theprev.data('type') == 'inline'){
loadInline();
} else if (theprev.data('type') == 'ajax'){
loadAjax();
} else if (theprev.data('type') == 'youtube'){
loadYoutube(autoplay);
} else if (theprev.data('type') == 'vimeo'){
loadVimeo(autoplay);
}else{
content.html('<img src="'+dest+'">');
preloadFirst();
}
obj = theprev;
checknav();
keyNavigationDisabled = false;
});
},
next: function() {
if (keyNavigationDisabled) {
return;
} else {
keyNavigationDisabled = true;
}
overlayColor = thenext.data('overlay');
framewidth = thenext.data('framewidth');
frameheight = thenext.data('frameheight');
border = thenext.data('border');
bgcolor = thenext.data('bgcolor');
dest = thenext.data('href') || thenext.attr('href');
autoplay = thenext.data('autoplay');
if(thenext.attr(option.titleattr)){
title = thenext.attr(option.titleattr);
}else{
title = '';
}
if (overlayColor === undefined ) {
overlayColor = "";
}
content.animate({ opacity:0}, 500, function(){
overlay.css('background',overlayColor);
if (thenext.data('type') == 'iframe') {
loadIframe();
} else if (thenext.data('type') == 'inline'){
loadInline();
} else if (thenext.data('type') == 'ajax'){
loadAjax();
} else if (thenext.data('type') == 'youtube'){
loadYoutube(autoplay);
} else if (thenext.data('type') == 'vimeo'){
loadVimeo(autoplay);
}else{
content.html('<img src="'+dest+'">');
preloadFirst();
}
obj = thenext;
checknav();
keyNavigationDisabled = false;
});
}
};
/* -------- NAVIGATE WITH ARROW KEYS -------- */
$('body').keydown(function(e) {
if(e.keyCode == 37 && prevok == true) { // left
gallnav.prev();
}
if(e.keyCode == 39 && nextok == true) { // right
gallnav.next();
}
});
/* -------- PREVGALL -------- */
$('.vbox-prev').click(function(){
gallnav.prev();
});
/* -------- NEXTGALL -------- */
$('.vbox-next').click(function(){
gallnav.next();
});
/* -------- ESCAPE HANDLER -------- */
function escapeHandler(e) {
if(e.keyCode === 27) {
closeVbox();
}
}
/* -------- CLOSE VBOX -------- */
function closeVbox(){
$('#menu_cabecera').removeClass('menu-static');
$('#contenido').addClass('contenido');
$('body').removeClass('vbox-open');
$('body').unbind('keydown', escapeHandler);
overlay.animate({opacity:0}, 500, function(){
overlay.remove();
keyNavigationDisabled = false;
obj.focus();
});
}
/* -------- CLOSE CLICK -------- */
var closeclickclass = '.vbox-close, .vbox-overlay';
if(!obj.data('overlayclose')){
closeclickclass = '.vbox-close'; // close only on X
}
$(closeclickclass).click(function(e){
evitacontent = '.figlio';
evitaprev = '.vbox-prev';
evitanext = '.vbox-next';
figliall = '.figlio *';
if(!$(e.target).is(evitacontent) && !$(e.target).is(evitanext) && !$(e.target).is(evitaprev)&& !$(e.target).is(figliall)){
closeVbox();
}
});
$('body').keydown(escapeHandler);
return false;
});
});
}
});
/* -------- LOAD AJAX -------- */
function loadAjax(){
$.ajax({
url: dest,
cache: false
}).done(function( msg ) {
content.html('<div class="vbox-inline">'+ msg +'</div>');
updateoverlay(true);
}).fail(function() {
content.html('<div class="vbox-inline"><p>Error retrieving contents, please retry</div>');
updateoverlay(true);
})
}
/* -------- LOAD IFRAME -------- */
function loadIframe(){
content.html('<iframe class="venoframe" src="'+dest+'"></iframe>');
// $('.venoframe').load(function(){ // valid only for iFrames in same domain
updateoverlay();
// });
}
/* -------- LOAD VIMEO -------- */
function loadVimeo(autoplay){
var pezzi = dest.split('/');
var videoid = pezzi[pezzi.length-1];
var stringAutoplay = autoplay ? "?autoplay=1" : "";
content.html('<iframe class="venoframe" webkitallowfullscreen mozallowfullscreen allowfullscreen frameborder="0" src="//player.vimeo.com/video/'+videoid+stringAutoplay+'"></iframe>');
updateoverlay();
}
/* -------- LOAD YOUTUBE -------- */
function loadYoutube(autoplay){
var pezzi = dest.split('/');
var videoid = pezzi[pezzi.length-1];
var stringAutoplay = autoplay ? "?autoplay=1" : "";
content.html('<iframe class="venoframe" webkitallowfullscreen mozallowfullscreen allowfullscreen src="//www.youtube.com/embed/'+videoid+stringAutoplay+'"></iframe>');
updateoverlay();
}
/* -------- LOAD INLINE -------- */
function loadInline(){
content.html('<div class="vbox-inline">'+$(dest).html()+'</div>');
updateoverlay();
}
/* -------- PRELOAD IMAGE -------- */
function preloadFirst(){
prima = $('.vbox-content').find('img');
prima.one('load', function() {
updateoverlay();
}).each(function() {
if(this.complete) $(this).load();
});
}
/* -------- CENTER ON LOAD -------- */
function updateoverlay(){
blocktitle.html(title);
content.find(">:first-child").addClass('figlio');
$('.figlio').css('width', framewidth).css('height', frameheight).css('padding', border).css('background', bgcolor);
sonH = content.outerHeight();
finH = $(window).height();
if(sonH+80 < finH){
margine = (finH - sonH)/2;
content.css('margin-top', margine);
content.css('margin-bottom', margine);
}else{
content.css('margin-top', '40px');
content.css('margin-bottom', '40px');
}
content.animate({
'opacity': '1'
},'slow');
}
/* -------- CENTER ON RESIZE -------- */
function updateoverlayresize(){
if($('.vbox-content').length){
sonH = content.height();
finH = $(window).height();
if(sonH+80 < finH){
margine = (finH - sonH)/2;
content.css('margin-top', margine);
content.css('margin-bottom', margine);
}else{
content.css('margin-top', '40px');
content.css('margin-bottom', '40px');
}
}
}
$(window).resize(function(){
updateoverlayresize();
});
})(jQuery); |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
module.metadata = {
"stability": "unstable"
};
const { isValidURI, isLocalURL, URL } = require('../url');
const { contract } = require('../util/contract');
const { isString, isNil, instanceOf } = require('../lang/type');
const { validateOptions,
string, array, object, either, required } = require('../deprecated/api-utils');
const isJSONable = (value) => {
try {
JSON.parse(JSON.stringify(value));
}
catch (e) {
return false;
}
return true;
};
const isValidScriptFile = (value) =>
(isString(value) || instanceOf(value, URL)) && isLocalURL(value);
// map of property validations
const valid = {
contentURL: {
is: either(string, object),
ok: url => isNil(url) || isLocalURL(url) || isValidURI(url),
msg: 'The `contentURL` option must be a valid URL.'
},
contentScriptFile: {
is: either(string, object, array),
ok: value => isNil(value) || [].concat(value).every(isValidScriptFile),
msg: 'The `contentScriptFile` option must be a local URL or an array of URLs.'
},
contentScript: {
is: either(string, array),
ok: value => isNil(value) || [].concat(value).every(isString),
msg: 'The `contentScript` option must be a string or an array of strings.'
},
contentScriptWhen: {
is: required(string),
map: value => value || 'end',
ok: value => ~['start', 'ready', 'end'].indexOf(value),
msg: 'The `contentScriptWhen` option must be either "start", "ready" or "end".'
},
contentScriptOptions: {
ok: value => isNil(value) || isJSONable(value),
msg: 'The contentScriptOptions should be a jsonable value.'
}
};
exports.validationAttributes = valid;
/**
* Shortcut function to validate property with validation.
* @param {Object|Number|String} suspect
* value to validate
* @param {Object} validation
* validation rule passed to `api-utils`
*/
function validate(suspect, validation) {
return validateOptions(
{ $: suspect },
{ $: validation }
).$;
}
function Allow(script) {
return {
get script() {
return script;
},
set script(value) {
script = !!value;
}
};
}
exports.contract = contract(valid);
|
g_en_template_texture = {
// common
tplNoPlatform : "none",
tplWarning : "Warning",
tplSearchFilter : "SearchFilter",
tplSearchTitle : "Search",
tplSearchBtn : "Search",
tplSearchResultTitle : "Search Result",
tplCheckNon : "No Check",
tplCheckEnableOnly : "Enable Only",
tplCheckDisableOnly : "Disable Only",
tplHitNum : "HitNum",
tplItem : "Item",
tplCheck : "Check",
tplCondition : "Condition",
tplAddConditionBtn : "Add condition",
tplDelConditionBtn : "delete",
tplFileInclude : "If filepath includes below words",
tplFileExclude : "If filepath doesn't include below words",
// specific
tplCondBasic : "Basic",
tplCondFormat : "Format",
tplCondImportType : "ImportType",
tplCondTextureSize : "TextureSize",
tplCondMipMapCheck : "MipMap check ",
tplCondReadWriteCheck : "Read/Write check ",
tplCondPow2Check : "Pow2 check",
tplCheckNonPow2Only : "Non pow2 only",
tplCondWidth : "Width",
tplCondHeight : "Height",
tplCondSpriteTag : "SpritePackTag",
// in result
tplResultPath : "Path",
tplResultType : "Type",
tplResultFormat : "Format",
tplResultSize : "Size",
tplResultNonPow2 : "isn't pow2 size",
tplResultSpriteTag : "SpritePackingTag",
tplResultMaxSize : "MaxSize",
tplResultMipMap : "MipMap",
tplResultReadWrite : "Read/Write",
}; |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {ReactContext} from 'shared/ReactTypes';
import type {Source} from 'shared/ReactElementType';
import type {Fiber} from 'react-reconciler/src/ReactFiber';
import type {
ComponentFilter,
ElementType,
} from 'react-devtools-shared/src/types';
import type {Interaction} from 'react-devtools-shared/src/devtools/views/Profiler/types';
import type {ResolveNativeStyle} from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
type BundleType =
| 0 // PROD
| 1; // DEV
export type WorkTag = number;
export type SideEffectTag = number;
export type ExpirationTime = number;
// TODO: If it's useful for the frontend to know which types of data an Element has
// (e.g. props, state, context, hooks) then we could add a bitmask field for this
// to keep the number of attributes small.
export type FiberData = {|
key: string | null,
displayName: string | null,
type: ElementType,
|};
export type NativeType = Object;
export type RendererID = number;
type Dispatcher = any;
export type GetFiberIDForNative = (
component: NativeType,
findNearestUnfilteredAncestor?: boolean,
) => number | null;
export type FindNativeNodesForFiberID = (id: number) => ?Array<NativeType>;
export type ReactProviderType<T> = {
$$typeof: Symbol | number,
_context: ReactContext<T>,
};
export type ReactRenderer = {
findFiberByHostInstance: (hostInstance: NativeType) => ?Fiber,
version: string,
bundleType: BundleType,
// 16.9+
overrideHookState?: ?(
fiber: Object,
id: number,
path: Array<string | number>,
value: any,
) => void,
// 16.7+
overrideProps?: ?(
fiber: Object,
path: Array<string | number>,
value: any,
) => void,
// 16.9+
scheduleUpdate?: ?(fiber: Object) => void,
setSuspenseHandler?: ?(shouldSuspend: (fiber: Object) => boolean) => void,
// Only injected by React v16.8+ in order to support hooks inspection.
currentDispatcherRef?: {|current: null | Dispatcher|},
// Only injected by React v16.9+ in DEV mode.
// Enables DevTools to append owners-only component stack to error messages.
getCurrentFiber?: () => Fiber | null,
// Uniquely identifies React DOM v15.
ComponentTree?: any,
// Present for React DOM v12 (possibly earlier) through v15.
Mount?: any,
};
export type ChangeDescription = {|
context: Array<string> | boolean | null,
didHooksChange: boolean,
isFirstMount: boolean,
props: Array<string> | null,
state: Array<string> | null,
|};
export type CommitDataBackend = {|
// Tuple of fiber ID and change description
changeDescriptions: Array<[number, ChangeDescription]> | null,
duration: number,
// Tuple of fiber ID and actual duration
fiberActualDurations: Array<[number, number]>,
// Tuple of fiber ID and computed "self" duration
fiberSelfDurations: Array<[number, number]>,
interactionIDs: Array<number>,
priorityLevel: string | null,
timestamp: number,
|};
export type ProfilingDataForRootBackend = {|
commitData: Array<CommitDataBackend>,
displayName: string,
// Tuple of Fiber ID and base duration
initialTreeBaseDurations: Array<[number, number]>,
// Tuple of Interaction ID and commit indices
interactionCommits: Array<[number, Array<number>]>,
interactions: Array<[number, Interaction]>,
rootID: number,
|};
// Profiling data collected by the renderer interface.
// This information will be passed to the frontend and combined with info it collects.
export type ProfilingDataBackend = {|
dataForRoots: Array<ProfilingDataForRootBackend>,
rendererID: number,
|};
export type PathFrame = {|
key: string | null,
index: number,
displayName: string | null,
|};
export type PathMatch = {|
id: number,
isFullMatch: boolean,
|};
export type Owner = {|
displayName: string | null,
id: number,
type: ElementType,
|};
export type OwnersList = {|
id: number,
owners: Array<Owner> | null,
|};
export type InspectedElement = {|
id: number,
displayName: string | null,
// Does the current renderer support editable hooks?
canEditHooks: boolean,
// Does the current renderer support editable function props?
canEditFunctionProps: boolean,
// Is this Suspense, and can its value be overriden now?
canToggleSuspense: boolean,
// Can view component source location.
canViewSource: boolean,
// Does the component have legacy context attached to it.
hasLegacyContext: boolean,
// Inspectable properties.
context: Object | null,
hooks: Object | null,
props: Object | null,
state: Object | null,
// List of owners
owners: Array<Owner> | null,
// Location of component in source coude.
source: Source | null,
type: ElementType,
|};
export const InspectElementFullDataType = 'full-data';
export const InspectElementNoChangeType = 'no-change';
export const InspectElementNotFoundType = 'not-found';
export const InspectElementHydratedPathType = 'hydrated-path';
type InspectElementFullData = {|
id: number,
type: 'full-data',
value: InspectedElement,
|};
type InspectElementHydratedPath = {|
id: number,
type: 'hydrated-path',
path: Array<string | number>,
value: any,
|};
type InspectElementNoChange = {|
id: number,
type: 'no-change',
|};
type InspectElementNotFound = {|
id: number,
type: 'not-found',
|};
export type InspectedElementPayload =
| InspectElementFullData
| InspectElementHydratedPath
| InspectElementNoChange
| InspectElementNotFound;
export type InstanceAndStyle = {|
instance: Object | null,
style: Object | null,
|};
export type RendererInterface = {
cleanup: () => void,
findNativeNodesForFiberID: FindNativeNodesForFiberID,
flushInitialOperations: () => void,
getBestMatchForTrackedPath: () => PathMatch | null,
getFiberIDForNative: GetFiberIDForNative,
getInstanceAndStyle(id: number): InstanceAndStyle,
getProfilingData(): ProfilingDataBackend,
getOwnersList: (id: number) => Array<Owner> | null,
getPathForElement: (id: number) => Array<PathFrame> | null,
handleCommitFiberRoot: (fiber: Object, commitPriority?: number) => void,
handleCommitFiberUnmount: (fiber: Object) => void,
inspectElement: (
id: number,
path?: Array<string | number>,
) => InspectedElementPayload,
logElementToConsole: (id: number) => void,
overrideSuspense: (id: number, forceFallback: boolean) => void,
prepareViewElementSource: (id: number) => void,
renderer: ReactRenderer | null,
setInContext: (id: number, path: Array<string | number>, value: any) => void,
setInHook: (
id: number,
index: number,
path: Array<string | number>,
value: any,
) => void,
setInProps: (id: number, path: Array<string | number>, value: any) => void,
setInState: (id: number, path: Array<string | number>, value: any) => void,
setTrackedPath: (path: Array<PathFrame> | null) => void,
startProfiling: (recordChangeDescriptions: boolean) => void,
stopProfiling: () => void,
updateComponentFilters: (somponentFilters: Array<ComponentFilter>) => void,
};
export type Handler = (data: any) => void;
export type DevToolsHook = {
listeners: {[key: string]: Array<Handler>},
rendererInterfaces: Map<RendererID, RendererInterface>,
renderers: Map<RendererID, ReactRenderer>,
emit: (event: string, data: any) => void,
getFiberRoots: (rendererID: RendererID) => Set<Object>,
inject: (renderer: ReactRenderer) => number | null,
on: (event: string, handler: Handler) => void,
off: (event: string, handler: Handler) => void,
reactDevtoolsAgent?: ?Object,
sub: (event: string, handler: Handler) => () => void,
// Used by react-native-web and Flipper/Inspector
resolveRNStyle?: ResolveNativeStyle,
nativeStyleEditorValidAttributes?: $ReadOnlyArray<string>,
// React uses these methods.
checkDCE: (fn: Function) => void,
onCommitFiberUnmount: (rendererID: RendererID, fiber: Object) => void,
onCommitFiberRoot: (
rendererID: RendererID,
fiber: Object,
commitPriority?: number,
) => void,
};
|
module.exports = function(grunt) {
grunt.config('file_dependencies.custom_config_functions', {
files: {
src: [
'test/fixtures/custom_config_functions/ClassB.js',
'test/fixtures/custom_config_functions/ClassA.js'
]
},
options: {
extractDefines: function(fileContent) {
var regex = /framework\.defineClass\s*\(\s*['"]([^'"]+)['"]/g,
matches = [],
match;
while(match = regex.exec(fileContent))
matches.push(match[1]);
return matches;
},
extractRequires: function(fileContent, defineMap) {
var regex = /framework\.requireClass\s*\(\s*['"]([^'"]+)['"]/g,
matches = [],
match;
while(match = regex.exec(fileContent)) {
if (match[1] in defineMap)
matches.push(match[1]);
}
return matches;
}
}
});
}
|
/**
* ContactType.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
var _ = require('lodash');
module.exports = _.merge(_.cloneDeep(require('./base')), {
attributes: {
type: {
type: 'string',
unique: true,
required: true
}
}
});
|
(function () {
'use strict';
angular
.module('bp.core')
.controller('homeController', HomeController);
HomeController.$inject = ['UserSettingsFactory'];
function HomeController(UserSettingsFactory) {
var vm = this;
vm.userName = '';
function activate() {
vm.userName = UserSettingsFactory.getUserName();
};
activate();
};
})(); |
!function( $ ) {
$.fn.spin = function(opts) {
this.each(function() {
var $this = $(this),
data = $this.data();
if (data.spinner) {
data.spinner.stop();
delete data.spinner;
}
if (opts !== false) {
data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
}
});
return this;
};
"use strict"
var opts = {
lines: 7,
length: 3,
width: 6,
radius: 7,
rotate: 54,
color: '#000',
speed: 1.7,
trail: 36,
shadow: true,
hwaccel: false,
className: 'spinner',
zIndex: 2e9,
top: 'auto',
left: 'auto'
};
$("#spin").spin(opts);
$('.carousel').carousel({
interval: 9999999
});
$('.carousel').bind('slid', function() {
$('#ans-buttons').toggle();
});
$('#btn-switch').click(function() {
$('.carousel').carousel('next');
return false;
});
KeyboardJS.bind.key('left, right, up, down',
function() {},
function() {
$('.carousel').carousel('next');
}
)
KeyboardJS.bind.key('a',
function() {},
function() {
if ($('#ans-buttons').css('display') != 'none') {
$('#btn-no').click();
}
}
)
KeyboardJS.bind.key('s',
function() {},
function() {
if ($('#ans-buttons').css('display') != 'none') {
$('#btn-yes').click();
}
}
)
$("#ans-buttons input").click(function() {
return false;
});
// add
$("#text-front").bind('keyup', function() {
$("#front-result").html($("#text-front").val())
});
$("#text-back").bind('keyup', function() {
$("#back-result").html($("#text-back").val())
});
}( window.jQuery );
|
/**
* Created by devesh on 4/8/15.
*/
var mongoose = require('mongoose');
var User = require('../models/user');
mongoose.connect('mongodb://localhost:27017/loginApp');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("Database connection opened...!!");
});
module.exports = db;
|
'use strict';
/**
* Module dependencies.
*/
var config = require('./config'),
express = require("express"),
_ = require('lodash'),
mongoose = require('./mongoose'),
path = require('path'),
bodyParser = require('body-parser'),
morgan = require('morgan'),
passport = require('passport'),
cookieParser = require('cookie-parser'),
cors = require('cors');
mongoose.connect(function () {
var app = express();
app.use(cors({origin: config.webServer}));
var middleware = require('./middleware/middlewares');
//Add Middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(morgan('dev'));
app.use(passport.initialize());
app.use(middleware.isAuthenticated());
app.use(middleware.translations());
// // write cleaned languages to request
// // app.use(function(req,res,next){
// // var langArray =[];
// // if(req.isSignedIn && req.user.preferredLanguage){
// // next();
// // }else{
// // _.forEach(req.acceptsLanguages(),function(acceptedLanguage){
// // _.forEach(config.languageOptions.languages,function(allowedLanguage){
// // if(allowedLanguage === acceptedLanguage){
// // langArray.push(acceptedLanguage);
// // }
// // })
// // });
// // }
// // req.languages = langArray;
// // next();
// // });
// //load Backendtranslations
// app.use(function (req, res, next) {
// //check here if there are params
// //check here if there are params
//
// });
//Importe routes
_.forEach(config.files.routes, function (routePath) {
require(path.resolve(routePath))(app, middleware);
});
//catch 404 error sites
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//app listen on port
app.listen(config.server.port, function () {
});
}); |
class Game {
constructor(width, height) {
this.game = new Phaser.Game(
width,
height,
Phaser.AUTO,
'fancy pancy',
{ create: this.create, update: this.update }
)
}
create() {
var fs = require('./shaders/lightwave.frag')()
this.sprite = this.game.add.sprite()
this.filter = new Phaser.Filter(this.game, null, fs)
this.filter.setResolution(this.game.width, this.game.height)
this.sprite.width = this.game.width
this.sprite.height = this.game.height
this.sprite.filters = [this.filter]
}
update() {
this.filter.update()
}
}
new Game(800, 600)
|
/* Pure Javascript Bouncy Boar implementation.
* MUST NOT depend on any external APIs.
* Integration with external APIs are provided via subclassing */
// BASE is for
// TODO: Next project: Hardcore batching (Multiple materials in a single geom, Compiling multiple material programs into a single program) See http://ce.u-sys.org/Veranstaltungen/Interaktive%20Computergraphik%20(Stamminger)/papers/BatchBatchBatch.pdf That said, this is not important because we are targeting crappy Intel CPUs, which are not even good with shaders in the first place. For the FUTURE I guess.
// TODO: Re-add input support (IMPT)
// TODO: FunctionQueue works now. Now, make it easy to use! (???)
// TODO: Common ID
// TODO: A better skybox that uses 2D Textures (IMPT)
// TODO: Make Viewport fill whole screen (IMPT)
// FINISH ALL IMPT TODOs NOW and then CODE DUMP!
"use strict";
(function(factory) {
if (typeof define != "undefined") {
define(["dcl", "gl-matrix"], factory);
} else if (typeof module != "undefined") {
module.exports = factory(require("dcl"), require("gl-matrix"));
} else {
core = factory(dcl, glm);
}
})(function(dcl, glm) {
var vec2 = glm.vec2;
var vec3 = glm.vec3;
var quat = glm.quat;
var mat4 = glm.mat4;
var mat3 = glm.mat3;
vec3.ZERO = vec3.create();
var vec3X = glm.vec3.fromValues(1.0, 0.0, 0.0);
var vec3Y = glm.vec3.fromValues(0.0, 1.0, 0.0);
var vec3Z = glm.vec3.fromValues(0.0, 0.0, 1.0);
vec3.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1],
az = a[2];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
out[2] = az + t * (b[2] - az);
return out;
};
/* Extension functions */
mat3.setFromAxes = function(out, xVec, yVec, zVec) {
out.set(xVec);
out.set(yVec, 3);
out.set(zVec, 6);
return out;
}
// Converts a rotation matrix mat3 into a quat
quat.setFromMat3 = function(out, m) {
var m11 = m[0], m12 = m[3], m13 = m[6],
m21 = m[1], m22 = m[4], m23 = m[7],
m31 = m[2], m32 = m[5], m33 = m[8],
trace = m11 + m22 + m33,
s,
w, x, y, z; //outbound variables
if( trace > 0 ) {
s = 0.5 / Math.sqrt( trace + 1.0 );
w = 0.25 / s;
x = ( m32 - m23 ) * s;
y = ( m13 - m31 ) * s;
z = ( m21 - m12 ) * s;
} else if ( m11 > m22 && m11 > m33 ) {
s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
w = (m32 - m23 ) / s;
x = 0.25 * s;
y = (m12 + m21 ) / s;
z = (m13 + m31 ) / s;
} else if (m22 > m33) {
s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
w = (m13 - m31 ) / s;
x = (m12 + m21 ) / s;
y = 0.25 * s;
z = (m23 + m32 ) / s;
} else {
s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
w = ( m21 - m12 ) / s;
x = ( m13 + m31 ) / s;
y = ( m23 + m32 ) / s;
z = 0.25 * s;
}
out[0] = x; out[1] = y; out[2] = z; out[3] = w;
return out;
}
quat.setFromAxes = function(out, xVec, yVec, zVec) {
var m = mat3.create();
mat3.setFromAxes(m, xVec, yVec, zVec);
return quat.setFromMat3(out, m);
}
var objectCounter = 0;
var Instance = dcl(null, {
declaredClass: "bb4.core.Instance",
constructor: function(args) {
this.id = objectCounter++;
},
});
// ===========================================================
// Event System
// Does event bubbling have any use? Probably not.
var EventEmitter = dcl(null, {
declaredClass: "bb4.core.EventEmitter",
constructor: function(args) {
this._callbacks = {};
this._callbackCtr = 0;
},
on: function(event, callback, numTimes) {
if (!numTimes) numTimes = 0;
if (!(event in this._callbacks))
this._callbacks[event] = {};
var callbackId = this._callbackCtr++;
if (numTimes > 0) {
var num = numTimes;
var cBack = function() {
if (--num <= 0)
this.removeListener(event, callbackId);
return callback.apply(this, arguments);
};
} else cBack = callback;
this._callbacks[event][callbackId] = cBack;
return callbackId;
},
once: function(event, callback) {
return this.on(event, callback, 1);
},
removeListener: function(event, callbackId) {
if (this._callbacks[event]) delete this._callbacks[event][callbackId];
},
emit: function(event, e, target) {
if (!target) {
//if (!(event in this._slots)) throw "Invalid event";
target = this;
}
var bubble = true;
if (event != "*" && this._callbacks["*"]) { //handle wildcard event
var callbacks = this._callbacks["*"];
for (var callbackId in callbacks)
callbacks[callbackId].call(this, e, target, callbackId, event);
}
if (this._callbacks[event]) {
var callbacks = this._callbacks[event];
for (var callbackId in callbacks)
if (callbacks[callbackId].call(this, e, target, callbackId, event)) bubble = false;
}
if (bubble && this.parent && this.parent.emit) this.parent.emit(event, e, target);
},
});
var TS_WORLD = 1,
TS_PARENT = 2,
TS_LOCAL = 3;
// ============================================================
var Node = dcl(Instance, {
// Implements parent-child relationship
declaredClass: "bb4.core.Node",
constructor: function(args) {
if (!args) args = {};
this.parent = args.parent || null;
this.children = args.children || {};
},
_onParentUpdate: function() {
for (var nodeid in this.children) this.children[nodeid]._onParentUpdate();
},
_onUpdate: function() {
for (var nodeid in this.children) this.children[nodeid]._onParentUpdate();
if (this.parent) this.parent._onChildUpdate();
},
_onChildUpdate: function() {
},
_setParent: function(node) {
this.parent = node;
this._onUpdate();
},
addChild: function(node) {
// Remove node from previous parent (if any)
if (node.parent) node.parent.removeChild(node);
node._setParent(this);
this.children[node.id] = node;
this._onChildUpdate();
},
removeChild: function(node) {
var nodeid = Object.prototype.toString.call(node) == "[object Number]" ? node : node.id;
var child = this.children[nodeid];
if (child) {
child._setParent(null);
delete this.children[nodeid];
this._onChildUpdate();
return true;
} else return false;
},
});
// ==============================================================
// Command Queue System
/*
function funcQueue(f) {
f.functionQueueFunc = f;
return f;
};*/
var FunctionQueue = dcl(EventEmitter, {
declaredClass: "bb4.FunctionQueue",
constructor: function(args) {
//this.target = args.target || null;
this.queue = []; //Not completed async functions.
this.numRunning = 0;
this.funcCounter = 0;
this.running = args.running || false; //If true, if there are no queued functions, all
// new functions added will start immediately.
//if(this.target) this.ctx(this.target);
},
/*
ctx: function(c) {
this.target = c;
for (var funcName in c) {
if (c[funcName] && c[funcName].functionQueueFunc) {
var f = c[funcName].functionQueueFunc;
this[funcName] = f;
}
}
return this;
},*/
run: function() {
// Run the Queue.
this.running = true;
this.emit("run");
},
fireComplete: function(funcId) {
// Remove this function from queue!
var i = this.queue.indexOf(funcId);
if (i > -1) {
this.queue.splice(i, 1);
}
this.numRunning --;
this.emit("start" + funcId);
// funcId has completed!
this.emit("complete" + funcId);
if (this.numRunning <= 0) {
this.emit("complete"); //No more functions left in the queue
}
},
async: function(func) {
// I start running once the function before me begins running
var that = this,
funcId = this.funcCounter++,
waitFuncId;
this.queue.push(funcId);
if (this.queue.length - 1 > 0) {
// There is a function which we need to wait for.
waitFuncId = this.queue[this.queue.length - 2];
this.once("start" + waitFuncId, function() {
that.numRunning ++;
func.call(that, funcId);
that.emit("start" + funcId); //Fire my start event (run callbacks only after function is run to preserve ordering)
});
} else if (this.running) {
// There is no function that we need to wait for. Start immeduately
this.numRunning ++;
func.call(this, funcId);
} else {
this.once("run", function() {
that.numRunning ++;
func.call(that, funcId);
that.emit("start" + funcId);
});
}
return this;
},
asyncQueue: function(queue) {
// Run a queue in an async manner. This is useful when you want to run
// events which are blocking with respect to each other, but you want
// to run them, as a whole, async.
this.async(function(funcId) {
var that = this;
queue.once("complete", function() {
that.fireComplete(funcId);
});
queue.run();
});
},
blockX: function() {
},
block: function() {
},
sync: function(func) {
//I will wait until all functions before me complete before running
if (!func) func = function(funcId){this.fireComplete(funcId);};
var that = this,
funcId = this.funcCounter++,
numRemaining = this.queue.length, //Number of functions left to wait for
callback = function() {
if (--numRemaining <= 0) {
//that.started[funcId] = true; //Add myself to started list
that.numRunning ++;
func.call(that, funcId);
that.emit("start" + funcId); //Fire my start event (run callbacks only after function is run to preserve ordering)
}
};
if (this.queue.length > 0) {
for (var i = 0; i < this.queue.length; ++i) {
this.once("complete" + this.queue[i], callback);
}
} else if (this.running) {
// There is nothing to wait for. Start immediately.
that.numRunning ++;
func.call(this, funcId);
} else {
this.once("run", function() {
that.numRunning ++;
func.call(that, funcId);
that.emit("start" + funcId);
});
}
this.queue.length = 0;
this.queue.push(funcId);
return this;
},
func: function(func) {
// Call a function
var args = [];
for (var i = 1; i < arguments.length; ++i)
args.push(arguments[i]);
this.async(function(funcId) {
func.call(null, args);
this.fireComplete(funcId);
});
return this;
},
});
/*
var FunctionQueueMixin = dcl(null, {
declaredClass: "FunctionQueueMixin",
constructor: function(args) {
this._functionQueue = new FunctionQueue({running: true, target: this});
for (var funcName in this) {
if (this[funcName] && this[funcName].functionQueueFunc) {
var f = this[funcName].functionQueueFunc;
this[funcName] = function() {
return f.apply(this._functionQueue, arguments);
}
}
}
},
wait: funcQueue(function() {
}),
});
*/
// ==============================================================
var SpatialNode = dcl(Node, {
declaredClass: "bb4.SpatialNode",
constructor: function(args) {
if (!args) args = {};
this.logicEngine = args.logicEngine || this.logicEngine || null;
this.localPosition = vec3.clone(args.localPosition || [0, 0, 0]);
this.worldPosition = vec3.create();
this.localOrientation = quat.clone(args.localOrientation || [0, 0, 0, 1]);
this.worldOrientation = quat.create();
this.localScale = vec3.clone(args.localScale || [1, 1, 1]);
this.worldScale = vec3.fromValues(1, 1, 1);
this.mMatrix = mat4.create();
this._worldOutdated = true;
},
_onParentUpdate: dcl.superCall(function(sup) {
return function() {
this._worldOutdated = true;
sup.call(this);
};
}),
_onUpdate: dcl.superCall(function(sup) {
return function() {
this._worldOutdated = true;
sup.call(this);
};
}),
updateWorldProperties: function() {
var parent = this.parent;
if (!this._worldOutdated) return false;
if (parent) {
// Ensure parent's world properties are updated
parent.updateWorldProperties();
// Combine orientation with that of parent
quat.mul(this.worldOrientation, parent.worldOrientation, this.localOrientation);
// Update scale
vec3.mul(this.worldScale, parent.worldScale, this.localScale);
// Update position based on parent's orientation and scale
// this.worldPosition = parent.worldOrientation * (parent.worldScale * this.localPosition) + parent.worldPosition
vec3.mul(this.worldPosition, parent.worldScale, this.localPosition);
vec3.transformQuat(this.worldPosition, parent.worldOrientation, this.worldPosition);
vec3.add(this.worldPosition, this.worldPosition, parent.worldPosition);
} else {
// Root node, no parent. Hence, worldX = localX, where X={Position,Orientation,Scale}
vec3.copy(this.worldPosition, this.localPosition);
quat.copy(this.worldOrientation, this.localOrientation);
vec3.copy(this.worldScale, this.localScale);
}
// Finally, update world model transformation matrix
this._worldOutdated = false;
mat4.fromRotationTranslation(this.mMatrix, this.worldOrientation, this.worldPosition);
mat4.scale(this.mMatrix, this.mMatrix, this.worldScale);
return true;
},
setDirection: function(vec, relativeTo, up) {
var parent = this.parent;
var targetDir = vec3.create();
if (!up) up = vec3Y;
if (!relativeTo) relativeTo = TS_WORLD;
// Do nothing if given a zero vector
if (vec3.squaredLength(vec) < 0.0000001) return;
// Ensure vec is normalised
vec3.normalize(targetDir, vec);
// Transform target direction to world space
switch (relativeTo) {
case TS_PARENT:
if (parent) {
parent.updateWorldProperties();
vec3.transformQuat(targetDir, targetDir, parent.worldOrientation);
}
break;
case TS_LOCAL:
this.updateWorldProperties();
vec3.transformQuat(targetDir, targetDir, this.worldOrientation);
break;
}
// Calculate target orientation relative to world space
// (assuming a fixed up axis) (and so no rolling)
var xvec = glm.vec3.create();
var yvec = glm.vec3.create();
var zvec = targetDir;
glm.vec3.cross(xvec, up, zvec);
glm.vec3.normalize(xvec, xvec);
glm.vec3.cross(yvec, zvec, xvec);
// Construct World Orientation Quat
quat.setFromAxes(this.worldOrientation, xvec, yvec, zvec);
// TODO: handle localDirection like OGRE
// Turn worldOrientation back into localOrientation
if (parent) {
parent.updateWorldProperties();
var parentInverseOrientation = quat.create();
quat.invert(parentInverseOrientation, parent.worldOrientation);
quat.multiply(this.localOrientation, parentInverseOrientation, this.worldOrientation);
} else {
quat.copy(this.localOrientation, this.worldOrientation);
}
this._onUpdate();
return this;
},
lookAt: function(target, relativeTo, up, reverse) {
if (!relativeTo) relativeTo = TS_WORLD;
switch (relativeTo) {
case TS_WORLD:
this.updateWorldProperties();
var origin = this.worldPosition;
break;
case TS_PARENT:
var origin = this.localPosition;
break;
case TS_LOCAL:
var origin = [0, 0, 0];
break;
}
var myTarget = glm.vec3.create();
vec3.subtract(myTarget, target, origin);
if (reverse) vec3.negate(myTarget, myTarget);
this.setDirection(myTarget, relativeTo, up);
return this;
},
yaw: function(rad) {
quat.rotateY(this.localOrientation, this.localOrientation, rad);
this._onUpdate();
return this;
},
pitch: function(rad) {
quat.rotateX(this.localOrientation, this.localOrientation, rad);
this._onUpdate();
return this;
},
roll: function(rad) {
quat.rotateZ(this.localOrientation, this.localOrientation, rad);
this._onUpdate();
return this;
},
_translate: function(out, d, relativeTo) {
if (!relativeTo) relativeTo = TS_PARENT;
var parent = this.parent,
target = vec3.clone(d);
switch (relativeTo) {
case TS_LOCAL:
// target = localOrientation * d
vec3.transformQuat(target, d, this.localOrientation);
break;
case TS_WORLD:
if (parent) {
parent.updateWorldProperties();
//target = (parent.worldOrientation.inverse() * d) / parent.worldScale
var parentWorldOrientationInverse = quat.create();
quat.invert(parentWorldOrientationInverse, parent.worldOrientation);
vec3.transformQuat(target, d, parentWorldOrientationInverse);
vec3.divide(target, target, parent.worldScale);
}
break;
}
// localPosition += target
vec3.add(out, this.localPosition, target);
return out;
},
translate: function(d, relativeTo) {
this._translate(this.localPosition, d, relativeTo);
this._onUpdate();
return this;
},
translateS: function(queue, d, relativeTo, s, interp) {
// For now we just do linear interpolation
var logicEngine = this.logicEngine,
that = this;
if (!interp) interp = vec3.lerp;
queue.async(function(funcId) {
var queue = this,
vecStart = vec3.clone(that.localPosition),
vecTarget = that._translate(vec3.create(), d, relativeTo),
stepCounter = 0;
logicEngine.on("step", function(e, target, callbackId) {
stepCounter++;
interp(that.localPosition, vecStart, vecTarget, (stepCounter / s));
that._onUpdate();
if (stepCounter >= s) {
logicEngine.removeListener("step", callbackId);
queue.fireComplete(funcId);
}
});
});
return this;
},
});
// ================================================================
function isPowerOfTwo(x) {
return (x & (x - 1)) == 0;
}
function nextHighestPowerOfTwo(x) {
--x;
for (var i = 1; i < 32; i <<= 1) {
x = x | x >> i;
}
return x + 1;
}
var _textureDefaultData = new Uint8Array([0, 0, 255, 255]);
var _object_plane_x = new Float32Array([1, 0, 0, 0]);
var _object_plane_y = new Float32Array([0, 1, 0, 0]);
var _object_plane_z = new Float32Array([0, 0, 1, 0]);
// TODO: TextureUnit class to represent Texture Unit so the same texture
// data can be used.
// Represents a Texture Unit
// texgen: normal_map, reflection_map, sphere_map
var Texture = dcl(null, {
declaredClass: "bb4.core.Texture",
constructor: function(args) {
if (typeof args != "object") args = {};
var videoEngine = this.videoEngine = args.videoEngine || this.videoEngine || console.error("args.videoEngine");
var gl = videoEngine.gl;
this.type = args.type || "TEXTURE_2D";
this.gltexture = gl.createTexture();
var images = args.images || {};
this.texgen = args.texgen || null;
this.images = {};
for (var imageType in images)
this.loadImage(imageType, this.images[imageType]);
},
bind: function() {
var gl = this.videoEngine.gl,
gltexture = this.gltexture,
gltexturetype = this.type;
gl.bindTexture(gl[this.type], this.gltexture);
gl.enable(gl[this.type]);
gl.texParameteri(gl[this.type], gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl[this.type], gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
},
unbind: function() {
var gl = this.videoEngine.gl;
gl.disable(gl[this.type]);
},
loadImage: function(imageType, src) {
// src: String or Image()
var gl = this.videoEngine.gl, that = this,
clearImage = function() {
gl.texImage2D(gl[imageType], 0, gl.RGBA, 1, 1, 0, gl.RGBA,
gl.UNSIGNED_BYTE, _textureDefaultData);
gl.generateMipmap(gl[that.type]);
};
this.bind();
if (!src) {
clearImage();
this.unbind();
return this;
} else if (typeof src == "string")
src = this.videoEngine.getImage(src);
if (src.isComplete()) {
this.images[imageType] = src;
gl.texImage2D(gl[imageType], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src);
gl.generateMipmap(gl[this.type]);
} else {
clearImage()
src.on("load", function() {
that.loadImage(imageType, src);
});
}
this.unbind();
return this;
/*
if (!isPowerOfTwo(img.width) || !isPowerOfTwo(img.height)) {
//Scale up the image to the next highest power of two
var canvas = document.createElement("canvas");
canvas.width = nextHighestPowerOfTwo(img.width);
canvas.height = nextHighestPowerOfTwo(img.height);
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
img = canvas;
}*/
},
});
var Texture2 = dcl(Texture, {
declaredClass: "bb4.core.Texture2",
constructor: function(args) {
if (typeof args == "string") {
args = {src: args};
} else if (typeof args != "object") args = {};
this.type = "TEXTURE_2D";
if (args.src) this.loadImage("TEXTURE_2D", args.src);
},
});
var TextureCube = dcl(Texture, {
declaredClass: "bb4.core.TextureCube",
constructor: function(args) {
// new TextureCube([+X, -X, +Y, -Y, +Z, -Z]); // length 6
// new TextureCube([+X/-X/+Z/-Z, +Y/-Y]); //length 2 (for Skybox)
// new TextureCube([+X/-X/+Z/-Z, +Y, -Y]); //length 3 (For skybox)
// new TextureCube(src) //string
function perm(x, y) {
var out = [];
for (var i = 0; i < x.length; ++i) {
for (var j = 0; j < y.length; ++j) {
out.push(y[j] + x[i]);
}
}
return out;
}
if (typeof args == "string") {
args = {src: [args]};
} else if (typeof args != "object") args = {};
this.type = "TEXTURE_CUBE_MAP";
var src = args.src || [];
if (typeof src == "string") src = [src];
switch (src.length) {
case 1:
var x = perm(["X", "Y", "Z"], ["POSITIVE_", "NEGATIVE_"]);
for (var i = 0; i < x.length; ++i) {
this.loadImage("TEXTURE_CUBE_MAP_" + x[i], src[0]);
}
break;
case 2:
var x = perm(["X", "Y", "Z"], ["POSITIVE", "NEGATIVE_"]);
for (var i = 0; i < x.length; ++i) {
this.loadImage("TEXTURE_CUBE_MAP_" + x[i], src[i]);
}
break;
};
},
bind: dcl.superCall(function(sup) {
return function() {
sup.call(this);
var gl = this.videoEngine.gl;
if (gl.texGen) {
switch(this.texgen) {
case "skybox":
// WARNING: skybox w/ cubemaps are SLOW on Intel Craphics.
gl.texGen(gl.S, gl.TEXTURE_GEN_MODE, gl.OBJECT_LINEAR);
gl.texGen(gl.T, gl.TEXTURE_GEN_MODE, gl.OBJECT_LINEAR);
gl.texGen(gl.R, gl.TEXTURE_GEN_MODE, gl.OBJECT_LINEAR);
gl.texGen(gl.S, gl.OBJECT_PLANE, _object_plane_x);
gl.texGen(gl.T, gl.OBJECT_PLANE, _object_plane_y);
gl.texGen(gl.R, gl.OBJECT_PLANE, _object_plane_z);
gl.enable(gl.TEXTURE_GEN_S);
gl.enable(gl.TEXTURE_GEN_T);
gl.enable(gl.TEXTURE_GEN_R);
break;
case "reflection":
gl.texGen(gl.S, gl.TEXTURE_GEN_MODE, gl.REFLECTION_MAP);
gl.texGen(gl.T, gl.TEXTURE_GEN_MODE, gl.REFLECTION_MAP);
gl.texGen(gl.R, gl.TEXTURE_GEN_MODE, gl.REFLECTION_MAP);
gl.enable(gl.TEXTURE_GEN_S);
gl.enable(gl.TEXTURE_GEN_T);
gl.enable(gl.TEXTURE_GEN_R);
break;
}
}
};
}),
unbind: dcl.superCall(function(sup) {
return function() {
sup.call(this);
var gl = this.videoEngine.gl;
if (gl.texGen) {
switch(this.texgen) {
case "skybox":
case "reflection":
gl.disable(gl.TEXTURE_GEN_S);
gl.disable(gl.TEXTURE_GEN_T);
gl.disable(gl.TEXTURE_GEN_R);
break;
}
}
};
}),
});
// =================================================
var Shader = dcl(Instance, {
declaredClass: "bb4.core.Shader",
constructor: function(args) {
if (!args) args = {};
this.videoEngine = args.videoEngine || this.videoEngine || console.error("args.videoEngine");
this.type = args.type || null;
this.content = args.content || null;
this._glshader = null;
this.needUpdate = true;
},
getInternalShader: function() {
// Returns internal shader object
if (this.needUpdate) this.compile();
return this._glshader;
},
compile: function() {
var content = this.content, type = this.type;
if (!content) return false;
if (!type) {
// Attempt to determine type
// TODO: Probably should be smarter (e.g. putting gl_Position
// in a comment will trick this)
if (content.indexOf("gl_Position") > -1) {
this.type = type = "VERTEX_SHADER";
} else if (content.indexOf("gl_FragColor") > -1) {
this.type = type = "FRAGMENT_SHADER";
} else {
console.error("Could not detect shader type");
return false;
}
}
var gl = this.videoEngine.gl;
var glshader = gl.createShader(gl[type]);
gl.shaderSource(glshader, content);
gl.compileShader(glshader);
if (!gl.getShaderParameter(glshader, gl.COMPILE_STATUS)) {
console.error("Could not compile shader:", gl.getShaderInfoLog(glshader));
return false;
}
this._glshader = glshader;
this.needUpdate = false;
},
});
// =================================================
// Skeletal Animation
var Bone = dcl(SpatialNode, {});
// TODO: Function to flatten bone positions (vec3)
// TODO: Function to flatten bone orientations (vec4)
// =================================================
// TODO: Material should allow parenting!!
// OPTIMIZE gl.useProgram!
// Roles of Shaders:
// 1. Applies runtime modifiers (e.g. the bones system)
var Material = dcl(Instance, {
declaredClass: "bb4.core.Material",
constructor: function(args) {
if (!args) args = {};
this.videoEngine = args.videoEngine || this.videoEngine || console.error("args.videoEngine");
this.bones = args.bones || [];
this.textures = args.textures || [];
},
// TODO: Bones system
clearBones: function() {
this.bones = [];
},
addBones: function() {
for (var i = 0; i < arguments.length; ++i) {
var bone = arguments[i];
bone["_boneIndex" + this.id] = this.bones.push(bone) - 1;
}
},
bind: function(viewport, camera) {
console.error(this.declaredClass, "bind not implemented");
return false;
},
render: function(geom, nodes) {
console.error(this.declaredClass, "render not implemented");
return false;
},
unbind: function() {
},
});
// Material using the fixed pipeline
var FixedMaterial = dcl(Material, {
declaredClass: "bb4.core.FixedMaterial",
constructor: function(args) {
if (!args) args = {};
this.mvMatrix = mat4.create();
},
bind: function(viewport, camera) {
var gl = this.videoEngine.gl;
// Switch back to fixed pipeline
if (gl.useProgram) {
gl.useProgram(null);
}
// Upload Projection Matrix
gl.matrixMode(gl.PROJECTION);
gl.loadMatrix(viewport.pMatrix);
// Bind textures
for (var i = 0; i < this.textures.length; ++i) {
var texture = this.textures[i];
gl.activeTexture(gl["TEXTURE" + i]);
texture.bind();
}
camera.updateWorldProperties();
this.vMatrix = camera.vMatrix;
gl.matrixMode(gl.MODELVIEW);
return true;
},
render: function(geom, nodes) {
var gl = this.videoEngine.gl,
glbuffer = geom.getGLBuffer();
if (!glbuffer) return false;
// Bind vertices
gl.bindBuffer(gl.ARRAY_BUFFER, glbuffer);
gl.enableClientState(gl.VERTEX_ARRAY);
gl.vertexPointer(3, gl.FLOAT, geom.stride, geom.vertexOffset);
// Bind vertex normals
gl.enableClientState(gl.NORMAL_ARRAY);
gl.normalPointer(gl.FLOAT, geom.stride, geom.vertexNormalOffset);
// Bind UV Layers (depends on number of textures, activeTexture is set appropriately)
for (var i = 0; i < this.textures.length; ++i) {
if (geom.uvOffsets[i]) {
gl.enableClientState(gl.TEXTURE_COORD_ARRAY);
gl.clientActiveTexture(gl["TEXTURE" + i]);
gl.texCoordPointer(2, gl.FLOAT, geom.stride, geom.uvOffsets[i]);
}
}
// Draw triangles for each scenenode
for (var nodeId in nodes) {
var node = nodes[nodeId];
node.updateWorldProperties(); //Ensure world properties updated.
// Construct ModelView Matrix
mat4.multiply(this.mvMatrix, this.vMatrix, node.mMatrix);
gl.loadMatrix(this.mvMatrix);
// DRAW
gl.drawArrays(gl.TRIANGLES, 0, geom.numVertices);
}
return true;
},
unbind: function() {
var gl = this.videoEngine.gl;
for (var i = 0; i < this.textures.length; ++i) {
var texture = this.textures[i];
gl.activeTexture(gl["TEXTURE" + i]);
texture.unbind();
}
},
});
// Material using Shader Program
var ProgramMaterial = dcl(Material, {
declaredClass: "bb4.core.ProgramMaterial",
constructor: function(args) {
if (!args) args = {};
var shaders = this.shaders = args.shaders || [];
for (var i = 0; i < shaders.length; ++i) {
var shader = shaders[i];
if (!dcl.isInstanceOf(shader, Shader)) {
shaders[i] = new this.videoEngine.Shader(shader);
}
}
this.glprogram = null;
this.uniforms = args.uniforms || {};
this.uniformInfo = {}; //{loc: num, type: str, size:}
this.attribInfo = {};
},
link: function() {
var gl = this.videoEngine.gl,
glEnums = this.videoEngine.glEnums,
shaders = this.shaders, i,
glprogram = this.glprogram = gl.createProgram();
for (i = 0; i < shaders.length; ++i) {
var glshader = shaders[i].getInternalShader();
if (glshader) gl.attachShader(glprogram, glshader);
else {
this.glprogram = null;
return false;
}
}
// Bind some attribs to known locations
gl.linkProgram(glprogram);
if (!gl.getProgramParameter(glprogram, gl.LINK_STATUS)) {
console.error("Unable to initialise shader program");
console.error(gl.getProgramInfoLog(glprogram));
this.glprogram = null;
return false;
}
// Populate Material Uniforms Information
var numUniforms = gl.getProgramParameter(glprogram, gl.ACTIVE_UNIFORMS);
for (var i = 0; i < numUniforms; ++i) {
var uniformInfo = gl.getActiveUniform(glprogram, i);
this.uniformInfo[uniformInfo.name] = {
loc: gl.getUniformLocation(glprogram, uniformInfo.name),
type: glEnums[uniformInfo.type], size: uniformInfo.size};
}
// Populate this.uniforms with current uniform data
for (var uniformName in this.uniformInfo) {
var uniformLoc = this.uniformInfo[uniformName].loc;
this.uniforms[uniformName] = gl.getUniform(glprogram, uniformLoc);
}
// Populate Material Attributes Information
var numAttribs = gl.getProgramParameter(glprogram, gl.ACTIVE_ATTRIBUTES);
for (var i = 0; i < numAttribs; ++i) {
var attribInfo = gl.getActiveAttrib(glprogram, i);
this.attribInfo[attribInfo.name] = {
loc: gl.getAttribLocation(glprogram, attribInfo.name),
type: glEnums[attribInfo.type], size: attribInfo.size};
}
return glprogram;
},
bind: function(viewport, camera) {
var engine = this.videoEngine, gl = engine.gl;
// Link program is it has not been linked yet.
if (!this.glprogram) {
if (!this.link()) return false;
}
var glprogram = this.glprogram,
attribInfo = this.attribInfo,
uniformInfo = this.uniformInfo,
locs = [];
gl.useProgram(this.glprogram);
// TODO: Add back the checks (need to reset this._pMatrixNode and this._vMatrixNode after every frame)
//if (this._pMatrixNode != viewport.id) {
if (this.uniformInfo["PMatrix"]) {
var uniform = this.uniformInfo["PMatrix"];
gl.uniformMatrix4fv(uniform.loc, false, viewport.pMatrix);
}
this._pMatrixNode = viewport.id;
//}
//if (this._vMatrixNode != camera.id) {
if (this.uniformInfo["VMatrix"]) {
var uniform = this.uniformInfo["VMatrix"];
gl.uniformMatrix4fv(uniform.loc, false, camera.vMatrix);
}
this._vMatrixNode = camera.id;
//}
// Bind textures to their correct position
for (var uniformName in this.uniformInfo) {
var uniformType = this.uniformInfo[uniformName].type;
if (uniformType == "SAMPLER_2D" || uniformType == "SAMPLER_CUBE") {
var textureUnit = this.uniforms[uniformName];
if (typeof textureUnit == "undefined") continue;
var texture = this.textures[textureUnit];
if (typeof texture == "undefined") continue;
gl.activeTexture(gl["TEXTURE" + textureUnit]);
texture.bind();
}
}
return true;
},
render: function(geom, nodes) {
var attribInfo = this.attribInfo,
uniformInfo = this.uniformInfo,
locs = [],
gl = this.videoEngine.gl,
glbuffer = geom.getGLBuffer();
if (!glbuffer) return false;
if (!this.glprogram) return false;
// Bind vertices
gl.bindBuffer(gl.ARRAY_BUFFER, glbuffer);
var attrib = attribInfo["Vertex"];
//TODO: OPTIMIZATION: Don't have to enable vertex attrib unless we are first material!
gl.enableVertexAttribArray(attrib.loc);
gl.vertexAttribPointer(attrib.loc, 3, gl.FLOAT, false, geom.stride, geom.vertexOffset);
if (attribInfo["Normal"]) {
var attrib = attribInfo["Normal"];
locs.push(attrib.loc);
gl.enableVertexAttribArray(attrib.loc);
gl.vertexAttribPointer(attrib.loc, 3, gl.FLOAT, false, geom.stride, geom.vertexNormalOffset);
}
// Bind UV Layers (depends on the size of the TexCoord attribute)
for (var i = 0; i < geom.numUvLayers; ++i) {
if (attribInfo["TexCoord" + i]) {
var attrib = attribInfo["TexCoord" + i];
locs.push(attrib.loc);
gl.enableVertexAttribArray(attrib.loc);
gl.vertexAttribPointer(attrib.loc, 2, gl.FLOAT, false, geom.stride, geom.uvOffsets[i]);
}
}
// Draw triangles for each SceneNode
for (var nodeId in nodes) {
var node = nodes[nodeId];
node.updateWorldProperties(); //Ensure world properties updated.
// Set the mMatrix
if (uniformInfo["MMatrix"]) {
gl.uniformMatrix4fv(uniformInfo["MMatrix"].loc, false, node.mMatrix);
}
gl.drawArrays(gl.TRIANGLES, 0, geom.numVertices);
}
// Cleanup
// TODO: OPTIMIZATION: Don't have to disable the vertex attrib array unless
// we are the last Material!
for (var i = 0; i < locs.length; ++i) {
gl.disableVertexAttribArray(locs[i]);
}
return true;
},
unbind: function() {
var gl = this.videoEngine.gl;
gl.useProgram(null);
},
});
var FixedProgramMaterial = dcl(ProgramMaterial, {
declaredClass: "bb4.core.FixedProgramMaterial",
constructor: function(args) {
// Set shaders
this.shaders = [];
this.genProgram();
},
genVertShader: function() {
var header = [
"attribute vec3 Vertex;",
"uniform mat4 MMatrix;",
"uniform mat4 VMatrix;",
"uniform mat4 PMatrix;",
];
var body = [
"void main() {",
"gl_Position = PMatrix * VMatrix * MMatrix * vec4(Vertex, 1.0);"
];
var footer = ["}"];
var textures = this.textures;
for (var i = 0; i < textures.length; ++i) {
var texture = textures[i];
header.push("attribute vec4 TexCoord" + i + ";");
header.push("varying highp vec4 vTexCoord" + i + ";");
// Depends on texgen
switch(texture.texgen) {
case "skybox":
body.push("vTexCoord" + i + " = vec4(Vertex, 0.0);");
break;
default:
body.push("vTexCoord" + i + " = TexCoord" + i + ";");
break;
}
}
return header.concat(body).concat(footer).join("\n");
},
genFragShader: function() {
var header = [];
var body = [
"void main() {",
];
var footer = [
"}"
];
var textures = this.textures;
for (var i = 0; i < textures.length; ++i) {
// We just assume it is GL_REPLACE for each texture
var texture = textures[i];
header.push("varying highp vec4 vTexCoord" + i + ";");
switch(texture.type) {
case "TEXTURE_2D":
header.push("uniform sampler2D Texture" + i + ";");
body.push("gl_FragColor = texture2D(Texture" + i + ", vTexCoord" + i + ".st);");
break;
case "TEXTURE_CUBE_MAP":
header.push("uniform samplerCube Texture" + i + ";");
body.push("gl_FragColor = textureCube(Texture" + i + ", vTexCoord" + i + ".stp);");
break;
}
}
if (textures.length < 1) {
// No texture, we just use a basic color (until we implement vertex colors)
body.push("gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);");
}
return header.concat(body).concat(footer).join("\n");
},
genProgram: function() {
// Run everytime anything is updated (e.g textures!)
var videoEngine = this.videoEngine;
this.shaders.length = 0;
this.shaders.push(new videoEngine.Shader({content: this.genVertShader()}));
this.shaders.push(new videoEngine.Shader({content: this.genFragShader()}));
this.glprogram = null;
},
});
// =================================================
var SceneNode = dcl(SpatialNode, {
declaredClass: "bb4.core.SceneNode",
constructor: function(args) {
if (!args) args = {};
this.geoms = args.geoms || {}; //Mapping geomId -> Geom (for later lookup by Geomid)
},
addGeoms: function() {
// attachGeoms(geom1, geom2...)
for (var i = 0; i < arguments.length; ++i) {
var geom = arguments[i];
this.geoms[geom.id] = geom;
}
return this;
},
});
// =================================================
function mat4NormalMatrix(out, a) {
glm.mat4.transpose(out, glm.mat4.invert(out, a));
//Remove affine translation part.
out[3] = out[7] = out[11] = out[12] = out[13] = out[14] = 0.0;
out[15] = 1;
return out;
}
// ========================================================
var _GLBuffer = dcl(null, {
declaredClass: "bb4.core._GLBuffer",
constructor: function(engine, usage) {
var gl = engine.gl;
this.engine = engine;
// this.size = data.length * 4;
this.usage = usage;
var glbuffer = this.glbuffer = gl.createBuffer();
},
update: function(data) {
var gl = this.engine.gl;
// TODO: gl.bufferSubData ???
gl.bindBuffer(gl.ARRAY_BUFFER, this.glbuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl[this.usage]);
}
});
var Geom = dcl(Instance, {
declaredClass: "bb4.core.Geom",
constructor: function(args) {
// NOTE: vertices, vertexNormals, uvLayers may be merged into a
// single array in the future to save buffer space
// Vertex (3 floats) | Normal (3 floats) | UV 0 (2 floats) | UV 1 (2 floats) ...
// TODO: Switch to:
if (!args) args = {};
var videoEngine = this.videoEngine = args.videoEngine || this.videoEngine || console.error("args.videoEngine");
this.data = args.data || [];
this.numVertices = args.numVertices || 0;
this.numUvLayers = args.numUvLayers || null;
var numBuffers = this.numBuffers = args.numBuffers || 1; //Default only use 1 buffer
// Use more than one buffer if you plan on updating the Geom frequently
// See also http://www.opengl.org/wiki/Buffer_Object_Streaming
this.material = args.material || null;
if (!args.material) console.error("No material");
this.glbuffer = null;
this.glbuffers = []; //Array of GLBuffers
this.currentBufferNum = -1;
this.bufferNeedUpdate = true;
this.stride = null;
this.vertexOffset = 0; //always 0
this.vertexNormalOffset = 12; //always 12
this.uvOffsets = null;
},
appendGeom: function(geom) {
this.data = this.data.concat(geom.data);
this.bufferNeedUpdate = true;
return true;
},
appendVertex: function(pos, normal, uvLayers) {
if (!uvLayers) uvLayers = [];
if (this.numUvLayers != null) {
if (uvLayers.length != this.numUvLayers) {
console.error("uvLayers.length != this.numUvLayers");
return false;
}
} else this.numUvLayers = uvLayers.length;
this.data = this.data.concat(pos);
this.data = this.data.concat(normal);
for (var i = 0; i < uvLayers.length; ++i) {
this.data = this.data.concat(uvLayers[i]);
}
this.numVertices += 1;
this.bufferNeedUpdate = true;
return true;
},
appendQuad: function() {
var that = this, x = arguments;
function v() {
for (var j = 0; j < arguments.length; ++j) {
var i = arguments[j];
that.appendVertex(x[i * 3], x[i * 3 + 1], x[i * 3 + 2]);
}
}
var a = 0, b = 1, c = 2, d = 3;
v(a, b, c, c, d, a);
return this;
},
updateBuffers: function() {
var engine = this.videoEngine, gl = engine.gl;
var nextBufferNum = this.currentBufferNum + 1;
if (nextBufferNum > this.numBuffers) {
nextBufferNum = 0;
}
var buffer = this.glbuffers[nextBufferNum];
if (!buffer) {
buffer = this.glbuffers[nextBufferNum] = new _GLBuffer(engine, "STATIC_DRAW");
}
buffer.update(this.data);
this.currentBufferNum = nextBufferNum;
this.stride = (4 * 3) + (4 * 3) + (4 * 2 * this.numUvLayers);
// Calculate UV offsets
this.uvOffsets = [];
for (var i = 0; i < this.numUvLayers; ++i) {
this.uvOffsets.push((4 * 3) + (4 * 3) + (4 * 2 * i));
}
this.glbuffer = buffer.glbuffer;
this.bufferNeedUpdate = false;
},
getGLBuffer: function() {
// Returns updated VBO representing the geometry
if (this.bufferNeedUpdate) this.updateBuffers();
return this.glbuffer;
},
// Utilities
appendPlane: function(u, v, width, height, widthSegments, heightSegments, wTranslate) {
// Appends a plane geometry to the Geom
var uDir = 1, vDir = 1;
switch(u) {
case "x": u = 0; break;
case "-x": u = 0; uDir = -1; break;
case "y": u = 1; break;
case "-y": u = 1; uDir = -1; break;
case "z": u = 2; break;
case "-z": u = 2; uDir = -1; break;
}
switch(v) {
case "x": v = 0; break;
case "-x": v = 0; vDir = -1; break;
case "y": v = 1; break;
case "-y": v = 1; vDir = -1; break;
case "z": v = 2; break;
case "-z": v = 2; vDir = -1; break;
}
var w = 3 - u - v;
// Vertices must be counter-clockwise
var segWidth = width / widthSegments;
var segHeight = height / heightSegments;
var uvSegWidth = 1 / widthSegments;
var uvSegHeight = 1 / heightSegments;
var halfWidth = width / 2;
var halfHeight = height / 2;
var vertexNormal = [0, 0, 1]; //All vertex normals are the same (ARE THEY?)
var faces = [];
for (var ix = 0; ix < widthSegments; ++ix) {
for (var iy = 0; iy < heightSegments; ++iy) {
var a = [0, 0, 0], b = [0,0,0], c = [0,0,0], d = [0,0,0];
a[u] = b[u] = (ix * segWidth - halfWidth) * uDir;
b[v] = c[v] = (iy * segHeight - halfHeight) * vDir;
c[u] = d[u] = ((ix + 1) * segWidth - halfWidth) * uDir;
a[v] = d[v] = ((iy + 1) * segHeight - halfHeight) * vDir;
a[w] = b[w] = c[w] = d[w] = wTranslate;
var uA = [0, 0], uB = [0, 0], uC = [0, 0], uD = [0, 0];
uA[0] = uB[0] = (ix * uvSegWidth);
uB[1] = uC[1] = (iy * uvSegHeight);
uC[0] = uD[0] = ((ix + 1) * uvSegWidth);
uA[1] = uD[1] = ((iy + 1) * uvSegHeight);
this.appendQuad(a, vertexNormal, [uA],
b, vertexNormal, [uB],
c, vertexNormal, [uC],
d, vertexNormal, [uD]);
}
}
return this;
},
appendCuboid: function(args) {
if (typeof args != "object") args = {};
var width = args.width || args.height || args.depth || 1;
var height = args.height || args.width || args.depth || 1;
var depth = args.depth || args.width || args.height || 1;
var widthSegments = args.widthSegments || args.heightSegments || args.depthSegments || 1;
var heightSegments = args.heightSegments || args.widthSegments || args.depthSegments || 1;
var depthSegments = args.depthSegments || args.widthSegments || args.heightSegments || 1;
var invert = args.invert || false;
// Appends cuboid geometry
var halfDepth = depth / 2;
var halfWidth = width / 2;
var halfHeight = height / 2;
if (invert) var inv = function(x){ return x[0] == "-" ? x[1] : "-" + x; };
else var inv = function(x){ return x; };
// Positive Z
this.appendPlane(inv("x"), "y", width, height, widthSegments, heightSegments, halfDepth);
// Negative Z
this.appendPlane(inv("-x"), "y", width, height, widthSegments, heightSegments,
-halfDepth);
// Positive X
this.appendPlane(inv("-z"), "y", depth, height, depthSegments, heightSegments, halfWidth);
// Negative X
this.appendPlane(inv("z"), "y", depth, height, depthSegments, heightSegments, -halfWidth);
// Positive Y
this.appendPlane(inv("-x"), "z", width, depth, widthSegments, depthSegments, halfHeight);
// Negative Y
this.appendPlane(inv("x"), "z", width, depth, widthSegments, depthSegments, -halfHeight);
return this;
},
});
// ====================================================
var Camera = dcl(SceneNode, {
declaredClass: "bb4.core.Camera",
constructor: function(args) {
if (!args) args = {};
this.vMatrix = glm.mat4.create();
},
cameraRender: function(viewport, scene) {
this.updateWorldProperties();
// Info: http://3dgep.com/?p=1700
glm.mat4.invert(this.vMatrix, this.mMatrix);
// Now, render Scene!
scene.render(viewport, this);
},
});
// ===============================================
var SceneManager = dcl(null, {
declaredClass: "bb4.core.SceneManager",
constructor: function(args) {
if (!args) args = {};
this.videoEngine = args.videoEngine || this.videoEngine || console.error("args.videoEngine");
this.main = {};
},
removeNode: function(node) {
// Removes node from all render queues
for (var materialId in this.main) {
var geoms = this.main[materialId];
for (var geomId in geoms) {
var nodes = geoms[geomId];
delete nodes[node.id];
}
}
},
addNode: function(node) {
// TODO: Just adding all nodes to the main render queue for now
for (var geomId in node.geoms) {
var materialId = node.geoms[geomId].material.id;
if (!(materialId in this.main)) {
// Material Id does not exist. Create it.
this.main[materialId] = {};
}
var matGroup = this.main[materialId];
if (!(geomId in matGroup)) {
matGroup[geomId] = {};
}
// Slot the node in.
matGroup[geomId][node.id] = node;
}
},
render: function(viewport, camera) {
var setupMaterial = false;
var geom = null;
var gl = this.videoEngine.gl;
var material;
// Lol complicated code. Thanks Javascript for having sucky
// data structures.
gl.enable(gl.DEPTH_TEST);
for (var materialId in this.main) {
var geoms = this.main[materialId];
for (var geomId in geoms) {
var nodes = geoms[geomId];
geom = null;
for (var nodeId in nodes) {
var node = nodes[nodeId];
if (!setupMaterial) {
material = node.geoms[geomId].material;
material.bind(viewport, camera);
setupMaterial = true;
}
//var material = node.geoms[geomId].material;
//material.bind(viewport, camera);
geom = node.geoms[geomId];
break;
}
if (geom) material.render(geom, nodes);
}
if (setupMaterial) material.unbind();
setupMaterial = false;
}
// TODO: A render queue for objects with transparency
},
});
// ==================================================
var Viewport = dcl(Instance, {
declaredClass: "bb4.core.Viewport",
constructor: function(args) {
// A viewport provides a view of a SceneGraph
if (!args) args = {};
this.videoEngine = args.videoEngine || this.videoEngine || console.error("args.videoEngine");
this.x = 0;
this.y = 0;
this.width = 640;
this.height = 480;
this.scene = args.scene || null;
this.camera = args.camera || null;
},
setScene: function(scene, camera) {
// Set scene to render with optional camera.
// If no camera is provided, we will create our own at identity.
// TODO: Create our own scene at identity!
this.scene = scene || null;
this.camera = camera || null;
return this;
},
resizeFill: function(args) {
// Resizes the viewport to fill the area
var screenWidth = args.width || this.videoEngine.getWidth();
var screenHeight = args.height || this.videoEngine.getHeight();
var aspect = args.aspectRatio || null;
// TODO: We assume that we anchor at the centre of the screen
// TODO: Some padding settings (e.g. like I want a small viewport
// at the side of the screen)
if (aspect) {
if (aspect > 1) {
this.width = screenWidth;
this.height = screenWidth / aspect;
} else {
this.width = screenHeight * aspect;
this.height = screenHeight;
}
} else {
this.width = screenWidth;
this.height = screenHeight;
}
this.x = (screenWidth - this.width) / 2;
this.y = (screenHeight - this.height) / 2;
this.reshape();
return this;
},
enableResizeFill: function(args) {
// Attach a resize listener to videoEngine and call resizeFill on resize.
var that = this;
if (!args) args = {};
this.resizeFill(args);
this._resizefillid = this.videoEngine.on("resize", function() {
that.resizeFill(args);
});
return this;
},
disableResizeFill: function() {
if (this._resizefillid) this.videoEngine.removeListener(this._resizefillid);
return this;
},
render: function() {
var gl = this.videoEngine.gl,
scene = this.scene,
camera = this.camera;
// Clear depth buffer! (Different projections use different depth buffer values)
gl.depthMask(true);
gl.clear(gl.DEPTH_BUFFER_BIT);
if (scene && camera) {
gl.viewport(this.x, this.y, this.width, this.height);
camera.cameraRender(this, scene);
}
return this;
},
getWidth: function() {return this.width;},
getHeight: function() {return this.height;},
setWidth: function(x) {this.width = x;},
setHeight: function(x) {this.height = x;},
getAspect: function() {return this.width / this.height;},
});
var PerspectiveViewport = dcl(Viewport, {
declaredClass: "bb4.core.PerspectiveViewport",
constructor: function(args) {
if (!args) args = {};
var pMatrix = glm.mat4.create();
//TODO: move Fov to camera
this.pMatrix = mat4.create();
this.reshape();
},
reshape: function() {
mat4.perspective(this.pMatrix, Math.PI/4, this.getAspect() , 0.1, 100);
return this;
},
});
var OrthographicViewport = dcl(Viewport, {
declaredClass: "bb4.core.OrthographicViewport",
constructor: function(args) {
if (!args) args = {};
if (this.width > this.height) {
var height = 2;
var width = (this.width / this.height) * 2;
} else {
// let width be one unit
var width = 2;
var height = (this.height / this.width) * 2;
}
this.pMatrix = mat4.create();
this.reshape();
},
reshape: function() {
mat4.ortho(this.pMatrix, -width / 2, width / 2, -height / 2, height / 2, -1, 1);
return this;
},
});
// ====================================================
// Input subsystem
var Input = dcl(EventEmitter, {
declaredClass: "bb4.core.Input",
constructor: function(args) {
if (!args) args = {};
var videoEngine = this.videoEngine = args.videoEngine || this.videoEngine || console.error("args.videoEngine");
var logicEngine = this.logicEngine = args.logicEngine || this.logicEngine || console.error("args.logicEngine");
this.name = args.name || "Unknown";
this.currentDown = this.down = false; //true if magnitude > engine.sensitivity
this.currentMag = this.mag = 0.0; //0.0 to 1.0
this.downChanged = false;
this.magChanged = false;
var that = this;
this._beforeStepListener = logicEngine.on("beforestep", function() {
var downChanged = that.downChanged = that.currentDown != that.down ? true : false;
var magChanged = that.magChanged = that.currentMag != that.mag ? true: false;
that.down = that.currentDown;
that.mag = that.currentMag;
if (downChanged) {
that.emit("downchange");
if (that.down)
that.emit("down");
else
that.emit("up");
}
if (magChanged) {
that.emit("magchange");
}
});
},
mapKey: function(key) {
if (this._mapDownListener) this.videoEngine.removeListener(this._mapDownListener);
if (this._mapUpListener) this.videoEngine.removeListener(this._mapUpListener);
var that = this;
this._mapDownListener = this.videoEngine.on("keydown", function(e) {
if (e.key == key) {
that.currentDown = true;
that.currentMag = 1.0;
}
});
this._mapUpListener = this.videoEngine.on("keyup", function(e) {
if (e.key == key) {
that.currentDown = false;
that.currentMag = 0.0;
}
});
},
});
var Axis = dcl(EventEmitter, {
declaredClass: "bb4.core.Axis",
constructor: function(args) {
if (!args) args = {};
this.up = args.up || null;
this.down = args.down || null;
this.left = args.left || null;
this.right = args.right || null;
this.rad = args.rad || 0.0;
this.mag = args.mag || 0;
var that = this;
this.__handler = function() {
var x = (that.right.mag - that.left.mag);
var y = (that.up.mag - that.down.mag);
that.rad = Math.atan2(y, x);
var mag = Math.sqrt(x*x + y*y);
if (Math.abs(x) > Math.abs(y)) mag *= Math.abs(Math.cos(that.rad));
else mag *= Math.abs(Math.sin(that.rad));
that.mag = Math.min(1.0, Math.max(0.0, mag));
}
this._upListener = this.up.on("magchange", this.__handler);
this._downListener = this.down.on("magchange", this.__handler);
this._leftListener = this.left.on("magchange", this.__handler);
this._rightListener = this.right.on("magchange", this.__handler);
},
});
// ====================================================
var Image = dcl(EventEmitter, {
// Represents an Image. Engine.getImage(). Returns cached image
// if available. Just like Data, the image might not have finished
// loading. Hence, it emits onLoad events.
declaredClass: "bb4.core.Image",
isComplete: function() {return false;},
getWidth: function() {return 0;},
getHeight: function() {return 0;},
});
var baseExports = {
vec2: vec2,
vec3: vec3,
quat: quat,
mat4: mat4,
mat3: mat3,
Instance: Instance,
EventEmitter: EventEmitter,
Node: Node,
FunctionQueue: FunctionQueue,
SpatialNode: SpatialNode,
};
function copyClasses(dest, src) {
for (var name in src) {
if (/[A-Z]/.test(name[0]) && src[name].prototype)
dest[name] = src[name];
}
}
function defClasses(t, obj) {
for (var name in t) {
if (/[A-Z]/.test(name[0]) && t[name].prototype)
t[name] = dcl(t[name], obj);
}
}
// Logic Engines can be made children of each other to form manageable
// logic groups. Logic Nodes can become members of Logic Engines
// by listening for them.
var LogicEngine = dcl([Node, EventEmitter], {
declaredClass: "bb4.core.LogicEngine",
constructor: function(args) {
if (!args) args = {};
this._lastStepTime = new Date().getTime(); //Local to reference time
this.stepInterval = 1000 / 60; //Logic runs at 60fps
defClasses(this, {logicEngine: this});
},
step: function() {
// Logic Step
this.emit("beforestep");
this.emit("step");
this.emit("afterstep");
for (var nodeId in this.children) {
// TODO: Assumes that stepInterval of children are the same
this.children[nodeId].step();
}
this._lastStepTime += this.stepInterval;
},
update: function(time) {
if (!time) time = new Date().getTime();
while (this._lastStepTime + this.stepInterval < time)
this.step();
},
});
var _logicExports = {
LogicEngine: LogicEngine,
};
var logicExports = Object.create(baseExports);
for (var name in _logicExports)
logicExports[name] = _logicExports[name];
for (var name in logicExports)
LogicEngine[name] = LogicEngine.prototype[name] = logicExports[name];
var VideoEngine = dcl(EventEmitter, {
declaredClass: "bb4.core.VideoEngine",
constructor: function(args) {
if (!args) args = {};
this.viewports = [];
this.width = args.width || 640; // Initial width of window
this.height = args.height || 480; // Initial height of window
var logicEngine = this.logicEngine = args.logicEngine || new this.LogicEngine();
this.conductor = args.conductor || null;
copyClasses(this, logicEngine);
defClasses(this, {logicEngine: logicEngine, videoEngine: this});
},
addViewport: function(viewport) {
// Add a viewport to the set of viewports.
this.viewports.push(viewport);
},
fullscreen: function() {
// Not implemented
// TODO: Send fullscreen failure event immediately
},
render: function() {
// Renders the scene graph
var gl = this.gl,
viewports = this.viewports;
gl.viewport(0, 0, this.width, this.height);
// Consider not even clearing the color buffer at all (glClear is slow)
//gl.clear(gl.COLOR_BUFFER_BIT);
for (var i = 0; i < viewports.length; ++i)
viewports[i].render();
},
// TODO: Should getImage be here????
getImage: function(src) {
// Returns Image
return new Image(src);
},
});
var _videoExports = {
Texture: Texture,
Texture2: Texture2,
TextureCube: TextureCube,
Shader: Shader,
Bone: Bone,
Material: Material,
FixedMaterial: FixedMaterial,
ProgramMaterial: ProgramMaterial,
FixedProgramMaterial: FixedProgramMaterial,
SceneNode: SceneNode,
Geom: Geom,
Camera: Camera,
SceneManager: SceneManager,
Viewport: Viewport,
PerspectiveViewport: PerspectiveViewport,
OrthographicViewport: OrthographicViewport,
Input: Input,
Axis: Axis,
Image: Image,
VideoEngine: VideoEngine,
};
var videoExports = Object.create(logicExports);
for (var name in _videoExports)
videoExports[name] = _videoExports[name];
for (var name in videoExports)
VideoEngine[name] = VideoEngine.prototype[name] = videoExports[name];
// The conductor manages and coordinates the running of all of the different engine types
// CONDUCTOR is the up-and-running tool of bb4 designed for rapid prototyping.
var Conductor = dcl(EventEmitter, {
declaredClass: "bb4.core.Conductor",
constructor: function(args) {
if (!args) args = {};
var logicEngine = this.logicEngine = args.logicEngine || new this.LogicEngine({conductor: this});
var videoEngine = this.videoEngine = args.videoEngine || new this.VideoEngine({conductor: this, logicEngine: logicEngine});
copyClasses(this, logicEngine);
copyClasses(this, videoEngine);
defClasses(this, {logicEngine: logicEngine, videoEngine: videoEngine, conductor: this});
var scene = this.scene = new videoEngine.SceneManager({videoEngine: videoEngine, logicEngine: logicEngine});
var camera = this.camera = new videoEngine.Camera({videoEngine: videoEngine, logicEngine: logicEngine});
var viewport = this.viewport = new videoEngine.PerspectiveViewport({videoEngine: videoEngine, logicEngine: logicEngine, scene: scene, camera: camera}).enableResizeFill();
videoEngine.addViewport(viewport);
var that = this;
var cback = function(e, target, callbackId, event) {
that.emit(event, e, target);
};
videoEngine.on("*", cback);
logicEngine.on("*", cback);
},
render: function() {
this.videoEngine.render();
},
update: function(time) {
this.logicEngine.update(time);
this.render();
},
play: function() {
throw "Not implemented";
},
pause: function() {
throw "Not implemented";
},
});
var _conductorExports = {
Conductor: Conductor,
};
var conductorExports = Object.create(logicExports);
for (var name in videoExports)
conductorExports[name] = videoExports[name];
for (var name in _conductorExports)
conductorExports[name] = _conductorExports[name];
for (var name in conductorExports)
Conductor[name] = Conductor.prototype[name] = conductorExports[name];
return Conductor;
});
// vim: set expandtab tabstop=2 shiftwidth=2:
|
import React from 'react';
import boom from 'boom';
import nodemailer from 'nodemailer';
import stubTransport from 'nodemailer-stub-transport';
import makeHandleEmail from '../handle-email';
describe('handle email requests', () => {
const subject = 'This is a test';
const testComponent = () => (
<mj-text>
<p>This is a test</p>
</mj-text>
);
const renderHTML = jest.fn(() => <p>this is a test</p>);
const reply = jest.fn();
const request = {
payload: {
email: 'example@gmail.com',
firstName: 'john',
lastName: 'doe'
},
log: jest.fn()
};
const transport = nodemailer.createTransport(stubTransport());
const sendMail = jest.fn(data => transport.sendMail(data));
beforeEach(() => {
sendMail.mockClear();
renderHTML.mockClear();
reply.mockClear();
request.log.mockClear();
});
// TODO: can't confirm that current email stub returns
// envelope, need to look further into this to figure out
// the problem, currently, the envelope is not defined, so
// this test is not accurate
// it.skip('should render the html, and send an email to the requested user', async () => {
// const handleEmail = makeHandleEmail(
// renderHTML,
// sendMail,
// testComponent,
// subject
// );
//
// await handleEmail(request, reply);
//
// expect(sendMail).toHaveBeenCalled();
// expect(sendMail).toHaveBeenCalledTimes(1);
// expect(sendMail.mock.calls[0][0]).toMatchSnapshot();
// });
it('should log the envelope when email is successful', async () => {
const handleEmail = makeHandleEmail(
renderHTML,
() => Promise.resolve('bloop'),
testComponent,
subject
);
await handleEmail(request, reply);
expect(request.log).toHaveBeenCalled();
expect(request.log).toHaveBeenCalledTimes(1);
expect(request.log).toHaveBeenCalledWith(
'info',
{
msg: 'Logged email information',
data: 'bloop'
}
);
});
it('should reply success when email is sent', async () => {
const handleEmail = makeHandleEmail(
renderHTML,
() => Promise.resolve('bloop'),
testComponent,
subject
);
await handleEmail(request, reply);
expect(reply).toHaveBeenCalled();
expect(reply).toHaveBeenCalledTimes(1);
expect(reply).toHaveBeenCalledWith({
success: true
});
});
it('should log an error when something goes wrong', async () => {
const handleEmail = makeHandleEmail(
renderHTML,
() => Promise.reject(new Error('uh oh!')),
testComponent,
subject
);
await handleEmail(request, reply);
expect(request.log).toHaveBeenCalled();
expect(request.log).toHaveBeenCalledTimes(1);
expect(request.log).toHaveBeenCalledWith(
'error',
{
err: new Error('uh oh!'),
msg: 'unable to send simple email'
}
);
});
it('should reply bad implementation when an error occurrs', async () => {
const handleEmail = makeHandleEmail(
renderHTML,
() => Promise.reject(new Error('uh oh!')),
testComponent,
subject
);
await handleEmail(request, reply);
expect(reply).toHaveBeenCalled();
expect(reply).toHaveBeenCalledTimes(1);
expect(reply).toHaveBeenCalledWith(boom.badImplementation());
});
});
|
export class RemarkTypeFormatValueConverter {
toView(reservationRequestRemarkType) {
switch (reservationRequestRemarkType) {
case "ReservationRequestInvoiceComment":
return 'ReservationRequestInvoiceComment';
break;
case "ReservationRequestVolComment":
return 'ReservationRequestVolComment';
break;
case "ReservationRequestSupplierRemark":
return 'ReservationRequestSupplierRemark';
break;
case "ReservationInvoiceComment":
return 'ReservationInvoiceComment';
break;
case "ReservationComment":
return 'ReservationComment';
break;
case "ReservationSupplierRemark":
return 'ReservationSupplierRemark';
break;
case "System":
return 'System';
break;
default:
return 'Type was not found';
}
}
} |
'use strict';
/**
* Module dependencies.
*/
var notes = require('../../app/controllers/notes.server.controller'),
multer = require('multer'),
users = require('../../app/controllers/users.server.controller');
module.exports = function(app) {
// Note Routes
app.route('/notes')
.get(users.requiresLogin, notes.fromUser, notes.fromTag)
// notes.create
.post(users.requiresLogin,
multer({
dest: './uploads/tmp',
limit: {
filesize: 5242880 // 5MB
},
onFileSizeLimit: function (file) {
fs.unlink('./' + file.path) // delete the partially written file
res.status(403).send({
message: 'Image size exceeds 5MB'
});
}
}), notes.addImageToNote);
app.route('/notes/findAll')
.get(notes.findAll);
app.route('/notes/:noteId/image')
.get(users.requiresLogin, notes.getImage)
.post(users.requiresLogin,
multer({
dest: './uploads/tmp',
limit: {
filesize: 5242880 // 5MB
},
onFileSizeLimit: function (file) {
fs.unlink('./' + file.path) // delete the partially written file
res.status(403).send({
message: 'Image size exceeds 5MB'
});
}
}), notes.hasAuthorization, notes.addImageToNote)
.delete(users.requiresLogin, notes.removeUserOwnedNote);
app.route('/notes/:noteId/doc')
.get(users.requiresLogin, notes.getDoc)
.post(users.requiresLogin,
multer({
dest: './uploads/tmp',
limit: {
filesize: 5242880 // 5MB
},
onFileSizeLimit: function (file) {
fs.unlink('./' + file.path) // delete the partially written file
res.status(403).send({
message: 'File size exceeds 5MB'
});
}
}), notes.hasAuthorization, notes.addDocToNote);
app.route('/notes/:noteId')
.get(notes.read)
.put(users.requiresLogin, notes.hasAuthorization, notes.update)
.delete(users.isAdmin, notes.delete);
app.route('/notes/tags/:noteId')
.put(users.requiresLogin, notes.addTags)
.delete(users.requiresLogin, notes.removeTags);
app.route('/notes/ratings/:noteId')
.put(users.requiresLogin, users.haveNotRated, notes.addRating);
app.route('/notes/flagSpam/:noteId')
.put(users.requiresLogin, notes.flagAsSpam);
app.param('noteId', notes.noteById);
};
|
var AttributeList = require('./AttributeList');
var Item = module.exports = function Item(attributes) {
this.attributes = new AttributeList(attributes);
this.properties = {
byteRange : null,
daiPlacementOpportunity: null,
date : null,
discontinuity : null,
duration : null,
title : null,
uri : null
};
};
Item.prototype.get = function get(key) {
if (this.propertiesHasKey(key)) {
return this.properties[key];
} else {
return this.attributes.get(key);
}
};
Item.prototype.set = function set(key, value) {
if (this.propertiesHasKey(key)) {
this.properties[key] = value;
} else {
this.attributes.set(key, value);
}
return this;
};
Item.prototype.serialize = function serialize() {
return {
attributes : this.attributes.serialize(),
properties : this.properties
}
};
Item.unserialize = function unserialize(constructor, object) {
var item = new constructor;
item.attributes = AttributeList.unserialize(object.attributes);
item.properties = object.properties;
return item;
};
Item.prototype.setData = function setData(data) {
var self = this;
Object.keys(data).forEach(function(key) {
self.set(key, data[key]);
});
};
Item.prototype.propertiesHasKey = function hasKey(key) {
return Object.keys(this.properties).indexOf(key) > -1;
};
|
"use strict";
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; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Controls = (function () {
function Controls(actor, action, hasStarted) {
_classCallCheck(this, Controls);
this.actor = actor;
this.action = action;
if (hasStarted) {
this.id = this.bindAction();
this.action.activate();
}
}
_createClass(Controls, [{
key: "start",
value: function start(input) {
this.id = this.bindAction();
this.actor.start(this.id, input);
this.action.activate();
return this;
}
}, {
key: "stop",
value: function stop() {
this.actor.unbindAction(this.id);
this.action.deactivate();
return this;
}
}, {
key: "pause",
value: function pause() {
this.action.deactivate();
return this;
}
}, {
key: "resume",
value: function resume() {
this.action.activate();
return this;
}
}, {
key: "toggle",
value: function toggle() {
var resume = this.actor.hasAction(this.id) ? this.resume : this.start;
return this.action.isActive ? this.pause() : resume.call(this);
}
}, {
key: "then",
value: function then() {
var _actor;
(_actor = this.actor).then.apply(_actor, arguments);
return this;
}
}, {
key: "bindAction",
value: function bindAction() {
return this.actor.bindAction(this.action, this.id);
}
}]);
return Controls;
})();
module.exports = Controls; |
module.exports = function(grunt) {
grunt.config('rename', {
backupLayout: {
src: '<%= root %>/app/file/layout',
dest: '<%= root %>/app/file/layout.bak'
},
backupTheme: {
src: '<%= root %>/app/file/theme',
dest: '<%= root %>/app/file/theme.bak'
},
backupWidget: {
src: '<%= root %>/app/file/widget',
dest: '<%= root %>/app/file/widget.bak'
},
restoreLayout: {
src: '<%= root %>/app/file/layout.bak',
dest: '<%= root %>/app/file/layout'
},
restoreTheme: {
src: '<%= root %>/app/file/theme.bak',
dest: '<%= root %>/app/file/theme'
},
restoreWidget: {
src: '<%= root %>/app/file/widget.bak',
dest: '<%= root %>/app/file/widget'
},
});
grunt.config('symlink', {
sites: {
files: [{
expand: true,
cwd: '<%= root %>/internal',
src: ['widget', 'layout', 'theme'],
dest: '<%= root %>/app/file'
}]
},
});
grunt.config('clean', {
folder: ["<%= root %>/app/file/layout", "<%= root %>/app/file/theme", "<%= root %>/app/file/widget"],
options: {
force: true
},
});
grunt.loadNpmTasks('grunt-rename');
grunt.loadNpmTasks('grunt-contrib-symlink');
grunt.loadNpmTasks('grunt-contrib-clean');
};
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'about', 'da', {
copy: 'Copyright © $1. Alle rettigheder forbeholdes.',
dlgTitle: 'Om CKEditor 4',
moreInfo: 'For informationer omkring licens, se venligst vores hjemmeside (på engelsk):'
} );
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var ts = require("typescript");
var Lint = require("tslint");
var changes_1 = require("../changes");
var memberRuleWalker_1 = require("./memberRuleWalker");
var util_1 = require("./util");
var Rule = /** @class */ (function (_super) {
__extends(Rule, _super);
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
Rule.prototype.applyWithProgram = function (sourceFile, program) {
return this.applyWithWalker(new ChangeReturnTypeWalker(sourceFile, this.getOptions(), program));
};
return Rule;
}(Lint.Rules.TypedRule));
exports.Rule = Rule;
var ChangeReturnTypeWalker = /** @class */ (function (_super) {
__extends(ChangeReturnTypeWalker, _super);
function ChangeReturnTypeWalker() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.configEntryName = "propertyTypeChanges";
return _this;
}
ChangeReturnTypeWalker.prototype.checkForChanges = function (node, oldParentName, oldMemberName, guess) {
if (node.kind !== ts.SyntaxKind.SetAccessor
&& node.kind !== ts.SyntaxKind.GetAccessor
&& node.kind !== ts.SyntaxKind.PropertyAccessExpression
&& node.kind !== ts.SyntaxKind.ElementAccessExpression) {
return;
}
var newType = changes_1.changes[this.configEntryName][oldParentName] && changes_1.changes[this.configEntryName][oldParentName][oldMemberName];
if (newType) {
var checker = this.getTypeChecker();
var oldType = void 0;
if (node.kind === ts.SyntaxKind.GetAccessor) {
var signature = checker.getSignatureFromDeclaration(node);
if (!signature)
return;
oldType = util_1.getFullyQualifiedName(signature.getReturnType(), checker);
}
else {
oldType = util_1.getFullyQualifiedName(checker.getTypeAtLocation(node), checker);
}
if (guess) {
this.addFailureAtNode(node, "The type of this property might have changed to \"" + newType + "\" (assuming this is a member of \"" + oldParentName + "\", inferred type is \"any\").");
}
else {
this.addFailureAtNode(node, "The type of property \"" + oldParentName + "#" + oldMemberName + "\" has changed from \"" + oldType + "\" to \"" + newType + "\"");
}
}
};
return ChangeReturnTypeWalker;
}(memberRuleWalker_1.MemberRuleWalker));
//# sourceMappingURL=changePropertyTypeRule.js.map |
const staticFilesRoute = {
method: 'GET',
path: '/{file*}',
handler: {
directory: {
path: '.',
},
},
};
module.exports = [staticFilesRoute];
|
import React from 'react'
import { IndexLink, Link } from 'react-router'
import './HomeView.scss'
const styles = {};
let data = require('../assets/data.json');
class Results extends React.Component {
constructor (props) {
super(props);
this.state = {
heroImage: require(`../../../img/${data.results[0].hero}`),
}
}
componentDidMount() {}
componentWillReceiveProps(nextProps) {}
render() {
return(
<div className={'results'}>
<div className="row subheaderbar" >
<em>{data.quizName}</em>
</div>
<div className="r1">
<img src={this.state.heroImage} className="img-responsive img-circle results" />
</div>
<div className="row2">
<h2>Your Car Should be <b>{data.results[0].title}</b></h2>
<Link className="whystate">email my results></Link>
<p className="resultLegend">{data.results[0].text}
<a href="http://www.libertymutual.com/carbuying" >Click here for guaranteed savings</a>
through the Liberty Mutual Car Buying Program.
</p>
</div>
<div className="clearfix"></div>
<div className="col-sm-6">
<p className="text-center lm-blue">
<em>Which Is Right for you:<br />
Gasoline, Electric or Hybrid?</em>
</p>
<nav aria-label="...">
<ul className="pager">
<li><a href="#"><em>Take this quiz <span className="yellow">></span></em></a></li>
</ul>
</nav>
</div>
<div className="col-sm-6">
<p className="text-center lm-blue">
<em>Which Is Right for You:<br />
Buy or Lease?</em>
</p>
<nav aria-label="...">
<ul className="pager">
<li><a href="#"><em>Take this quiz <span className="yellow">></span></em></a></li>
</ul>
</nav>
</div>
</div>
)
}
}
Results.contextTypes = {
router: React.PropTypes.object.isRequired
};
export default Results
|
var f = function(){
//定义测试模块
module("scrolly");
var _ = NEJ.P,
_p = _('nej.ui');
//开始单元测试
test('scrolly',function(){
var _sly = _p._$$ScrollerY._$allocate({
parent:'scroll-y-container',
onscroll:function(){
},
onscrollend:function(){
},
onbounce:function(_event){
},
onbouncend:function(_event){
},
onbouncestart:function(_event){
},
onrelease:function(){
}
});
});
}
module('依赖模块');
test('define',function(){
define('{pro}scrollyTest.js',['{lib}ui/scroller/scroller.y.js','{pro}log.js'],f);
}); |
'use strict';
var streamerService = (function() {
function Streamer(serviceId, ioType, callback) {
this._serviceId = serviceId;
this._ioType = ioType == 'STDOUT' ? 'out' : 'error';
this._xhr = null;
this._dataCallback = callback || function() {};
this._createXhrObject();
}
Streamer.prototype._createXhrObject = function() {
this._xhr = new XMLHttpRequest();
this._xhr.onload = this._onLoad.bind(this);
this._xhr.onloadend = this._onLoadEnd.bind(this);
this._xhr.onreadystatechange = this._onXhrStateChanged.bind(this);
};
Streamer.prototype.poll = function(fileName) {
this._xhr.open('GET' ,this._getStreamUri(fileName) ,true);
this._xhr.send(null);
};
Streamer.prototype._onLoad = function() {
this._dataCallback && this._dataCallback(this._xhr.responseText);
};
Streamer.prototype._onLoadEnd = function() {
};
Streamer.prototype._onXhrStateChanged = function() {
if(this._xhr.readyState == 4) {
}
};
Streamer.prototype._getStreamUri = function(fileName) {
return window.socketConnectionString + 'io/' + this._serviceId + '/' + this._ioType + '/stream/' + (fileName ? '?fileName=' + fileName : '');
};
Streamer.prototype.getIOType = function() {
return this._ioType;
};
Streamer.prototype.getServiceId = function() {
return this._serviceId;
};
var _initialized = false,
_streamer = null;
function _initialize(serviceId, ioType, callback) {
if(!_initialized) {
_initialized = true;
_streamer = new Streamer(serviceId, ioType, callback);
}
}
function _poll(fileName) {
if(_initialized) {
_streamer.poll(fileName);
}
}
function _getSTDFilesList(callback) {
$.get(window.socketConnectionString + 'io/' + _streamer.getServiceId() + '/' + _streamer.getIOType() + '/list/', function(data) {
callback && callback(data);
});
}
return {
initialize: _initialize,
getSTDFilesList: _getSTDFilesList,
poll: _poll
}
})(); |
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 1){
$('.top-bar').addClass("navbar-fixed-top");
$('#navbar').addClass("navbar-fixed-top");
}
else{
$('.top-bar').removeClass("navbar-fixed-top");
$('#navbar').removeClass("navbar-fixed-top");
}
});
$(function() {
$(".dropdown").hover(
function(){ $(this).addClass('open') },
function(){ $(this).removeClass('open') }
);
});
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
},
// About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point.
|
'use strict';
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Foundation select by Samuel Moncarey
* Version 0.0.0
* Licensed under MIT Open Source
*/
!function ($) {
"use strict";
/**
* Stars module.
* @module foundation.stars
* @requires foundation.util.keyboard
*/
var Stars = function () {
function Stars(element, options) {
_classCallCheck(this, Stars);
this.$element = element;
this.options = $.extend({}, Stars.defaults, this.$element.data(), options);
this._init();
Foundation.registerPlugin(this, 'Stars');
Foundation.Keyboard.register('Stars', {
'ARROW_UP': 'rate_up',
'ARROW_DOWN': 'rate_down'
});
}
_createClass(Stars, [{
key: '_init',
value: function _init() {
this.rating = this.options.rating;
if (this.options.editable) {
this.rating = parseInt(this.$element.val());
this.$starsWrapper = $('<div class="stars">');
this.$element.after(this.$starsWrapper);
for (var i = 0; i < this.options.maxStars; i++) {
var $star = $('<a class="star" data-rate="' + (i + 1) + '"><i class="' + (this.rating < i + 1 ? this.options.emptyStar : this.options.filledStar) + '"></i></a>');
this.$starsWrapper.append($star);
}
this._events();
} else {
this.$element.addClass('stars');
for (var _i = 0; _i < this.options.maxStars; _i++) {
var _$star = $('<span class="star" data-rate="' + (_i + 1) + '"><i class="' + (this.rating < _i + 1 ? this.options.emptyStar : this.options.filledStar) + '"></i></span>');
this.$element.append(_$star);
}
}
}
/**
* Adds event listeners to the element utilizing the triggers utility library.
* @function
* @private
*/
}, {
key: '_events',
value: function _events() {
var _this = this;
this.$starsWrapper.find('.star').each(function (index, star) {
$(star).on('mouseover', function (e) {
_this.onHover(e, index);
}).on('mouseout', _this.onOut.bind(_this)).on('click', _this.onClick.bind(_this));
});
}
}, {
key: 'onHover',
value: function onHover(e, index) {
var _this = this,
$star = $(e.currentTarget);
this.$starsWrapper.find('.star').each(function (_index, _star) {
if (_index <= index) $(_star).find('i').removeClass(_this.options.emptyStar).addClass(_this.options.filledStar);else $(_star).find('i').removeClass(_this.options.filledStar).addClass(_this.options.emptyStar);
});
}
}, {
key: 'onOut',
value: function onOut() {
var _this2 = this;
var _this = this;
this.$starsWrapper.find('.star').each(function (_index, _star) {
if (_index >= _this2.options.rating) $(_star).find('i').removeClass(_this.options.filledStar).addClass(_this.options.emptyStar);else $(_star).find('i').removeClass(_this.options.emptyStar).addClass(_this.options.filledStar);
});
}
}, {
key: 'onClick',
value: function onClick(e) {
var $star = $(e.currentTarget),
rating = $star.data('rate');
this.$element.val(rating);
this.options.rating = rating;
}
/**
* Destroys the select.
* @function
*/
}, {
key: 'destroy',
value: function destroy() {
Foundation.unregisterPlugin(this);
}
}], [{
key: 'defaults',
get: function get() {
return {
maxStars: 5,
emptyStar: 'fa fa-star-o',
filledStar: 'fa fa-star',
editable: false,
rating: 0
};
}
}]);
return Stars;
}();
// Window exports
Foundation.plugin(Stars, 'Stars');
}(jQuery); |
/* globals db, load, makeMapWith, emit, renderDate */
load('./mongo-helpers/period-aggregator.mongo.js'); // exports makeMapWith()
// notice: MongoDB will not call the reduce function for a key that has only a single value
const map = makeMapWith(renderDate, function mapTemplate() {
// => emit same kind of output as reduce()'s
emit(renderDate(this._id.getTimestamp()), 1);
});
function reduce(day, count) {
// notice: MongoDB can invoke the reduce function more than once for the same key
var sum = (a, b) => a + b;
return count.reduce(sum);
}
var opts = {
out: { inline: 1 },
//limit: 1000
};
var res = db.post.mapReduce(map, reduce, opts);
//print(res.results.map(res => [ res._id, res.value ]).join('\n'));
print(
res.results
.sort((a, b) => new Date(a._id) - new Date(b._id))
.map((res) => [res._id, res.value])
.join('\n')
);
|
'use strict';
angular.module('proyectXApp')
.config(function ($stateProvider) {
$stateProvider
.state('main', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
});
}); |
/* global Vue*/
const projects =[{
name:"Random Quote machine",
description:"",
link:"https://fega.github.io/freecodecamp/random-quote",
img:"",
category:"freecodecamp",
technologies:["Materialize","Axios"],
},{
name:"Local weather app",
description:"",
link:"https://fega.github.io/freecodecamp/local-weather",
img:"",
category:"freecodecamp",
technologies:["Materialize","Axios"],
}, {
name:"GPS tracker webpage",
description:"A Front-End project developed with Gulp, Handlebars and Materialize for a Colombian GPS company, as a curiosity, my decisions in hosting and domain provider saves the company from a 1 week of problems in the service provided and also from a couple of lawsuits.",
link:"http://www.gpstrackerls.com/",
img:"img/gps-tracker.png",
category:"frontend",
technologies:["Materialize","Handlebars","Schema.org","Gulp"],
},{
name:"Espractica Landing page",
description:"A Front-End project developed with Gulp, Handlebars and Materialize to perform a market research in online education",
link:"http://espractica.github.io/",
img:"img/espractica.png",
category:"frontend",
technologies:["Materialize","Handlebars","Schema.org","Gulp"],
}, {
name:"Foundation Rock event showcase",
description:"A simple static HTML page, made with the Foundation framework",
link:"https://fega.github.io/frontend/foundation",
img:"img/rock.png",
category:"frontend",
technologies:["Foundation"],
},{
name:"Bootstrap Shop showcase",
description:"A simple static HTML page, made with the Bootstrap framework",
link:"https://fega.github.io/frontend/bootstrap",
img:"img/pebbleshop.png",
category:"frontend",
technologies:["Bootstrap"],
},{
name:"Arduair Project",
description:"My Environmental engineering undergraduate project, it combines my career with full-stack development and the development of a physic device (with Arduino)",
link:"http://arduair.herokuapp.com",
img:"img/arduair.png",
category:"fullstack",
labels:["Spa arquitecture"],
technologies:["Node.js","Jquery","Arduino","Moment.js","Lodash","MongoDb"]
},{
name:"Meloway webpage",
description:"A full-stack project developed with vue.js, Node.js and materialize for a Colombian based startup",
link:"http://www.meloway.com/",
img:"./img/meloway.png",
category:"fullstack",
labels:["Spa arquitecture","Rest API"],
technologies:["Materialize","Axios","Vue.js","Express.js","Babel.js","Gulp"],
},{
name:"Maravillarte eShop",
description:"A full-stack project developed with Jquery.js, Express.js and materialize for a Colombian based startup",
link:"http://www.maravillarte.co/",
img:"./img/maravillarte.png",
category:"fullstack",
labels:["Spa arquitecture","Rest API"],
technologies:["Materialize","Express.js","Babel.js","Gulp"],
},{
name:"Calculating pi!",
description:"A curious project that shows the basel method to get the Pi Number",
link:"/quantum-fracture ",
img:"./img/pi.png",
category:"frontend",
// labels:["Spa arquitecture","Rest API"],
technologies:["Materialize","Express.js","Babel.js","Gulp"],
},{
name:"express-ion",
description:"A mvc framework build on top of express and inspired by laravel. ",
link:"",
img:"",
category:"backend",
// labels:["Spa arquitecture","Rest API"],
technologies:["Express.js","Babel.js","Gulp"],
},]
const categories =[{
name:"Full-stack",
description:"My Full-stack projects made in Javascript, Django, On Rails, etc",
category:"fullstack"
},{
name:"Front-End",
description:"Some projects made in different frameworks or technologies, Vue, React, Materialize, Bootstrap, Foundation, etc",
category:"frontend",
},
// {
// name:"FreeCodeCamp",
// description:'A selection of some projects made for the freeCodeCamp web page. to see all projects, <a href="https://fega.github.io/freecodecamp/">click here to see al my freeCodeCamp projects</a>',
// category:"freecodecamp"
// },
// {
// name:"Back-end",
// description:'',
// category:"backend"
// },
]
const social=[
// {
// name:"Facebook",
// alt:"Fabian Gutierrez's Facebook Fan page",
// link:"#",
// icon:"img/icons/facebook.png",
// tooptip:"",
// color:"",
// },
{
name:"GitHub",
alt:"Fabian Gutierrez's GitHub Link",
link:"https://github.com/fega",
icon:"img/icons/github.png",
tooptip:"",
color:"",
}
// ,{
// name:"Medium",
// alt:"Fabian Gutierrez's Medium blog",
// link:"#",
// icon:"img/icons/medium.png",
// tooptip:"",
// color:"",
// }
// ,{
// name:"Youtube",
// alt:"Fabian Gutierrez's Youtube channel",
// link:"#",
// icon:"img/icons/youtube.png",
// tooptip:"",
// color:"",
// }
]
var skills = [{
name: "Linux management",
icon: "",
tooptip: "",
category: "",
level: 1,
main: false
}, {
name: "Amazon AWS management",
icon: "",
tooptip: "",
category: "",
level: 1,
main: false
},{
name: "Git workflow",
icon: "",
tooptip: "",
category: "",
level: 2,
main: false
},{
name: "Node.js",
icon: "",
tooptip: "",
category: "",
level: 4,
main: false
},{
name: "express.js",
icon: "",
tooptip: "",
category: "",
level: 4,
main: false
},{
name: "Vue.js",
icon: "",
tooptip: "",
category: "",
level: 4,
main: false
}]
Vue.component("sections-c",{
template:"#sections-t",
props:["categories","projects"],
methods:{
categoryFilter(array,category){
return array.filter((item)=>item.category===category)
}
}
})
Vue.component("nav-c",{
template:"#nav-t",
props:["categories","blog","burger"],
mounted(){
$(".button-collapse").sideNav()
$("#mobile-nav>li").sideNav('hide')
$('.dropdown-button').dropdown()
}
})
Vue.component("social-c",{
template:"#social-t",
props:["social"]
})
var vm = new Vue({
el: "main",
data:{
projects,
categories,
social,
}
})
|
/////////////INDEX PAGE///////////////
var API_URL = "http://www.omdbapi.com/?t=";
var movie;
var $divContain = $('.movie-container');
var $addButton = $('.add');
var $divTable = $('.movie-list');
//FIREBASE VARIABLES
var FIREBASE_AUTH = 'https://mymdb.firebaseio.com';
var fb = new Firebase(FIREBASE_AUTH);
var favMovies;
//////////LOGIN PAGE JAVASCRIPT//////////////////
//LOGOUT
$('.doLogout').click(function () {
fb.unauth();
$divTable.empty();
})
//LOGIN EVENT TRIGGER
$('.login form').submit(function () {
var email = $('.login input[type="email"]').val();
var password = $('.login input[type="password"]').val();
doLogin(email, password)
event.preventDefault();
});
//LOGIN ACTION AUTHORIZATION
function doLogin (email, password, cb) {
fb.authWithPassword({
email: email,
password: password
}, function (err, authData) {
if (err) {
alert(err.toString());
} else {
saveAuthData(authData);
typeof cb === 'function' && cb(authData); //read about this
}
});
}
//AUTHORIZATION DATA
function saveAuthData (authData) {
var info = fb.child('/users/' + authData.uid + '/profile');
info.set(authData);
}
//REGISTRATION PROCESS
$('.doRegister').click(function () {
var email = $('.login input[type="email"]').val();
var password = $('.login input[type="password"]').val();
fb.createUser({
email: email,
password: password
}, function (err, userData) {
if (err) {
alert(err.toString());
} else {
doLogin(email, password)
console.log("Successfully created user account with uid:", userData.uid);
}
});
event.preventDefault();
});
//CLEARING form
function clearLoginForm () {
$('.login input[type="email"]').val('');
$('.login input[type="password"]').val('');
}
//RESET Password
$('.doResetPassword').click(function () {
var email = $('.login input[type="email"]').val();
fb.resetPassword({
email: email
}, function(err){
if (err) {
alert(err.toString());
} else {
alert('Check your email!');
}
});
});
//CHANGE PASSWORD
$('.onTempPassword form').submit(function () {
var email = fb.getAuth().password.email;
var oldPw = $('.onTempPassword input:nth-child(1)').val();
var newPw = $('.onTempPassword input:nth-child(2)').val();
fb.changePassword({
email : email,
oldPassword : oldPw,
newPassword : newPw
}, function(err) {
if (err) {
alert(err.toString());
} else {
fb.unauth();
}
});
event.preventDefault();
})
//ONLOAD DATA WITH toggle of forms
//if authData is true, they are logged in.
fb.onAuth(function (authData) {
if (authData && authData.password.isTemporaryPassword && window.location.pathname !== '/reset/') {
window.location = '/reset';
} else if (authData && !authData.password.isTemporaryPassword && window.location.pathname === '/' ) {
favMovies = fb.child(`users/${fb.getAuth().uid}/movies`)
favMovies.on('child_added', function (snapshot){ //when movie is added, capture data
var obj = {}; //creating object
obj[snapshot.key()] = snapshot.val(); //storing snapshot.val as property
userMovies(obj); //passing that object to this function
})
} else if (!authData && window.location.pathname !== '/login/'){
window.location = '/login/';
$('.onLoggedIn').addClass('hidden');
}
clearLoginForm();
})
//Onload get function for MOVIE DATA
function userMovies(data) {
if (data) {
var id = Object.keys(data)[0]; //Grabbing the id but I think I already define this
saveMovieToDiv(data[id], id)
}
}
//MAIN PAGE
//SEARCH FOR MOVIES
$('.submit-form').submit(function (evt) {
evt.preventDefault();
movie = $(this).find('input[type!="submit"]').val();
var url = API_URL + movie.split(" ").join("+");
$.get(url, addMovieToDiv, 'jsonp');
$addButton.show();
$('.movie_result').addClass("result_styling");
});
//Adds first HTML fragment to div and empties it for next search
function addMovieToDiv(data) {
var current_movie = data;
$divContain.empty();
$divContain.append(createMovieNode(data));
}
//HTML fragment for first div
function createMovieNode(data) {
var movie_info = $('<div></div>');
movie_info.addClass("movie");
var poster = $("<img src='" + data.Poster + "'></img>");
poster.attr('class', 'col-md-6');
var title = $('<h3>' + data.Title + '</h3>');
var year = $('<h4>' + data.Year + '</h4>');
var genre = $('<p>' + data.Genre + '</p>');
var rating = $('<p>' + data.imdbRating + '</p>');
movie_info.append(poster, title, year, genre, rating);
return movie_info;
}
//Adding movies into firebase and table click function
$addButton.click(function() {
movie = $("input").val();
var url = API_URL + movie.split(" ").join("+");
$.get(url, function(data) {
favMovies.push(data, function(err){
console.log(err)
})
}, 'jsonp');
});
//appending data for second onclick
function saveMovieToDiv(data, id) {
$divTable.append(createMovieTable(data, id));
}
//html to insert for second button info
function createMovieTable(data, id) {
var tr = $('<tr></tr>')
tr.attr('data-id', id); //passing the name of the attibute and value. Need to make sure id is set from the GET from firebase.
tr.attr('class', 'movie_row');
var td = $("<td><img class='small_poster' src='" + data.Poster + "'></img></td>");
var td_1 = $('<td>' + data.Title + '</td>');
var td_2 = $('<td>' + data.Year + '</td>');
var td_3 = $('<td>' + data.Genre + '</td>');
var td_4 = $('<td>' + data.imdbRating + '</td>');
var td_5 = $('<input type="button" class="btn btn-danger del_btn" value="X">');
tr.append(td, td_1, td_2, td_3, td_4, td_5);
return tr;
}
//to delete rows
var $rows = $('.movie-list');
$rows.on('click', '.btn', function() {
var $movie_row = $(this).closest('.movie_row');
var id = $movie_row.attr('data-id');
favMovies.child(id).set(null); //removing url from firebase. could also .remove() instead of set?
$movie_row.remove(); //removing row from table
favMovies.on('child_removed', function() {
})
});
// var deleteUrl = FIREBASE_AUTH + '/users/' + fb.getAuth().uid + '/movies.json'.slice(0, -5) + '/' + id + '.json?auth=' + fb.getAuth().token;
// $.ajax({
// url: deleteUrl,
// type: 'DELETE',
// success: function() {
// $movie_row.remove();
// }
// })
|
export const messages = {
resources: {
posts: {
name: 'Article |||| Articles',
fields: {
allow_comments: 'Accepte les commentaires ?',
average_note: 'Note moyenne',
body: 'Contenu',
comments: 'Commentaires',
commentable: 'Commentable',
created_at: 'Créé le',
notifications: 'Destinataires de notifications',
nb_view: 'Nb de vues',
password: 'Mot de passe (si protégé)',
pictures: 'Photos associées',
published_at: 'Publié le',
teaser: 'Description',
tags: 'Catégories',
title: 'Titre',
views: 'Vues',
},
},
comments: {
name: 'Commentaire |||| Commentaires',
fields: {
body: 'Contenu',
created_at: 'Créé le',
post_id: 'Article',
author: {
name: 'Auteur',
},
},
},
},
post: {
list: {
search: 'Recherche',
},
form: {
summary: 'Résumé',
body: 'Contenu',
miscellaneous: 'Extra',
comments: 'Commentaires',
},
edit: {
title: 'Article "%{title}"',
},
},
comment: {
list: {
about: 'Au sujet de',
},
},
};
export default messages;
|
import React from 'react'
import { action as MetaAction, AppLoader } from 'mk-meta-engine'
import config from './config'
import { Tree } from 'mk-component'
import utils from 'mk-utils'
import beautify from 'mk-utils/lib/beautify'
import { fromJS } from 'immutable'
let apisJson
let apis
class action {
constructor(option) {
this.metaAction = option.metaAction
this.config = config.current
}
onInit = ({ component, injections }) => {
this.component = component
this.injections = injections
if (!apisJson) {
apisJson = [...this.config.apis]
Object.keys(utils.fetch.mockApi).forEach(k => {
if (apisJson.findIndex(o => o.url == k) == -1) {
apisJson.push({
url: k,
group: '未写注释'
})
}
})
apisJson = apisJson.sort((a, b) => a.url > b.url ? 1 : -1)
apisJson = apisJson.filter((o, index, self) => self.findIndex(x => x.url == o.url) == index)
apis = fromJS(apisJson)
}
injections.reduce('init', apisJson)
const filter = this.metaAction.gf('data.filter').toJS()
this.load(filter)
}
load = (filter) => {
var lst = apis.filter(o => {
return o.get('group').indexOf(filter.group) != -1
&& (
!filter.search
|| (o.get('title') && o.get('title').indexOf(filter.search) != -1)
|| (o.get('url') && o.get('url').indexOf(filter.search) != -1)
)
})
this.metaAction.sfs({
"data.apis": lst,
"data.filter": fromJS(filter)
})
}
loopTreeChildren = (groups) => {
if (!groups || groups.length == 0) return null
return groups.map((item) => {
if (item.children && item.children.length) {
return <Tree.TreeNode key={item.group} title={item.group}>{this.loopTreeChildren(item.children)}</Tree.TreeNode>
}
return <Tree.TreeNode key={item.group} title={item.group} />
})
}
selectGroup = (selectedKeys) => {
const filter = this.metaAction.gf('data.filter').toJS()
var selectedGroup = ''
if (!selectedKeys || selectedKeys.length == 0)
selectedGroup = ''
else
selectedGroup = selectedKeys[0]
if (filter.gourp == selectedGroup)
return
filter.group = selectedGroup
this.load(filter)
}
searchChange = (e) => {
const filter = this.metaAction.gf('data.filter').toJS()
const search = e.target.value
if (search == filter.search)
return
filter.search = search
this.load(filter)
}
rowClick = (e, rowIndex) => {
const api = this.metaAction.gf('data.apis.' + rowIndex)
const currentApi = this.metaAction.gf('data.currentApi')
if (currentApi && currentApi.get('url') == api.get('url'))
return
const apiJSON = api.toJS()
const apiParamExample = apiJSON.parameter && apiJSON.parameter.examples && apiJSON.parameter.examples[0]
this.metaAction.sfs({
'data.currentApi': api,
'data.currentTabKey': 'base',
'data.runParams': apiParamExample && apiParamExample.content,
'data.runUrl': apiJSON.url,
'data.runResult': undefined
})
}
tabChange = (key) => {
this.metaAction.sf('data.currentTabKey', key)
}
getCellClassName = (rowIndex) => {
if (this.metaAction.gf('data.currentApi.url') == this.metaAction.gf(`data.apis.${rowIndex}.url`))
return 'mk-app-apidoc-content-grid-content-cell mk-app-apidoc-content-grid-content-selectrow'
else
return 'mk-app-apidoc-content-grid-content-cell'
}
runParamsChange = (e, d, v) => {
this.metaAction.sf('data.runParams', v)
}
run = async () => {
var runParams = this.metaAction.gf('data.runParams')
var runUrl = this.metaAction.gf('data.runUrl')
try {
runParams = utils.string.toJson(runParams)
const response = await utils.fetch.post(runUrl, runParams, undefined, { ignoreAOP: true })
this.metaAction.sf('data.runResult', beautify.beautifyJS(JSON.stringify(response)))
} catch (e) {
this.metaAction.sf('data.runResult', e.stack)
}
}
}
export default function creator(option) {
const metaAction = new MetaAction(option),
o = new action({ ...option, metaAction }),
ret = { ...metaAction, ...o }
metaAction.config({ metaHandlers: ret })
return ret
} |
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@material-ui/core/Divider';
import InboxIcon from '@material-ui/icons/Inbox';
import DraftsIcon from '@material-ui/icons/Drafts';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
}));
export default function SelectedListItem() {
const classes = useStyles();
const [selectedIndex, setSelectedIndex] = React.useState(1);
const handleListItemClick = (event, index) => {
setSelectedIndex(index);
};
return (
<div className={classes.root}>
<List component="nav" aria-label="main mailbox folders">
<ListItem
button
selected={selectedIndex === 0}
onClick={(event) => handleListItemClick(event, 0)}
>
<ListItemIcon>
<InboxIcon />
</ListItemIcon>
<ListItemText primary="Inbox" />
</ListItem>
<ListItem
button
selected={selectedIndex === 1}
onClick={(event) => handleListItemClick(event, 1)}
>
<ListItemIcon>
<DraftsIcon />
</ListItemIcon>
<ListItemText primary="Drafts" />
</ListItem>
</List>
<Divider />
<List component="nav" aria-label="secondary mailbox folder">
<ListItem
button
selected={selectedIndex === 2}
onClick={(event) => handleListItemClick(event, 2)}
>
<ListItemText primary="Trash" />
</ListItem>
<ListItem
button
selected={selectedIndex === 3}
onClick={(event) => handleListItemClick(event, 3)}
>
<ListItemText primary="Spam" />
</ListItem>
</List>
</div>
);
}
|
elation.require([
"engine.things.generic"
], function() {
elation.extend("engine.systems.world", function(args) {
elation.implement(this, elation.engine.systems.system);
this.children = {};
this.scene = {
'world-3d': new THREE.Scene(),
'world-dom': new THREE.Scene(),
'colliders': new THREE.Scene(),
'sky': false
};
this.persistdelay = 1000;
this.lastpersist = 0;
//this.scene['world-3d'].fog = new THREE.FogExp2(0x000000, 0.0000008);
//this.scene['world-3d'].fog = new THREE.FogExp2(0xffffff, 0.01);
this.system_attach = function(ev) {
console.log('INIT: world');
this.rootname = (args ? args.parentname + '/' + args.name : '/');
this.loaded = false;
this.loading = false;
if (ENV_IS_BROWSER && document.location.hash) {
this.parseDocumentHash();
elation.events.add(window, 'popstate', elation.bind(this, this.parseDocumentHash));
}
elation.events.add(this, 'world_thing_add', this);
}
this.engine_start = function(ev) {
// If no local world override, load from args
if (!this.loaded && !this.loading) {
if (!elation.utils.isEmpty(args)) {
this.load(args);
} else {
//this.createDefaultScene();
}
}
}
this.engine_frame = function(ev) {
//console.log('FRAME: world', ev);
}
this.engine_stop = function(ev) {
console.log('SHUTDOWN: world');
}
this.add = function(thing) {
if (!this.children[thing.name]) {
this.children[thing.name] = thing;
thing.parent = this;
if (thing.objects['3d']) {
this.scene['world-3d'].add(thing.objects['3d']);
}
if (thing.objects['dynamics']) {
this.engine.systems.physics.add(thing.objects['dynamics']);
}
if (thing.container) {
//this.renderer['world-dom'].domElement.appendChild(thing.container);
}
if (thing.colliders) {
this.scene['colliders'].add(thing.colliders);
}
this.attachEvents(thing);
elation.events.fire({type: 'world_thing_add', element: this, data: {thing: thing}});
return true;
}
return false;
}
this.attachEvents = function(thing) {
elation.events.add(thing, 'thing_add,thing_remove,thing_change', this);
if (thing.children) {
for (var k in thing.children) {
this.attachEvents(thing.children[k]);
}
}
}
this.thing_add = function(ev) {
elation.events.fire({type: 'world_thing_add', element: this, data: ev.data});
this.attachEvents(ev.data.thing);
if (this.hasLights(ev.data.thing)) {
this.refreshLights();
}
}
this.thing_remove = function(ev) {
elation.events.fire({type: 'world_thing_remove', element: this, data: ev.data});
elation.events.remove(ev.data.thing, 'thing_add,thing_remove,thing_change', this);
}
this.thing_change = function(ev) {
elation.events.fire({type: 'world_thing_change', element: this, data: ev.data});
}
this.world_thing_add = function(ev) {
//elation.events.add(ev.data.thing, 'thing_add,thing_remove,thing_change', this);
this.attachEvents(ev.data.thing);
if (ev.data.thing && ev.data.thing.objects['3d']) {
if (this.hasLights(ev.data.thing)) {
this.refreshLights();
}
}
}
this.remove = function(thing) {
if (this.children[thing.name]) {
if (thing.objects['3d']) {
this.scene['world-3d'].remove(thing.objects['3d']);
}
if (thing.container) {
//this.renderer['world-dom'].domElement.removeChild(thing.container);
}
if (thing.colliders) {
this.scene['colliders'].remove(thing.colliders);
}
delete this.children[thing.name];
elation.events.fire({type: 'world_thing_remove', element: this, data: {thing: thing}});
}
}
this.extract_types = function(things, types, onlymissing) {
if (!types) {
types = [];
}
if (!elation.utils.isArray(things)) {
things = [things];
}
for (var i = 0; i < things.length; i++) {
var thing = things[i];
if (((onlymissing && typeof elation.engine.things[thing.type] == 'undefined') || !onlymissing) && types.indexOf(thing.type) == -1) {
types.push(thing.type);
elation.engine.things[thing.type] = null;
}
if (thing.things) {
for (var k in thing.things) {
this.extract_types(thing.things[k], types, onlymissing);
}
}
}
return types;
}
this.reset = function() {
// Kill all objects except ones which are set to persist
for (var k in this.children) {
if (!this.children[k].properties.persist) {
this.children[k].die();
}
}
while (this.scene['world-3d'].children.length > 0) {
this.scene['world-3d'].remove(this.scene['world-3d'].children[0]);
}
while (this.scene['colliders'].children.length > 0) {
this.scene['colliders'].remove(this.scene['colliders'].children[0]);
}
// Initialize collider scene with some basic lighting for debug purposes
this.scene['colliders'].add(new THREE.AmbientLight(0xcccccc));
var colliderlight = new THREE.DirectionalLight();
colliderlight.position.set(10, 17.5, 19);
this.scene['colliders'].add(colliderlight);
}
this.createNew = function() {
this.reset();
this.spawn("sector", "default");
}
this.saveLocal = function(name) {
if (!name) name = this.rootname;
console.log('Saved local world: ' + name);
var key = 'elation.engine.world.override:' + name;
localStorage[key] = JSON.stringify(this.serialize());
}
this.loadLocal = function(name) {
console.log('Load local world: ' + name);
this.rootname = name;
this.reset();
var key = 'elation.engine.world.override:' + name;
if (localStorage[key]) {
var world = JSON.parse(localStorage[key]);
this.load(world);
} else {
this.createDefaultScene();
}
if (ENV_IS_BROWSER) {
var hashargs = elation.url();
hashargs['world.load'] = name;
if (this.engine.systems.physics.timescale == 0) {
hashargs['world.paused'] = 1;
}
document.location.hash = elation.utils.encodeURLParams(hashargs);
}
}
this.listLocalOverrides = function() {
var overrides = [];
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.match(/elation\.engine\.world\.override:/)) {
var name = key.substr(key.indexOf(':')+1);
overrides.push(name);
}
}
return overrides;
}
this.load = function(things, root, logprefix) {
if (!things) return;
if (!elation.utils.isArray(things)) {
things = [things];
}
this.loading = true;
if (!this.root) {
this.currentlyloaded = thing;
var loadtypes = this.extract_types(things, [], true);
if (loadtypes.length > 0) {
elation.require(loadtypes.map(function(a) { return 'engine.things.' + a; }), elation.bind(this, function() { this.load(things, root, logprefix); }));
return;
}
}
if (!logprefix) logprefix = "";
if (typeof root == 'undefined') {
//this.rootname = (thing.parentname ? thing.parentname : '') + '/' + thing.name;
root = this;
}
for (var i = 0; i < things.length; i++) {
var thing = things[i];
var currentobj = this.spawn(thing.type, thing.name, thing.properties, root, false);
if (thing.things) {
for (var k in thing.things) {
this.load(thing.things[k], currentobj, logprefix + "\t");
}
}
}
if (root === this) {
this.loaded = true;
this.loading = false;
this.dirty = true;
elation.events.fire({type: 'engine_world_init', element: this});
}
return root;
}
this.reload = function() {
if (this.rootname) {
this.loadLocal(this.rootname);
}
}
this.refresh = function() {
elation.events.fire({type: 'world_change', element: this});
}
this.hasLights = function(thing) {
var object = thing.objects['3d'];
var hasLight = object instanceof THREE.Light;
if (!hasLight && object.children.length > 0) {
object.traverse(function(n) { if (n instanceof THREE.Light) { hasLight = true; } });
}
return hasLight;
}
this.refreshLights = function() {
this.scene['world-3d'].traverse(function(n) { if (n instanceof THREE.Mesh) { n.material.needsUpdate = true; } });
}
this.createDefaultScene = function() {
var scenedef = {
type: 'sector',
name: 'default',
properties: {
persist: true
},
things: {
ground: {
type: 'terrain',
name: 'ground',
properties: {
'textures.map': '/media/space/textures/dirt.jpg',
'textures.normalMap': '/media/space/textures/dirt-normal.jpg',
'textures.mapRepeat': [ 100, 100 ],
'persist': true,
'position': [0,0,100]
}
},
sun: {
type: 'light',
name: 'sun',
properties: {
type: 'directional',
position: [ -20, 50, 25 ],
persist: true
}
}
}
};
this.load(scenedef);
}
this.loadSceneFromURL = function(url, callback) {
//this.reset();
elation.net.get(url, null, { onload: elation.bind(this, this.handleSceneLoad, callback) });
if (ENV_IS_BROWSER) {
var dochash = "world.url=" + url;
if (this.engine.systems.physics.timescale == 0) {
dochash += "&world.paused=1";
}
document.location.hash = dochash;
}
}
this.handleSceneLoad = function(callback, ev) {
var response = ev.target.response;
var data = JSON.parse(response);
if (elation.utils.isArray(data)) {
for (var i = 0; i < data.length; i++) {
this.load(data[i]);
}
} else {
this.load(data);
}
if (callback) { setTimeout(callback, 0); }
}
this.spawn = function(type, name, spawnargs, parent, autoload) {
if (elation.utils.isNull(name)) name = type + Math.floor(Math.random() * 1000);
if (!spawnargs) spawnargs = {};
if (!parent) parent = this.children['default'] || this;
if (typeof autoload == 'undefined') autoload = true;
var logprefix = "";
var currentobj = false;
var realtype = type;
var initialized = false;
try {
if (typeof elation.engine.things[type] != 'function') {
if (autoload) {
// Asynchronously load the new object type's definition, and create the real object when we're done
elation.require('engine.things.' + realtype, elation.bind(this, function() {
if (currentobj) {
currentobj.die();
}
this.spawn(realtype, name, spawnargs, parent, false);
}));
}
// FIXME - we should be able to return a generic, load the new object asynchronously, and then morph the generic into the specified type
// Right now this might end up with weird double-object behavior...
type = 'generic';
} else {
currentobj = elation.engine.things[type].obj[name];
if (currentobj) {
for (var k in spawnargs) {
currentobj.setProperties(spawnargs);
}
} else {
currentobj = elation.engine.things[type]({type: realtype, container: elation.html.create(), name: name, engine: this.engine, client: this.client, properties: spawnargs});
}
parent.add(currentobj);
//currentobj.reparent(parent);
//console.log(logprefix + "\t- added new " + type + ": " + name, currentobj);
}
} catch (e) {
console.error(e.stack);
}
return currentobj;
}
this.serialize = function(serializeAll) {
var ret = {};
/*
for (var k in this.children) {
if (!this.serializeAll && this.children[k].properties.persist) {
ret[k] = this.children[k].serialize(serializeAll);
return ret[k]; // FIXME - dumb
}
else if (this.serializeAll) {
ret[k] = this.children[k].serialize(serializeAll);
return ret[k];
}
}
return null;
*/
for (var k in this.children)
{
if (serializeAll || this.children[k].properties.persist)
{
ret[k] = this.children[k].serialize(serializeAll);
return ret[k]; // FIXME - dumb
}
}
return ret;
}
this.setSky = function(texture, format, prefixes) {
if (texture !== false) {
if (!(texture instanceof THREE.Texture)) {
format = format || 'jpg';
prefixes = prefixes || ['p', 'n'];
if (texture.substr(texture.length-1) != '/') {
texture += '/';
}
var urls = [
texture + prefixes[0] + 'x' + '.' + format, texture + prefixes[1] + 'x' + '.' + format,
texture + prefixes[0] + 'y' + '.' + format, texture + prefixes[1] + 'y' + '.' + format,
texture + prefixes[0] + 'z' + '.' + format, texture + prefixes[1] + 'z' + '.' + format
];
var texturecube = THREE.ImageUtils.loadTextureCube( urls, undefined, elation.bind(this, this.refresh) );
texturecube.format = THREE.RGBFormat;
this.skytexture = texturecube;
} else {
this.skytexture = texture;
}
if (!this.scene['sky']) {
this.scene['sky'] = (this.engine.systems.render && this.engine.systems.render.views[0] ? this.engine.systems.render.views[0].skyscene : new THREE.Scene());
var skygeom = new THREE.BoxGeometry(1,1,1, 10, 10, 10);
var skymat = new THREE.MeshBasicMaterial({color: 0xff0000, side: THREE.DoubleSide, wireframe: true, depthWrite: false});
this.skyshader = THREE.ShaderLib[ "cube" ];
var skymat = new THREE.ShaderMaterial( {
fragmentShader: this.skyshader.fragmentShader,
vertexShader: this.skyshader.vertexShader,
uniforms: this.skyshader.uniforms,
depthWrite: false,
side: THREE.DoubleSide
} );
this.skymesh = new THREE.Mesh(skygeom, skymat);
this.scene['sky'].add(this.skymesh);
//console.log('create sky mesh', this.scene['sky'], this.engine.systems.render.views['main']);
if (this.engine.systems.render && this.engine.systems.render.views['main']) {
this.engine.systems.render.views['main'].setskyscene(this.scene['sky']);
}
}
this.skyshader.uniforms[ "tCube" ].value = this.skytexture;
this.skyenabled = true;
} else {
this.skyenabled = false;
}
if (this.skyenabled) {
}
}
this.setClearColor = function(color, opacity) {
this.engine.systems['render'].setclearcolor(color, opacity);
}
this.setFog = function(near, far, color) {
if (typeof color == 'undefined') color = 0xffffff;
this.scene['world-3d'].fog = new THREE.Fog(color, near, far);
}
this.setFogExp = function(exp, color) {
if (!color) color = 0xffffff;
this.scene['world-3d'].fog = new THREE.FogExp2(color, exp);
}
this.disableFog = function() {
this.scene['world-3d'].fog = false;
}
this.parseDocumentHash = function() {
var parsedurl = elation.utils.parseURL(document.location.hash);
if (parsedurl.hashargs) {
if (+parsedurl.hashargs['world.paused']) {
this.engine.systems.physics.timescale = 0;
}
if (parsedurl.hashargs['world.load'] && parsedurl.hashargs['world.load'] != this.rootname) {
this.loadLocal(parsedurl.hashargs['world.load']);
}
if (parsedurl.hashargs['world.url']) {
elation.net.get(parsedurl.hashargs['world.url'], null, {
callback: function(response) {
try {
var data = JSON.parse(response);
this.load(data);
} catch (e) {
console.log('Error loading world:', response, e);
}
}.bind(this)
});
}
}
}
// Convenience functions for querying objects from world
this.getThingsByTag = function(tag) {
var things = [];
var childnames = Object.keys(this.children);
for (var i = 0; i < childnames.length; i++) {
var childname = childnames[i];
if (this.children[childname].hasTag(tag)) {
things.push(this.children[childname]);
}
this.children[childname].getChildrenByTag(tag, things);
}
return things;
}
this.getThingsByPlayer = function(player) {
var things = [];
for (var k in this.children) {
if (this.children[k].getPlayer() == player) {
things.push(this.children[k]);
}
this.children[k].getChildrenByPlayer(player, things);
}
return things;
}
this.getThingsByType = function(type) {
var things = [];
var childnames = Object.keys(this.children);
for (var i = 0; i < childnames.length; i++) {
var childname = childnames[i];
if (this.children[childname].type == type) {
things.push(this.children[childname]);
}
this.children[childname].getChildrenByType(type, things);
}
return things;
}
this.getThingByObject = function(obj) {
}
this.getThingById = function(id) {
}
this.worldToLocal = function(pos) {
return pos;
}
this.localToWorld = function(pos) {
return pos;
}
this.worldToLocalOrientation = function(orient) {
return orient;
}
this.localToWorldOrientation = function(orient) {
return orient;
}
});
});
|
var TouchHistoryMath = {
/**
* This code is optimized and not intended to look beautiful. This allows
* computing of touch centroids that have moved after `touchesChangedAfter`
* timeStamp. You can compute the current centroid involving all touches
* moves after `touchesChangedAfter`, or you can compute the previous
* centroid of all touches that were moved after `touchesChangedAfter`.
*
* @param {TouchHistoryMath} touchHistory Standard Responder touch track
* data.
* @param {number} touchesChangedAfter timeStamp after which moved touches
* are considered "actively moving" - not just "active".
* @param {boolean} isXAxis Consider `x` dimension vs. `y` dimension.
* @param {boolean} ofCurrent Compute current centroid for actively moving
* touches vs. previous centroid of now actively moving touches.
* @return {number} value of centroid in specified dimension.
*/
centroidDimension: function(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) {
var touchBank = touchHistory.touchBank;
var total = 0;
var count = 0;
var oneTouchData = touchHistory.numberActiveTouches === 1 ?
touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null;
if (oneTouchData !== null) {
if (oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter) {
total += ofCurrent && isXAxis ? oneTouchData.currentPageX :
ofCurrent && !isXAxis ? oneTouchData.currentPageY :
!ofCurrent && isXAxis ? oneTouchData.previousPageX :
oneTouchData.previousPageY;
count = 1;
}
} else {
for (var i = 0; i < touchBank.length; i++) {
var touchTrack = touchBank[i];
if (touchTrack !== null &&
touchTrack !== undefined &&
touchTrack.touchActive &&
touchTrack.currentTimeStamp >= touchesChangedAfter) {
var toAdd; // Yuck, program temporarily in invalid state.
if (ofCurrent && isXAxis) {
toAdd = touchTrack.currentPageX;
} else if (ofCurrent && !isXAxis) {
toAdd = touchTrack.currentPageY;
} else if (!ofCurrent && isXAxis) {
toAdd = touchTrack.previousPageX;
} else {
toAdd = touchTrack.previousPageY;
}
total += toAdd;
count++;
}
}
}
return count > 0 ? total / count : TouchHistoryMath.noCentroid;
},
currentCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(
touchHistory,
touchesChangedAfter,
true, // isXAxis
true // ofCurrent
);
},
currentCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(
touchHistory,
touchesChangedAfter,
false, // isXAxis
true // ofCurrent
);
},
previousCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(
touchHistory,
touchesChangedAfter,
true, // isXAxis
false // ofCurrent
);
},
previousCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(
touchHistory,
touchesChangedAfter,
false, // isXAxis
false // ofCurrent
);
},
currentCentroidX: function(touchHistory) {
return TouchHistoryMath.centroidDimension(
touchHistory,
0, // touchesChangedAfter
true, // isXAxis
true // ofCurrent
);
},
currentCentroidY: function(touchHistory) {
return TouchHistoryMath.centroidDimension(
touchHistory,
0, // touchesChangedAfter
false, // isXAxis
true // ofCurrent
);
},
noCentroid: -1,
};
module.exports = TouchHistoryMath;
|
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
markdown: {
article: {
files: [
{
expand: true,
src: [
'guide/**/*.md',
'account/**/*.md',
'todo/**/*.md'
],
dest: './',
ext: '.html'
}
],
options: {
template: '_template.html',
markdownOptions: {
sanitize: false,
highlight: 'manual'
}
}
}
},
esteWatch: {
options: {
dirs: [
'./',
'assets/**/',
'guide/**/',
'account/**/',
'todo/**/',
'!components/**/',
'!node_modules/**/',
],
ignoredFiles: [
'README.md'
],
livereload: {
enabled: true,
port: 35729,
extensions: ['js', 'css', 'html']
}
},
md: function (filepath) {
var files = [{
expand: true,
src: filepath,
ext: '.html'
}];
grunt.config.set('markdown.article.files', files);
return 'markdown:article';
}
},
connect: {
app: {
options: {
port: 9000,
livereload: true,
open: 'http://localhost:9000/'
}
}
}
});
grunt.loadNpmTasks('grunt-markdown');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-este-watch');
grunt.registerTask('default', ['connect', 'esteWatch']);
};
|
var xlsx = require('xlsx');
var fs = require('fs');
var Excel = require('exceljs');
var workbook1 = new Excel.Workbook();
if (typeof require !== 'undefined') XLSX = require('xlsx');
var workbook = XLSX.readFile('boxxspring.xlsx',{ cellStyles: true });
var countBeforeAdd;
var worksheet = workbook.Sheets['videoupload'];
var videoUrl = [];
var videoTitle = [];
var shortTitle = [];
var shortDesc = [];
var author = [];
var attribution = [];
var categoryName = [];
var categoryType = [];
var shortNote = [];
var dragImg = [];
var result = [];
module.exports = {
before: function(browser) {
var profile = browser.globals.profile;
browser.resizeWindow(1585, 2187);
//browser.windowMaximize();
browser.
login(profile.portalUri, profile.username, profile.password);
},
'Uploading a Video URL': function(client) {
//Read values from excel
for (z in worksheet) {
if (z[0] === '!') continue;
//Read video URL
if (z.includes('A')) {
videoUrl.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Video Title
if (z.includes('B')) {
videoTitle.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Short Title
if (z.includes('C')) {
shortTitle.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Short Description
if (z.includes('D')) {
shortDesc.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Author Name
if (z.includes('E')) {
author.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Attribution Name
if (z.includes('F')) {
attribution.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Category Name
if (z.includes('G')) {
categoryName.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Category Type
if (z.includes('H')) {
categoryType.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Short Notes
if (z.includes('I')) {
shortNote.push(worksheet[z].v);
console.log(worksheet[z].v);
}
//Read Replace Thumbnail
if (z.includes('J')) {
dragImg.push(worksheet[z].v);
console.log(worksheet[z].v);
}
}
if (videoUrl.length > 0) {
console.log("length",+videoUrl.length);
//console.log("video",+videoUrl);
//for ( var i in videoUrl ) {
//for (var i = 0; i < videoUrl.length; i++) {
//Search for videos link
//console.log("First", i);
client.pause(9000).
waitForElementVisible("span.ng-isolate-scope:nth-child(4) > span:nth-child(1) > ng-transclude:nth-child(1) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(1) > a:nth-child(1)", 5000).
//"li.active > a:first-child"
verify.containsText("span.ng-isolate-scope:nth-child(4) > span:nth-child(1) > ng-transclude:nth-child(1) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(1) > a:nth-child(1)", "Videos").
click("span.ng-isolate-scope:nth-child(4) > span:nth-child(1) > ng-transclude:nth-child(1) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(1) > a:nth-child(1)").
pause(10000)
client.getText('.content-count > strong', function(result) {
if (result.status !== -1) {
countBeforeAdd = result.value;
countBeforeAdd = countBeforeAdd.substring(1, countBeforeAdd.length - 1);
console.log('Count - Before adding video: ' + countBeforeAdd)
}
client.waitForElementVisible(".btn.btn-primary.btn-add", 9000).
verify.visible(".btn.btn-primary.btn-add").
pause(5000).
//moveToElement(".btn.btn-primary.btn-add",0,0).
click(".btn.btn-primary.btn-add").
pause(9000)
for (var i = 0; i < videoUrl.length; i++) {
client.
waitForElementVisible("#video_url", 9000,false).
pause(9000).
verify.visible("#video_url")
//geturl = 'https://vimeo.com/29247071';
// geturl = videoUrl [ i ];
//var geturl ='https://facebook.com/';
client.
pause(5000).
setValue("#video_url", videoUrl[i])
//Check the valid URL from given URL
//client.url(function ( test ) {
console.log("Given URL:", videoUrl[i]);
console.log("Given URL:", i.length + " = " + videoUrl[i]);
console.log("Given URL:", i + " = " + videoUrl.length);
if (videoUrl[i].match(/www.dailymotion.com/g))
// if ( videoUrl [ i ].match ( /www.youtube.com/g ))
{
client.pause(5000).
waitForElementVisible('.video-preview', 15000).
//Check Video Preview and Title
verify.visible(".video-preview").
verify.visible(".video-title").
//Check - Continue Button
verify.visible(".edit-form > div > .btn-primary")
console.log("Dailymotion url is passed");
client.videoproperties(videoTitle[i], shortTitle[i], shortDesc[i], author[i], attribution[i], categoryName[i], shortNote[i], dragImg[i], countBeforeAdd);
//client.properties( profile1.videoTitle[i]);
if(i<videoUrl.length-1) {
this.getText('.content-count > strong', function(result) {
if (result.status !== -1) {
countBeforeAdd = result.value;
countBeforeAdd = countBeforeAdd.substring(1, countBeforeAdd.length - 1);
console.log('Count - Before adding video: ' + countBeforeAdd)
}
this.pause ( 10000).
waitForElementVisible(".btn.btn-primary.btn-add", 9000).
verify.visible(".btn.btn-primary.btn-add").
//moveToElement(".btn.btn-primary.btn-add",0,0).
click(".btn.btn-primary.btn-add")
//Get no of Videos
});
}
}
else if (videoUrl[i].match(/www.youtube.com/g)) {
client.pause(5000).
waitForElementVisible('.video-preview', 15000,false).
//Check Video Preview and Title
verify.visible(".video-preview").
pause(5000).
verify.visible(".video-title").
//Check - Continue Button
verify.visible(".edit-form > div > .btn-primary")
console.log("Youtube url is passed");
client.videoproperties(videoTitle[i], shortTitle[i], shortDesc[i], author[i], attribution[i], categoryName[i], shortNote[i], dragImg[i], countBeforeAdd);
if(i<videoUrl.length-1) {
this.getText('.content-count > strong', function(result) {
if (result.status !== -1) {
countBeforeAdd = result.value;
countBeforeAdd = countBeforeAdd.substring(1, countBeforeAdd.length - 1);
console.log('Count - Before adding video: ' + countBeforeAdd)
}
this.pause ( 10000).
waitForElementVisible(".btn.btn-primary.btn-add", 9000).
pause(5000).
verify.visible(".btn.btn-primary.btn-add").
//moveToElement(".btn.btn-primary.btn-add",0,0).
click(".btn.btn-primary.btn-add")
//Get no of Videos
});
}
}
else if (videoUrl[i].match(/vimeo.com/g)) {
client.pause(15000).
waitForElementVisible('.video-preview', 15000,false).
pause(15000).
//Check Video Preview and Title
verify.visible(".video-preview").
pause(15000).
verify.visible(".video-title").
//Check - Continue Button
verify.visible(".edit-form > div > .btn-primary")
console.log("Vimeo url is passed");
console.log("Beforefor loop:" +i);
client.videoproperties(videoTitle[i], shortTitle[i], shortDesc[i], author[i], attribution[i], categoryName[i], shortNote[i], dragImg[i], countBeforeAdd);
if(i<videoUrl.length-1) {
this.getText('.content-count > strong', function(result) {
if (result.status !== -1) {
countBeforeAdd = result.value;
countBeforeAdd = countBeforeAdd.substring(1, countBeforeAdd.length - 1);
console.log('Count - Before adding video: ' + countBeforeAdd)
}
this.pause ( 10000).
waitForElementVisible(".btn.btn-primary.btn-add", 9000).
verify.visible(".btn.btn-primary.btn-add").
//moveToElement(".btn.btn-primary.btn-add",0,0).
click(".btn.btn-primary.btn-add")
//Get no of Videos
});
}
}
else {
console.log("Invalid url :Failed");
client.
pause(5000).
waitForElementVisible('.field-error > span:nth-child(1) > span:nth-child(2) > span:nth-child(1)', 15000, false).
getText('.field-error > span:nth-child(1) > span:nth-child(2) > span:nth-child(1)', function(urlErrorMsg) {
if (urlErrorMsg.status !== -1) {
var errmsg = urlErrorMsg.value;
console.log("Invalid message" + errmsg)
var expectedmsg = "Please enter a valid URL.";
if (expectedmsg == errmsg) {
workbook1.xlsx.readFile('boxxspring.xlsx', { cellStyles: true })
.then(function() {
var worksheet1 = workbook1.getWorksheet( 'videoupload' );
var row = worksheet1.getRow(2);
row.getCell(11).font = { bold: true, color:{ argb: 'FFFF0000' } };
row.alignment= { wrapText: true }
row.getCell(11).value = 'FAIL';
row.getCell(12).font = { color:{ argb: 'FFFF0000'} };
row.alignment= { wrapText: true }
row.getCell(12).value = "ActualResult: '" + countAfterAdd + "' in the Total Videos Count After Added New story. ExpectedResult: should be'" + countBeforeAdd1 + "' in the Total Videos Count ";
result.push ( 'FAIL' );
row.hidden = false;
worksheet1.getColumn(j).hidden = false;
workbook1.xlsx.writeFile( 'boxxspring.xlsx' );
row.commit();
console.log("if error passed");
});
}
else {
console.log("not found in the page")
workbook1.xlsx.readFile('boxxspring.xlsx', { cellStyles: true })
.then(function() {
var worksheet1 = workbook1.getWorksheet('videoupload');
var row = worksheet1.getRow(++j);
row.getCell(11).font = { bold: true, color: { argb: 'FFFF0000' }
};
row.alignment = { wrapText: true }
row.getCell(11).value = 'FAIL';
row.getCell(12).font = { color: { argb: 'FFFF0000' }
};
row.alignment = { wrapText: true }
row.getCell(12).value = "ActualResult: '" + countAfterAdd + "' in the Videos Total Count After Added New. ExpectedResult: should be'" + countBeforeAdd1 + "' in the Video Total Count ";
result.push('FAIL');
row.hidden = false;
worksheet1.getColumn(j).hidden = false;
workbook1.xlsx.writeFile('boxxspring.xlsx');
row.commit();
});
}
}
});
client.pause(5000).
waitForElementVisible ( "span.ng-isolate-scope:nth-child(4) > span:nth-child(1) > ng-transclude:nth-child(1) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(1) > a:nth-child(1)", 5000 ).
verify.containsText ( "span.ng-isolate-scope:nth-child(4) > span:nth-child(1) > ng-transclude:nth-child(1) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(1) > a:nth-child(1)", "Videos" ).
click ( "span.ng-isolate-scope:nth-child(4) > span:nth-child(1) > ng-transclude:nth-child(1) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(1) > a:nth-child(1)" ).
pause ( 9000 )
if( i<videoUrl.length-1) {
client.getText('.content-count > strong', function(result1) {
if (result1.status !== -1) {
countBeforeAdd = result1.value;
countBeforeAdd = countBeforeAdd.substring(1, countBeforeAdd.length - 1);
console.log('Count - Before adding video: ' + countBeforeAdd)
}
client.pause ( 10000).
waitForElementVisible(".btn.btn-primary.btn-add", 9000).
verify.visible(".btn.btn-primary.btn-add").
//moveToElement(".btn.btn-primary.btn-add",0,0).
click(".btn.btn-primary.btn-add")
//Get no of Videos
});
}
}
} } );
//}
//});
//this.assert.fail( undefined, undefined , "Invalid url" ) });
//client.waitForElementVisible ( '.field-error', 15000 ).
//verify.visible ( ".field-error" )
// });
client.end();
}
//else { console.log("overall scenario failed")}
}
}
|
var path = require('path');
var webpack = require('webpack');
var _ = require("lodash");
var commonConfig = require("./webpack.common.config");
var config = _.assign(commonConfig, {
devtool: 'eval',
mode: "development",
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/example/index.tsx'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
})
module.exports = config;
|
// MIT © 2017 azu
"use strict";
const fs = require("fs");
const path = require("path");
const getPackages = require("./lib/package-list").getPackages;
const updatePackage = (pkg, updatablePkg) => {
return Object.assign({}, pkg, updatablePkg);
};
/**
* Add
*
* ```
* "publishConfig": {
* "access": "public"
* }
* ```
*
* https://github.com/lerna/lerna/issues/914#issuecomment-318497928
*/
getPackages().forEach(packageDirectory => {
const packageJSONPath = path.join(packageDirectory, "package.json");
const pkg = JSON.parse(fs.readFileSync(packageJSONPath, "utf-8"));
const newPkg = updatePackage(pkg, {
publishConfig: {
access: "public"
}
});
fs.writeFileSync(packageJSONPath, JSON.stringify(newPkg, null, 2), "utf-8");
});
|
/**
* Created by Administrator on 2016/5/6.
*/
var app = angular.module("myApp",[]).config(function($httpProvider) {
$httpProvider.defaults.headers
.common['Accept'] = 'application/json; charset=utf-8';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8';
$httpProvider.defaults.transformRequest = [function(data) {
if(null!=data) {
if (null != getCookie("token")) {
data.token = getCookie("token");
}
//console.log(data.token);
var jsonStr = JSON.stringify(data);
return jsonStr;
}
}];
$httpProvider.defaults.transformResponse = [function(data) {
var json = "";
try {
json = JSON.parse(data);
}catch(e) { //如果不是json数据,把数据直接返回
return data;
}
if(json.status.errorCode=="000001") {
alert(json.status.errorMsg);
return null;
}else if(json.status.errorCode=="000002") {
alert(json.status.errorMsg);
top.location.href=loginUrl;
}else if(json.status.errorCode=="000003") {
alert(json.status.errorMsg);
top.location.href=loginUrl;
}else if(json.status.errorCode=="000000") {
if(json.data.token!=null&&json.data.token!=undefined) {
var exp = getParamFromToken(json.data.token,"exp");
setCookie("token",json.data.token,exp);
}
}
return json;
}];
});
//流水业务类
app.factory('BusinessService', ['$http', function ($http) {
var get = function (url,params) {
return $http({
params: params,
url: url,
method: 'GET'
});
};
var post = function (url, business) {
return $http.post(url, business);
};
return {
get: function (url,params) {
return get(url,params);
},
post: function (url, business) {
return post(url, business);
}
};
}]);
//输出html
app.filter('html', ['$sce', function ($sce) {
return function (text) {
return $sce.trustAsHtml(text);
}
}]);
//表格组件
app.directive("myGrid",function($compile){
return {
restrict : 'E',
templateUrl: '../ngTemplate/grid.html',
replace : true,
scope: {
gid: '='
},
transclude:true,
controller :function($scope, $element, $attrs, $transclude){
//console.log("come in controller<<<<<<");
$scope.gid.columns=[];
this.addColumn = function(columnObj) {
$scope.gid.columns.push(columnObj);
//console.log($scope.columns);
};
},
link: function($scope, iElement, iAttrs, controller) {
//console.log("come in link<<<<<<");
//console.log($scope.gid);
//表格相关属性和方法
$scope.gid.items={};
$scope.gid.checkAllVal=false;
$scope.gid.checkAll=function() {
for(var i=0;i<$scope.gid.items.length;i++) {
$scope.gid.items[i].checked=$scope.gid.checkAllVal;
}
};
$scope.gid.checkItem=function(checked) {
if(!checked) {
$scope.gid.checkAllVal=false;
}
};
$scope.gid.pages=1;
$scope.gid.gridPrompt=true;
$scope.gid.gridPromptTxt="数据加载中......";
$scope.gid.listItems=function() {
$scope.gid.gridPrompt=true;
$scope.gid.gridPromptTxt="数据加载中......";
$scope.gid.checkAllVal=false;
$scope.gid.param.currentPage=$scope.gid.param.currentPage?$scope.gid.param.currentPage:1;
$scope.gid.param.pageSize=$scope.gid.param.pageSize?$scope.gid.param.pageSize:10;
$scope.gid.param.orderBy=$scope.gid.param.orderBy?$scope.gid.param.orderBy:"";
$scope.gid.param.searchStr=$scope.gid.searchStr?$scope.gid.searchStr:"";
$scope.gid.loadGridData();
};
$scope.gid.setGridData = function(data) {
//console.log(data);
if(null==data) {
return;
}
if(data.data.total>0) {
$scope.gid.gridPrompt = false;
}else {
$scope.gid.gridPrompt = true;
$scope.gid.gridPromptTxt="没有符合条件的记录";
}
$scope.gid.items = data.data.items;
for (var i = 0; i < $scope.gid.items.length; i++) {
$scope.gid.items[i].checked = false;
}
if($scope.gid.changeGridData) {
$scope.gid.changeGridData();
}
$scope.gid.pages = data.data.pages;
if ($scope.gid.pages > 1) {
laypage({
cont: 'pagingDiv',
pages: $scope.gid.pages, //可以叫服务端把总页数放在某一个隐藏域,再获取。假设我们获取到的是18
curr: function () { //通过url获取当前页,也可以同上(pages)方式获取
return $scope.gid.param.currentPage;
}(),
jump: function (e, first) { //触发分页后的回调
if (!first) { //一定要加此判断,否则初始时会无限刷新
$scope.gid.param.currentPage = e.curr;
$scope.gid.checkAllVal=false;
$scope.gid.listItems();
}
}
});
} else {
$("#pagingDiv").html("");
}
//重新编译,使动态插入的ng-click等生效
//console.log(document.querySelector("table tr"));
//var newElem = $compile(document.querySelector("table tr"))($scope);
//console.log(newElem);
//iElement.contents().remove();
//iElement.append(newElem);
};
$scope.gid.searchKeyup = function(e){
var keycode = window.event?e.keyCode:e.which;
if(keycode==13){
$scope.gid.listItems();
}
};
//执行获取表格数据的函数
$scope.gid.listItems();
//=====================表格相关属性和方法 结束
}
}
});
app.directive("myGridColumn",function() {
return {
restrict: 'E',
require : '^myGrid',
scope: {
headtext: '@headtext',
datafield: '@datafield',
width: '@width',
align: '@align',
itemrender: '@itemrender'
},
link: function ($scope, iElement, iAttrs, controller) {
//console.log("come in link<<<<<<<");
var columnObj = {};
columnObj.headtext=$scope.headtext;
columnObj.datafield = $scope.datafield;
//if($scope.datafield&&$scope.datafield.indexOf("item.")!=-1) {
// columnObj.datafield = $scope.datafield;
//}else {
// columnObj.datafield = "item." + $scope.datafield;
//}
columnObj.width=$scope.width;
if($scope.align) {
columnObj.align=$scope.align;
}else {
columnObj.align="center"; //默认居中
}
columnObj.itemrender=$scope.itemrender;
controller.addColumn(columnObj);
}
}
});
|
var React = require('react');
import {Icon} from "react-photonkit";
var styles = {
avatar: {
marginRight: 10,
borderRadius: '50%',
verticalAlign: 'middle'
}
}
module.exports = React.createClass({
renderComment: function () {
var c = [];
var _this = this;
this.props.comments.map(function (comment) {
c.push(
<div key={comment.id}>
<p>
<img src={comment.user.image_url['32px']} style={styles.avatar}/>
<b>{comment.user.name}</b> <Icon glyph="up-open-big" title="up-open-big"/> {comment.votes}
</p>
<p>
{comment.body}
</p>
</div>
)
})
return c;
},
render: function () {
return (
<div>
{this.renderComment()}
</div>
);
}
}); |
'use strict'
eventsApp.controller('EditEventController',function($scope,$firebaseArray,fbRef,$location){
$scope.saveEvent=function(event,newEventForm){
if(newEventForm.$valid){
//window.alert('event'+event.name+"saved!");
// eventData.save(event)
// .$promise.then(
// function(response){debugger;console.log('success',response)},
// function(response){debugger;console.log('failure',response)}
// );
$firebaseArray(fbRef.getEvents()).$add(event);
$location.path("/events");
}
}
$scope.cancelEdit=function(){
window.location="/events";
}
}); |
var gulp = require('gulp');
var wiredep = require('wiredep');
var paths = gulp.paths;
// inject bower components
gulp.task('wiredep', function() {
gulp.src(paths.src + '/app/styles/*.scss')
.pipe(wiredep({
ignorePath: /^(\.\.\/)+/
}))
.pipe(gulp.dest('app/styles'));
gulp.src(paths.src + '/app/*.html')
.pipe(wiredep({
exclude: ['bootstrap-sass'],
ignorePath: /^(\.\.\/)*\.\./
}))
.pipe(gulp.dest(paths.src + '/app'));
});
|
/* @flow */
import { warn, extend, isPlainObject } from 'core/util/index'
// 合并 v-on 绑定的函数
export function bindObjectListeners (data: any, value: any): VNodeData {
if (value) {
if (!isPlainObject(value)) {
process.env.NODE_ENV !== 'production' && warn(
'v-on without argument expects an Object value',
this
)
} else {
const on = data.on = data.on ? extend({}, data.on) : {}
for (const key in value) {
const existing = on[key]
const ours = value[key]
on[key] = existing ? [].concat(existing, ours) : ours
}
}
}
return data
}
|
var sign = require('./sign.js');
var request = require( 'request' );
var config = {
appID:'wx9037bc18a8016fb5',
appSecret:'c15c32f6f2ca373cd3b4545e768133db',
url:'http://test.fangcheng.cn/test'
};
var SIGNATURE = {
appId:config.appID,
jsapi_ticket:'',
nonceStr:'',
timestamp:'',
url:'',
signature:'',
beginTime:(new Date()).getTime(),
expires_in:7200,
status:false
},INTERVAL = 30 * 1000 * 60,//30分钟
signatureTimer = new SignatureTimer();
var accsess_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+config.appID+"&secret="+config.appSecret;
function getSignature(callback) {
request.get( accsess_url, function(err, response, body ) {
try {
var access = JSON.parse( body );
SIGNATURE.expires_in = access.expires_in;
request.get( "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access.access_token+"&type=jsapi", function(err, response, body ) {
var ticket = JSON.parse( body).ticket;
var _sign = sign(ticket, config.url);
SIGNATURE.jsapi_ticket = _sign.jsapi_ticket;
SIGNATURE.nonceStr = _sign.nonceStr;
SIGNATURE.timestamp = _sign.timestamp;
SIGNATURE.url = _sign.url;
SIGNATURE.signature = _sign.signature;
SIGNATURE.status = true;
SIGNATURE.beginTime = (new Date()).getTime();
if(typeof callback === 'function') {
callback(SIGNATURE);
}
});
} catch(e) {
if(typeof callback === 'function') {
callback(SIGNATURE);
}
console.log('get weixin signature error');
}
} );
}
function SignatureTimer() {
function worker() {
var currentTime = (new Date()).getTime(),
dur = currentTime - SIGNATURE.beginTime;
if(dur > 7200 * 1000 * 0.9) {
getSignature();
}
}
return {
started:false,
start:function(){
if(!this.interval && !this.started) {
this.interval = setInterval(worker,INTERVAL);
this.started = true;
}
},
stop:function() {
if(this.interval) {
clearInterval(this.interval);
delete this.interval;
this.started = false;
}
}
}
}
exports.getSignature = function(callback) {
if(!SIGNATURE.status) {
getSignature(callback);
if(!signatureTimer.started) {
signatureTimer.start();
}
} else {
callback(SIGNATURE);
}
};
|
(function($){
// var aboutSection = $('.section-blue');
// $('.main-button').click(function () {
// $('html, body').animate({
// scrollTop: aboutSection.offset().top
// }, 500);
// return false;
// });
var $window = $(window);
var nav = $('nav');
var $navLinks = $('.nav-list-link:not(.normal)');
var $htmlAndBody = $('html, body');
var $sections = $('.section:not(.subsection)');
$navLinks.on("click", function(e) {
e.preventDefault();
var $self = $(this);
var sectionId = $self.data("section-id");
$htmlAndBody.animate({
scrollTop: $("#" + sectionId)
.offset()
.top - 50
}, 300, function() {
$navLinks.removeClass("active");
$self.addClass("active");
});
});
$('.Category__button').on("click", function(e) {
e.preventDefault();
var $self = $(this);
var sectionId = $self.data("section-id");
$htmlAndBody.animate({
scrollTop: $("#" + sectionId)
.offset()
.top - 50
}, 300, function() {
$navLinks.removeClass("active");
$self.addClass("active");
$("a[data-section-id=" + sectionId + "]").addClass("active");
console.log('section id: ' + sectionId);
});
});
$window.on('mousewheel scroll', function() {
var aboveBlocks = $sections.map(function(i, section) {
if (section.getBoundingClientRect().top <= $window.height() / 3) {
return section;
}
});
$navLinks.removeClass("active");
$($navLinks[aboveBlocks.length - 1]).addClass("active");
});
$('.hamburger-button').click(function() {
if (nav.hasClass('open')) {
nav.removeClass('open');
return;
}
nav.addClass('open');
});
$(window).resize(function () {
if ($window.width > 610 && isScreenLarge === false) {
isScreenLarge = true;
nav.removeClass('compact');
nav.removeClass('open');
hamburgerButton.removeClass('active');
}
if ($window <= 610 && isScreenLarge === true) {
isScreenLarge = false;
nav.addClass('compact');
}
});
var updateValidErrors = function ($form, validErrors) {
console.log(validErrors);
$form.find('input, textarea').each(function (index, input) {
var $input = $(input);
var fieldName = $input.attr('name');
var $errorBlock = $input.next('.error');
var $errorMsg;
if (validErrors[fieldName] != null) {
switch(fieldName) {
case 'email':
$errorMsg = validErrors[fieldName][0];
break;
case 'password':
$errorMsg = validErrors[fieldName][0].replace('password', 'пароль');
break;
case 'message':
$errorMsg = validErrors[fieldName][0].replace('message', 'сообщение');
}
$errorBlock.text($errorMsg);
} else {
$errorBlock.text('');
}
});
};
$('.modal-form').submit(function (e) {
e.preventDefault();
var $this = $(this);
$this.find('i').css('visibility', 'visible');
var request = $.ajax({
url: $this.attr('action'),
method: 'POST',
data: $this.serialize()
});
request.done(function (response) {
$this.find('i').css('visibility', 'hidden');
if ($this.closest('.remodal').length != 0) {
// $('.Nav__item--modal').remove();
// $('.Nav__list').append('<li class="Nav__item"><a href="/profile" class="Nav__link"><span>My profile</span></a></li>');
// $('.Nav__list').append('<li class="Nav__item"><a href="/logout" class="Nav__link"><span>Logout</span></a></li>');
// ohSnap(response.notify, {color: 'green'});
} else {
//updateValidErrors($this, {});
//console.log('second');
//ohSnap(response.notifyMessage, {color: 'green'});
//$this.next().html(response.notify);
//$('html, body').animate({scrollTop: $('.Block').position().top}, 'slow');
}
if ($this.attr('action') != '/email') {
document.location = '/';
} else {
console.log('niko');
ohSnap(response.notify, {color: 'green'});
$this.find('.remodal-cancel').trigger('click');
}
});
request.fail(function (response) {
$this.find('i').css('visibility', 'hidden');
var errors = JSON.parse(response.responseText);
if (errors.notify) {
updateValidErrors($this, {});
} else {
updateValidErrors($this, errors);
}
ohSnap(errors.notify || 'пожалуйста, исправьте ошибки в форме', {color: 'red'});
});
});
//show flash message in alert
var flashMessage = $('#ohsnap').data('notify')
if (flashMessage != null) {
ohSnap(flashMessage, {color: 'green'});
}
})(jQuery);
//# sourceMappingURL=all.js.map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.