code
stringlengths
2
1.05M
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = require("vue"); var _vue2 = _interopRequireDefault(_vue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var bus = new _vue2.default(); exports.default = bus;
//1. Copy onpremise files into distribution folder //First from addon folder, second from shared folder var pathes = [ 'addon/onpremise/*', 'addon/onpremise/src/aps/*', 'addon/onpremise/src/main/java/com/yasoon/jira/*', 'addon/onpremise/src/main/resources/*', 'addon/distribution/onpremise', ]; var copyfiles = require('copyfiles'); copyfiles(pathes, 2, function () { pathes = [ 'addon/shared/*', 'addon/shared/css/*', 'addon/shared/fonts/*', 'addon/shared/fonts/roboto/*', 'addon/shared/images/*', 'addon/shared/img/*', 'addon/shared/js/*', 'addon/shared/js/components/*', 'addon/shared/js/library/*', 'addon/distribution/onpremise/src/main/resources' ]; copyfiles(pathes, 2, function () { }); });
/* To use/test admin panel in your local machine you have to insert an admin data mannually in mongoDB and make sure you make "HasAccess" set to "true" as it is "false" by default */ var express = require('express'); var router = express.Router(); var sess = {}; // Admin schema imported var Admin = require("./../models/Admin"); // Event schema imported var Event = require("./../models/Event"); // User schema imported var User = require("./../models/User"); // Registrations schema imported var Registration = require('./../models/Registrations'); /* GET Signup page. */ router.get('/', function(req, res) { sess = req.session; if(sess.admin) { res.render('adminlogin.hbs', {user : sess.admin}); } else { res.render('adminlogin.hbs', {user : {username:"New admin"}}); } }); router.post('/login', function(req, res) { sess = req.session; if(!sess.admin){ // Checking username from current database Admin.find({username:req.body.username},function(err,admin){ if(err){ res.status(500).send({error:"Could not get to Database"}); console.log("Could get to database"); } else{ if (admin[0].length!== 0) { if(admin[0].username){ console.log(req.body); console.log(admin); if(admin[0].Password == req.body.password){ //Successful sign in req.session.admin = admin[0]; res.render('adminpanel.hbs', { user :admin[0] }); } else{ res.render('adminlogin.hbs', { user :"New admin", login:"Username or password wrong, try again." }); } } } else{ res.render('adminlogin.hbs', { user :"New admin", login:"Username or password wrong, try again." }); } } }); } else{ res.render('adminlogin.hbs', { user : sess.admin, login : "You have to log out first" }); } }); router.get('/addevent', function(req, res) { sess = req.session; if(sess.admin) { res.render('addevent.hbs', {user : sess.admin}); } else { res.render('adminlogin.hbs', {user : {username:"New admin"},login:"You need to log in first. !"}); } }); router.post('/addevent_submit', function(req, res) { sess = req.session; if(sess.admin) { Event.find({Event_ID:req.body.ID},function(err,event){ if(err){ res.status(500).send({error:err}); console.log(err); } else{ if (event.length!=0) { if(event[0].Event_ID){ console.log("Event ID already exist username:"+event[0].Event_ID); res.render('addevent.hbs', { user : sess.admin, emessage:"Event ID already exist, try again" }); } } else{ var event = new Event(); event.Event_ID = req.body.ID; event.Event_Name = req.body.Name; event.Event_Type = req.body.eventType; event.Event_Description = req.body.Description; event.Venue= req.body.Venue; event.Date = req.body.Date; event.Time = req.body.Time; event.Fee = req.body.Fee; event.Additional_Links = req.body.Additional; // Saving new event to database event.save(function(err, newEvent){ if(err){ res.status(500).send({error:err}); console.log("Could not add event."); } else{ res.render('adminpanel.hbs', {user : sess.admin, eventMessage : "Event created!"}); console.log('! An event created: \n' + newEvent); } }); } } }); } else { res.render('adminlogin.hbs', {user : {username:"New admin"},login:"You need to log in first. !"}); } }); router.get('/editevent', function(req, res) { sess = req.session; if(sess.admin) { res.render('editevent.hbs', {user : sess.admin}); } else { res.render('adminlogin.hbs', {user : {username:"New admin"},login:"You need to log in first. !"}); } }); var holdID; router.post('/editevent_search', function(req, res) { sess = req.session; if(sess.admin) { Event.find({Event_ID:req.body.srcheventID},function(err,event){ if(err){ res.status(500).send({error:err}); console.log(err); } else{ if (event.length!=0) { if(event[0].Event_ID){ console.log("Event found :"+event[0]); holdID = event[0]._id; res.render('editevent.hbs', { user : sess.admin, event: event[0], emessage:"Event found. You can edit now.", }); } } else{ res.render('editevent.hbs', { user : sess.admin, emessage:"Event not found. Try again.", }); } } }); } else { res.render('adminlogin.hbs', {user : {username:"New admin"},login:"You need to log in first. !"}); } }); router.post('/editevent_submit', function(req, res, next) { sess=req.session; if(sess.admin) { Event.findOneAndUpdate({_id: holdID}, {$set:{ Event_Name:req.body.Name, Event_Type:req.body.eventType, Event_Description:req.body.Description, Venue:req.body.Venue, Date:req.body.Date, Time:req.body.Time, Fee:req.body.Fee, Additional_Links:req.body.Additional, }}, {new: true}, function(err, event){ if(!err){ res.render('adminpanel.hbs', {user : sess.admin, eventMessage : "Event details updated. !"}); } else{ res.status(500).send({error:"Error, can't access Database!"}); } }); } else { res.render('adminpanel.hbs', {user : {username:"New admin"}, login : "You have to log in first. !"}); } }); router.get('/deleteevent', function(req, res) { sess = req.session; if(sess.admin) { res.render('deleteEvent.hbs', {user : sess.admin}); } else { res.render('adminlogin.hbs', {user : {username:"New admin"},login:"You need to log in first. !"}); } }); router.post('/deleteevent/delete', function(req, res) { sess = req.session; if(sess.admin) { Event.find({Event_ID:req.body.srcheventID},function(err,event){ if(err){ res.status(500).send({error:err}); console.log(err); } else{ if (event.length!=0) { if(event[0].Event_ID){ Event.findOneAndRemove({Event_ID:req.body.srcheventID},function (err,event){ console.log("Event deleted ID:"+req.body.srcheventID); res.render('adminpanel.hbs', { user : sess.admin, eventMessage:"Event Deleted, ID:"+req.body.srcheventID, }); }); } } else{ res.render('deleteEvent.hbs', { user : sess.admin, emessage:"Event not found. Try again.", displaysubmit : false }); } } }); } else { res.render('adminlogin.hbs', {user : {username:"New admin"},login:"You need to log in first. !"}); } }); router.get('/users', function(req, res, next) { sess = req.session; if (!sess.admin){ return res.render('adminlogin.hbs', {user : {username:"New admin"},login:"You need to log in first. !"}); } Registration.find({}).then(function(reg){ var promisedInfo = reg.map(function(item){ var promisedUser = User.findById(item.user[0]); var promisedEvent = Event.findById(item.event[0]); return Promise.all([ promisedUser, promisedEvent]).then(function(res){ return { 'user' : res[0], 'event' : res[1] }; }); }); Promise.all(promisedInfo).then(function(items){ res.render('listusers.hbs', {items : items}); }); }).catch(function(err){ res.status(500).send({error:err}); }); }); router.get('/logout', function(req, res, next) { sess=req.session; if(sess.admin) { req.session.destroy(); res.render('adminlogin.hbs', {user : {username:"New admin"}, login : "Successfully logged out."}); } else { res.render('adminlogin.hbs', {user : {username:"New admin"}, login : "You have to sign in first. !"}); } }); module.exports = router;
export class Character { constructor() { this.strength = Character.rollAbility(); this.dexterity = Character.rollAbility(); this.constitution = Character.rollAbility(); this.intelligence = Character.rollAbility(); this.wisdom = Character.rollAbility(); this.charisma = Character.rollAbility(); this.hitpoints = 10 + abilityModifier(this.constitution); } static rollAbility() { let diceRolls = []; for (let i = 0; i < 4; i++) { diceRolls.push(Math.floor(Math.random() * 5) + 1); } return diceRolls .sort() .slice(1) .reduce((partialSum, num) => partialSum + num, 0); } } export const abilityModifier = abilityScore => { if (abilityScore < 3) { throw new Error('Ability scores must be at least 3'); } if (abilityScore > 18) { throw new Error('Ability scores can be at most 18'); } return Math.floor((abilityScore - 10) / 2); };
/** * 执行fn并把一个新的Wrapper的$()和$$()传递给它 * 如果没有传递任何参数,则执行{@link M.exportDSL} * @namespace {Function} M * @param {Function} [fn] */ var M=function(fn){ if(arguments.length == 0){ return M.exportDSL(); }else if(fn){ var wrapper = M.$wrapper(); var args = Array.prototype.slice.call(arguments, 1); return fn.apply(this, [wrapper.$, wrapper.$$].concat(args)); } } /** * 引用当前运行环境的全局对象 * 浏览器中指向window,node环境下指向global */ M.global = this; if(typeof global != "undefined")M.global = global; /** * 将May.js的关键字方法复制到目标对象 * 如果未传递target参数,则使用eval()导出到当前作用域内 * @param {Object} [target] 目标对象 */ M.exportDSL = function(target) { var _getKeywordFunc = function(){ return Object.keys(M).filter(function(name){ return (/^\$/).test(name) && ["$", "$$"].indexOf(name) == -1; }); } if(target){ _getKeywordFunc().forEach(function (prop) { target[prop] = M[prop]; }); }else{ return M.util.dsl(M, _getKeywordFunc()) + M.util.dsl(M.$wrapper()); } } if(typeof(module) != "undefined")module.exports = M;
var assert = require('assert'); var toArabic = require('./../index.js').toArabic; var literals = [ 'I', 'IV', 'VIII', 'XV', 'XVI', 'XXIII', 'XLII', 'LXXXIV', 'C', 'CCLVI', 'DXII', 'MXXIV', 'MMXLVIII', 'MMMCMXCIX' ]; var objects = literals.map(function (x) { return new String(x) }); var lowercase = literals.map(function (x) { return x.toLowerCase(); }); var answers = [ 1, 4, 8, 15, 16, 23, 42, 84, 100, 256, 512, 1024, 2048, 3999 ]; var bad_literals = [ 42 ]//{}, [], 42, function () {} ]; var bad_objects = [ new Object(), new Array(), new Number(42), new Function () ]; var bad_strings = [ 'foo', 'bar', 'foobar', 'red', 'MMORPG', 'CCCC' ]; function wontThrow (arr) { return function () { arr.forEach(function (x) { assert.doesNotThrow(function () { toArabic(x); }); }); }; } function makeThrow (arr) { return function () { arr.forEach(function (x) { assert.throws(function () { toArabic(x); }, "Because of __" + x); }); }; } function checkResults (arr) { return function () { arr.forEach(function (x, i) { assert.strictEqual(toArabic(x), answers[i]); }); }; } describe('toArabic function:', function () { describe('Checking good inputs', function () { it('Accepts literals strings', wontThrow(literals)); it('Accepts objects strings', wontThrow(objects)); it('Accepts lowercase strings', wontThrow(lowercase)); }); describe('Checking wrong inputs', function () { it('Throws on non-string literals', makeThrow(bad_literals)); it('Throws on non-string objects', makeThrow(bad_objects)); it('Throws on incorrect strings', makeThrow(bad_strings)); }); describe('Checking results', function () { it('Works with a "nulla"', function () { assert.strictEqual(toArabic('nulla'), 0); assert.strictEqual(toArabic('nuLLa'), 0); assert.strictEqual(toArabic(new String('nulla')), 0); assert.strictEqual(toArabic(new String('nuLLa')), 0); }); it('Works with an empty string', function () { assert.strictEqual(toArabic(''), 0); assert.strictEqual(toArabic(new String('')), 0); }); it('Works with string literals ', checkResults(literals)); it('Works with string objects', checkResults(objects)); it('Works with lowercase strings', checkResults(lowercase)); }); });
const process = require("process"), mysql = require("mysql"), config = require("../../config.json"); module.exports = (function() { const connectURL = `${config.databaseEndPoint || process.env["OPENSHIFT_MYSQL_DB_URL"]}bot`; // TODO: Pooling const query = (...args) => { const connection = mysql.createConnection(connectURL); connection.connect(); connection.query(...args); connection.end() }; return { query } })()
export var STORAGE; (function (STORAGE) { STORAGE[STORAGE["local"] = 0] = "local"; STORAGE[STORAGE["session"] = 1] = "session"; })(STORAGE || (STORAGE = {})); //# sourceMappingURL=storage.js.map
var debug = require('debug')('kaffeeundkuchen.api.player'); function handlePlayRequest(req, res) { debug('handle play request'); var spotifyWrapper = req.app.get('spotifyWrapper') , spotifyId = req.params.trackid , track = spotifyWrapper.getCachedTrack(spotifyId); spotifyWrapper.playTrack(track); res.json({ success: true }); } module.exports = { play: handlePlayRequest };
var needleTail = { url: '', initialize: function (twoWayControllerUrl) { this.url = twoWayControllerUrl; if (!!window.EventSource) { var source = new EventSource(this.url); source.addEventListener('message', function (e) { needleTail.executeServerCall(e); }, false); source.addEventListener('open', function (e) { needleTail.connectionOpen(e); }, false); source.addEventListener('error', function (e) { needleTail.connectionError(e); }, false); } else { alert('SSE not supported'); } }, executeServerCall: function (e) { //convert string to json var call = eval("(" + e.data + ")"); //the call is on e.data var method = call.command; var pars = call.parameters; needleTail.executeFunction(method, window, pars); }, connectionOpen: function (e) { /* run any code when the connection is opened */ }, connectionError: function (e) { /* run code when a connection fails */ }, executeFunction: function (functionName, context, args) { var namespaces = functionName.split("."); var func = namespaces.pop(); for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } return context[func].apply(context, args); } };
sabio.services.jobPosting = sabio.services.jobPosting || {}; sabio.services.jobPosting.post = function (data, onSuccess, onError) { var url = "/api/jobpostings"; var settings = { cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", data: data, dataType: "json", type: "POST", success: onSuccess, error: onError }; $.ajax(url, settings); } sabio.services.jobPosting.put = function (id, data, onSuccess, onError) { var url = "/api/jobpostings/" + id; var settings = { cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", data: data, dataType: "json", type: "PUT", success: onSuccess, error: onError, }; $.ajax(url, settings); } sabio.services.jobPosting.delete = function (id, onSuccess, onError) { var url = "/api/jobpostings/" + id; var settings = { cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "json", type: "DELETE", success: onSuccess, error: onError, }; $.ajax(url, settings); } sabio.services.jobPosting.getById = function (id, onSuccess, onError) { var url = "/api/jobpostings/" + id; var settings = { async: false, cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "json", type: "GET", success: onSuccess, error: onError, }; $.ajax(url, settings); } sabio.services.jobPosting.searchByKeyword = function (searchRequest, onSuccess, onError) { var url = "/api/jobpostings/search/" + searchRequest; var settings = { async: false, cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "json", type: "GET", success: onSuccess, error: onError, }; $.ajax(url, settings); } sabio.services.jobPosting.searchIndeed = function (searchRequest, onSuccess, onError) { var url = "/api/jobpostings/indeedsearch?" + searchRequest; var settings = { cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "json", type: "GET", success: onSuccess, error: onError, }; $.ajax(url, settings); } sabio.services.jobPosting.searchMonster = function (searchRequest, onSuccess, onError) { var url = "/api/jobpostings/monstersearch?" + searchRequest; var settings = { cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "json", type: "GET", success: onSuccess, error: onError, }; $.ajax(url, settings); } sabio.services.jobPosting.searchUsaJobs = function (searchRequest, onSuccess, onError) { var url = "/api/jobpostings/usajobssearch?" + searchRequest; var settings = { cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "json", type: "GET", success: onSuccess, error: onError, }; $.ajax(url, settings); } sabio.services.jobPosting.getAll = function (onSuccess, onError) { var url = "/api/jobpostings/"; var settings = { cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "json", type: "GET", success: onSuccess, error: onError, }; $.ajax(url, settings); } sabio.services.jobPosting.clickLog = function (engineId, onSuccess, onError) { var url = "/api/jobpostings/clicklog/" + engineId; var settings = { cache: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", type: "POST", success: onSuccess, error: onError, }; $.ajax(url, settings); }
/** * @author: Michael * @date: 2017-07-28 17:35:05 * @last modified by: Michael * @last modified time: 2017-07-28 17:35:05 * @gitHub: https://github.com/maxsmu */ import { handleActions } from 'redux-actions'; import { get_monitor, get_sows_monitor, update_monitor_data, editor_state } from '@actions/monitor/action-types'; const reducer = handleActions({ /** * 获取监控列表 * @param {*} state * @param {*} action */ [get_sows_monitor](state, action) { // monitorList:监控列表数据 const { monitorList } = action.payload; return { ...state, monitorList: { data: monitorList.data, pagination: monitorList.pagination, isFetching: action.payload.isFetching } }; }, /** * 获取监控状态 * @param {*} state * @param {*} action */ [get_monitor](state, action) { // monitorState:监控状态 return { ...state, monitorState: { ...action.payload.monitorState, isFetching: action.payload.isFetching } }; }, /** * 更新监控数据 * @param {*} state * @param {*} action */ [update_monitor_data](state, action) { let monitorList = state.monitorList.data; // 获取更新数据 const { success, isFetching } = action.payload; // 若修改成功后则更新数据 if (!isFetching) { monitorList = updatList(success, monitorList); } return { ...state, updateMonitor: action.payload, monitorList: { data: monitorList, pagination: state.monitorList.pagination, isFetching: false } }; }, /** * 编辑状态 * @param {*} state * @param {*} action */ [editor_state](state, action) { const { visible, item = {} } = action.payload; return { ...state, editorState: { visible, item } } } }, {}); /** * 更新修改数据 * @param {Object} success 修改成功后返回对象 * @param {*} list 列表 * @return {Array} monitorList */ function updatList(success, list = []) { const currentIndex = list.findIndex(item => item.id === success.id); if (currentIndex >= 0) { list[currentIndex] = success; } return list; } export default reducer;
version https://git-lfs.github.com/spec/v1 oid sha256:646a3daef1fe62622e901f30d5618120b08c991ea1bcc0b5e6717db92b9efac1 size 52927
//~ name b64 alert(b64); //~ component b65.js
// config/passport.js // load all the things we need var LocalStrategy = require('passport-local').Strategy; // load up the user model var User = require('../app/models/user/user'); // expose this function to our app using module.exports module.exports = function(passport) { // ========================================================================= // passport session setup ================================================== // ========================================================================= // required for persistent login sessions // passport needs ability to serialize and unserialize users out of session // used to serialize the user for the session passport.serializeUser(function(user, done) { done(null, user.id); }); // used to deserialize the user passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); // ========================================================================= // LOCAL SIGNUP ============================================================ // ========================================================================= // we are using named strategies since we have one for login and one for signup // by default, if there was no name, it would just be called 'local' passport.use('local-signup', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email', passwordField : 'password', passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // asynchronous // User.findOne wont fire unless data is sent back process.nextTick(function() { // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ 'local.email' : email }, function(err, user) { // if there are any errors, return the error if (err) return done(err); // check to see if theres already a user with that email if (user) { return done(null, false, req.flash('signupMessage', 'That email is already taken.')); } else { // if there is no user with that email // create the user var newUser = new User(); // set the user's local credentials newUser.details.fullname = req.body.fullname; newUser.local.email = email; newUser.local.password = newUser.generateHash(password); // save the user newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); }); })); // ========================================================================= // LOCAL LOGIN ============================================================= // ========================================================================= // we are using named strategies since we have one for login and one for signup // by default, if there was no name, it would just be called 'local' passport.use('local-login', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email', passwordField : 'password', passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // callback with email and password from our form // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ 'local.email' : email }, function(err, user) { // if there are any errors, return the error before anything else if (err) return done(err); // if no user is found, return the message if (!user) return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash // if the user is found but the password is wrong if (!user.validPassword(password)) return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata // all is well, return successful user return done(null, user); }); })); };
import fs from 'fs'; import path from 'path'; import zlib from 'zlib'; import request from 'supertest'; import promisify from 'es6-promisify'; import app from '../app'; import sites from '../actions/sites'; import imageQueue from '../queues/images'; import db from '../db/db'; import storage from '../aws-s3'; const object = { name: 'object', value: {} }; const array = { name: 'array', value: [] }; const string = { name: 'string', value: 'foo' }; const number = { name: 'number', value: 123 }; const boolean = { name: 'boolean', value: true }; const readFile = promisify(fs.readFile); const gzipBuffer = promisify(zlib.gzip); describe('POST /api/images/:siteId', () => { let count; let consoleError; beforeEach(() => { count = 1; db.query = jest.fn((query, values) => { if (query.indexOf('COUNT(*)') > -1) { return Promise.resolve([{ count }]); } return Promise.resolve([{ id: 123 }]); }); sites.getSite = jest.fn(() => { return Promise.resolve({}); }); storage.putObject = jest.fn(() => Promise.resolve()); imageQueue.push = jest.fn(); consoleError = console.error; console.error = jest.fn(); }); afterEach(() => { console.error = consoleError; }); xdescribe('User validation', () => { it('fails if the user is not logged in', () => { return request(app) .post('/api/images/0') .expect(401); }); it('fails if the user is not the site owner', () => { return request(app) .post('/api/images/0') .set('', '') .expect(401); }); }); it('fails if we do not pass any data', () => { return request(app) .post('/api/images/0') .expect(400); }); describe('For', () => { [object, array, number, boolean].forEach(type => { it(`fails if it is a ${type.name}`, () => { return request(app) .post('/api/images/0') .send({ for: type.value }) .expect(400) .then(res => { expect(res.text).toEqual( 'The given For is not valid. It must be one of: "site", "blog", "category".' ); }); }); }); describe('blog', () => { it('fails if the blog does not exist or is not part of that website', () => { count = 0; return request(app) .post('/api/images/0') .send({ for: 'blog', forId: 10 }) .expect(400) .then(res => { expect(res.text).toEqual('The given blog does not exist.'); }); }); }); describe('category', () => { it('fails if the blog does not exist or is not part of that website', () => { count = 0; return request(app) .post('/api/images/0') .send({ for: 'category', forId: 10 }) .expect(400) .then(res => { expect(res.text).toEqual('The given category does not exist.'); }); }); }); describe('site', () => { // TODO: Implement new login with Cookies for that to work }); }); describe('Title', () => { [object, array, number, boolean].forEach(type => { it(`fails if it is a ${type.name}`, () => { return request(app) .post('/api/images/0') .send({ for: 'category', forId: 10, title: type.value }) .expect(400) .then(res => { expect(res.text).toEqual( 'The given Title is not valid. It must be of a maximum of 80 characters.' ); }); }); }); it('fails if it is a empty string', () => { return request(app) .post('/api/images/0') .send({ for: 'category', forId: 10, type: 'image', title: '' }) .expect(400) .then(res => { expect(res.text).toEqual( 'The given Title is not valid. It must be of a maximum of 80 characters.' ); }); }); it('fails if it is a string with more than 80 characters', () => { return request(app) .post('/api/images/0') .send({ for: 'category', forId: 10, title: 'My title of more than 80 characters is here: 0123456789 0123456789 0123456789 012' }) .expect(400) .then(res => { expect(res.text).toEqual( 'The given Title is not valid. It must be of a maximum of 80 characters.' ); }); }); }); describe('Description', () => { [object, array, number, boolean].forEach(type => { it(`fails if it is a ${type.name}`, () => { return request(app) .post('/api/images/0') .send({ for: 'category', forId: 10, title: 'My Title', description: type.value }) .expect(400) .then(res => { expect(res.text).toEqual('The given Description is not valid.'); }); }); }); it('fails if it is a empty string', () => { return request(app) .post('/api/images/0') .send({ for: 'category', forId: 10, title: 'My Title', description: '' }) .expect(400) .then(res => { expect(res.text).toEqual('The given Description is not valid.'); }); }); }); describe('image fails', () => { it('returns an error if the uploaded file is missing', () => { return request(app) .post('/api/images/0') .field('for', 'category') .field('forId', 10) .field('title', 'My Title') .field('description', 'My Description') .expect(400) .then(res => { expect(res.text).toContain('The required Image is missing.'); }); }); it('returns an error if the uploaded file is invalid', () => { return request(app) .post('/api/images/0') .field('for', 'category') .field('forId', 10) .field('title', 'My Title') .field('description', 'My Description') .attach('image', path.resolve(__dirname, 'images.test.txt')) .expect(400) .then(res => { expect(res.text).toContain('The uploaded file is not valid.'); }); }); }); describe('Post image', () => { it('inserts a new image in the DB', () => { return ( request(app) .post('/api/images/0') .field('for', 'blog') .field('forId', 10) .field('title', 'My Title') .field('description', 'My Description') .attach('image', path.resolve(__dirname, 'images.test.png')) // .expect(200) .then(res => { expect(db.query).toHaveBeenCalledWith(expect.any(String), [0, 'images', 10, 'blog']); }) ); }); it('returns the ID of the new images', () => { return request(app) .post('/api/images/0') .field('for', 'blog') .field('forId', 10) .field('title', 'My Title') .field('description', 'My Description') .attach('image', path.resolve(__dirname, 'images.test.png')) .expect(200) .then(res => { expect(res.body).toEqual({ status: 'success', id: 123 }); }); }); it('uploads the default image gzipped', () => { return request(app) .post('/api/images/0') .field('for', 'blog') .field('forId', 10) .field('title', 'My Title') .field('description', 'My Description') .attach('image', path.resolve(__dirname, 'images.test.png')) .expect(200) .then(res => { return readFile(path.resolve(__dirname, 'images.test.png')) .then(buffer => gzipBuffer(buffer)) .then(buffer => { expect(storage.putObject).toHaveBeenCalledWith({ CacheControl: 'public, max-age=31536000', ContentEncoding: 'gzip', ContentType: 'image/png', ACL: 'public-read', Key: '0/blogs/10/images/123.png', Body: buffer }); }); }); }); it('inserts the new image in the DB', () => { return request(app) .post('/api/images/0') .field('for', 'blog') .field('forId', 10) .field('title', 'My Title') .field('description', 'My Description') .attach('image', path.resolve(__dirname, 'images.test.png')) .expect(200) .then(() => { expect(db.query).toHaveBeenCalledWith( expect.stringContaining('INSERT INTO medias_images'), [123, 'My Title', 'My Description', '0/blogs/10/images/123.png', 'image/png'] ); }); }); it('adds the image optimizations to the queue', () => { return request(app) .post('/api/images/0') .field('for', 'blog') .field('forId', 10) .field('title', 'My Title') .field('description', 'My Description') .attach('image', path.resolve(__dirname, 'images.test.png')) .expect(200) .then(() => { expect(imageQueue.push).toHaveBeenCalledWith(0, 123, 'thumbnail'); expect(imageQueue.push).toHaveBeenCalledWith(0, 123, 'small'); expect(imageQueue.push).toHaveBeenCalledWith(0, 123, 'medium'); expect(imageQueue.push).toHaveBeenCalledWith(0, 123, 'large'); }); }); }); });
$(document).ready(function() { var movieApp = {}; movieApp.apiKey = 'ca6ea09713defa345edd21995ca6f8f8'; movieApp.getMovies = function(year){ $.ajax({ url: `https://api.themoviedb.org/3/discover/movie?`, method: 'GET', dataType: 'jsonp', data: { api_key: movieApp.apiKey, primary_release_year: year, certification_country: 'US', language: "en-US", include_adult: false, certification: 'R', total_results: 9 } }).then(function(res){ var moviesOutput = res.results; console.log(moviesOutput); // this only sends the DATA of the moviesOutput variable to displayMovies we use an arbitrary var 'item' in this case to add a new name to the data so we can loop over it using the forEach method movieApp.displayMovies(moviesOutput); }) } var movieApp = {}; movieApp.apiKey = 'ca6ea09713defa345edd21995ca6f8f8'; movieApp.getMovies = function(year){ $.ajax({ url: `https://api.themoviedb.org/3/discover/movie?`, method: 'GET', dataType: 'jsonp', data: { api_key: movieApp.apiKey, primary_release_year: year, certification_country: 'US', language: "en-US", include_adult: false, certification: 'R', page: 1 } }).then(function(res){ var moviesOutput = res.results; console.log(moviesOutput); // this only sends the DATA of the moviesOutput variable to displayMovies we use an arbitrary var 'item' in this case to add a new name to the data so we can loop over it using the forEach method movieApp.displayMovies(moviesOutput); }) } movieApp.browserStuff = function(){ $('.fader').addClass('animated fadeInRight'); $('i').addClass('animated infinite bounce'); $('a').smoothScroll({ offset:0, speed: 400 }); $(window).scroll(function() { if ($(this).scrollTop() > 0) { $('.prelude h3').addClass('animated fadeInLeft'); } }); } movieApp.displayMovies = function(item){ console.log(item); // the someObject is just an arbitrary var that loops over the objects in 'item'. $('.movieInfo').empty(); item.forEach(function(someObject){ // var titleEl = $('<h2>').text(someObject.original_title); var posters = $(`<img>`).attr(`src`, `https://image.tmdb.org/t/p/w300${someObject.poster_path}`); var synopsis = $('<p>').text(someObject.overview); var synopsisContainer = $('<div>').addClass('synopsisContainer').append(synopsis); var movieContainer = $('<div>').addClass('flickity-cell').append(posters, synopsisContainer) $('.movieInfo').append(movieContainer); }); } movieApp.init = function(){ movieApp.getMovies(); movieApp.browserStuff(); } $(function(){ movieApp.init(); }); });
import SearchPanel from "./SearchPanel.js"; export default function main(session) { let searchPanel = new SearchPanel(session); session.toolbar.addButton("Search", () => searchPanel.attach()); }
///////////////////////////////////////////////////////////////////////////////////// // status ///////////////////////////////////////////////////////////////////////////////////// var ENV = require('./_config/modules/status') var PROD = ENV === 'production' console.log('\n' + 'status ----\n\n' + ENV + '\n\n----') ///////////////////////////////////////////////////////////////////////////////////// // requirement ///////////////////////////////////////////////////////////////////////////////////// // common var ExtractTextPlugin = require('extract-text-webpack-plugin') var webpack = require('webpack') var path = require('path') // var BrowserSyncPlugin = require('browser-sync-webpack-plugin') ///////////////////////////////////////////////////////////////////////////////////// // config ///////////////////////////////////////////////////////////////////////////////////// var config = require('./_config') var projectRoot = config.projectRoot var options = config.webpack var dir = config.dir var entry = require('./_config/modules/entry') // entry file's object ///////////////////////////////////////////////////////////////////////////////////// // plugins ///////////////////////////////////////////////////////////////////////////////////// var plugins = PROD ? [ new webpack.optimize.AggressiveMergingPlugin(), new webpack.optimize.OccurrenceOrderPlugin() ] : [ new webpack.NoEmitOnErrorsPlugin() ] var commonPlugins = [ // new BrowserSyncPlugin(options.BrowserSyncPlugin), new ExtractTextPlugin('[name]'), new webpack.LoaderOptionsPlugin(options.LoaderOptionsPlugin) // new webpack.LoaderOptionsPlugin(options.pugLoader) ] plugins = plugins.concat(commonPlugins) ///////////////////////////////////////////////////////////////////////////////////// // output a list like 'entryFile => bundleFile' to the console ///////////////////////////////////////////////////////////////////////////////////// var bundleLog = require('./_config/modules/bundle-log') bundleLog() ///////////////////////////////////////////////////////////////////////////////////// // webpack.config ///////////////////////////////////////////////////////////////////////////////////// module.exports = { resolve: { modules: [ 'node_modules', 'modules' ], alias: { } }, cache: !PROD, entry: entry, output: { path: dir.abs.dist, filename: '[name]' }, plugins: plugins, externals: { jquery: 'jQuery' }, module: { rules: [ { test: /\.scss$/, use: ExtractTextPlugin.extract([ { loader: 'css-loader', options: options.cssLoader }, { loader: 'pleeease-loader' }, { loader: 'resolve-url-loader' }, { loader: 'sass-loader', options: options.sassLoader } ]) }, { test: /\.css$/, use: [ { loader: 'css-loader' } ] }, { test: /\.(jpe?g|png|gif|svg)$/, use: [ { loader: 'url-loader', options: options.urlLoader }, { loader: 'img-loader', options: options.imgLoader } ] }, { test: /\.(ttf|otf|eot|woff(2)?)(\?[a-z0-9]+)?$/, use: { loader: 'url-loader', options: options.urlLoader } } ] } }
// jquery.gohashurl.js // copyright Jiangshui // website http://yujiangshui.com // contact yujiangshui@gmail.com // https://github.com/yujiangshui/jquery.gourlhash.js ;(function($) { $.extend({ 'gohashurl': function(options){ options = jQuery.extend({ target: '', topfixed: '', offset: 10, duration: 200, easing: 'linear' },options); var hashtarget = options.target || location.hash || 'body', topfixedtarget = options.topfixed, hashtarget_top = $(hashtarget).length ? $(hashtarget).offset().top : $('a[name='+hashtarget.substring(1)+']').offset().top, //获取目标元素的高度位置 topfixed_top = $(topfixedtarget).height() || 0, current_top = hashtarget_top - topfixed_top - options.offset; //获得要滚动的正确高度 if( options.duration == 0 ) options.duration = 1; //修正时间间隔为 0 的Bug $('body,html').animate({ scrollTop: current_top }, options.duration, options.easing); } }); })(jQuery);
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.lang['mk'] = { "editor": "Rich Text Editor", "editorPanel": "Rich Text Editor panel", "common": { "editorHelp": "Притисни ALT 0 за помош", "browseServer": "Пребарај низ серверот", "url": "URL", "protocol": "Протокол", "upload": "Прикачи", "uploadSubmit": "Прикачи на сервер", "image": "Слика", "flash": "Flash", "form": "Form", "checkbox": "Checkbox", "radio": "Radio Button", "textField": "Поле за текст", "textarea": "Големо поле за текст", "hiddenField": "Скриено поле", "button": "Button", "select": "Selection Field", "imageButton": "Копче-слика", "notSet": "<not set>", "id": "Id", "name": "Name", "langDir": "Насока на јазик", "langDirLtr": "Лево кон десно", "langDirRtl": "Десно кон лево", "langCode": "Код на јазик", "longDescr": "Long Description URL", "cssClass": "Stylesheet Classes", "advisoryTitle": "Advisory Title", "cssStyle": "Стил", "ok": "OK", "cancel": "Cancel", "close": "Close", "preview": "Preview", "resize": "Resize", "generalTab": "Општо", "advancedTab": "Advanced", "validateNumberFailed": "This value is not a number.", "confirmNewPage": "Any unsaved changes to this content will be lost. Are you sure you want to load new page?", "confirmCancel": "You have changed some options. Are you sure you want to close the dialog window?", "options": "Опции", "target": "Target", "targetNew": "Нов прозорец (_blank)", "targetTop": "Најгорниот прозорец (_top)", "targetSelf": "Истиот прозорец (_self)", "targetParent": "Прозорец-родител (_parent)", "langDirLTR": "Лево кон десно", "langDirRTL": "Десно кон лево", "styles": "Стил", "cssClasses": "Stylesheet Classes", "width": "Широчина", "height": "Височина", "align": "Alignment", "alignLeft": "Лево", "alignRight": "Десно", "alignCenter": "Во средина", "alignJustify": "Justify", "alignTop": "Горе", "alignMiddle": "Средина", "alignBottom": "Доле", "alignNone": "Никое", "invalidValue": "Невалидна вредност", "invalidHeight": "Височината мора да биде број.", "invalidWidth": "Широчината мора да биде број.", "invalidCssLength": "Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).", "invalidHtmlLength": "Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).", "invalidInlineStyle": "Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.", "cssLengthTooltip": "Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).", "unavailable": "%1<span class=\"cke_accessibility\">, unavailable</span>", "keyboard": { "8": "Backspace", "13": "Enter", "16": "Shift", "17": "Ctrl", "18": "Alt", "32": "Space", "35": "End", "36": "Home", "46": "Delete", "224": "Command" }, "keyboardShortcut": "Keyboard shortcut" }, "about": { "copy": "Авторски права &copy; $1. Сите права се задржани.", "dlgTitle": "За CKEditor", "help": "Отворете $1 за помош.", "moreInfo": "За информации околу лиценцата, ве молиме посетете го нашиот веб-сајт: ", "title": "За CKEditor", "userGuide": "CKEditor упатство за корисници" }, "basicstyles": { "bold": "Здебелено", "italic": "Накривено", "strike": "Прецртано", "subscript": "Долен индекс", "superscript": "Горен индекс", "underline": "Подвлечено" }, "blockquote": {"toolbar": "Одвоен цитат"}, "clipboard": { "copy": "Копирај (Copy)", "copyError": "Опциите за безбедност на вашиот прелистувач не дозволуваат уредувачот автоматски да изврши копирање. Ве молиме употребете ја тастатурата. (Ctrl/Cmd+C)", "cut": "Исечи (Cut)", "cutError": "Опциите за безбедност на вашиот прелистувач не дозволуваат уредувачот автоматски да изврши сечење. Ве молиме употребете ја тастатурата. (Ctrl/Cmd+C)", "paste": "Залепи (Paste)", "pasteArea": "Простор за залепување", "pasteMsg": "Ве молиме да залепите во следниот квадрат користејќи ја тастатурата (<string>Ctrl/Cmd+V</string>) и да притиснете OK", "securityMsg": "Опциите за безбедност на вашиот прелистувач не дозволуваат уредувачот директно да пристапи до копираните податоци. Потребно е повторно да се обидете во овој прозорец.", "title": "Залепи (Paste)" }, "contextmenu": {"options": "Контекст-мени опции"}, "button": {"selectedLabel": "%1 (Selected)"}, "toolbar": { "toolbarCollapse": "Collapse Toolbar", "toolbarExpand": "Expand Toolbar", "toolbarGroups": { "document": "Document", "clipboard": "Clipboard/Undo", "editing": "Editing", "forms": "Forms", "basicstyles": "Basic Styles", "paragraph": "Paragraph", "links": "Links", "insert": "Insert", "styles": "Styles", "colors": "Colors", "tools": "Tools" }, "toolbars": "Editor toolbars" }, "elementspath": {"eleLabel": "Elements path", "eleTitle": "%1 element"}, "format": { "label": "Format", "panelTitle": "Paragraph Format", "tag_address": "Address", "tag_div": "Normal (DIV)", "tag_h1": "Heading 1", "tag_h2": "Heading 2", "tag_h3": "Heading 3", "tag_h4": "Heading 4", "tag_h5": "Heading 5", "tag_h6": "Heading 6", "tag_p": "Normal", "tag_pre": "Formatted" }, "horizontalrule": {"toolbar": "Insert Horizontal Line"}, "image": { "alt": "Алтернативен текст", "border": "Раб", "btnUpload": "Прикачи на сервер", "button2Img": "Дали сакате да направите сликата-копче да биде само слика?", "hSpace": "Хоризонтален простор", "img2Button": "Дали сакате да ја претворите сликата во слика-копче?", "infoTab": "Информации за сликата", "linkTab": "Врска", "lockRatio": "Зачувај пропорција", "menu": "Својства на сликата", "resetSize": "Ресетирај големина", "title": "Својства на сликата", "titleButton": "Својства на копче-сликата", "upload": "Прикачи", "urlMissing": "Недостасува URL-то на сликата.", "vSpace": "Вертикален простор", "validateBorder": "Работ мора да биде цел број.", "validateHSpace": "Хор. простор мора да биде цел број.", "validateVSpace": "Верт. простор мора да биде цел број." }, "indent": {"indent": "Increase Indent", "outdent": "Decrease Indent"}, "fakeobjects": { "anchor": "Anchor", "flash": "Flash Animation", "hiddenfield": "Скриено поле", "iframe": "IFrame", "unknown": "Unknown Object" }, "link": { "acccessKey": "Access Key", "advanced": "Advanced", "advisoryContentType": "Advisory Content Type", "advisoryTitle": "Advisory Title", "anchor": { "toolbar": "Anchor", "menu": "Edit Anchor", "title": "Anchor Properties", "name": "Anchor Name", "errorName": "Please type the anchor name", "remove": "Remove Anchor" }, "anchorId": "By Element Id", "anchorName": "By Anchor Name", "charset": "Linked Resource Charset", "cssClasses": "Stylesheet Classes", "download": "Force Download", "displayText": "Display Text", "emailAddress": "E-Mail Address", "emailBody": "Message Body", "emailSubject": "Message Subject", "id": "Id", "info": "Link Info", "langCode": "Код на јазик", "langDir": "Насока на јазик", "langDirLTR": "Лево кон десно", "langDirRTL": "Десно кон лево", "menu": "Edit Link", "name": "Name", "noAnchors": "(No anchors available in the document)", "noEmail": "Please type the e-mail address", "noUrl": "Please type the link URL", "other": "<other>", "popupDependent": "Dependent (Netscape)", "popupFeatures": "Popup Window Features", "popupFullScreen": "Full Screen (IE)", "popupLeft": "Left Position", "popupLocationBar": "Location Bar", "popupMenuBar": "Menu Bar", "popupResizable": "Resizable", "popupScrollBars": "Scroll Bars", "popupStatusBar": "Status Bar", "popupToolbar": "Toolbar", "popupTop": "Top Position", "rel": "Relationship", "selectAnchor": "Select an Anchor", "styles": "Стил", "tabIndex": "Tab Index", "target": "Target", "targetFrame": "<frame>", "targetFrameName": "Target Frame Name", "targetPopup": "<popup window>", "targetPopupName": "Popup Window Name", "title": "Врска", "toAnchor": "Link to anchor in the text", "toEmail": "E-mail", "toUrl": "URL", "toolbar": "Врска", "type": "Link Type", "unlink": "Unlink", "upload": "Прикачи" }, "list": {"bulletedlist": "Insert/Remove Bulleted List", "numberedlist": "Insert/Remove Numbered List"}, "magicline": {"title": "Insert paragraph here"}, "maximize": {"maximize": "Maximize", "minimize": "Minimize"}, "pastetext": {"button": "Paste as plain text", "title": "Paste as Plain Text"}, "pastefromword": { "confirmCleanup": "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?", "error": "It was not possible to clean up the pasted data due to an internal error", "title": "Paste from Word", "toolbar": "Paste from Word" }, "removeformat": {"toolbar": "Remove Format"}, "sourcearea": {"toolbar": "Source"}, "specialchar": { "options": "Special Character Options", "title": "Select Special Character", "toolbar": "Insert Special Character" }, "scayt": { "btn_about": "About SCAYT", "btn_dictionaries": "Dictionaries", "btn_disable": "Disable SCAYT", "btn_enable": "Enable SCAYT", "btn_langs": "Languages", "btn_options": "Options", "text_title": "Spell Check As You Type" }, "stylescombo": { "label": "Styles", "panelTitle": "Formatting Styles", "panelTitle1": "Block Styles", "panelTitle2": "Inline Styles", "panelTitle3": "Object Styles" }, "table": { "border": "Border size", "caption": "Caption", "cell": { "menu": "Cell", "insertBefore": "Insert Cell Before", "insertAfter": "Insert Cell After", "deleteCell": "Delete Cells", "merge": "Merge Cells", "mergeRight": "Merge Right", "mergeDown": "Merge Down", "splitHorizontal": "Split Cell Horizontally", "splitVertical": "Split Cell Vertically", "title": "Cell Properties", "cellType": "Cell Type", "rowSpan": "Rows Span", "colSpan": "Columns Span", "wordWrap": "Word Wrap", "hAlign": "Horizontal Alignment", "vAlign": "Vertical Alignment", "alignBaseline": "Baseline", "bgColor": "Background Color", "borderColor": "Border Color", "data": "Data", "header": "Header", "yes": "Yes", "no": "No", "invalidWidth": "Cell width must be a number.", "invalidHeight": "Cell height must be a number.", "invalidRowSpan": "Rows span must be a whole number.", "invalidColSpan": "Columns span must be a whole number.", "chooseColor": "Choose" }, "cellPad": "Cell padding", "cellSpace": "Cell spacing", "column": { "menu": "Column", "insertBefore": "Insert Column Before", "insertAfter": "Insert Column After", "deleteColumn": "Delete Columns" }, "columns": "Columns", "deleteTable": "Delete Table", "headers": "Headers", "headersBoth": "Both", "headersColumn": "First column", "headersNone": "None", "headersRow": "First Row", "invalidBorder": "Border size must be a number.", "invalidCellPadding": "Cell padding must be a positive number.", "invalidCellSpacing": "Cell spacing must be a positive number.", "invalidCols": "Number of columns must be a number greater than 0.", "invalidHeight": "Table height must be a number.", "invalidRows": "Number of rows must be a number greater than 0.", "invalidWidth": "Table width must be a number.", "menu": "Table Properties", "row": { "menu": "Row", "insertBefore": "Insert Row Before", "insertAfter": "Insert Row After", "deleteRow": "Delete Rows" }, "rows": "Rows", "summary": "Summary", "title": "Table Properties", "toolbar": "Table", "widthPc": "percent", "widthPx": "pixels", "widthUnit": "width unit" }, "undo": {"redo": "Redo", "undo": "Undo"}, "wsc": { "btnIgnore": "Ignore", "btnIgnoreAll": "Ignore All", "btnReplace": "Replace", "btnReplaceAll": "Replace All", "btnUndo": "Undo", "changeTo": "Change to", "errorLoading": "Error loading application service host: %s.", "ieSpellDownload": "Spell checker not installed. Do you want to download it now?", "manyChanges": "Spell check complete: %1 words changed", "noChanges": "Spell check complete: No words changed", "noMispell": "Spell check complete: No misspellings found", "noSuggestions": "- No suggestions -", "notAvailable": "Sorry, but service is unavailable now.", "notInDic": "Not in dictionary", "oneChange": "Spell check complete: One word changed", "progress": "Spell check in progress...", "title": "Spell Checker", "toolbar": "Check Spelling" } };
var express = require('express'); var mongoose = require('mongoose'); var moment = require('moment'); var bodyParser = require('body-parser'); var Point = require('./point.js'); var app = express(); app.use(bodyParser.json()); if (process.env.DEBUG) { mongoose.connect('mongodb://localhost/tracker'); } else { mongoose.connect(process.env.MONGO_URL); } var authenticate = function(req, res, next) { var token = req.get('X-Auth-Token'); var tokenIsCorrect = process.env.TOKEN !== undefined && token === process.env.TOKEN; var pathRequiresAuthentication = req.path !== '/points/latest'; if (!tokenIsCorrect && pathRequiresAuthentication) { return res.status(401).json({ error: '401 Unauthorized' }); } if (tokenIsCorrect) { req.authenticated = true; } next(); }; app.all('*', authenticate); app.get('/', function (req, res) { res.json({}); }); app.post('/points', function (req, res, next) { var point = new Point({ name: req.body.name, inside: req.body.inside, date: moment(req.body.date), coordinates: [req.body.longitude, req.body.latitude] }); point.save(function (err) { if (err) return next(err); res.status(201).json(point); }); }); app.get('/points', function (req, res, next) { Point.find().sort({ date: -1 }).exec(function(err, points) { if (err) return next(err); res.json(points); }); }); app.get('/points/latest', function (req, res, next) { Point.findOne().sort({ date: -1 }).exec(function(err, point) { if (err) return next(err); if (req.authenticated) { res.json(point); } else { res.jsonp({ name: point.name, inside: point.inside }); } }); }); var port = process.env.PORT || 3000; app.listen(port, function () { console.log('App listening on port ' + port + '.'); });
var winston = require('winston'); require('newrelic'); // // Requiring `winston-papertrail` will expose // `winston.transports.Papertrail` var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); var sprintf = require('sprintf').sprintf; var sscanf = require('scanf').sscanf; var AWS = require('aws-sdk'); AWS.config.update({ accessKeyId: 'YOURKEYS', secretAccessKey: 'YOURKEYS' }); var s3 = new AWS.S3(); var urlParser = require('url'); var testVideoId = '1766429771001'; var knox = require('knox'); //AWS.config.loadFromPath('./aws-config.json'); AWS.config.region = 'us-east-1'; var testbcd = '1800831757001'; var __dirname; /** * Don't hard-code your credentials! * Export the following environment variables instead: * * export AWS_ACCESS_KEY_ID='AKID' * export AWS_SECRET_ACCESS_KEY='SECRET' */ // all environments app.set('port', process.env.PORT || 3031); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(require('stylus').middleware(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); port = app.get('port'); var queue = require("queue-async"); var brightcoveQueryStrings = { host: "http://api.brightcove.com/", TagQuery:'/services/library?command=search_videos&token=&any=tag%s&get_item_count=true&media_delivery=http&page_number=%s', IdQuery: '/services/library?command=find_video_by_id&video_id=%s&media_delivery=http&token=', createTagQuery: function (userId, pageNumber, bcId) { if( bcId == undefined || bcId.length == 0) { return sprintf(this.TagQuery, encodeURIComponent(':##@' + userId + '##@'), pageNumber); } else { return sprintf(this.IdQuery, bcId, pageNumber); } }, createBidQuery: function (bcd) { return sprintf(this.bidQuery, bcd) }, }; function downloadFromBcAndUploadToS3(url, outputPath, jobId, _options, cb) { // console.log("beggining download of " + outputPath + " " + jobId) var params_for_head_request = { Bucket: 'lfe-user-videos', /* required */ Key: outputPath, }; function downloadFileFromBc(url, _options, cb) { http.get(url, function (res) { var params = { Bucket: 'lfe-user-videos', /* required */ Key: outputPath, ACL: 'public-read', Body: res, ContentType: res.headers['content-type'], ContentLength: res.headers['content-length'], }; var firstRequestInFile = true; res.on("socket", function (socket) { console.log("onsocket"); }); res.on("connect", function (socket) { console.log("onsocket"); }); res.on("connection", function (socket) { console.log("onsocket"); }); res.on("error", function (socket) { console.error(" data error error must retry"); }); s3.upload(params, function (data, err) { if (err) console.log(err, err.stack); // an error occurred else { } cb(data, _options); }); }); } function preformHeadRequest(url, callback){ var parsedUrl = urlParser.parse(url); var optionsHttp = { hostname: parsedUrl.hostname, port: parsedUrl.port || 80, path: parsedUrl.pathname, method: 'HEAD' }; http.get(optionsHttp, function (response) { callback(response.headers) }); } s3.headObject(params_for_head_request, function(err, data) { if(err == null){ if(_options.size) { if (data.ContentLength == _options.size) { cb(); return; } else { console.log("file found in s3 but size missmatch redownloading " + url); downloadFileFromBc(url, _options, cb); } }else{ preformHeadRequest(url, function(headers) { var contentLength = headers['content-length']; if(contentLength != data.ContentLength){ console.log("content length is different re-downloading " + url); downloadFileFromBc(url, _options, cb); }else{ cb(); } }); } }else{ console.log("file not found in s3 downloading " + url); downloadFileFromBc(url, _options, cb); } }); } initHttpServer(); //testPostMethod(); app.get('/', function (req, res) { res.send("Ok"); }); app.get('/toggle/:id', testToggle); function executeMediaApiQuery(userId, pageNumber, bcId, callback) { var a = { host: 'api.brightcove.com', path: brightcoveQueryStrings.createTagQuery(userId, pageNumber, bcId) }; var err = ""; var combniedItemList = []; http.get(a, function (response) { // Continuously update stream with data var body = ''; response.on('data', function (d) { body += d; }); response.on('error', function (d) { err = d; }); response.on('end', function () { var parsedBody = JSON.parse(body); callback(parsedBody, pageNumber, err); }); }); } function queryBrightCoveForUserVideos(userId, bcId, finalCallback) { var pageNumber = 0; var combinedArray = []; var err = ""; var combinedJSON = {}; function executePagedQuery(jsonResult, pageNumber, bcId, err1) { err += err1; combinedArray = combinedArray.concat(jsonResult.items); if(jsonResult.total_count == 0){ finalCallback(combinedArray, err); return; } if (combinedArray.length < (jsonResult.total_count || Infinity)) { pageNumber++; executeMediaApiQuery(userId, pageNumber,bcId, executePagedQuery, err); } else { finalCallback(combinedArray, err); } } if(bcId.length ==0) return executePagedQuery(combinedArray, -1); else{ executeMediaApiQuery(userId, pageNumber,bcId, function(jsonResult){ finalCallback(['huj', jsonResult], err); }); } } var q = queue(15); function uploadAJob(req, _item, i, launchedJobIndex, renditionReporter, callback) { var amazonPath = req.body['userId'] + "/" + _item.id + "/" + _item.renditions[i].id + "/" + _item.renditions[i].id + "." + _item.renditions[i].videoContainer; var location = req.body['userId'] + "/" + _item.id + "/"; var url = _item.renditions[i].url; //console.log('Launching job #' + launchedJobIndex + " " + amazonPath); //function downloadFromBcAndUploadToS3(url, outputPath, jobId, metaData, cb) var options = { rendition: _item.renditions[i], amazonPath: amazonPath, item: _item, location: location, size: _item.renditions[i].size }; downloadFromBcAndUploadToS3(_item.renditions[i].url, amazonPath, launchedJobIndex, options, function (data, option, err) { if(option != undefined && option != null) { option.rendition.BcId = option.item.id; option.rendition.location = option.location; option.rendition.S3Url = "https://s3.amazonaws.com/lfe-user-videos/" + option.amazonPath; option.rendition.CloudFrontPath = "http://uservideos.lfe.com/" + option.amazonPath option.rendition.numberOfRenditions = option.item.renditions.length; renditionReporter(option.rendition); } callback(); }); } function processQueuedJobs(videosToDownload, req, res,renditionReporter) { var queuedJobIndex = 0; var launchedJobIndex= 0; for(index=1; index<videosToDownload.length; index++){ item = videosToDownload[index]; q.defer(function(cb) { downloadFromBcAndUploadToS3(item.videoStillURL, req.body['userId'] + "/" + item.id + "/still.jpg", 0, { }, function (err) { cb(); }); }); q.defer(function (cb) { downloadFromBcAndUploadToS3(item.thumbnailURL, req.body['userId'] + "/" + item.id + "/thumbnail.jpg", 0, {}, function (ee) { cb(); }); }); for (i = 0; i < item.renditions.length; i++) { var rendition = item.renditions[i]; var re = /(?:\.([^.]+))?$/; queuedJobIndex++; q.defer(uploadAJob, req, item, i, launchedJobIndex, renditionReporter ); //function (_item, i, launchedJobIndex, callback, cb) { //} launchedJobIndex++; } } console.log("queuing jobs " + queuedJobIndex ); res.status(202).send('All qeued'); } app.post('/downloadUserVideos', function (req, res) { var qStarted = false; var video; var uId = req.body['userId']; var host = req.body['host']; var path = req.body['path']; var port = req.body['port']; var bcId = req.body['bcId']; if(bcId == undefined) bcId=""; console.log("Got a request Uid " + uId + " HOST" + host +" path " + path + " port" + port + " bcid " + bcId); //console.log(req.headers); // console.log(req.body); // final callback queryBrightCoveForUserVideos(uId, bcId, function (combinedArray, err, combinedJSON){ processQueuedJobs(combinedArray, req, res, function renditionReporter(renditionResponse){ var jsonPostData = JSON.stringify(renditionResponse); var options = { hostname: host, port: port, path: path, method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': jsonPostData.length, } }; try { var req = http.request(options); }catch(e){ console.log('connection exception : ' + e); req.end(); return; } //console.log("sendin response " + jsonPostData); req.on('error', function (e) { console.log('problem with request: ' + e.message); }); req.write(jsonPostData); req.end(); }); // console.dir(cominedArray); }) q.awaitAll(function (error, results) { console.log("all done!"); }); }); function initHttpServer() { console.log('Starting http server:', app.get('port')); http.createServer(app).listen(app.get('port'), function (error, result) { console.log('http.createServer(app) callback', arguments); console.log('Express server listening on port ' + app.get('port')); }); } function testToggle (req, res) { var userId = req.params.id; var bcid = req.query.bcid; runTransferJobs(userId, bcid ); console.log('Toggle GET started jobs with userId: ' + userId); res.send("Ok"); } function runTransferJobs (id, bcid) { var postData = { userId: id, bcId: bcid, host: '', path: '', }; //var postData = { // UserId: '422', // callbackHost: '', // callbackPath: '' //}; var jsonPostData = JSON.stringify(postData); var options = { hostname: 'localhost', port: app.get('port'), path: '/downloadUserVideos', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': jsonPostData.length, 'Connection': 'Keep-Alive' } }; var req = http.request(options); req.on('error', function (e) { console.log('problem with request: ' + e.message); }); req.write(jsonPostData); req.end(); }
angular.module('dotametrics') .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/denies', { controller: 'DeniesController', templateUrl: 'templates/denies.html' }) .when('/cs', { controller: 'csController', templateUrl: 'templates/cs.html' }) .when('/lasthits', { controller: 'LastHitsController', templateUrl: 'templates/lasthits.html' }) .when('/kda', { controller: 'KdaController', templateUrl: 'templates/kda.html' }) .when('/runes', { controller: 'RunesController', templateUrl: 'templates/runes.html' }) } ]);
/*! * @module report * @author kael * @date @DATE * Copyright (c) 2014 kael,chriscai * Licensed under the MIT license. */ var BJ_REPORT = (function(global) { if (global.BJ_REPORT) return global.BJ_REPORT; var _error = []; var orgError = global.onerror; global.onerror = function(msg, url, line, col, error) { var newMsg = msg; if(error && error.stack){ newMsg = _processStackMsg(error); } if(_isOBJByType(newMsg , "Event")){ newMsg += newMsg.type?('--'+newMsg.type +'--' + (newMsg.target ? (newMsg.target.tagName + "::" + newMsg.target.src):"")) : ""; } report.push({ msg: newMsg, target: url, rowNum: line, colNum: col /*error : error*/ /* stack : stack*/ }); _send(); orgError && orgError.apply(global, arguments); }; var _config = { id: 0, uin: 0, url: "", combo: 1, ext: {}, level: 4, // 1-debug 2-info 4-error 8-fail ignore: [], random : 1, delay: 1000, submit: null }; var _isOBJByType = function(o, type) { return Object.prototype.toString.call(o) === "[object " + (type || "Object") + "]"; }; var _isOBJ = function(obj) { var type = typeof obj; return type === 'object' && !!obj; }; var _processError = function ( errObj){ try { if (errObj.stack) { var url = errObj.stack.match('http://[^\n]+'); url = url ? url[0] : ""; var rowCols = url.match(':([0-9]+):([0-9]+)'); if(!rowCols ){ rowCols= [0 , 0 ,0]; } var stack = _processStackMsg(errObj); return { msg: stack, rowNum: rowCols[1], colNum: rowCols[2], target: url.replace(rowCols[0], '') /* stack : stack*/ }; } else { return errObj; } } catch (err) { return errObj; } }; var _processStackMsg = function ( error){ var stack = error.stack.replace(/\n/gi, '').split(/\bat\b/).slice(0,5).join("@").replace(/\?[^:]+/gi , ""); var msg = error.toString(); if(stack.indexOf(msg) <0){ stack = msg +"@" + stack; } return stack; }; var _error_tostring = function(error, index) { var param = []; var params = []; var stringify = []; if (_isOBJ(error)) { error.level = error.level || _config.level; for (var key in error) { var value = error[key] || ""; if (value) { if (_isOBJ(value)) { try { value = JSON.stringify(value); } catch (err) { value = "[BJ_REPORT detect value stringify error] " + err.toString(); } } stringify.push(key + ":" + value); param.push(key + "=" + encodeURIComponent(value)); params.push(key + "[" + index + "]=" + encodeURIComponent(value)); } } } // msg[0]=msg&target[0]=target -- combo report // msg:msg,target:target -- ignore // msg=msg&target=target -- report with out combo return [params.join("&"), stringify.join(","), param.join("&")]; }; var _imgs = []; var _submit = function(url) { if (_config.submit) { _config.submit(url); } else { var _img = new Image(); _imgs.push(_img); _img.src = url; } }; var error_list = []; var comboTimeout = 0; var _send = function(isReoprtNow) { if (!_config.report) return; while (_error.length) { var isIgnore = false; var error = _error.shift(); var error_str = _error_tostring(error, error_list.length); for (var i = 0, l = _config.ignore.length; i < l; i++) { var rule = _config.ignore[i]; if ((_isOBJByType(rule, "RegExp") && rule.test(error_str[1])) || (_isOBJByType(rule, "Function") && rule(error, error_str[1]))) { isIgnore = true; break; } } if (!isIgnore) { if (_config.combo) { error_list.push(error_str[0]); } else { _submit(_config.report + error_str[2] + "&_t=" + (+new Date)); } _config.onReport && (_config.onReport(_config.id, error)); } } // 合并上报 var count = error_list.length; if (count) { var comboReport = function(){ clearTimeout(comboTimeout); _submit(_config.report + error_list.join("&") + "&count=" + count + "&_t=" + (+new Date)); comboTimeout = 0; error_list = []; }; if (isReoprtNow) { comboReport(); // 立即上报 } else if (!comboTimeout) { comboTimeout = setTimeout(comboReport, _config.delay); // 延迟上报 } } }; var report = { push: function(msg) { // 将错误推到缓存池 if(Math.random() >= _config.random){ return report; } _error.push(_isOBJ(msg) ? _processError(msg) : { msg: msg }); _send(); return report; }, report: function(msg) { // error report msg && report.push(msg); _send(true); return report; }, info: function(msg) { // info report if(!msg){ return report; } if(_isOBJ(msg)){ msg.level = 2; }else { msg = {msg : msg , level :2}; } report.push(msg); return report; }, debug: function(msg) { // debug report if(!msg){ return report; } if(_isOBJ(msg)){ msg.level = 1; }else { msg = {msg : msg , level :1}; } report.push(msg); return report; }, init: function(config) { // 初始化 if (_isOBJ(config)) { for (var key in config) { _config[key] = config[key]; } } // 没有设置id将不上报 var id = parseInt(_config.id, 10); if (id) { _config.report = (_config.url || "http://badjs.vip.qq.com/badjs") + "?id=" + id + "&uin=" + parseInt(_config.uin || (document.cookie.match(/\buin=\D+(\d+)/) || [])[1], 10) + "&from=" + encodeURIComponent(location.href) + "&ext=" + JSON.stringify(_config.ext) +"&"; } return report; }, __onerror__ : global.onerror }; return report; }(window)); if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = BJ_REPORT; } exports.BJ_REPORT = BJ_REPORT; } ;(function (root) { if (!root.BJ_REPORT) { return; } var _onthrow = function (errObj) { root.BJ_REPORT.report(errObj); }; var tryJs = root.BJ_REPORT.tryJs = function init(throwCb) { throwCb && ( _onthrow =throwCb ); return tryJs; }; // merge var _merge = function (org, obj) { var key; for (key in obj) { org[key] = obj[key]; } }; // function or not var _isFunction = function (foo) { return typeof foo === 'function'; }; var cat = function (foo, args) { return function () { try { return foo.apply(this, args || arguments); } catch (error) { _onthrow(error); //some browser throw error (chrome) , can not find error where it throw, so print it on console; if( error.stack && console && console.error){ console.error("[BJ-REPORT]" , error.stack); } // hang up browser and throw , but it should trigger onerror , so rewrite onerror then recover it var orgOnerror = root.onerror; root.onerror = function (){}; setTimeout(function(){ root.onerror = orgOnerror; },50); throw error; } }; }; var catArgs = function (foo) { return function () { var arg, args = []; for (var i = 0, l = arguments.length; i < l; i++) { arg = arguments[i]; _isFunction(arg) && (arg = cat(arg)); args.push(arg); } return foo.apply(this, args); }; }; var catTimeout = function (foo) { return function (cb, timeout) { // for setTimeout(string, delay) if (typeof cb === 'string') { try { cb = new Function(cb); } catch (err) { throw err; } } var args = [].slice.call(arguments, 2); // for setTimeout(function, delay, param1, ...) cb = cat(cb, args.length && args); return foo(cb, timeout); }; }; /** * makeArgsTry * wrap a function's arguments with try & catch * @param {Function} foo * @param {Object} self * @returns {Function} */ var makeArgsTry = function (foo, self) { return function () { var arg, tmp, args = []; for (var i = 0, l = arguments.length; i < l; i++) { arg = arguments[i]; _isFunction(arg) && (tmp = cat(arg)) && (arg.tryWrap = tmp) && (arg = tmp); args.push(arg); } return foo.apply(self || this, args); }; }; /** * makeObjTry * wrap a object's all value with try & catch * @param {Function} foo * @param {Object} self * @returns {Function} */ var makeObjTry = function (obj) { var key, value; for (key in obj) { value = obj[key]; if (_isFunction(value)) obj[key] = cat(value); } return obj; }; /** * wrap jquery async function ,exp : event.add , event.remove , ajax * @returns {Function} */ tryJs.spyJquery = function () { var _$ = root.$; if (!_$ || !_$.event) { return tryJs; } var _add = _$.event.add, _ajax = _$.ajax, _remove = _$.event.remove; if (_add) { _$.event.add = makeArgsTry(_add); _$.event.remove = function () { var arg, args = []; for (var i = 0, l = arguments.length; i < l; i++) { arg = arguments[i]; _isFunction(arg) && (arg = arg.tryWrap); args.push(arg); } return _remove.apply(this, args); }; } if (_ajax) { _$.ajax = function (url, setting) { if (!setting) { setting = url; url = undefined; } makeObjTry(setting); if (url) return _ajax.call(_$, url, setting); return _ajax.call(_$, setting); }; } return tryJs; }; /** * wrap amd or commonjs of function ,exp : define , require , * @returns {Function} */ tryJs.spyModules = function () { var _require = root.require, _define = root.define; if (_define && _define.amd && _require) { root.require = catArgs(_require); _merge(root.require, _require); root.define = catArgs(_define); _merge(root.define, _define); } if ( root.seajs && _define ) { root.define = function () { var arg, args = []; for (var i = 0, l = arguments.length; i < l; i++) { arg = arguments[i]; if(_isFunction(arg)){ arg = cat(arg); //seajs should use toString parse dependencies , so rewrite it arg.toString =(function (orgArg){ return function (){ return orgArg.toString(); }; }(arguments[i])); } args.push(arg); } return _define.apply(this, args); }; _merge(root.define, _define); } return tryJs; }; /** * wrap async of function in window , exp : setTimeout , setInterval * @returns {Function} */ tryJs.spySystem = function () { root.setTimeout = catTimeout(root.setTimeout); root.setInterval = catTimeout(root.setInterval); return tryJs; }; /** * wrap custom of function , * @param obj - obj or function * @returns {Function} */ tryJs.spyCustom = function (obj) { if (_isFunction(obj)) { return cat(obj); } else { return makeObjTry(obj); } }; /** * run spyJquery() and spyModules() and spySystem() * @returns {Function} */ tryJs.spyAll = function () { tryJs.spyJquery().spyModules().spySystem(); return tryJs; }; }(window));
const random = require('./random'); const round = require('./round'); const config = require('../../config'); /** * get provider from list with load balance * @param {string} invokerDescription * @param {Array<Provider>} providers * @return {Provider} */ module.exports = (invokerDescription, providers) => { if (providers.length === 0) { throw new Error(`no provider for ${invokerDescription}`); } else if (providers.length === 1) { return providers[0]; } else { return config.getLoadBalance() === 'random' ? random(providers) : round(providers, invokerDescription); } };
/* global require, describe, it, before, after, beforeEach, afterEach */ 'use strict'; var path = require('path'), assert = require('chai').assert, async = require('async'), fse = require('fs-extra'); var nginx = require('..'); var prefixDir = 'tmp'; fse.emptyDirSync(prefixDir); fse.ensureFileSync(path.join(prefixDir, 'logs/error.log')); describe('Nginx test server', function () { this.slow(500); var server = nginx({ config: 'test/conf/nginx.conf', prefix: prefixDir // , log: console.log }); it('require option.config', function () { assert.throws(function () { nginx({}) }, /options.config/); }); it('start', function (done) { server.start(done); }); it('stop', function (done) { server.stop(done); }); it('multiple start-stop', function (done) { async.series([ server.start, server.stop, server.start, server.stop, server.start, server.stop, server.start, server.stop ], done); }); it('start callback is called only once', function (done) { var called = 0; server.start(() => { server.stop(() => called++); }); setTimeout(() => { assert.equal(called, 1); done(); }, 100); }); });
/* global module:false */ module.exports = function(grunt) { // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner: '/*!\n' + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + ' * http://lab.hakim.se/reveal-js\n' + ' * MIT licensed\n' + ' *\n' + ' * Copyright (C) 2013 Hakim El Hattab, http://hakim.se\n' + ' */' }, // Tests will be added soon qunit: { files: [ 'test/*.html' ] }, uglify: { options: { banner: '<%= meta.banner %>\n' }, build: { src: 'js/reveal.js', dest: 'js/reveal.min.js' } }, cssmin: { compress: { files: { 'css/reveal.min.css': [ 'css/reveal.css' ] } } }, sass: { main: { files: { 'css/theme/default.css': 'css/theme/source/default.scss', 'css/theme/beige.css': 'css/theme/source/beige.scss', 'css/theme/night.css': 'css/theme/source/night.scss', 'css/theme/serif.css': 'css/theme/source/serif.scss', 'css/theme/simple.css': 'css/theme/source/simple.scss', 'css/theme/sky.css': 'css/theme/source/sky.scss', 'css/theme/moon.css': 'css/theme/source/moon.scss', 'css/theme/solarized.css': 'css/theme/source/solarized.scss', 'css/theme/hootsuite.css': 'css/theme/source/hootsuite.scss' } } }, jshint: { options: { curly: false, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, eqnull: true, browser: true, expr: true, globals: { head: false, module: false, console: false } }, files: [ 'Gruntfile.js', 'js/reveal.js' ] }, connect: { server: { options: { port: 8000, base: '.' } } }, zip: { 'reveal-js-presentation.zip': [ 'index.html', 'css/**', 'js/**', 'lib/**', 'images/**', 'plugin/**' ] }, watch: { main: { files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], tasks: 'default' }, theme: { files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], tasks: 'themes' } } }); // Dependencies grunt.loadNpmTasks( 'grunt-contrib-qunit' ); grunt.loadNpmTasks( 'grunt-contrib-jshint' ); grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); grunt.loadNpmTasks( 'grunt-contrib-uglify' ); grunt.loadNpmTasks( 'grunt-contrib-watch' ); grunt.loadNpmTasks( 'grunt-contrib-sass' ); grunt.loadNpmTasks( 'grunt-contrib-connect' ); grunt.loadNpmTasks( 'grunt-zip' ); // Default task grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); // Theme task grunt.registerTask( 'themes', [ 'sass' ] ); // Package presentation to archive grunt.registerTask( 'package', [ 'default', 'zip' ] ); // Serve presentation locally grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); // Run tests grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); };
"use strict"; /** * Table head cell component will render th elements. The table head elements * can affect sorting of data if available on the field. * * Accepts following props: * - setSorting : {function} Function accepting single `key` argument to set * sorting for that key. * * - sorting : {object} Contains following keys, `key` and `direction`. See * TableHead component description for more info. * * - field : {object} Field object from the list of fields passed to Table */ export class TableHeadCell extends React.Component { constructor(props) { super(props); this.setSorting = this.setSorting.bind(this); } /** * Will only set sorting using props if the field is sortable * * @return {void} */ setSorting() { if(this.props.field.sortable !== true) { return; } this.props.setSorting(this.props.field.key); } render() { let classes = ["cell", this.props.field.key], sorting = this.props.sorting !== undefined ? this.props.sorting : {}, sortDirection = sorting.direction || 0; if(sortDirection > 0 && sorting.key === this.props.field.key) { classes.push("sort-ascending"); } else if(sortDirection < 0 && sorting.key === this.props.field.key) { classes.push("sort-descending"); } if(this.props.field.sortable === true) { classes.push("sortable"); } return ( <div className={classes.join(" ")} onClick={this.setSorting}> {this.props.field.label} </div> ); } }
document.getElementById('clear').addEventListener('click', () => { chrome.runtime.sendMessage({ type: 'CLEAR_STATE' }, (response) => { if (response.ok === true) { alert('Data cleared!'); // eslint-disable-line } }); }, false);
var Joke = require('./model.js'); var BaseController = require('../../classes/base_controller') var controller = new BaseController(Joke); controller.getComicJokes = function(req, reply) { return reply(Joke.query({ where: { comic_id: req.params.comic_id } }).fetchAll()); } module.exports = controller;
var fs = require('fs') ,httpGet = require('./http_get') ,ut = require('./ut') module.exports = function(filePath, cb){ if (ut.pathIsRemote(filePath)) { httpGet(filePath, function(err,data){ if (err) return cb(err); cb(false, data); }); } else { fs.readFile(filePath, function(err,data){ if (err) return cb(err); cb(false, data); }); } }
var mvcModulizer = function ( module ) { var moduleLoad = ("load" in module) ? module.load : null, moduleTimer = null, moduleInit = null; var dfd = $.Deferred(); // debug dfd.done( function () { //mvc.log("module ready",this); } ); dfd.fail( function () { mvc.log("module "+this.type+":"+this.id+" load failed m-s="+module.prop("status")); module.prop("status", "error"); } ); var resolve = function () { return dfd.resolveWith( module ); }; var reject = function () { return dfd.rejectWith( module ); }; $( module ) // todo: nahern? .on( "mvc:propUpdated:status", function () { if ( module.prop("status") === "ready" ) { return resolve(); } else if (module.prop("status") === "error") { return reject(); } } ); module.cast = function ( method ) { if ( !arguments.length ) { // todo: arguments throw "mvc.module.cast: no arguments"; } var cast = $.Deferred(), rejecter = function () { return cast.rejectWith( module ); }, args = ([]).slice.call(arguments,1), cast_method = function(){ if (typeof method === "string") { if (!(method in module)) { throw "mvc.module.cast: method["+method+"] not defined in module["+module.id+"]"; } } else if(typeof method === "function"){ return method; } else { throw "mvc.module.cast: incorrect method argument"; } return module[method]; }; //mvc.log("module.cast method=",method," args=",args); LIB.async( function () { module .load() .done( function(){ var res = cast_method().apply(module, args); if ( res instanceof Object && "promise" in res ) { res.done( function(){ cast.resolveWith(this, arguments); } ).fail( rejecter ); cast.pipe( res ); } else { cast.resolveWith(module, [res]); } } ) .fail( rejecter ); } ); return cast.promise(); }; module.load = function () { if (moduleTimer === null) { moduleInit = null; moduleTimer = window.setTimeout( function () { if ( moduleTimer ) { throw "moduleTimer " + module.id; } }, mvc.obj("mvc-config").prop( module.type + "-timeout-ms" ) ); moduleLoad .call( module ) .fail( reject ); } //mvc.log("load ",module.type," ",module.id); return dfd.promise(); }; module.get = function ( ) { // todo: arguments var arg = 1 in arguments[0] ? arguments[0][1] : null; if ( arg ) { /*console.log ("module.get( arg )", arg);*/ if ( moduleTimer ) { window.clearTimeout( moduleTimer ); } LIB.merge.call( module, arg ); var initRes = ("init" in module ? module.init() : true); //mvc.log("initRes", module, initRes); if ( initRes === true) { resolve(); } else if(initRes === false || initRes === void(0) ){ module.initRes = initRes; } else if("done" in initRes){ initRes .done( resolve ) .fail( reject ); } } return module; }; return module; };
// Regular expression that matches all symbols in the Bopomofo Extended block as per Unicode v7.0.0: /[\u31A0-\u31BF]/;
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import {withFrameSwitcher} from './util/storybookFrames.js'; import WorkshopCode from './WorkshopCode.js'; function testProps(props) { return { ...props, onInteraction: action('onInteraction'), onDone: action('onDone') }; } storiesOf('WorkshopCode', module) //eslint-disable-line no-undef .add('normal', () => { return withFrameSwitcher(<WorkshopCode {...testProps()} />); }) .add('shouldWarnAboutCodeStudio', () => { return withFrameSwitcher( <WorkshopCode shouldWarnAboutCodeStudio={true} {...testProps()} /> ); });
'use strict'; /* Services */ angular.module('whiteboardApp.services', []);
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize underscore exports="amd" -o ./underscore/` * Copyright 2012-2014 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.6.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ define(['../internals/baseCompareAscending', '../internals/baseEach', '../functions/createCallback'], function(baseCompareAscending, baseEach, createCallback) { /** * Used by `_.sortBy` to compare transformed elements of a collection and stable * sort them in ascending order. * * @private * @param {Object} object The object to compare to `other`. * @param {Object} other The object to compare to `object`. * @returns {number} Returns the sort order indicator for `object`. */ function compareAscending(object, other) { return baseCompareAscending(object.criteria, other.criteria) || object.index - other.index; } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through the callback. This method * performs a stable sort, that is, it will preserve the original sort order * of equal elements. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an array of property names is provided for `callback` the collection * will be sorted by each property value. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|Function|Object|string} [callback=identity] The function * called per iteration. If a property name or object is provided it will * be used to create a "_.pluck" or "_.where" style callback respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns the new sorted array. * @example * * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); * // => [3, 1, 2] * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 }, * { 'name': 'barney', 'age': 26 }, * { 'name': 'fred', 'age': 30 } * ]; * * // using "_.pluck" callback shorthand * _.map(_.sortBy(characters, 'age'), _.values); * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] * * // sorting by multiple properties * _.map(_.sortBy(characters, ['name', 'age']), _.values); * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] */ function sortBy(collection, callback, thisArg) { var index = -1, length = collection && collection.length, result = Array(length < 0 ? 0 : length >>> 0); callback = createCallback(callback, thisArg, 3); baseEach(collection, function(value, key, collection) { result[++index] = { 'criteria': callback(value, key, collection), 'index': index, 'value': value }; }); length = result.length; result.sort(compareAscending); while (length--) { result[length] = result[length].value; } return result; } return sortBy; });
// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. function toInt32(x) { return x | 0; } assertEquals(0, toInt32(Infinity), "Inf"); assertEquals(0, toInt32(-Infinity), "-Inf"); assertEquals(0, toInt32(NaN), "NaN"); assertEquals(0, toInt32(0.0), "zero"); assertEquals(0, toInt32(-0.0), "-zero"); assertEquals(0, toInt32(Number.MIN_VALUE)); assertEquals(0, toInt32(-Number.MIN_VALUE)); assertEquals(0, toInt32(0.1)); assertEquals(0, toInt32(-0.1)); assertEquals(1, toInt32(1), "one"); assertEquals(1, toInt32(1.1), "onepointone"); assertEquals(-1, toInt32(-1), "-one"); assertEquals(0, toInt32(0.6), "truncate positive (0.6)"); assertEquals(1, toInt32(1.6), "truncate positive (1.6)"); assertEquals(0, toInt32(-0.6), "truncate negative (-0.6)"); assertEquals(-1, toInt32(-1.6), "truncate negative (-1.6)"); assertEquals(2147483647, toInt32(2147483647)); assertEquals(-2147483648, toInt32(2147483648)); assertEquals(-2147483647, toInt32(2147483649)); assertEquals(-1, toInt32(4294967295)); assertEquals(0, toInt32(4294967296)); assertEquals(1, toInt32(4294967297)); assertEquals(-2147483647, toInt32(-2147483647)); assertEquals(-2147483648, toInt32(-2147483648)); assertEquals(2147483647, toInt32(-2147483649)); assertEquals(1, toInt32(-4294967295)); assertEquals(0, toInt32(-4294967296)); assertEquals(-1, toInt32(-4294967297)); assertEquals(-2147483648, toInt32(2147483648.25)); assertEquals(-2147483648, toInt32(2147483648.5)); assertEquals(-2147483648, toInt32(2147483648.75)); assertEquals(-1, toInt32(4294967295.25)); assertEquals(-1, toInt32(4294967295.5)); assertEquals(-1, toInt32(4294967295.75)); assertEquals(-1294967296, toInt32(3000000000.25)); assertEquals(-1294967296, toInt32(3000000000.5)); assertEquals(-1294967296, toInt32(3000000000.75)); assertEquals(-2147483648, toInt32(-2147483648.25)); assertEquals(-2147483648, toInt32(-2147483648.5)); assertEquals(-2147483648, toInt32(-2147483648.75)); assertEquals(1, toInt32(-4294967295.25)); assertEquals(1, toInt32(-4294967295.5)); assertEquals(1, toInt32(-4294967295.75)); assertEquals(1294967296, toInt32(-3000000000.25)); assertEquals(1294967296, toInt32(-3000000000.5)); assertEquals(1294967296, toInt32(-3000000000.75)); var base = Math.pow(2, 64); assertEquals(0, toInt32(base + 0)); assertEquals(0, toInt32(base + 1117)); assertEquals(4096, toInt32(base + 2234)); assertEquals(4096, toInt32(base + 3351)); assertEquals(4096, toInt32(base + 4468)); assertEquals(4096, toInt32(base + 5585)); assertEquals(8192, toInt32(base + 6702)); assertEquals(8192, toInt32(base + 7819)); assertEquals(8192, toInt32(base + 8936)); assertEquals(8192, toInt32(base + 10053)); assertEquals(12288, toInt32(base + 11170)); assertEquals(12288, toInt32(base + 12287)); assertEquals(12288, toInt32(base + 13404)); assertEquals(16384, toInt32(base + 14521)); assertEquals(16384, toInt32(base + 15638)); assertEquals(16384, toInt32(base + 16755)); assertEquals(16384, toInt32(base + 17872)); assertEquals(20480, toInt32(base + 18989)); assertEquals(20480, toInt32(base + 20106)); assertEquals(20480, toInt32(base + 21223)); assertEquals(20480, toInt32(base + 22340)); assertEquals(24576, toInt32(base + 23457)); assertEquals(24576, toInt32(base + 24574)); assertEquals(24576, toInt32(base + 25691)); assertEquals(28672, toInt32(base + 26808)); assertEquals(28672, toInt32(base + 27925)); assertEquals(28672, toInt32(base + 29042)); assertEquals(28672, toInt32(base + 30159)); assertEquals(32768, toInt32(base + 31276)); // bignum is (2^53 - 1) * 2^31 - highest number with bit 31 set. var bignum = Math.pow(2, 84) - Math.pow(2, 31); assertEquals(-Math.pow(2,31), toInt32(bignum)); assertEquals(-Math.pow(2,31), toInt32(-bignum)); assertEquals(0, toInt32(2 * bignum)); assertEquals(0, toInt32(-(2 * bignum))); assertEquals(0, toInt32(bignum - Math.pow(2,31))); assertEquals(0, toInt32(-(bignum - Math.pow(2,31)))); // max_fraction is largest number below 1. var max_fraction = (1 - Math.pow(2,-53)); assertEquals(0, toInt32(max_fraction)); assertEquals(0, toInt32(-max_fraction));
({ onShowDialogValueChange: function(component, event, helper){ if(component.get('v.showDialog')) return; helper.fireCloseEvent(component, false, null); }, closeModal: function(component, event, helper){ component.set('v.showDialog', false); helper.fireCloseEvent(component, false, null); }, closeModalYes: function(component, event, helper){ component.set('v.showDialog', false); helper.fireCloseEvent(component, true, null); } })
//Problem 1. Exchange if greater //Write an if statement that takes two double variables a and b and exchanges their values if the first one is greater than the second. //As a result print the values a and b, separated by a space. var a = [5, 3, 5.5]; var b = [2, 4, 4.5]; var tmp; for (var i = 0; i < 3; i += 1) { if (a > b) { tmp = b; b = a; a = tmp; } console.log(a[i] + ' ' + b[i]); }
module.exports = { newRelicKey: '', azureNamespace: "", azureAccessKey: "", messageTopic: "messagetopic", subName: "testSubscription" };
/** * @license * This file is written by MemoriesOff (https://github.com/MemoriesOff) * you can use it based on the Apache License, Version 2.0 * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * ============================================================================= */ class SemanticSegmentation { constructor(modelAddress,modelPixels=[198, 352]){ this.modelAddress = modelAddress; this.modelPixels=modelPixels; this.class_names = ['background', 'aeroplane', 'bicycle', 'bird', 'boat','bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable','dog', 'horse', 'motorbike', 'person', 'potted-plant','sheep', 'sofa', 'train', 'tv/monitor', 'ambigious']; } async load(){ this.modelLoader = await tf.loadGraphModel(this.modelAddress); this.modelWeights=new ModelWeights(this.modelLoader); this.modelNet=new MobileNet(this.modelWeights); this.isLoad=true; console.log("loadfinish") } predict(inputImage,isOnlyPerson,isFcn32){ return tf.tidy(() => { const imageTensor = tf.browser.fromPixels(inputImage); const {resizedAndPadded,paddedBy,} = resizeAndPadTo(imageTensor, this.modelPixels); const mobileNetOutput = this.modelNet.predict(resizedAndPadded, 32); const segments =this.modelNet.convToOutput(mobileNetOutput,isOnlyPerson,isFcn32); const [resizedHeight, resizedWidth] = resizedAndPadded.shape; const [height, width] = imageTensor.shape; const scaledSegmentScores = scaleAndCropToInputTensorShape( segments, [height, width], [resizedHeight, resizedWidth], paddedBy); if(isOnlyPerson) return scaledSegmentScores.sigmoid(); return scaledSegmentScores.argMax(2) }); } }
var _ = require('underscore'); var Models = require('JSCoreGraphics').CoreGraphics.Geometry.DataTypes; var Touch = require('./Touch'); var shouldLogGestureInfo = false; var logContext = "ReactGestureRecognizerMixin"; var logGestureInfo = function(logString) { if(shouldLogGestureInfo) { console.log(logContext + ' - ' +logString); } } function ReactGestureRecognizerMixinFactory() { var ReactGestureRecognizerMixin = { componentWillMount: function() { }, componentDidMount: function() { var node = this.getDOMNode(); node.addEventListener('mousedown', this.gestureRecognizerOnMouseDown); window.addEventListener('mousemove', this.gestureRecognizerOnMouseMove); window.addEventListener('mouseup', this.gestureRecognizerOnMouseUp); node.addEventListener('touchstart', this.gestureRecognizerOnTouchStart); window.addEventListener('touchmove', this.gestureRecognizerOnTouchMove); window.addEventListener('touchend', this.gestureRecognizerOnTouchEnd); if(!this.shouldAllowTouchToBubble) { this.shouldAllowTouchToBubble = false; } if(this.logMixinDebugInfo) { shouldLogGestureInfo = this.logMixinDebugInfo; } logGestureInfo("componentDidMount"); }, componentWillUnmount: function() { var node = this.getDOMNode(); node.removeEventListener('mousedown', this.gestureRecognizerOnMouseDown); window.removeEventListener('mousemove', this.gestureRecognizerOnMouseMove); window.removeEventListener('mouseup', this.gestureRecognizerOnMouseUp); node.removeEventListener('touchstart', this.gestureRecognizerOnTouchStart); window.removeEventListener('touchmove', this.gestureRecognizerOnTouchMove); window.removeEventListener('touchend', this.gestureRecognizerOnTouchEnd); logGestureInfo("componentWillUnmount"); }, addedLocalDelegate: false, //TODO: this should be called on each listening gesture to see if any will handle touch or delegated to mixins super shouldHandleGesture: function(e, isTouch) { if(isTouch) { return this.shouldHandleTouchGestures; } else { return this.shouldHandleMouseGestures; } }, shouldPreventDefault: function() { return !this.shouldAllowTouchToBubble; }, isAnyGestureCurrentlyActive: function() { var isActive = false; for(var i = 0; i < this.gestureRecognizers.length; i++) { if(this.gestureRecognizers[i].isActive()) { isActive = true; break; } } //logGestureInfo("isAnyGestureCurrentlyActive: " + isActive); return isActive; }, resetRecognizers: function() { for(var i = 0; i < this.gestureRecognizers.length; i++) { this.gestureRecognizers[i].reset(); } logGestureInfo("resetRecognizers"); }, onGestureStateChanged: function() { var anyActive = this.isAnyGestureCurrentlyActive(); logGestureInfo("onGestureStateChanged. anyActive: " + anyActive); if(!anyActive) { this.resetRecognizers(); } }, gestureRecognizerOnMouseDown: function(e) { if(this.shouldHandleGesture(e, false)) { var point = new Models.Point({x: e.pageX, y: e.pageY}); var touch = new Touch(1, point, e.relatedTarget); this.gestureRecognizerOnGestureDown(touch, function(shouldPreventDefault) { logGestureInfo("gestureRecognizerOnMouseDown. ShouldPreventDefault: " + shouldPreventDefault); if(shouldPreventDefault) { e.preventDefault(); } }); } }, gestureRecognizerOnMouseMove: function(e) { if(this.shouldHandleGesture(e, false) && this.isAnyGestureCurrentlyActive()) { var point = new Models.Point({x: e.pageX, y: e.pageY}); var touch = new Touch(1, point, e.relatedTarget); this.gestureRecognizerOnGestureMove(touch, function(shouldPreventDefault) { logGestureInfo("gestureRecognizerOnMouseMove. ShouldPreventDefault: " + shouldPreventDefault); if(shouldPreventDefault) { e.preventDefault(); } }); } }, gestureRecognizerOnMouseUp: function(e) { if(this.shouldHandleGesture(e, false)) { var point = new Models.Point({x: e.pageX, y: e.pageY}); var touch = new Touch(1, point, e.relatedTarget); this.gestureRecognizerOnGestureUp(touch, function(shouldPreventDefault) { logGestureInfo("gestureRecognizerOnMouseUp. ShouldPreventDefault: " + shouldPreventDefault); if(shouldPreventDefault) { e.preventDefault(); } }); } }, gestureRecognizerOnTouchStart: function(e) { if(this.shouldHandleGesture(e, true)) { var touches = []; for (var i = 0; i < e.changedTouches.length; i++) { var point = new Models.Point({x: e.changedTouches[i].pageX, y: e.changedTouches[i].pageY}); var touch = new Touch(e.changedTouches[i].identifier, point, e.changedTouches[i].target); touches.push(touch); } this.gestureRecognizerOnGestureDown(touches, function(shouldPreventDefault) { logGestureInfo("gestureRecognizerOnTouchStart. ShouldPreventDefault: " + shouldPreventDefault); if(shouldPreventDefault) { e.preventDefault(); } }); } }, gestureRecognizerOnTouchMove: function(e) { var touchOne = { pageX: e.touches && e.touches.length > 0 ? e.touches[0].pageX : "NA", pageY: e.touches && e.touches.length > 0 ? e.touches[0].pageY : "NA" }; var changedTouchOne = { pageX: e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches[0].pageX : "NA", pageY: e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches[0].pageY : "NA" }; logGestureInfo("gestureRecognizerOnTouchMove - touches: " + JSON.stringify(touchOne, null) + ", changedTouches: " + JSON.stringify(changedTouchOne, null)); if(this.shouldHandleGesture(e, true) && this.isAnyGestureCurrentlyActive()) { var touches = []; for (var i = 0; i < e.changedTouches.length; i++) { var point = new Models.Point({x: e.changedTouches[i].pageX, y: e.changedTouches[i].pageY}); var touch = new Touch(e.changedTouches[i].identifier, point, e.changedTouches[i].target); touches.push(touch); } this.gestureRecognizerOnGestureMove(touches, function(shouldPreventDefault) { logGestureInfo("gestureRecognizerOnTouchStart. ShouldPreventDefault: " + shouldPreventDefault); if(shouldPreventDefault) { e.preventDefault(); } }); } }, gestureRecognizerOnTouchEnd: function(e) { if(this.shouldHandleGesture(e, true)) { var touches = []; for (var i = 0; i < e.changedTouches.length; i++) { var point = new Models.Point({x: e.changedTouches[i].pageX, y: e.changedTouches[i].pageY}); var touch = new Touch(e.changedTouches[i].identifier, point, e.changedTouches[i].target); touches.push(touch); } this.gestureRecognizerOnGestureUp(touches, function(shouldPreventDefault) { logGestureInfo("gestureRecognizerOnTouchEnd. ShouldPreventDefault: " + shouldPreventDefault); if(shouldPreventDefault) { e.preventDefault(); } }); } }, gestureRecognizerOnGestureDown: function(touches, shouldPreventDefaultCallback) { if(!this.addedLocalDelegate) {//hackety hack this.addedLocalDelegate = true; for(var i = 0; i < this.gestureRecognizers.length; i++) { this.gestureRecognizers[i].stateFailedOrEndedCallback = this.onGestureStateChanged; } } if(!_.isArray(touches)) { touches = [touches]; } for(var i = 0; i < this.gestureRecognizers.length; i++) { this.gestureRecognizers[i].onGestureDown(touches); } var anyActive = this.isAnyGestureCurrentlyActive(); shouldPreventDefaultCallback(anyActive && this.shouldPreventDefault()); }, gestureRecognizerOnGestureMove: function(touches, shouldPreventDefaultCallback) { if (this.isAnyGestureCurrentlyActive()) { if (!_.isArray(touches)) { touches = [touches]; } for (var i = 0; i < this.gestureRecognizers.length; i++) { this.gestureRecognizers[i].onGestureMove(touches); } var anyActive = this.isAnyGestureCurrentlyActive(); shouldPreventDefaultCallback(anyActive && this.shouldPreventDefault()); } }, gestureRecognizerOnGestureUp: function(touches, shouldPreventDefaultCallback) { if (!_.isArray(touches)) { touches = [touches]; } for (var i = 0; i < this.gestureRecognizers.length; i++) { this.gestureRecognizers[i].onGestureUp(touches); } var anyActive = this.isAnyGestureCurrentlyActive(); if (!anyActive) { this.resetRecognizers(); } shouldPreventDefaultCallback(anyActive && this.shouldPreventDefault()); } }; return ReactGestureRecognizerMixin; } module.exports = ReactGestureRecognizerMixinFactory;
alert("Hello world"); var el = document.querySelector('.register-auth-input-error'); console.log(el); el.classList.add("error");
/** * @license Highstock JS v9.1.0 (2021-05-04) * @module highcharts/modules/stock-tools * @requires highcharts * @requires highcharts/modules/stock * * Advanced Highcharts Stock tools * * (c) 2010-2021 Highsoft AS * Author: Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import '../../Stock/StockToolsBindings.js'; import '../../Stock/StockToolsGui.js';
import DingTalk from './dingtalk' export default new DingTalk()
import { combineReducers } from 'redux' import githubReducer from './github/githubModule' import moquiReducer from './moqui/moquiModule' export default combineReducers({ github: githubReducer, moqui: moquiReducer })
function ConvenientHunk(raw, i) { this.raw = raw; this.i = i; } /** * Diff header string that represents the context of this hunk * of the diff. Something like `@@ -169,14 +167,12 @@ ...` * @return {String} */ ConvenientHunk.prototype.header = function() { return this.raw.hunk(this.i).header; }; /** * Number of lines in this hunk * @return {Number} */ ConvenientHunk.prototype.size = function() { return this.raw.numLinesInHunk(this.i); }; /** * The lines in this hunk * @return {[String]} array of strings */ ConvenientHunk.prototype.lines = function() { var result = []; for (var i = 0; i < this.size(); i++) { result.push(this.raw.getLineInHunk(this.i, i)); } return result; }; module.exports = ConvenientHunk;
// loader manager (function(undefined,window){ "use strict"; var oriP = window.P, P = function(cfg){ return P.config(cfg) }; if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = P; } else if (typeof define === 'function ' && define.amd) { define(P); } P.noConflict = function () { window.P = oriP; return this;}; P.version = '20150928'; window.P = P; P.global = {}; var loading = {}; var modules = P.global; Date.now = Date.now || function () { return new Date().valueOf(); }; var L = function(){ var v = Array.prototype.slice.call(arguments); for(var i in v) { console.log(v); } } var logger = { info:function(v){ console.log("%cINFO : "+v,"color:#0080ff"); }, error : function(v){ console.log("%cERROR : "+v,"color:red"); }, warn : function(v){ console.log("%cWARN : "+v,"color:orange"); }, success : function(v){console.log("%cSUCCESS : "+v,"color:green");} } var getModule = function(module) { var src = module; if (/^P\./.test(module)) { src = src+'.js'; if (P.MODULE_ROOT) { src = P.MODULE_ROOT + '/' + src; } } return src; }; var extend = function (k) { var argus = Array.prototype.slice.call(arguments, 1) , o = k || {} , src; for (var i = 0 , l = argus.length; i < l; i++) { src = argus[i] || {}; if (typeof src == 'object') { for (var p in src) { o[p] = src[p]; } } } return o; } var include = function(imports, callback) { if (imports instanceof Array) { var i, len = imports.length; if (len) { var inc = function(index) { include(imports[index], function() { index++; if (index < len) { inc(index); } else { callback(); } }); }; inc(0); } else { callback(); return; } } else if (imports == null) { callback(); return; } else { if (!modules.hasOwnProperty(imports)) { // 外部导入 //console.log("r - req:"+imports) var r = require(imports); if(r){ modules[imports] = {object : r} callback(); return; } var src = getModule(imports); var ele = document.createElement('script'); ele.setAttribute('src', src); document.getElementsByTagName('head')[0].appendChild(ele); loading[imports] = { name: imports, src: src, callback: callback }; } else { callback(); return; } } }; var require = function(v) { var nss = v.split("."), cc = window, i, l; for (i = 0, l = nss.length; i < l && cc != undefined; i++) { cc = cc[nss[i]]; } return cc; }; //赋值继承 function inherit_s(C,T,o){ C.prototype = new T(); C.prototype.constructor = C; for(var i in o){ //掺元 if (i == 'mixin') extend(C.prototype, o.mixin); else if (i == 'static') extend(C, o.static); else{ //console.log(i); C.prototype[i] = o[i]; } } } //继承 function inherit(C, L) { var F = function () {}; F.prototype = L.prototype; /* var proto = new F(); proto.constructor = C; C.prototype = proto;*/ C.prototype = new F; // static vars for (var i in L) { if (L.hasOwnProperty(i) && i !== 'prototype') { C[i] = L[i]; } } // 多重继承 、 对象混入(mixin)、静态赋值 var i, l, o; for (i = 2, l = arguments.length; i < l; i++) { o = arguments[i]; if (typeof o === "function") { o = o.prototype; } extend(C.prototype, o); if (o.mixin) extend(C.prototype, o.mixin); if (o.static) extend(C, o.static); } }; function nclass() { var len = arguments.length; var L = arguments[0]; var F = arguments[len - 1]; /* var C = function(){ if(L.prototype.initialize) L.prototype.initialize.apply(this, arguments); }*/ var C = typeof F.initialize == "function" ? F.initialize : function () { L.prototype.initialize && L.prototype.initialize.apply(this, arguments); }; if (len > 1) { var newArgs = [C, L].concat(Array.prototype.slice.call(arguments).slice(1, len - 1), F); inherit.apply(null, newArgs); } else { C.prototype = F; } return C; }; /** * 模块加载 */ function module(mod, dependencies, factory){ modules[mod] = {object:undefined} include(dependencies, function() { var nc = mod.split("."), pnc, o = window , i, l = nc.length; for (i = 0 ; i < l-1; i++) { o = o[nc[i]] = o[nc[i]] || {}; } var reqs = []; for(var j=dependencies.length-1;j>=0;j--) { //console.log("req:"+dependencies[j]) reqs[j] = require(dependencies[j]); } modules[mod].object = o[nc[i]] = factory.apply(factory,reqs);//, reqs //正在加载 if (module in loading) { var callback = loading[mod].callback; delete loading[mod]; callback(); } }); } /** * 传统继承 */ function provide(ns, pns, props) { var nc = ns.split("."), pnc, o = window , i, l , argus; if (typeof pns == "string" && pns != "") pnc = P.require(pns); for (i = 0, l = nc.length - 1; i < l; i++) { o = o[nc[i]] = o[nc[i]] || {}; } if (arguments.length > 1) { argus = props || {}; o[nc[i]] = typeof pnc == "function" ? nclass(pnc, argus) : P.extend({}, pns); } else { o[nc[i]] = {}; } }; /** * 模块继承 * @type {module} */ function use(ns, pns,dep, props) { var argus = props || {} , pnc = P.require(pns); var nc = nclass(pnc, argus); P.module(ns,dep,nc); }; var isarray = Array.isArray || function (obj) { return (Object.prototype.toString.call(obj) === '[object Array]'); }; /** * 新增工厂 */ function factory(v , cls){ P[v] = cls; } P.factory = factory; P.module = module; P.require = require; P.provide = provide; P.extend = extend; P.use = use; P.isArray = isarray; P.inherit = inherit_s; P.logger = logger; })(undefined, window);
import React from 'react'; import shallowEqual from 'react-pure-render/shallowEqual'; // import diff from 'immutablediff'; /** * Purified React.Component. Goodness. * http://facebook.github.io/react/docs/advanced-performance.html */ class Component extends React.Component { shouldComponentUpdate(nextProps, nextState) { // TODO: Make whole React Pure, add something like dangerouslySetLocalState. // https://github.com/gaearon/react-pure-render#known-issues // https://twitter.com/steida/status/600395820295450624 if (this.context.router) { const changed = this.pureComponentLastPath !== this.context.router.getCurrentPath(); this.pureComponentLastPath = this.context.router.getCurrentPath(); if (changed) return true; } const shouldUpdate = !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); // if (shouldUpdate) // this._logShouldUpdateComponents(nextProps, nextState) return shouldUpdate; } // // Helper to check which component was changed and why. // _logShouldUpdateComponents(nextProps, nextState) { // const name = this.constructor.displayName || this.constructor.name // console.log(`${name} shouldUpdate`) // const propsDiff = diff(this.props, nextProps).toJS() // const stateDiff = diff(this.state, nextState).toJS() // if (propsDiff.length) console.log('props', propsDiff) // if (stateDiff.length) console.log('state', stateDiff) // } } Component.contextTypes = { router: React.PropTypes.func }; export default Component;
/// <reference path="../../typings/ember/ember.d.ts"/> app = Ember.Application.create({ LOG_TRANSITIONS: true }); app.IndexController = Ember.ArrayController.extend({ renderedOn: function () { return new Date(); }.property(), actions: { clickMe: function () { alert("I have been clicked"); } } }); Ember.Handlebars.registerBoundHelper("fromDate", function (theDate) { var today = moment(); var target = moment(theDate); return target.from(today); }); Ember.Handlebars.registerBoundHelper("longYear", function (theDate) { return moment(theDate).format('YYYY'); }); app.IndexRoute = Ember.Route.extend({ model: function () { return ['red', 'yellow', 'blue']; } }); app.Router.map(function () { this.route("index", { path: "/" }); this.route("table"); this.route("component"); });
import { local } from './http' export const getAllLayers = () => { return local.get('/layers.json', {}) }
'use strict'; var viewport = require('../controllers/viewport'); module.exports = function(Pollution, app, auth) { app.route('/viewport/:year/:month/:day/:hour/:parameter_name') .post(viewport.render); };
/* global SimpleSchema*/ import { Folder } from '../Folder.js'; import { File } from '../../File/File.js'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { LoggedInMixin } from 'meteor/tunifight:loggedin-mixin'; export const deleteFolder = new ValidatedMethod({ name: 'deleteFolder', mixins: [LoggedInMixin], checkLoggedInError: { error: 'notLogged', reason: 'Do not have permission', }, validate: new SimpleSchema({ _id: { type: String, } }).validator(), run({_id}) { const f = Folder.findOne(_id); if (!f) { throw new Meteor.Error(404, 'Folder does not exist'); } // XXX: not really a good check, should show more explicit logic if (f.folderType !== 'normal') { throw new Meteor.Error(403, 'Can not delete this folder'); } const re = Folder.update({ _id, }, { $set: { isDelete: true, } }); Meteor.setTimeout(() => { const folders = f.getFolderDescendant().map(obj => obj._id); const files = f.getFileDescendant().map(obj => obj._id); Folder.update({ _id: { $in: folders, } }, { $set: { isDelete: true, } }, { multi: true, }, () => {}); File.update({ _id: { $in: files, } }, { $set: { isDelete: true, } }, { multi: true, }, () => {}); }, 0); return re; } });
var semver = require('semver'); checkVersion = function(customExpectedVersion) { var version = process.version; var expectedVersion = version; // Default: always satisfied if (typeof customExpectedVersion !== "undefined" && customExpectedVersion !== null) { expectedVersion = customExpectedVersion; } else { var packageJson; try { packageJson = require('../../package.json'); } catch (e) { return; } engines = packageJson.engines; if (typeof engines !== "undefined" && engines !== null) { expectedVersion = engines.node; } } if (!semver.satisfies(version, expectedVersion)){ throw new Error('Node ' + expectedVersion + ' required.'); } }; module.exports = checkVersion
'use strict'; /** * Please see webpack config reference for better understanding: * https://webpack.github.io/docs/configuration.html */ const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin; module.exports = { /** * These parameters will be used for rendering `index.html`. */ metadata: { title: 'Demo Application', baseUrl: '/' }, entry: { 'polyfills': './src/polyfills.ts', 'vendor': './src/vendor.ts', 'app': './src/main.ts' }, resolve: { extensions: ['', '.ts', '.js', '.scss', '.html'], /** * Adding src to resolving paths allows us to do, say, `import 'app/a/a.service'` instead of * import `../../../a/service`. Especially useful for tests, since they are in a separate directory. */ modulesDirectories: ['node_modules', 'src'] }, module: { loaders: [ /** * Loaders for TypeScript. * No need to exclude tests by `(spec|e2e)` mask here, as they are in separate directory. * * See project repository for details / configuration reference: * https://github.com/s-panferov/awesome-typescript-loader * https://github.com/TheLarkInn/angular2-template-loader */ { test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'] }, /** * Loaders for HTML templates, JSON files, SASS/SCSS stylesheets. See details at projects' repositories: * * https://github.com/webpack/json-loader * https://github.com/webpack/html-loader * https://github.com/gajus/to-string-loader */ {test: /\.json$/, loader: 'json-loader'}, {test: /\.html$/, loader: 'raw-loader'}, {test: /\.scss$/, loaders: ['raw-loader', 'sass-loader']} ] }, plugins: [ /** * This plugin is a part of `awesome-typescript-loader`, it allows to run type checking in a separate process, * so webpack won't wait for it. */ new ForkCheckerPlugin(), /** * Quote from webpack docs: "Assign the module and chunk ids by occurrence count. Ids that are used often get * lower (shorter) ids. This make ids predictable, reduces total file size and is recommended." * * See https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin */ new webpack.optimize.OccurenceOrderPlugin(true), /** * This plugin simplifies generation of `index.html` file. Especially useful for production environment, * where your files have hashes in their names. * * We have auto-injection disabled here, otherwise scripts will be automatically inserted at the end * of `body` element. * * See https://www.npmjs.com/package/html-webpack-plugin for details. * * TODO: Google Analytics and other stuff like that */ new HtmlWebpackPlugin({ title: 'Demo Application', template: 'src/index.ejs', chunksSortMode: 'dependency', inject: false }), /** * This plugin helps to share common code between pages. * * For more info see: * https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin * https://github.com/webpack/docs/wiki/optimization#multi-page-app */ new webpack.optimize.CommonsChunkPlugin({ name: ['vendor', 'polyfills'] }) ] };
export default function assert(condition, message) { if (!condition) { throw new Error(message); } }
'use strict'; //Strict mode, to limit silent errors //Switching between languages $("#language").click(function() { //Redirect to the url that matches the current language if (/[?]lang=fr/.test(window.location.href) ) { window.location.href = window.location.href.split('?')[0]; } else { window.location.href = '?lang=fr'; } }); //Defining a variable with page url, as it is reused many times in //following code (but without modifying it as in first if) var wlh = window.location.href; //If url has the suffix for French if (/[?]lang=fr/.test(wlh) ) { //Switch text to the other language $("span[lang|='en']").toggle(0); $("span[lang|='fr']").toggle(0); //Switch links to French versions $("a:not(.slideshow):not(#instagram)").each(function() { var $this = $(this); var _href = $this.attr("href"); $this.attr("href", _href + '?lang=fr'); }); $("a#instagram").each(function() { var $this = $(this); var _href = $this.attr("href"); $this.attr("href", _href + '?hl=fr'); }); //Switch html language (for google translate purposes) to French $("html").attr("lang", "fr"); } //Fill-in urls towards slideshows, including which picture is being clicked $("a.slideshow").each(function() { var _pjt = /[/]portfolio[/](.*?)([?]lang=fr)*$/.exec(wlh)[1]; var $this = $(this); var _img = $this.children().first().attr("src"); var _img2 = _img.replace(/^.*?[/]images[/]layout_600[/]/,''); $this.attr("href", 'slideshows/' + _pjt + '?img=' + _img2); }); //If url has an img suffix (slideshows) if (/[?]img=/.test(wlh) ) { //Display current image var ssimg = /[?]img=(.*?)$/.exec(wlh)[1]; ssimg = ssimg.replace(/%20/g, " "); $("[src$='" + ssimg + "']").removeClass("inactive").addClass("active"); //Link to full resolution images var current = $("img.active"); function updateFullResLink() { var currentFullRes = current.attr('src').replace(/^.*?[/]images[/]slideshow_[0-9]*?[/]/,''); $("a.full-res").attr("href", "../../images/full_size/" + currentFullRes); } updateFullResLink(); //Next and previous slideshow-buttons $('a.next').click( function(e) { e.preventDefault(); var _next = current.next("img"); if (typeof _next[0] === "undefined") { _next = current.siblings("img").first(); } current.removeClass("active").addClass("inactive"); _next.removeClass("inactive").addClass("active"); current = $("img.active"); updateFullResLink(); return false; //prevent browser from following link, as only within page action is needed } ); $('a.previous').click( function(e) { e.preventDefault(); var _prev = current.prev("img"); if (typeof _prev[0] === "undefined") { _prev = current.siblings("img").last(); } current.removeClass("active").addClass("inactive"); _prev.removeClass("inactive").addClass("active"); current = $("img.active"); updateFullResLink(); return false; //prevent browser from following link, as only within page action is needed } ); $('a.close').click( function(e) { e.preventDefault(); window.history.back(); return false; //prevent browser from following link, as only within page action is needed } ); //Swipe-control of slideshow //Simple swipe detection on vanilla js //Based on https://gist.github.com/SleepWalker/da5636b1abcbaff48c4d //Using swipe definition from https://api.jquerymobile.com/swipeleft/ var touchstartX = 0; var touchstartY = 0; var touchendX = 0; var touchendY = 0; var timestart = 0; var timeend = 0; var gesuredZone = document.getElementsByClassName('gesuredZone')[0]; gesuredZone.addEventListener('touchstart', function(event) { touchstartX = event.changedTouches[0].screenX; touchstartY = event.changedTouches[0].screenY; timestart = Date.now(); }, false); gesuredZone.addEventListener('touchend', function(event) { touchendX = event.changedTouches[0].screenX; touchendY = event.changedTouches[0].screenY; timeend = Date.now(); handleGesure(); }, false); function handleGesure() { if (touchendX < touchstartX && Math.abs(touchendX - touchstartX) >= 30 && Math.abs(touchendY - touchstartY) < 30 && (timeend - timestart) / 1000 <= 1) { $("a.next").click(); } if (touchendX > touchstartX && Math.abs(touchendX - touchstartX) >= 30 && Math.abs(touchendY - touchstartY) < 30 && (timeend - timestart) / 1000 <= 1) { $("a.previous").click(); } } //Arrow-keys control of slideshow //Based on https://siongui.github.io/2017/02/14/javascript-arrow-key-example-via-event-key/ var _keyCodeOld = { //Now being deprecated, kept for compatiblity with old browsers LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, ESC: 27 }; var _keyCodeNew = { //New web standard LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", DOWN: "ArrowDown", ESC: "Escape", }; var _keyCodeNewIE = { //Compatibility with some IE and Firefox older versions LEFT: "Left", UP: "Up", RIGHT: "Right", DOWN: "Down", ESC: "Esc" }; function handleKeyboardEvent(evt) { if (!evt) {evt = window.event;} //For old IE compatibility var _keyPressed = evt.key || evt.keyCode || evt.which; //Cross-browser compatibility switch (_keyPressed) { case _keyCodeOld.LEFT: case _keyCodeOld.UP: case _keyCodeNew.LEFT: case _keyCodeNew.UP: case _keyCodeNewIE.LEFT: case _keyCodeNewIE.UP: $("a.previous").click(); break; case _keyCodeOld.RIGHT: case _keyCodeOld.DOWN: case _keyCodeNew.RIGHT: case _keyCodeNew.DOWN: case _keyCodeNewIE.RIGHT: case _keyCodeNewIE.DOWN: $("a.next").click(); break; case _keyCodeOld.ESC: case _keyCodeNew.ESC: case _keyCodeNewIE.ESC: $("a.close").click(); break; default: return; //Quit function when other keys are pressed. } evt.preventDefault(); //Prevent default action for implemented keys } //To attach the above function to keydown events on the whole document function _addEventListener(evt, element, fn) { if (window.addEventListener) { //Check if function exist element.addEventListener(evt, fn, false); //Firefox, Chrome, or modern browsers } else { element.attachEvent('on'+evt, fn); //Old IE } } _addEventListener('keydown', document, handleKeyboardEvent); //To switch between smartphone slideshow pictures and tablet/desktop slideshow pictures function higherRes() { if (window.matchMedia("(min-width: 601px)").matches) { if(/slideshow_900/.test($("div.slideshow img").attr("src"))) { $("div.slideshow img").each(function() { var $this = $(this); var _src = $this.attr("src"); $this.attr("src", _src.replace('slideshow_900/','slideshow_2000/')); }); } } } higherRes(); _addEventListener('resize', window, higherRes); }
angular .module('eArkPlatform') .factory('uploadService', UploadService); function UploadService($http, notificationUtilsService) { var service = { uploadFile: uploadFile, uploadUsersCSVFile: uploadUsersCSVFile }; return service; /** * IMPORTANT - Change the url for the ajax post method * @param file * @param destination * @param extras * @returns {*} */ function uploadFile(file, destination, extras) { var formData = new FormData(); formData.append("filedata", file); formData.append("filename", file.name); formData.append("destination", destination ? destination : null); if (!extras || !extras.majorVersion) { formData.append("majorVersion", "false"); } /** * optional fields which may be passed via extras: * * siteId * containerId * uploaddirectory * majorVersion * updateNodeRef * description * username * overwrite * thumbnails * username */ if (extras) { angular.forEach(extras, function (value, key) { formData.append(key, value); }); } return $http.post("/api/upload", formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }).then(function (response) { return response; }, function (response) { notificationUtilsService.alert(response.data.message); }); } function uploadUsersCSVFile(file) { var formData = new FormData(); formData.append("filedata", file); formData.append("filename", file.name); formData.append("destination", null); return $http.post("/api/people/upload.json", formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }).then(function (response) { return response.data.data; }); } }
// Helpers function ready(fn) { if (document.readyState != "loading") { fn(); } else { document.addEventListener("DOMContentLoaded", fn); } } function outerSizeWithMargin(el) { var height = el.offsetHeight; var width = el.offsetWidth; var style = getComputedStyle(el); height += parseInt(style.marginTop) + parseInt(style.marginBottom); width += parseInt(style.marginLeft) + parseInt(style.marginRight); return { height: height, width: width }; } // Main ready(function () { console.log("Volatile"); })
angular.module('proton.models.user', []) .factory('User', function($http, url) { var User = { create: function(params) { return $http.post(url.get() + '/users', params); }, code: function(params) { return $http.post(url.get() + '/users/code', params); }, get: function() { return $http.get(url.get() + '/users'); }, pubkeys: function(emails) { return $http.get(url.get() + '/users/pubkeys/' + window.encodeURIComponent(emails)); }, available: function(username) { return $http.get(url.get() + '/users/available/' + username); }, direct: function() { return $http.get(url.get() + '/users/direct'); }, unlock: function(params) { return $http.put(url.get() + '/users/unlock', params); }, delete: function(params) { return $http.put(url.get() + '/users/delete', params); } }; return User; });
/* * name * numBlocks * blockList * mesh * mainly for active: * in out pairs - key, value = in, out face * (face defined as blockNum, faceNum) * * orientation - default as one * position - * mass, for calculating V by momentum * V to frame rate ratio * change in hight, 0 if not applicable * * Type of interaction * has object (for instance, if this is a carrier, it might have a ball chillin) * */ /* * object type: * inert: * Elasticity: * amount of momentum reflected, shown as a value from 0-1. * thus the calculation would be momentum times this constant, reflected. * active: * Roamer Object - for example, a ball * Carrier Object - eg. rails * Gadget Object - eg. hammer * */ /* * rotate * unrotate */
module.exports = ops => { const isObject = item => typeof item === 'object' && item !== null && !Array.isArray(item) const isString = item => typeof item === 'string' || item instanceof String const isArray = item => Array.isArray(item) const processValueArray = arr => Promise.all(arr.map(processValueUnknownType)) const processValueObject = obj => // eslint-disable-next-line new Promise(async resolve => { const acc = {} for (const key in obj) { acc[key] = await processValueUnknownType(obj[key], key, ops) } return resolve(acc) }) const processValueUnknownType = (unknown, key) => // eslint-disable-next-line new Promise(async resolve => { if (Number.isInteger(unknown)) { return resolve(JSON.stringify([unknown, unknown])) } if (isString(unknown)) return resolve(ops.tokenizer(unknown, key, ops)) if (isObject(unknown)) return resolve(processValueObject(unknown)) if (isArray(unknown)) return resolve(processValueArray(unknown)) if (unknown === null) return resolve(JSON.stringify([null, '1.00'])) return resolve(unknown) }) const processDocument = async doc => // eslint-disable-next-line new Promise(async resolve => { // Documents that are Strings are converted into { body: ... } if (isString(doc)) doc = { body: doc } // Docs with no _id are auto-assigned an ID // if (!doc.hasOwnProperty('_id')) doc._id = ops.idGenerator.next().value if (!Object.prototype.hasOwnProperty.call(doc, '_id')) { doc._id = ops.idGenerator.next().value } const acc = {} for (const key in doc) { if (key === '_id') { acc[key] = doc[key] continue } acc[key] = await processValueUnknownType(doc[key], key) } return resolve(acc) }) return { processDocuments: docs => Promise.all(docs.map(processDocument)) } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ // ideas taken from: // . The ocean spray in your face [Jeff Lander] // http://www.double.co.nz/dust/col0798.pdf // . Building an Advanced Particle System [John van der Burg] // http://www.gamasutra.com/features/20000623/vanderburg_01.htm // . LOVE game engine // http://love2d.org/ // // // Radius mode support, from 71 squared // http://particledesigner.71squared.com/ // // IMPORTANT: Particle Designer is supported by cocos2d, but // 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, // cocos2d uses a another approach, but the results are almost identical. // /** * Shape Mode of Particle Draw * @constant * @type Number */ cc.PARTICLE_SHAPE_MODE = 0; /** * Texture Mode of Particle Draw * @constant * @type Number */ cc.PARTICLE_TEXTURE_MODE = 1; /** * Star Shape for ShapeMode of Particle * @constant * @type Number */ cc.PARTICLE_STAR_SHAPE = 0; /** * Ball Shape for ShapeMode of Particle * @constant * @type Number */ cc.PARTICLE_BALL_SHAPE = 1; /** * The Particle emitter lives forever * @constant * @type Number */ cc.PARTICLE_DURATION_INFINITY = -1; /** * The starting size of the particle is equal to the ending size * @constant * @type Number */ cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE = -1; /** * The starting radius of the particle is equal to the ending radius * @constant * @type Number */ cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS = -1; /** * Gravity mode (A mode) * @constant * @type Number */ cc.PARTICLE_MODE_GRAVITY = 0; /** * Radius mode (B mode) * @constant * @type Number */ cc.PARTICLE_MODE_RADIUS = 1; // tCCPositionType // possible types of particle positions /** * Living particles are attached to the world and are unaffected by emitter repositioning. * @constant * @type Number */ cc.PARTICLE_TYPE_FREE = 0; /** * Living particles are attached to the world but will follow the emitter repositioning.<br/> * Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite. * @constant * @type Number */ cc.PARTICLE_TYPE_RELATIVE = 1; /** * Living particles are attached to the emitter and are translated along with it. * @constant * @type Number */ cc.PARTICLE_TYPE_GROUPED = 2; // backward compatible cc.PARTICLE_TYPE_FREE = cc.PARTICLE_TYPE_FREE; cc.PARTICLE_TYPE_GROUPED = cc.PARTICLE_TYPE_GROUPED; /** * Structure that contains the values of each particle * @Class * @Construct * @param {cc.Point} pos Position of particle * @param {cc.Point} startPos * @param {cc.Color4F} color * @param {cc.Color4F} deltaColor * @param {cc.Size} size * @param {cc.Size} deltaSize * @param {Number} rotation * @param {Number} deltaRotation * @param {Number} timeToLive * @param {cc.Particle.ModeA} modeA * @param {cc.Particle.ModeA} modeB */ cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) { this.pos = pos ? pos : cc.PointZero(); this.startPos = startPos ? startPos : cc.PointZero(); this.color = color ? color : new cc.Color4F(0, 0, 0, 1); this.deltaColor = deltaColor ? deltaColor : new cc.Color4F(0, 0, 0, 1); this.size = size || 0; this.deltaSize = deltaSize || 0; this.rotation = rotation || 0; this.deltaRotation = deltaRotation || 0; this.timeToLive = timeToLive || 0; this.atlasIndex = atlasIndex || 0; this.modeA = modeA ? modeA : new cc.Particle.ModeA(); this.modeB = modeB ? modeB : new cc.Particle.ModeB(); this.isChangeColor = false; this.drawPos = cc.p(0, 0); }; /** * Mode A: gravity, direction, radial accel, tangential accel * @Class * @Construct * @param {cc.Point} dir direction of particle * @param {Number} radialAccel * @param {Number} tangentialAccel */ cc.Particle.ModeA = function (dir, radialAccel, tangentialAccel) { this.dir = dir ? dir : cc.PointZero(); this.radialAccel = radialAccel || 0; this.tangentialAccel = tangentialAccel || 0; }; /** * Mode B: radius mode * @Class * @Construct * @param {Number} angle * @param {Number} degreesPerSecond * @param {Number} radius * @param {Number} deltaRadius */ cc.Particle.ModeB = function (angle, degreesPerSecond, radius, deltaRadius) { this.angle = angle || 0; this.degreesPerSecond = degreesPerSecond || 0; this.radius = radius || 0; this.deltaRadius = deltaRadius || 0; }; /** * Array of Point instances used to optimize particle updates */ cc.Particle.TemporaryPoints = [ cc.p(), cc.p(), cc.p(), cc.p() ]; /** * <p> * Particle System base class. <br/> * Attributes of a Particle System:<br/> * - emmision rate of the particles<br/> * - Gravity Mode (Mode A): <br/> * - gravity <br/> * - direction <br/> * - speed +- variance <br/> * - tangential acceleration +- variance<br/> * - radial acceleration +- variance<br/> * - Radius Mode (Mode B): <br/> * - startRadius +- variance <br/> * - endRadius +- variance <br/> * - rotate +- variance <br/> * - Properties common to all modes: <br/> * - life +- life variance <br/> * - start spin +- variance <br/> * - end spin +- variance <br/> * - start size +- variance <br/> * - end size +- variance <br/> * - start color +- variance <br/> * - end color +- variance <br/> * - life +- variance <br/> * - blending function <br/> * - texture <br/> * <br/> * cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).<br/> * 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, <br/> * cocos2d uses a another approach, but the results are almost identical.<br/> * cocos2d supports all the variables used by Particle Designer plus a bit more: <br/> * - spinning particles (supported when using CCParticleSystemQuad) <br/> * - tangential acceleration (Gravity mode) <br/> * - radial acceleration (Gravity mode) <br/> * - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only) <br/> * It is possible to customize any of the above mentioned properties in runtime. Example: <br/> * </p> * @class * @extends cc.Node * * @example * emitter.radialAccel = 15; * emitter.startSpin = 0; */ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ //***********variables************* _plistFile:"", //! time elapsed since the start of the system (in seconds) _elapsed:0, _dontTint:false, // Different modes //! Mode A:Gravity + Tangential Accel + Radial Accel modeA:null, //! Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode) modeB:null, //private POINTZERO for ParticleSystem _pointZeroForParticle:cc.p(0, 0), //! Array of particles _particles:null, // color modulate // BOOL colorModulate; //! How many particles can be emitted per second _emitCounter:0, //! particle idx _particleIdx:0, _batchNode:null, /** * return weak reference to the cc.SpriteBatchNode that renders the cc.Sprite * @return {cc.ParticleBatchNode} */ getBatchNode:function () { return this._batchNode; }, /** * set weak reference to the cc.SpriteBatchNode that renders the cc.Sprite * @param {cc.ParticleBatchNode} batchNode */ setBatchNode:function (batchNode) { if (this._batchNode != batchNode) { this._batchNode = batchNode; //weak reference if (batchNode) { for (var i = 0; i < this._totalParticles; i++) { this._particles[i].atlasIndex = i; } } } }, _atlasIndex:0, /** * return index of system in batch node array * @return {Number} */ getAtlasIndex:function () { return this._atlasIndex; }, /** * set index of system in batch node array * @param {Number} atlasIndex */ setAtlasIndex:function (atlasIndex) { this._atlasIndex = atlasIndex; }, //true if scaled or rotated _transformSystemDirty:false, _allocatedParticles:0, //drawMode _drawMode:cc.PARTICLE_SHAPE_MODE, /** * Return DrawMode of ParticleSystem * @return {Number} */ getDrawMode:function () { return this._drawMode; }, /** * DrawMode of ParticleSystem setter * @param {Number} drawMode */ setDrawMode:function (drawMode) { this._drawMode = drawMode; }, //shape type _shapeType:cc.PARTICLE_BALL_SHAPE, /** * Return ShapeType of ParticleSystem * @return {Number} */ getShapeType:function () { return this._shapeType; }, /** * ShapeType of ParticleSystem setter * @param {Number} shapeType */ setShapeType:function (shapeType) { this._shapeType = shapeType; }, _isActive:false, /** * Return ParticleSystem is active * @return {Boolean} */ isActive:function () { return this._isActive; }, _particleCount:0, /** * Quantity of particles that are being simulated at the moment * @return {Number} */ getParticleCount:function () { return this._particleCount; }, /** * Quantity of particles setter * @param {Number} particleCount */ setParticleCount:function (particleCount) { this._particleCount = particleCount; }, _duration:0, /** * How many seconds the emitter wil run. -1 means 'forever' * @return {Number} */ getDuration:function () { return this._duration; }, /** * set run seconds of the emitter * @param {Number} duration */ setDuration:function (duration) { this._duration = duration; }, _sourcePosition:cc.PointZero(), /** * Return sourcePosition of the emitter * @return {cc.Point} */ getSourcePosition:function () { return this._sourcePosition; }, /** * sourcePosition of the emitter setter * @param sourcePosition */ setSourcePosition:function (sourcePosition) { this._sourcePosition = sourcePosition; }, _posVar:cc.PointZero(), /** * Return Position variance of the emitter * @return {cc.Point} */ getPosVar:function () { return this._posVar; }, /** * Position variance of the emitter setter * @param {cc.Point} posVar */ setPosVar:function (posVar) { this._posVar = posVar; }, _life:0, /** * Return life of each particle * @return {Number} */ getLife:function () { return this._life; }, /** * life of each particle setter * @param {Number} life */ setLife:function (life) { this._life = life; }, _lifeVar:0, /** * Return life variance of each particle * @return {Number} */ getLifeVar:function () { return this._lifeVar; }, /** * life variance of each particle setter * @param {Number} lifeVar */ setLifeVar:function (lifeVar) { this._lifeVar = lifeVar; }, _angle:0, /** * Return angle of each particle * @return {Number} */ getAngle:function () { return this._angle; }, /** * angle of each particle setter * @param {Number} angle */ setAngle:function (angle) { this._angle = angle; }, _angleVar:0, /** * Return angle variance of each particle * @return {Number} */ getAngleVar:function () { return this._angleVar; }, /** * angle variance of each particle setter * @param angleVar */ setAngleVar:function (angleVar) { this._angleVar = angleVar; }, // mode A /** * Return Gravity of emitter * @return {cc.Point} */ getGravity:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); return this.modeA.gravity; }, /** * Gravity of emitter setter * @param {cc.Point} gravity */ setGravity:function (gravity) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); this.modeA.gravity = gravity; }, /** * Return Speed of each particle * @return {Number} */ getSpeed:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); return this.modeA.speed; }, /** * Speed of each particle setter * @param {Number} speed */ setSpeed:function (speed) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); this.modeA.speed = speed; }, /** * return speed variance of each particle. Only available in 'Gravity' mode. * @return {Number} */ getSpeedVar:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); return this.modeA.speedVar; }, /** * speed variance of each particle setter. Only available in 'Gravity' mode. * @param {Number} speedVar */ setSpeedVar:function (speedVar) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); this.modeA.speedVar = speedVar; }, /** * Return tangential acceleration of each particle. Only available in 'Gravity' mode. * @return {Number} */ getTangentialAccel:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); return this.modeA.tangentialAccel; }, /** * Tangential acceleration of each particle setter. Only available in 'Gravity' mode. * @param {Number} tangentialAccel */ setTangentialAccel:function (tangentialAccel) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); this.modeA.tangentialAccel = tangentialAccel; }, /** * Return tangential acceleration variance of each particle. Only available in 'Gravity' mode. * @return {Number} */ getTangentialAccelVar:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); return this.modeA.tangentialAccelVar; }, /** * tangential acceleration variance of each particle setter. Only available in 'Gravity' mode. * @param {Number} tangentialAccelVar */ setTangentialAccelVar:function (tangentialAccelVar) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); this.modeA.tangentialAccelVar = tangentialAccelVar; }, /** * Return radial acceleration of each particle. Only available in 'Gravity' mode. * @return {Number} */ getRadialAccel:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); return this.modeA.radialAccel; }, /** * radial acceleration of each particle setter. Only available in 'Gravity' mode. * @param {Number} radialAccel */ setRadialAccel:function (radialAccel) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); this.modeA.radialAccel = radialAccel; }, /** * Return radial acceleration variance of each particle. Only available in 'Gravity' mode. * @return {Number} */ getRadialAccelVar:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); return this.modeA.radialAccelVar; }, /** * radial acceleration variance of each particle setter. Only available in 'Gravity' mode. * @param radialAccelVar */ setRadialAccelVar:function (radialAccelVar) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_GRAVITY, "Particle Mode should be Gravity"); this.modeA.radialAccelVar = radialAccelVar; }, // mode B /** * Return starting radius of the particles. Only available in 'Radius' mode. * @return {Number} */ getStartRadius:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); return this.modeB.startRadius; }, /** * starting radius of the particles setter. Only available in 'Radius' mode. * @param {Number} startRadius */ setStartRadius:function (startRadius) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); this.modeB.startRadius = startRadius; }, /** * Return starting radius variance of the particles. Only available in 'Radius' mode. * @return {Number} */ getStartRadiusVar:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); return this.modeB.startRadiusVar; }, /** * starting radius variance of the particles setter. Only available in 'Radius' mode. * @param {Number} startRadiusVar */ setStartRadiusVar:function (startRadiusVar) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); this.modeB.startRadiusVar = startRadiusVar; }, /** * Return ending radius of the particles. Only available in 'Radius' mode. * @return {Number} */ getEndRadius:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); return this.modeB.endRadius; }, /** * ending radius of the particles setter. Only available in 'Radius' mode. * @param {Number} endRadius */ setEndRadius:function (endRadius) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); this.modeB.endRadius = endRadius; }, /** * Return ending radius variance of the particles. Only available in 'Radius' mode. * @return {Number} */ getEndRadiusVar:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); return this.modeB.endRadiusVar; }, /** * ending radius variance of the particles setter. Only available in 'Radius' mode. * @param endRadiusVar */ setEndRadiusVar:function (endRadiusVar) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); this.modeB.endRadiusVar = endRadiusVar; }, /** * get Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. * @return {Number} */ getRotatePerSecond:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); return this.modeB.rotatePerSecond; }, /** * set Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. * @param {Number} degrees */ setRotatePerSecond:function (degrees) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); this.modeB.rotatePerSecond = degrees; }, /** * Return Variance in degrees for rotatePerSecond. Only available in 'Radius' mode. * @return {Number} */ getRotatePerSecondVar:function () { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); return this.modeB.rotatePerSecondVar; }, /** * Variance in degrees for rotatePerSecond setter. Only available in 'Radius' mode. * @param degrees */ setRotatePerSecondVar:function (degrees) { cc.Assert(this._emitterMode == cc.PARTICLE_MODE_RADIUS, "Particle Mode should be Radius"); this.modeB.rotatePerSecondVar = degrees; }, ////////////////////////////////////////////////////////////////////////// //don't use a transform matrix, this is faster setScale:function (scale, scaleY) { this._transformSystemDirty = true; cc.Node.prototype.setScale.call(this, scale, scaleY); }, setRotation:function (newRotation) { this._transformSystemDirty = true; cc.Node.prototype.setRotation.call(this, newRotation); }, setScaleX:function (newScaleX) { this._transformSystemDirty = true; cc.Node.prototype.setScaleX.call(this, newScaleX); }, setScaleY:function (newScaleY) { this._transformSystemDirty = true; cc.Node.prototype.setScaleY.call(this, newScaleY); }, _startSize:0, /** * get start size in pixels of each particle * @return {Number} */ getStartSize:function () { return this._startSize; }, /** * set start size in pixels of each particle * @param {Number} startSize */ setStartSize:function (startSize) { this._startSize = startSize; }, _startSizeVar:0, /** * get size variance in pixels of each particle * @return {Number} */ getStartSizeVar:function () { return this._startSizeVar; }, /** * set size variance in pixels of each particle * @param {Number} startSizeVar */ setStartSizeVar:function (startSizeVar) { this._startSizeVar = startSizeVar; }, _endSize:0, /** * get end size in pixels of each particle * @return {Number} */ getEndSize:function () { return this._endSize; }, /** * set end size in pixels of each particle * @param endSize */ setEndSize:function (endSize) { this._endSize = endSize; }, _endSizeVar:0, /** * get end size variance in pixels of each particle * @return {Number} */ getEndSizeVar:function () { return this._endSizeVar; }, /** * set end size variance in pixels of each particle * @param {Number} endSizeVar */ setEndSizeVar:function (endSizeVar) { this._endSizeVar = endSizeVar; }, _startColor:new cc.Color4F(0, 0, 0, 1), /** * set start color of each particle * @return {cc.Color4F} */ getStartColor:function () { return this._startColor; }, /** * get start color of each particle * @param {cc.Color4F} startColor */ setStartColor:function (startColor) { if (startColor instanceof cc.Color3B) startColor = cc.c4FFromccc3B(startColor); this._startColor = startColor; }, _startColorVar:new cc.Color4F(0, 0, 0, 1), /** * get start color variance of each particle * @return {cc.Color4F} */ getStartColorVar:function () { return this._startColorVar; }, /** * set start color variance of each particle * @param {cc.Color4F} startColorVar */ setStartColorVar:function (startColorVar) { if (startColorVar instanceof cc.Color3B) startColorVar = cc.c4FFromccc3B(startColorVar); this._startColorVar = startColorVar; }, _endColor:new cc.Color4F(0, 0, 0, 1), /** * get end color and end color variation of each particle * @return {cc.Color4F} */ getEndColor:function () { return this._endColor; }, /** * set end color and end color variation of each particle * @param {cc.Color4F} endColor */ setEndColor:function (endColor) { if (endColor instanceof cc.Color3B) endColor = cc.c4FFromccc3B(endColor); this._endColor = endColor; }, _endColorVar:new cc.Color4F(0, 0, 0, 1), /** * get end color variance of each particle * @return {cc.Color4F} */ getEndColorVar:function () { return this._endColorVar; }, /** * set end color variance of each particle * @param {cc.Color4F} endColorVar */ setEndColorVar:function (endColorVar) { if (endColorVar instanceof cc.Color3B) endColorVar = cc.c4FFromccc3B(endColorVar); this._endColorVar = endColorVar; }, _startSpin:0, /** * get initial angle of each particle * @return {Number} */ getStartSpin:function () { return this._startSpin; }, /** * set initial angle of each particle * @param {Number} startSpin */ setStartSpin:function (startSpin) { this._startSpin = startSpin; }, _startSpinVar:0, /** * get initial angle variance of each particle * @return {Number} */ getStartSpinVar:function () { return this._startSpinVar; }, /** * set initial angle variance of each particle * @param {Number} startSpinVar */ setStartSpinVar:function (startSpinVar) { this._startSpinVar = startSpinVar; }, _endSpin:0, /** * get end angle of each particle * @return {Number} */ getEndSpin:function () { return this._endSpin; }, /** * set end angle of each particle * @param {Number} endSpin */ setEndSpin:function (endSpin) { this._endSpin = endSpin; }, _endSpinVar:0, /** * get end angle variance of each particle * @return {Number} */ getEndSpinVar:function () { return this._endSpinVar; }, /** * set end angle variance of each particle * @param {Number} endSpinVar */ setEndSpinVar:function (endSpinVar) { this._endSpinVar = endSpinVar; }, _emissionRate:0, /** * get emission rate of the particles * @return {Number} */ getEmissionRate:function () { return this._emissionRate; }, /** * set emission rate of the particles * @param {Number} emissionRate */ setEmissionRate:function (emissionRate) { this._emissionRate = emissionRate; }, _totalParticles:0, /** * get maximum particles of the system * @return {Number} */ getTotalParticles:function () { return this._totalParticles; }, /** * set maximum particles of the system * @param {Number} totalParticles */ setTotalParticles:function (totalParticles) { cc.Assert(totalParticles <= this._allocatedParticles, "Particle: resizing particle array only supported for quads"); this._totalParticles = totalParticles; }, _texture:null, /** * get Texture of Particle System * @return {cc.Texture2D} */ getTexture:function () { return this._texture; }, /** * set Texture of Particle System * @param {cc.Texture2D | HTMLImageElement | HTMLCanvasElement} texture */ setTexture:function (texture) { if (this._texture != texture) { this._texture = texture; this._updateBlendFunc(); } }, /** conforms to CocosNodeTexture protocol */ _blendFunc: null, /** * get BlendFunc of Particle System * @return {cc.BlendFunc} */ getBlendFunc:function () { return this._blendFunc; }, /** * set BlendFunc of Particle System * @param {Number} src * @param {Number} dst */ setBlendFunc:function (src, dst) { if (arguments.length == 1) { if (this._blendFunc != src) { this._blendFunc = src; this._updateBlendFunc(); } } else { if (this._blendFunc.src != src || this._blendFunc.dst != dst) { this._blendFunc = {src:src, dst:dst}; this._updateBlendFunc(); } } }, _opacityModifyRGB:false, /** * does the alpha value modify color getter * @return {Boolean} */ getOpacityModifyRGB:function () { return this._opacityModifyRGB; }, /** * does the alpha value modify color setter * @param newValue */ setOpacityModifyRGB:function (newValue) { this._opacityModifyRGB = newValue; }, /** * <p>whether or not the particles are using blend additive.<br/> * If enabled, the following blending function will be used.<br/> * </p> * @return {Boolean} * @example * source blend function = GL_SRC_ALPHA; * dest blend function = GL_ONE; */ isBlendAdditive:function () { return (( this._blendFunc.src == gl.SRC_ALPHA && this._blendFunc.dst == gl.ONE) || (this._blendFunc.src == gl.ONE && this._blendFunc.dst == gl.ONE)); }, /** * <p>whether or not the particles are using blend additive.<br/> * If enabled, the following blending function will be used.<br/> * </p> * @param {Boolean} isBlendAdditive */ setBlendAdditive:function (isBlendAdditive) { if (isBlendAdditive) { this._blendFunc.src = gl.SRC_ALPHA; this._blendFunc.dst = gl.ONE; } else { if (cc.renderContextType === cc.WEBGL) { if (this._texture && !this._texture.hasPremultipliedAlpha()) { this._blendFunc.src = gl.SRC_ALPHA; this._blendFunc.dst = gl.ONE_MINUS_SRC_ALPHA; } else { this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; } } else { this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; } } }, _positionType:cc.PARTICLE_TYPE_FREE, /** * get particles movement type: Free or Grouped * @return {Number} */ getPositionType:function () { return this._positionType; }, /** * set particles movement type: Free or Grouped * @param {Number} positionType */ setPositionType:function (positionType) { this._positionType = positionType; }, _isAutoRemoveOnFinish:false, /** * <p> return whether or not the node will be auto-removed when it has no particles left.<br/> * By default it is false.<br/> * </p> * @return {Boolean} */ isAutoRemoveOnFinish:function () { return this._isAutoRemoveOnFinish; }, /** * <p> set whether or not the node will be auto-removed when it has no particles left.<br/> * By default it is false.<br/> * </p> * @param {Boolean} isAutoRemoveOnFinish */ setAutoRemoveOnFinish:function (isAutoRemoveOnFinish) { this._isAutoRemoveOnFinish = isAutoRemoveOnFinish; }, _emitterMode:0, /** * return kind of emitter modes * @return {Number} */ getEmitterMode:function () { return this._emitterMode; }, /** * <p>Switch between different kind of emitter modes:<br/> * - CCPARTICLE_MODE_GRAVITY: uses gravity, speed, radial and tangential acceleration<br/> * - CCPARTICLE_MODE_RADIUS: uses radius movement + rotation <br/> * </p> * @param {Number} emitterMode */ setEmitterMode:function (emitterMode) { this._emitterMode = emitterMode; }, /** * Constructor * @override */ ctor:function () { cc.Node.prototype.ctor.call(this); this._emitterMode = cc.PARTICLE_MODE_GRAVITY; this.modeA = new cc.ParticleSystem.ModeA(); this.modeB = new cc.ParticleSystem.ModeB(); this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST}; this._particles = []; this._sourcePosition = new cc.Point(0, 0); this._posVar = new cc.Point(0, 0); this._startColor = new cc.Color4F(1, 1, 1, 1); this._startColorVar = new cc.Color4F(1, 1, 1, 1); this._endColor = new cc.Color4F(1, 1, 1, 1); this._endColorVar = new cc.Color4F(1, 1, 1, 1); }, /** * initializes a cc.ParticleSystem */ init:function () { return this.initWithTotalParticles(150); }, /** * <p> * initializes a CCParticleSystem from a plist file. <br/> * This plist files can be creted manually or with Particle Designer:<br/> * http://particledesigner.71squared.com/ * </p> * @param {String} plistFile * @return {cc.ParticleSystem} */ initWithFile:function (plistFile) { this._plistFile = plistFile; var dict = cc.FileUtils.getInstance().dictionaryWithContentsOfFileThreadSafe(this._plistFile); cc.Assert(dict != null, "Particles: file not found"); // XXX compute path from a path, should define a function somewhere to do it return this.initWithDictionary(dict, ""); }, /** * return bounding box of particle system in world space * @return {cc.Rect} */ getBoundingBoxToWorld:function () { return cc.rect(0, 0, cc.canvas.width, cc.canvas.height); }, /** * initializes a particle system from a NSDictionary and the path from where to load the png * @param {object} dictionary * @param {String} dirname * @return {Boolean} */ initWithDictionary:function (dictionary, dirname) { var ret = false; var buffer = null; var image = null; var maxParticles = parseInt(this._valueForKey("maxParticles", dictionary)); // self, not super if (this.initWithTotalParticles(maxParticles)) { // angle this._angle = parseFloat(this._valueForKey("angle", dictionary)); this._angleVar = parseFloat(this._valueForKey("angleVariance", dictionary)); // duration this._duration = parseFloat(this._valueForKey("duration", dictionary)); // blend function this._blendFunc.src = parseInt(this._valueForKey("blendFuncSource", dictionary)); this._blendFunc.dst = parseInt(this._valueForKey("blendFuncDestination", dictionary)); // color this._startColor.r = parseFloat(this._valueForKey("startColorRed", dictionary)); this._startColor.g = parseFloat(this._valueForKey("startColorGreen", dictionary)); this._startColor.b = parseFloat(this._valueForKey("startColorBlue", dictionary)); this._startColor.a = parseFloat(this._valueForKey("startColorAlpha", dictionary)); this._startColorVar.r = parseFloat(this._valueForKey("startColorVarianceRed", dictionary)); this._startColorVar.g = parseFloat(this._valueForKey("startColorVarianceGreen", dictionary)); this._startColorVar.b = parseFloat(this._valueForKey("startColorVarianceBlue", dictionary)); this._startColorVar.a = parseFloat(this._valueForKey("startColorVarianceAlpha", dictionary)); this._endColor.r = parseFloat(this._valueForKey("finishColorRed", dictionary)); this._endColor.g = parseFloat(this._valueForKey("finishColorGreen", dictionary)); this._endColor.b = parseFloat(this._valueForKey("finishColorBlue", dictionary)); this._endColor.a = parseFloat(this._valueForKey("finishColorAlpha", dictionary)); this._endColorVar.r = parseFloat(this._valueForKey("finishColorVarianceRed", dictionary)); this._endColorVar.g = parseFloat(this._valueForKey("finishColorVarianceGreen", dictionary)); this._endColorVar.b = parseFloat(this._valueForKey("finishColorVarianceBlue", dictionary)); this._endColorVar.a = parseFloat(this._valueForKey("finishColorVarianceAlpha", dictionary)); // particle size this._startSize = parseFloat(this._valueForKey("startParticleSize", dictionary)); this._startSizeVar = parseFloat(this._valueForKey("startParticleSizeVariance", dictionary)); this._endSize = parseFloat(this._valueForKey("finishParticleSize", dictionary)); this._endSizeVar = parseFloat(this._valueForKey("finishParticleSizeVariance", dictionary)); // position var x = parseFloat(this._valueForKey("sourcePositionx", dictionary)); var y = parseFloat(this._valueForKey("sourcePositiony", dictionary)); this.setPosition(cc.p(x, y)); this._posVar.x = parseFloat(this._valueForKey("sourcePositionVariancex", dictionary)); this._posVar.y = parseFloat(this._valueForKey("sourcePositionVariancey", dictionary)); // Spinning this._startSpin = parseFloat(this._valueForKey("rotationStart", dictionary)); this._startSpinVar = parseFloat(this._valueForKey("rotationStartVariance", dictionary)); this._endSpin = parseFloat(this._valueForKey("rotationEnd", dictionary)); this._endSpinVar = parseFloat(this._valueForKey("rotationEndVariance", dictionary)); this._emitterMode = parseInt(this._valueForKey("emitterType", dictionary)); // Mode A: Gravity + tangential accel + radial accel if (this._emitterMode == cc.PARTICLE_MODE_GRAVITY) { // gravity this.modeA.gravity.x = parseFloat(this._valueForKey("gravityx", dictionary)); this.modeA.gravity.y = parseFloat(this._valueForKey("gravityy", dictionary)); // speed this.modeA.speed = parseFloat(this._valueForKey("speed", dictionary)); this.modeA.speedVar = parseFloat(this._valueForKey("speedVariance", dictionary)); // radial acceleration var pszTmp = this._valueForKey("radialAcceleration", dictionary); this.modeA.radialAccel = (pszTmp) ? parseFloat(pszTmp) : 0; pszTmp = this._valueForKey("radialAccelVariance", dictionary); this.modeA.radialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0; // tangential acceleration pszTmp = this._valueForKey("tangentialAcceleration", dictionary); this.modeA.tangentialAccel = (pszTmp) ? parseFloat(pszTmp) : 0; pszTmp = this._valueForKey("tangentialAccelVariance", dictionary); this.modeA.tangentialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0; } else if (this._emitterMode == cc.PARTICLE_MODE_RADIUS) { // or Mode B: radius movement this.modeB.startRadius = parseFloat(this._valueForKey("maxRadius", dictionary)); this.modeB.startRadiusVar = parseFloat(this._valueForKey("maxRadiusVariance", dictionary)); this.modeB.endRadius = parseFloat(this._valueForKey("minRadius", dictionary)); this.modeB.endRadiusVar = 0; this.modeB.rotatePerSecond = parseFloat(this._valueForKey("rotatePerSecond", dictionary)); this.modeB.rotatePerSecondVar = parseFloat(this._valueForKey("rotatePerSecondVariance", dictionary)); } else { cc.Assert(false, "Invalid emitterType in config file"); return false; } // life span this._life = parseFloat(this._valueForKey("particleLifespan", dictionary)); this._lifeVar = parseFloat(this._valueForKey("particleLifespanVariance", dictionary)); // emission Rate this._emissionRate = this._totalParticles / this._life; //don't get the internal texture if a batchNode is used if (!this._batchNode) { // Set a compatible default for the alpha transfer this._opacityModifyRGB = false; // texture // Try to get the texture from the cache var textureName = this._valueForKey("textureFileName", dictionary); var fullpath = cc.FileUtils.getInstance().fullPathFromRelativeFile(textureName, this._plistFile); var tex = cc.TextureCache.getInstance().textureForKey(fullpath); if (tex) { this.setTexture(tex); } else { var textureData = this._valueForKey("textureImageData", dictionary); if (textureData && textureData.length == 0) { cc.Assert(textureData, "cc.ParticleSystem.initWithDictory:textureImageData is null"); tex = cc.TextureCache.getInstance().addImage(fullpath); if (!tex) return false; this.setTexture(tex); } else { buffer = cc.unzipBase64AsArray(textureData, 1); if (!buffer) { cc.log("cc.ParticleSystem: error decoding or ungzipping textureImageData"); return false; } var imageFormat = cc.getImageFormatByData(buffer); if(imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG){ cc.log("cc.ParticleSystem: unknown image format with Data"); return false; } var canvasObj = document.createElement("canvas"); if(imageFormat === cc.FMT_PNG){ var myPngObj = new cc.PNGReader(buffer); myPngObj.render(canvasObj); } else { var myTIFFObj = cc.TIFFReader.getInstance(); myTIFFObj.parseTIFF(buffer,canvasObj); } cc.TextureCache.getInstance().cacheImage(fullpath, canvasObj); var addTexture = cc.TextureCache.getInstance().textureForKey(fullpath); cc.Assert(addTexture != null, "cc.ParticleSystem: error loading the texture"); if (cc.renderContextType === cc.CANVAS) this.setTexture(canvasObj); else this.setTexture(addTexture); } } } ret = true; } return ret; }, /** * Initializes a system with a fixed number of particles * @param {Number} numberOfParticles * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { this._totalParticles = numberOfParticles; var i; this._particles = []; for(i = 0; i< numberOfParticles; i++){ this._particles[i] = new cc.Particle(); } if (!this._particles) { cc.log("Particle system: not enough memory"); return false; } this._allocatedParticles = numberOfParticles; if (this._batchNode) for (i = 0; i < this._totalParticles; i++) this._particles[i].atlasIndex = i; // default, active this._isActive = true; // default blend function this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; // default movement type; this._positionType = cc.PARTICLE_TYPE_FREE; // by default be in mode A: this._emitterMode = cc.PARTICLE_MODE_GRAVITY; // default: modulate // XXX: not used // colorModulate = YES; this._isAutoRemoveOnFinish = false; // Optimization: compile udpateParticle method //updateParticleSel = @selector(updateQuadWithParticle:newPosition:); //updateParticleImp = (CC_UPDATE_PARTICLE_IMP) [self methodForSelector:updateParticleSel]; //for batchNode this._transformSystemDirty = false; // udpate after action in run! this.scheduleUpdateWithPriority(1); return true; }, destroyParticleSystem:function () { this.unscheduleUpdate(); }, /** * Add a particle to the emitter * @return {Boolean} */ addParticle: function () { if (this.isFull()) return false; var particle, particles = this._particles; if (cc.renderContextType === cc.CANVAS) { if (this._particleCount < particles.length) { particle = particles[this._particleCount]; } else { particle = new cc.Particle(); particles.push(particle); } } else { particle = particles[this._particleCount]; } this.initParticle(particle); ++this._particleCount; return true; }, /** * Initializes a particle * @param {cc.Particle} particle */ initParticle:function (particle) { // timeToLive // no negative life. prevent division by 0 particle.timeToLive = this._life + this._lifeVar * cc.RANDOM_MINUS1_1(); particle.timeToLive = Math.max(0, particle.timeToLive); // position particle.pos.x = this._sourcePosition.x + this._posVar.x * cc.RANDOM_MINUS1_1(); particle.pos.y = this._sourcePosition.y + this._posVar.y * cc.RANDOM_MINUS1_1(); // Color var start, end; if (cc.renderContextType === cc.CANVAS) { start = new cc.Color4F( cc.clampf(this._startColor.r + this._startColorVar.r * cc.RANDOM_MINUS1_1(), 0, 1), cc.clampf(this._startColor.g + this._startColorVar.g * cc.RANDOM_MINUS1_1(), 0, 1), cc.clampf(this._startColor.b + this._startColorVar.b * cc.RANDOM_MINUS1_1(), 0, 1), cc.clampf(this._startColor.a + this._startColorVar.a * cc.RANDOM_MINUS1_1(), 0, 1) ); end = new cc.Color4F( cc.clampf(this._endColor.r + this._endColorVar.r * cc.RANDOM_MINUS1_1(), 0, 1), cc.clampf(this._endColor.g + this._endColorVar.g * cc.RANDOM_MINUS1_1(), 0, 1), cc.clampf(this._endColor.b + this._endColorVar.b * cc.RANDOM_MINUS1_1(), 0, 1), cc.clampf(this._endColor.a + this._endColorVar.a * cc.RANDOM_MINUS1_1(), 0, 1) ); } else { start = { r: cc.clampf(this._startColor.r + this._startColorVar.r * cc.RANDOM_MINUS1_1(), 0, 1), g: cc.clampf(this._startColor.g + this._startColorVar.g * cc.RANDOM_MINUS1_1(), 0, 1), b: cc.clampf(this._startColor.b + this._startColorVar.b * cc.RANDOM_MINUS1_1(), 0, 1), a: cc.clampf(this._startColor.a + this._startColorVar.a * cc.RANDOM_MINUS1_1(), 0, 1) }; end = { r: cc.clampf(this._endColor.r + this._endColorVar.r * cc.RANDOM_MINUS1_1(), 0, 1), g: cc.clampf(this._endColor.g + this._endColorVar.g * cc.RANDOM_MINUS1_1(), 0, 1), b: cc.clampf(this._endColor.b + this._endColorVar.b * cc.RANDOM_MINUS1_1(), 0, 1), a: cc.clampf(this._endColor.a + this._endColorVar.a * cc.RANDOM_MINUS1_1(), 0, 1) }; } particle.color = start; particle.deltaColor.r = (end.r - start.r) / particle.timeToLive; particle.deltaColor.g = (end.g - start.g) / particle.timeToLive; particle.deltaColor.b = (end.b - start.b) / particle.timeToLive; particle.deltaColor.a = (end.a - start.a) / particle.timeToLive; // size var startS = this._startSize + this._startSizeVar * cc.RANDOM_MINUS1_1(); startS = Math.max(0, startS); // No negative value particle.size = startS; if (this._endSize === cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE) { particle.deltaSize = 0; } else { var endS = this._endSize + this._endSizeVar * cc.RANDOM_MINUS1_1(); endS = Math.max(0, endS); // No negative values particle.deltaSize = (endS - startS) / particle.timeToLive; } // rotation var startA = this._startSpin + this._startSpinVar * cc.RANDOM_MINUS1_1(); var endA = this._endSpin + this._endSpinVar * cc.RANDOM_MINUS1_1(); particle.rotation = startA; particle.deltaRotation = (endA - startA) / particle.timeToLive; // position if (this._positionType == cc.PARTICLE_TYPE_FREE) particle.startPos = this.convertToWorldSpace(this._pointZeroForParticle); else if (this._positionType == cc.PARTICLE_TYPE_RELATIVE) particle.startPos = this._position; // direction var a = cc.DEGREES_TO_RADIANS(this._angle + this._angleVar * cc.RANDOM_MINUS1_1()); // Mode Gravity: A if (this._emitterMode === cc.PARTICLE_MODE_GRAVITY) { var s = this.modeA.speed + this.modeA.speedVar * cc.RANDOM_MINUS1_1(); // direction particle.modeA.dir.x = Math.cos(a); particle.modeA.dir.y = Math.sin(a); cc.pMultIn(particle.modeA.dir, s); // radial accel particle.modeA.radialAccel = this.modeA.radialAccel + this.modeA.radialAccelVar * cc.RANDOM_MINUS1_1(); // tangential accel particle.modeA.tangentialAccel = this.modeA.tangentialAccel + this.modeA.tangentialAccelVar * cc.RANDOM_MINUS1_1(); } else { // Mode Radius: B // Set the default diameter of the particle from the source position var startRadius = this.modeB.startRadius + this.modeB.startRadiusVar * cc.RANDOM_MINUS1_1(); var endRadius = this.modeB.endRadius + this.modeB.endRadiusVar * cc.RANDOM_MINUS1_1(); particle.modeB.radius = startRadius; if (this.modeB.endRadius === cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS) { particle.modeB.deltaRadius = 0; } else { particle.modeB.deltaRadius = (endRadius - startRadius) / particle.timeToLive; } particle.modeB.angle = a; particle.modeB.degreesPerSecond = cc.DEGREES_TO_RADIANS(this.modeB.rotatePerSecond + this.modeB.rotatePerSecondVar * cc.RANDOM_MINUS1_1()); } }, /** * stop emitting particles. Running particles will continue to run until they die */ stopSystem:function () { this._isActive = false; this._elapsed = this._duration; this._emitCounter = 0; }, /** * Kill all living particles. */ resetSystem:function () { this._isActive = true; this._elapsed = 0; for (this._particleIdx = 0; this._particleIdx < this._particleCount; ++this._particleIdx) this._particles[this._particleIdx].timeToLive = 0 ; }, /** * whether or not the system is full * @return {Boolean} */ isFull:function () { return (this._particleCount >= this._totalParticles); }, /** * should be overridden by subclasses * @param {cc.Particle} particle * @param {cc.Point} newPosition */ updateQuadWithParticle:function (particle, newPosition) { // should be overriden }, /** * should be overridden by subclasses */ postStep:function () { // should be overriden }, /** * update emitter's status * @override * @param {Number} dt delta time */ update:function (dt) { if (this._isActive && this._emissionRate) { var rate = 1.0 / this._emissionRate; //issue #1201, prevent bursts of particles, due to too high emitCounter if (this._particleCount < this._totalParticles) this._emitCounter += dt; while ((this._particleCount < this._totalParticles) && (this._emitCounter > rate)) { this.addParticle(); this._emitCounter -= rate; } this._elapsed += dt; if (this._duration != -1 && this._duration < this._elapsed) this.stopSystem(); } this._particleIdx = 0; var currentPosition = cc.Particle.TemporaryPoints[0]; if (this._positionType == cc.PARTICLE_TYPE_FREE) { cc.pIn(currentPosition, this.convertToWorldSpace(this._pointZeroForParticle)); } else if (this._positionType == cc.PARTICLE_TYPE_RELATIVE) { currentPosition.x = this._position.x; currentPosition.y = this._position.y; } if (this._visible) { // Used to reduce memory allocation / creation within the loop var tpa = cc.Particle.TemporaryPoints[1], tpb = cc.Particle.TemporaryPoints[2], tpc = cc.Particle.TemporaryPoints[3]; while (this._particleIdx < this._particleCount) { // Reset the working particles cc.pZeroIn(tpa); cc.pZeroIn(tpb); cc.pZeroIn(tpc); var selParticle = this._particles[this._particleIdx]; // life selParticle.timeToLive -= dt; if (selParticle.timeToLive > 0) { // Mode A: gravity, direction, tangential accel & radial accel if (this._emitterMode == cc.PARTICLE_MODE_GRAVITY) { var tmp = tpc, radial = tpa, tangential = tpb; // radial acceleration if (selParticle.pos.x || selParticle.pos.y) { cc.pIn(radial, selParticle.pos); cc.pNormalizeIn(radial); } else { cc.pZeroIn(radial); } cc.pIn(tangential, radial); cc.pMultIn(radial, selParticle.modeA.radialAccel); // tangential acceleration var newy = tangential.x; tangential.x = -tangential.y; tangential.y = newy; cc.pMultIn(tangential, selParticle.modeA.tangentialAccel); cc.pIn(tmp, radial); cc.pAddIn(tmp, tangential); cc.pAddIn(tmp, this.modeA.gravity); cc.pMultIn(tmp, dt); cc.pAddIn(selParticle.modeA.dir, tmp); cc.pIn(tmp, selParticle.modeA.dir); cc.pMultIn(tmp, dt); cc.pAddIn(selParticle.pos, tmp); } else { // Mode B: radius movement var selModeB = selParticle.modeB; // Update the angle and radius of the particle. selModeB.angle += selModeB.degreesPerSecond * dt; selModeB.radius += selModeB.deltaRadius * dt; selParticle.pos.x = -Math.cos(selModeB.angle) * selModeB.radius; selParticle.pos.y = -Math.sin(selModeB.angle) * selModeB.radius; } // color if (!this._dontTint) { selParticle.color.r += (selParticle.deltaColor.r * dt); selParticle.color.g += (selParticle.deltaColor.g * dt); selParticle.color.b += (selParticle.deltaColor.b * dt); selParticle.color.a += (selParticle.deltaColor.a * dt); selParticle.isChangeColor = true; } // size selParticle.size += (selParticle.deltaSize * dt); selParticle.size = Math.max(0, selParticle.size); // angle selParticle.rotation += (selParticle.deltaRotation * dt); // // update values in quad // var newPos = tpa; if (this._positionType == cc.PARTICLE_TYPE_FREE || this._positionType == cc.PARTICLE_TYPE_RELATIVE) { var diff = tpb; cc.pIn(diff, currentPosition); cc.pSubIn(diff, selParticle.startPos); cc.pIn(newPos, selParticle.pos); cc.pSubIn(newPos, diff); } else { cc.pIn(newPos, selParticle.pos); } // translate newPos to correct position, since matrix transform isn't performed in batchnode // don't update the particle with the new position information, it will interfere with the radius and tangential calculations if (this._batchNode) { newPos.x += this._position.x; newPos.y += this._position.y; } if (cc.renderContextType == cc.WEBGL) { // IMPORTANT: newPos may not be used as a reference here! (as it is just the temporary tpa point) // the implementation of updateQuadWithParticle must use // the x and y values directly this.updateQuadWithParticle(selParticle, newPos); } else { cc.pIn(selParticle.drawPos, newPos); } //updateParticleImp(self, updateParticleSel, p, newPos); // update particle counter ++this._particleIdx; } else { // life < 0 var currentIndex = selParticle.atlasIndex; if(this._particleIdx !== this._particleCount -1){ var deadParticle = this._particles[this._particleIdx]; this._particles[this._particleIdx] = this._particles[this._particleCount -1]; this._particles[this._particleCount -1] = deadParticle; } if (this._batchNode) { //disable the switched particle this._batchNode.disableParticle(this._atlasIndex + currentIndex); //switch indexes this._particles[this._particleCount - 1].atlasIndex = currentIndex; } --this._particleCount; if (this._particleCount == 0 && this._isAutoRemoveOnFinish) { this.unscheduleUpdate(); this._parent.removeChild(this, true); return; } } } this._transformSystemDirty = false; } if (!this._batchNode) this.postStep(); //cc.PROFILER_STOP_CATEGORY(kCCProfilerCategoryParticles , "cc.ParticleSystem - update"); }, updateWithNoTime:function () { this.update(0); }, /** * return the string found by key in dict. * @param {string} key * @param {object} dict * @return {String} "" if not found; return the string if found. * @private */ _valueForKey:function (key, dict) { if (dict) { var pString = dict[key]; return pString != null ? pString : ""; } return ""; }, _updateBlendFunc:function () { cc.Assert(!this._batchNode, "Can't change blending functions when the particle is being batched"); if (this._texture) { if ((this._texture instanceof HTMLImageElement) || (this._texture instanceof HTMLCanvasElement)) { } else { var premultiplied = this._texture.hasPremultipliedAlpha(); this._opacityModifyRGB = false; if (this._texture && ( this._blendFunc.src == cc.BLEND_SRC && this._blendFunc.dst == cc.BLEND_DST )) { if (premultiplied) { this._opacityModifyRGB = true; } else { this._blendFunc.src = gl.SRC_ALPHA; this._blendFunc.dst = gl.ONE_MINUS_SRC_ALPHA; } } } } } }); /** * <p> return the string found by key in dict. <br/> * This plist files can be creted manually or with Particle Designer:<br/> * http://particledesigner.71squared.com/<br/> * </p> * @param {String} plistFile * @return {cc.ParticleSystem} */ cc.ParticleSystem.create = function (plistFile) { return cc.ParticleSystemQuad.create(plistFile); /*var particle = new cc.ParticleSystem(); if (particle && particle.initWithFile(plistFile)) return particle; return null;*/ }; /** * create a system with a fixed number of particles * @param {Number} number_of_particles * @return {cc.ParticleSystem} */ cc.ParticleSystem.createWithTotalParticles = function (number_of_particles) { return cc.ParticleSystemQuad.create(number_of_particles); /*//emitter.initWithTotalParticles(number_of_particles); var particle = new cc.ParticleSystem(); if (particle && particle.initWithTotalParticles(number_of_particles)) return particle; return null;*/ }; // Different modes /** * Mode A:Gravity + Tangential Accel + Radial Accel * @Class * @Construct * @param {cc.Point} gravity Gravity value. * @param {Number} speed speed of each particle. * @param {Number} speedVar speed variance of each particle. * @param {Number} tangentialAccel tangential acceleration of each particle. * @param {Number} tangentialAccelVar tangential acceleration variance of each particle. * @param {Number} radialAccel radial acceleration of each particle. * @param {Number} radialAccelVar radial acceleration variance of each particle. */ cc.ParticleSystem.ModeA = function (gravity, speed, speedVar, tangentialAccel, tangentialAccelVar, radialAccel, radialAccelVar) { /** Gravity value. Only available in 'Gravity' mode. */ this.gravity = gravity ? gravity : cc.PointZero(); /** speed of each particle. Only available in 'Gravity' mode. */ this.speed = speed || 0; /** speed variance of each particle. Only available in 'Gravity' mode. */ this.speedVar = speedVar || 0; /** tangential acceleration of each particle. Only available in 'Gravity' mode. */ this.tangentialAccel = tangentialAccel || 0; /** tangential acceleration variance of each particle. Only available in 'Gravity' mode. */ this.tangentialAccelVar = tangentialAccelVar || 0; /** radial acceleration of each particle. Only available in 'Gravity' mode. */ this.radialAccel = radialAccel || 0; /** radial acceleration variance of each particle. Only available in 'Gravity' mode. */ this.radialAccelVar = radialAccelVar || 0; }; /** * Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode) * @Class * @Construct * @param {Number} startRadius The starting radius of the particles. * @param {Number} startRadiusVar The starting radius variance of the particles. * @param {Number} endRadius The ending radius of the particles. * @param {Number} endRadiusVar The ending radius variance of the particles. * @param {Number} rotatePerSecond Number of degress to rotate a particle around the source pos per second. * @param {Number} rotatePerSecondVar Variance in degrees for rotatePerSecond. */ cc.ParticleSystem.ModeB = function (startRadius, startRadiusVar, endRadius, endRadiusVar, rotatePerSecond, rotatePerSecondVar) { /** The starting radius of the particles. Only available in 'Radius' mode. */ this.startRadius = startRadius || 0; /** The starting radius variance of the particles. Only available in 'Radius' mode. */ this.startRadiusVar = startRadiusVar || 0; /** The ending radius of the particles. Only available in 'Radius' mode. */ this.endRadius = endRadius || 0; /** The ending radius variance of the particles. Only available in 'Radius' mode. */ this.endRadiusVar = endRadiusVar || 0; /** Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. */ this.rotatePerSecond = rotatePerSecond || 0; /** Variance in degrees for rotatePerSecond. Only available in 'Radius' mode. */ this.rotatePerSecondVar = rotatePerSecondVar || 0; };
(function () { 'use strict'; angular.module('auth.notifications') .factory('NotificationsServ', function ($q, url, users, $firebaseObject, $firebaseArray, userAuth) { var ref = new Firebase(users); function addNotificationsToUserType(keys, usersObj, event, userType) { var promises = []; angular.forEach(keys, function (key) { var user = usersObj[key]; if (user.profile.role === userType) { var managerRef=new Firebase(users+key+'/profile/'+'notifications'); var notificationsArr = $firebaseArray(managerRef); var addPromise = notificationsArr.$add(event); promises.push(addPromise); } }); return $q.all(promises); } return { markNotificationOpened: function (notification) { var userKey = userAuth.key; var notificationUrl = users + userKey + '/profile/notifications/' + notification; return $q(function (resolve, reject) { var notificationObject = $firebaseObject(new Firebase(notificationUrl)); notificationObject.$loaded().then(function () { notificationObject.opened = true; notificationObject.$save().then(function () { resolve(); }) }) }); }, markAllNotificationsOpened: function () { var userKey = userAuth.key; var notificationUrl = users + userKey + '/profile/notifications/'; return $q(function (resolve, reject) { var notificationsArray = $firebaseArray(new Firebase(notificationUrl)); notificationsArray.$loaded().then(function () { notificationsArray.forEach(function (notification) { notification.opened = true; notificationsArray.$save(notification); }); }) }); }, addToCustomers: function (notification) { return $q(function (resolve, reject) { var usersObj = $firebaseObject(new Firebase(users)); usersObj.$loaded().then(function () { var keys = _.chain(usersObj).keysIn().filter(function (key) { return !_.startsWith(key, '$') && key !== 'forEach'; }).value(); addNotificationsToUserType(keys, usersObj, notification, 'customer').then(function (resolvedArray) { resolve(resolvedArray); }).catch(function (error) { reject(error); }); }) }); }, addToManagers: function (notification) { return $q(function (resolve, reject) { var usersObj = $firebaseObject(new Firebase(users)); usersObj.$loaded().then(function () { var keys = _.chain(usersObj).keysIn().filter(function (key) { return !_.startsWith(key, '$') && key !== 'forEach'; }).value(); addNotificationsToUserType(keys, usersObj, notification, 'manager').then(function (resolvedArray) { resolve(resolvedArray); }).catch(function (error) { reject(error); }); }) }); } }; }); })();
/* global describe, it, require */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Deep close to: deepCloseTo = require( './utils/deepcloseto.js' ), // Module to be tested: variance = require( './../lib/array.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'array variance', function tests() { it( 'should export a function', function test() { expect( variance ).to.be.a( 'function' ); }); it( 'should compute the distribution variance', function test() { var k, actual, expected; k = [ 2, 4, 8, 16 ]; actual = new Array( k.length ); actual = variance( actual, k ); expected = [ 4, 8, 16, 32 ]; assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) ); }); it( 'should return an empty array if provided an empty array', function test() { assert.deepEqual( variance( [], [] ), [] ); }); it( 'should handle non-numeric values by setting the element to NaN', function test() { var data, actual, expected; data = [ true, null, [], {} ]; actual = new Array( data.length ); actual = variance( actual, data ); expected = [ NaN, NaN, NaN, NaN ]; assert.deepEqual( actual, expected ); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; /** * Copyright (c) 2018-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ /* eslint-disable no-redeclare */ // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 var isInteger = Number.isInteger || function (value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; }; var _default = isInteger; exports.default = _default;
const flatten = v => [].concat(...v) const mapObject = (obj, map) => Object.entries(obj) .reduce((acc, [key, value]) => { const v = map(key, value) if(isDefined(v)) { const [newKey, newValue] = v acc[newKey] = newValue } return acc }, {}) const toArray = arg => [].concat(arg) const isArray = Array.isArray const isFunction = arg => typeof arg === 'function' const isString = arg => typeof arg === 'string' const isObject = arg => typeof arg === 'object' const isUndefined = arg => arg === undefined const isDefined = arg => arg !== undefined const unique = arg => [...new Set(arg)] export {flatten, mapObject, unique, toArray, isArray, isFunction, isString, isObject, isUndefined, isDefined}
// Copyright 2012 Dan Wolff | danwolff.se // // 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. require('object.assign').shim(); var fs = require('fs'); var path = require('path'); var os = require('os'); var cheerio = require('cheerio'); // requires Node v0.11.12 var child_process = require('child_process'); var useCompilers = String(process.argv[2]).toLowerCase() === "compilers"; var isOptional = function isOptional(category) { return (category || '').indexOf('annex b')>-1 || category === 'pre-strawman' || category === 'strawman (stage 0)'; }; // let prototypes declared below in this file be initialized process.nextTick(function () { var es5 = require('./data-es5'); handle(es5); var es6 = require('./data-es6'); handle(es6); var esnext = require('./data-esnext'); handle(esnext); handle(require('./data-esintl')); handle(require('./data-non-standard')); // ES6 compilers if (!useCompilers) { return; } if (!fs.existsSync('es5/compilers')) { fs.mkdirSync('es5/compilers'); } if (!fs.existsSync('es6/compilers')) { fs.mkdirSync('es6/compilers'); } if (!fs.existsSync('esnext/compilers')) { fs.mkdirSync('esnext/compilers'); } var closure = require('closurecompiler'); var babel = require('babel-core'); var traceur = require('traceur'); var esdown = require('esdown'); var jstransform = require('jstransform/simple'); var ts = require('typescript'); var esprima = require('esprima'); var espree = require('espree'); var jshint = require('jshint'); [ { name: 'es5-shim', url: 'https://github.com/es-shims/es5-shim', target_file: 'es5/compilers/es5-shim.html', polyfills: ['node_modules/es5-shim/es5-shim.js'], compiler: String, }, ].forEach(function(e){ Object.assign(es5, e); es5.browsers = {}; es5.skeleton_file = 'es5/compiler-skeleton.html'; handle(es5); }); [ { name: 'es6-shim', url: 'https://github.com/paulmillr/es6-shim/', target_file: 'es6/compilers/es6-shim.html', polyfills: ['node_modules/es6-shim/es6-shim.js'], compiler: String, }, { name: 'Traceur', url: 'https://github.com/google/traceur-compiler/', target_file: 'es6/compilers/traceur.html', polyfills: ['node_modules/traceur/bin/traceur-runtime.js'], compiler: function(code) { return traceur.compile(code); }, }, { name: 'babel', url: 'https://babeljs.io/', target_file: 'es6/compilers/babel.html', polyfills: [], compiler: function(code) { return babel.transform(code, {presets: ['es2015']}).code; }, }, { name: 'babel + core-js', url: 'https://babeljs.io/', target_file: 'es6/compilers/babel-core-js.html', polyfills: ['node_modules/babel-polyfill/browser.js'], compiler: function(code) { return babel.transform(code, {presets: ['es2015']}).code; }, }, { name: 'ES6 Transpiler', url: 'https://github.com/termi/es6-transpiler', target_file: 'es6/compilers/es6-transpiler.html', polyfills: [], compiler: (function() { var es6tr; return function(code) { // Known bug: running require('es6-transpiler') causes babel to break. // So, it's run here, as late as possible. es6tr = es6tr || require('es6-transpiler'); var result = es6tr.run({src:code}); if (result.src) { return result.src; } throw new Error('\n' + result.errors.join('\n')); }; }()), }, { name: 'esdown', url: 'https://github.com/zenparsing/esdown', target_file: 'es6/compilers/esdown.html', polyfills: [], compiler: function(code) { return esdown.transform(code, { runtime: true, polyfill: true }); }, }, { name: 'esprima', url: 'http://esprima.org/', target_file: 'es6/compilers/esprima.html', compiler: function(code) { try { esprima.parse(code); return "(function(){return true;})"; } catch(e) { return "/*\n" + e.message + "\n*/\n(function(){return false;})"; } }, }, { name: 'espree', url: 'http://espree.org/', target_file: 'es6/compilers/espree.html', compiler: function(code) { try { espree.parse(code,{ ecmaFeatures: { arrowFunctions: true, blockBindings: true, destructuring: true, regexYFlag: true, regexUFlag: true, templateStrings: true, binaryLiterals: true, octalLiterals: true, unicodeCodePointEscapes: true, defaultParams: true, restParams: true, forOf: true, objectLiteralComputedProperties: true, objectLiteralShorthandMethods: true, objectLiteralShorthandProperties: true, objectLiteralDuplicateProperties: true, generators: true, spread: true, classes: true, modules: true, globalReturn: true }}); return "(function(){return true;})"; } catch(e) { return "/*\n" + e.message + "\n*/\n(function(){return false;})"; } }, }, { name: 'jshint', url: 'http://jshint.com/', target_file: 'es6/compilers/jshint.html', compiler: function(code) { var result = jshint.JSHINT(code,{ asi:true, boss:true, elision:true, eqnull:true, esnext:true, evil:true, expr:true, laxbreak:true, laxcomma:true, loopfunc:true, multistr: true, noyield:true, plusplus:true, proto:true, sub:true, supernew: true, validthis:true, withstmt:true, nonstandard:true, typed:true, "-W032":true, }); if (result) { return "(function(){return true;})"; } else { return "/*\n" + jshint.JSHINT.errors.map(function(e){ return (e && e.reason) || ""; }).join('\n') + "\n*/\n(function(){return false;})"; } }, }, { name: 'JSX', url: 'https://github.com/facebook/react', target_file: 'es6/compilers/jsx.html', polyfills: [], compiler: function(code) { var ret = jstransform.transform(code, { harmony:true }); return ret.code || ret; }, }, { name: 'TypeScript', url: 'https://www.typescriptlang.org/', target_file: 'es6/compilers/typescript.html', polyfills: [], compiler: ts.transpile }, { name: 'TypeScript + core-js', url: 'https://www.typescriptlang.org/', target_file: 'es6/compilers/typescript-core-js.html', polyfills: ["node_modules/core-js/client/core.js"], compiler: ts.transpile }, { name: 'Closure Compiler', url: 'https://developers.google.com/closure/compiler/', target_file: 'es6/compilers/closure.html', polyfills: [], compiler: function(code) { var fpath = os.tmpDir() + path.sep + 'temp.js'; var file = fs.writeFileSync(fpath, code); try { output = ""+child_process.execSync('node_modules/closurecompiler/bin/ccjs ' + fpath + ' --language_in=ECMASCRIPT6 --language_out=ECMASCRIPT5' ); } catch(e) { throw new Error('\n' + e.stdout.toString().split(fpath).join('')); } return output; }, }, ].forEach(function(e){ Object.assign(es6, e); es6.browsers = {}; es6.skeleton_file = 'es6/compiler-skeleton.html'; handle(es6); }); [ { name: 'babel + core-js', url: 'https://babeljs.io/', target_file: 'esnext/compilers/babel-core-js.html', polyfills: ['node_modules/babel-polyfill/browser.js'], compiler: function(code) { return babel.transform(code, {presets: ['es2015', 'babel-preset-stage-0']}).code; }, }, { name: 'es7-shim', url: 'https://github.com/es-shims/es7-shim/', target_file: 'esnext/compilers/es7-shim.html', polyfills: ['node_modules/es7-shim/dist/es7-shim.js'], compiler: String, }, { name: 'JSX', url: 'https://github.com/facebook/react', target_file: 'esnext/compilers/jsx.html', polyfills: [], compiler: function(code) { var ret = jstransform.transform(code, { harmony:true }); return ret.code || ret; }, }, { name: 'TypeScript + core-js', url: 'https://www.typescriptlang.org/', target_file: 'esnext/compilers/typescript-core-js.html', polyfills: ["node_modules/core-js/client/core.js"], compiler: ts.transpile }, ].forEach(function(e){ Object.assign(esnext, e); esnext.browsers = {}; esnext.skeleton_file = 'esnext/compiler-skeleton.html'; handle(esnext); }); }); function handle(options, compiler) { var skeleton = fs.readFileSync(__dirname + path.sep + options.skeleton_file, 'utf-8'); var html = dataToHtml(skeleton, options.browsers, options.tests, options.compiler); var result = replaceAndIndent(html, [ ["<!-- NAME -->", [options.name]], ["<!-- URL -->", [options.name.link(options.url)]], ["<!-- POLYFILLS -->", !options.polyfills ? [] : options.polyfills.map(function(e) { return '<script>' + fs.readFileSync(__dirname + path.sep + e, 'utf-8').replace(/<(?=\/script>)/g,'\\u003c') + '</script>\n'; })], ]).replace(/\t/g, ' '); var target_file = __dirname + path.sep + options.target_file; var old_result; try { old_result = fs.readFileSync(target_file, 'utf-8'); } catch (e) {} if (old_result === result) { console.log('[' + options.name + '] ' + options.target_file + ' not changed'); } else { fs.writeFileSync(target_file, result, 'utf-8'); console.log('[' + options.name + '] Write to file ' + options.target_file); } } function dataToHtml(skeleton, rawBrowsers, tests, compiler) { var $ = cheerio.load(skeleton); var head = $('table thead tr:last-child'); var body = $('table tbody'); var footnoteIndex = {}; var rowNum = 0; // rawBrowsers includes very obsolete browsers which mustn't be printed, but should // be used by interpolateResults(). All other uses should use this, which filters // the very obsolete ones out. var browsers = Object.keys(rawBrowsers).reduce(function(obj,e) { if (rawBrowsers[e].obsolete !== "very") { obj[e] = rawBrowsers[e]; } return obj; },{}); function interpolateResults(res) { var browser, prevBrowser, result, prevResult, bid, prevBid, j; // For each browser, check if the previous browser has the same // browser full name (e.g. Firefox) or family name (e.g. Chakra) as this one. for (var bid in rawBrowsers) { browser = rawBrowsers[bid]; if (prevBrowser && (prevBrowser.full.replace(/,.+$/,'') === browser.full.replace(/,.+$/,'') || (browser.family !== undefined && prevBrowser.family === browser.family))) { // For each test, check if the previous browser has a result // that this browser lacks. result = res[bid]; prevResult = res[prevBid]; if (prevResult !== undefined && result === undefined) { res[bid] = prevResult; } } prevBrowser = browser; prevBid = bid; } // For browsers that are essentially equal to other browsers, // copy over the results. for (var bid in rawBrowsers) { browser = rawBrowsers[bid]; if (browser.equals) { result = res[browser.equals]; res[bid] = browser.ignore_flagged && result === 'flagged' ? false : result; } } } function getHtmlId(id) { return 'test-' + id; } function footnoteHTML(obj) { if (obj && obj.note_id) { if (!footnoteIndex[obj.note_id]) { if (obj.note_html) { footnoteIndex[obj.note_id] = obj.note_html; } } var num = Object.keys(footnoteIndex).indexOf(obj.note_id) + 1; return '<a href="#' + obj.note_id + '-note"><sup>[' + num + ']</sup></a>'; } return ''; } function allFootnotes() { var ret = $('<p>'); Object.keys(footnoteIndex).forEach(function(e,id) { if (!(e in footnoteIndex)) { console.error("There's no footnote with id '" + e + "'"); } ret.append('<p id="' + e + '-note">' + '\t<sup>[' + (id + 1) + ']</sup> ' + footnoteIndex[e] + '</p>'); }); return ret; } function testValue(result) { if (result && typeof result === "object" && "val" in result) { return result.val; } return result; } function escapeTestName(name) { return name.replace(/^[\s<>&"',]+|[\s<>&"',]+$/g, '').replace(/[\s<>&"]+/g, '_'); } // Write the browser headers Object.keys(browsers).forEach(function(browserId) { var b = browsers[browserId]; if (!b) { throw new Error('No browser with ID ' + browserId); } head.append($('<th></th>') .addClass("platform " + browserId + ' ' + (b.platformtype || 'desktop')) .addClass(b.obsolete ? "obsolete" : b.unstable ? "unstable" : "") .attr("data-browser", browserId) .append( $('<a href="#' + browserId + '" class="browser-name"></a>') .append('<abbr title="' + b.full + '">' + b.short + '</abbr>')) .append(footnoteHTML(b) ) ); }); // Now print the results. tests.forEach(function(t, testNum) { var subtests; // Calculate the result totals for tests which consist solely of subtests. if ("subtests" in t) { t.subtests.forEach(function(e) { interpolateResults(e.res); }); } else interpolateResults(t.res); var id = escapeTestName(t.name); var name = t.link ? ('<a href="' + t.link + '">' + t.name + '</a>') : t.name; var testRow = $('<tr></tr>') .addClass("subtests" in t ? 'supertest' : '') .attr("significance", t.significance === "tiny" ? 0.125 : t.significance === "small" ? 0.25 : t.significance === "medium" ? 0.5 : 1) .addClass(isOptional(t.category) ? 'optional-feature' : '') .append($('<td></td>') .attr('id', getHtmlId(id)) .append('<span><a class="anchor" href="#' + getHtmlId(id) + '">&sect;</a>' + name + footnoteHTML(t) + '</span></td>') .append(testScript(t.exec, compiler, rowNum++)) ); body.append(testRow); // If this row has a different category to the last, add a title <tr> before it. if (t.category && (!testNum || t.category !== tests[testNum-1].category)) { testRow.before('<tr class="category"><td colspan="' + (Object.keys(browsers).length+2) + '">' + capitalise(t.category) + '</td></tr>'); } // Function to print out a single <td> result cell. function resultCell(browserId, result, footnote) { if (!browsers[browserId]) { return; } result = testValue(result); // Create the cell, and add classes and attributes var cell = $('<td></td>'); cell.addClass({ 'true': "yes", 'false': "no", 'undefined': "no", 'tally': 'tally', 'flagged': 'no flagged', 'needs-polyfill-or-native': 'no needs-polyfill-or-native', 'strict': 'no strict', 'null': 'unknown', }[result] || ''); if (result === "needs-polyfill-or-native") { cell.attr('title', "Requires native support or a polyfill."); } else if (result === "strict") { cell.attr('title', "Support for this feature incorrectly requires strict mode."); } cell.attr('data-browser', browserId).addClass( browsers[browserId].obsolete ? "obsolete" : browsers[browserId].unstable ? "unstable" : ""); // Add extra signifiers if the result is not applicable. if (isOptional(t.category) && // Annex B is only optional for non-browsers. (t.category.indexOf("annex b")===-1 || (browsers[browserId].platformtype && "desktop|mobile".indexOf(browsers[browserId].platformtype) === -1 && !browsers[browserId].needs_annex_b))) { var msg = ({ 'pre-strawman': "This proposal has not yet been accepted by ECMA Technical Committee 39", 'strawman (stage 0)': "This proposal has not yet reached ECMA TC39 stage 1", }[t.category] || "This feature is optional on non-browser platforms") + ", and doesn't contribute to the platform's support percentage."; cell.attr('title', msg); cell.addClass("not-applicable"); } if (result !== 'tally') { cell.text({ strict: 'Strict', flagged: 'Flag', 'true': 'Yes', 'null': '?', }[result] || 'No'); } if (footnote) { cell.append(footnote); } return cell; } // Print all the results for the subtests if ("subtests" in t) { t.subtests.forEach(function(subtest, subtestNum) { var subtestName = subtest.name; var subtestId = id + '_' + escapeTestName(subtestName); subtestRow = $('<tr class="subtest"></tr>') .attr('data-parent', id) .attr('id', getHtmlId(subtestId)) .append( $('<td></td>') .append('<span><a class="anchor" href="#' + getHtmlId(subtestId) + '">&sect;</a>' + subtestName + '</span>') .append(testScript(subtest.exec, compiler, rowNum++)) ); body.append(subtestRow); // Add all the result cells Object.keys(browsers).forEach(function(browserId) { var result = subtest.res[browserId]; subtestRow.append(resultCell( browserId, result, footnoteHTML(result) )); }); }); } // Print all the results for the main test Object.keys(browsers).forEach(function(browserId) { // For supertests, calculate the tally and total if ("subtests" in t) { var tally = 0, outOf = 0, flaggedTally = 0; t.subtests.forEach(function(e) { var result = e.res[browserId]; tally += testValue(result) === true; flaggedTally += ['flagged','strict'].indexOf(testValue(result)) > -1; outOf += 1; }); var grade = (tally / outOf); var cell = resultCell(browserId, 'tally') .text((tally|0) + "/" + outOf) .attr('data-tally', grade); if (grade > 0 && grade < 1 && !cell.hasClass('not-applicable')) { cell.attr('style','background-color:hsl(' + (120*grade|0) + ',' +((86 - (grade*44))|0) +'%,50%)'); } if (flaggedTally) { cell.attr('data-flagged-tally', (tally + flaggedTally) / outOf); } testRow.append(cell); } // For single tests: else { var result = t.res[browserId]; testRow.append(resultCell( browserId, result, footnoteHTML(result) )); } }); // Finish the <tr> if (t.separator === 'after') { body.append( '<tr><th colspan="' + (Object.keys(browsers).length + 3) + '" class="separator"></th></tr>' ); } }); $('#footnotes').append(allFootnotes()); return $.root().html().replace(/(<\/t\w>)/g, "$1\n"); } function capitalise(s) { return s[0].toUpperCase() + s.slice(1); } function replaceAndIndent(str, replacements) { var i, replacement, indent; for (i = 0; i < replacements.length; i++) { replacement = replacements[i]; indent = new RegExp('(\n[ \t]*)' + replacement[0]).exec(str); if (!indent) { indent = [,'']; } str = str .split(replacement[0]) .join(replacement[1].join(indent[1])); } return str; } function testScript(fn, transformFn, rowNum) { function deindentFunc(fn) { fn = (fn+''); var indent = /(?:^|\n)([\t ]+)[^\n]+/.exec(fn); if (indent) { fn = fn.replace(new RegExp('\n' + indent[1], 'g'), '\n'); } return fn; } if (!fn) { return ''; } if (typeof fn === 'function') { // see if the code is encoded in a comment var expr = (fn+"").match(/[^]*\/\*([^]*)\*\/\}$/); var transformed = false; // if there wasn't an expression, make the function statement into one if (!expr) { if (transformFn) { try { expr = transformFn("("+fn+")"); transformed = true; } catch(e) { expr = "false"; } } else { expr = deindentFunc(fn); } return cheerio.load('')('<script>test(\n' + expr + '())</script>').attr('data-source', expr); } else { expr = deindentFunc(expr[1]); if (transformFn) { try { if (expr.search(/Function\s*\(|eval\s*\(/) > -1) { throw new Error("This test's code invokes eval() and cannot be compiled."); } expr = transformFn("(function(){" + expr + "})") transformed = true; } catch(e) { expr = "/* Error during compilation: " + e.message + "*/"; } } var async = !!/asyncTestPassed/.exec(fn); var codeString = JSON.stringify(expr).replace(/\\r/g,''); var asyncFn = 'global.__asyncPassedFn && __asyncPassedFn("' + rowNum + '")'; var strictAsyncFn = 'global.__strictAsyncPassedFn && __strictAsyncPassedFn("' + rowNum + '")'; var funcString = transformed ? '' + asyncFn + ' && eval(' + codeString + ')()' : 'Function("asyncTestPassed",' + codeString + ')(asyncTestPassed)'; var strictFuncString = transformed ? '' + strictAsyncFn + ' && function(){"use strict";' + codeString + '}() && "Strict"' : 'Function("asyncTestPassed","\'use strict\';"+' + codeString + ')(asyncTestPassed)'; return cheerio.load('')('<script>' + 'test(function(){' + 'try{' + 'var asyncTestPassed=' + asyncFn + ';' + 'try{' + 'return ' + funcString + '}' + 'catch(e){' + 'asyncTestPassed=' + strictAsyncFn + ';' + 'return ' + strictFuncString + '&&"Strict"' + '}' + '}' + 'catch(e){' + 'return false;' + '}' +'}());' +'\n</script>').attr('data-source', expr); } } else { // it's an array of objects like the following: // { type: 'application/javascript;version=1.8', script: function () { ... } } return fn.reduce(function(text, script) { var expr = deindentFunc( (script.script+'').replace(/^function \(\) \{\s*|\s*\}$/g, '') ); var $ = cheerio.load ('<script' + (script.type ? ' type="' + script.type + '"' : '') + '>' + expr + '</script>' ); $('script').attr('data-source', expr); return text + $.html(); },''); } }
const fs = require('fs') const slack = require('slack') const bot = slack.rtm.client() const env = require('node-env-file') const channels = require('./channels') const admins = require('./admins') env(__dirname + '/.env') const token = process.env.SLACK_TOKEN let lastTimeStamp let myId bot.started(function(payload) { lastTimeStamp = parseFloat(payload.latest_event_ts) myId = payload.self.id }) const commands = [] // auto rejoin bot.channel_left(function(msg) { const toJoin = channels.whitelist.find((chan) => { return chan.id === msg.channel && chan.always }) if (toJoin !== undefined) { slack.channels.join( {token: token, name: toJoin.name}, (err, data) => { if (data) { console.log(`auto rejoined #${toJoin.name}`) } if (err) { console.log(err) } } ) } }) // auto leave bot.channel_joined(function(msg) { if (channels.whitelist.find((chan) => { return chan.id === msg.channel.id }) === undefined) { slack.channels.leave( {token: token, channel: msg.channel.id}, (err, data) => { if (data) { console.log(`auto left #${msg.channel.name}`) } if (err) { console.log(err) } } ) } }) // list admins function cmd_admins(arg) { if (arg.from.isAdmin !== true) { return } if (arg.message === '') { const text = '<@' + arg.from.name + '>: ' + admins.map((admin) => {return '<@' + admin.name + '>'}).join('\n') slack.chat.postMessage( {token: token, as_user: true, channel: arg.in, text: text}, (err, data) => { if (data) { console.log(`cmd_admins from ${arg.from.name} to ${arg.in}`) } if (err) { console.log(err) } } ) } else { const option = arg.message.match(/^(add|remove) ([^ ]+) *$/) if (option !== null) { if (option[1] === 'add' && arg.from.isOverlord === true) { const action = (user) => { const newAdmins = admins.filter((u) => { return u.id !== user.id || u.overlord === true }) newAdmins.push({id: user.id, overloard: false, name: user.name}) const adminsStr = 'const admins = ' + JSON.stringify(newAdmins, undefined, 2) + '\n\nmodule.exports = admins' fs.writeFileSync('./admins.js', adminsStr, 'utf8') } // Duplicate code start if (option[2].search(/^<@U[A-Z0-9]{8}>$/) !== -1) { slack.users.info( {token: token, user: option[2].substr(2,9)}, (err, resp) => { if (resp && resp.user) { action(resp.user) } if (err) { console.log(err) } }) } else { slack.users.list( {token: token}, (err, resp) => { if (resp && resp.members) { const user = resp.members.find((member) => { return member.name === option[2] }) action(user) } if (err) { console.log(err) } }) } // Duplicate code end } else if (option[1] === 'remove' && arg.from.isOverlord === true) { const action = (user) => { const newAdmins = admins.filter((u) => { return u.id !== user.id || u.overlord === true }) const adminsStr = 'const admins = ' + JSON.stringify(newAdmins, undefined, 2) + '\n\nmodule.exports = admins' fs.writeFileSync('./admins.js', adminsStr, 'utf8'); } // Duplicate code start if (option[2].search(/^<@U[A-Z0-9]{8}>$/) !== -1) { slack.users.info( {token: token, user: option[2].substr(2,9)}, (err, resp) => { if (resp && resp.user) { action(resp.user) } if (err) { console.log(err) } }) } else { slack.users.list( {token: token}, (err, resp) => { if (resp && resp.members) { const user = resp.members.find((member) => { return member.name === option[2] }) action(user) } if (err) { console.log(err) } }) } // Duplicate code end } } } } commands.push({ func: cmd_admins, names: ['!admins', '!admin'], description: 'Lists admins.\n' + 'Options: `add`/`remove` + nick to add or remove an admin.' }) // list commands and print help messages function cmd_help(arg) { if (arg.from.isAdmin !== true) { return } let text = '<@' + arg.from.name + '>:\n' if (arg.message === '') { text += 'usage: `!help [!command]`\n' text += commands.map((command) => { return command.names.join(', ') }).join('\n') } else { const cmd = commands.find((command) => { return command.names.includes(arg.message) }) if (cmd !== undefined) { text += cmd.names.join(', ') + '\n' + cmd.description } else { text += 'Command not recognized.' } } slack.chat.postMessage( {token: token, as_user: true, channel: arg.in, text: text}, (err, data) => { if (data) { console.log(`cmd_help from ${arg.from.name} to ${arg.in}`) } if (err) { console.log(err) } } ) } commands.push({ func: cmd_help, names: ['!help', '!command', '!commands'], description: 'Lists commands. Add a command name for more specific help.' }) // tell time and date function cmd_time(arg) { if (arg.from.isAdmin !== true) { return } const now = new Date() const text = `<@${arg.from.name}>: ${now.toDateString()} ${now.toTimeString()}` slack.chat.postMessage( {token: token, as_user: true, channel: arg.in, text: text}, (err, data) => { if (data) { console.log(`cmd_time from ${arg.from.name} to ${arg.in}`) } if (err) { console.log(err) } } ) } commands.push({ func: cmd_time, names: ['!time', '!date'], description: 'Prints the current date and time.' }) // repeat with @channel function cmd_announce(arg) { if (arg.from.isAdmin !== true || arg.message == '') { return } const to = { '!annonces': '#annonces', '!asso': '#association-sans-nom', '!libre': '#asn-libre', '!lockpicking': '#asn-lockpicking', '!secu': '#asn-secu', '!event': '#42staff_events' }[arg.name] const text = `<!channel>: ${arg.message}\n(<@${arg.from.name}>)` slack.chat.postMessage( {token: token, as_user: true, channel: to, text: text}, (err, data) => { if (data) { console.log(`cmd_announce to ${to} | ${text}`) slack.pins.add( {token: token, channel: data.channel, timestamp: data.ts}, (err, resp) => { if (resp) { console.log(' (pinned it)\n') } } ) } if (err) { console.log(err) } } ) } commands.push({ func: cmd_announce, names: ['!annonces', '!asso', '!libre', '!lockpicking', '!secu', '!event'], description: 'Announcement on the specified channel ' + '(#annonces, #association-sans-nom, #asn-libre, #asn-lockpicking, #asn-secu or ' + '#42staff_events) with your nick at the end of the message.' }) // commands function onMessage(msg) { slack.users.info({token: token, user: msg.user}, (err, rawFrom) => { if (err) { console.log(err) } if (rawFrom && rawFrom.user) { if (rawFrom.user.id === myId) { return } // just in case const from = {id: rawFrom.user.id, name: rawFrom.user.name} const adm = admins.find((admin) => {return admin.id === rawFrom.user.id}) from.isAdmin = (adm !== undefined) ? true : false from.isOverlord = (adm !== undefined) ? adm.overlord : false const matches = msg.text.match(/^(![a-z]+)(\s+|$)/) if (matches !== null) { const command = commands.find((command) => { return command.names.includes(matches[1]) }) if (command !== undefined) { const name = command.names.find((name) => {return name === matches[1]}) if (name !== undefined) { command.func({ name: matches[1], ts: msg.ts, from: from, in: msg.channel, message: msg.text.substr(matches[0].length) }) } } } } }) } function onEdit(msg) { } // message events include many subtypes about topics, join/leave, files, etc. // https://api.slack.com/events/message#message_subtypes bot.message(function(msg) { // Don't process the same message twice if (lastTimeStamp && lastTimeStamp >= parseFloat(msg.ts)) { return } else { lastTimeStamp = parseFloat(msg.ts) } if (msg.subtype === undefined) { onMessage(msg) } if (msg.subtype === 'message_changed') { onEdit(msg) } }) // callback on slack `listen` event const listenCb = () => { bot.ws.on('close', (code, reason) => { console.log('' + new Date() + ' - WebSocket closed, reopening') bot.listen({token:token}, listenCb) }) } // start listening to the slack team associated to the token bot.listen({token:token}, listenCb)
'use strict' const app = require('./app') const PORT = 8000 app.listen(PORT) console.log(`Listening on port ${PORT}...`)
var args = arguments[0] || {}; var duration = (OS_IOS) ? 200 : 1000; // add child views to controller if they exist if (args.children) { _.each(args.children, function(child) { // fix: https://jira.appcelerator.org/browse/TC-3583 if (!child) { return; } $.contents.add(child); }); } var disableBackshadeClose = false; $.init = function (args) { if(!args) args = {}; if(args.disableBackshadeClose) disableBackshadeClose = true; $.title.text = (args.title) ? args.title : ''; if(args.showLeftNavButton) { $.leftnavbutton.text = (args.leftNavButtonTitle) ? args.leftNavButtonTitle : ''; $.leftnavbutton.visible = true; $.leftnavbutton.addEventListener('click', function(e){ e.bubbles = false; e.cancelBubble = true; if (args && args.view && args.view.children) { var kids = args.view.children; if(kids && kids.length) { for(var i=0, j=kids.length; i<j; i++) { try { kids[i].blur(); } catch(err) {} } } } if(typeof args.leftNavCallback == 'function') { args.leftNavCallback(); } $.hideMe(); }); } if(args.showRightNavButton) { $.rightnavbutton.text = (args.rightNavButtonTitle) ? args.rightNavButtonTitle : ''; $.rightnavbutton.visible = true; $.rightnavbutton.addEventListener('click', function(e){ e.bubbles = false; e.cancelBubble = true; if (args && args.view && args.view.children) { var kids = args.view.children; if(kids && kids.length) { for(var i=0, j=kids.length; i<j; i++) { try { kids[i].blur(); } catch(err) {} } } } args.rightNavCallback(); $.hideMe(); }); } if(args.view) { $.contents.add(args.view); } if(args.duration) { duration = args.duration; } if(args.openCallback && typeof args.openCallback==='function') { //add a callback function when this opens $.popover.addEventListener('open', function(e){ e.bubbles = false; e.cancelBubble = true; args.openCallback(); }); } if(args.closeCallback && typeof args.closeCallback==='function') { //add a callback function when this closes $.popover.addEventListener('close', function(e){ e.bubbles = false; e.cancelBubble = true; args.closeCallback(); }); } }; if(OS_IOS) { var shadowOffset = Ti.UI.createAnimation({ transform: Ti.UI.create2DMatrix().translate(3,3), duration: 1 }); $.shadow.animate(shadowOffset); } if(OS_IOS) { var showAnim = Titanium.UI.createAnimation({ opacity: 1, duration: duration }), hideAnim = Titanium.UI.createAnimation({ // closes quicker than opens opacity: 0, duration: duration/2 }); } $.popover.addEventListener('click', function(e) { if(e.source.id == 'backshade' && !disableBackshadeClose) { if(OS_IOS) $.popover.animate(hideAnim); setTimeout(function() { $.popover.close(); }, duration); } }); $.hideMe = function() { if(OS_IOS) $.popover.animate(hideAnim); setTimeout(function() { $.popover.close(); }, duration); }; $.showMe = function(theArgs) { var args = theArgs || {}; if(args.view) { try { $.contents.removeAllChildren(); } catch(err) { alert(JSON.stringify(err)); } $.contents.add(args.view); } $.popover.opacity = 0; $.popover.open(); if(OS_IOS) { $.popover.animate(showAnim); } else { $.popover.opacity = 1; } };
//optionally connect to the redux store import { createStore, combineReducers, applyMiddleware, compose } from "redux"; import { vectorEditorReducer as VectorEditor, vectorEditorMiddleware } from "../../src"; import thunk from "redux-thunk"; import { reducer as form } from "redux-form"; const composeEnhancer = (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ actionsDenylist: ["HOVEREDANNOTATIONUPDATE", "HOVEREDANNOTATIONCLEAR"], // actionSanitizer, latency: 1000, name: "openVE" })) || compose; const store = createStore( combineReducers({ form, VectorEditor: VectorEditor() }), undefined, composeEnhancer( applyMiddleware(thunk, vectorEditorMiddleware) //your store should be redux-thunk connected for the VectorEditor component to work ) ); export default store;
const { EventEmitter } = require('events'); const Dispatcher = require('../dispatcher'); const Constants = require('../constants'); const notifier = require('../ui/notifier'); const CHANGE_EVENT = 'change'; let _notifications = {}; function _tradeOfferNotification(newCount) { if(newCount > _notifications.tradeOffers) { notifier.tradeOffer(); } } function updateAll(notifications) { _tradeOfferNotification(notifications.tradeOffers); _notifications = notifications; } function updateTradeOfferCount(count) { _tradeOfferNotification(count); _notifications.tradeOffers = count; } function clear() { _notifications = {}; } class NotificationStore extends EventEmitter { emitChange() { this.emit(CHANGE_EVENT); } addChangeListener(callback) { this.on(CHANGE_EVENT, callback); } removeChangeListener(callback) { this.removeListener(CHANGE_EVENT, callback); } get() { return _notifications; } }; const notificationStore = new NotificationStore(); NotificationStore.dispatchToken = Dispatcher.register((action) => { switch(action.type) { case Constants.NotificationActions.NOTIFICATION_UPDATE_TRADEOFFER_COUNT: updateTradeOfferCount(action.count); notificationStore.emitChange(); break; case Constants.NotificationActions.NOTIFICATION_UPDATE_ALL: updateAll(action.notifications); notificationStore.emitChange(); break; case Constants.UIActions.UI_LOGOUT: clear(); notificationStore.emitChange(); break; default: // ignore } }); module.exports = notificationStore;
import Vue from 'vue' import App from './App.vue' import router from './router/index' Vue.config.productionTip = false export default new Vue({ el: '#app', router, template: '<App/>', components: { App } })
const crypto = require('crypto'); const algorithm = 'aes-256-ctr'; exports.encrypt = function (buffer, password){ var cipher = crypto.createCipher(algorithm,password) return Buffer.concat([cipher.update(buffer),cipher.final()]); }; exports.decrypt = function(buffer, password){ var decipher = crypto.createDecipher(algorithm,password) return Buffer.concat([decipher.update(buffer) , decipher.final()]); };
import { assignDefaults, isolate } from '../../../utils' import * as defaults from '../defaults' import { Entity } from '../../../core' import { CubeTexturePointerContext } from './pointer' import { CubeTextureDataContext } from './data' import { CubeTextureInfoContext } from './info' export function CubeTextureContext(ctx, initialState = {}) { assignDefaults(initialState, defaults) const {uniformName} = initialState return Entity(ctx, initialState, isolate(CubeTextureDataContext(ctx, initialState)), CubeTexturePointerContext(ctx, initialState), CubeTextureInfoContext(ctx, initialState), ) }
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), MunicipalCourtWebsite = mongoose.model('MunicipalCourtWebsite'); /** * Globals */ var user, municipalCourtWebsite; /** * Unit tests */ describe('Municipal court websites Model Unit Tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: 'username', password: 'password' }); user.save(function() { municipalCourtWebsite = new MunicipalCourtWebsite({ // Add model fields // ... }); done(); }); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { return municipalCourtWebsite.save(function(err) { should.not.exist(err); done(); }); }); }); afterEach(function(done) { MunicipalCourtWebsite.remove().exec(); User.remove().exec(); done(); }); });
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var middle = __webpack_require__(1); var chatApp = __webpack_require__(2); var chat = __webpack_require__(3); var userAvatarComponent = __webpack_require__(7); middle.userAvatarComponent = userAvatarComponent; $(function() { $("#init").modal('show'); $("[name='my-checkbox']").bootstrapSwitch({ size: 'small', onColor: 'success', onText: '开启', offText: '关闭', onSwitchChange: function(event, state) { console.log(state); chat.settingMsgSoundPrompt(); } }); }); /***/ }, /* 1 */ /***/ function(module, exports) { // 持有 后端 和前台渲染的公共变量 // 解决互相依赖导致某些前端渲染被超前执行 var middle = {}; middle.my_connect = null; module.exports = middle; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var middle = __webpack_require__(1); var chat = __webpack_require__(3); var chatApp = angular.module('chatApp', []); chatApp.controller('sign', function($scope, $http) { $scope.signUser = function() { if (undefined === $scope.username || $scope.username.trim() === '') { alert('请输入用户名'); } else { $("#init").modal('hide'); chat.signinuser.username = $scope.username; chat.signIn($scope.username); } }; }); module.exports = chatApp; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var config = __webpack_require__(4); var Connect = __webpack_require__(5); var middle = __webpack_require__(1); // 没有<> 就变成选取元素了 var templateDiv = $("<div>"); // 自己的聊天消息 var chatMsgRight; // 他人的聊天消息 var chatMsgLeft; // 聊天窗口 var chatWindow; var msg_input; var msg_end; // 聊天框显示出最新的 function msgScrollEnd() { msg_end[0].scrollIntoView(); } /** * 自己的消息 * 一条消息需要名字,时间,头像,内容 * @return {[type]} [description] */ function insertChatMsgRight(content) { var date = new Date(); var clone = chatMsgRight.clone(); clone.find(".direct-chat-timestamp").html((new Date()).toLocaleTimeString()); clone.find(".direct-chat-text").html(content); msg_end.before(clone); } /** * 对方的消息 * @return {[type]} [description] */ function insertChatMsgLeft(message) { var date = new Date(); var clone = chatMsgLeft.clone(); clone.find(".direct-chat-timestamp").html((new Date()).toLocaleTimeString()); clone.find(".direct-chat-text").html(message.content); clone.find('img').attr('src', message.avatar); msg_end.before(clone); } function Chat() { this.connect = null; this.users = []; this.currentChat = { theUser: null, username: null, chatname: null }; this.signinuser = { username: null }; // key username value chat window dom this.chatWindowDom = new Map(); } /** * 清除掉未读信息 * @param {[type]} user [description] * @return {[type]} [description] */ Chat.prototype.clearUnread = function(user) { user.unreadMsgCount = 0; middle.userAvatarComponent.userListScope.$apply(); }; Chat.prototype.toggleChatView = function(user) { var chat = this; console.log(chat.chatWindow); console.log(this); console.log(chat); var userDom = chat.chatWindowDom.get(user.username); if (userDom === undefined || userDom === null) { userDom = chat.chatWindow.clone(); chat.chatWindowDom.set(user.username, userDom); userDom.find('#chatWindow-username').html(user.username); userDom.find('#msg-input').on('keydown', function(event) { if (event.keyCode === 13) { // 回车 chat.say(); } }); userDom.find('#say').click(function() { chat.say(); }); } else { console.log('userdom is not null'); } msg_input = userDom.find("#msg-input"); msg_end = userDom.find("#msg_end"); console.log(msg_input); console.log(msg_end); $('#chatWindowDiv').replaceWith(userDom); }; /** * 接收到消息,但不一定会显示出来,只有当前的窗口就是该消息来源时才会显示 * @param {[type]} message [description] * @return {[type]} [description] */ Chat.prototype.receiveMessage = function(message) { playMsgComingPromptTone(); var sendUserName = message.sendUser; if (sendUserName === this.currentChat.username) { // 正式当前聊天的 message.avatar = this.currentChat.theUser.avatar; this.listen(message); } else { // 当前窗口并不是该用户 var user = this.usersMap.get(sendUserName); // 未读消息加1 if (user.unreadMsgCount === undefined) { user.unreadMsgCount = 0; } user.unreadMsgCount += 1; middle.userAvatarComponent.userListScope.$apply(); } }; /** * 该方法在会显示出 对方的消息 * @param {[type]} message [description] * @return {[type]} [description] */ Chat.prototype.listen = function(message) { insertChatMsgLeft(message); msgScrollEnd(); }; Chat.prototype.say = function() { var msg = msg_input.val(); if (msg !== '') { msg_input.val(null); insertChatMsgRight(msg); msgScrollEnd(); var letter = { directive: { send: { message: null } }, message: { sendUser: chat.signinuser.username, content: msg } }; if (chat.currentChat.username !== null) { // 单聊 letter.message.receiveUser = chat.currentChat.username; letter.message.type = 'one'; } else { // 群聊 letter.message.receiveUser = chat.currentChat.chatname; letter.message.type = 'some'; } // 发送到服务器 this.connect.sendToUser(letter); } }; Chat.prototype.refreshUserList = function() { middle.userAvatarComponent.userListScope.$apply(); }; Chat.prototype.signIn = function(username) { this.connect.sign_in(username); }; // key username ,value 客户端 user Chat.prototype.usersMap = new Map(); // 引用设置项 Chat.prototype.setting = { msgSoundPrompt: true }; /** * 设置是否开启消息声音提示,如果不传参数会在两种状态间切换 * @param {[type]} value [description] * @return {[type]} [description] */ Chat.prototype.settingMsgSoundPrompt = function(value) { if (value === undefined) { this.setting.msgSoundPrompt = !this.setting.msgSoundPrompt; } else { this.setting.msgSoundPrompt = value; } }; var chat = new Chat(); var connect = new Connect(chat); chat.connect = connect; // 连接server connect.connect(config.communication_server_host); // TODO 防止缓存的问题 templateDiv.load('/public/app/template/template.html', function() { chatMsgRight = templateDiv.find("#msg-right>div"); chatMsgLeft = templateDiv.find("#msg-left>div"); chatWindow = templateDiv.find("#chatWindow>div"); // 加载完在赋值 chat.chatWindow = chatWindow; }); var audio; $(function() { audio = document.getElementById('audio'); }); function playMsgComingPromptTone() { if (chat.setting.msgSoundPrompt) { audio.play(); } } module.exports = chat; /***/ }, /* 4 */ /***/ function(module, exports) { var my_config = { // 通讯服务器地址 communication_server_host: window.location.href }; module.exports = my_config; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var Pubsub = __webpack_require__(6); var pubsub = new Pubsub(); // 初始化事件 pubsub.addEvent("signinBack"); pubsub.addEvent("signoutBack"); pubsub.addEvent("msgfromUser"); pubsub.addEvent('chat'); /** * 聊天消息回调 * @param content */ function chatBack(content) { pubsub.emit('chat', content); } /** * 登录事件回调 * @param content */ function signInBack(content) { console.log("sign in success!"); pubsub.emit("signinBack", content); } /** * 登出事件回调 * @param content */ function signOutBack(content) { pubsub.emit("signoutBack", content); } var public_chat; function Connect(chat) { this.chat = chat; public_chat = chat; this.socket = null; } Connect.prototype.connect = function(host) { var socket = io(host); this.socket = socket; // 以下是socketio 的内部事件 socket.on('connect', function() { console.log("已连接到服务器"); }); socket.on('event', function(data) { }); socket.on('disconnect', function() { }); socket.on('error', function(obj) { console.log(obj); }); socket.on('reconnect', function(number) { console.log(number); }); socket.on('reconnecting', function(number) { console.log(number); }); socket.on('reconnet_error', function(obj) { console.log(obj); }); /** * letter 是自定义的消息事件 */ socket.on('letter', function(letter) { console.log(letter); // letter = JSON.parse(letter); var key = Object.keys(letter.directive)[0]; if (directive[key] === undefined) { console.log('directive ' + key + ' 未实现'); } else { directive[key](letter); } }); }; Connect.prototype.deliver = function(letter) { this.socket.emit("letter", JSON.stringify(letter)); console.log("deliver a letter: "); console.log(JSON.stringify(letter)); }; Connect.prototype.sendToUser = function(letter) { this.deliver(letter); }; Connect.prototype.sign_in = function(username) { var letter = { directive: { client: { sign_in: null } }, user: { username: username } }; this.deliver(letter); }; Connect.prototype.user_presence = function(letter) { }; /** * 通知服务器 本人用户名字 * @param {[type]} username [description] * @return {[type]} [description] */ Connect.prototype.setUsername = function(username) { // letter 如果不指定收件人,则 postoffice 处理 // var letter = {}; var letter = { directive: { set: { username: username } } }; this.deliver(letter); }; /** * 指令对象 */ function Directive() { } Directive.prototype.client = function(letter) { var client = {}; // 有其他用户上线时会调用 client.user_presence = function(letter) { var user = letter.user; user.avatar = genereateAvatarImg(); public_chat.users.push(user); public_chat.usersMap.set(user.username, user); public_chat.refreshUserList(); }; // 登陆后加载当前已经登录的用户 client.init_userList = function(letter) { // 这样使用 第二个参数是参数数组, 而其正好就是一个数组 Array.prototype.push.apply(public_chat.users, letter.directive.client.init_userList); public_chat.users.forEach(function(user) { user.avatar = genereateAvatarImg(); public_chat.usersMap.set(user.username, user); }); public_chat.refreshUserList(); }; var key = Object.keys(letter.directive.client); client[key](letter); }; // 随机生成一个用户的头像 function genereateAvatarImg() { return '/public/app/img/avatar/avatar' + (Math.floor(Math.random() * 5) + 1) + '.png'; } Directive.prototype.receive = function(letter) { var receive = {}; receive.message = function(letter) { var message = letter.message; }; public_chat.receiveMessage(letter.message); }; var directive = new Directive(); module.exports = Connect; /***/ }, /* 6 */ /***/ function(module, exports) { function Pubsub() { this.handlers = {}; } Pubsub.prototype = { on: function(eventType, handler) { var self = this; if (!(eventType in self.handlers)) { self.handlers[eventType] = []; } self.handlers[eventType].push(handler); return this; }, // 在emit 方法中 会回调 on 中设置的方法 () emit: function(eventType) { var self = this; if (self.handlers[eventType] !== undefined) { var handlerArgs = arguments.slice(1); for (var i = 0; i < self.handlers[eventType].length; i++) { // 调用方法传递参数 // 参数都来自于发出事件时的参数 self.handlers[eventType][i].apply(self, handlerArgs); } } else { // 没有此事件的监听者 } return this; }, addEvent: function(eventType) { if (!(eventType in this.handlers)) { this.handlers[eventType] = []; } return this; } }; module.exports = Pubsub; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var chat = __webpack_require__(3); var userAvatarComponent = { userListScope: null }; // angular 好像使用不了map angular.module('chatApp').component('userList', { template: `<div class='user-list'> <div class='user-list-item' ng-click='toggleChat(user)' ng-repeat='user in users'> <img class="user-avatar" ng-src='{{user.avatar}}' alt="" /> <span>{{user.username}}</span> <span class="badge">{{user.unreadMsgCount}}</span> </div> </div>`, controller: function UserListController($scope) { // 使用scope 是因为 在外界改变了 users 的值 为了使用 $scope.$apply方法 $scope.users = chat.users; userAvatarComponent.userListScope = $scope; $scope.toggleChat = function(user) { chat.currentChat.username = user.username; chat.currentChat.theUser = user; chat.toggleChatView(user); user.unreadMsgCount = null; }; } }); module.exports = userAvatarComponent; /***/ } /******/ ]); //# sourceMappingURL=app.js.map
/** * MsgHeaders * ========== * * Sends a list of block headers. */ 'use strict' let dependencies = { BlockHeader: require('./block-header'), Br: require('./br'), Bw: require('./bw'), Msg: require('./msg') } let inject = function (deps) { let BlockHeader = deps.BlockHeader let Br = deps.Br let Bw = deps.Bw let Msg = deps.Msg class MsgHeaders extends Msg { initialize () { Msg.prototype.initialize.call(this) this.setCmd('headers') return this } static dataBufFromBlockHeaders (blockHeaders) { let bw = new Bw() bw.writeVarIntNum(blockHeaders.length) for (let i = 0; i < blockHeaders.length; i++) { bw.write(blockHeaders[i].toBuffer()) } return bw.toBuffer() } fromBlockHeaders (blockHeaders) { this.setData(MsgHeaders.dataBufFromBlockHeaders(blockHeaders)) return this } static fromBlockHeaders (blockHeaders) { return new this().fromBlockHeaders(blockHeaders) } asyncFromBlockHeaders (blockHeaders) { return this.asyncSetData(MsgHeaders.dataBufFromBlockHeaders(blockHeaders)) } toBlockHeaders () { let br = new Br(this.dataBuf) let len = br.readVarIntNum() let blockHeaders = [] for (let i = 0; i < len; i++) { let blockHeaderbuf = br.read(80) let blockHeader = new BlockHeader().fromBuffer(blockHeaderbuf) blockHeaders.push(blockHeader) } return blockHeaders } isValid () { return this.getCmd() === 'headers' } } return MsgHeaders } inject = require('injecter')(inject, dependencies) let MsgHeaders = inject() MsgHeaders.Mainnet = inject({ Msg: require('./msg').Mainnet }) MsgHeaders.Testnet = inject({ Msg: require('./msg').Testnet }) module.exports = MsgHeaders
var model = require('./cases'); var assert = require('assert'); for(var key in model.CASES) describe(key, function(){ for(var kik in model.CASES[key]) describe(kik, function(){ it(model.CASES[key][kik].TITLE, function(){ assert.equal(model.CASES[key][kik].EQUALS, model.CASES[key][kik].EXECUTER); }); }); });
import React, { Component } from 'react' import { View, ScrollView, Image } from 'react-native' import { connect } from 'react-redux' import { Text, List, ListItem } from 'react-native-elements' import Icon from 'react-native-vector-icons/MaterialIcons' import colors from '../../colors' import settings_section from '../../sample_settings' import { push_profile, restart_feed } from '../../actions/navigation' const uri = 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg'; class ProfileHome extends Component { componentDidMount() { if(true) { // this.props.hideTabBar() // this.props.dispatch(push({ key: 'Login', type: 'login' })) } // onPress={() => this.props.dispatch(push_profile({ key: 'About' }))} // onPress={() => this.props.dispatch(push_profile({ key: 'About', type: 'modal' }))} } render() { return ( <ScrollView style={styles.container}> <View style={styles.headingContainer}> <Image style={styles.avatar} source={{uri}}/> <View style={styles.userDetails}> <Text style={styles.headingName}>Chris Jackson</Text> <Text style={styles.headingTitle}>Vice Chairman</Text> </View> </View> <View style={styles.bodycontainer}> <List> { settings_section.map((item, index) => ( <ListItem key={index} onPress={() => this.props.dispatch(push_profile({ key: item.route, type: item.route }))} title={item.title} icon={{name: item.icon}} /> )) } </List> <List containerStyle={{marginBottom: 10}}> <ListItem key={1} hideChevron={true} onPress={() => { this.props.changeTab('feed'); this.props.dispatch(restart_feed({ key: 'Login', type: 'login' }))}} title='LOGOUT' titleStyle={styles.logoutText} icon={{name: ''}} /> </List> </View> </ScrollView> ) } } const styles = { container: { flex: 1, backgroundColor: colors.grey5 }, headingContainer: { flex: 2, justifyContent: 'center', alignItems: 'center', padding: 20, backgroundColor: colors.primary2 }, bodycontainer: { flex: 3, paddingTop: 10, }, avatar: { width: 100, height: 100, borderRadius: 50, flex: 1, }, userDetails: { justifyContent: 'center', alignItems: 'center', paddingTop: 20, }, headingName: { color: 'white', fontSize: 22 }, headingTitle: { color: colors.grey1, fontSize: 17 }, logoutText: { color: 'red', textAlign: 'center', } } export default connect()(ProfileHome)
/*jslint nomen: true, vars: true */ /*global interstate,esprima,able,uid,console,jQuery,window */ (function (ist, $) { "use strict"; var cjs = ist.cjs, _ = ist._; ist.programStateCommands = ["undo", "redo", "reset", "export", "upload", "store", "begin_define_path"]; ist.ProgramStateClient = function (options) { able.make_this_listenable(this); this.comm_mechanism = options.comm_mechanism; this.wrapper_clients = {}; this.constraint_clients = {}; this.clients = {}; this.response_listeners = {}; this.pending_responses = {}; this.loaded = false; if (options.ready_func === true) { var old_ready = window.ready; window.ready = _.bind(function () { this.on_loaded(); window.ready = old_ready; }, this); } else { if (window.document.readyState === "complete") { _.defer(_.bind(this.on_loaded, this), this); } else { window.addEventListener("load", _.bind(this.on_loaded, this)); } } this.info_servers = {}; this.comm_mechanism .on("croot", this.on_croot, this) .on("response", this.on_response, this) .on("cobj_links", this.on_cobj_links, this) .on("wrapper_server", this.on_wrapper_server, this) .on("stringified_root", this.post_forward, this) .on("get_ptr_response", this.post_forward, this) .on("inspect", this.post_forward, this) .on("stringified_obj", this.post_forward, this); }; (function (my) { var proto = my.prototype; able.make_proto_listenable(proto); proto.on_loaded = function () { if(!this.loaded) { this.loaded = true; this.add_message_listener(); this.post({ type: "ready" }); } }; proto.add_message_listener = function () { this.comm_mechanism.on("message", this.on_message, this); }; proto.remove_message_listener = function () { this.comm_mechanism.off("message", this.on_message, this); }; proto.disconnect = function() { this.destroy_every_client(); this.post({type: "disconnect"}); }; proto.destroy_every_client = function() { _.each(this.clients, function(client, client_id) { client.destroy(); delete this.clients[client_id]; }, this); }; proto.post_forward = function(event) { this._emit(event.type, event); }; var DEREGISTERED = {}; proto.on_croot = function(message) { if(this.root_client) { this._emit("root_changed", message); } var summary = message.summary, info_server_info = message.info_servers; if(summary) { this.root_client = this.get_wrapper_client(summary); _.each(message.info_servers, function(id, name) { this.info_servers[name] = new ist.RemoteConstraintClient(id); this.info_servers[name].set_communication_mechanism(this.comm_mechanism); }, this); } this._emit("loaded", this.root_client, this.info_servers); this.post({type: "loaded"}); this.clist = $("<div />").appendTo(this.element).component_list({ info_servers: this.info_servers }); }; proto.on_wrapper_server = function(message) { if(this.clients) { // I haven't been destroyed var server_message = message.server_message, client_id = server_message.client_id, smtype = server_message.type, client = this.clients[client_id]; if(client) { if (smtype === "changed") { client.on_change.apply(client, server_message.getting); } else if (smtype === "emit") { client.on_emit.apply(client, ([server_message.event_type]).concat(server_message.args)); } } } }; proto.on_response = function(message) { var request_id = message.request_id, response = message.response; if (this.response_listeners.hasOwnProperty(request_id)) { var response_listener = this.response_listeners[request_id]; if(response_listener !== DEREGISTERED) { response_listener(response); } delete this.response_listeners[request_id]; } else { this.pending_responses[request_id] = response; } }; proto.on_cobj_links = function(message) { this._emit("cobj_links", message); }; proto.register_response_listener = function (id, listener) { if (this.pending_responses.hasOwnProperty(id)) { listener(this.pending_responses[id]); delete this.pending_responses[id]; } else { this.response_listeners[id] = listener; } }; proto.deregister_response_listener = function(id) { if (this.pending_responses.hasOwnProperty(id)) { delete this.pending_responses[id]; } if (this.response_listeners.hasOwnProperty(id)) { this.response_listeners[id] = DEREGISTERED; // don't want it added to pending when we get a response } }; proto.get_constraint_client = function(id) { if(this.constraint_clients.hasOwnProperty(id)) { return this.constraint_clients[id]; } else { var rv = this.constraint_clients[id] = new ist.RemoteConstraintClient(false, id); rv.set_communication_mechanism(this.comm_mechanism); return rv; } }; proto.get_wrapper_client = function(object_summary) { var cobj_id = object_summary.id; var rv; if(this.wrapper_clients.hasOwnProperty(cobj_id)) { rv = this.wrapper_clients[cobj_id]; rv.object_summary = object_summary; return rv; } else { var otype = object_summary.type; var obj_id = object_summary.obj_id; rv = new ist.WrapperClient({ comm_mechanism: this.comm_mechanism, cobj_id: cobj_id, obj_id: obj_id, type: otype, object_summary: object_summary, program_state_client: this }); var client_id = rv.id(); this.clients[client_id] = rv; this.wrapper_clients[cobj_id] = rv; rv.on_ready(); var on_destroy = _.bind(function() { rv.off("wc_destroy", on_destroy); this.destroy_wrapper_client(client_id, cobj_id); }, this); rv.on("wc_destroy", on_destroy); return rv; } }; proto.destroy_wrapper_client = function(client_id, cobj_id) { delete this.clients[client_id]; delete this.wrapper_clients[cobj_id]; }; proto.destroy = function (dont_destroy_comm_wrapper) { this.disconnect(); able.destroy_this_listenable(this); this.remove_message_listener(); this.destroy_every_client(); delete this.wrapper_clients; delete this.clients; delete this.root_client; if(dont_destroy_comm_wrapper !== false && this.comm_mechanism) { this.comm_mechanism.destroy(); delete this.comm_mechanism; } }; proto.post = function (message, callback) { this.comm_mechanism.post(message, callback); }; proto.post_command = function (command, callback) { var stringified_command; if (ist.programStateCommands.indexOf(command) >= 0) { stringified_command = command; } else { stringified_command = ist.stringify(command); } this.post({ type: "command", command: stringified_command }, callback); return stringified_command; }; }(ist.ProgramStateClient)); ist.indirectClient = function(client_constraint) { var client_val = cjs.get(client_constraint), old_client = client_val, prop_names = _.rest(arguments), client_is_valid, rv, is_arr = prop_names.length !== 1; if (client_val instanceof ist.WrapperClient) { client_val.signal_interest(); client_is_valid = true; } else { client_is_valid = false; } if(is_arr) { rv = cjs.map({ keys: _.map(prop_names, function(prop_name) { return _.isArray(prop_name) ? prop_name[0] : prop_name; }), values: _.map(prop_names, function(prop_name) { var args = _.isArray(prop_name) ? prop_name : [prop_name]; return (client_val instanceof ist.WrapperClient) ? client_val.get_$.apply(client_val, args) : false; }) }); } else { var args = _.isArray(prop_names[0]) ? prop_names[0] : [prop_names[0]]; rv = cjs.constraint((client_val instanceof ist.WrapperClient) ? client_val.get_$.apply(client_val, args) : false); } var on_change_fn = function() { old_client = client_val; var client_was_valid = old_client instanceof ist.WrapperClient; client_val = cjs.get(client_constraint); client_is_valid = client_val instanceof ist.WrapperClient; if(is_arr) { _.each(prop_names, function(prop_name) { if(client_val instanceof ist.WrapperClient) { var args = _.isArray(prop_name) ? prop_name : [prop_name]; rv.put(args[0], client_val.get_$.apply(client_val, args)); if(rv.do_debug) { console.log(prop_name, args); } } else { rv.remove(prop_name); } }); } else { if(client_val instanceof ist.WrapperClient) { var args = _.isArray(prop_names[0]) ? prop_names[0] : [prop_names[0]]; rv.set(client_val.get_$.apply(client_val, args)); } else { rv.set(false); } } if(client_is_valid && !client_was_valid) { client_val.signal_interest(); } else if(client_was_valid && !client_is_valid) { old_client.signal_destroy(); } else if(client_was_valid && client_is_valid) { if(old_client !== client_val) { old_client.signal_destroy(); client_val.signal_interest(); } } }; if(cjs.isConstraint(client_constraint)) { client_constraint.onChange(on_change_fn); } var old_destroy = rv.destroy; rv.destroy = function() { if(cjs.isConstraint(client_constraint)) { client_constraint.offChange(on_change_fn); } old_destroy.apply(rv, arguments); if(client_val instanceof ist.WrapperClient) { client_val.signal_destroy(); } }; return rv; }; }(interstate, jQuery));
/* 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( 'undo', 'ka', { redo: 'გამეორება', undo: 'გაუქმება' } );
/* eslint-disable complexity */ import createActivitiesStyle from './StyleSet/Activities'; import createActivityStyle from './StyleSet/Activity'; import createAudioAttachmentStyle from './StyleSet/AudioAttachment'; import createAudioContentStyle from './StyleSet/AudioContent'; import createAvatarStyle from './StyleSet/Avatar'; import createBubbleStyle from './StyleSet/Bubble'; import createCarouselFilmStrip from './StyleSet/CarouselFilmStrip'; import createCarouselFlipper from './StyleSet/CarouselFlipper'; import createConnectivityNotification from './StyleSet/ConnectivityNotification'; import createDictationInterimsStyle from './StyleSet/DictationInterims'; import createErrorBoxStyle from './StyleSet/ErrorBox'; import createErrorNotificationStyle from './StyleSet/ErrorNotification'; import createFileContentStyle from './StyleSet/FileContent'; import createImageAvatarStyle from './StyleSet/ImageAvatar'; import createInitialsAvatarStyle from './StyleSet/InitialsAvatar'; import createMicrophoneButtonStyle from './StyleSet/MicrophoneButton'; import createRootStyle from './StyleSet/Root'; import createScrollToEndButtonStyle from './StyleSet/ScrollToEndButton'; import createSendBoxButtonStyle from './StyleSet/SendBoxButton'; import createSendBoxStyle from './StyleSet/SendBox'; import createSendBoxTextAreaStyle from './StyleSet/SendBoxTextArea'; import createSendBoxTextBoxStyle from './StyleSet/SendBoxTextBox'; import createSendStatusStyle from './StyleSet/SendStatus'; import createSingleAttachmentActivityStyle from './StyleSet/SingleAttachmentActivity'; import createSpinnerAnimationStyle from './StyleSet/SpinnerAnimation'; import createStackedLayoutStyle from './StyleSet/StackedLayout'; import createSuggestedActionsStyle from './StyleSet/SuggestedActions'; import createSuggestedActionStyle from './StyleSet/SuggestedAction'; import createTextContentStyle from './StyleSet/TextContent'; import createToasterStyle from './StyleSet/Toaster'; import createToastStyle from './StyleSet/Toast'; import createTypingAnimationStyle from './StyleSet/TypingAnimation'; import createTypingIndicatorStyle from './StyleSet/TypingIndicator'; import createUploadButtonStyle from './StyleSet/UploadButton'; import createVideoAttachmentStyle from './StyleSet/VideoAttachment'; import createVideoContentStyle from './StyleSet/VideoContent'; import createVimeoContentStyle from './StyleSet/VimeoContent'; import createWarningNotificationStyle from './StyleSet/WarningNotification'; import createYouTubeContentStyle from './StyleSet/YouTubeContent'; import defaultStyleOptions from './defaultStyleOptions'; // TODO: [P4] We should add a notice for people who want to use "styleSet" instead of "styleOptions". // "styleSet" is actually CSS stylesheet and it is based on the DOM tree. // DOM tree may change from time to time, thus, maintaining "styleSet" becomes a constant effort. function parseBorder(border) { const dummyElement = document.createElement('div'); dummyElement.setAttribute('style', `border: ${border}`); const { style: { borderColor: color, borderStyle: style, borderWidth: width } } = dummyElement; return { color, style, width }; } const PIXEL_UNIT_PATTERN = /^\d+px$/u; export default function createStyleSet(options) { options = { ...defaultStyleOptions, ...options }; // Keep this list flat (no nested style) and serializable (no functions) // TODO: [P4] Deprecate this code after bump to v5 const { bubbleBorder, bubbleFromUserBorder, bubbleFromUserNubOffset, bubbleNubOffset, suggestedActionBorder, suggestedActionDisabledBorder } = options; if (bubbleBorder) { console.warn( 'botframework-webchat: "styleSet.bubbleBorder" is deprecated and will be removed on or after 2020-07-17. Please use "bubbleBorderColor", "bubbleBorderStyle", and, "bubbleBorderWidth.' ); const { color, style, width } = parseBorder(bubbleBorder); if (color && color !== 'initial') { options.bubbleBorderColor = color; } if (style && style !== 'initial') { options.bubbleBorderStyle = style; } if (PIXEL_UNIT_PATTERN.test(width)) { options.bubbleBorderWidth = parseInt(width, 10); } } if (bubbleFromUserBorder) { console.warn( 'botframework-webchat: "styleSet.bubbleFromUserBorder" is deprecated and will be removed on or after 2020-07-17. Please use "bubbleFromUserBorderColor", "bubbleFromUserBorderStyle", and, "bubbleFromUserBorderWidth".' ); const { color, style, width } = parseBorder(bubbleFromUserBorder); if (color && color !== 'initial') { options.bubbleFromUserBorderColor = color; } if (style && style !== 'initial') { options.bubbleFromUserBorderStyle = style; } if (PIXEL_UNIT_PATTERN.test(width)) { options.bubbleFromUserBorderWidth = parseInt(width, 10); } } if (suggestedActionBorder) { console.warn( 'botframework-webchat: "styleSet.suggestedActionBorder" is deprecated and will be removed on or after 2020-09-11. Please use "suggestedActionBorderColor", "suggestedActionBorderStyle", and, "suggestedActionBorderWidth".' ); const { color, style, width } = parseBorder(suggestedActionBorder); if (color && color !== 'initial') { options.suggestedActionBorderColor = color; } if (style && style !== 'initial') { options.suggestedActionBorderStyle = style; } if (PIXEL_UNIT_PATTERN.test(width)) { options.suggestedActionBorderWidth = parseInt(width, 10); } } if (suggestedActionDisabledBorder) { console.warn( 'botframework-webcaht: "styleSet.suggestedActionDisabledBorder" is deprecated and will be removed on or after 2020-09-11. Please use "suggestedActionDisabledBorderColor", "suggestedActionDisabledBorderStyle", and, "suggestedActionDisabledBorderWidth".' ); const { color, style, width } = parseBorder(suggestedActionDisabledBorder); if (color && color !== 'initial') { options.suggestedActionDisabledBorderColor = color; } if (style && style !== 'initial') { options.suggestedActionDisabledBorderStyle = style; } if (PIXEL_UNIT_PATTERN.test(width)) { options.suggestedActionDisabledBorderWidth = parseInt(width, 10); } } if (bubbleFromUserNubOffset === 'top') { options.bubbleFromUserNubOffset = 0; } else if (typeof bubbleFromUserNubOffset !== 'number') { options.bubbleFromUserNubOffset = -0; } if (bubbleNubOffset === 'top') { options.bubbleNubOffset = 0; } else if (typeof bubbleNubOffset !== 'number') { options.bubbleNubOffset = -0; } if (options.emojiSet === true) { options.emojiSet = { ':)': '😊', ':-)': '😊', '(:': '😊', '(-:': '😊', ':-|': '😐', ':|': '😐', ':-(': '☹️', ':(': '☹️', ':-D': '😀', ':D': '😀', ':-p': '😛', ':p': '😛', ':-P': '😛', ':P': '😛', ':-o': '😲', ':o': '😲', ':O': '😲', ':-O': '😲', ':-0': '😲', ':0': '😲', ';-)': '😉', ';)': '😉', '<3': '❤️', '</3': '💔', '<\\3': '💔' }; } else if (Object.prototype.toString.call(options.emojiSet) !== '[object Object]') { console.warn('botframework-webchat: emojiSet must be a boolean or an object with emoticon: emojiValues'); options.emojiSet = false; } return { activities: createActivitiesStyle(options), activity: createActivityStyle(options), audioAttachment: createAudioAttachmentStyle(options), audioContent: createAudioContentStyle(options), avatar: createAvatarStyle(options), bubble: createBubbleStyle(options), carouselFilmStrip: createCarouselFilmStrip(options), carouselFlipper: createCarouselFlipper(options), connectivityNotification: createConnectivityNotification(options), dictationInterims: createDictationInterimsStyle(options), errorBox: createErrorBoxStyle(options), errorNotification: createErrorNotificationStyle(options), fileContent: createFileContentStyle(options), imageAvatar: createImageAvatarStyle(options), initialsAvatar: createInitialsAvatarStyle(options), microphoneButton: createMicrophoneButtonStyle(options), options: { ...options }, // Cloned to make sure no additional modifications will propagate up. root: createRootStyle(options), scrollToEndButton: createScrollToEndButtonStyle(options), sendBox: createSendBoxStyle(options), sendBoxButton: createSendBoxButtonStyle(options), sendBoxTextArea: createSendBoxTextAreaStyle(options), sendBoxTextBox: createSendBoxTextBoxStyle(options), sendStatus: createSendStatusStyle(options), singleAttachmentActivity: createSingleAttachmentActivityStyle(options), spinnerAnimation: createSpinnerAnimationStyle(options), stackedLayout: createStackedLayoutStyle(options), suggestedAction: createSuggestedActionStyle(options), suggestedActions: createSuggestedActionsStyle(options), textContent: createTextContentStyle(options), toast: createToastStyle(options), toaster: createToasterStyle(options), typingAnimation: createTypingAnimationStyle(options), typingIndicator: createTypingIndicatorStyle(options), uploadButton: createUploadButtonStyle(options), videoAttachment: createVideoAttachmentStyle(options), videoContent: createVideoContentStyle(options), vimeoContent: createVimeoContentStyle(options), warningNotification: createWarningNotificationStyle(options), youTubeContent: createYouTubeContentStyle(options) }; }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Tag Schema */ var TagSchema = new Schema({ created: { type: Date, default: Date.now }, title: { type: String, default: '', trim: true, required: 'Title cannot be blank' }, content: { type: String, default: '', trim: true }, tag: { type: String, default: '', trim: true }, user: { type: Schema.ObjectId, ref: 'User' }, containertag: { type: Schema.ObjectId, ref: 'Containertags' }, count: { type: Number, default: 0 } }); mongoose.model('Tag', TagSchema);
const AlfredModule = require("../../AlfredModule") const moduleUtils = require("../../lib/moduleUtils") const randomElement = require("../../lib/randomElement") const request = require("request") module.exports = class ModuleHello extends AlfredModule { constructor(){ super() this.icon = "🔮" //Un emoji this.name = "Encyclopédie" this.help = [{example: "Qui est Barrack Obama ?"}, {example: "Qu'est ce qu'un tabouret ?", description: "Je cherche la signification sur wikipedia et d'autres sites"}] this.start([/Qu[' ]est[- ]ce qu(?:e|') ?(?:la|le|les|une?|l')? ?([^?]+)(?: ?\?)?/i, /Qui est ([^?]+)(?: ?\?)?/i], (matching,bot)=>this.search(matching,bot)) } init(bot){ super.init(bot) console.log("Encyclopedia module initialized") } search(matching,bot){ matching.reply("Je cherche...") this.searchOnWikipedia(matching,(result) => { if(result){ matching.reply(result) matching.conversation.end() }else{ this.searchOnDuckduckgo(matching,result => { if(result) matching.reply(result) else matching.reply("Je n'ai rien trouvé d'interessant à propos de "+matching.case.regexResult[1]+". Essayez https://duckduckgo.com/?q="+matching.regexResult[1].replace(/ /g,"+")) matching.conversation.end() }) } }) } searchOnWikipedia(matching,callback) { var wikiSerachOptions = "http://fr.wikipedia.org/w/api.php?action=opensearch&search="+matching.case.regexResult[1]+"&format=json&utf8" request(wikiSerachOptions,(err,res,result) => { try{ result = JSON.parse(result) if(result[2].length > 0){ if(result[2][0] == "" && result[2][1]){ callback(result[2][1]) } else if(result[2][0] != "") { callback(result[2][0]) } else { callback() return } } else { callback() } } catch(e) { matching.reply("Whoops, j'ai une érreur... proposez autre chose peut être...") } }) } searchOnDuckduckgo(matching,callback){ var trustedLiks = [ /[^.]+\.wikia\.com/i, /imdb\.com/i ] var searchQuery = "https://duckduckgo.com/html?q="+matching.case.regexResult[1].replace(/ /g,"+") request(searchQuery,(err,res,result) => { var resultParser = /class="result__snippet" href=".+uddg=([^"]+)/gi var regResult = [] while((regResult = resultParser.exec(result)) != null){ var link = decodeURIComponent(regResult[1]) for(var i in trustedLiks){ if(link.match(trustedLiks[i])){ callback(link) return } } } callback() }) } }
var path = require('path') var webpack = require('webpack') module.exports = { devtool: 'cheap-module-eval-source-map', entry: { react: './ssr/react-bundle', helloworld: './ssr/helloworld', }, output: { path: path.join(__dirname, 'public/build'), filename: '[name].bundle.js', publicPath: '/build/' }, plugins: [ ], module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel'], exclude: /node_modules/, include: __dirname }] } }
/* ************************************************************************ * * qooxdoo-compiler - node.js based replacement for the Qooxdoo python * toolchain * * https://github.com/qooxdoo/qooxdoo-compiler * * Copyright: * 2011-2019 Zenesis Limited, http://www.zenesis.com * * License: * MIT: https://opensource.org/licenses/MIT * * This software is provided under the same licensing terms as Qooxdoo, * please see the LICENSE file in the Qooxdoo project's top-level directory * for details. * * Authors: * * John Spackman (john.spackman@zenesis.com, @johnspackman) * * *********************************************************************** */ /** * Writer for serialising JSON, automatically indenting as required */ qx.Class.define("qx.tool.utils.json.Writer", { extend: qx.core.Object, construct: function() { this.base(arguments); this.buffer = ""; this.__indent = 0; this.__indentStr = ""; this.__currentLine = 0; }, members: { /** * Writes a string/number. Multiple lines are rewritten with indentation at the * start of each line */ write(str) { if (str === null) { str = "null"; } else if (str === undefined) { str = "undefined"; } else if (typeof str === "number") { str = str.toString(); } else if (typeof str === "boolean") { str = str ? "true" : "false"; } else if (typeof str !== "string") { throw new Error("Can only write strings and numbers"); } var startPos = 0; /* eslint-disable no-constant-condition */ while (true) { var pos = str.indexOf("\n", startPos); if (pos > -1) { this.buffer += str.substring(startPos, pos + 1); this.__currentLine = this.buffer.length; this.buffer += this.__indentStr; startPos = pos + 1; } else { this.buffer += str.substring(startPos); break; } } return this; }, /** * Outputs comments */ comments(comments) { var t = this; if (comments) { comments.forEach(function(comment) { t.write(comment.source + "\n"); }); } }, /** * Increases or decreases the indentation level (one indent is two spaces) * * @param count {Number} number to increase/decrease by */ indent(count) { if (this.__indent + count < 0) { throw new Error("Unbalanced indent"); } this.__indent += count; var indentStr = this.__indentStr; if (count > 0) { var str = ""; for (var i = 0; i < count; i++) { str += " "; } indentStr += str; } else { indentStr = indentStr.substring(0, indentStr.length + (count * 2)); } var line = this.buffer.substring(this.__currentLine); if (!line.match(/[^\s]/)) { this.buffer = this.buffer.substring(0, this.__currentLine) + indentStr; } this.__indentStr = indentStr; return this; }, /** * Detects the current indentation level in the output, which has been added manually, * ie outside of the `indent()` method. When outputting an AST via `reprint()`, whitespace * is copied too, this allows the code to adopt whatever indentation level has been * output by the AST so that injecting `prettyPrint()`-ed new objects are at the same\ * level. * * The old indent is returned, and should be passed to `resetIndent()` to restore the * previous value. * * @return {Object} previous indentation */ matchIndent() { var line = this.buffer.substring(this.__currentLine); var m = line.match(/^([\s]*)/); var indent = m[0]; var oldIndent = this.__indentStr; this.__indentStr = indent; return oldIndent; }, /** * Restores the previous indentation settings prior to `matchIndent()` * * @param indent {Object} previous indentation settings */ resetIndent(indent) { this.__indentStr = indent; } } });
/** * Message Parser * Cassius - https://github.com/sirDonovan/Cassius * * This file parses messages sent by the server. * * @license MIT license */ 'use strict'; const capsRegex = new RegExp('[A-Z]', 'g'); const stretchRegex = new RegExp('(.+)\\1+', 'g'); const FLOOD_MINIMUM_MESSAGES = 5; const FLOOD_MAXIMUM_TIME = 5 * 1000; const STRETCHING_MINIMUM = 20; const CAPS_MINIMUM = 30; const PUNISHMENT_COOLDOWN = 5 * 1000; class Context { /** * @param {string} target * @param {Room | User} room * @param {User} user * @param {string} command * @param {string} originalCommand * @param {number} [time] */ constructor(target, room, user, command, originalCommand, time) { this.target = target ? target.trim() : ''; this.room = room; this.user = user; this.command = command; this.originalCommand = originalCommand; this.time = time || Date.now(); } /** * @param {string} text */ say(text) { this.room.say(text); } /** * @param {string} message; */ sayHtml(message) { if (this.room instanceof Users.User) return this.pmHtml(this.room, message); this.room.say("/addhtmlbox " + message, true); } /** * @param {User | string} user * @param {string} message; */ pm(user, message) { if (typeof user === 'string') user = Users.add(user); user.say(message); } /** * @param {User | string} user * @param {string} message; */ pmHtml(user, message) { let room = this.room; if (room instanceof Users.User) { let botRoom; Users.self.rooms.forEach((rank, room) => { if (rank === '*') botRoom = room; }); if (!botRoom) return this.pm(user, message); room = botRoom; } room.say("/pminfobox " + Tools.toId(user) + ", " + message, true); } /** * @param {string} [newCommand] * @param {string} [newTarget] * @returns {boolean} */ run(newCommand, newTarget) { let command = this.command; let target = this.target; let originalCommand = this.originalCommand; if (newCommand) { newCommand = Tools.toId(newCommand); if (!Commands[newCommand]) return false; originalCommand = newCommand; if (typeof Commands[newCommand] === 'string') { // @ts-ignore Typescript bug - issue #10530 newCommand = Commands[newCommand]; } // @ts-ignore command = newCommand; if (newTarget) { target = newTarget.trim(); } else { target = ''; } } if (typeof Commands[command] !== 'function') return false; try { // @ts-ignore Typescript bug - issue #10530 Commands[command].call(this, target, this.room, this.user, originalCommand, this.time); } catch (e) { let stack = e.stack; stack += 'Additional information:\n'; stack += 'Command = ' + command + '\n'; stack += 'Target = ' + target + '\n'; stack += 'Time = ' + new Date(this.time).toLocaleString() + '\n'; stack += 'User = ' + this.user.name + '\n'; stack += 'Room = ' + (this.room instanceof Users.User ? 'in PM' : this.room.id); console.log(stack); return false; } return true; } } exports.Context = Context; class MessageParser { constructor() { /**@type {string[]} */ this.formatsList = []; /**@type {{[k: string]: {name: string, id: string, section: string, searchShow: boolean, challengeShow: boolean, tournamentShow: boolean, playable: boolean}}} */ this.formatsData = {}; this.globalContext = new Context('', Rooms.globalRoom, Users.self, '', ''); } /** * @param {string} message * @param {Room} room */ parse(message, room) { let splitMessage = message.split('|').slice(1); let messageType = splitMessage[0]; splitMessage.shift(); if (typeof Config.parseMessage === 'function') Config.parseMessage(room, messageType, splitMessage); if (Plugins) { for (let i = 0, len = Plugins.length; i < len; i++) { if (typeof Plugins[i].parseMessage === 'function') Plugins[i].parseMessage(room, messageType, splitMessage); } } switch (messageType) { case 'challstr': Client.challstr = splitMessage.join("|"); Client.login(); break; case 'updateuser': const parsedUsername = Tools.parseUsernameText(splitMessage[0]); if (Tools.toId(parsedUsername.username) !== Users.self.id) return; if (Client.connectTimeout) clearTimeout(Client.connectTimeout); if (splitMessage[1] !== '1') { console.log('Failed to log in'); process.exit(); } console.log('Successfully logged in'); if (Config.rooms) { if (!(Config.rooms instanceof Array)) throw new Error("Config.rooms must be an array"); for (let i = 0, len = Config.rooms.length; i < len; i++) { Client.send('|/join ' + Config.rooms[i]); } } if (Config.avatar) Client.send('|/avatar ' + Config.avatar); break; case 'init': room.onJoin(Users.self, ' '); console.log('Joined room: ' + room.id); break; case 'noinit': console.log('Could not join room: ' + room.id); Rooms.destroy(room); break; case 'deinit': Rooms.destroy(room); break; case 'users': { if (splitMessage[0] === '0') return; let users = splitMessage[0].split(","); for (let i = 1, len = users.length; i < len; i++) { const parsedUsername = Tools.parseUsernameText(users[i].substr(1)); let user = Users.add(parsedUsername.username); let rank = users[i].charAt(0); room.users.set(user, rank); user.rooms.set(room, rank); } break; } case 'formats': { this.formatsList = splitMessage.slice(); this.parseFormats(); break; } case 'tournament': { if (!Config.tournaments || !Config.tournaments.includes(room.id)) return; switch (splitMessage[0]) { case 'create': { let format = Tools.getFormat(splitMessage[1]); if (!format) throw new Error("Unknown format used in tournament (" + splitMessage[1] + ")"); room.tour = Tournaments.createTournament(room, format, splitMessage[2]); if (splitMessage[3]) room.tour.playerCap = parseInt(splitMessage[3]); break; } case 'update': { let data = JSON.parse(splitMessage.slice(1).join("|")); if (!data || !(data instanceof Object)) return; if (!room.tour) { let format = Tools.getFormat(data.teambuilderFormat) || Tools.getFormat(data.format); if (!format) throw new Error("Unknown format used in tournament (" + (data.teambuilderFormat || data.format) + ")"); room.tour = Tournaments.createTournament(room, format, data.generator); room.tour.started = true; } Object.assign(room.tour.updates, data); break; } case 'updateEnd': if (room.tour) room.tour.update(); break; case 'end': { let data = JSON.parse(splitMessage.slice(1).join("|")); if (!data || !(data instanceof Object)) return; if (!room.tour) { let format = Tools.getFormat(data.teambuilderFormat) || Tools.getFormat(data.format); if (!format) throw new Error("Unknown format used in tournament (" + (data.teambuilderFormat || data.format) + ")"); room.tour = Tournaments.createTournament(room, format, data.generator); room.tour.started = true; } Object.assign(room.tour.updates, data); room.tour.update(); room.tour.end(); break; } case 'forceend': if (room.tour) room.tour.end(); break; case 'join': if (room.tour) room.tour.addPlayer(splitMessage[1]); break; case 'leave': if (room.tour) room.tour.removePlayer(splitMessage[1]); break; case 'disqualify': if (room.tour) room.tour.removePlayer(splitMessage[1]); break; case 'start': if (room.tour) room.tour.start(); break; case 'battlestart': if (room.tour && !room.tour.isRoundRobin && room.tour.generator === 1 && room.tour.getRemainingPlayerCount() === 2) { room.say("/wall Final battle of " + room.tour.format.name + " tournament: <<" + splitMessage[3].trim() + ">>"); } break; } break; } case 'J': case 'j': { const parsedUsername = Tools.parseUsernameText(splitMessage[0]); let user = Users.add(parsedUsername.username); if (!user) return; room.onJoin(user, splitMessage[0].charAt(0)); if (Storage.globalDatabase.mail && user.id in Storage.globalDatabase.mail) { let mail = Storage.globalDatabase.mail[user.id]; for (let i = 0, len = mail.length; i < len; i++) { user.say("[" + Tools.toDurationString(Date.now() - mail[i].time) + " ago] **" + mail[i].from + "** said: " + mail[i].text); } delete Storage.globalDatabase.mail[user.id]; Storage.exportDatabase('global'); } break; } case 'L': case 'l': { const parsedUsername = Tools.parseUsernameText(splitMessage[0]); let user = Users.add(parsedUsername.username); if (!user) return; room.onLeave(user); break; } case 'N': case 'n': { let user = Users.add(splitMessage[1]); if (!user) return; const parsedUsername = Tools.parseUsernameText(splitMessage[0]); room.onRename(user, splitMessage[0].charAt(0) + parsedUsername.username); break; } case 'c': { let user = Users.get(splitMessage[0]); if (!user) return; let rank = splitMessage[0].charAt(0); if (user.rooms.get(room) !== rank) user.rooms.set(room, rank); let message = splitMessage.slice(1).join('|'); if (user.id === Users.self.id) { message = Tools.toId(message); if (message in room.listeners) room.listeners[message](); return; } let time = Date.now(); this.parseCommand(message, room, user, time); if (!user.hasRank(room, '+')) this.moderate(message, room, user, time); break; } case 'c:': { let user = Users.get(splitMessage[1]); if (!user) return; let rank = splitMessage[1].charAt(0); if (user.rooms.get(room) !== rank) user.rooms.set(room, rank); let message = splitMessage.slice(2).join('|'); if (user.id === Users.self.id) { message = Tools.toId(message); if (message in room.listeners) room.listeners[message](); return; } let time = parseInt(splitMessage[0]) * 1000; this.parseCommand(message, room, user, time); if (!user.hasRank(room, '+')) this.moderate(message, room, user, time); break; } case 'pm': { let user = Users.add(splitMessage[0]); if (!user) return; if (user.id === Users.self.id) return; this.parseCommand(splitMessage.slice(2).join('|'), user, user); break; } case 'raw': { let message = splitMessage.join('|'); if (message.includes('<div class="broadcast-red">') && message.includes('The server is restarting soon.')) { Client.lockdown = true; } else if (message.includes('<div class="broadcast-green">') && message.includes('The server restart was canceled.')) { Client.lockdown = false; } } } } /** * @param {string} message * @param {Room | User} room * @param {User} user * @param {number} [time] */ parseCommand(message, room, user, time) { message = message.trim(); if (message.charAt(0) !== Config.commandCharacter) return; message = message.substr(1); let spaceIndex = message.indexOf(' '); let target = ''; let command = ''; if (spaceIndex !== -1) { command = message.substr(0, spaceIndex); target = message.substr(spaceIndex + 1); } else { command = message; } command = Tools.toId(command); if (!Commands[command]) return; let originalCommand = command; if (typeof Commands[command] === 'string') { // @ts-ignore Typescript bug - issue #10530 command = Commands[command]; } if (typeof Commands[command] !== 'function') return; return new Context(target, room, user, command, originalCommand, time).run(); } parseFormats() { if (!this.formatsList.length) return; this.formatsData = {}; let isSection = false; let section = ''; for (let i = 0, len = this.formatsList.length; i < len; i++) { if (isSection) { section = this.formatsList[i]; isSection = false; } else if (this.formatsList[i] === ',LL') { continue; } else if (this.formatsList[i] === '' || (this.formatsList[i].charAt(0) === ',' && !isNaN(parseInt(this.formatsList[i].substr(1))))) { isSection = true; } else { let name = this.formatsList[i]; let searchShow = true; let challengeShow = true; let tournamentShow = true; let lastCommaIndex = name.lastIndexOf(','); let code = lastCommaIndex >= 0 ? parseInt(name.substr(lastCommaIndex + 1), 16) : NaN; if (!isNaN(code)) { name = name.substr(0, lastCommaIndex); if (!(code & 2)) searchShow = false; if (!(code & 4)) challengeShow = false; if (!(code & 8)) tournamentShow = false; } else { // Backwards compatibility: late 0.9.0 -> 0.10.0 if (name.substr(name.length - 2) === ',#') { // preset teams name = name.substr(0, name.length - 2); } if (name.substr(name.length - 2) === ',,') { // search-only challengeShow = false; name = name.substr(0, name.length - 2); } else if (name.substr(name.length - 1) === ',') { // challenge-only searchShow = false; name = name.substr(0, name.length - 1); } } let id = Tools.toId(name); if (!id) continue; this.formatsData[id] = { name: name, id: id, section: section, searchShow: searchShow, challengeShow: challengeShow, tournamentShow: tournamentShow, playable: tournamentShow || ((searchShow || challengeShow) && tournamentShow !== false), }; } } Tools.FormatCache.clear(); } /** * @param {string} message * @param {Room} room * @param {User} user * @param {number} time */ moderate(message, room, user, time) { if (!Users.self.hasRank(room, '%')) return; if (typeof Config.allowModeration === 'object') { if (!Config.allowModeration[room.id]) return; } else { if (!Config.allowModeration) return; } if (!Config.punishmentPoints || !Config.punishmentActions) return; message = Tools.trim(message); let data = user.roomData.get(room); if (!data) { data = {messages: [], points: 0, lastAction: 0}; user.roomData.set(room, data); } data.messages.unshift({message: message, time: time}); // avoid escalating punishments for the same message(s) due to lag or the message queue if (data.lastAction && time - data.lastAction < PUNISHMENT_COOLDOWN) return; /**@type {Array<{action: string, rule: string, reason: string}>} */ let punishments = []; if (typeof Config.moderate === 'function') { let result = Config.moderate(message, room, user, time); if (result instanceof Array) punishments = punishments.concat(result); } // flooding if (data.messages.length >= FLOOD_MINIMUM_MESSAGES) { let testTime = time - data.messages[FLOOD_MINIMUM_MESSAGES - 1].time; // account for the server's time changing if (testTime >= 0 && testTime <= FLOOD_MAXIMUM_TIME) { punishments.push({action: 'mute', rule: 'flooding', reason: 'please do not flood the chat'}); } } // stretching let stretching = message.match(stretchRegex); if (stretching) { stretching.sort((a, b) => b.length - a.length); if (stretching[0].length >= STRETCHING_MINIMUM) { punishments.push({action: 'verbalwarn', rule: 'stretching', reason: 'please do not stretch'}); } } // caps let caps = message.match(capsRegex); if (caps && caps.length >= CAPS_MINIMUM) { punishments.push({action: 'verbalwarn', rule: 'caps', reason: 'please do not abuse caps'}); } if (!punishments.length) return; punishments.sort((a, b) => Config.punishmentPoints[b.action] - Config.punishmentPoints[a.action]); let punishment = punishments[0]; let points = Config.punishmentPoints[punishment.action]; let reason = punishment.reason; if (Config.punishmentReasons && Config.punishmentReasons[punishment.rule]) reason = Config.punishmentReasons[punishment.rule]; let action = punishment.action; if (data.points >= points) { data.points++; points = data.points; if (Config.punishmentActions['' + points]) action = Config.punishmentActions['' + points]; } else { data.points = points; } if (action === 'verbalwarn') return room.say(user.name + ", " + reason); if (action === 'roomban' && !Users.self.hasRank(room, '@')) action = 'hourmute'; room.say("/" + action + " " + user.name + ", " + reason); data.lastAction = time; } } exports.MessageParser = new MessageParser();
$axure.loadCurrentPage( (function() { var _ = function() { var r={},a=arguments; for(var i=0; i<a.length; i+=2) r[a[i]]=a[i+1]; return r; } var _creator = function() { return _(b,c,d,e,f,g,h,[i],j,_(k,l,m,n,o,p,q,_(),r,_(s,t,u,v,w,_(x,y,z,A),B,null,C,v,D,v,E,F,G,null,H,I,J,K,L,M,N,I),O,_(),P,_(),Q,_(R,[])),S,_(),T,_());}; var b="url",c="用户列表.html",d="generationDate",e=new Date(1448075094930.75),f="isCanvasEnabled",g=false,h="variables",i="OnLoadVariable",j="page",k="packageId",l="1f40c6d678494240bf86fadb5531b21e",m="type",n="Axure:Page",o="name",p="用户列表",q="notes",r="style",s="baseStyle",t="627587b6038d43cca051c114ac41ad32",u="pageAlignment",v="near",w="fill",x="fillType",y="solid",z="color",A=0xFFE4E4E4,B="image",C="imageHorizontalAlignment",D="imageVerticalAlignment",E="imageRepeat",F="auto",G="favicon",H="sketchFactor",I="0",J="colorStyle",K="appliedColor",L="fontName",M="Applied Font",N="borderWidth",O="adaptiveStyles",P="interactionMap",Q="diagram",R="objects",S="masters",T="objectPaths"; return _creator(); })());
/* * dependencies of this config should be specified in `./package.json` relative * to this config file (which should be in the root of the monorepo); * yarn-workspace hoisting re: dev/Deps specified in * `packages/utils/collective/package.json` is not reliable re: dependencies of * this root-level config being resolvable (with correct versions) from the * monorepo root */ const cloneDeep = require('lodash.clonedeep'); module.exports = (api) => { const env = api.env(); const base = { babelrcRoots: [ '.', 'packages/*' ], plugins: [ 'babel-plugin-macros', [ '@babel/plugin-proposal-decorators', { legacy: true } ], '@babel/plugin-proposal-export-namespace-from', '@babel/plugin-proposal-export-default-from', '@babel/plugin-syntax-dynamic-import', [ '@babel/plugin-proposal-class-properties', { loose: true } ], '@babel/plugin-proposal-nullish-coalescing-operator', '@babel/plugin-proposal-optional-chaining', [ '@babel/plugin-transform-runtime', { corejs: 3 } ] ], presets: [ '@babel/preset-env', '@babel/preset-typescript' ] }; if (env === 'base' || env.startsWith('base:')) { return base; } const browser = cloneDeep(base); browser.plugins[browser.plugins.length - 1][1].useESModules = true; browser.presets[0] = [ browser.presets[0], { corejs: 3, modules: false, shippedProposals: true, targets: {browsers: ['last 1 version', 'not dead', '> 0.2%']}, useBuiltIns: 'usage' } ]; if (env === 'browser' || env.startsWith('browser:')) { return browser; } const node = cloneDeep(base); node.plugins.splice( node.plugins.indexOf('@babel/plugin-syntax-dynamic-import') + 1, 0, 'babel-plugin-dynamic-import-node' ); node.presets[0] = [ node.presets[0], { corejs: 3, shippedProposals: true, targets: {node: '10.17.0'}, useBuiltIns: 'usage' } ]; if (env === 'node' || env.startsWith('node:')) { return node; } const test = cloneDeep(node); if (env === 'test') { return test; } return {}; };
'use strict'; const connection = require('../knexfile'); const knex = require('knex')(connection); const assert = require('assert'); require('../libs/seedrandom-ext'); const isArray = require('lodash/isArray'); const union = require('lodash/union'); const isPlainObject = require('lodash/isPlainObject'); const Comment = require('../models/comment'); const Enrolment = require('../models/enrolment'); const Friend = require('../models/friend'); const Group = require('../models/group'); const Post = require('../models/post'); const Rating = require('../models/rating'); const Role = require('../models/role'); const Tag = require('../models/tag'); const User = require('../models/user'); const Empty = require('../models/empty'); function modelAttrs(model) { return model.attributes; } function bookify(Model) { return function(obj) { obj.__proto__ = null; // Remove hidden columns. if (Model != null) { if (Model.prototype.hidden != null) { for (let attr of Model.prototype.hidden) { delete obj[attr]; } } } return obj; }; } function removeProto(obj) { obj.__proto__ = null; delete obj.__proto__; for (let property in obj) { if (isArray(obj[property])) obj[property] = obj[property].map(removeProto); else if (isPlainObject(obj[property])) { obj[property] = ([obj[property]].map(removeProto)[0]); } } return obj; } exports.test = async function() { // Run the test. This function is required. let knexResult = null; let bookResult = null; knexResult = (await knex.select().from(User.prototype.tableName) .whereNull('deletedAt')).map(bookify(User)); let knexResultPost = new Map(); (await knex.select().from(Post.prototype.tableName) .whereNull('deletedAt')).map(bookify(Post)).map((e) => { if (e.createdById === null) return; if (!knexResultPost.has(e.createdById)) knexResultPost.set(e.createdById, []); knexResultPost.get(e.createdById).push(e); }); let knexResultComments = new Map(); (await knex.select().from(Comment.prototype.tableName) .whereNull('deletedAt')).map(bookify(Comment)).map((e) => { if (e.postId === null) return; if (!knexResultComments.has(e.postId)) knexResultComments.set(e.postId, []); knexResultComments.get(e.postId).push(e); }); for (let user of knexResult) { if (knexResultPost.has(user.userIdAttr)) user.posts = knexResultPost.get(user.userIdAttr); else user.posts = []; for (let post of user.posts) { if (knexResultComments.has(post.postIdAttr)) post.comments = knexResultComments.get(post.postIdAttr); else post.comments = []; } } bookResult = (await User.with('posts.comments').get()) .toJSON().map(removeProto); assert.deepStrictEqual(bookResult, knexResult); // With select. knexResult = (await knex.select().from(User.prototype.tableName) .whereNull('deletedAt')).map(bookify(User)); knexResultPost = new Map(); (await knex.select().from(Post.prototype.tableName) .whereNull('deletedAt')).map(bookify(Post)).map((e) => { if (e.createdById === null) return; if (!knexResultPost.has(e.createdById)) knexResultPost.set(e.createdById, []); knexResultPost.get(e.createdById).push(e); }); knexResultComments = new Map(); (await knex.select(['text', 'postId']).from(Comment.prototype.tableName) .whereNull('deletedAt')).map(bookify(Comment)).map((e) => { if (e.postId === null) return; if (!knexResultComments.has(e.postId)) knexResultComments.set(e.postId, []); knexResultComments.get(e.postId).push(e); }); for (let user of knexResult) { if (knexResultPost.has(user.userIdAttr)) user.posts = knexResultPost.get(user.userIdAttr); else user.posts = []; for (let post of user.posts) { if (knexResultComments.has(post.postIdAttr)) post.comments = knexResultComments.get(post.postIdAttr); else post.comments = []; } } bookResult = (await User.withSelect('posts.comments', ['text']).get()) .toJSON().map(removeProto); assert.deepStrictEqual(bookResult, knexResult); // Nested with. knexResult = (await knex.select().from(User.prototype.tableName) .whereNull('deletedAt')).map(bookify(User)); knexResultPost = new Map(); (await knex.select(['postIdAttr', 'text', 'createdById']) .from(Post.prototype.tableName) .whereNull('deletedAt') .where('title', 'not like', 'a%')) .map(bookify(Post)).map((e) => { if (e.createdById === null) return; if (!knexResultPost.has(e.createdById)) knexResultPost.set(e.createdById, []); knexResultPost.get(e.createdById).push(e); }); knexResultComments = new Map(); (await knex.select(['text', 'postId']).from(Comment.prototype.tableName) .whereNull('deletedAt')).map(bookify(Comment)).map((e) => { if (e.postId === null) return; if (!knexResultComments.has(e.postId)) knexResultComments.set(e.postId, []); knexResultComments.get(e.postId).push(e); }); for (let user of knexResult) { if (knexResultPost.has(user.userIdAttr)) user.posts = knexResultPost.get(user.userIdAttr); else user.posts = []; for (let post of user.posts) { if (knexResultComments.has(post.postIdAttr)) post.comments = knexResultComments.get(post.postIdAttr); else post.comments = []; } } bookResult = (await User.withSelect('posts', ['postIdAttr', 'text'], (q) => { q.whereNotLike('title', 'a%'); q.withSelect('comments', 'text'); }).get()) .toJSON().map(removeProto); assert.deepStrictEqual(bookResult, knexResult); }; /*(async() => { //await exports.setUp(); await exports.test(); //await exports.tearDown(); })().catch((error) => { console.error(error); }); */
Reveal.initialize({ width: 1920, height: 1080, margin: 0.1, controls: false, center: false, dependencies: [ { src: './bower_components/reveal.js/plugin/notes/notes.js', async: true }, { src: './bower_components/reveal.js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } } ] }); Reveal.addEventListener('slidechanged', drawGraph); Reveal.addEventListener('fragmentshown', drawGraph); Reveal.addEventListener('fragmenthidden', drawGraph); Reveal.addEventListener('pancakes', showPancakes); Reveal.addEventListener('commands', showCommands);
/** * render to canvas */ Fireworks.EffectsStackBuilder.prototype.renderToCanvas = function(opts) { opts = opts || {}; var ctx = opts.ctx || buildDefaultContext(); // create the effect itself var effect = Fireworks.createEffect('renderToCanvas', { ctx : ctx }).pushTo(this._emitter); if( opts.type === 'arc' ) ctorTypeArc(effect); else if( opts.type === 'drawImage' ) ctorTypeDrawImage(effect); else{ console.assert(false, 'renderToCanvas opts.type is invalid: '); } return this; // for chained API function buildDefaultContext(){ // build canvas element var canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); // canvas.style canvas.style.position = "absolute"; canvas.style.left = 0; canvas.style.top = 0; // setup ctx var ctx = canvas.getContext('2d'); // return ctx return ctx; } function ctorTypeArc(){ return effect.onCreate(function(particle, particleIdx){ particle.renderToCanvas = { size : 3 }; }).onRender(function(particle){ var position = particle.position.vector; var size = particle.renderToCanvas.size; ctx.beginPath(); ctx.arc(position.x + canvas.width /2, position.y + canvas.height/2, size, 0, Math.PI*2, true); ctx.fill(); }); }; function ctorTypeDrawImage(){ // handle parameter polymorphism if( typeof(opts.image) === 'string' ){ var images = [new Image]; images[0].src = opts.image; }else if( opts.image instanceof Image ){ var images = [opts.image]; }else if( opts.image instanceof Array ){ var images = opts.image; }else console.assert(false, 'invalid .renderToCanvas() options') return effect.onCreate(function(particle, particleIdx){ particle.renderToCanvas = { scale : 1, // should that be there ? or in its own effect ? opacity : 1, // should that be there ? or in its own effect ? rotation : 0*Math.PI }; }).onRender(function(particle){ var position = particle.position.vector; var data = particle.renderToCanvas; var canonAge = particle.lifeTime.normalizedAge(); var imageIdx = Math.floor(canonAge * images.length); var image = images[imageIdx]; // save the context ctx.save(); // translate in canvas's center, and the particle position ctx.translate(position.x + canvas.width/2, position.y + canvas.height/2); // set the scale of this particles ctx.scale(data.scale, data.scale); // set the rotation ctx.rotate(data.rotation); // set ctx.globalAlpha ctx.globalAlpha = data.opacity; // draw the image itself if( image instanceof Image ){ ctx.drawImage(image, -image.width/2, -image.height/2); }else if( typeof(image) === 'object' ){ ctx.drawImage(image.image , image.offsetX, image.offsetY , image.width, image.height , -image.width/2, -image.height/2, image.width, image.height); }else console.assert(false); // restore the context ctx.restore(); }); }; };
function Marker(poiData, orderNumber) { /* マーカー(=ポップアップするバルーンUI)を作成するには、 ジオロケーション(=地球上の三次元空間座標)に結び付けられた新しいAR.GeoObjectオブジェクト(=ロケーションベースのARオブジェクト)を作成します。 このAR.GeoObjectは、必ず1つ以上のAR.GeoLocation(=ロケーション)と、複数の関連付けられたAR.Drawable(=描画物)が必要です。 AR.Drawablesは、カメラ(cam)や、レーダー(radar)、方向インジケーター(indicator)といったターゲットに対して定義できます。 */ this.poiData = poiData; // POIデータ(緯度=latitude、経度=longitude、高度=altitude)からマーカーロケーション(=AR.GeoLocationオブジェクト)を作成します。 var markerLocation = new AR.GeoLocation(poiData.latitude, poiData.longitude, poiData.altitude); // アイドル状態時のイメージリソースと、高さ(2.5)、各種オプションを指定して、マーカー用のAR.ImageDrawable(=画像の描画物)を作成します。 this.markerDrawable_idle = new AR.ImageDrawable(World.markerDrawable_idle, 2.5, { zOrder: 0, opacity: 1.0, /* ユーザーの操作を受け付けるには、それぞれのAR.DrawableでonClickプロパティに関数をセットしてください。 この関数は、ユーザーが描画物をタップするたびに呼ばれます。この例では、本ファイル内に定義された下記のヘルパー関数を指定しています。 クリックされたマーカーは、引数としてこの関数に渡されています。 */ onClick: Marker.prototype.getOnClickTrigger(this) // オプションは数が多いので割愛。こちらを参照: http://docs.grapecity.com/help/wikitude/wikitude-sdk-js-api-reference/classes/ImageDrawable.html }); // 選択状態のマーカー用のAR.ImageDrawableを作成します。 this.markerDrawable_selected = new AR.ImageDrawable(World.markerDrawable_selected, 2.5, { zOrder: 0, opacity: 0.0, onClick: null }); // マーカーの距離表示用のAR.Label(=ラベルの描画物)を作成します。 this.distanceLabel = new AR.Label(poiData.distance.trunc(10), 1, { zOrder: 1, offsetY: 0.55, style: { textColor: '#FFFFFF', fontStyle: AR.CONST.FONT_STYLE.BOLD } // オプションは数が多いので割愛。こちらを参照: http://docs.grapecity.com/help/wikitude/wikitude-sdk-js-api-reference/classes/Label.html }); // マーカーのレストラン名表示用のAR.Labelを作成します。 this.nameLabel = new AR.Label(poiData.name.trunc(15), 0.8, { zOrder: 1, offsetY: -0.55, style: { textColor: '#FFFFFF' } }); // 1つ以上のマーカーロケーションと、複数の描画物を指定して、AR.GeoObjectを作成します。 this.markerObject = new AR.GeoObject(markerLocation, { drawables: { cam: [this.markerDrawable_idle, this.markerDrawable_selected, this.distanceLabel, this.nameLabel] }, renderingOrder: (orderNumber) /* ここではdrawables/renderingOrderオプションを指定していますが、指定可能なオプションは以下のとおりです。 ・enabled: Boolean型(デフォルト値: true)。有効/無効を指定します。 ・renderingOrder: Number型(デフォルト値: 0) 。描画順序を指定します。 ・onEnterFieldOfVision:AR.GeoObjectが表示開始された時の処理を実施する関数を指定します。 ・onExitFieldOfVision: AR.GeoObjectが表示終了する時の処理を実施する関数を指定します。 ・onClick: ユーザークリックを処理する関数を指定します。 ・drawables.cam: Drawable[]型。カメラビュー内の描画物を指定します。 ・drawables.radar: Drawable2D[]型。レーダー内の描画物を指定します。 ・drawables.indicator: Drawable2D[]型。方向インジケーター内の描画物を指定します。 */ }); return this; } Marker.prototype.getOnClickTrigger = function(marker) { /* この関数内では、描画物の選択状態を判定して、選択状態を設定し直し、適切な処理が実行されます。 */ return function() { if (marker.isSelected) { Marker.prototype.setDeselected(marker); } else { Marker.prototype.setSelected(marker); try { World.onMarkerSelected(marker); } catch (err) { alert(err); } } return true; }; }; var renderringOrderLevel = 1000; // レンダリング順序の番号はこの数値を基準に指定します。タップされた場合は、この数値を抜くことで最上位にします。 Marker.prototype.setSelected = function(marker) { marker.isSelected = true; if (marker.markerObject.renderingOrder < renderringOrderLevel) { marker.markerObject.renderingOrder = marker.markerObject.renderingOrder + renderringOrderLevel; // 選択されたものを最上位に表示します。 } marker.markerDrawable_idle.opacity = 0.0; marker.markerDrawable_selected.opacity = 1.0; marker.markerDrawable_idle.onClick = null; marker.markerDrawable_selected.onClick = Marker.prototype.getOnClickTrigger(marker); }; Marker.prototype.setDeselected = function(marker) { marker.isSelected = false; if (marker.markerObject.renderingOrder > renderringOrderLevel) { marker.markerObject.renderingOrder = marker.markerObject.renderingOrder - renderringOrderLevel; // 選択解除されたものを元の位置に表示します。 } marker.markerDrawable_idle.opacity = 1.0; marker.markerDrawable_selected.opacity = 0.0; marker.markerDrawable_idle.onClick = Marker.prototype.getOnClickTrigger(marker); marker.markerDrawable_selected.onClick = null; }; // Stringクラスに長すぎる文字列を短く省略するための関数を追加定義します。 String.prototype.trunc = function(n) { return this.substr(0, n - 1) + (this.length > n ? '...' : ''); };
define(["exports", "aurelia-route-recognizer", "aurelia-path", "./navigation-context", "./navigation-instruction", "./router-configuration", "./util"], function (exports, _aureliaRouteRecognizer, _aureliaPath, _navigationContext, _navigationInstruction, _routerConfiguration, _util) { "use strict"; var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); }; var RouteRecognizer = _aureliaRouteRecognizer.RouteRecognizer; var join = _aureliaPath.join; var NavigationContext = _navigationContext.NavigationContext; var NavigationInstruction = _navigationInstruction.NavigationInstruction; var RouterConfiguration = _routerConfiguration.RouterConfiguration; var processPotential = _util.processPotential; var Router = exports.Router = (function () { function Router(container, history) { this.container = container; this.history = history; this.viewPorts = {}; this.reset(); this.baseUrl = ""; } _prototypeProperties(Router, null, { registerViewPort: { value: function registerViewPort(viewPort, name) { name = name || "default"; this.viewPorts[name] = viewPort; }, writable: true, configurable: true }, refreshBaseUrl: { value: function refreshBaseUrl() { if (this.parent) { var baseUrl = this.parent.currentInstruction.getBaseUrl(); this.baseUrl = this.parent.baseUrl + baseUrl; } }, writable: true, configurable: true }, refreshNavigation: { value: function refreshNavigation() { var nav = this.navigation; for (var i = 0, length = nav.length; i < length; i++) { var current = nav[i]; if (!this.history._hasPushState) { if (this.baseUrl[0] == "/") { current.href = "#" + this.baseUrl; } else { current.href = "#/" + this.baseUrl; } } else { current.href = "/" + this.baseUrl; } if (current.href[current.href.length - 1] != "/") { current.href += "/"; } current.href += current.relativeHref; } }, writable: true, configurable: true }, configure: { value: function configure(callbackOrConfig) { if (typeof callbackOrConfig == "function") { var config = new RouterConfiguration(); callbackOrConfig(config); config.exportToRouter(this); } else { callbackOrConfig.exportToRouter(this); } return this; }, writable: true, configurable: true }, navigate: { value: function navigate(fragment, options) { fragment = join(this.baseUrl, fragment); return this.history.navigate(fragment, options); }, writable: true, configurable: true }, navigateBack: { value: function navigateBack() { this.history.navigateBack(); }, writable: true, configurable: true }, createChild: { value: function createChild(container) { var childRouter = new Router(container || this.container.createChild(), this.history); childRouter.parent = this; return childRouter; }, writable: true, configurable: true }, createNavigationInstruction: { value: function createNavigationInstruction() { var url = arguments[0] === undefined ? "" : arguments[0]; var parentInstruction = arguments[1] === undefined ? null : arguments[1]; var results = this.recognizer.recognize(url); var fragment, queryIndex, queryString; if (!results || !results.length) { results = this.childRecognizer.recognize(url); } fragment = url; queryIndex = fragment.indexOf("?"); if (queryIndex != -1) { fragment = url.substr(0, queryIndex); queryString = url.substr(queryIndex + 1); } if ((!results || !results.length) && this.catchAllHandler) { results = [{ config: { navModel: {} }, handler: this.catchAllHandler, params: { path: fragment } }]; } if (results && results.length) { var first = results[0], fragment = url, queryIndex = fragment.indexOf("?"), queryString; if (queryIndex != -1) { fragment = url.substr(0, queryIndex); queryString = url.substr(queryIndex + 1); } var instruction = new NavigationInstruction(fragment, queryString, first.params, first.queryParams || results.queryParams, first.config || first.handler, parentInstruction); if (typeof first.handler == "function") { return first.handler(instruction).then(function (instruction) { if (!("viewPorts" in instruction.config)) { instruction.config.viewPorts = { "default": { moduleId: instruction.config.moduleId } }; } return instruction; }); } return Promise.resolve(instruction); } else { return Promise.reject(new Error("Route Not Found: " + url)); } }, writable: true, configurable: true }, createNavigationContext: { value: function createNavigationContext(instruction) { return new NavigationContext(this, instruction); }, writable: true, configurable: true }, generate: { value: function generate(name, params) { return this.recognizer.generate(name, params); }, writable: true, configurable: true }, addRoute: { value: function addRoute(config) { var navModel = arguments[1] === undefined ? {} : arguments[1]; if (!("viewPorts" in config)) { config.viewPorts = { "default": { moduleId: config.moduleId, view: config.view } }; } navModel.title = navModel.title || config.title; this.routes.push(config); this.recognizer.add([{ path: config.route, handler: config }]); if (config.route) { var withChild = JSON.parse(JSON.stringify(config)); withChild.route += "/*childRoute"; withChild.hasChildRouter = true; this.childRecognizer.add([{ path: withChild.route, handler: withChild }]); withChild.navModel = navModel; } config.navModel = navModel; if ((config.nav || "order" in navModel) && this.navigation.indexOf(navModel) === -1) { navModel.order = navModel.order || config.nav; navModel.href = navModel.href || config.href; navModel.isActive = false; navModel.config = config; if (!config.href) { navModel.relativeHref = config.route; navModel.href = ""; } if (typeof navModel.order != "number") { navModel.order = ++this.fallbackOrder; } this.navigation.push(navModel); this.navigation = this.navigation.sort(function (a, b) { return a.order - b.order; }); } }, writable: true, configurable: true }, handleUnknownRoutes: { value: function handleUnknownRoutes(config) { var callback = function (instruction) { return new Promise(function (resolve, reject) { function done(inst) { inst = inst || instruction; inst.config.route = inst.params.path; resolve(inst); } if (!config) { instruction.config.moduleId = instruction.fragment; done(instruction); } else if (typeof config == "string") { instruction.config.moduleId = config; done(instruction); } else if (typeof config == "function") { processPotential(config(instruction), done, reject); } else { instruction.config = config; done(instruction); } }); }; this.catchAllHandler = callback; }, writable: true, configurable: true }, reset: { value: function reset() { this.fallbackOrder = 100; this.recognizer = new RouteRecognizer(); this.childRecognizer = new RouteRecognizer(); this.routes = []; this.isNavigating = false; this.navigation = []; }, writable: true, configurable: true } }); return Router; })(); exports.__esModule = true; });
/// <reference path="../../_all.ts" /> 'use strict'; var app; (function (app) { angular.module('blocks.interceptor', []); })(app || (app = {})); //# sourceMappingURL=interceptor.module.js.map
import mongoose, { Schema } from 'mongoose'; import timestamps from 'mongoose-timestamp'; const postSchema = new Schema({ author: { type: { type: Schema.Types.ObjectId, ref: 'users', }, }, // not sure how to best store this here. Maybe as a buffer? content: String, list: { type: Schema.Types.ObjectId, ref: 'lists', }, links: [{ title: String, link: String, description: String, post: { type: Schema.Types.ObjectId, ref: 'posts', }, }], }); postSchema.methods = {}; postSchema.plugin(timestamps); export default mongoose.model('posts', postSchema);
export default class ClientFloat32Array extends Float32Array { update ( ) { this.buffer.update( this ); return this; } setValues ( ) { this.set.call( this, arguments ); return this; } }