code
stringlengths
2
1.05M
export default { 'Acorn': ` ■ ■ ■ ■ ■ ■ ■ `, 'Block': ` ■ ■ ■ ■ `, 'Glider': ` ■ ■ ■ ■ ■ `, 'Gosper glider gun': ` ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ `, 'Switch engine': ` ■ ■ ■ ■ ■ ■ ■ ■ ` }
import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); import { Loading } from 'element-ui'; import Cookies from 'js-cookie'; const config = require('../../config'); const {themeArray} = require('./themeArray'); //封装一些全局元素。如全站通用功能函数和http请求等 export const global = { // 测试环境 // baseUrl:"http://120.76.119.16:8888/jojosns/", // baseImgUrl:"http://120.76.119.16:8888/jojosns/", // 开发环境 baseUrl: "http://27.61.80.50:8080/jojosns/", baseImgUrl: "http://27.61.80.50:8080/jojosns/", //图片服务器,若没有单独服务,可忽略此项 staticPath: process.env.NODE_ENV !== 'development' ? config.build.staticPath: config.dev.staticPath,//静态资源路径 /** * 切换主题函数 */ changeTheme:function(themeValue){ var that = this; // console.log('切换主题颜色值:',themeValue,that.staticPath,JSON.stringify(themeArray) ); //需要移到单独的文件存放 var cssArray = themeArray; for (let i = 0 ,len = cssArray.length; i < len; i++) { var itemPath = that.staticPath+'/theme/'+themeValue+'/'+cssArray[i].toLowerCase()+'.css'; loadCss(itemPath) }; localStorage.setItem("themeValue",themeValue) function loadCss(path){ var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.href = path; link.rel = 'stylesheet'; link.type = 'text/css'; head.appendChild(link); } }, /** * 全局ID计数器,保证返回的是一个全局的id标识(数字) */ globalId: function () { return window._idCounter_ ? window._idCounter_ += 1 : window._idCounter_ = 1; }, /** * 统一接口处理:get请求方法封装。this.$http.get(url, [options]) * @param url { String } -必选 接口url * @param options { Object } -必选 含官方的所有options对象。传参为{params:{key:11}} * @param sucCb { Function } -必选 成功回调 * @param errorCb { Function } -可选 失败回调 * @param isLoading { Boolean } -可选 是否显示加载状态 * @param isLogin { Boolean } -可选 是否登陆信息(移动端使用得较多,设置头部信息) */ get:function( url,options = {},sucCb,errorCb,isLoading = true,isLogin ){ if(!url){ console.log('接口url不能为空!'); return false ; } //lss 2017-6-28 补默认laoding状态 // var isLoading = isLoading===undefined ||(isLoading!==undefined && isLoading !== false )? true : false; //遮罩层 if(isLoading){ var loadingInstance = Loading.service({text:"拼命加载中"}); } Vue.http.get(url, options).then((response) => { // 响应成功回调 //console.log('成功回调') setTimeout(function(){ sucCb(response); if(isLoading){ loadingInstance.close(); } },1000) }, (response) => { // 响应错误回调 //console.log('失败回调') errorCb(response); if(isLoading){ loadingInstance.close(); } }) }, /** * 统一接口处理:post请求方法封装。this.$http.get(url, [options]) * @param url { String } -必选 接口url * @param body { Object } -必选 含官方的所有body对象,可为null。传参时不需要参数名,例如body为{key:11} * @param options { Object } -必选 含官方的所有options对象,可为null。传参为{params:{key:11}} * @param sucCb { Function } -必选 成功回调 * @param errorCb { Function } -可选 失败回调 * @param isLoading { Boolean } -可选 是否显示加载状态 * @param isLogin { Boolean } -可选 是否登陆信息(移动端使用得较多,设置头部信息) */ post:function( url,body,options,sucCb,errorCb,isLoading = true,isLogin ){ if(!url){ console.log('接口url不能为空!'); return false ; } //lss 2017-6-28 补默认laoding状态 // var isLoading = isLoading===undefined ||(isLoading!==undefined && isLoading !== false )? true : false; //遮罩层 if(isLoading){ var loadingInstance = Loading.service(); } Vue.http.post(url,body,options).then((response) => { // 响应成功回调 //console.log('成功回调') sucCb(response); if(isLoading){ loadingInstance.close(); } }, (response) => { // 响应错误回调 //console.log('失败回调') errorCb(response); if(isLoading){ loadingInstance.close(); } }) }, /** * author lss * 日期格式化,传入为毫秒数,转出时间格式为 :2016-6-6 12:00:00 * @objD 必填,格式为毫秒数 */ formatDate: function (objD) { if (!objD) { return ''; } objD = new Date(objD); var str; var yy = objD.getYear(); if (yy < 1900) yy = yy + 1900; var MM = objD.getMonth() + 1; if (MM < 10) MM = '0' + MM; var dd = objD.getDate(); if (dd < 10) dd = '0' + dd; var hh = objD.getHours(); if (hh < 10) hh = '0' + hh; var mm = objD.getMinutes(); if (mm < 10) mm = '0' + mm; var ss = objD.getSeconds(); if (ss < 10) ss = '0' + ss; str = yy + "-" + MM + "-" + dd + " " + hh + ":" + mm + ":" + ss; return (str); }, /** * author lss * 日期格式化,传入为毫秒数,转出时间格式为 :2016-6-6 * @objD 必填,格式为毫秒数 */ formatDate2: function (objD) { if (!objD) { return ''; } objD = new Date(objD); var str; var yy = objD.getYear(); if (yy < 1900) yy = yy + 1900; var MM = objD.getMonth() + 1; //if(MM<10) MM = '0' + MM; var dd = objD.getDate(); //if(dd<10) dd = '0' + dd; //去掉0 我的圈子 加入圈子,布局放不下。。 str = yy + "-" + MM + "-" + dd; return (str); }, /** * 移动端弹窗,样式文件已写在配置依赖里 * 使用方法 请参照 http:// * @param * @param */ popupMobile: { // 默认弹窗参数 defaultOpt: { title: '弹框标题', content: '告知当前状态,信息和解决方法' , btn: ['确定'] , yes: function (index) { } } // 关闭所有弹窗 , close: function () { layer.closeAll(); } // 普通信息弹窗 , msg: function (content,time) { var t = this; t.close(); layer.open({ content: content , skin: 'msg' // footer(即底部对话框风格)、msg(普通提示) , time: 2 || time//2秒后自动关闭 }); } // 加载中弹窗 , loading: function (txt) { var t = this; t.close(); layer.open({ type: 2 , content: '加载中' || txt }); } // 普通弹窗 含单标题和双标题 自定义弹框 , dialog: function (opt) { var t = this; t.close(); var newOpt = $.extend(t.defaultOpt, opt); console.log(newOpt) layer.open(newOpt); } // 自定义内容 弹窗 , dialog2: function (opt) { var t = this; t.close(); layer.open(opt); } }, /** * 获取url参数 */ getUrlFn: function () { var querystr = window.location.href.split("?"), // var querystr = "http://xxxx.com/recharge.html?mid=&version=7701&from=music".split("?"), GETs = "", GET = ""; if (querystr[1]) { GETs = querystr[1].split("&"); GET = []; for (i = 0; i < GETs.length; i++) { tmp_arr = GETs[i].split("="); var key = tmp_arr[0]; GET[key] = tmp_arr[1]; } } return GET; // return querystr[1]; }, /** * 获取url data参数。aa.html?data={} */ getUrlData: function () { var purl = window.location.href; purl = purl.substr(purl.indexOf("?") + 1); var urlData = JSON.parse(decodeURI(purl.substr(purl.indexOf("=") + 1))); return urlData; }, }; // export default global
var _; //globals describe("About Applying What We Have Learnt", function() { var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } ]; }); /*********************************************************************************/ it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () { var i,j,hasMushrooms, productsICanEat = []; for (i = 0; i < products.length; i+=1) { if (products[i].containsNuts === false) { hasMushrooms = false; for (j = 0; j < products[i].ingredients.length; j+=1) { if (products[i].ingredients[j] === "mushrooms") { hasMushrooms = true; } } if (!hasMushrooms) productsICanEat.push(products[i]); } } expect(productsICanEat.length).toBe(1); }); it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { var productsICanEat = []; var noNuts = _(products).filter(function(x) { return x.containsNuts == false }); var noNutsOrShrooms = _(noNuts).filter(function(x) { return x.ingredients.indexOf("mushrooms") == -1 }); productsICanEat = noNutsOrShrooms; /* solve using filter() & all() / any() */ expect(productsICanEat.length).toBe(1); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } var range = _.range(1, 1000); var ansArr = _(range).filter(function (x) { return x % 3 === 0 || x % 5 === 0 }); var ans = _(ansArr).reduce(function (sum, x) { return sum + x }); expect(sum).toBe(ans); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var sum = _.range(1,1000).filter(function(x) { return x % 3 === 0 || x % 5 === 0}).reduce(function (sum, x) { return sum + x }); /* try chaining range() and reduce() */ expect(233168).toBe(sum); }); /*********************************************************************************/ it("should count the ingredient occurrence (imperative)", function () { var ingredientCount = { "{ingredient name}": 0 }; for (i = 0; i < products.length; i+=1) { for (j = 0; j < products[i].ingredients.length; j+=1) { ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1; } } expect(ingredientCount['mushrooms']).toBe(2); }); it("should count the ingredient occurrence (functional)", function () { // var ingredientCount = { "{ingredient name}": 0 }; var ingredientCount = _(products).chain() .pluck("ingredients") .flatten() .reduce(function(memo, item) { memo[item] = (memo[item] || 0) + 1; return memo; }, {}) .value(); /* chain() together map(), flatten() and reduce() */ expect(ingredientCount['mushrooms']).toBe(2); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ /* it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should find the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should find the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { }); */ });
/** * Module dependencies */ var program = require('commander'); var messages = require('./messages'); var notify = require('./notify'); program.parse(process.argv); module.exports = function(mssg) { console.log(program.args); notify.debug(mssg); }; /** * Export the whole thing */ // module.exports = { // debug: debug // };
(function () { console.log("Start"); var hub = $.connection.testHub; //hub.client.tell does not work, beware hub.client.answer = function (message, messageId) { console.log("Message received, id: " + messageId); console.log(message); }; $.connection.hub.start().done(function () { console.log("Hup opened"); var path = "/echo"; var msg = { "Message": "Ping" }; var msgType = "SignalRMeetsAkka.Echo"; console.log("Send(" + path + ", " + JSON.stringify(msg) + ", " + msgType); hub.server.send(path, msg, msgType); var uuid = "t45t8u34r8h3u984ur9384r"; console.log("Ask(" + path + ", " + JSON.stringify(msg) + ", " + msgType + ", " + uuid); hub.server.ask(path, msg, msgType, uuid); }); })();
// +---------------------------------------------------------------------- // | CmsWing [ 网站内容管理框架 ] // +---------------------------------------------------------------------- // | Copyright (c) 2015 http://www.cmswing.com All rights reserved. // +---------------------------------------------------------------------- // | Author: arterli <arterli@qq.com> // +---------------------------------------------------------------------- const DEFULT_AUTO_REPLY = '功能正在开发中~'; module.exports = class extends think.Controller { indexAction() { const echostr = this.get('echostr'); return this.body = echostr; } // 关键词消息回复 async textAction() { // console.log(this.http); const message = this.post(); // console.log(message); const key = message.Content.trim(); const kmodel = this.model('wx_keywords'); const isKey = await kmodel.field('rule_id').where({keyword_name: key}).find(); if (!think.isEmpty(isKey)) { // 是关键字 const rulemodel = this.model('wx_keywords_rule'); const replyliststr = await rulemodel.where({id: isKey.rule_id}).getField('reply_id', true); const replylisttmp = replyliststr.split(','); const replylist = []; for (const i in replylisttmp) { if (replylisttmp[i] != '') { replylist.push(replylisttmp[i]); } } if (!think.isEmpty(replylist)) { const randomi = parseInt(Math.random() * replylist.length); const replymodel = this.model('wx_replylist'); const data = await replymodel.where({id: replylist[randomi]}).getField('content', true); return this.success(data); } } // 普通消息回复 const replymodel = this.model('wx_replylist'); const datas = await replymodel.where({reply_type: 2}).order('create_time DESC').select(); const data = datas[0]; let content; switch (data.type) { case 'text': content = data.content; break; case 'news': content = JSON.parse(data.content); break; } return this.success(content); } // 事件关注 async eventAction() { const message = this.post(); switch (message.Event) { case 'subscribe': // 首次关注 const datas = await this.model('wx_replylist').where({reply_type: 1}).order('create_time DESC').select(); const data = datas[0]; let content; switch (data.type) { case 'text': content = data.content; break; case 'news': content = JSON.parse(data.content); break; } this.success(content); break; case 'unsubscribe':// 取消关注 // todo break; case 'CLICK':// click事件坚挺 const res = await this.model('wx_material').find(message.EventKey); const news_item = JSON.parse(res.material_wx_content); const list = news_item.news_item; for (const v of list) { v.picurl = v.thumb_url; } this.success(list); // todo break; case 'SCAN':// 扫码事件监听 // todo console.log(message); break; default: console.log(message); break; } // this.reply(JSON.stringify(message)); } __call() { return this.success(DEFULT_AUTO_REPLY); } };
var gulp = require('gulp'); gulp.task('phpmd', function(callback) { var spawn = require('child_process').spawn; spawn( 'phpmd', [ 'src', 'text', 'app/Resources/phpmd.xml' ], {stdio: 'inherit'} ).on('close', function(code, signal) { callback(); }); });
let fileInfoOptions = { name: 'file.info', filename: 'out.log', colorize: true, level : 'info', levels : {debug: 0, info : 1, warn: 2, error: 3}, colors : {debug: 'blue', info : 'green', warn: 'orange', error: 'red'}, json: true, handleExeptions: true, humanReadableUnhandledException: true, }; let fileErrorOptions = { name: 'file.error', filename: 'err.log', colorize: true, level : 'error', levels : {debug: 0, info : 1, warn: 2, error: 3}, colors : {debug: 'blue', info : 'green', warn: 'orange', error: 'red'}, json: true, handleExeptions: true, humanReadableUnhandledException: true, }; // Share the same transport(=File) between 2 different files... // one for debug & the other file for errors only. logger.addTransport('file', fileInfoOptions); logger.addTransport('file', fileErrorOptions); let consoleOptions = { colorize: true, level : 'info', }; logger.addTransport('console', consoleOptions); let papertrailOptions = { host: 'logs5.papertrailapp.com', // Replace with your papertrail app URL port: 44279, // Replace with your papertrail app's port number logFormat: function(level, message) { return '[' + level + '] ' + message; }, inlineMeta: true, json: true, colorize: true, handleExeptions: true }; // Simply add the papertrail transport logger.addTransport('papertrail', papertrailOptions);
define(['angular', './card.controller', './card.service', 'requestApi'], function (angular, cardsCtrl, CardDataService) { 'use strict'; angular.module('boardGame.card', ['boardGame.requestApi']) .service('CardDataService', CardDataService) .controller('cardsCtrl', cardsCtrl); });
const Koa = require('koa') const app = new Koa() const views = require('koa-views') const json = require('koa-json') const onerror = require('koa-onerror') const bodyparser = require('koa-bodyparser') const logger = require('koa-logger') const index = require('./routes/index') const users = require('./routes/users') const config = require('./config.js') // api代理 const proxy = require('koa-proxies') const httpsProxyAgent = require('https-proxy-agent') app.use(proxy('/api', { target: 'http://172.16.8.197:8081', changeOrigin: true, logs: true, rewrite: path => path.replace(/^\/api/g, '') // agent: new httpsProxyAgent('http://172.16.8.197:8081'), // rewrite: path => path.replace(/^\/api(\/|\/\w+)?$/, '') })) // 链接数据库 const db = require('mysql'); // var connection = db.createConnection({ // host: '172.16.8.191:3306', // // host: '172.16.8.191:3306/pudong', // user: 'root', // password: 'ipudong', // database: 'ceshi' // }) var connection = db.createConnection(config.mysql) connection.connect(function(err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); global.connection = connection; global.sf = require('./boot.js'); // error handler onerror(app) // middlewares app.use(bodyparser({ enableTypes:['json', 'form', 'text'] })) app.use(json()) app.use(logger()) // 使用端路由渲染页面 // app.use(require('koa-static')(__dirname + '/public')) // app.use(views(__dirname + '/views', { // extension: 'pug' // })) // 使用前端路由分离渲染页面 // app.use(require('koa-static')(__dirname + '/dist')) // app.use(views(__dirname + '/dist')) // 使用前端路由,前后端,node端做后端,代理访问其他数据员后台api app.use(require('koa-static')(__dirname + '/fronts')) app.use(views(__dirname + '/fronts')) // logger app.use(async (ctx, next) => { const start = new Date() await next() const ms = new Date() - start console.log(`${ctx.method} ${ctx.url} - ${ms}ms`) }) // routes app.use(index.routes(), index.allowedMethods()) app.use(users.routes(), users.allowedMethods()) module.exports = app
Ext.BLANK_IMAGE_URL = '/vendor/ext/3.4.1/resources/images/default/s.gif'; Ext.override(Ext.form.ComboBox, { doQuery : function(q, forceAll){ if(q === undefined || q === null){ q = ''; } var qe = { query: q, forceAll: forceAll, combo: this, cancel:false }; if(this.fireEvent('beforequery', qe)===false || qe.cancel){ return false; } q = qe.query; forceAll = qe.forceAll; if(forceAll === true || (q.length >= this.minChars)){ if(this.lastQuery !== q){ this.lastQuery = q; if(this.mode == 'local'){ this.selectedIndex = -1; if(forceAll){ this.store.clearFilter(); }else{ this.store.filter(this.displayField, q, true); } this.onLoad(); }else{ this.store.baseParams[this.queryParam] = q; this.store.load({ params: this.getParams(q) }); this.expand(); } }else{ this.selectedIndex = -1; this.onLoad(); } } } }); Ext.onReady(function(){ var states = [ ["AL","Alabama"], ["AK","Alaska"], ["AZ","Arizona"], ["AR","Arkansas"], ["CA","California"], ["CO","Colorado"], ["CT","Connecticut"], ["DE","Delaware"], ["FL","Florida"], ["GA","Georgia"], ["HI","Hawaii"], ["ID","Idaho"], ["IL","Illinois"], ["IN","Indiana"], ["IA","Iowa"], ["KS","Kansas"], ["KY","Kentucky"], ["LA","Louisiana"], ["ME","Maine"], ["MD","Maryland"], ["MA","Massachusetts"], ["MI","Michigan"], ["MN","Minnesota"], ["MS","Mississippi"], ["MO","Missouri"], ["MT","Montana"], ["NE","Nebraska"], ["NV","Nevada"], ["NH","New Hampshire"], ["NJ","New Jersey"], ["NM","New Mexico"], ["NY","New York"], ["NC","North Carolina"], ["ND","North Dakota"], ["OH","Ohio"], ["OK","Oklahoma"], ["OR","Oregon"], ["PA","Pennsylvania"], ["RI","Rhode Island"], ["SC","South Carolina"], ["SD","South Dakota"], ["TN","Tennessee"], ["TX","Texas"], ["UT","Utah"], ["VT","Vermont"], ["VA","Virginia"], ["WA","Washington"], ["WV","West Virginia"], ["WI","Wisconsin"], ["WY","Wyoming"] ]; var varStore = new Ext.data.Store({ autoLoad : false, proxy : new Ext.data.HttpProxy({ url : '/json/dcp_vars.php' }), reader: new Ext.data.JsonReader({ root: 'vars', id: 'id' }, [ {name: 'id', mapping: 'id'} ]), listeners: { load: function(st, records){ if (records.length == 0){ Ext.get('msg').update('Sorry, did not find any variables for this site!'); } else{ Ext.get('msg').update(''); } } } }); var varCB = new Ext.form.ComboBox({ store : varStore, displayField : 'id', valueField : 'id', width : 100, mode : 'local', fieldLabel : 'Variable', emptyText : 'Select Variable...', tpl : new Ext.XTemplate( '<tpl for="."><div class="search-item">', '<span>[{id}]</span>', '</div></tpl>' ), typeAhead : false, itemSelector : 'div.search-item', hideTrigger : false }); var stationStore = new Ext.data.Store({ autoLoad : false, proxy : new Ext.data.HttpProxy({ url : '/json/network.php' }), baseParams : {'network': 'IA_DCP'}, reader: new Ext.data.JsonReader({ root: 'stations', id: 'id' }, [ {name: 'id', mapping: 'id'}, {name: 'name', mapping: 'name'}, {name: 'combo', mapping: 'combo'} ]) }); var stateCB = new Ext.form.ComboBox({ hiddenName : 'state', store : new Ext.data.SimpleStore({ fields: ['abbr', 'name'], data : states }), valueField : 'abbr', width : 180, fieldLabel : 'Select State', displayField: 'name', typeAhead : true, tpl : '<tpl for="."><div class="x-combo-list-item">[{abbr}] {name}</div></tpl>', mode : 'local', triggerAction: 'all', emptyText :'Select/or type here...', selectOnFocus:true, lazyRender : true, id : 'stateselector', listeners : { select: function(cb, record, idx){ stationStore.load({add: false, params: {network: record.data.abbr +"_DCP"}}); return false; } } }); var stationCB = new Ext.form.ComboBox({ store : stationStore, displayField : 'combo', valueField : 'id', width : 300, mode : 'local', triggerAction : 'all', fieldLabel : 'Station', emptyText : 'Select Station...', tpl : new Ext.XTemplate( '<tpl for="."><div class="search-item">', '<span>[{id}] {name}</span>', '</div></tpl>' ), typeAhead : false, itemSelector : 'div.search-item', hideTrigger : false, listeners : { select: function(cb, record, idx){ varStore.load({add: false, params: {station: record.id}}); return false; } } }); var datepicker = new Ext.form.DateField({ minValue : new Date('1/1/2002'), maxValue : new Date(), fieldLabel : 'Start Date', emptyText : "Select Date", allowBlank : false }); var dayInterval = new Ext.form.NumberField({ minValue : 1, maxValue : 31, value : 5, width : 30, fieldLabel : 'Number of Days' }); function updateImage(){ var ds = datepicker.getValue(); var ds2 = ds.add(Date.DAY, dayInterval.getValue()); var url = String.format('plot.php?station={0}&sday={1}&eday={2}&var={3}', stationCB.getValue(), ds.format('Y-m-d'), ds2.format('Y-m-d'), varCB.getValue()); Ext.get("imagedisplay").dom.src = url; /* Now adjust the URL */ var uri = String.format('#{0}.{1}.{2}.{3}.{4}', stateCB.getValue(), stationCB.getValue(), varCB.getValue(), ds.format('Y-m-d'), dayInterval.getValue() ); window.location.href = uri; } new Ext.form.FormPanel({ applyTo : 'myform', labelAlign : 'top', width : 320, style : 'padding-left: 5px;', title : 'Make Plot Selections Below...', items : [stateCB, stationCB, varCB, datepicker, dayInterval], buttons : [{ text : 'Create Graph', handler : function(){ updateImage(); } }] }); /* Check to see if we had something specified on the URL! */ var tokens = window.location.href.split('#'); if (tokens.length == 2){ var tokens2 = tokens[1].split('.'); if (tokens2.length == 5){ stateCB.setValue( tokens2[0] ); stationCB.setValue( tokens2[1] ); varCB.setValue( tokens2[2] ); datepicker.setValue( tokens2[3] ); dayInterval.setValue( tokens2[4] ); updateImage(); } } });
//= require spec_helper //= require models/dot //= require collections/dots //= require templates/dot_view //= require views/dot_view //= require views/dots_view describe('DotsView', function() { var subject, dot; beforeEach(function() { dots = new Dots(); dots.add([{ id: 1, name: 'Breakfast', priority: 3 }, { id: 2, name: 'Lunch', priority: 2 }, { id: 3, name: 'Dinner', priority: 1 }]); subject = new DotsView({ collection: dots }); SANDBOX.append(subject.render().el); }); describe("when an item is prioritized", function() { it("re-renders with the prioritized item at the top", function() { subject.$('.dot-prioritize[data-dot-id=' + dots.at(2).id + ']').trigger('click'); expect(subject.children.findByIndex(0).$el.hasClass('js-top')).to.be.true; }); }); });
import React from 'react' import Button from './Button' import { removeToken } from '../storages/SessionStorage' export default (props) => { const handleLogInClick = () => { chrome.runtime.sendMessage({ action: 'vk_notification_auth' }, (response) => { if (response.content == 'OK') { if (props.afterLogInClick) { props.afterLogInClick() } } }) } const handleLogOutClick = async () => { try { await removeToken() if (props.afterLogOutClick) { props.afterLogOutClick() } } catch (e) { /* handle error */ console.log(e); } } let button if (props.accessToken) { button = <Button onClick={ handleLogOutClick }>Выйти</Button> } else { button = <Button onClick={ handleLogInClick }>Войти</Button> } return props.hidden ? null : button }
const path = require('path'); const should = require('should'); const supertest = require('supertest'); const sinon = require('sinon'); const testUtils = require('../../../../utils'); const localUtils = require('../../../../acceptance/old/admin/utils'); const config = require('../../../../../server/config'); const labs = require('../../../../../server/services/labs'); const ghost = testUtils.startGhost; let request; describe('Subscribers API', function () { before(function () { sinon.stub(labs, 'isSet').withArgs('subscribers').returns(true); }); after(function () { sinon.restore(); }); before(function () { return ghost() .then(function () { request = supertest.agent(config.get('url')); }) .then(function () { return localUtils.doAuth(request, 'subscriber'); }); }); it('Can browse', function () { return request .get(localUtils.API.getApiQuery('subscribers/')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .then((res) => { should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.subscribers); jsonResponse.subscribers.should.have.length(1); localUtils.API.checkResponse(jsonResponse.subscribers[0], 'subscriber'); testUtils.API.isISO8601(jsonResponse.subscribers[0].created_at).should.be.true(); jsonResponse.subscribers[0].created_at.should.be.an.instanceof(String); jsonResponse.meta.pagination.should.have.property('page', 1); jsonResponse.meta.pagination.should.have.property('limit', 15); jsonResponse.meta.pagination.should.have.property('pages', 1); jsonResponse.meta.pagination.should.have.property('total', 1); jsonResponse.meta.pagination.should.have.property('next', null); jsonResponse.meta.pagination.should.have.property('prev', null); }); }); it('Can read', function () { return request .get(localUtils.API.getApiQuery(`subscribers/${testUtils.DataGenerator.Content.subscribers[0].id}/`)) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .then((res) => { should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.subscribers); jsonResponse.subscribers.should.have.length(1); localUtils.API.checkResponse(jsonResponse.subscribers[0], 'subscriber'); }); }); it('Can add', function () { const subscriber = { name: 'test', email: 'subscriberTestAdd@test.com' }; return request .post(localUtils.API.getApiQuery(`subscribers/`)) .send({subscribers: [subscriber]}) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(201) .then((res) => { should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.subscribers); jsonResponse.subscribers.should.have.length(1); // localUtils.API.checkResponse(jsonResponse.subscribers[0], 'subscriber'); // TODO: modify checked schema jsonResponse.subscribers[0].name.should.equal(subscriber.name); jsonResponse.subscribers[0].email.should.equal(subscriber.email); }); }); it('Can edit by id', function () { const subscriberToChange = { name: 'changed', email: 'subscriber1Changed@test.com' }; const subscriberChanged = { name: 'changed', email: 'subscriber1Changed@test.com' }; return request .post(localUtils.API.getApiQuery(`subscribers/`)) .send({subscribers: [subscriberToChange]}) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(201) .then((res) => { should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.subscribers); jsonResponse.subscribers.should.have.length(1); return jsonResponse.subscribers[0]; }) .then((newSubscriber) => { return request .put(localUtils.API.getApiQuery(`subscribers/${newSubscriber.id}/`)) .send({subscribers:[subscriberChanged]}) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .then((res) => { should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.subscribers); jsonResponse.subscribers.should.have.length(1); localUtils.API.checkResponse(jsonResponse.subscribers[0], 'subscriber'); jsonResponse.subscribers[0].name.should.equal(subscriberChanged.name); jsonResponse.subscribers[0].email.should.equal(subscriberChanged.email); }); }); }); it('Can destroy', function () { const subscriber = { name: 'test', email: 'subscriberTestDestroy@test.com' }; return request .post(localUtils.API.getApiQuery(`subscribers/`)) .send({subscribers: [subscriber]}) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(201) .then((res) => { should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.subscribers); return jsonResponse.subscribers[0]; }) .then((newSubscriber) => { return request .delete(localUtils.API.getApiQuery(`subscribers/${newSubscriber.id}`)) .set('Origin', config.get('url')) .expect('Cache-Control', testUtils.cacheRules.private) .expect(204) .then(() => newSubscriber); }) .then((newSubscriber) => { return request .get(localUtils.API.getApiQuery(`subscribers/${newSubscriber.id}/`)) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(404); }); }); it('Can export CSV', function () { return request .get(localUtils.API.getApiQuery(`subscribers/csv/`)) .set('Origin', config.get('url')) .expect('Content-Type', /text\/csv/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .then((res) => { should.not.exist(res.headers['x-cache-invalidate']); res.headers['content-disposition'].should.match(/Attachment;\sfilename="subscribers/); res.text.should.match(/id,email,created_at,deleted_at/); res.text.should.match(/subscriber1@test.com/); }); }); it('Can import CSV', function () { return request .post(localUtils.API.getApiQuery(`subscribers/csv/`)) .attach('subscribersfile', path.join(__dirname, '/../../../../utils/fixtures/csv/single-column-with-header.csv')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(201) .then((res) => { should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.meta); should.exist(jsonResponse.meta.stats); jsonResponse.meta.stats.imported.should.equal(2); jsonResponse.meta.stats.duplicates.should.equal(0); jsonResponse.meta.stats.invalid.should.equal(0); }); }); });
/** * Services for connecting to Player's real-time API * @module realtime */
'use strict'; var util = require('util'), Store = require('../base'), _ = require('lodash'), debug = require('debug')('saga:redis'), uuid = require('node-uuid').v4, ConcurrencyError = require('../../errors/concurrencyError'), jsondate = require('jsondate'), async = require('async'), redis = require('redis'); function Redis(options) { Store.call(this, options); var defaults = { host: 'localhost', port: 6379, prefix: 'saga', max_attempts: 1 }; _.defaults(options, defaults); if (options.url) { var url = require('url').parse(options.url); if (url.protocol === 'redis:') { if (url.auth) { var userparts = url.auth.split(":"); options.user = userparts[0]; if (userparts.length === 2) { options.password = userparts[1]; } } options.host = url.hostname; options.port = url.port; if (url.pathname) { options.db = url.pathname.replace("/", "", 1); } } } this.options = options; } util.inherits(Redis, Store); _.extend(Redis.prototype, { connect: function (callback) { var self = this; var options = this.options; this.client = new redis.createClient(options.port || options.socket, options.host, options); this.prefix = options.prefix; var calledBack = false; if (options.password) { this.client.auth(options.password, function(err) { if (err && !calledBack && callback) { calledBack = true; if (callback) callback(err, self); return; } if (err) throw err; }); } if (options.db) { this.client.select(options.db); } this.client.on('end', function () { self.disconnect(); }); this.client.on('error', function (err) { console.log(err); if (calledBack) return; calledBack = true; if (callback) callback(null, self); }); this.client.on('connect', function () { if (options.db) { self.client.send_anyways = true; self.client.select(options.db); self.client.send_anyways = false; } self.emit('connect'); if (calledBack) return; calledBack = true; if (callback) callback(null, self); }); }, disconnect: function (callback) { if (this.client) { this.client.end(); } this.emit('disconnect'); if (callback) callback(null, this); }, getNewId: function(callback) { this.client.incr('nextItemId:' + this.prefix, function(err, id) { if (err) { return callback(err); } callback(null, id.toString()); }); }, save: function (saga, cmds, callback) { if (!saga || !_.isObject(saga) || !_.isString(saga.id) || !_.isDate(saga._commitStamp)) { var err = new Error('Please pass a valid saga!'); debug(err); return callback(err); } if (!cmds || !_.isArray(cmds)) { var err = new Error('Please pass a valid saga!'); debug(err); return callback(err); } if (cmds.length > 0) { for (var c in cmds) { var cmd = cmds[c]; if (!cmd.id || !_.isString(cmd.id) || !cmd.payload) { var err = new Error('Please pass a valid commands array!'); debug(err); return callback(err); } } } var self = this; var sagaKey; if (saga._timeoutAt) { sagaKey = this.options.prefix + '_saga' + ':' + saga._commitStamp.getTime() + ':' + saga._timeoutAt.getTime() + ':' + saga.id; } else { sagaKey = this.options.prefix + '_saga' + ':' + saga._commitStamp.getTime() + ':Infinity:' + saga.id; } var cmdMap = []; _.each(cmds, function (cmd) { cmd.payload._sagaId = saga.id; cmd.payload._commandId = cmd.id; cmd.payload._commitStamp = saga._commitStamp; cmdMap.push(self.options.prefix + '_command' + ':' + cmd.payload._sagaId+ ':' + cmd.payload._commandId); cmdMap.push(JSON.stringify(cmd.payload)); }); this.client.watch(sagaKey, function (err) { if (err) { return callback(err); } self.get(saga.id, function (err, s) { if (err) { debug(err); if (callback) callback(err); return; } if ((s && saga._hash && saga._hash !== s._hash) || (!s && saga._hash) || (s && s._hash && !saga._hash)) { self.client.unwatch(function (err) { if (err) { debug(err); } err = new ConcurrencyError(); debug(err); if (callback) { callback(err); } }); return; } saga._hash = uuid().toString(); var args = [sagaKey, JSON.stringify(saga)].concat(cmdMap); self.client.multi([['mset'].concat(args)]).exec(function (err, replies) { if (err) { debug(err); if (callback) { callback(err); } return; } if (!replies || replies.length === 0 || _.find(replies, function (r) { return r !== 'OK' })) { var err = new ConcurrencyError(); debug(err); if (callback) { callback(err); } return; } if (callback) { callback(null); } }); }); }); }, scan: function (key, cursor, handleKeys, callback) { var self = this; if (!callback) { callback = handleKeys; handleKeys = cursor; cursor = 0; } (function scanRecursive (curs) { self.client.scan(curs, 'match', key, function (err, res) { if (err) { return callback(err); } function next () { if (res[0] === '0') { callback(null); } else { scanRecursive(res[0]); } } if (res[1].length === 0) { return next(); } handleKeys(res[1], function (err) { if (err) { return callback(err); } next(); }); }); })(cursor); }, get: function (id, callback) { if (!id || !_.isString(id)) { var err = new Error('Please pass a valid id!'); debug(err); return callback(err); } var self = this; var allKeys = []; this.scan(this.options.prefix + '_saga:*:*:' + id, function (keys, fn) { allKeys = allKeys.concat(keys); fn(); }, function (err) { if (err) { debug(err); if (callback) callback(err); return; } if (allKeys.length === 0) { if (callback) callback(null, null); return; } allKeys = _.sortBy(allKeys, function (s) { return s; }); self.client.get(allKeys[0], function (err, saga) { if (err) { return callback(err); } if (!saga) { return callback(null, null); } try { saga = jsondate.parse(saga.toString()); } catch (error) { if (callback) callback(err); return; } callback(null, saga); }); } ); }, remove: function (id, callback) { if (!id || !_.isString(id)) { var err = new Error('Please pass a valid id!'); debug(err); return callback(err); } var self = this; async.parallel([ function (callback) { self.scan(self.options.prefix + '_saga:*:*:' + id, function (keys, fn) { async.each(keys, function (key, callback) { self.client.del(key, callback); }, fn); }, callback ); }, function (callback) { self.scan(self.options.prefix + '_command:' + id + ':*', function (keys, fn) { async.each(keys, function (key, callback) { self.client.del(key, callback); }, fn); }, callback ); } ], function (err) { if (err) { debug(err); } if (callback) callback(err); }); }, getTimeoutedSagas: function (callback) { var res = []; var self = this; var allKeys = []; this.scan(this.options.prefix + '_saga:*:*:*', function (keys, fn) { allKeys = allKeys.concat(keys); fn(); }, function (err) { if (err) { debug(err); if (callback) callback(err); return; } if (allKeys.length === 0) { return callback(null, res); } allKeys = _.sortBy(allKeys, function (s) { return s; }); async.each(allKeys, function (key, callback) { var parts = key.split(':'); var prefix = parts[0]; var commitStampMs = parts[1]; var timeoutAtMs = parts[2]; var sagaId = parts[3]; if (commitStampMs === 'Infinity') { commitStampMs = Infinity; } if (_.isString(commitStampMs)) { commitStampMs = parseInt(commitStampMs, 10); } if (timeoutAtMs === 'Infinity') { timeoutAtMs = Infinity; } if (_.isString(timeoutAtMs)) { timeoutAtMs = parseInt(timeoutAtMs, 10); } if (timeoutAtMs > (new Date()).getTime()) { return callback(null); } self.get(sagaId, function (err, saga) { if (err) { return callback(err); } if (saga) { res.push(saga); } callback(null); }); }, function (err) { if (err) { return callback(err); } callback(null, res); }); } ); }, getOlderSagas: function (date, callback) { if (!date || !_.isDate(date)) { var err = new Error('Please pass a valid date object!'); debug(err); return callback(err); } var res = []; var self = this; var allKeys = []; this.scan(this.options.prefix + '_saga:*:*:*', function (keys, fn) { allKeys = allKeys.concat(keys); fn(); }, function (err) { if (err) { debug(err); if (callback) callback(err); return; } if (allKeys.length === 0) { return callback(null, res); } allKeys = _.sortBy(allKeys, function (s) { return s; }); async.each(allKeys, function (key, callback) { var parts = key.split(':'); var prefix = parts[0]; var commitStampMs = parts[1]; var timeoutAtMs = parts[2]; var sagaId = parts[3]; if (commitStampMs === 'Infinity') { commitStampMs = Infinity; } if (_.isString(commitStampMs)) { commitStampMs = parseInt(commitStampMs, 10); } if (timeoutAtMs === 'Infinity') { timeoutAtMs = Infinity; } if (_.isString(timeoutAtMs)) { timeoutAtMs = parseInt(timeoutAtMs, 10); } if (commitStampMs > date.getTime()) { return callback(null); } self.get(sagaId, function (err, saga) { if (err) { return callback(err); } if (saga) { res.push(saga); } callback(null); }); }, function (err) { if (err) { return callback(err); } callback(null, res); }); } ); }, getUndispatchedCommands: function (callback) { var res = []; var self = this; var allKeys = []; this.scan(this.options.prefix + '_command:*:*', function (keys, fn) { allKeys = allKeys.concat(keys); fn(); }, function (err) { if (err) { debug(err); if (callback) callback(err); return; } allKeys = _.sortBy(allKeys, function (s) { return s; }); async.each(allKeys, function (key, callback) { self.client.get(key, function (err, data) { if (err) { return callback(err); } if (!data) { return callback(null); } try { data = jsondate.parse(data.toString()); } catch (error) { return callback(err); } res.push({ sagaId: data._sagaId, commandId: data._commandId, command: data, commitStamp: data._commitStamp }); callback(null); }); }, function (err) { if (err) { debug(err); } if (callback) callback(err, res); }); } ); }, setCommandToDispatched: function (cmdId, sagaId, callback) { if (!cmdId || !_.isString(cmdId)) { var err = new Error('Please pass a valid command id!'); debug(err); return callback(err); } if (!sagaId || !_.isString(sagaId)) { var err = new Error('Please pass a valid saga id!'); debug(err); return callback(err); } this.client.del(this.options.prefix + '_command:' + sagaId + ':' + cmdId, function (err) { if (callback) callback(err); }); }, clear: function (callback) { var self = this; async.parallel([ function (callback) { self.client.del('nextItemId:' + self.options.prefix, callback); }, function (callback) { self.client.keys(self.options.prefix + '_saga:*', function(err, keys) { if (err) { return callback(err); } async.each(keys, function (key, callback) { self.client.del(key, callback); }, callback); }); }, function (callback) { self.client.keys(self.options.prefix + '_command:*', function(err, keys) { if (err) { return callback(err); } async.each(keys, function (key, callback) { self.client.del(key, callback); }, callback); }); } ], function (err) { if (err) { debug(err); } if (callback) callback(err); }); } }); module.exports = Redis;
var mappingDefaults = { styles: ['css', 'less', 'scss', 'sass', 'styl'], templates: ['jade', 'pug', 'json', 'html', 'htm', 'yml', 'yaml'], images: ['jpg', 'jpeg', 'png', 'svg'], sprites: ['svg'] } module.exports = function(gulp, config, watch) { var mapping = require('lodash').merge({}, mappingDefaults, config.mapping || {}) var fileExtensions = [] var mappingRegEx = {} Object.keys(mapping).forEach(function(key) { mappingRegEx[key] = [] mappingRegEx[key] = mapping[key].map(function(i) { var ext = '.' + i.replace(/^\./, '') // remove . from the beginning of the string if(fileExtensions.indexOf(key) == -1) { fileExtensions.push(ext.substring(1)) } return new RegExp(ext + '$') }) }) return function(done) { var c = require('better-console') c.info('Watching sources for change and recompilation...') var log = require('better-console') var minimatch = require('minimatch') var path = require('path') var runcmd = require('../helpers/runcmd') var glob = '**/*.{' + fileExtensions.join() + '}' var subtractPaths = require('../helpers/subtractPaths') var distFolderRelative = subtractPaths(config.dist_folder, config.dir) var globDist = distFolderRelative + '/**/*.*' var completeHandler = function(e) { if(config.hooks && config.hooks.watch) { log.info('~ watch hook: ' + config.hooks.watch) runcmd(config.hooks.watch, config.dir, function() { log.info('/>') }) } } var changeHandler = function(filepath) { // Filter dist sources if (minimatch(filepath, globDist)) { return } config._lastChanged = filepath var handlers = [] Object.keys(mappingRegEx).forEach(function (key) { mappingRegEx[key].forEach(function(regexp) { if(filepath.match(regexp)) { handlers.push(key) } }) }) if (!handlers.length) { c.warn('! unknown extension', path.extname(filepath), filepath) return } handlers.forEach(function(handler) { try { gulp.task(handler)(completeHandler) } catch(e) { // task is not defined, we can silently ignore it } }) } watch(glob, changeHandler) done() } }
'use strict'; //TODO: // Use distinct routes per passenger [stopOver: true] // Create controls for numbers of cars, frequency of passenger requests, tick speed, pause // Track passenger wait times // Track car transit times per route; aggregate interesting stats // Export stats as .json; make downloadable // Show infowindow on car click for car-specific details // Animate marker events // Reshuffle optimize passengers that are not part of a car's immediate route RideshareSimApp.controller('OptionsCtrl', function($scope, app) { $scope.togglePause = function(){ app.togglePause(); } $scope.paused = function(){ return app.paused(); } $scope.togglePauseText = function(){ return ($scope.paused() ? 'Resume' : 'Pause'); } });
import Employee from '../../components/EmployeePage'; import { graphql } from 'gatsby'; /** TODO: make this work dynamically */ export const query = graphql` query { EmployeeImages: allFile( sort: { order: ASC, fields: [absolutePath] } filter: { relativePath: { regex: "/mugshots/hallvard.jpg/" } } ) { edges { node { relativePath name childImageSharp { fluid(maxWidth: 1000) { ...GatsbyImageSharpFluid } } } } } } `; export default Employee;
const chalk = require('chalk'); const settings = require('../settings.json'); exports.run = function(client, message, args) { if (message.author == settings.adminid){ // If anyone else was to host a version of this bot, you may wish to change this to your ID. console.log(chalk.bgRed('Send command used!')); let result = args.join(' '); // Stores the server id into a serperate string var server = result.split(" "); // So the message is neat. var messagePrep = server.toString(); var message = messagePrep.replace(/,/g , " "); // As it is an array converted to a string I must replace the commas with spaces! message = message.substr(message.indexOf(" ") + 1); // Removes the server ID. // Actually sends the message, yay. client.channels.get(server[0]).sendMessage(message); } };
'use strict'; /** * StackPush * * [TOP][MAX][0][][][][MAX - 1] */ const Command = require('../../command'); class StackPush extends Command { run(base, value, length = 1) { this.writeLog(`base: ${base}, value: ${value}, length: ${length}`); //TODO return true; } output(base, value, length = 1) { const ret = []; base = this.parseVar(base); // isFull if (length == 1) { ret.push(`If(01, ${base}, 1, ${base + 1}, 1, 1)`); // equalでもいいけど…… } else { const tmpVar = this.getTmpVarNumber(0); ret.push(`Variable(0, ${tmpVar}, ${tmpVar}, 0, 1, ${base}, 0)`); ret.push(`Variable(0, ${tmpVar}, ${tmpVar}, 1, 0, ${length - 1}, 0)`); ret.push(`If(01, ${tmpVar}, 1, ${base + 1}, 1, 1)`); } // debug Message // TODO エラー処理 // ret.push(`Text("isFull")`); ret.push(`Else`); for (let i = 0; i < length; i ++) { // push var if (typeof value == 'string') { // var const valueVarNum = this.parseVar(value); ret.push(`Variable(2, ${base}, 0, 0, 1, ${valueVarNum + i}, 0)`); } else { // int扱い ret.push(`Variable(2, ${base}, 0, 0, 0, ${value}, 0)`); } // TOP++ ret.push(`Variable(0, ${base}, ${base}, 1, 0, 1, 0)`); } ret.push(`EndIf`); return ret; } get JP_NAME() { return 'SET:stack-PUSH'; } } module.exports = StackPush;
var setupMethods = function(specs, window){ var Element = window.Element || global.Element; global.disableNegNth = true; global.cannotDisableQSA = true; window.SELECT = function(context, selector, append){ return Element.getElements(context, selector); }; window.SELECT1 = function(context, selector){ return Element.getElement(context, selector); }; window.MATCH = function(context, selector){ return Element.match(context, selector); }; // window.isXML = function(document){ // return Slick.isXML(document); // }; // window.PARSE = function(selector){ // return Slick.parse(selector); // }; } var verifySetupMethods = function(specs, window){ describe('Verify Setup',function(){ it('should define SELECT', function(){ expect( typeof window.SELECT ).toEqual('function'); expect( window.SELECT(window.document, '*').length ).not.toEqual(0); }); it('should define MATCH', function(){ expect( typeof window.MATCH ).toEqual('function'); expect( window.MATCH(window.document.documentElement, '*') ).toEqual(true); }); // it('should define isXML', function(){ // expect( typeof window.isXML ).toEqual('function'); // expect( typeof window.isXML(window.document) ).toEqual('boolean'); // }); }); }; var verifySetupContext = function(specs, context){ describe('Verify Context',function(){ it('should set the context properly', function(){ expect(context.document).toBeDefined(); expect(context.document.nodeType).toEqual(9); var title = context.document.getElementsByTagName('title'); for (var i=0, l=title.length; i < l; i++) if (title[i].firstChild) expect(title[i].firstChild.nodeValue).not.toMatch(404); }); }); };
ig.module( 'plugins.shade.util.math.geom' ).defines(function () { window.sh = window.sh || {}; sh.util = sh.util || {}; sh.util.math = sh.util.math || {}; sh.util.math.geom = sh.util.math.geom || {}; sh.util.math.geom.projVert = function (a, b, x) { var pos = a, dir = { x: b.x - a.x, y: b.y - a.y }; if (dir.x === 0) return null; var t = (x - pos.x)/dir.x; return (t < 0) ? null : (pos.y + t * dir.y); }; sh.util.math.geom.projHorz = function (a, b, y) { var pos = a, dir = { x: b.x - a.x, y: b.y - a.y }; if (dir.y === 0) return null; var t = (y - pos.y)/dir.y; return (t < 0) ? null : (pos.x + t * dir.x); }; // TODO Clean up this method to make fewer comparisons sh.util.math.geom.polyContains = function (points, test) { var len = points.length, res = false; for (var i = 0, j = len - 1; i < len; j = i++) { var pi = points[i], pj = points[j]; if ((pi.x > test.x) !== (pj.x > test.x) && pi.y === pj.y && pi.y === test.y) { return true; } if ((pi.y > test.y) !== (pj.y > test.y)) { if (pi.x === pj.x && pi.x === test.x) { return true; } if ((test.x < (pj.x - pi.x) * (test.y - pi.y) / (pj.y - pi.y) + pi.x)) { res = !res; } } } return res; }; });
function hello() { if (Meteor.isCordova) { alert("Hello, World!"); } else { alert("Hello, World!"); } } function helloNative() { if (Meteor.isCordova) { navigator.notification.alert("Hello, World!", null, ""); } else { alert("Hello, World!"); } } Template.appBody.events({ 'click [data-action=hello]': hello, 'click [data-action=helloNative]': helloNative, });
'use strict'; var $npm = { utils: require('../utils'), formatting: require('../formatting') }; /** * @class helpers.TableName * @description * * **Alternative Syntax:** `TableName({table, [schema]})` &#8658; {@link helpers.TableName} * * Prepares and escapes a full table name that can be injected into queries directly. * * This is a read-only type that can be used wherever parameter `table` is supported. * * @param {String|Object} table * Table name details, depending on the type: * * - table name, if `table` is a string * - object `{table, [schema]}` * * @param {string} [schema] * Database schema name. * * When `table` is passed in as `{table, [schema]}`, this parameter is ignored. * * @property {string} name * Formatted/escaped full table name, based on properties `schema` + `table`. * * @property {string} table * Table name. * * @property {string} schema * Database schema name. * * It is `undefined` when no schema was specified (or if it was an empty string). * * @returns {helpers.TableName} * * @example * * var table = new pgp.helpers.TableName('my-table', 'my-schema'); * console.log(table); * //=> "my-schema"."my-table" * */ function TableName(table, schema) { if (!(this instanceof TableName)) { return new TableName(table, schema); } if (table && typeof table === 'object' && 'table' in table) { schema = table.schema; table = table.table; } if (!$npm.utils.isText(table)) { throw new TypeError("Table name must be non-empty text string."); } if (!$npm.utils.isNull(schema)) { if (typeof schema !== 'string') { throw new TypeError("Invalid schema name."); } if (schema.length > 0) { this.schema = schema; } } this.table = table; this.name = $npm.formatting.as.name(table); if (this.schema) { this.name = $npm.formatting.as.name(schema) + '.' + this.name; } Object.freeze(this); } /** * @method helpers.TableName.toString * @description * Creates a well-formatted string that represents the object. * * It is called automatically when writing the object into the console. * * @returns {string} */ TableName.prototype.toString = function () { return this.name; }; TableName.prototype.inspect = function () { return this.toString(); }; module.exports = TableName;
'use strict'; const Resource = require('./Resource').Resource; const PendingOperation = require('./PendingOperation').PendingOperation; const now = require('./utils').now; const duration = require('./utils').duration; const checkOptionalTime = require('./utils').checkOptionalTime; const delay = require('./utils').delay; const reflect = require('./utils').reflect; const tryPromise = require('./utils').tryPromise; class Pool { constructor(opt) { opt = opt || {}; if (!opt.create) { throw new Error('Tarn: opt.create function most be provided'); } if (!opt.destroy) { throw new Error('Tarn: opt.destroy function most be provided'); } if (typeof opt.min !== 'number' || opt.min < 0 || opt.min !== Math.round(opt.min)) { throw new Error('Tarn: opt.min must be an integer >= 0'); } if (typeof opt.max !== 'number' || opt.max <= 0 || opt.max !== Math.round(opt.max)) { throw new Error('Tarn: opt.max must be an integer > 0'); } if (opt.min > opt.max) { throw new Error('Tarn: opt.max is smaller than opt.min'); } if (!checkOptionalTime(opt.acquireTimeoutMillis)) { throw new Error( 'Tarn: invalid opt.acquireTimeoutMillis ' + JSON.stringify(opt.acquireTimeoutMillis) ); } if (!checkOptionalTime(opt.createTimeoutMillis)) { throw new Error( 'Tarn: invalid opt.createTimeoutMillis ' + JSON.stringify(opt.createTimeoutMillis) ); } if (!checkOptionalTime(opt.idleTimeoutMillis)) { throw new Error( 'Tarn: invalid opt.idleTimeoutMillis ' + JSON.stringify(opt.idleTimeoutMillis) ); } if (!checkOptionalTime(opt.reapIntervalMillis)) { throw new Error( 'Tarn: invalid opt.reapIntervalMillis ' + JSON.stringify(opt.reapIntervalMillis) ); } if (!checkOptionalTime(opt.createRetryIntervalMillis)) { throw new Error( 'Tarn: invalid opt.createRetryIntervalMillis ' + JSON.stringify(opt.createRetryIntervalMillis) ); } this.creator = opt.create; this.destroyer = opt.destroy; this.validate = typeof opt.validate === 'function' ? opt.validate : () => true; this.log = opt.log || (() => {}); this.acquireTimeoutMillis = opt.acquireTimeoutMillis || 30000; this.createTimeoutMillis = opt.createTimeoutMillis || 30000; this.idleTimeoutMillis = opt.idleTimeoutMillis || 30000; this.reapIntervalMillis = opt.reapIntervalMillis || 1000; this.createRetryIntervalMillis = opt.createRetryIntervalMillis || 200; this.propagateCreateError = !!opt.propagateCreateError; this.min = opt.min; this.max = opt.max; this.used = []; this.free = []; this.pendingCreates = []; this.pendingAcquires = []; this.destroyed = false; this.interval = null; } numUsed() { return this.used.length; } numFree() { return this.free.length; } numPendingAcquires() { return this.pendingAcquires.length; } numPendingCreates() { return this.pendingCreates.length; } acquire() { const pendingAcquire = new PendingOperation(this.acquireTimeoutMillis); this.pendingAcquires.push(pendingAcquire); // If the acquire fails for whatever reason // remove it from the pending queue. pendingAcquire.promise = pendingAcquire.promise.catch(err => { remove(this.pendingAcquires, pendingAcquire); return Promise.reject(err); }); this._tryAcquireOrCreate(); return pendingAcquire; } release(resource) { for (let i = 0, l = this.used.length; i < l; ++i) { const used = this.used[i]; if (used.resource === resource) { this.used.splice(i, 1); this.free.push(used.resolve()); this._tryAcquireOrCreate(); return true; } } return false; } isEmpty() { return ( [this.numFree(), this.numUsed(), this.numPendingAcquires(), this.numPendingCreates()].reduce( (total, value) => total + value ) === 0 ); } check() { const timestamp = now(); const newFree = []; const minKeep = this.min - this.used.length; const maxDestroy = this.free.length - minKeep; let numDestroyed = 0; this.free.forEach(free => { if ( duration(timestamp, free.timestamp) > this.idleTimeoutMillis && numDestroyed < maxDestroy ) { numDestroyed++; this._destroy(free.resource); } else { newFree.push(free); } }); this.free = newFree; //Pool is completely empty, stop reaping. //Next .acquire will start reaping interval again. if (this.isEmpty()) { this._stopReaping(); } } destroy() { this._stopReaping(); this.destroyed = true; // First wait for all the pending creates get ready. return reflect( Promise.all(this.pendingCreates.map(create => reflect(create.promise))) .then(() => { // Wait for all the used resources to be freed. return Promise.all(this.used.map(used => reflect(used.promise))); }) .then(() => { // Abort all pending acquires. return Promise.all( this.pendingAcquires.map(acquire => { acquire.abort(); return reflect(acquire.promise); }) ); }) .then(() => { // Now we can destroy all the freed resources. this.free.forEach(free => this._destroy(free.resource)); this.free = []; this.pendingAcquires = []; }) ); } _tryAcquireOrCreate() { if (this.destroyed) { return; } if (this._hasFreeResources()) { this._doAcquire(); } else if (this._shouldCreateMoreResources()) { this._doCreate(); } } _hasFreeResources() { return this.free.length > 0; } _doAcquire() { let didDestroyResources = false; while (this._canAcquire()) { const pendingAcquire = this.pendingAcquires[0]; const free = this.free[this.free.length - 1]; if (!this._validateResource(free.resource)) { this.free.pop(); this._destroy(free.resource); didDestroyResources = true; continue; } this.pendingAcquires.shift(); this.free.pop(); this.used.push(free.resolve()); //At least one active resource, start reaping this._startReaping(); pendingAcquire.resolve(free.resource); } // If we destroyed invalid resources, we may need to create new ones. if (didDestroyResources) { this._tryAcquireOrCreate(); } } _canAcquire() { return this.free.length > 0 && this.pendingAcquires.length > 0; } _validateResource(resource) { try { return !!this.validate(resource); } catch (err) { // There's nothing we can do here but log the error. This would otherwise // leak out as an unhandled exception. this.log('Tarn: resource validator threw an exception ' + err.stack, 'warn'); return false; } } _shouldCreateMoreResources() { return ( this.used.length + this.pendingCreates.length < this.max && this.pendingCreates.length < this.pendingAcquires.length ); } _doCreate() { const pendingAcquiresBeforeCreate = this.pendingAcquires.slice(); const pendingCreate = this._create(); pendingCreate.promise .then(() => { // Not returned on purpose. this._tryAcquireOrCreate(); }) .catch(err => { if (this.propagateCreateError && this.pendingAcquires.length !== 0) { // If propagateCreateError is true, we don't retry the create // but reject the first pending acquire immediately. Intentionally // use `this.pendingAcquires` instead of `pendingAcquiresBeforeCreate` // in case some acquires in pendingAcquiresBeforeCreate have already // been resolved. this.pendingAcquires[0].reject(err); } // Save the create error to all pending acquires so that we can use it // as the error to reject the acquire if it times out. pendingAcquiresBeforeCreate.forEach(pendingAcquire => { pendingAcquire.possibleTimeoutCause = err; }); // Not returned on purpose. delay(this.createRetryIntervalMillis).then(() => this._tryAcquireOrCreate()); }); } _create() { const pendingCreate = new PendingOperation(this.createTimeoutMillis); this.pendingCreates.push(pendingCreate); callbackOrPromise(this.creator) .then(resource => { remove(this.pendingCreates, pendingCreate); this.free.push(new Resource(resource)); pendingCreate.resolve(resource); }) .catch(err => { remove(this.pendingCreates, pendingCreate); pendingCreate.reject(err); }); return pendingCreate; } _destroy(resource) { try { this.destroyer(resource); } catch (err) { // There's nothing we can do here but log the error. This would otherwise // leak out as an unhandled exception. this.log('Tarn: resource destroyer threw an exception ' + err.stack, 'warn'); } } _startReaping() { if (!this.interval) { this.interval = setInterval(() => this.check(), this.reapIntervalMillis); } } _stopReaping() { clearInterval(this.interval); this.interval = null; } } function remove(arr, item) { var idx = arr.indexOf(item); if (idx === -1) { return false; } else { arr.splice(idx, 1); return true; } } function callbackOrPromise(func) { return new Promise((resolve, reject) => { const callback = (err, resource) => { if (err) { reject(err); } else { resolve(resource); } }; tryPromise(() => func(callback)) .then(res => { // If the result is falsy, we assume that the callback will // be called instead of interpreting the falsy value as a // result value. if (res) { resolve(res); } }) .catch(err => { reject(err); }); }); } module.exports = { Pool };
/* 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( 'notification', 'ko', { closed: '알림이 닫힘.' } );
/* * This file is part of the Husky Validation. * * (c) MASSIVE ART WebServices GmbH * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. * */ define([ 'type/default' ], function(Default) { 'use strict'; var dataChangedHandler = function(data, $el) { App.emit('sulu.preview.update', $el, data); App.emit('sulu.content.changed'); }; return function($el, options) { var defaults = {}, subType = { initializeSub: function() { var dataChangedEvent = 'sulu.media-selection.' + options.instanceName + '.data-changed'; App.off(dataChangedEvent, dataChangedHandler); App.on(dataChangedEvent, dataChangedHandler); }, setValue: function(value) { // array of objects if (App.util.typeOf(value) === 'array' && App.util.typeOf(value[0]) === 'object') { var ids = []; App.util.foreach(value, function(el) { ids.push(el.id); }.bind(this)); value = {ids: ids}; } App.dom.data($el, 'media-selection', value); }, getValue: function() { return App.dom.data($el, 'media-selection'); }, needsValidation: function() { return false; }, validate: function() { return true; } }; return new Default($el, defaults, options, 'smartContent', subType); }; });
search_result['3261']=["topic_00000000000007CA_props--.html","ApplicantProfileListResponseDto Properties",""];
define(['object/ImageObject'], function(ImageObject) { function Troll(id, x, y, scene) { ImageObject.call(this, id, x, y, 100, scene, '/images/trollface_small.jpg'); return this; } Troll.prototype = new ImageObject(); Troll.prototype.constructor = Troll; Troll.prototype.replace = function(canvasWidth, canvasHeight) { // Need to make sure image will not be out of canvas boundary var maxX = canvasWidth - this.image.width; var x = Math.floor(Math.random() * maxX); var maxY = canvasHeight - this.image.height; var y = Math.floor(Math.random() * maxY); // Update position in scene this.position.x = x; this.position.y = y; }; return Troll; });
//站点路径 js (function ($) { //配置样式 var pathStartWith = "web"; //从哪一级路径开始匹配 var divsionClass = "gt"; //分隔符样式 var divsionChartper = "/";//分隔符字符 var crumbsClassPrefix = "level";//面包屑样式前缀 var crumbs = function(){ //判断是否启用 if(this.attr("data-enable") == "false") return; this.addClass("crumbs"); var paths = getNode(); var divsion = "<span class='"+ divsionClass +"'>"+ divsionChartper +"</span>"; var htmlstring = ""; for(var i =0 ; i< paths.length ; i++){ if(paths[i] != undefined){ var classname = crumbsClassPrefix + (i+1); var href = paths[i].url; var name = paths[i].name; if(i>0){ htmlstring += divsion; } //若href空或者未定义就生成spna标签 if(href =="" || href == undefined){ htmlstring += "<span class='"+ classname +"'>"+ name +"</span>"; } else{ htmlstring += "<a class='"+ classname +"' href='"+ href +"'>"+ name +"</a>"; } } } //处理绑定的数据 htmlstring = bindData(this,htmlstring); this.html(htmlstring); } //处理绑定的数据 var bindData = function($targ,htmlstring){ var start = htmlstring.indexOf("{") + 1; var end = htmlstring.indexOf("}") - start; if(start == 0|| end == -1){ return htmlstring; } var targerAttr = "data-" + htmlstring.substr(start,end); var data = $targ.attr(targerAttr); return htmlstring.replace("{" + htmlstring.substr(start,end) + "}",data); } //站点地图配置 var getNode = function(){ var path = window.location.pathname; var nodes = getWebNodeArray(path).reverse(); var level1,level2,level3; //找第一级 var node = nodes.pop(); if(node != undefined){ for(var i =0; i<sitemap.length ; i++ ) { if(node.indexOf(sitemap[i].match) != -1){ //找到第一级元素 level1 = sitemap[i]; break; } } } //找第二级 var node = nodes.pop(); if(node != undefined && level1 != undefined && level1.item != undefined){ for(var i =0; i<level1.item.length ; i++ ) { if(node.indexOf(level1.item[i].match) != -1){ //找到第二级元素 level2 = level1.item[i]; break; } } } //找第三级 var node = nodes.pop(); if(node != undefined && level2 != undefined && level2.item != undefined){ for(var i =0; i<level2.item.length ; i++ ) { if(node.indexOf(level2.item[i].match) != -1){ //找到第二级元素 level3 = level2.item[i]; break; } } } return [level1,level2,level3]; } var getWebNodeArray = function(path){ pathStartWith = pathStartWith.toLocaleLowerCase(); var nodes = []; var arr=new Array(); arr=path.split('/'); var status = 0; for(var i=0;i<arr.length;i++){ if(status==1){ nodes.push(arr[i]); } if(arr[i].indexOf(pathStartWith) != -1){ status = 1; } } return nodes; } $.fn.crumbs = crumbs; })(jQuery);
var ajax = require('ajax') var Future = require("async-future") var decodeDataUrl = require("./decodeDataUrl") exports.fromUrl = function(sourceUrl, toSource) { return ajax(sourceUrl, true).then(function(response) { return fromSourceOrHeaders(response.headers, response.text, toSource) }) } exports.fromSource = function(sourceText, toSource) { return fromSourceOrHeaders({}, sourceText, toSource) } function fromSourceOrHeaders(headers, sourceText, toSource) { if(toSource === undefined) toSource = false var sourcemapUrl = getSourceMapUrl(headers, sourceText) if(sourcemapUrl === undefined) { return Future(undefined) } else if(toSource) { if(sourcemapUrl.indexOf('data:') === 0) { return Future(decodeDataUrl(sourcemapUrl)) } else { return ajax(sourcemapUrl).then(function(response) { return Future(response.text) }) } } else { return Future(sourcemapUrl) } } exports.cacheGet = ajax.cacheGet exports.cacheSet = ajax.cacheSet var URL_PATTERN = '(((?:http|https|file)://)?[^\\s)]+|javascript:.*)' var SOURCE_MAP_PATTERN_PART = " sourceMappingURL=("+URL_PATTERN+")" var SOURCE_MAP_PATTERN1 = "\/\/#"+SOURCE_MAP_PATTERN_PART var SOURCE_MAP_PATTERN2 = "\/\/@"+SOURCE_MAP_PATTERN_PART function getSourceMapUrl(headers, content) { if(headers['SourceMap'] !== undefined) { return headers['SourceMap'] } else if(headers['X-SourceMap']) { return headers['X-SourceMap'] } else { var match = content.match(SOURCE_MAP_PATTERN1) if(match !== null) return match[1] match = content.match(SOURCE_MAP_PATTERN2) if(match !== null) return match[1] } }
const deposits = require('../models/deposits') const NO_HISTORY = 'no_history_in_range' async function insertNewRecord (playerId, voucherId) { return deposits.create(playerId, voucherId) } async function findBetween (playerId, from, to, page, pagination) { const histories = await deposits.findByOwnerAndCreationDuration(playerId, from, to, page - 1, pagination) if (histories.length === 0) { throw new Error(NO_HISTORY) } return histories } module.exports = { NO_HISTORY, insertNewRecord, findBetween }
'use strict'; (function (ga) { function DataMetrics() { this.init(); } DataMetrics.prototype = { init: function () { this.addEventListeners(); }, addEventListeners: function () { var elements = document.querySelectorAll('*[data-metrics]'); for (var i = 0; i < elements.length; i++) { if (!this.isForm(elements[i])) { elements[i].addEventListener('click', this.appendEvent.bind(this), false); } else { elements[i].onsubmit = this.appendEvent.bind(this); } } }, isForm: function (elem) { if (elem.tagName === 'FORM') { return true; } else { return false; } }, appendEvent: function (e) { var elem = e.currentTarget; if (!elem.classList.contains('sending-metrics')) { var params = elem.getAttribute('data-metrics').split('|'); if (params[1] === undefined) { params[1] = null; } if (params[2] === undefined) { params[2] = null; } this.sendToGA(params[0], params[1], params[2], elem); elem.classList.add('sending-metrics'); if (!this.isForm(elem) && !elem.getAttribute('target')) { e.preventDefault(); return false; } } }, sendToGA: function (category, action, label, elem) { var self = this; window.ga('send', 'event', category, action, label, { 'hitCallback': function () { self.onHitCallback(elem); }}); }, onHitCallback: function (elem) { if (elem) { this.onEventIsDispatched(elem); } }, onEventIsDispatched: function (elem) { if (elem.getAttribute('href') && !elem.getAttribute('target')) { window.location.href = elem.getAttribute('href'); } else if (this.isForm(elem)) { elem.submit(); } elem.classList.remove('sending-metrics'); } }; window.dataMetrics = new DataMetrics(); })(window.ga);
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require page-styles //= require_tree .
"use strict"; /* See License / Disclaimer https://raw.githubusercontent.com/DynamicTyped/Griddle/master/LICENSE */ var React = require("react"); var _ = require("underscore"); var ColumnProperties = require("./columnProperties.js"); var GridTitle = React.createClass({ displayName: "GridTitle", getDefaultProps: function () { return { columnSettings: null, rowSettings: null, sortSettings: null, headerStyle: null, useGriddleStyles: true, useGriddleIcons: true, headerStyles: {} }; }, componentWillMount: function () { this.verifyProps(); }, sort: function (event) { this.props.sortSettings.changeSort(event.target.dataset.title || event.target.parentElement.dataset.title); }, verifyProps: function () { if (this.props.columnSettings === null) { console.error("gridTitle: The columnSettings prop is null and it shouldn't be"); } if (this.props.sortSettings === null) { console.error("gridTitle: The sortSettings prop is null and it shouldn't be"); } }, render: function () { this.verifyProps(); var that = this; var nodes = this.props.columnSettings.getColumns().map(function (col, index) { var columnSort = ""; var sortComponent = null; var titleStyles = null; if (that.props.sortSettings.sortColumn == col && that.props.sortSettings.sortAscending) { columnSort = that.props.sortSettings.sortAscendingClassName; sortComponent = that.props.useGriddleIcons && that.props.sortSettings.sortAscendingComponent; } else if (that.props.sortSettings.sortColumn == col && that.props.sortSettings.sortAscending === false) { columnSort += that.props.sortSettings.sortDescendingClassName; sortComponent = that.props.useGriddleIcons && that.props.sortSettings.sortDescendingComponent; } var meta = that.props.columnSettings.getColumnMetadataByName(col); var columnIsSortable = that.props.columnSettings.getMetadataColumnProperty(col, "sortable", true); var displayName = that.props.columnSettings.getMetadataColumnProperty(col, "displayName", col); columnSort = meta == null ? columnSort : (columnSort && columnSort + " " || columnSort) + that.props.columnSettings.getMetadataColumnProperty(col, "cssClassName", ""); if (that.props.useGriddleStyles) { titleStyles = { backgroundColor: "#EDEDEF", border: "0", borderBottom: "1px solid #DDD", color: "#222", padding: "5px", cursor: columnIsSortable ? "pointer" : "default" }; } return React.createElement( "th", { onClick: columnIsSortable ? that.sort : null, "data-title": col, className: columnSort, key: displayName, style: titleStyles }, displayName, sortComponent ); }); //Get the row from the row settings. var className = that.props.rowSettings && that.props.rowSettings.getHeaderRowMetadataClass() || null; return React.createElement( "thead", null, React.createElement( "tr", { className: className, style: this.props.headerStyles }, nodes ) ); } }); module.exports = GridTitle;
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html 'use strict'; module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', 'angular-cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-remap-istanbul'), require('angular-cli/plugins/karma') ], files: [ { pattern: './src/test.ts', watched: false } ], preprocessors: { './src/test.ts': ['angular-cli'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, remapIstanbulReporter: { reports: { html: 'coverage', lcovonly: './coverage/coverage.lcov' } }, angularCli: { config: './angular-cli.json', environment: 'dev' }, reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'karma-remap-istanbul'] : ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chromium'], singleRun: false }); };
var async = require('async'), events = require('events'), log = function (text, debug) { if(debug) { console.log(new Date().toLocaleTimeString(), '|', text); } }, generateAndApplyETags = function (newBuilds) { for (var i = 0; i < newBuilds.length; i++) { var build = newBuilds[i]; build.etag = require('crypto') .createHash('md5') .update(JSON.stringify(build)) .digest('hex'); } }, sortBuilds = function (newBuilds, sortOrder) { if(sortOrder == "project") { newBuilds.sort(function (a, b) { if(a.project > b.project) return 1; if(a.project < b.project) return -1; return 0; }); } else { var takeDate = function (build) { return build.isRunning ? build.startedAt : build.finishedAt; }; newBuilds.sort(function (a, b) { var dateA = takeDate(a); var dateB = takeDate(b); if(dateA < dateB) return 1; if(dateA > dateB) return -1; return 0; }); } }, distinctBuildsByETag = function (newBuilds) { var unique = {}; for (var i = newBuilds.length - 1; i >= 0; i--) { var build = newBuilds[i]; if (unique[build.etag]) { newBuilds.splice(i, 1); } unique[build.etag] = true; } }, onlyTake = function (numberOfBuilds, newBuilds) { newBuilds.splice(numberOfBuilds); }, changed = function (currentBuilds, newBuilds) { var newBuildsHash = newBuilds .map(function (value) { return value.etag; }) .join('|'); var currentBuildsHash = currentBuilds .map(function (value) { return value.etag; }) .join('|'); return newBuildsHash !== currentBuildsHash; }, detectChanges = function (currentBuilds, newBuilds) { var changes = { added: [], removed: [], updated: [] }, getById = function (builds, id) { return builds.filter(function (build) { return build.id === id; })[0]; }; var currentBuildIds = currentBuilds.map(function (build) { return build.id; }); var newBuildIds = newBuilds.map(function (build) { return build.id; }); newBuildIds.forEach(function (newBuildId) { if (currentBuildIds.indexOf(newBuildId) === -1) { changes.added.push(getById(newBuilds, newBuildId)); } if (currentBuildIds.indexOf(newBuildId) >= 0) { var currentBuild = getById(currentBuilds, newBuildId); var newBuild = getById(newBuilds, newBuildId); if (currentBuild.etag !== newBuild.etag) { changes.updated.push(getById(newBuilds, newBuildId)); } } }); currentBuildIds.forEach(function (currentBuildId) { if (newBuildIds.indexOf(currentBuildId) === -1) { changes.removed.push(getById(currentBuilds, currentBuildId)); } }); changes.order = newBuildIds; return changes; }; module.exports = function () { var self = this; self.configuration = { interval: 5000, numberOfBuilds: 12, debug: false }; self.plugins = []; self.currentBuilds = []; self.configure = function (config) { self.configuration = config; }; self.watchOn = function (plugin) { self.plugins.push(plugin); }; self.run = function () { var allBuilds = []; async.each(self.plugins, function (plugin, callback) { log('Check for builds...', self.configuration.debug); plugin.check(function (error, pluginBuilds) { if (error) { console.log('**********************************************************************'); console.log('An error occured when fetching builds for the following configuration:'); console.log('----------------------------------------------------------------------'); console.log(plugin.configuration); console.log('----------------------------------------------------------------------'); console.log(); console.error(error); console.log('**********************************************************************'); console.log(); console.log(); callback(); return; } if(self.configuration.latestBuildOnly) { Array.prototype.push.apply(allBuilds, [pluginBuilds.shift()]); } else { Array.prototype.push.apply(allBuilds, pluginBuilds); } callback(); }); }, function (error) { log(allBuilds.length + ' builds found....', self.configuration.debug); generateAndApplyETags(allBuilds); distinctBuildsByETag(allBuilds); sortBuilds(allBuilds, self.configuration.sortOrder); if(!self.configuration.latestBuildOnly) { onlyTake(self.configuration.numberOfBuilds, allBuilds); } if(changed(self.currentBuilds, allBuilds)) { log('builds changed', self.configuration.debug); self.emit('buildsChanged', detectChanges(self.currentBuilds, allBuilds)); self.currentBuilds = allBuilds; } setTimeout(self.run, self.configuration.interval); }); }; }; module.exports.prototype = new events.EventEmitter();
function routes(handlers) { const routeArr = [ { method: 'GET', path: '/img/{file*}', handler: handlers.img }, { method: 'GET', path: '/js/{file*}', handler: handlers.js }, { method: 'GET', path: '/', handler: handlers.index }, { method: 'GET', path: '/version', handler: handlers.version }, { method: 'POST', path: '/identify', handler: handlers.identifyPeople }]; return routeArr; } module.exports = routes;
app.controller('bodyController', ['$scope', function($scope) { 'use strict'; $scope.setBodyClass = function(bodyClass) { $scope.bodyClass = bodyClass; $scope.loginPage = ($scope.bodyClass === 'login'); }; } ]);
import {inject, bindable, customElement} from 'aurelia-framework'; import './attribute-item.less'; @customElement('attribute-item') @bindable('model') @inject(Element) export class AttributeItem { constructor(element) { this.element = element; } remove() { let e = new window.CustomEvent('removed', { detail: this.model }); this.element.dispatchEvent(e); } }
/*globals template*/ var parse = function (key, obj) { 'use strict'; var ar = key.split('.'); while (obj && ar.length) { obj = obj[ar.shift()]; } return obj; }; var extend = function (a, b) { 'use strict'; for (var i in b) { if (a.hasOwnProperty(i) || b.hasOwnProperty(i)) { a[i] = b[i]; } } return a; }; var templateString = function (st, data, options, lng, defaults) { 'use strict'; var i; var evaluate = /\{\{([\s\S]+?)\}\}/g; var interpolate = /\{\{=([\s\S]+?)\}\}/g; var escape = /\{\{-([\s\S]+?)\}\}/g; options = options || {}; var settings = { evaluate: options.evaluate || evaluate, interpolate: options.interpolate || interpolate, escape: options.escape || escape }; var newDatas = extend(extend(defaults, defaults[lng]), data) || defaults || {}; var needsTemplate = false; for (i in settings) { if (settings.hasOwnProperty(i) && settings[i].test(st)) { needsTemplate = true; break; } } if (needsTemplate && typeof st !== 'function' && typeof template === 'function') { st = template(st, settings); } return typeof st === 'function' ? st(newDatas) : st; }; var I18n = function () { 'use strict'; // PRIVATES var localLang = 'en'; var dico = {}; var defaults = {}; this.add = function (lang, ns, locales) { var i; var obj; dico[lang] = dico[lang] || {}; if (locales === undefined) { locales = ns; ns = undefined; obj = dico[lang]; } else { dico[lang][ns] = dico[lang][ns] || {}; obj = dico[lang][ns]; } obj = extend(obj, locales); }; this.has = function (key, lang) { lang = lang || localLang; var keyToParse = lang + '.' + key; // Check for the lang if (dico[key]) { return true; } // Check for the key and lang return parse(keyToParse, dico) ? true : false; }; this.listLangs = function () { var langs = []; for (var i in dico) { langs.push(i); } return langs; }; this.getCurrentLang = function () { return localLang; }; this.getDico = function () { return dico; }; this.getDefaults = function () { return defaults; }; this.setLang = function (lang) { localLang = lang; return localLang; }; this.setDefaults = function (options) { defaults = extend(defaults, options || {}); }; this.get = function (key, data, options, lang) { var lng = lang || localLang; if (lang === undefined) { if (typeof data === 'string') { lng = data; data = undefined; } else if (typeof options === 'string') { lng = options; } } var obj = parse(lng + '.' + key, dico) || parse(lng + '.' + key, defaults) || parse(key, defaults); options = options || {}; var toReturn = key; if (typeof obj === 'string' || typeof obj === 'function') { toReturn = templateString(obj, data, options, lng, defaults); } else if (typeof obj === 'object') { toReturn = obj; } return toReturn; }; }; return new I18n();
$("#addOptionButton").on("click", function (event) { let description = $("#optionDesc").val(); let id = location.href.split("=")[1]; let body = { id: id, description: description }; $.ajax({ url: "/Question/AddOption", type: "post", cors: true, contentType: "application/json", data: JSON.stringify(body), success: function (response) { location.reload(); } }); });
/* ============================================================ * bootstrap-tokenfield.js v0.11.0 * ============================================================ * * Copyright 2013 Sliptree * ============================================================ */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { root.Tokenfield = factory(root.jQuery); } }(this, function ($) { "use strict"; // jshint ;_; /* TOKENFIELD PUBLIC CLASS DEFINITION * ============================== */ var Tokenfield = function (element, options) { var _self = this this.$element = $(element) this.textDirection = this.$element.css('direction'); // Extend options this.options = $.extend({}, $.fn.tokenfield.defaults, { tokens: this.$element.val() }, options) // Setup delimiters and trigger keys this._delimiters = (typeof this.options.delimiter === 'string') ? [this.options.delimiter] : this.options.delimiter this._triggerKeys = $.map(this._delimiters, function (delimiter) { return delimiter.charCodeAt(0); }); // Store original input width var elRules = (typeof window.getMatchedCSSRules === 'function') ? window.getMatchedCSSRules( element ) : null , elStyleWidth = element.style.width , elCSSWidth , elWidth = this.$element.width() if (elRules) { $.each( elRules, function (i, rule) { if (rule.style.width) { elCSSWidth = rule.style.width; } }); } // Move original input out of the way var hidingPosition = $('body').css('direction') === 'rtl' ? 'right' : 'left'; this.$element.css('position', 'absolute').css(hidingPosition, '-10000px').prop('tabindex', -1) // Create a wrapper this.$wrapper = $('<div class="tokenfield form-control" />') if (this.$element.hasClass('input-lg')) this.$wrapper.addClass('input-lg') if (this.$element.hasClass('input-sm')) this.$wrapper.addClass('input-sm') if (this.textDirection === 'rtl') this.$wrapper.addClass('rtl') // Create a new input var id = this.$element.prop('id') || new Date().getTime() + '' + Math.floor((1 + Math.random()) * 100) this.$input = $('<input type="text" class="token-input" autocomplete="off" />') .appendTo( this.$wrapper ) .prop( 'placeholder', this.$element.prop('placeholder') ) .prop( 'id', id + '-tokenfield' ) // Re-route original input label to new input var $label = $( 'label[for="' + this.$element.prop('id') + '"]' ) if ( $label.length ) { $label.prop( 'for', this.$input.prop('id') ) } // Set up a copy helper to handle copy & paste this.$copyHelper = $('<input type="text" />').css('position', 'absolute').css(hidingPosition, '-10000px').prop('tabindex', -1).prependTo( this.$wrapper ) // Set wrapper width if (elStyleWidth) { this.$wrapper.css('width', elStyleWidth); } else if (elCSSWidth) { this.$wrapper.css('width', elCSSWidth); } // If input is inside inline-form with no width set, set fixed width else if (this.$element.parents('.form-inline').length) { this.$wrapper.width( elWidth ) } // Set tokenfield disabled, if original or fieldset input is disabled if (this.$element.prop('disabled') || this.$element.parents('fieldset[disabled]').length) { this.disable(); } // Set up mirror for input auto-sizing this.$mirror = $('<span style="position:absolute; top:-999px; left:0; white-space:pre;"/>'); this.$input.css('min-width', this.options.minWidth + 'px') $.each([ 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'letterSpacing', 'textTransform', 'wordSpacing', 'textIndent' ], function (i, val) { _self.$mirror[0].style[val] = _self.$input.css(val); }); this.$mirror.appendTo( 'body' ) // Insert tokenfield to HTML this.$wrapper.insertBefore( this.$element ) this.$element.prependTo( this.$wrapper ) // Calculate inner input width this.update() // Create initial tokens, if any this.setTokens(this.options.tokens, false, false) // Start listening to events this.listen() // Initialize autocomplete, if necessary if ( ! $.isEmptyObject( this.options.autocomplete ) ) { var side = this.textDirection === 'rtl' ? 'right' : 'left' var autocompleteOptions = $.extend({}, this.options.autocomplete, { minLength: this.options.showAutocompleteOnFocus ? 0 : null, position: { my: side + " top", at: side + " bottom", of: this.$wrapper } }) this.$input.autocomplete( autocompleteOptions ) } // Initialize typeahead, if necessary if ( ! $.isEmptyObject( this.options.typeahead ) ) { var typeaheadOptions = $.extend({}, this.options.typeahead, {}) this.$input.typeahead( typeaheadOptions ) this.typeahead = true } } Tokenfield.prototype = { constructor: Tokenfield , createToken: function (attrs, triggerChange) { if (typeof attrs === 'string') { attrs = { value: attrs, label: attrs } } if (typeof triggerChange === 'undefined') { triggerChange = true } var _self = this , value = $.trim(attrs.value) , label = attrs.label.length ? $.trim(attrs.label) : value if (!value.length || !label.length || value.length < this.options.minLength) return if (this.options.limit && this.getTokens().length >= this.options.limit) return // Allow changing token data before creating it var beforeCreateEvent = $.Event('beforeCreateToken') beforeCreateEvent.token = { value: value, label: label } this.$element.trigger( beforeCreateEvent ) if (!beforeCreateEvent.token) return value = beforeCreateEvent.token.value label = beforeCreateEvent.token.label // Check for duplicates if (!this.options.allowDuplicates && $.grep(this.getTokens(), function (token) { return token.value === value }).length) { // Allow listening to when duplicates get prevented var duplicateEvent = $.Event('preventDuplicateToken') duplicateEvent.token = { value: value, label: label } this.$element.trigger( duplicateEvent ) // Add duplicate warning class to existing token for 250ms var duplicate = this.$wrapper.find( '.token[data-value="' + value + '"]' ).addClass('duplicate') setTimeout(function() { duplicate.removeClass('duplicate'); }, 250) return false } var token = $('<div class="token" />') .attr('data-value', value) .append('<span class="token-label" />') .append('<a href="#" class="close" tabindex="-1">&times;</a>') // Insert token into HTML if (this.$input.hasClass('tt-query')) { this.$input.parent().before( token ) } else { this.$input.before( token ) } this.$input.css('width', this.options.minWidth + 'px') var tokenLabel = token.find('.token-label') , closeButton = token.find('.close') // Determine maximum possible token label width if (!this.maxTokenWidth) { this.maxTokenWidth = this.$wrapper.width() - closeButton.outerWidth() - parseInt(closeButton.css('margin-left'), 10) - parseInt(closeButton.css('margin-right'), 10) - parseInt(token.css('border-left-width'), 10) - parseInt(token.css('border-right-width'), 10) - parseInt(token.css('padding-left'), 10) - parseInt(token.css('padding-right'), 10) parseInt(tokenLabel.css('border-left-width'), 10) - parseInt(tokenLabel.css('border-right-width'), 10) - parseInt(tokenLabel.css('padding-left'), 10) - parseInt(tokenLabel.css('padding-right'), 10) parseInt(tokenLabel.css('margin-left'), 10) - parseInt(tokenLabel.css('margin-right'), 10) } tokenLabel .text(label) .css('max-width', this.maxTokenWidth) // Listen to events token .on('mousedown', function (e) { if (_self.disabled) return false; _self.preventDeactivation = true }) .on('click', function (e) { if (_self.disabled) return false; _self.preventDeactivation = false if (e.ctrlKey || e.metaKey) { e.preventDefault() return _self.toggle( token ) } _self.activate( token, e.shiftKey, e.shiftKey ) }) .on('dblclick', function (e) { if (_self.disabled || !_self.options.allowEditing ) return false; _self.edit( token ) }) closeButton .on('click', $.proxy(this.remove, this)) var afterCreateEvent = $.Event('afterCreateToken') afterCreateEvent.token = beforeCreateEvent.token afterCreateEvent.relatedTarget = token.get(0) this.$element.trigger( afterCreateEvent ) var changeEvent = $.Event('change') changeEvent.initiator = 'tokenfield' if (triggerChange) { this.$element.val( this.getTokensList() ).trigger( changeEvent ) } this.update() return this.$input.get(0) } , setTokens: function (tokens, add, triggerChange) { if (!tokens) return if (!add) this.$wrapper.find('.token').remove() if (typeof triggerChange === 'undefined') { triggerChange = true } if (typeof tokens === 'string') { if (this._delimiters.length) { tokens = tokens.split( new RegExp( '[' + this._delimiters.join('') + ']' ) ) } else { tokens = [tokens]; } } var _self = this $.each(tokens, function (i, token) { _self.createToken(token, triggerChange) }) return this.$element.get(0) } , getTokenData: function(token) { var data = token.map(function() { var $token = $(this); return { value: $token.attr('data-value'), label: $token.find('.token-label').text() } }).get(); if (data.length == 1) { data = data[0]; } return data; } , getTokens: function(active) { var self = this , tokens = [] , activeClass = active ? '.active' : '' // get active tokens only this.$wrapper.find( '.token' + activeClass ).each( function() { tokens.push( self.getTokenData( $(this) ) ) }) return tokens } , getTokensList: function(delimiter, beautify, active) { delimiter = delimiter || this._delimiters[0] beautify = ( typeof beautify !== 'undefined' && beautify !== null ) ? beautify : this.options.beautify var separator = delimiter + ( beautify && delimiter !== ' ' ? ' ' : '') return $.map( this.getTokens(active), function (token) { return token.value }).join(separator) } , getInput: function() { return this.$input.val() } , listen: function () { var _self = this this.$element .on('change', $.proxy(this.change, this)) this.$wrapper .on('mousedown',$.proxy(this.focusInput, this)) this.$input .on('focus', $.proxy(this.focus, this)) .on('blur', $.proxy(this.blur, this)) .on('paste', $.proxy(this.paste, this)) .on('keydown', $.proxy(this.keydown, this)) .on('keypress', $.proxy(this.keypress, this)) .on('keyup', $.proxy(this.keyup, this)) this.$copyHelper .on('focus', $.proxy(this.focus, this)) .on('blur', $.proxy(this.blur, this)) .on('keydown', $.proxy(this.keydown, this)) .on('keyup', $.proxy(this.keyup, this)) // Secondary listeners for input width calculation this.$input .on('keypress', $.proxy(this.update, this)) .on('keyup', $.proxy(this.update, this)) this.$input .on('autocompletecreate', function() { // Set minimum autocomplete menu width var $_menuElement = $(this).data('ui-autocomplete').menu.element var minWidth = _self.$wrapper.outerWidth() - parseInt( $_menuElement.css('border-left-width'), 10 ) - parseInt( $_menuElement.css('border-right-width'), 10 ) $_menuElement.css( 'min-width', minWidth + 'px' ) }) .on('autocompleteselect', function (e, ui) { if (_self.createToken( ui.item )) { _self.$input.val('') if (_self.$input.data( 'edit' )) { _self.unedit(true) } } return false }) .on('typeahead:selected', function (e, datum, dataset) { var valueKey = 'value' // Get the actual valueKey for this dataset $.each(_self.$input.data('ttView').datasets, function (i, set) { if (set.name === dataset) { valueKey = set.valueKey } }) // Create token if (_self.createToken( datum[valueKey] )) { _self.$input.typeahead('setQuery', '') if (_self.$input.data( 'edit' )) { _self.unedit(true) } } }) .on('typeahead:autocompleted', function (e, datum, dataset) { _self.createToken( _self.$input.val() ) _self.$input.typeahead('setQuery', '') if (_self.$input.data( 'edit' )) { _self.unedit(true) } }) // Listen to window resize $(window).on('resize', $.proxy(this.update, this )) } , keydown: function (e) { if (!this.focused) return var _self = this switch(e.keyCode) { case 8: // backspace if (!this.$input.is(document.activeElement)) break this.lastInputValue = this.$input.val() break case 37: // left arrow leftRight( this.textDirection === 'rtl' ? 'next': 'prev' ) break case 38: // up arrow upDown('prev') break case 39: // right arrow leftRight( this.textDirection === 'rtl' ? 'prev': 'next' ) break case 40: // down arrow upDown('next') break case 65: // a (to handle ctrl + a) if (this.$input.val().length > 0 || !(e.ctrlKey || e.metaKey)) break this.activateAll() e.preventDefault() break case 9: // tab case 13: // enter // We will handle creating tokens from autocomplete in autocomplete events if (this.$input.data('ui-autocomplete') && this.$input.data('ui-autocomplete').menu.element.find("li:has(a.ui-state-focus)").length) break // We will handle creating tokens from typeahead in typeahead events if (this.$input.hasClass('tt-query') && this.$wrapper.find('.tt-is-under-cursor').length ) break if (this.$input.hasClass('tt-query') && this.$wrapper.find('.tt-hint').val().length) break // Create token if (this.$input.is(document.activeElement) && this.$input.val().length || this.$input.data('edit')) { return this.createTokensFromInput(e, this.$input.data('edit')); } // Edit token if (e.keyCode === 13) { if (!this.$copyHelper.is(document.activeElement) || this.$wrapper.find('.token.active').length !== 1) break if (!_self.options.allowEditing) break this.edit( this.$wrapper.find('.token.active') ) } } function leftRight(direction) { if (_self.$input.is(document.activeElement)) { if (_self.$input.val().length > 0) return direction += 'All' var token = _self.$input.hasClass('tt-query') ? _self.$input.parent()[direction]('.token:first') : _self.$input[direction]('.token:first') if (!token.length) return _self.preventInputFocus = true _self.preventDeactivation = true _self.activate( token ) e.preventDefault() } else { _self[direction]( e.shiftKey ) e.preventDefault() } } function upDown(direction) { if (!e.shiftKey) return if (_self.$input.is(document.activeElement)) { if (_self.$input.val().length > 0) return var token = _self.$input.hasClass('tt-query') ? _self.$input.parent()[direction + 'All']('.token:first') : _self.$input[direction + 'All']('.token:first') if (!token.length) return _self.activate( token ) } var opposite = direction === 'prev' ? 'next' : 'prev' , position = direction === 'prev' ? 'first' : 'last' _self.firstActiveToken[opposite + 'All']('.token').each(function() { _self.deactivate( $(this) ) }) _self.activate( _self.$wrapper.find('.token:' + position), true, true ) e.preventDefault() } this.lastKeyDown = e.keyCode } , keypress: function(e) { this.lastKeyPressCode = e.keyCode this.lastKeyPressCharCode = e.charCode // Comma if ($.inArray( e.charCode, this._triggerKeys) !== -1 && this.$input.is(document.activeElement)) { if (this.$input.val()) { this.createTokensFromInput(e) } return false; } } , keyup: function (e) { this.preventInputFocus = false if (!this.focused) return switch(e.keyCode) { case 8: // backspace if (this.$input.is(document.activeElement)) { if (this.$input.val().length || this.lastInputValue.length && this.lastKeyDown === 8) break this.preventDeactivation = true var prev = this.$input.hasClass('tt-query') ? this.$input.parent().prevAll('.token:first') : this.$input.prevAll('.token:first') if (!prev.length) break this.activate( prev ) } else { this.remove(e) } break case 46: // delete this.remove(e, 'next') break } this.lastKeyUp = e.keyCode } , focus: function (e) { this.focused = true this.$wrapper.addClass('focus') if (this.$input.is(document.activeElement)) { this.$wrapper.find('.active').removeClass('active') this.firstActiveToken = null if (this.options.showAutocompleteOnFocus) { this.search() } } } , blur: function (e) { this.focused = false this.$wrapper.removeClass('focus') if (!this.preventDeactivation && !this.$element.is(document.activeElement)) { this.$wrapper.find('.active').removeClass('active') this.firstActiveToken = null } if (!this.preventCreateTokens && (this.$input.data('edit') && !this.$input.is(document.activeElement) || this.options.createTokensOnBlur )) { this.createTokensFromInput(e) } this.preventDeactivation = false this.preventCreateTokens = false } , paste: function (e) { var _self = this // Add tokens to existing ones setTimeout(function () { _self.createTokensFromInput(e) }, 1) } , change: function (e) { if ( e.initiator === 'tokenfield' ) return // Prevent loops this.setTokens( this.$element.val() ) } , createTokensFromInput: function (e, focus) { if (this.$input.val().length < this.options.minLength) return // No input, simply return var tokensBefore = this.getTokensList() this.setTokens( this.$input.val(), true ) if (tokensBefore == this.getTokensList() && this.$input.val().length) return false // No tokens were added, do nothing (prevent form submit) if (this.$input.hasClass('tt-query')) { // Typeahead acts weird when simply setting input value to empty, // so we set the query to empty instead this.$input.typeahead('setQuery', '') } else { this.$input.val('') } if (this.$input.data( 'edit' )) { this.unedit(focus) } return false // Prevent form being submitted } , next: function (add) { if (add) { var firstActive = this.$wrapper.find('.active:first') , deactivate = firstActive && this.firstActiveToken ? firstActive.index() < this.firstActiveToken.index() : false if (deactivate) return this.deactivate( firstActive ) } var active = this.$wrapper.find('.active:last') , next = active.nextAll('.token:first') if (!next.length) { this.$input.focus() return } this.activate(next, add) } , prev: function (add) { if (add) { var lastActive = this.$wrapper.find('.active:last') , deactivate = lastActive && this.firstActiveToken ? lastActive.index() > this.firstActiveToken.index() : false if (deactivate) return this.deactivate( lastActive ) } var active = this.$wrapper.find('.active:first') , prev = active.prevAll('.token:first') if (!prev.length) { prev = this.$wrapper.find('.token:first') } if (!prev.length && !add) { this.$input.focus() return } this.activate( prev, add ) } , activate: function (token, add, multi, remember) { if (!token) return if (this.$wrapper.find('.token.active').length === this.$wrapper.find('.token').length) return if (typeof remember === 'undefined') var remember = true if (multi) var add = true this.$copyHelper.focus() if (!add) { this.$wrapper.find('.active').removeClass('active') if (remember) { this.firstActiveToken = token } else { delete this.firstActiveToken } } if (multi && this.firstActiveToken) { // Determine first active token and the current tokens indicies // Account for the 1 hidden textarea by subtracting 1 from both var i = this.firstActiveToken.index() - 2 , a = token.index() - 2 , _self = this this.$wrapper.find('.token').slice( Math.min(i, a) + 1, Math.max(i, a) ).each( function() { _self.activate( $(this), true ) }) } token.addClass('active') this.$copyHelper.val( this.getTokensList( null, null, true ) ).select() } , activateAll: function() { var _self = this this.$wrapper.find('.token').each( function (i) { _self.activate($(this), i !== 0, false, false) }) } , deactivate: function(token) { if (!token) return token.removeClass('active') this.$copyHelper.val( this.getTokensList( null, null, true ) ).select() } , toggle: function(token) { if (!token) return token.toggleClass('active') this.$copyHelper.val( this.getTokensList( null, null, true ) ).select() } , edit: function (token) { if (!token) return var value = token.data('value') , label = token.find('.token-label').text() // Allow changing input value before editing var beforeEditEvent = $.Event('beforeEditToken') beforeEditEvent.token = { value: value, label: label } beforeEditEvent.relatedTarget = token.get(0) this.$element.trigger( beforeEditEvent ) if (!beforeEditEvent.token) return value = beforeEditEvent.token.value label = beforeEditEvent.token.label token.find('.token-label').text(value) var tokenWidth = token.outerWidth() var $_input = this.$input.hasClass('tt-query') ? this.$input.parent() : this.$input token.replaceWith( $_input ) this.preventCreateTokens = true this.$input.val( value ) .select() .data( 'edit', true ) .width( tokenWidth ) } , unedit: function (focus) { var $_input = this.$input.hasClass('tt-query') ? this.$input.parent() : this.$input $_input.appendTo( this.$wrapper ) this.$input.data('edit', false) this.update() // Because moving the input element around in DOM // will cause it to lose focus, we provide an option // to re-focus the input after appending it to the wrapper if (focus) { var _self = this setTimeout(function () { _self.$input.focus() }, 1) } } , remove: function (e, direction) { if (this.$input.is(document.activeElement) || this.disabled) return var token = (e.type === 'click') ? $(e.target).closest('.token') : this.$wrapper.find('.token.active') if (e.type !== 'click') { if (!direction) var direction = 'prev' this[direction]() // Was this the first token? if (direction === 'prev') var firstToken = token.first().prevAll('.token:first').length === 0 } // Prepare events var removeEvent = $.Event('removeToken') removeEvent.token = this.getTokenData( token ) var changeEvent = $.Event('change') changeEvent.initiator = 'tokenfield' // Remove token from DOM token.remove() // Trigger events this.$element.val( this.getTokensList() ).trigger( removeEvent ).trigger( changeEvent ) // Focus, when necessary: // When there are no more tokens, or if this was the first token // and it was removed with backspace or it was clicked on if (!this.$wrapper.find('.token').length || e.type === 'click' || firstToken) this.$input.focus() // Adjust input width this.$input.css('width', this.options.minWidth + 'px') this.update() e.preventDefault() e.stopPropagation() } , update: function (e) { var value = this.$input.val() , inputLeftPadding = parseInt(this.$input.css('padding-left'), 10) , inputRightPadding = parseInt(this.$input.css('padding-right'), 10) , inputPadding = inputLeftPadding + inputRightPadding if (this.$input.data('edit')) { if (!value) { value = this.$input.prop("placeholder") } if (value === this.$mirror.text()) return this.$mirror.text(value) var mirrorWidth = this.$mirror.width() + 10; if ( mirrorWidth > this.$wrapper.width() ) { return this.$input.width( this.$wrapper.width() ) } this.$input.width( mirrorWidth ) } else { this.$input.css( 'width', this.options.minWidth + 'px' ) if (this.textDirection === 'rtl') { return this.$input.width( this.$input.offset().left + this.$input.outerWidth() - this.$wrapper.offset().left - parseInt(this.$wrapper.css('padding-left'), 10) - inputPadding - 1 ) } this.$input.width( this.$wrapper.offset().left + this.$wrapper.width() + parseInt(this.$wrapper.css('padding-left'), 10) - this.$input.offset().left - inputPadding ) } } , focusInput: function (e) { if ($(e.target).closest('.token').length || $(e.target).closest('.token-input').length) return // Focus only after the current call stack has cleared, // otherwise has no effect. // Reason: mousedown is too early - input will lose focus // after mousedown. However, since the input may be moved // in DOM, there may be no click or mouseup event triggered. var _self = this setTimeout(function() { _self.$input.focus() }, 0) } , search: function () { if ( this.$input.data('ui-autocomplete') ) { this.$input.autocomplete('search') } } , disable: function () { this.disabled = true; this.$input.prop('disabled', true); this.$element.prop('disabled', true); this.$wrapper.addClass('disabled'); } , enable: function () { this.disabled = false; this.$input.prop('disabled', false); this.$element.prop('disabled', false); this.$wrapper.removeClass('disabled'); } } /* TOKENFIELD PLUGIN DEFINITION * ======================== */ var old = $.fn.tokenfield $.fn.tokenfield = function (option, param) { var value , args = [] Array.prototype.push.apply( args, arguments ); var elements = this.each(function () { var $this = $(this) , data = $this.data('bs.tokenfield') , options = typeof option == 'object' && option if (typeof option === 'string' && data && data[option]) { args.shift() value = data[option].apply(data, args) } else { if (!data) $this.data('bs.tokenfield', (data = new Tokenfield(this, options))) } }) return typeof value !== 'undefined' ? value : elements; } $.fn.tokenfield.defaults = { minWidth: 60, minLength: 0, allowDuplicates: false, allowEditing: true, limit: 0, autocomplete: {}, typeahead: {}, showAutocompleteOnFocus: false, createTokensOnBlur: false, delimiter: ',', beautify: true } $.fn.tokenfield.Constructor = Tokenfield /* TOKENFIELD NO CONFLICT * ================== */ $.fn.tokenfield.noConflict = function () { $.fn.tokenfield = old return this } return Tokenfield; }));
import jwt from 'jsonwebtoken'; import tokens from './tokenStore'; const token = { issue: (payload, secret, options, connectionString) => { let database; return tokens.connect(connectionString).then((db) => { database = db; return tokens.find(database, payload); }) .then((record) => { if (record) { throw new Error('JWT already white listed.'); } return tokens.save(database, payload); }) .then((record) => { if (!record) { throw new Error('Failed to whitelist JWT.'); } return sign(payload, secret, options); }); }, revoke: (decodedToken, connectionString) => tokens.connect(connectionString) .then((db) => tokens.remove(db, decodedToken)), verify: (token, secret, connectionString) => { let decodedToken; return verify(token, secret).then((decoded) => { decodedToken = decoded; return tokens.connect(connectionString); }) .then((db) => tokens.find(db, decodedToken)) .then((record) => new Promise((resolve, reject) => { if (!record) { return reject('JWT is not whitelisted.'); } return resolve(decodedToken); })); } }; function verify(token, secret) { return new Promise((resolve, reject) => jwt.verify(token, secret, (err, decoded) => { if (err) { return reject(err); } return resolve(decoded); })); } function sign(payload, secret, options) { return new Promise((resolve) => { let token = jwt.sign(payload, secret, options); return resolve(token); }); } module.exports = token;
module.exports = function(app , func , mail, upload, storage, mailer, multer, validator, Services, paginate, cors){ app.get("/services/" , servicelist); app.get("/services/view/:id" , serviceview); app.get("/services/add" , serviceadd); app.post("/services/add" , serviceadd); app.get("/services/edit/:id" , serviceedit); app.post("/services/edit/:id" , serviceedit); app.get("/services/delete/:id" , servicedelete); function servicelist(req, res){ var sess = req.session; //req.session.flashmessage = ""; func.isGuestSession(req.session , res); var data = { }; if(req.query.title && validator.trim(req.query.title.trim())){ var searchtitle = req.query.title.trim(); data.title = searchtitle; } if(req.query.price && validator.trim(req.query.price.trim())){ var searchprice = req.query.price.trim(); data.price = searchprice; } if(req.query.cost && validator.trim(req.query.cost.trim())){ var searchcost = req.query.cost.trim(); data.cost = searchcost; } if(req.query.limit){ perPage = req.query.limit; } else { perPage = 1; } page = req.query.page > 0 ? req.query.page:1; Services.find(data).limit(perPage).skip(perPage * (page-1)).sort({'title': 'asc'}).exec(function(err, services){ console.log(services); Services.count().exec(function (err, count) { console.log(count); res.render("services/index" , { services:services, session:sess, pages: count/perPage, count: count, pagelimit:perPage, currentpage:page }); }); }); } function serviceview(req, res){ var sess = req.session; var serviceid = req.params.id; func.isGuestSession(req.session , res); Services.find({_id:serviceid}, function(err, services) { if (err) throw err; console.log(services); res.render("services/view" , { service:services, session:sess }); }); } function servicedelete(req, res){ var sess = req.session; var serviceid = req.params.id; func.isGuestSession(req.session , res); Services.findOneAndRemove({ _id: serviceid }, function(err) { if (err) throw err; console.log('Service successfully deleted!'); sess.flashmessage = "Service detail deleted successfully"; res.redirect("../"); }); } function serviceadd(req, res){ var sess = req.session; var error = []; var data = {}; func.isGuestSession(req.session , res); if(req.method=="POST"){ if(!validator.trim(req.body.title)){ error.push("Enter Title"); } if(!validator.trim(req.body.description)){ error.push("Enter Description"); } if(!validator.trim(req.body.price)){ error.push("Enter Price"); } if(!validator.trim(req.body.cost)){ error.push("Enter Cost"); } if(!validator.trim(req.body.status)){ error.push("Select Status"); } if(error.length<=0){ data = { title:req.body.title.trim(), description:req.body.description.trim(), price:req.body.price.trim(), cost:req.body.cost.trim(), status:req.body.status.trim() }; var detail = new Services(data); detail.save(function(err){ if(err) throw err; console.log('Service saved successfully!'); sess.flashmessage = "Service detail saved successfully"; res.redirect('../services'); }); } else { res.render("services/add" , { service:req.body, errors:error }); } } else { res.render("services/add" , { service:req.body, errors:error }); } } function serviceedit(req, res){ var sess = req.session; var serviceid = req.params.id; var error = []; var data = []; var servicedata = []; func.isGuestSession(req.session , res); if(req.method=="POST"){ if(!validator.trim(req.body.title)){ error.push("Enter Title"); } if(!validator.trim(req.body.description)){ error.push("Enter Description"); } if(!validator.trim(req.body.price)){ error.push("Enter Price"); } if(!validator.trim(req.body.cost)){ error.push("Enter Cost"); } if(!validator.trim(req.body.status)){ error.push("Select Status"); } if(error.length<=0){ var data = { title:req.body.title.trim(), description:req.body.description.trim(), price:req.body.price.trim(), cost:req.body.cost.trim(), status:req.body.status.trim() }; Services.findOneAndUpdate({ _id: serviceid }, data, function(err, services) { if (err) throw err; console.log(services); sess.flashmessage = "Service detail updated successfully"; res.redirect("../"); }); } } Services.find({_id:serviceid}, function(err, services) { if (err) throw err; console.log(services); res.render("services/edit" , { service:services, id:serviceid, errors:error }); }); } }
var i = 0; function timedCount() { i = i + 1; postMessage(i); setTimeout("timedCount()", 500); } timedCount();
const jwt = require('jsonwebtoken'); import { usersData } from '../data/users'; export const checkLogin = (req, res, next) => { let user = usersData.find(({firstName}) => firstName === req.body.firstName); if (!user || user.lastName !== req.body.lastName) { res.status(403).json({success: false, message: 'User or password is invalid'}) } else { user.token = jwt.sign(user, 'enigma', {expiresIn: 3600}) req.user = user; next() } };
import { storiesOf } from '@storybook/polymer'; import { html } from 'lit-html'; import moment from 'moment'; import { object, text } from '@storybook/addon-knobs'; import '@lit-any/lit-any/lit-view'; import ViewTemplates from '@lit-any/lit-any/views'; import { defaultValue } from './knobs'; import basic from './notes/lit-view/basic'; import recursive from './notes/lit-view/recursive'; import recursiveElements from './notes/lit-view/recursive-elements'; import recursiveWithParams from './notes/lit-view/recursive-with-params'; storiesOf('lit-view', module) .add('basic', () => { ViewTemplates.byName('basic') .when .valueMatches(v => v.type === 'Person') .renders(v => html`Hello, my name is ${v.fullName}`); const value = { type: 'Person', fullName: 'Louis Litt', }; return basic(html`<lit-view .value="${defaultValue(object, value)}" template-registry="basic"></lit-view>`); }); storiesOf('lit-view/nesting', module) .add('using callback', () => { ViewTemplates.byName('recursive') .when .valueMatches(value => value.type === 'Person') .renders((person, render) => html`Hello, my name is ${person.fullName}. I was born ${render(person.birthDate)}`); ViewTemplates.byName('recursive').when .valueMatches(value => value instanceof Date || Date.parse(value)) .renders(date => html`${moment(date).fromNow()}`); const value = { type: 'Person', fullName: 'Louis Litt', birthDate: new Date(1976, 8, 12), }; return recursive(html`<lit-view .value="${defaultValue(object, value)}" template-registry="recursive"></lit-view>`); }); storiesOf('lit-view/nesting', module) .add('using view element', () => { ViewTemplates.byName('nested') .when .valueMatches(value => value.type === 'Person') .renders(person => html`Hello, my name is ${person.fullName}. I was born <lit-view .value="${person.birthDate}" template-registry="nested"></lit-view>`); ViewTemplates.byName('nested').when .valueMatches(value => value instanceof Date || Date.parse(value)) .renders(date => html`${moment(date).fromNow()}`); const value = { type: 'Person', fullName: 'Louis Litt', birthDate: new Date(1976, 8, 12), }; return recursiveElements(html`<lit-view .value="${defaultValue(object, value)}" template-registry="nested"></lit-view>`); }); storiesOf('lit-view/nesting', module) .add('passing context params', () => { ViewTemplates.byName('recursive-with-params') .when .valueMatches(value => value.type === 'Person') .renders((person, render) => { const params = { format: text('Date format', 'LL'), }; return html`Hello, my name is ${person.fullName}. I was born on ${render(person.birthDate, params)}`; }); ViewTemplates.byName('recursive-with-params').when .valueMatches(value => value instanceof Date || Date.parse(value)) .renders((date, next, scope, params) => html`${moment(date).format(params.format)}`); const value = { type: 'Person', fullName: 'Louis Litt', birthDate: new Date(1976, 8, 12), }; return recursiveWithParams(html`<lit-view .value="${defaultValue(object, value)}" template-registry="recursive-with-params"></lit-view>`); });
/* * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ define(function (require, exports, module) { "use strict"; var Immutable = require("immutable"); /** * @constructor * @param {object} model */ var HistoryState = Immutable.Record({ /** * @type {Document} */ document: null, /** * @type {DocumentExports} */ documentExports: null, /** * @type {string} */ name: null, /** * @type {number} */ id: null, /** * @type {boolean} */ rogue: false }); /** * Return true if either a document or documentExports is provided, * and it is not equal to its associated property on this object * * @param {Document} document * @param {DocumentExports} documentExports * @return {boolean} */ HistoryState.prototype.isInconsistent = function (document, documentExports) { return (this.document && this.document !== document) || (this.documentExports && this.documentExports !== documentExports); }; module.exports = HistoryState; });
// Wait till the browser is ready to render the game (avoids glitches) window.requestAnimationFrame(function () { new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager); });
#!/usr/bin/env node /* eslint-disable */ const pkg = require('../package.json') console.log(pkg.version) process.exit()
webpackJsonp([60335399758886],{87:function(t,a){t.exports={data:{site:{siteMetadata:{title:"Barricade Records"}}},layoutContext:{}}}}); //# sourceMappingURL=path----ae8e548c4bb56394be0b.js.map
export {default} from './Button'; export {default as Button, buttonFactory} from './Button';
/*! Sly 1.0.0-rc.6 - 6th Feb 2013 | https://github.com/Darsain/sly */ (function(h,w,Q){function $(f,a,ea){var ia,n,ja,x,w,J;function F(c,ya){if(G&&b.released){var g=ka(c),pa=c>d.start&&c<d.end;R?(pa&&(c=m[g.centerItem].center),B&&e.activate(g.centerItem,1)):pa&&(c=m[g.firstItem].start)}!b.released&&"slidee"===b.source&&a.elasticBounds?c>d.end?c=d.end+(c-d.end)/6:c<d.start&&(c=d.start+(c-d.start)/6):c=H(c,d.start,d.end);ia=+new Date;n=0;ja=d.cur;x=c;w=c-d.cur;J=ya;d.dest=c;b.released&&!S&&e.cycle();h.extend(j,ka(void 0));$();aa[0]&&I.page!==j.activePage&&(I.page=j.activePage, aa.removeClass(a.activeClass).eq(j.activePage).addClass(a.activeClass));c!==d.cur&&(z("change"),M||L())}function L(){M?(J||(!b.released?"slidee"===b.source:33>a.speed)?d.cur=x:!b.released&&"handle"===b.source?d.cur+=(x-d.cur)*a.syncFactor:(n=Math.min(+new Date-ia,a.speed),d.cur=ja+w*jQuery.easing[a.easing](n/a.speed,n,0,1,a.speed)),x===Math.round(d.cur)&&(!b.released||n>=a.speed)?(d.cur=d.dest,M=0):M=fa(L),z("move"),C||(A?s[0].style[A]=la+(a.horizontal?"translateX":"translateY")+"("+-d.cur+"px)": s[0].style[a.horizontal?"left":"top"]=-Math.round(d.cur)+"px"),!M&&b.released&&z("moveEnd"),O()):(M=fa(L),b.released&&z("moveStart"))}function O(){y&&(q.cur=d.start===d.end?0:((!b.released&&"handle"===b.source?d.dest:d.cur)-d.start)/(d.end-d.start)*q.end,q.cur=H(Math.round(q.cur),q.start,q.end),I.hPos!==q.cur&&(I.hPos=q.cur,A?y[0].style[A]=la+(a.horizontal?"translateX":"translateY")+"("+q.cur+"px)":y[0].style[a.horizontal?"left":"top"]=q.cur+"px"))}function P(c,a,g){"boolean"===typeof a&&(g=a,a=Q); a===Q?F(d[c]):R&&"center"!==c||(a=e.getPos(a))&&F(a[c],g)}function ma(c){return T(c)?H(c,0,m.length-1):c===Q?-1:t.index(c)}function ka(c){c=H(T(c)?c:d.dest,d.start,d.end);var a={},g=B?0:u/2;if(!C)for(var b=0,e=v.length;b<e;b++){if(c>=d.end||b===v.length-1){a.activePage=v.length-1;break}if(c<=v[b]+g){a.activePage=b;break}}if(G){for(var e=b=g=!1,f=0,j=m.length;f<j;f++){!1===g&&c<=m[f].start&&(g=f);!1===e&&c-m[f].size/2<=m[f].center&&(e=f);if(f===m.length-1||!1===b&&c<m[f+1].end)b=f;if(!1!==b)break}a.firstItem= T(g)?g:0;a.centerItem=T(e)?e:a.firstItem;a.lastItem=T(b)?b:a.centerItem}return a}function $(){if(G){var c=0===j.activeItem,b=j.activeItem>=m.length-1,g=c?"first":b?"last":"middle";I.itemsButtonState!==g&&(I.itemsButtonState=g,U.is("button,input")&&U.prop("disabled",c),V.is("button,input")&&V.prop("disabled",b),U[c?"removeClass":"addClass"](a.disabledClass),V[b?"removeClass":"addClass"](a.disabledClass))}aa[0]&&(c=d.dest<=d.start,b=d.dest>=d.end,g=c?"first":b?"last":"middle",I.pagesButtonState!==g&& (I.pagesButtonState=g,W.is("button,input")&&W.prop("disabled",c),X.is("button,input")&&X.prop("disabled",b),W[c?"removeClass":"addClass"](a.disabledClass),X[b?"removeClass":"addClass"](a.disabledClass)))}function da(a){return Math.round(H(a,q.start,q.end)/q.end*(d.end-d.start))+d.start}function qa(c){var e="touchstart"===c.type,g=c.data.source,f="slidee"===g;if(e||1>=c.which)r(c),b.source=g,b.$source=h(c.target),b.init=0,b.released=0,b.touch=e,b.initLoc=(e?c.originalEvent.touches[0]:c)[a.horizontal? "pageX":"pageY"],b.initPos=f?d.cur:q.cur,b.start=+new Date,b.time=0,b.path=0,b.pathMin=f?-b.initLoc:-q.cur,b.pathMax=f?document[a.horizontal?"width":"height"]-b.initLoc:q.end-q.cur,(f?s:y).addClass(a.draggedClass),ga.on(e?ra:sa,ta)}function ta(c){b.released="mouseup"===c.type||"touchend"===c.type;b.path=H((b.touch?c.originalEvent[b.released?"changedTouches":"touches"][0]:c)[a.horizontal?"pageX":"pageY"]-b.initLoc,b.pathMin,b.pathMax);if(!b.init&&(Math.abs(b.path)>(b.touch?50:10)||"handle"===b.source))b.init= 1,"slidee"===b.source&&(ha=1),e.pause(1),b.$source.on("click",function g(a){r(a,1);"slidee"===b.source&&(ha=0);b.$source.off("click",g)}),z("moveStart");b.init&&(r(c),b.released&&("slidee"===b.source&&33<a.speed)&&(b.path+=200*b.path/(+new Date-b.start)),F("slidee"===b.source?Math.round(b.initPos-b.path):da(b.initPos+b.path)));b.released&&(ga.off(b.touch?ra:sa,ta),("slidee"===b.source?s:y).removeClass(a.draggedClass),d.cur===d.dest&&z("moveEnd"))}function z(c,b,g,e,h){switch(c){case "active":g=b; b=t;break;case "activePage":g=b;b=v;break;default:h=b,b=d,g=t,e=j}if(l[c])for(var k=0,m=l[c].length;k<m;k++)l[c][k].call(f,b,g,e,h);a.domEvents&&!C&&D.trigger(ba+":"+c,[b,g,e,h])}a=h.extend({},h.fn[ba].defaults,a);var e=this,ua=0,C=T(f),ga=h(document),D=h(f),s=D.children().eq(0),u=0,p=0,d={start:0,center:0,end:0,cur:0,dest:0},E=h(a.scrollBar).eq(0),y=E.length?E.children().eq(0):0,ca=0,N=0,q={start:0,end:0,cur:0},Y=h(a.pagesBar),aa=0,v=[],na="basic"===a.itemNav,va="smart"===a.itemNav,B="forceCentered"=== a.itemNav,R="centered"===a.itemNav||B,G=!C&&(na||va||R||B),t=0,m=[],j={firstItem:0,lastItem:1,centerItem:1,activeItem:-1,activePage:0,items:0,pages:0},wa=a.scrollSource?h(a.scrollSource):D,oa=a.dragSource?h(a.dragSource):D,U=h(a.prev),V=h(a.next),W=h(a.prevPage),X=h(a.nextPage),l={},I={};J=w=x=ja=n=ia=void 0;var b={released:1},xa="touchstart."+k+" mousedown."+k,sa="mousemove."+k+" mouseup."+k,ra="touchmove."+k+" touchend."+k,M=0,K=0,S=0,ha=0,za=e.reload=function(){var c=0;d.old=h.extend({},d);u=C? 0:D[a.horizontal?"width":"height"]();ca=E[a.horizontal?"width":"height"]();p=C?f:s[a.horizontal?"outerWidth":"outerHeight"]();v=[];d.start=0;d.end=Math.max(p-u,0);I={};if(G){t=s.children(":visible");j.items=t.length;m=[];var b=Z(s,a.horizontal?"paddingLeft":"paddingTop"),g=Z(s,a.horizontal?"paddingRight":"paddingBottom"),k=Z(t,a.horizontal?"marginLeft":"marginTop"),c=Z(t.slice(-1),a.horizontal?"marginRight":"marginBottom"),ea=0,n="none"!==t.css("float"),c=k?0:c;p=0;t.each(function(c,e){var d=h(e), f=d[a.horizontal?"outerWidth":"outerHeight"](!0),j=Z(d,a.horizontal?"marginLeft":"marginTop"),d=Z(d,a.horizontal?"marginRight":"marginBottom"),l={size:f,start:p-(!c||a.horizontal?0:j),center:p-Math.round(u/2-f/2),end:p-u+f-(k?0:d)};c||(ea=-(B?Math.round(u/2-f/2):0)+b,p+=b);p+=f;!a.horizontal&&!n&&d&&(j&&0<c)&&(p-=Math.min(j,d));c===t.length-1&&(p+=g);m.push(l)});s[0].style[a.horizontal?"width":"height"]=p+"px";p-=c;d.start=ea;d.end=B?m[m.length-1].center:Math.max(p-u,0);j.activeItem>=m.length?e.activate(m.length- 1):1===m.length&&t.eq(j.activeItem).addClass(a.activeClass)}d.center=Math.round(d.end/2+d.start/2);h.extend(j,ka(void 0));y&&(N=a.dynamicHandle?Math.round(ca*u/p):y[a.horizontal?"outerWidth":"outerHeight"](),a.dynamicHandle&&(N=H(N,a.minHandleSize,ca),y[0].style[a.horizontal?"width":"height"]=N+"px"),q.end=ca-N,M||O());if(!C){var l=d.start,c="",x=0;if(G)h.each(m,function(a,c){if(B||c.start+c.size>l)l=c[B?"center":"start"],v.push(l),l+=u});else for(;l-u<=d.end;)v.push(l),l+=u;if(Y[0]){for(var r=0;r< v.length;r++)c+=a.pageBuilder(x++);aa=h(c).appendTo(Y.empty())}}F(H(d.dest,d.start,d.end));j.pages=v.length;j.slideeSize=p;j.frameSize=u;j.sbSize=ca;j.handleSize=N;z("load")};e.getPos=function(c){if(c===Q)return d;if(G)return c=ma(c),-1!==c?m[c]:!1;var b=s.find(c).eq(0);return b[0]?(c=a.horizontal?b.offset().left-s.offset().left:b.offset().top-s.offset().top,b=b[a.horizontal?"outerWidth":"outerHeight"](),{start:c,center:c-u/2+b/2,end:c-u+b,size:b}):!1};e.getRel=function(){return j};e.prev=function(){e.activate(j.activeItem- 1)};e.next=function(){e.activate(j.activeItem+1)};e.prevPage=function(){e.activatePage(j.activePage-1)};e.nextPage=function(){e.activatePage(j.activePage+1)};e.slideBy=function(c,a){F(d.dest+c,a)};e.slideTo=function(a,b){F(a,b)};e.toStart=function(a,b){P("start",a,b)};e.toEnd=function(a,b){P("end",a,b)};e.toCenter=function(a,b){P("center",a,b)};e.activate=function(c,d){if(G&&c!==Q){var g=ma(c),f=j.activeItem;j.activeItem=g;t.eq(f).removeClass(a.activeClass);t.eq(g).addClass(a.activeClass);$();g!== f&&z("active",g);d||(R?e.toCenter(g):va&&(g>=j.lastItem?e.toStart(g):g<=j.firstItem?e.toEnd(g):b.released&&!S&&e.cycle()))}};e.activatePage=function(a){v.length&&(a=H(a,0,v.length-1),F(v[a]),z("activePage",a))};e.cycle=function(c){if(a.cycleBy&&a.cycleInterval&&!("items"===a.cycleBy&&!m[0]||c&&S))S=0,K?K=clearTimeout(K):z("cycleStart"),K=setTimeout(function(){switch(a.cycleBy){case "items":e.activate(j.activeItem>=m.length-1?0:j.activeItem+1);break;case "pages":e.activatePage(j.activePage>=v.length- 1?0:j.activePage+1)}z("cycle")},a.cycleInterval)};e.pause=function(a){a||(S=!0);K&&(K=clearTimeout(K),z("cyclePause"))};e.toggle=function(){e[K?"pause":"cycle"]()};e.set=function(c,b){h.isPlainObject(c)?h.extend(a,c):a.hasOwnProperty(c)&&(a[c]=b)};e.on=function(a,b){if("object"===typeof a)for(var g in a){if(a.hasOwnProperty(g))e.on(g,a[g])}else if(b instanceof Array){g=0;for(var d=b.length;g<d;g++)e.on(a,b[g])}else if("function"===typeof b){l[a]=l[a]||[];g=0;for(d=l[a].length;g<d;g++)if(l[a][g]=== b)return;l[a].push(b)}};e.off=function(a,b){if(l[a])if(b instanceof Array)for(var g=0,d=b.length;g<d;g++)e.off(a,b[g]);else if("function"===typeof b){g=0;for(d=l[a].length;g<d;g++)l[a][g]===b&&l[a].splice(g,1)}else l[a].length=0};e.destroy=function(){ga.add(s).add(wa).add(y).add(E).add(Y).add(U).add(V).add(W).add(X).unbind("."+k);U.add(V).add(W).add(X).removeClass(a.disabledClass);t&&t.eq(j.activeItem).removeClass(a.activeClass);Y.empty();C||(D.unbind("."+k),s.add(y).css(A||(a.horizontal?"left":"top"), A?"none":0),h.removeData(f,k))};e.init=function(){if(!ua){e.on(ea);if(!C){D.css("overflow","hidden");var b=s.add(y);if(A){var f={};f[A]="translateZ(0)";b.css(f)}else"static"===D.css("position")&&D.css("position","relative"),b.css({position:"absolute"})}!A&&"static"===E.css("position")&&E.css("position","relative");za();G?e.activate(a.startAt):F(a.startAt);if(a.scrollBy)wa.on("DOMMouseScroll."+k+" mousewheel."+k,function(b){if(d.start!==d.end){r(b,1);b=b.originalEvent;var c=0;b.wheelDelta&&(c=0>b.wheelDelta/ 120);b.detail&&(c=0>-b.detail/3);G?(b=ma((R?B?j.activeItem:j.centerItem:j.firstItem)+(c?a.scrollBy:-a.scrollBy)),e[R?B?"activate":"toCenter":"toStart"](b)):e.slideBy(c?a.scrollBy:-a.scrollBy)}});if(a.clickBar&&E[0])E.on("click."+k,function(b){1>=b.which&&(r(b),F(da((a.horizontal?b.clientX-E.offset().left:b.clientY-E.offset().top)-N/2)))});a.keyboardNavBy&&ga.bind("keydown."+k,function(b){switch(b.which){case a.horizontal?37:38:r(b);e["pages"===a.keyboardNavBy?"prevPage":"prev"]();break;case a.horizontal? 39:40:r(b),e["pages"===a.keyboardNavBy?"nextPage":"next"]()}});if(a.prev)U.on("click."+k,function(a){r(a);e.prev()});if(a.next)V.on("click."+k,function(a){r(a);e.next()});if(a.prevPage)W.on("click."+k,function(a){r(a);e.prevPage()});if(a.nextPage)X.on("click."+k,function(a){r(a);e.nextPage()});s.on("click."+k,"*",function(a){1>=a.which&&(this.parentNode===a.delegateTarget&&!ha)&&e.activate(this);ha=0});if(Y[0])Y.on("click."+k,"*",function(){e.activatePage(aa.index(this))});if(a.dragging)oa.on(xa, {source:"slidee"},qa);if(a.dragHandle&&y)y.on(xa,{source:"handle"},qa);if(a.cycleBy&&!C){if(a.pauseOnHover)D.on("mouseenter."+k+" mouseleave."+k,function(a){if(!S)e["mouseenter"===a.type?"pause":"cycle"](1)});e[a.startPaused?"pause":"cycle"]()}ua=1;return e}}}function r(f,a){f=f||w.event;f.preventDefault?f.preventDefault():f.returnValue=!1;a&&(f.stopPropagation?f.stopPropagation():f.cancelBubble=!0)}function T(f){return!isNaN(parseFloat(f))&&isFinite(f)}function Z(f,a){return parseInt(f.css(a),10)|| 0}function H(f,a,h){return f<a?a:f>h?h:f}for(var ba="sly",k=ba,n=w.cancelAnimationFrame||w.cancelRequestAnimationFrame,fa=w.requestAnimationFrame,A,la,L=window,O=["moz","webkit","o"],da=0,J=0,na=O.length;J<na&&!n;++J)fa=(n=L[O[J]+"CancelAnimationFrame"]||L[O[J]+"CancelRequestAnimationFrame"])&&L[O[J]+"RequestAnimationFrame"];n||(fa=function(f){var a=+new Date,h=Math.max(0,16-(a-da));da=a+h;return L.setTimeout(function(){f(a+h)},h)},n=function(f){clearTimeout(f)});var n=function(f){for(var a=0,h=P.length;a< h;a++){var k=P[a]?P[a]+f.charAt(0).toUpperCase()+f.slice(1):f;if(oa.style[k]!==Q)return k}},P=["","webkit","moz","ms","o"],oa=document.createElement("div");A=n("transform");la=n("perspective")?"translateZ(0) ":"";w.Sly=$;h.fn[ba]=function(f,a){var n,r;if(!h.isPlainObject(f)){if("string"===typeof f||!1===f)n=!1===f?"destroy":f,r=Array.prototype.slice.call(arguments,1);f={}}return this.each(function(A,w){var x=h.data(w,k);!x&&!n?h.data(w,k,(new $(w,f,a)).init()):x&&n&&x[n]&&x[n].apply(x,r)})};h.fn[ba].defaults= {horizontal:0,itemNav:null,scrollBar:null,dragHandle:0,dynamicHandle:0,minHandleSize:50,clickBar:0,syncFactor:0.5,pagesBar:null,pageBuilder:function(f){return"<li>"+(f+1)+"</li>"},prev:null,next:null,prevPage:null,nextPage:null,cycleBy:null,cycleInterval:5E3,pauseOnHover:0,startPaused:0,scrollBy:0,dragging:0,elasticBounds:0,speed:0,easing:"swing",scrollSource:null,dragSource:null,startAt:0,keyboardNavBy:0,domEvents:0,draggedClass:"dragged",activeClass:"active",disabledClass:"disabled"}})(jQuery,window);
/** * @author Richard Davey <rich@photonstorm.com> * @author Pavle Goloskokovic <pgoloskokovic@gmail.com> (http://prunegames.com) * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var BaseSound = require('../BaseSound'); var Class = require('../../utils/Class'); /** * @classdesc * HTML5 Audio implementation of the sound. * * @class HTML5AudioSound * @extends Phaser.Sound.BaseSound * @memberOf Phaser.Sound * @constructor * @since 3.0.0 * * @param {Phaser.Sound.HTML5AudioSoundManager} manager - Reference to the current sound manager instance. * @param {string} key - Asset key for the sound. * @param {SoundConfig} [config={}] - An optional config object containing default sound settings. */ var HTML5AudioSound = new Class({ Extends: BaseSound, initialize: function HTML5AudioSound (manager, key, config) { if (config === undefined) { config = {}; } /** * An array containing all HTML5 Audio tags that could be used for individual * sound's playback. Number of instances depends on the config value passed * to the Loader#audio method call, default is 1. * * @name Phaser.Sound.HTML5AudioSound#tags * @type {HTMLAudioElement[]} * @private * @since 3.0.0 */ this.tags = manager.game.cache.audio.get(key); if (!this.tags) { // eslint-disable-next-line no-console console.warn('Audio cache entry missing: ' + key); return; } /** * Reference to an HTML5 Audio tag used for playing sound. * * @name Phaser.Sound.HTML5AudioSound#audio * @type {HTMLAudioElement} * @private * @default null * @since 3.0.0 */ this.audio = null; /** * Timestamp as generated by the Request Animation Frame or SetTimeout * representing the time at which the delayed sound playback should start. * Set to 0 if sound playback is not delayed. * * @name Phaser.Sound.HTML5AudioSound#startTime * @type {number} * @private * @default 0 * @since 3.0.0 */ this.startTime = 0; /** * Audio tag's playback position recorded on previous * update method call. Set to 0 if sound is not playing. * * @name Phaser.Sound.HTML5AudioSound#previousTime * @type {number} * @private * @default 0 * @since 3.0.0 */ this.previousTime = 0; this.duration = this.tags[0].duration; this.totalDuration = this.tags[0].duration; BaseSound.call(this, manager, key, config); }, /** * @event Phaser.Sound.HTML5AudioSound#playEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. */ /** * Play this sound, or a marked section of it. * It always plays the sound from the start. If you want to start playback from a specific time * you can set 'seek' setting of the config object, provided to this call, to that value. * * @method Phaser.Sound.HTML5AudioSound#play * @fires Phaser.Sound.HTML5AudioSound#playEvent * @since 3.0.0 * * @param {string} [markerName=''] - If you want to play a marker then provide the marker name here, otherwise omit it to play the full sound. * @param {SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. * * @return {boolean} Whether the sound started playing successfully. */ play: function (markerName, config) { if (this.manager.isLocked(this, 'play', [ markerName, config ])) { return false; } if (!BaseSound.prototype.play.call(this, markerName, config)) { return false; } // \/\/\/ isPlaying = true, isPaused = false \/\/\/ if (!this.pickAndPlayAudioTag()) { return false; } this.emit('play', this); return true; }, /** * @event Phaser.Sound.HTML5AudioSound#pauseEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. */ /** * Pauses the sound. * * @method Phaser.Sound.HTML5AudioSound#pause * @fires Phaser.Sound.HTML5AudioSound#pauseEvent * @since 3.0.0 * * @return {boolean} Whether the sound was paused successfully. */ pause: function () { if (this.manager.isLocked(this, 'pause')) { return false; } if (this.startTime > 0) { return false; } if (!BaseSound.prototype.pause.call(this)) { return false; } // \/\/\/ isPlaying = false, isPaused = true \/\/\/ this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); this.stopAndReleaseAudioTag(); this.emit('pause', this); return true; }, /** * @event Phaser.Sound.HTML5AudioSound#resumeEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. */ /** * Resumes the sound. * * @method Phaser.Sound.HTML5AudioSound#resume * @fires Phaser.Sound.HTML5AudioSound#resumeEvent * @since 3.0.0 * * @return {boolean} Whether the sound was resumed successfully. */ resume: function () { if (this.manager.isLocked(this, 'resume')) { return false; } if (this.startTime > 0) { return false; } if (!BaseSound.prototype.resume.call(this)) { return false; } // \/\/\/ isPlaying = true, isPaused = false \/\/\/ if (!this.pickAndPlayAudioTag()) { return false; } this.emit('resume', this); return true; }, /** * @event Phaser.Sound.HTML5AudioSound#stopEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. */ /** * Stop playing this sound. * * @method Phaser.Sound.HTML5AudioSound#stop * @fires Phaser.Sound.HTML5AudioSound#stopEvent * @since 3.0.0 * * @return {boolean} Whether the sound was stopped successfully. */ stop: function () { if (this.manager.isLocked(this, 'stop')) { return false; } if (!BaseSound.prototype.stop.call(this)) { return false; } // \/\/\/ isPlaying = false, isPaused = false \/\/\/ this.stopAndReleaseAudioTag(); this.emit('stop', this); return true; }, /** * Used internally to do what the name says. * * @method Phaser.Sound.HTML5AudioSound#pickAndPlayAudioTag * @private * @since 3.0.0 * * @return {boolean} Whether the sound was assigned an audio tag successfully. */ pickAndPlayAudioTag: function () { if (!this.pickAudioTag()) { this.reset(); return false; } var seek = this.currentConfig.seek; var delay = this.currentConfig.delay; var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; this.previousTime = offset; this.audio.currentTime = offset; this.applyConfig(); if (delay === 0) { this.startTime = 0; if (this.audio.paused) { this.playCatchPromise(); } } else { this.startTime = window.performance.now() + delay * 1000; if (!this.audio.paused) { this.audio.pause(); } } this.resetConfig(); return true; }, /** * This method performs the audio tag pooling logic. It first looks for * unused audio tag to assign to this sound object. If there are no unused * audio tags, based on HTML5AudioSoundManager#override property value, it * looks for sound with most advanced playback and hijacks its audio tag or * does nothing. * * @method Phaser.Sound.HTML5AudioSound#pickAudioTag * @private * @since 3.0.0 * * @return {boolean} Whether the sound was assigned an audio tag successfully. */ pickAudioTag: function () { if (this.audio) { return true; } for (var i = 0; i < this.tags.length; i++) { var audio = this.tags[i]; if (audio.dataset.used === 'false') { audio.dataset.used = 'true'; this.audio = audio; return true; } } if (!this.manager.override) { return false; } var otherSounds = []; this.manager.forEachActiveSound(function (sound) { if (sound.key === this.key && sound.audio) { otherSounds.push(sound); } }, this); otherSounds.sort(function (a1, a2) { if (a1.loop === a2.loop) { // sort by progress return (a2.seek / a2.duration) - (a1.seek / a1.duration); } return a1.loop ? 1 : -1; }); var selectedSound = otherSounds[0]; this.audio = selectedSound.audio; selectedSound.reset(); selectedSound.audio = null; selectedSound.startTime = 0; selectedSound.previousTime = 0; return true; }, /** * Method used for playing audio tag and catching possible exceptions * thrown from rejected Promise returned from play method call. * * @method Phaser.Sound.HTML5AudioSound#playCatchPromise * @private * @since 3.0.0 */ playCatchPromise: function () { var playPromise = this.audio.play(); if (playPromise) { // eslint-disable-next-line no-unused-vars playPromise.catch(function (reason) { console.warn(reason); }); } }, /** * Used internally to do what the name says. * * @method Phaser.Sound.HTML5AudioSound#stopAndReleaseAudioTag * @private * @since 3.0.0 */ stopAndReleaseAudioTag: function () { this.audio.pause(); this.audio.dataset.used = 'false'; this.audio = null; this.startTime = 0; this.previousTime = 0; }, /** * Method used internally to reset sound state, usually when stopping sound * or when hijacking audio tag from another sound. * * @method Phaser.Sound.HTML5AudioSound#reset * @private * @since 3.0.0 */ reset: function () { BaseSound.prototype.stop.call(this); }, /** * Method used internally by sound manager for pausing sound if * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. * * @method Phaser.Sound.HTML5AudioSoundManager#onBlur * @private * @since 3.0.0 */ onBlur: function () { this.isPlaying = false; this.isPaused = true; this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); this.currentConfig.delay = Math.max(0, (this.startTime - window.performance.now()) / 1000); this.stopAndReleaseAudioTag(); }, /** * Method used internally by sound manager for resuming sound if * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. * * @method Phaser.Sound.HTML5AudioSound#onFocus * @private * @since 3.0.0 */ onFocus: function () { this.isPlaying = true; this.isPaused = false; this.pickAndPlayAudioTag(); }, /** * @event Phaser.Sound.HTML5AudioSound#loopedEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. */ /** * @event Phaser.Sound.HTML5AudioSound#endedEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. */ /** * Update method called automatically by sound manager on every game step. * * @method Phaser.Sound.HTML5AudioSound#update * @fires Phaser.Sound.HTML5AudioSound#loopedEvent * @fires Phaser.Sound.HTML5AudioSound#endedEvent * @protected * @since 3.0.0 * * @param {number} time - The current timestamp as generated by the Request Animation Frame or SetTimeout. * @param {number} delta - The delta time elapsed since the last frame. */ // eslint-disable-next-line no-unused-vars update: function (time, delta) { if (!this.isPlaying) { return; } // handling delayed playback if (this.startTime > 0) { if (this.startTime < time - this.manager.audioPlayDelay) { this.audio.currentTime += Math.max(0, time - this.startTime) / 1000; this.startTime = 0; this.previousTime = this.audio.currentTime; this.playCatchPromise(); } return; } // handle looping and ending var startTime = this.currentMarker ? this.currentMarker.start : 0; var endTime = startTime + this.duration; var currentTime = this.audio.currentTime; if (this.currentConfig.loop) { if (currentTime >= endTime - this.manager.loopEndOffset) { this.audio.currentTime = startTime + Math.max(0, currentTime - endTime); currentTime = this.audio.currentTime; } else if (currentTime < startTime) { this.audio.currentTime += startTime; currentTime = this.audio.currentTime; } if (currentTime < this.previousTime) { this.emit('looped', this); } } else if (currentTime >= endTime) { this.reset(); this.stopAndReleaseAudioTag(); this.emit('ended', this); return; } this.previousTime = currentTime; }, /** * Calls Phaser.Sound.BaseSound#destroy method * and cleans up all HTML5 Audio related stuff. * * @method Phaser.Sound.HTML5AudioSound#destroy * @since 3.0.0 */ destroy: function () { BaseSound.prototype.destroy.call(this); this.tags = null; if (this.audio) { this.stopAndReleaseAudioTag(); } }, /** * Method used internally to determine mute setting of the sound. * * @method Phaser.Sound.HTML5AudioSound#updateMute * @private * @since 3.0.0 */ updateMute: function () { if (this.audio) { this.audio.muted = this.currentConfig.mute || this.manager.mute; } }, /** * Method used internally to calculate total volume of the sound. * * @method Phaser.Sound.HTML5AudioSound#updateVolume * @private * @since 3.0.0 */ updateVolume: function () { if (this.audio) { this.audio.volume = this.currentConfig.volume * this.manager.volume; } }, /** * Method used internally to calculate total playback rate of the sound. * * @method Phaser.Sound.HTML5AudioSound#calculateRate * @protected * @since 3.0.0 */ calculateRate: function () { BaseSound.prototype.calculateRate.call(this); if (this.audio) { this.audio.playbackRate = this.totalRate; } }, /** * @event Phaser.Sound.HTML5AudioSound#muteEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. * @param {boolean} value - An updated value of Phaser.Sound.HTML5AudioSound#mute property. */ /** * Boolean indicating whether the sound is muted or not. * Gets or sets the muted state of this sound. * * @name Phaser.Sound.HTML5AudioSound#mute * @type {boolean} * @default false * @since 3.0.0 */ mute: { get: function () { return this.currentConfig.mute; }, set: function (value) { this.currentConfig.mute = value; if (this.manager.isLocked(this, 'mute', value)) { return; } this.emit('mute', this, value); } }, /** * Sets the muted state of this Sound. * * @method Phaser.Sound.HTML5AudioSound#setMute * @fires Phaser.Sound.HTML5AudioSound#muteEvent * @since 3.4.0 * * @param {boolean} value - `true` to mute this sound, `false` to unmute it. * * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. */ setMute: function (value) { this.mute = value; return this; }, /** * @event Phaser.Sound.HTML5AudioSound#volumeEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. * @param {number} value - An updated value of Phaser.Sound.HTML5AudioSound#volume property. */ /** * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). * * @name Phaser.Sound.HTML5AudioSound#volume * @type {number} * @default 1 * @since 3.0.0 */ volume: { get: function () { return this.currentConfig.volume; }, set: function (value) { this.currentConfig.volume = value; if (this.manager.isLocked(this, 'volume', value)) { return; } this.emit('volume', this, value); } }, /** * Sets the volume of this Sound. * * @method Phaser.Sound.HTML5AudioSound#setVolume * @fires Phaser.Sound.HTML5AudioSound#volumeEvent * @since 3.4.0 * * @param {number} value - The volume of the sound. * * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. */ setVolume: function (value) { this.volume = value; return this; }, /** * @event Phaser.Sound.HTML5AudioSound#rateEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted the event. * @param {number} value - An updated value of Phaser.Sound.HTML5AudioSound#rate property. */ /** * Rate at which this Sound will be played. * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed * and 2.0 doubles the audios playback speed. * * @name Phaser.Sound.HTML5AudioSound#rate * @type {number} * @default 1 * @since 3.0.0 */ rate: { get: function () { return this.currentConfig.rate; }, set: function (value) { this.currentConfig.rate = value; if (this.manager.isLocked(this, 'rate', value)) { return; } else { this.calculateRate(); this.emit('rate', this, value); } } }, /** * Sets the playback rate of this Sound. * * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed * and 2.0 doubles the audios playback speed. * * @method Phaser.Sound.HTML5AudioSound#setRate * @fires Phaser.Sound.HTML5AudioSound#rateEvent * @since 3.3.0 * * @param {number} value - The playback rate at of this Sound. * * @return {Phaser.Sound.HTML5AudioSound} This Sound. */ setRate: function (value) { this.rate = value; return this; }, /** * @event Phaser.Sound.HTML5AudioSound#detuneEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the Sound that emitted event. * @param {number} value - An updated value of Phaser.Sound.HTML5AudioSound#detune property. */ /** * The detune value of this Sound, given in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29). * The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). * * @name Phaser.Sound.HTML5AudioSound#detune * @type {number} * @default 0 * @since 3.0.0 */ detune: { get: function () { return this.currentConfig.detune; }, set: function (value) { this.currentConfig.detune = value; if (this.manager.isLocked(this, 'detune', value)) { return; } else { this.calculateRate(); this.emit('detune', this, value); } } }, /** * Sets the detune value of this Sound, given in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29). * The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). * * @method Phaser.Sound.HTML5AudioSound#setDetune * @fires Phaser.Sound.HTML5AudioSound#detuneEvent * @since 3.3.0 * * @param {number} value - The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). * * @return {Phaser.Sound.HTML5AudioSound} This Sound. */ setDetune: function (value) { this.detune = value; return this; }, /** * @event Phaser.Sound.HTML5AudioSound#seekEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. * @param {number} value - An updated value of Phaser.Sound.HTML5AudioSound#seek property. */ /** * Property representing the position of playback for this sound, in seconds. * Setting it to a specific value moves current playback to that position. * The value given is clamped to the range 0 to current marker duration. * Setting seek of a stopped sound has no effect. * * @name Phaser.Sound.HTML5AudioSound#seek * @type {number} * @since 3.0.0 */ seek: { get: function () { if (this.isPlaying) { return this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); } else if (this.isPaused) { return this.currentConfig.seek; } else { return 0; } }, set: function (value) { if (this.manager.isLocked(this, 'seek', value)) { return; } if (this.startTime > 0) { return; } if (this.isPlaying || this.isPaused) { value = Math.min(Math.max(0, value), this.duration); if (this.isPlaying) { this.previousTime = value; this.audio.currentTime = value; } else if (this.isPaused) { this.currentConfig.seek = value; } this.emit('seek', this, value); } } }, /** * Seeks to a specific point in this sound. * * @method Phaser.Sound.HTML5AudioSound#setSeek * @fires Phaser.Sound.HTML5AudioSound#seekEvent * @since 3.4.0 * * @param {number} value - The point in the sound to seek to. * * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. */ setSeek: function (value) { this.seek = value; return this; }, /** * @event Phaser.Sound.HTML5AudioSound#loopEvent * @param {Phaser.Sound.HTML5AudioSound} sound - Reference to the sound that emitted event. * @param {boolean} value - An updated value of Phaser.Sound.HTML5AudioSound#loop property. */ /** * Flag indicating whether or not the sound or current sound marker will loop. * * @name Phaser.Sound.HTML5AudioSound#loop * @type {boolean} * @default false * @since 3.0.0 */ loop: { get: function () { return this.currentConfig.loop; }, set: function (value) { this.currentConfig.loop = value; if (this.manager.isLocked(this, 'loop', value)) { return; } if (this.audio) { this.audio.loop = value; } this.emit('loop', this, value); } }, /** * Sets the loop state of this Sound. * * @method Phaser.Sound.HTML5AudioSound#setLoop * @fires Phaser.Sound.HTML5AudioSound#loopEvent * @since 3.4.0 * * @param {boolean} value - `true` to loop this sound, `false` to not loop it. * * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. */ setLoop: function (value) { this.loop = value; return this; } }); module.exports = HTML5AudioSound;
version https://git-lfs.github.com/spec/v1 oid sha256:73320a5fc05e6688b53e1b947564a252791cd3276ffaf049b3d44cab8df45a98 size 366
version https://git-lfs.github.com/spec/v1 oid sha256:2f5d9bf5f89960a25c3091c26915d16a709d4a24499fb76626d92231faa42fef size 1918
import {Schema} from "prosemirror-model" // ::Schema Document schema for the data model used by CommonMark. export const schema = new Schema({ nodes: { doc: { content: "block+" }, paragraph: { content: "inline*", group: "block", parseDOM: [{tag: "p"}], toDOM() { return ["p", 0] } }, blockquote: { content: "block+", group: "block", parseDOM: [{tag: "blockquote"}], toDOM() { return ["blockquote", 0] } }, horizontal_rule: { group: "block", parseDOM: [{tag: "hr"}], toDOM() { return ["div", ["hr"]] } }, heading: { attrs: {level: {default: 1}}, content: "(text | image)*", group: "block", defining: true, parseDOM: [{tag: "h1", attrs: {level: 1}}, {tag: "h2", attrs: {level: 2}}, {tag: "h3", attrs: {level: 3}}, {tag: "h4", attrs: {level: 4}}, {tag: "h5", attrs: {level: 5}}, {tag: "h6", attrs: {level: 6}}], toDOM(node) { return ["h" + node.attrs.level, 0] } }, code_block: { content: "text*", group: "block", code: true, defining: true, marks: "", attrs: {params: {default: ""}}, parseDOM: [{tag: "pre", preserveWhitespace: "full", getAttrs: node => ( {params: node.getAttribute("data-params") || ""} )}], toDOM(node) { return ["pre", node.attrs.params ? {"data-params": node.attrs.params} : {}, ["code", 0]] } }, ordered_list: { content: "list_item+", group: "block", attrs: {order: {default: 1}, tight: {default: false}}, parseDOM: [{tag: "ol", getAttrs(dom) { return {order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1, tight: dom.hasAttribute("data-tight")} }}], toDOM(node) { return ["ol", {start: node.attrs.order == 1 ? null : node.attrs.order, "data-tight": node.attrs.tight ? "true" : null}, 0] } }, bullet_list: { content: "list_item+", group: "block", attrs: {tight: {default: false}}, parseDOM: [{tag: "ul", getAttrs: dom => ({tight: dom.hasAttribute("data-tight")})}], toDOM(node) { return ["ul", {"data-tight": node.attrs.tight ? "true" : null}, 0] } }, list_item: { content: "paragraph block*", defining: true, parseDOM: [{tag: "li"}], toDOM() { return ["li", 0] } }, text: { group: "inline" }, image: { inline: true, attrs: { src: {}, alt: {default: null}, title: {default: null} }, group: "inline", draggable: true, parseDOM: [{tag: "img[src]", getAttrs(dom) { return { src: dom.getAttribute("src"), title: dom.getAttribute("title"), alt: dom.getAttribute("alt") } }}], toDOM(node) { return ["img", node.attrs] } }, hard_break: { inline: true, group: "inline", selectable: false, parseDOM: [{tag: "br"}], toDOM() { return ["br"] } } }, marks: { em: { parseDOM: [{tag: "i"}, {tag: "em"}, {style: "font-style", getAttrs: value => value == "italic" && null}], toDOM() { return ["em"] } }, strong: { parseDOM: [{tag: "b"}, {tag: "strong"}, {style: "font-weight", getAttrs: value => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null}], toDOM() { return ["strong"] } }, link: { attrs: { href: {}, title: {default: null} }, inclusive: false, parseDOM: [{tag: "a[href]", getAttrs(dom) { return {href: dom.getAttribute("href"), title: dom.getAttribute("title")} }}], toDOM(node) { return ["a", node.attrs] } }, code: { parseDOM: [{tag: "code"}], toDOM() { return ["code"] } } } })
/*------------------------------------- EASY WAYPOINT FUNCTIONS -------------------------------------*/ // Creates a standerd waypoint with the option of custom logic. To pass in // the custom logic, just create a function with all the logic you would // like to call when the waypoint is activated, then pass just the name of the // function into this function without qoutes. Note that these waypoint functions are // available to any js file in this project // Example Single Waypoint: createWaypoint('.that', 'is-active', '35%', animateThat) function createWaypoint(element, classToToggle, offset, cb) { return jQuery(element).waypoint(function(direction) { jQuery(element).toggleClass(classToToggle); if (typeof cb !== "undefined") { cb(element, classToToggle, offset, direction); } }, { offset: offset }); } // A loop for standerd waypoint creation. Also has the ability to pass in custom // logic, and classToToggle. Both are optional. // Example Multiple Waypoints: waypointer(['.that', '#that', '#this'], 'resolved', '10%', animate); function waypointer(elementArray, classToToggle, offset, cb) { for (var i=0; i < elementArray.length; i++) { createWaypoint(elementArray[i], classToToggle, offset, cb); } return true; } // This will be invoked when the page loads ;(function($){ $(function() { // place waypoints here }); }(jQuery));
version https://git-lfs.github.com/spec/v1 oid sha256:6b3e4decf59fdb2e9c8a552b36cea9986e875fb957b248276bd04888917730ff size 5429
var React = require('react'); var MainSection = require('./components/MainSection.component'); React.render(<MainSection />, document.getElementById('container'));
var classktt_1_1_parameter_pair = [ [ "ParameterPair", "classktt_1_1_parameter_pair.html#aa1a0cc60c3c77a523d2a82533e1cba5e", null ], [ "ParameterPair", "classktt_1_1_parameter_pair.html#ad5ec1fe348f5084be1bb93a72e36300c", null ], [ "ParameterPair", "classktt_1_1_parameter_pair.html#a0542a9454902488e990906cc276197ef", null ], [ "getName", "classktt_1_1_parameter_pair.html#a330e6a703f523d4d8654b0baf9f55542", null ], [ "getValue", "classktt_1_1_parameter_pair.html#a3a84a10729e19dd2158abd219c49e165", null ], [ "getValueDouble", "classktt_1_1_parameter_pair.html#a196698403542667a5754e3a0f2428609", null ], [ "hasValueDouble", "classktt_1_1_parameter_pair.html#a0222cbe77642692479552ac73391be3a", null ], [ "setValue", "classktt_1_1_parameter_pair.html#a5cc19f299e2409aa3bc584d7c195ff47", null ] ];
'@fixture Test fixture'; '@page http://my.page.url'; function ultraSuperHelperFunc() { return 'nothing'; } '@test'['My first test'] = { '1.Do smthg cool' : function () { var foo = 'bar', baz = 0; for (var i = 0; i < 50; i++) baz++; act.click(foo); }, '2.Stop here' : function () { act.wait(500); }, '3.Not a mixin' : '@mixin Undefined yeah' }; var someUselessVar = 'blahblahblah'; '@test'['I want more tests!'] = { '1.Here we go' : function () { while (true) { var a = 3 + 2; console.log('This is infinite loop lol'); } }, "2.I'm really tired creating stupid names for test steps" : function () { callSomeUselessFunc(); act.drag(); }, '3.This is a final step' : function () { finish(); } }; alert('Hi there!');
/* jQuery.flexMenu 1.1 https://github.com/352Media/flexMenu Description: If a list is too long for all items to fit on one line, display a popup menu instead. Dependencies: jQuery, Modernizr (optional). Without Modernizr, the menu can only be shown on click (not hover). */ (function ($) { var flexObjects = [], // Array of all flexMenu objects resizeTimeout; // When the page is resized, adjust the flexMenus. function adjustFlexMenu() { $(flexObjects).each(function () { $(this).flexMenu({ 'undo' : true }).flexMenu(this.options); }); } function collapseAllExcept($menuToAvoid) { var $activeMenus, $menusToCollapse; $activeMenus = $('li.flexMenu-viewMore.active'); $menusToCollapse = $activeMenus.not($menuToAvoid); $menusToCollapse.removeClass('active').find('> ul').hide(); } $(window).resize(function () { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(function () { adjustFlexMenu(); }, 200); }); $.fn.flexMenu = function (options) { var checkFlexObject, s = $.extend({ 'threshold' : 2, // [integer] If there are this many items or fewer in the list, we will not display a "View More" link and will instead let the list break to the next line. This is useful in cases where adding a "view more" link would actually cause more things to break to the next line. 'cutoff' : 2, // [integer] If there is space for this many or fewer items outside our "more" popup, just move everything into the more menu. In that case, also use linkTextAll and linkTitleAll instead of linkText and linkTitle. To disable this feature, just set this value to 0. 'linkText' : 'More', // [string] What text should we display on the "view more" link? 'linkTitle' : 'View More', // [string] What should the title of the "view more" button be? 'linkTextAll' : 'Menu', // [string] If we hit the cutoff, what text should we display on the "view more" link? 'linkTitleAll' : 'Open/Close Menu', // [string] If we hit the cutoff, what should the title of the "view more" button be? 'showOnHover' : true, // [boolean] Should we we show the menu on hover? If not, we'll require a click. If we're on a touch device - or if Modernizr is not available - we'll ignore this setting and only show the menu on click. The reason for this is that touch devices emulate hover events in unpredictable ways, causing some taps to do nothing. 'popupAbsolute' : true, // [boolean] Should we absolutely position the popup? Usually this is a good idea. That way, the popup can appear over other content and spill outside a parent that has overflow: hidden set. If you want to do something different from this in CSS, just set this option to false. 'undo' : false // [boolean] Move the list items back to where they were before, and remove the "View More" link. }, options); this.options = s; // Set options on object checkFlexObject = $.inArray(this, flexObjects); // Checks if this object is already in the flexObjects array if (checkFlexObject >= 0) { flexObjects.splice(checkFlexObject, 1); // Remove this object if found } else { flexObjects.push(this); // Add this object to the flexObjects array } return this.each(function () { var $this = $(this), $self = $this, $firstItem = $this.find('li:first-child'), $lastItem = $this.find('li:last-child'), numItems = $this.find('li').length, firstItemTop = Math.floor($firstItem.offset().top), firstItemHeight = Math.floor($firstItem.outerHeight(true)), $lastChild, keepLooking, $moreItem, $moreLink, numToRemove, allInPopup = false, $menu, i; function needsMenu($itemOfInterest) { var result = (Math.ceil($itemOfInterest.offset().top) >= (firstItemTop + firstItemHeight)) ? true : false; // Values may be calculated from em and give us something other than round numbers. Browsers may round these inconsistently. So, let's round numbers to make it easier to trigger flexMenu. return result; } if (needsMenu($lastItem) && numItems > s.threshold && !s.undo && $this.is(':visible')) { var $popup = $('<ul class="flexMenu-popup" style="display:none;' + ((s.popupAbsolute) ? ' position: absolute;' : '') + '"></ul>'), // Move all list items after the first to this new popup ul firstItemOffset = $firstItem.offset().top; for (i = numItems; i > 1; i--) { // Find all of the list items that have been pushed below the first item. Put those items into the popup menu. Put one additional item into the popup menu to cover situations where the last item is shorter than the "more" text. $lastChild = $this.find('li:last-child'); keepLooking = (needsMenu($lastChild)); $lastChild.appendTo($popup); // If there only a few items left in the navigation bar, move them all to the popup menu. if ((i - 1) <= s.cutoff) { // We've removed the ith item, so i - 1 gives us the number of items remaining. $($this.children().get().reverse()).appendTo($popup); allInPopup = true; break; } if (!keepLooking) { break; } } if (allInPopup) { $this.append('<li class="flexMenu-viewMore flexMenu-allInPopup"><a href="#" title="' + s.linkTitleAll + '">' + s.linkTextAll + '</a></li>'); } else { $this.append('<li class="flexMenu-viewMore"><a href="#" title="' + s.linkTitle + '">' + s.linkText + '</a></li>'); } $moreItem = $this.find('li.flexMenu-viewMore'); /// Check to see whether the more link has been pushed down. This might happen if the link immediately before it is especially wide. if (needsMenu($moreItem)) { $this.find('li:nth-last-child(2)').appendTo($popup); } // Our popup menu is currently in reverse order. Let's fix that. $popup.children().each(function (i, li) { $popup.prepend(li); }); $moreItem.append($popup); $moreLink = $this.find('li.flexMenu-viewMore > a'); $moreLink.click(function (e) { // Collapsing any other open flexMenu collapseAllExcept($moreItem); //Open and Set active the one being interacted with. $popup.toggle(); $moreItem.toggleClass('active'); e.preventDefault(); }); if (s.showOnHover && (typeof Modernizr !== 'undefined') && !Modernizr.touch) { // If requireClick is false AND touch is unsupported, then show the menu on hover. If Modernizr is not available, assume that touch is unsupported. Through the magic of lazy evaluation, we can check for Modernizr and start using it in the same if statement. Reversing the order of these variables would produce an error. $moreItem.hover( function () { $popup.show(); $(this).addClass('active'); }, function () { $popup.hide(); $(this).removeClass('active'); }); } } else if (s.undo && $this.find('ul.flexMenu-popup')) { $menu = $this.find('ul.flexMenu-popup'); numToRemove = $menu.find('li').length; for (i = 1; i <= numToRemove; i++) { $menu.find('li:first-child').appendTo($this); } $menu.remove(); $this.find('li.flexMenu-viewMore').remove(); } }); }; })(jQuery);
// ============================== // MANUFACTURER (DIRECTOR) // ============================== export default class Manufacturer { static manufacture(builder) { builder.motherboard = "Asus Z170-A ATX LGA1151"; builder.cpu = "Intel Core i7 6950X"; builder.ram = "HyperX Fury 8 GB"; builder.ssd = "SanDisk SSD PLUS 240 GB"; builder.nic = "D-Link DGE-528T"; builder.powerSupply = "Corsair RM750x"; builder.caseDesign = "Cooler Master HAF X"; return builder.assemblePC(); } }
"use strict"; const mongoose = require('mongoose'); module.exports = function (application, done) { application.db = mongoose.connection; application.models = require('./common/models')(application); application.db.on('error', function (err) { application.log.error(err); }); application.db.on('connected', function() { application.log.info('MongoDB connected!'); }); application.db.once('open', function() { application.log.info('MongoDB connection opened!'); }); application.db.on('reconnected', function () { application.log.info('MongoDB reconnected!'); }); application.db.on('disconnected', function() { application.log.info('MongoDB disconnected!'); }); mongoose.connect(application.config.mongo.uri, application.config.mongo.options, function(err) { if(err) { application.log.error(err); } done(); }); }; // Close the Mongoose connection, when receiving SIGINT process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Force to close the MongoDB conection'); process.exit(0); }); });
(function() { var Post, create, edit; Post = function() { this.title = ""; this.content = ""; this.author = ""; this.categories = []; this.tags = []; this.date = ""; this.modified = ""; return this.published = true; }; create = function(title, content, categories, tags, published) { var post; post = new Post(); post.title = title; post.content = content; post.categories = categories; post.tags = tags; post.published = published; post.date = Date.now(); return post; }; edit = function(title, content, categories, tags, published) { var modified, post; post = new Post(); title = title; content = content; categories = categories; tags = tags; published = published; modified = Date.now(); return post; }; exports.create = create; exports.edit = edit; }).call(this);
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.11.0-master-bc4100a */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.menu-bar */ angular.module('material.components.menuBar', [ 'material.core', 'material.components.menu' ]); angular .module('material.components.menuBar') .controller('MenuBarController', MenuBarController); var BOUND_MENU_METHODS = ['handleKeyDown', 'handleMenuHover', 'scheduleOpenHoveredMenu', 'cancelScheduledOpen']; /** * ngInject */ function MenuBarController($scope, $element, $attrs, $mdConstant, $document, $mdUtil, $timeout) { this.$element = $element; this.$attrs = $attrs; this.$mdConstant = $mdConstant; this.$mdUtil = $mdUtil; this.$document = $document; this.$scope = $scope; this.$timeout = $timeout; var self = this; angular.forEach(BOUND_MENU_METHODS, function(methodName) { self[methodName] = angular.bind(self, self[methodName]); }); } MenuBarController.$inject = ["$scope", "$element", "$attrs", "$mdConstant", "$document", "$mdUtil", "$timeout"]; MenuBarController.prototype.init = function() { var $element = this.$element; var $mdUtil = this.$mdUtil; var $scope = this.$scope; var self = this; $element.on('keydown', this.handleKeyDown); this.parentToolbar = $mdUtil.getClosest($element, 'MD-TOOLBAR'); $scope.$on('$mdMenuOpen', function(event, el) { if (self.getMenus().indexOf(el[0]) != -1) { $element[0].classList.add('md-open'); el[0].classList.add('md-open'); self.currentlyOpenMenu = el.controller('mdMenu'); self.currentlyOpenMenu.registerContainerProxy(self.handleKeyDown); self.enableOpenOnHover(); } }); $scope.$on('$mdMenuClose', function(event, el) { var rootMenus = self.getMenus(); if (rootMenus.indexOf(el[0]) != -1) { $element[0].classList.remove('md-open'); el[0].classList.remove('md-open'); } if ($element[0].contains(el[0])) { var parentMenu = el[0]; while (parentMenu && rootMenus.indexOf(parentMenu) == -1) { parentMenu = $mdUtil.getClosest(parentMenu, 'MD-MENU', true); } if (parentMenu) { parentMenu.querySelector('button').focus(); self.currentlyOpenMenu = undefined; self.disableOpenOnHover(); self.setKeyboardMode(true); } } }); angular .element(this.getMenus()) .on('mouseenter', this.handleMenuHover); this.setKeyboardMode(true); }; MenuBarController.prototype.setKeyboardMode = function(enabled) { if (enabled) this.$element[0].classList.add('md-keyboard-mode'); else this.$element[0].classList.remove('md-keyboard-mode'); }; MenuBarController.prototype.enableOpenOnHover = function() { if (this.openOnHoverEnabled) return; this.openOnHoverEnabled = true; var $element = this.$element; var parentToolbar; if (parentToolbar = this.parentToolbar) { parentToolbar.dataset.mdRestoreStyle = parentToolbar.getAttribute('style'); parentToolbar.style.position = 'relative'; parentToolbar.style.zIndex = 100; } }; MenuBarController.prototype.handleMenuHover = function(e) { this.setKeyboardMode(false); if (this.openOnHoverEnabled) { this.scheduleOpenHoveredMenu(e); } }; MenuBarController.prototype.disableOpenOnHover = function() { if (!this.openOnHoverEnabled) return; this.openOnHoverEnabled = false; var parentToolbar; if (parentToolbar = this.parentToolbar) { parentToolbar.setAttribute('style', parentToolbar.dataset.mdRestoreStyle || ''); } }; MenuBarController.prototype.scheduleOpenHoveredMenu = function(e) { var menuEl = angular.element(e.currentTarget); var menuCtrl = menuEl.controller('mdMenu'); this.setKeyboardMode(false); this.scheduleOpenMenu(menuCtrl); }; MenuBarController.prototype.scheduleOpenMenu = function(menuCtrl) { var self = this; var $timeout = this.$timeout; if (menuCtrl != self.currentlyOpenMenu) { $timeout.cancel(self.pendingMenuOpen); self.pendingMenuOpen = $timeout(function() { self.pendingMenuOpen = undefined; if (self.currentlyOpenMenu) { self.currentlyOpenMenu.close(true, { closeAll: true }); } menuCtrl.open(); }, 200, false); } } MenuBarController.prototype.handleKeyDown = function(e) { var keyCodes = this.$mdConstant.KEY_CODE; var currentMenu = this.currentlyOpenMenu; var wasOpen = currentMenu && currentMenu.isOpen; this.setKeyboardMode(true); var handled; switch (e.keyCode) { case keyCodes.DOWN_ARROW: if (currentMenu) { currentMenu.focusMenuContainer(); } else { this.openFocusedMenu(); } handled = true; break; case keyCodes.UP_ARROW: currentMenu && currentMenu.close(); handled = true; break; case keyCodes.LEFT_ARROW: var newMenu = this.focusMenu(-1); if (wasOpen) { var newMenuCtrl = angular.element(newMenu).controller('mdMenu'); this.scheduleOpenMenu(newMenuCtrl); } handled = true; break; case keyCodes.RIGHT_ARROW: var newMenu = this.focusMenu(+1); if (wasOpen) { var newMenuCtrl = angular.element(newMenu).controller('mdMenu'); this.scheduleOpenMenu(newMenuCtrl); } handled = true; break; } if (handled) { e && e.preventDefault && e.preventDefault(); e && e.stopImmediatePropagation && e.stopImmediatePropagation(); } }; MenuBarController.prototype.focusMenu = function(direction) { var menus = this.getMenus(); var focusedIndex = this.getFocusedMenuIndex(); if (focusedIndex == -1) { focusedIndex = this.getOpenMenuIndex(); } var changed = false; if (focusedIndex == -1) { focusedIndex = 0; } else if ( direction < 0 && focusedIndex > 0 || direction > 0 && focusedIndex < menus.length - direction ) { focusedIndex += direction; changed = true; } if (changed) { menus[focusedIndex].querySelector('button').focus(); return menus[focusedIndex]; } }; MenuBarController.prototype.openFocusedMenu = function() { var menu = this.getFocusedMenu(); menu && angular.element(menu).controller('mdMenu').open(); }; MenuBarController.prototype.getMenus = function() { var $element = this.$element; return this.$mdUtil.nodesToArray($element[0].children) .filter(function(el) { return el.nodeName == 'MD-MENU'; }); }; MenuBarController.prototype.getFocusedMenu = function() { return this.getMenus()[this.getFocusedMenuIndex()]; }; MenuBarController.prototype.getFocusedMenuIndex = function() { var $mdUtil = this.$mdUtil; var $element = this.$element; var focusedEl = $mdUtil.getClosest( this.$document[0].activeElement, 'MD-MENU' ); if (!focusedEl) return -1; var focusedIndex = this.getMenus().indexOf(focusedEl); return focusedIndex; }; MenuBarController.prototype.getOpenMenuIndex = function() { var menus = this.getMenus(); for (var i = 0; i < menus.length; ++i) { if (menus[i].classList.contains('md-open')) return i; } return -1; }; /** * @ngdoc directive * @name mdMenuBar * @module material.components.menu-bar * @restrict E * @description * * Menu bars are containers that hold multiple menus. They change the behavior and appearence * of the `md-menu` directive to behave similar to an operating system provided menu. * * @usage * <hljs lang="html"> * <md-menu-bar> * <md-menu> * <button ng-click="$mdOpenMenu()"> * File * </button> * <md-menu-content> * <md-menu-item> * <md-button ng-click="ctrl.sampleAction('share', $event)"> * Share... * </md-button> * </md-menu-item> * <md-menu-divider></md-menu-divider> * <md-menu-item> * <md-menu-item> * <md-menu> * <md-button ng-click="$mdOpenMenu()">New</md-button> * <md-menu-content> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item> * </md-menu-content> * </md-menu> * </md-menu-item> * </md-menu-content> * </md-menu> * </md-menu-bar> * </hljs> * * ## Menu Bar Controls * * You may place `md-menu-items` that function as controls within menu bars. * There are two modes that are exposed via the `type` attribute of the `md-menu-item`. * `type="checkbox"` will function as a boolean control for the `ng-model` attribute of the * `md-menu-item`. `type="radio"` will function like a radio button, setting the `ngModel` * to the `string` value of the `value` attribute. If you need non-string values, you can use * `ng-value` to provide an expression (this is similar to how angular's native `input[type=radio]` works. * * <hljs lang="html"> * <md-menu-bar> * <md-menu> * <button ng-click="$mdOpenMenu()"> * Sample Menu * </button> * <md-menu-content> * <md-menu-item type="checkbox" ng-model="settings.allowChanges">Allow changes</md-menu-item> * <md-menu-divider></md-menu-divider> * <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 1</md-menu-item> * <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 2</md-menu-item> * <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 3</md-menu-item> * </md-menu-content> * </md-menu> * </md-menu-bar> * </hljs> * * * ### Nesting Menus * * Menus may be nested within menu bars. This is commonly called cascading menus. * To nest a menu place the nested menu inside the content of the `md-menu-item`. * <hljs lang="html"> * <md-menu-item> * <md-menu> * <button ng-click="$mdOpenMenu()">New</md-button> * <md-menu-content> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item> * </md-menu-content> * </md-menu> * </md-menu-item> * </hljs> * */ angular .module('material.components.menuBar') .directive('mdMenuBar', MenuBarDirective); /** * * @ngInjdect */ function MenuBarDirective($mdUtil, $mdTheming) { return { restrict: 'E', require: 'mdMenuBar', controller: 'MenuBarController', compile: function compile(templateEl, templateAttrs) { if (!templateAttrs.ariaRole) { templateEl[0].setAttribute('role', 'menubar'); } angular.forEach(templateEl[0].children, function(menuEl) { if (menuEl.nodeName == 'MD-MENU') { if (!menuEl.hasAttribute('md-position-mode')) { menuEl.setAttribute('md-position-mode', 'left bottom'); } menuEl.setAttribute('role', 'menu'); var contentEls = $mdUtil.nodesToArray(menuEl.querySelectorAll('md-menu-content')); angular.forEach(contentEls, function(contentEl) { contentEl.classList.add('md-menu-bar-menu'); contentEl.classList.add('md-dense'); if (!contentEl.hasAttribute('width')) { contentEl.setAttribute('width', 5); } }); } }); return function postLink(scope, el, attrs, ctrl) { $mdTheming(scope, el); ctrl.init(); }; } }; } MenuBarDirective.$inject = ["$mdUtil", "$mdTheming"]; angular .module('material.components.menuBar') .directive('mdMenuDivider', MenuDividerDirective); function MenuDividerDirective() { return { restrict: 'E', compile: function(templateEl, templateAttrs) { if (!templateAttrs.role) { templateEl[0].setAttribute('role', 'separator'); } } }; } angular .module('material.components.menuBar') .controller('MenuItemController', MenuItemController); /** * ngInject */ function MenuItemController($scope, $element, $attrs) { this.$element = $element; this.$attrs = $attrs; this.$scope = $scope; } MenuItemController.$inject = ["$scope", "$element", "$attrs"]; MenuItemController.prototype.init = function(ngModel) { var $element = this.$element; var $attrs = this.$attrs; this.ngModel = ngModel; if ($attrs.type == 'checkbox' || $attrs.type == 'radio') { this.mode = $attrs.type; this.iconEl = $element[0].children[0]; this.buttonEl = $element[0].children[1]; if (ngModel) this.initClickListeners(); } }; MenuItemController.prototype.initClickListeners = function() { var ngModel = this.ngModel; var $scope = this.$scope; var $attrs = this.$attrs; var $element = this.$element; var mode = this.mode; this.handleClick = angular.bind(this, this.handleClick); var icon = this.iconEl var button = angular.element(this.buttonEl); var handleClick = this.handleClick; $attrs.$observe('disabled', setDisabled); setDisabled($attrs.disabled); ngModel.$render = function render() { if (isSelected()) { icon.style.display = ''; $element.attr('aria-checked', 'true'); } else { icon.style.display = 'none'; $element.attr('aria-checked', 'false'); } }; $scope.$$postDigest(ngModel.$render); function isSelected() { if (mode == 'radio') { var val = $attrs.ngValue ? $scope.$eval($attrs.ngValue) : $attrs.value; return ngModel.$modelValue == val; } else { return ngModel.$modelValue; } } function setDisabled(disabled) { if (disabled) { button.off('click', handleClick); } else { button.on('click', handleClick); } } }; MenuItemController.prototype.handleClick = function(e) { var mode = this.mode; var ngModel = this.ngModel; var $attrs = this.$attrs; var newVal; if (mode == 'checkbox') { newVal = !ngModel.$modelValue; } else if (mode == 'radio') { newVal = $attrs.ngValue ? this.$scope.$eval($attrs.ngValue) : $attrs.value; } ngModel.$setViewValue(newVal); ngModel.$render(); }; angular .module('material.components.menuBar') .directive('mdMenuItem', MenuItemDirective); /** * * @ngInjdect */ function MenuItemDirective() { return { require: ['mdMenuItem', '?ngModel'], compile: function(templateEl, templateAttrs) { if (templateAttrs.type == 'checkbox' || templateAttrs.type == 'radio') { var text = templateEl[0].textContent; var buttonEl = angular.element('<md-button type="button"></md-button>'); buttonEl.html(text); buttonEl.attr('tabindex', '0'); templateEl.html(''); templateEl.append(angular.element('<md-icon md-svg-icon="check"></md-icon>')); templateEl.append(buttonEl); templateEl[0].classList.add('md-indent'); setDefault('role', (templateAttrs.type == 'checkbox') ? 'menuitemcheckbox' : 'menuitemradio'); angular.forEach(['ng-disabled'], moveAttrToButton); } else { setDefault('role', 'menuitem'); } return function(scope, el, attrs, ctrls) { var ctrl = ctrls[0]; var ngModel = ctrls[1]; ctrl.init(ngModel); }; function setDefault(attr, val) { if (!templateEl[0].hasAttribute(attr)) { templateEl[0].setAttribute(attr, val); } } function moveAttrToButton(attr) { if (templateEl[0].hasAttribute(attr)) { var val = templateEl[0].getAttribute(attr); buttonEl[0].setAttribute(attr, val); templateEl[0].removeAttribute(attr); } } }, controller: 'MenuItemController' }; } })(window, window.angular);
describe('Loading Nuora', function () { //using nuora as a module var colors = require('colors'), Nuora = require('../'), nuora, zuora, tests; it('has opts property', function () { expect(Nuora).to.have.property('opts'); }); Nuora.opts.option('--reporter [value]', ''); Nuora.opts.option('-r [value]', ''); it('builds Nuora', function () { nuora = Nuora.build(); zuora = nuora.zuora; describe('Nuora build', function () { it('has zuora property', function () { expect(nuora).to.have.property('zuora'); }); it('has zuora.soap property', function () { expect(zuora).to.have.property('soap'); }); }); tests = function () { describe('Perform a query', function () { this.timeout(10000); it('should return an array of no more than two elements', function (done) { var sql = "select id from account limit 1", i = 0, callback = function (err, data) { describe('Query ResultObject', function () { it('should have property id', function () { assert(data.result.records.hasOwnProperty('Id')); }); }); done(err); }; zuora.query(sql, callback, true); }); }); }; }); describe('Logging in', function () { it('connected to the server', function (done) { zuora.on('loggedin', function () { done(); tests(); }); }); }); });
/* * Node-side Configuration */ OVERRIDE(NODE_CONFIG, (origin) => { global.NODE_CONFIG = COMBINE([{ isSingleCoreMode : false, // maxUploadFileMB // isNotToModelInitialize // 룸 서버를 사용하지 않을지 여부 설정 isNotUsingRoomServer : false }, origin]); });
"use strict"; // // Debugging // // Declare DEBUG constant, but be sure we aren't in production var DEBUG = Browser.inProduction() ? false : true; // Disable logging if in production if (!DEBUG) { window.console = {}; window.console.log = function(){}; window.console.info = function(){}; window.console.warn = function(){}; window.console.error = function(){}; } // // Shorthand to localStorage, used everywhere, as essential here as jQuery // var ls = localStorage; // // All other constants // // API server var API_SERVER = 'https://passoa.online.ntnu.no/api/'; // Loops & intervals var BACKGROUND_LOOP = 60000; // 60s var BACKGROUND_LOOP_DEBUG = 5000; // 5s, respond fairly quickly for us developers var PAGE_LOOP = 10000; // 10s var PAGE_LOOP_DEBUG = 5000; // 5s var ONLINE_MESSAGE = '\nNow online, run mainloop\n'; var OFFLINE_MESSAGE = '\nNow offline, stop execution\n'; // Update stuff at every X intervals var UPDATE_AFFILIATION_INTERVAL = 1; // recommended: 1 var UPDATE_CANTINAS_INTERVAL = 60; // recommended: 60 var UPDATE_BUS_INTERVAL = 2; // recommended: 1 var UPDATE_NEWS_INTERVAL = 20; // recommended: 20 // Hard totals // It's this, or doing synchronous XMLHttpRequests, which have been deprecated in Chrome now, so.. yeah. var MEME_AMOUNT = 31;
'use strict'; /** * @ngdoc overview * @name gabineteApp * @description * # gabineteApp * * Main module of the application. */ angular .module('gabineteApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'slugifier' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/integrantes.html', controller: 'IntegrantesCtrl', controllerAs: 'main' }) .when('/integrantes/:persona', { templateUrl: 'views/integrantes.html', controller: 'IntegrantesCtrl', controllerAs: 'main' }) .otherwise({ redirectTo: '/' }); }) .service('TabletopService', function ($q,Slug) { this.keys = false; this.data = false; this.loading = false; this.getData = function(){ var that = this; return $q(function(resolve, reject) { if(!that.data){ // if(!that.loading){ that.loading = true; d3.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vSZG-bnXn217ELlkVTAuNZDdmtdPTdsbJ6CGYxAXyFEz24Uk503mOeMtr2dEVUNlg2OowwWpCOKGgIr/pub?gid=1766965020&single=true&output=csv") .then(function(indexData) { var fileList = []; that.keys = {} that.data = {} indexData.forEach(function(row){ fileList.push( d3.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vSZG-bnXn217ELlkVTAuNZDdmtdPTdsbJ6CGYxAXyFEz24Uk503mOeMtr2dEVUNlg2OowwWpCOKGgIr/pub?single=true&output=csv&gid="+row.id_hoja) .then(function(data) {return data}) ) that.keys[Slug.slugify(row.grupo)] = row.grupo; }) Promise.all(fileList).then(function(responses) { indexData.map(function(row,ix) { that.data[row.grupo] = {elements: responses[ix]}; }) that.loading = false; resolve({ data: that.data, keys: that.keys }); }) return indexData; }); // } } else { resolve({data:that.data,keys:that.keys}); } }); }; });
import * as evaluator from './evaluator.js'; import * as environment from './environment.js'; function parseExpression(program) { program = skipSpace(program); var match, expr; if (match = /^"([^"]*)"/.exec(program)) { expr = {type: "value", value: match[1]}; } else if (match = /^\d+\b/.exec(program)) { expr = {type: "value", value: Number(match[0])}; } else if (match = /^[^\s(),"]+/.exec(program)) { expr = {type: "word", name: match[0]}; } else { throw new SyntaxError("Unexpected syntax: " + program) } return parseApply(expr, program.slice(match[0].length)); } function skipSpace(string) { var first = string.search(/\S/); if (first == -1) { return ""; } return string.slice(first); } function parseApply(expr, program) { program = skipSpace(program); if (program[0] != "(") { return {expr: expr, rest: program}; } program = skipSpace(program.slice(1)); expr = {type: "apply", operator: expr, args: []}; while (program[0] != ")") { var arg = parseExpression(program); expr.args.push(arg.expr); program = skipSpace(arg.rest); if (program[0] == ",") { program = skipSpace(program.slice(1)); } else if (program[0] != ")") { throw new SyntaxError("Expected ',' or ')'"); } } return parseApply(expr, program.slice(1)); } function parse(program) { var result = parseExpression(program); if (skipSpace(result.rest).length > 0) { throw new SyntaxError("Unexpected text after program"); } return result.expr; }
const NON_WORD_REGEXP = /[^A-Za-z0-9]/g export const DEFAULT_RANGES = ['0-9', 'A-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'] export function groupBrandsByRanges (brands, ranges = DEFAULT_RANGES) { let rangeBrandsHash = {} for (let brand of brands) { addBrandToRangedBrandHash(rangeBrandsHash, brand, ranges) } return rangeBrandsHash } export function addBrandToRangedBrandHash (rangeBrandsHash, brand, ranges = DEFAULT_RANGES) { const range = getBrandRange(brand.brand_copy[0].brand_name, ranges) if (!range) { return } if (!rangeBrandsHash[range]) { rangeBrandsHash[range] = [] } brandFastInsert(rangeBrandsHash[range], brand) } export function normalizeString (s) { return s.replace(NON_WORD_REGEXP, '').toLowerCase() } export function stringsAreInDescendingOrder (s1, s2, equality = false) { if (equality) { return normalizeString(s1) >= normalizeString(s2) } return normalizeString(s1) > normalizeString(s2) } export function stringsAreInAscendingOrder (s1, s2, equality = false) { if (equality) { return normalizeString(s1) <= normalizeString(s2) } return normalizeString(s1) < normalizeString(s2) } function getBrandRange (brandName, ranges = DEFAULT_RANGES) { const normalizedName = normalizeString(brandName) if (normalizedName.length === 0) { return undefined } const zeroChar = normalizedName.charAt(0).toUpperCase() for (let range of ranges) { const left = range.charAt(0) const right = range.charAt(2) if (zeroChar >= left && zeroChar <= right) { return range } } return undefined } // here i'm using binary insertion algorithm with slight modification // http://machinesaredigging.com/2014/04/27/binary-insert-how-to-keep-an-array-sorted-as-you-insert-data-in-it/ function brandFastInsert (brands, brand, left, right) { const length = brands.length const l = typeof (left) !== 'undefined' ? left : 0 const r = typeof (right) !== 'undefined' ? right : length - 1 const m = (l + r) >> 1 const brandName = brand.brand_copy[0].brand_name if (brands.length === 0) { brands.push(brand) return } if (stringsAreInDescendingOrder(brandName, brands[r].brand_copy[0].brand_name, true)) { brands.splice(r + 1, 0, brand) return } if (stringsAreInAscendingOrder(brandName, brands[l].brand_copy[0].brand_name, true)) { brands.splice(l, 0, brand) return } if (l >= r) { return } if (stringsAreInAscendingOrder(brandName, brands[m].brand_copy[0].brand_name, true)) { brandFastInsert(brands, brand, l, m - 1) return } if (stringsAreInDescendingOrder(brandName, brands[m].brand_copy[0].brand_name, true)) { brandFastInsert(brands, brand, m + 1, r) return } }
import cheerio from 'cheerio' import { join } from 'path' import { findPort, launchApp, killApp, nextStart, nextBuild, renderViaHTTP, File, } from 'next-test-utils' jest.setTimeout(1000 * 60 * 5) let app let appPort const appDir = join(__dirname, '..') const nextConfig = new File(join(appDir, 'next.config.js')) const runTests = () => { it('should have gip in __NEXT_DATA__', async () => { const html = await renderViaHTTP(appPort, '/') const $ = cheerio.load(html) expect(JSON.parse($('#__NEXT_DATA__').text()).gip).toBe(true) }) it('should not have gip in __NEXT_DATA__ for non-GIP page', async () => { const html = await renderViaHTTP(appPort, '/normal') const $ = cheerio.load(html) expect('gip' in JSON.parse($('#__NEXT_DATA__').text())).toBe(false) }) it('should have correct router.asPath for direct visit dynamic page', async () => { const html = await renderViaHTTP(appPort, '/blog/1') const $ = cheerio.load(html) expect($('#as-path').text()).toBe('/blog/1') }) it('should have correct router.asPath for direct visit dynamic page rewrite direct', async () => { const html = await renderViaHTTP(appPort, '/blog/post/1') const $ = cheerio.load(html) expect($('#as-path').text()).toBe('/blog/post/1') }) } describe('getInitialProps', () => { describe('dev mode', () => { beforeAll(async () => { appPort = await findPort() app = await launchApp(appDir, appPort) }) afterAll(() => killApp(app)) runTests() }) describe('serverless mode', () => { beforeAll(async () => { await nextConfig.replace('// replace me', `target: 'serverless', `) await nextBuild(appDir) appPort = await findPort() app = await nextStart(appDir, appPort) }) afterAll(async () => { await killApp(app) nextConfig.restore() }) runTests() }) describe('production mode', () => { beforeAll(async () => { await nextBuild(appDir) appPort = await findPort() app = await nextStart(appDir, appPort) }) afterAll(() => killApp(app)) runTests() }) })
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ServerOptions_1 = require("./ServerOptions"); const Http = require("http"); const Https = require("https"); const express = require("express"); const debug = require("debug"); const compression = require("compression"); const path = require("path"); const datefmt = require("dateformat"); const favicon = require("serve-favicon"); const fs = require("fs"); const cluster = require("cluster"); const process = require("process"); const os = require("os"); const cors = require("cors"); const logError = debug('saco:error'); const logInfo = debug('saco:info'); var ClusterMessage; (function (ClusterMessage) { ClusterMessage[ClusterMessage["WORKER_LISTENING"] = 0] = "WORKER_LISTENING"; })(ClusterMessage || (ClusterMessage = {})); class Server { constructor(options) { this.startedWorkersCount = 0; this.app = express(); this.options = Object.assign({}, ServerOptions_1.DEFAULT_OPTIONS, options); this.options.workers = Math.min(Math.max(this.options.workers, 1), os.cpus().length); this.appConfigure(); } isHttps() { return this.options.key != null && this.options.cert != null; } setMaxSockets() { if (this.isHttps()) { Https.globalAgent.maxSockets = Infinity; logInfo('Https max sockets set to %O', Https.globalAgent.maxSockets); } else { Http.globalAgent.maxSockets = Infinity; logInfo('Http max sockets set to %O', Http.globalAgent.maxSockets); } } appConfigure() { this.app.disable('x-powered-by'); if (this.options.cors) { this.app.use(cors()); } this.app.use(compression()); if (this.options.behindProxy) { this.app.enable('trust proxy'); } if (this.options.verbose) { this.app.use((req, res, next) => { logInfo(this.options.name, datefmt(new Date(), this.options.dateformat), 'pid:', process.pid, 'ip:', req.ip, '\t', req.method, '\t', req.url); next(); }); } this.app.use(this.options.assets.url, express.static(path.join(this.options.rootPath, this.options.assets.path), { maxAge: this.options.maxAge })); this.app.get(this.options.index.url, (req, res) => { res.setHeader('Cache-Control', `public, max-age=${this.options.maxAge}`); res.sendFile(path.join(this.options.rootPath, this.options.index.path)); }); this.app.use((err, req, res, next) => { logError(datefmt(new Date(), this.options.dateformat), '\t:', req.method, req.url); logError(err.stack); res.status(500).send('Something broke!'); }); if (this.options.favicon != null) { this.app.use(this.options.favicon.url, favicon(path.join(this.options.rootPath, this.options.favicon.path))); } } createServer() { if (this.isHttps()) { logInfo('Starting https server on worker %O...', process.pid); let httpsOptions = { key: fs.readFileSync(this.options.key), cert: fs.readFileSync(this.options.cert) }; return Https.createServer(httpsOptions, this.app); } else { logInfo('Starting http server on worker %O...', process.pid); return Http.createServer(this.app); } } startMaster() { var self = this; return new Promise((resolve, reject) => { for (let i = 0; i < self.options.workers; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { logInfo(`Worker %O died`, worker.process.pid); self.startedWorkersCount--; if (self.startedWorkersCount === 0) { logInfo('Bye'); } }); cluster.on('message', (worker, data) => { logInfo('Process %O listening on port %O', data.pid, self.options.port); self.startedWorkersCount++; if (self.startedWorkersCount === self.options.workers) { logInfo('Server ready'); resolve(self.startedWorkersCount); } }); cluster.on('online', worker => { logInfo('Process %O just went online', worker.process.pid); }); }); } sendMaster(pid, msg) { process.send({ pid, msg }); } startWorker() { var self = this; return new Promise((resolve, reject) => { self.server = self.createServer(); self.server .listen(self.options.port, self.options.ip, () => { self.sendMaster(process.pid, ClusterMessage.WORKER_LISTENING); resolve(); }) .on('error', () => { logError('Failed to start the server on port %O', self.options.port); reject(); }); }); } // returnes a promise that resolves only after all workers // have sent ClusterMessage.WORKER_LISTENING to the master start() { var self = this; return new Promise((resolve, reject) => { if (cluster.isMaster) { logInfo(`Starting %O master %O...`, this.options.name, process.pid); logInfo('Options: %O', self.options); self.setMaxSockets(); resolve(self.startMaster()); } else { logInfo(`Starting %O worker %O...`, this.options.name, process.pid); self.startWorker(); } }); } // returnes a promise that resolves only after all // workers have send 'exit' event to the master stop() { return new Promise((resolve, reject) => { cluster.disconnect(() => { resolve(); }); }); } } exports.Server = Server; //# sourceMappingURL=Server.js.map
$(function () { var root = this, viewers = root.viewers || {}, WDZV = (viewers.WDZV = {}); root.viewers = viewers; var canvas = document.getElementById("map-wdz"), context = canvas.getContext("2d"); canvas.width = 640; canvas.height = 512; var N = Scl.N, M = Scl.M; WDZV.paint = function (data) { context.clearRect(0, 0, 640, 512); for (var i = 0; i < N; i++) { for (var j = 0; j <= M; j++) { var measure = data.map[i][j], wdz = measure[8], fill = "#000000"; if (wdz > 100 || wdz < -100) { fill = "#ffffff"; } else { var hight = 100 + wdz; var low = wdz; hight = Math.floor(hight / 200.0 * 255).toString(16); low = Math.floor(low / 200.0 * 255).toString(16); fill = "rgb(" + hight + ", 88, " + low + ")"; } context.fillStyle = fill; context.fillRect(5 * i, 4 * j, 5, 4); if (i === 0 && j === 50) { $("#wdz1").html(wdz); } if (i === 150 && j === 50) { $("#wdz2").html(wdz); } } } }; });
import React, { PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Editor from '../Editor'; import TodoItem from '../TodoItem'; import { getTodos } from '../../actions'; class TodoList extends React.Component { render() { const rows = this.props.todos.map((item, index) => <TodoItem key={index} index={index} item={item} />); if (this.props.adding) { rows.push(<Editor key={-1} />); } return ( <table className="table"> <tbody> {rows} </tbody> </table> ); } } TodoList.propTypes = { todos: React.PropTypes.arrayOf(React.PropTypes.object), adding: PropTypes.bool, getTodos: PropTypes.func, }; const mapStateToProps = state => ({ todos: state.todos, adding: state.adding, }); const mapDispatchToProps = dispatch => ({ getTodos: bindActionCreators(getTodos, dispatch), }); export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
/* global hexo */ 'use strict'; const renderer = require('./lib/renderer'); hexo.extend.renderer.register('swig', 'html', renderer, true);
import React, { createRef, Component } from 'react'; import { DomHandler, classNames } from 'primereact/utils'; import { InputText } from 'primereact/inputtext'; import { tip } from 'primereact/tooltip'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var InputMask = /*#__PURE__*/function (_Component) { _inherits(InputMask, _Component); var _super = _createSuper(InputMask); function InputMask(props) { var _this; _classCallCheck(this, InputMask); _this = _super.call(this, props); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onKeyPress = _this.onKeyPress.bind(_assertThisInitialized(_this)); _this.onInput = _this.onInput.bind(_assertThisInitialized(_this)); _this.handleInputChange = _this.handleInputChange.bind(_assertThisInitialized(_this)); _this.inputRef = /*#__PURE__*/createRef(_this.props.inputRef); return _this; } _createClass(InputMask, [{ key: "caret", value: function caret(first, last) { var range, begin, end; var inputEl = this.inputRef && this.inputRef.current; if (!inputEl || !inputEl.offsetParent || inputEl !== document.activeElement) { return; } if (typeof first === 'number') { begin = first; end = typeof last === 'number' ? last : begin; if (inputEl.setSelectionRange) { inputEl.setSelectionRange(begin, end); } else if (inputEl['createTextRange']) { range = inputEl['createTextRange'](); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } } else { if (inputEl.setSelectionRange) { begin = inputEl.selectionStart; end = inputEl.selectionEnd; } else if (document['selection'] && document['selection'].createRange) { range = document['selection'].createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } } }, { key: "isCompleted", value: function isCompleted() { for (var i = this.firstNonMaskPos; i <= this.lastRequiredNonMaskPos; i++) { if (this.tests[i] && this.buffer[i] === this.getPlaceholder(i)) { return false; } } return true; } }, { key: "getPlaceholder", value: function getPlaceholder(i) { if (i < this.props.slotChar.length) { return this.props.slotChar.charAt(i); } return this.props.slotChar.charAt(0); } }, { key: "getValue", value: function getValue() { return this.props.unmask ? this.getUnmaskedValue() : this.inputRef && this.inputRef.current && this.inputRef.current.value; } }, { key: "seekNext", value: function seekNext(pos) { while (++pos < this.len && !this.tests[pos]) { } return pos; } }, { key: "seekPrev", value: function seekPrev(pos) { while (--pos >= 0 && !this.tests[pos]) { } return pos; } }, { key: "shiftL", value: function shiftL(begin, end) { var i, j; if (begin < 0) { return; } for (i = begin, j = this.seekNext(end); i < this.len; i++) { if (this.tests[i]) { if (j < this.len && this.tests[i].test(this.buffer[j])) { this.buffer[i] = this.buffer[j]; this.buffer[j] = this.getPlaceholder(j); } else { break; } j = this.seekNext(j); } } this.writeBuffer(); this.caret(Math.max(this.firstNonMaskPos, begin)); } }, { key: "shiftR", value: function shiftR(pos) { var i, c, j, t; for (i = pos, c = this.getPlaceholder(pos); i < this.len; i++) { if (this.tests[i]) { j = this.seekNext(i); t = this.buffer[i]; this.buffer[i] = c; if (j < this.len && this.tests[j].test(t)) { c = t; } else { break; } } } } }, { key: "handleAndroidInput", value: function handleAndroidInput(e) { var curVal = this.inputRef.current.value; var pos = this.caret(); if (this.oldVal && this.oldVal.length && this.oldVal.length > curVal.length) { // a deletion or backspace happened this.checkVal(true); while (pos.begin > 0 && !this.tests[pos.begin - 1]) { pos.begin--; } if (pos.begin === 0) { while (pos.begin < this.firstNonMaskPos && !this.tests[pos.begin]) { pos.begin++; } } this.caret(pos.begin, pos.begin); } else { this.checkVal(true); while (pos.begin < this.len && !this.tests[pos.begin]) { pos.begin++; } this.caret(pos.begin, pos.begin); } if (this.props.onComplete && this.isCompleted()) { this.props.onComplete({ originalEvent: e, value: this.getValue() }); } } }, { key: "onBlur", value: function onBlur(e) { this.focus = false; this.checkVal(); this.updateModel(e); this.updateFilledState(); if (this.props.onBlur) { this.props.onBlur(e); } if (this.inputRef.current.value !== this.focusText) { var event = document.createEvent('HTMLEvents'); event.initEvent('change', true, false); this.inputRef.current.dispatchEvent(event); } } }, { key: "onKeyDown", value: function onKeyDown(e) { if (this.props.readOnly) { return; } var k = e.which || e.keyCode, pos, begin, end; var iPhone = /iphone/i.test(DomHandler.getUserAgent()); this.oldVal = this.inputRef.current.value; //backspace, delete, and escape get special treatment if (k === 8 || k === 46 || iPhone && k === 127) { pos = this.caret(); begin = pos.begin; end = pos.end; if (end - begin === 0) { begin = k !== 46 ? this.seekPrev(begin) : end = this.seekNext(begin - 1); end = k === 46 ? this.seekNext(end) : end; } this.clearBuffer(begin, end); this.shiftL(begin, end - 1); this.updateModel(e); e.preventDefault(); } else if (k === 13) { // enter this.onBlur(e); this.updateModel(e); } else if (k === 27) { // escape this.inputRef.current.value = this.focusText; this.caret(0, this.checkVal()); this.updateModel(e); e.preventDefault(); } } }, { key: "onKeyPress", value: function onKeyPress(e) { var _this2 = this; if (this.props.readOnly) { return; } var k = e.which || e.keyCode, pos = this.caret(), p, c, next, completed; if (e.ctrlKey || e.altKey || e.metaKey || k < 32) { //Ignore return; } else if (k && k !== 13) { if (pos.end - pos.begin !== 0) { this.clearBuffer(pos.begin, pos.end); this.shiftL(pos.begin, pos.end - 1); } p = this.seekNext(pos.begin - 1); if (p < this.len) { c = String.fromCharCode(k); if (this.tests[p].test(c)) { this.shiftR(p); this.buffer[p] = c; this.writeBuffer(); next = this.seekNext(p); if (/android/i.test(DomHandler.getUserAgent())) { //Path for CSP Violation on FireFox OS 1.1 var proxy = function proxy() { _this2.caret(next); }; setTimeout(proxy, 0); } else { this.caret(next); } if (pos.begin <= this.lastRequiredNonMaskPos) { completed = this.isCompleted(); } } } e.preventDefault(); } this.updateModel(e); if (this.props.onComplete && completed) { this.props.onComplete({ originalEvent: e, value: this.getValue() }); } } }, { key: "clearBuffer", value: function clearBuffer(start, end) { var i; for (i = start; i < end && i < this.len; i++) { if (this.tests[i]) { this.buffer[i] = this.getPlaceholder(i); } } } }, { key: "writeBuffer", value: function writeBuffer() { this.inputRef.current.value = this.buffer.join(''); } }, { key: "checkVal", value: function checkVal(allow) { this.isValueChecked = true; //try to place characters where they belong var test = this.inputRef.current.value, lastMatch = -1, i, c, pos; for (i = 0, pos = 0; i < this.len; i++) { if (this.tests[i]) { this.buffer[i] = this.getPlaceholder(i); while (pos++ < test.length) { c = test.charAt(pos - 1); if (this.tests[i].test(c)) { this.buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) { this.clearBuffer(i + 1, this.len); break; } } else { if (this.buffer[i] === test.charAt(pos)) { pos++; } if (i < this.partialPosition) { lastMatch = i; } } } if (allow) { this.writeBuffer(); } else if (lastMatch + 1 < this.partialPosition) { if (this.props.autoClear || this.buffer.join('') === this.defaultBuffer) { // Invalid value. Remove it and replace it with the // mask, which is the default behavior. if (this.inputRef.current.value) this.inputRef.current.value = ''; this.clearBuffer(0, this.len); } else { // Invalid value, but we opt to show the value to the // user and allow them to correct their mistake. this.writeBuffer(); } } else { this.writeBuffer(); this.inputRef.current.value = this.inputRef.current.value.substring(0, lastMatch + 1); } return this.partialPosition ? i : this.firstNonMaskPos; } }, { key: "onFocus", value: function onFocus(e) { var _this3 = this; if (this.props.readOnly) { return; } this.focus = true; clearTimeout(this.caretTimeoutId); var pos; this.focusText = this.inputRef.current.value; pos = this.checkVal(); this.caretTimeoutId = setTimeout(function () { if (_this3.inputRef.current !== document.activeElement) { return; } _this3.writeBuffer(); if (pos === _this3.props.mask.replace("?", "").length) { _this3.caret(0, pos); } else { _this3.caret(pos); } _this3.updateFilledState(); }, 10); if (this.props.onFocus) { this.props.onFocus(e); } } }, { key: "onInput", value: function onInput(event) { if (this.androidChrome) this.handleAndroidInput(event);else this.handleInputChange(event); } }, { key: "handleInputChange", value: function handleInputChange(e) { if (this.props.readOnly) { return; } var pos = this.checkVal(true); this.caret(pos); this.updateModel(e); if (this.props.onComplete && this.isCompleted()) { this.props.onComplete({ originalEvent: e, value: this.getValue() }); } } }, { key: "getUnmaskedValue", value: function getUnmaskedValue() { var unmaskedBuffer = []; for (var i = 0; i < this.buffer.length; i++) { var c = this.buffer[i]; if (this.tests[i] && c !== this.getPlaceholder(i)) { unmaskedBuffer.push(c); } } return unmaskedBuffer.join(''); } }, { key: "updateModel", value: function updateModel(e) { if (this.props.onChange) { var val = this.props.unmask ? this.getUnmaskedValue() : e && e.target.value; this.props.onChange({ originalEvent: e, value: this.defaultBuffer !== val ? val : '', stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: this.defaultBuffer !== val ? val : '' } }); } } }, { key: "updateFilledState", value: function updateFilledState() { if (this.inputRef && this.inputRef.current && this.inputRef.current.value && this.inputRef.current.value.length > 0) DomHandler.addClass(this.inputRef.current, 'p-filled');else DomHandler.removeClass(this.inputRef.current, 'p-filled'); } }, { key: "updateValue", value: function updateValue(allow) { var _this4 = this; var pos; if (this.inputRef && this.inputRef.current) { if (this.props.value == null) { this.inputRef.current.value = ''; } else { this.inputRef.current.value = this.props.value; pos = this.checkVal(allow); setTimeout(function () { if (_this4.inputRef && _this4.inputRef.current) { _this4.writeBuffer(); return _this4.checkVal(allow); } }, 10); } this.focusText = this.inputRef.current.value; } this.updateFilledState(); return pos; } }, { key: "isValueUpdated", value: function isValueUpdated() { return this.props.unmask ? this.props.value !== this.getUnmaskedValue() : this.defaultBuffer !== this.inputRef.current.value && this.inputRef.current.value !== this.props.value; } }, { key: "init", value: function init() { if (this.props.mask) { this.tests = []; this.partialPosition = this.props.mask.length; this.len = this.props.mask.length; this.firstNonMaskPos = null; this.defs = { '9': '[0-9]', 'a': '[A-Za-z]', '*': '[A-Za-z0-9]' }; var ua = DomHandler.getUserAgent(); this.androidChrome = /chrome/i.test(ua) && /android/i.test(ua); var maskTokens = this.props.mask.split(''); for (var i = 0; i < maskTokens.length; i++) { var c = maskTokens[i]; if (c === '?') { this.len--; this.partialPosition = i; } else if (this.defs[c]) { this.tests.push(new RegExp(this.defs[c])); if (this.firstNonMaskPos === null) { this.firstNonMaskPos = this.tests.length - 1; } if (i < this.partialPosition) { this.lastRequiredNonMaskPos = this.tests.length - 1; } } else { this.tests.push(null); } } this.buffer = []; for (var _i = 0; _i < maskTokens.length; _i++) { var _c = maskTokens[_i]; if (_c !== '?') { if (this.defs[_c]) this.buffer.push(this.getPlaceholder(_i));else this.buffer.push(_c); } } this.defaultBuffer = this.buffer.join(''); } } }, { key: "updateInputRef", value: function updateInputRef() { var ref = this.props.inputRef; if (ref) { if (typeof ref === 'function') { ref(this.inputRef.current); } else { ref.current = this.inputRef.current; } } } }, { key: "componentDidMount", value: function componentDidMount() { this.updateInputRef(); this.init(); this.updateValue(); if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } if (this.isValueUpdated()) { this.updateValue(); } if (prevProps.mask !== this.props.mask) { this.init(); this.caret(this.updateValue(true)); this.updateModel(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = tip({ target: this.inputRef.current, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "render", value: function render() { var inputMaskClassName = classNames('p-inputmask', this.props.className); return /*#__PURE__*/React.createElement(InputText, { id: this.props.id, ref: this.inputRef, type: this.props.type, name: this.props.name, style: this.props.style, className: inputMaskClassName, placeholder: this.props.placeholder, size: this.props.size, maxLength: this.props.maxLength, tabIndex: this.props.tabIndex, disabled: this.props.disabled, readOnly: this.props.readOnly, onFocus: this.onFocus, onBlur: this.onBlur, onKeyDown: this.onKeyDown, onKeyPress: this.onKeyPress, onInput: this.onInput, onPaste: this.handleInputChange, required: this.props.required, "aria-labelledby": this.props.ariaLabelledBy }); } }]); return InputMask; }(Component); _defineProperty(InputMask, "defaultProps", { id: null, inputRef: null, value: null, type: 'text', mask: null, slotChar: '_', autoClear: true, unmask: false, style: null, className: null, placeholder: null, size: null, maxLength: null, tabIndex: null, disabled: false, readOnly: false, name: null, required: false, tooltip: null, tooltipOptions: null, ariaLabelledBy: null, onComplete: null, onChange: null, onFocus: null, onBlur: null }); export { InputMask };
/** * 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/createAggregator'], function(createAggregator) { /** Used for native method references */ var objectProto = Object.prototype; /** Native method shortcuts */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an object composed of keys generated from the results of running * each element of `collection` through the callback. The corresponding value * of each key is the number of times the key was returned by the callback. * 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 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 {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 {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); }); return countBy; });
{ "name": "43places", "domain": "43places.com", "urlMappings": [{ "urlTemplate": "http://www.43places.com/person/{username}", "schema": "None", "contentType": "Profile", "mediaType": "Html" }], "www": true }
'use strict'; angular.module('studyApp') .service('User', function User() { // AngularJS will instantiate a singleton by calling "new" on this function });
'use strict'; var requireHelper = require(process.env.TEST_DIR + '/require_helper'); var Game = requireHelper('models/game'); var expect = require('chai').expect; describe('Game', function() { describe('contructor', function() { var game1 = new Game(); it('should create a new Game with ID equals 1', function() { expect(game1.id).to.equals(1); }); it('should create a new Game with a specific grid', function() { expect(game1.grid).to.have.length(5); expect(game1.grid[0]).to.have.length(5); expect(game1.grid[0][0]).to.equals('B'); }); it('shoud create the next Game with a different ID', function() { var game2 = new Game(); expect(game2.id).to.not.equals(game1.id); }); }); });
'use strict'; angular .module('app.module') .factory('exception', exception); exception.$inject = ['logger']; function exception(logger) { var service = { catcher: catcher }; return service; function catcher(message) { return function(reason) { logger.error(message, reason); }; } } /* angular //TODO: get back to this .module('blocks.exception') .config(exceptionConfig); exceptionConfig.$inject = ['$provide']; function exceptionConfig($provide) { $provide.decorator('$exceptionHandler', extendExceptionHandler); } extendExceptionHandler.$inject = ['$delegate']; function extendExceptionHandler($delegate) { return function(exception, cause) { $delegate(exception, cause); var errorData = { exception: exception, cause: cause }; //toastr.error(exception.msg, errorData); console.error("ExceptionDecoService: " +exception.msg +" " +errorData) }; } */
/** * Write text. * * Any number of columns. Everything is displayed as text. * * @class sgvizler.visualization.Generic * @extends sgvizler.charts.Chart * @constructor * @param {Object} container The container element where the * chart will be drawn. * @since 0.6.1 **/ /** * Available options: * * In `NoX` `X` should replaced with a number 1 =< X =< no. of columns. * * - 'dataFunction' : function applied to every cell value. (default: identify function) * - 'includeHeaders' : include column headings or not. (default: false) * - 'headingCellSep' : string to separate cells in each column. (default: '') * - 'headingCellSepNoX' : string to separate cells in each column. (default: headingCellSep) * - 'headingCellPrefix' : string to prefix each cell with. (default: '') * - 'headingCellPostfix' : string to postfix each cell with. (default: '') * - 'headingCellPrefixNoX' : string to prefix each cell with. (default: headingCellPrefixNoX) * - 'headingCellPostfixNoX' : string to postfix each cell with. (default: headingCellPostfixNoX) * - 'headingRowPrefix' : string to prefix each row with. (default: '') * - 'headingRowPostfix' : string to postfix each row with. (default: '') * - 'headingRowPrefixNoX' : string to prefix each row with. (default: headingRowPrefixNoX) * - 'headingRowPostfixNoX' : string to postfix each row with. (default: headingRowPostfixNoX) * - 'cellSep' : string (can be html) to separate cells in each column. (default: '') * - 'cellSepNoX' : string (can be html) to separate cells in each column. (default: cellSep) * - 'cellPrefix' : string (can be html) to prefix each cell with. (default: '') * - 'cellPostfix' : string (can be html) to postfix each cell with. (default: '') * - 'cellPrefixNoX' : string (can be html) to prefix each first cell in every row with. (default: cellPrefix) * - 'cellPostfixNoX' : string (can be html) to postfix each first cell in every row with. (default: cellPostfix) * - 'rowPrefix' : string (can be html) to prefix each row with. (default: '') * - 'rowPostfix' : string (can be html) to postfix each row with. (default: '') * - 'rowPrefixNoX' : string (can be html) to prefix each row with. (default: rowPrefix) * - 'rowPostfixNoX' : string (can be html) to postfix each row with. (default: rowPostfix) * - 'resultsPrefix' : string (can be html) to prefix the results with. (default: '') * - 'resultsPostfix' : string (can be html) to postfix the results with. (default: '') * * @method draw * @public * @param {google.visualization.DataTable} data * @param {Object} [chartOptions] * @since 0.6.1 **/ C.Generic = charts.add(modSC, "Generic", function (data, chartOptions) { var text = C.util.genericTextDraw(data, $.extend({}, chartOptions)); $(this.container) .empty() .html(text); this.fireListener('ready'); } );
/** * Copyright (c) 2014, Oracle and/or its affiliates. * All rights reserved. */ "use strict";var l={"NZL_WELLINGTON":[null,"\u05D5\u05D5\u05DC\u05D9\u05E0\u05D2\u05D8\u05D5\u05DF"],"AUS_CANBERRA":[null,"\u05E7\u05E0\u05D1\u05E8\u05D4"]};(this?this:window)['DvtBaseMapManager']['_UNPROCESSED_MAPS'][2].push(["australia","cities",l]);
const getBaseType = require('./_getBaseType') /** * * @param {Object} value */ const isNumber = value => getBaseType('Number')(value) module.exports = isNumber
import React from 'react'; import styled from 'styled-components'; import { Button, Icon, Col, Tag, Typography } from 'antd'; import JSONEditor from './JSONEditor'; import EditorViewer from './EditorViewer'; import variations from './variations'; import { createImageChildren } from './CarouselSlideItem'; import ItemsCarousel from '../../src/ItemsCarousel'; import CenteredRow from './CenteredRow'; import DemoHeader from './DemoHeader'; const Wrapper = styled.div` `; const Variations = styled.div` display: flex; flex-wrap: wrap; align-items: center; height: 40px; `; const Variation = styled(Tag.CheckableTag)` cursor: pointer; `; export class ItemsCarouselPlayground extends React.Component { state = { activeItemIndex: 0, activeVariation: variations[0], }; render() { const { activeVariation } = this.state; const { noOfChildren, wrapperStyle, componentProps, } = activeVariation.state; const children = createImageChildren(noOfChildren); return ( <Wrapper> <DemoHeader title={'Playground'} description={'Play around with props to see if this library suits your needs'} /> <div style={wrapperStyle}> <ItemsCarousel {...componentProps} activeItemIndex={this.state.activeItemIndex} requestToChangeActive={value => this.setState({ activeItemIndex: value })} rightChevron={ <Button shape="circle"> <Icon type="right" /> </Button> } leftChevron={ <Button shape="circle"> <Icon type="left" /> </Button> } children={children} /> </div> <CenteredRow gutter={12}> <Col xs={24} md={12}> <Typography.Title level={3}>Change props here</Typography.Title> <Variations> {variations.map((variation, index) => ( <Variation checked={variation.name === activeVariation.name} key={index} onChange={() => this.setState({ activeItemIndex: 0, activeVariation: variation })} > {variation.name} </Variation> ))} </Variations> <JSONEditor json={{ noOfChildren, wrapperStyle, componentProps, }} onJSONChange={({ noOfChildren, wrapperStyle, componentProps }) => { this.setState({ activeVariation: { name: activeVariation.name, state: { noOfChildren, wrapperStyle, componentProps, }, }, }); }} /> </Col> <Col xs={24} md={12}> <Typography.Title level={3}>Usage <Typography.Text type={'secondary'}>(Read-Only)</Typography.Text></Typography.Title> <Variations /> <EditorViewer noOfChildren={noOfChildren} wrapperStyle={wrapperStyle} componentProps={componentProps} /> </Col> </CenteredRow> </Wrapper> ); } } export default ItemsCarouselPlayground;
/* jshint ignore: start */ import React from 'react'; import Footer from './Footer'; import Popup from 'reactjs-popup'; import BurgerIcon from './BurgerIcon'; import Menu from './Menu'; // import { Content } from 'reactbulma'; import '../smde-editor.css'; const styles = { fontFamily: 'sans-serif', textAlign: 'left', marginTop: '40px' }; const contentStyle = { background: 'rgba(255,255,255,0)', width: '80%', border: 'none' }; const Privacy = () => ( <React.Fragment> <div style={styles}> <Popup modal overlayStyle={{ background: 'rgba(255,255,255,0.98' }} contentStyle={contentStyle} closeOnDocumentClick={false} trigger={open => <BurgerIcon open={open} />} > {close => <Menu close={close} />} </Popup> </div> <div className="container is-fluid content"> <h1>Privacy Policy</h1> <p>Effective date: September 20, 2018</p> <p> Check Yo Self ("us", "we", or "our") operates the https://checkyoself.netlify.com website (the "Service"). </p> <p> This page informs you of our policies regarding the collection, use, and disclosure of personal data when you use our Service and the choices you have associated with that data. Our Privacy Policy for Check Yo Self is managed through{' '} <a href="https://www.freeprivacypolicy.com/free-privacy-policy-generator.php"> Free Privacy Policy </a>. </p> <p> We use your data to provide and improve the Service. By using the Service, you agree to the collection and use of information in accordance with this policy. Unless otherwise defined in this Privacy Policy, terms used in this Privacy Policy have the same meanings as in our Terms and Conditions, accessible from https://checkyoself.netlify.com </p> <h2>Information Collection And Use</h2> <p> We collect several different types of information for various purposes to provide and improve our Service to you. </p> <h3>Types of Data Collected</h3> <h4>Personal Data</h4> <p> While using our Service, we may ask you to provide us with certain personally identifiable information that can be used to contact or identify you ("Personal Data"). Personally identifiable information may include, but is not limited to: </p> <ul> <li>Cookies and Usage Data</li> </ul> <h4>Usage Data</h4> <p> We may also collect information how the Service is accessed and used ("Usage Data"). This Usage Data may include information such as your computer's Internet Protocol address (e.g. IP address), browser type, browser version, the pages of our Service that you visit, the time and date of your visit, the time spent on those pages, unique device identifiers and other diagnostic data. </p> <h4>Tracking & Cookies Data</h4> <p> We use cookies and similar tracking technologies to track the activity on our Service and hold certain information. </p> <p> Cookies are files with small amount of data which may include an anonymous unique identifier. Cookies are sent to your browser from a website and stored on your device. Tracking technologies also used are beacons, tags, and scripts to collect and track information and to improve and analyze our Service. </p> <p> You can instruct your browser to refuse all cookies or to indicate when a cookie is being sent. However, if you do not accept cookies, you may not be able to use some portions of our Service. </p> <p>Examples of Cookies we use:</p> <ul> <li> <strong>Session Cookies.</strong> We use Session Cookies to operate our Service. </li> <li> <strong>Preference Cookies.</strong> We use Preference Cookies to remember your preferences and various settings. </li> <li> <strong>Security Cookies.</strong> We use Security Cookies for security purposes. </li> </ul> <h2>Use of Data</h2> <p>Check Yo Self uses the collected data for various purposes:</p> <ul> <li>To provide and maintain the Service</li> <li>To notify you about changes to our Service</li> <li> To allow you to participate in interactive features of our Service when you choose to do so </li> <li>To provide customer care and support</li> <li> To provide analysis or valuable information so that we can improve the Service </li> <li>To monitor the usage of the Service</li> <li>To detect, prevent and address technical issues</li> </ul> <h2>Transfer Of Data</h2> <p> Your information, including Personal Data, may be transferred to — and maintained on — computers located outside of your state, province, country or other governmental jurisdiction where the data protection laws may differ than those from your jurisdiction. </p> <p> If you are located outside United States and choose to provide information to us, please note that we transfer the data, including Personal Data, to United States and process it there. </p> <p> Your consent to this Privacy Policy followed by your submission of such information represents your agreement to that transfer. </p> <p> Check Yo Self will take all steps reasonably necessary to ensure that your data is treated securely and in accordance with this Privacy Policy and no transfer of your Personal Data will take place to an organization or a country unless there are adequate controls in place including the security of your data and other personal information. </p> <h2>Disclosure Of Data</h2> <h3>Legal Requirements</h3> <p> Check Yo Self may disclose your Personal Data in the good faith belief that such action is necessary to: </p> <ul> <li>To comply with a legal obligation</li> <li> To protect and defend the rights or property of Check Yo Self </li> <li> To prevent or investigate possible wrongdoing in connection with the Service </li> <li> To protect the personal safety of users of the Service or the public </li> <li>To protect against legal liability</li> </ul> <h2>Security Of Data</h2> <p> The security of your data is important to us, but remember that no method of transmission over the Internet, or method of electronic storage is 100% secure. While we strive to use commercially acceptable means to protect your Personal Data, we cannot guarantee its absolute security. </p> <h2>Service Providers</h2> <p> We may employ third party companies and individuals to facilitate our Service ("Service Providers"), to provide the Service on our behalf, to perform Service-related services or to assist us in analyzing how our Service is used. </p> <p> These third parties have access to your Personal Data only to perform these tasks on our behalf and are obligated not to disclose or use it for any other purpose. </p> <h3>Analytics</h3> <p> We may use third-party Service Providers to monitor and analyze the use of our Service. </p> <ul> <li> <p> <strong>Google Analytics</strong> </p> <p> Google Analytics is a web analytics service offered by Google that tracks and reports website traffic. Google uses the data collected to track and monitor the use of our Service. This data is shared with other Google services. Google may use the collected data to contextualize and personalize the ads of its own advertising network. </p> <p> You can opt-out of having made your activity on the Service available to Google Analytics by installing the Google Analytics opt-out browser add-on. The add-on prevents the Google Analytics JavaScript (ga.js, analytics.js, and dc.js) from sharing information with Google Analytics about visits activity. </p> <p> For more information on the privacy practices of Google, please visit the Google Privacy & Terms web page:{' '} <a href="https://policies.google.com/privacy?hl=en"> https://policies.google.com/privacy?hl=en </a> </p> </li> </ul> <h2>Links To Other Sites</h2> <p> Our Service may contain links to other sites that are not operated by us. If you click on a third party link, you will be directed to that third party's site. We strongly advise you to review the Privacy Policy of every site you visit. </p> <p> We have no control over and assume no responsibility for the content, privacy policies or practices of any third party sites or services. </p> <h2>Children's Privacy</h2> <p> Our Service does not address anyone under the age of 18 ("Children"). </p> <p> We do not knowingly collect personally identifiable information from anyone under the age of 18. If you are a parent or guardian and you are aware that your Children has provided us with Personal Data, please contact us. If we become aware that we have collected Personal Data from children without verification of parental consent, we take steps to remove that information from our servers. </p> <h2>Changes To This Privacy Policy</h2> <p> We may update our Privacy Policy from time to time. We will notify you of any changes by posting the new Privacy Policy on this page. </p> <p> We will let you know via email and/or a prominent notice on our Service, prior to the change becoming effective and update the "effective date" at the top of this Privacy Policy. </p> <p> You are advised to review this Privacy Policy periodically for any changes. Changes to this Privacy Policy are effective when they are posted on this page. </p> <h2>Contact Us</h2> <p> If you have any questions about this Privacy Policy, please contact us: </p> <ul> <li>By email: <a href="mailto:feedback@tiffanyrwhite.com">feedback@tiffanyrwhite.com</a></li> </ul> </div> <Footer /> </React.Fragment> ); export default Privacy;
(function (){ 'use strict'; function <%= ctrlname %> (){ var vm = this; } angular.module('<%= appname %>').controller('<%= ctrlname %>', <%= ctrlname %>); })();
// Tigra Calendar v5.2 (11/20/2011) // http://www.softcomplex.com/products/tigra_calendar/ // License: Public Domain... You're welcome. // default settins - this structure can be moved in separate file in multilangual applications var A_TCALCONF = { 'cssprefix' : 'tcal', 'months' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], 'weekdays' : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], 'longwdays' : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], 'yearscroll' : true, // show year scroller 'weekstart' : 0, // first day of week: 0-Su or 1-Mo 'prevyear' : 'Previous Year', 'nextyear' : 'Next Year', 'prevmonth' : 'Previous Month', 'nextmonth' : 'Next Month', 'format' : 'Y-m-d' // 'd-m-Y', Y-m-d', 'l, F jS Y' }; var A_TCALTOKENS = [ // A full numeric representation of a year, 4 digits {'t': 'Y', 'r': '19\\d{2}|20\\d{2}', 'p': function (d_date, n_value) { d_date.setFullYear(Number(n_value)); return d_date; }, 'g': function (d_date) { var n_year = d_date.getFullYear(); return n_year; }}, // Numeric representation of a month, with leading zeros {'t': 'm', 'r': '0?[1-9]|1[0-2]', 'p': function (d_date, n_value) { d_date.setMonth(Number(n_value) - 1); return d_date; }, 'g': function (d_date) { var n_month = d_date.getMonth() + 1; return (n_month < 10 ? '0' : '') + n_month }}, // A full textual representation of a month, such as January or March {'t': 'F', 'r': A_TCALCONF.months.join('|'), 'p': function (d_date, s_value) { for (var m = 0; m < 12; m++) if (A_TCALCONF.months[m] == s_value) { d_date.setMonth(m); return d_date; }}, 'g': function (d_date) { return A_TCALCONF.months[d_date.getMonth()]; }}, // Day of the month, 2 digits with leading zeros {'t': 'd', 'r': '0?[1-9]|[12][0-9]|3[01]', 'p': function (d_date, n_value) { d_date.setDate(Number(n_value)); if (d_date.getDate() != n_value) d_date.setDate(0); return d_date }, 'g': function (d_date) { var n_date = d_date.getDate(); return (n_date < 10 ? '0' : '') + n_date; }}, // Day of the month without leading zeros {'t': 'j', 'r': '0?[1-9]|[12][0-9]|3[01]', 'p': function (d_date, n_value) { d_date.setDate(Number(n_value)); if (d_date.getDate() != n_value) d_date.setDate(0); return d_date }, 'g': function (d_date) { var n_date = d_date.getDate(); return n_date; }}, // A full textual representation of the day of the week {'t': 'l', 'r': A_TCALCONF.longwdays.join('|'), 'p': function (d_date, s_value) { return d_date }, 'g': function (d_date) { return A_TCALCONF.longwdays[d_date.getDay()]; }}, // English ordinal suffix for the day of the month, 2 characters {'t': 'S', 'r': 'st|nd|rd|th', 'p': function (d_date, s_value) { return d_date }, 'g': function (d_date) { n_date = d_date.getDate(); if (n_date % 10 == 1 && n_date != 11) return 'st'; if (n_date % 10 == 2 && n_date != 12) return 'nd'; if (n_date % 10 == 3 && n_date != 13) return 'rd'; return 'th'; }} ]; function f_tcalGetHTML (d_date) { var e_input = f_tcalGetInputs(true); if (!e_input) return; var s_pfx = A_TCALCONF.cssprefix, s_format = A_TCALCONF.format; // today from config or client date var d_today = f_tcalParseDate(A_TCALCONF.today, A_TCALCONF.format); if (!d_today) d_today = f_tcalResetTime(new Date()); // selected date from input or config or today var d_selected = f_tcalParseDate(e_input.value, s_format); if (!d_selected) d_selected = f_tcalParseDate(A_TCALCONF.selected, A_TCALCONF.format); if (!d_selected) d_selected = new Date(d_today); // show calendar for passed or selected date d_date = d_date ? f_tcalResetTime(d_date) : new Date(d_selected); var d_firstDay = new Date(d_date); d_firstDay.setDate(1); d_firstDay.setDate(1 - (7 + d_firstDay.getDay() - A_TCALCONF.weekstart) % 7); var a_class, s_html = '<table id="' + s_pfx + 'Controls"><tbody><tr>' + (A_TCALCONF.yearscroll ? '<td id="' + s_pfx + 'PrevYear" ' + f_tcalRelDate(d_date, -1, 'y') + ' title="' + A_TCALCONF.prevyear + '"></td>' : '') + '<td id="' + s_pfx + 'PrevMonth"' + f_tcalRelDate(d_date, -1) + ' title="' + A_TCALCONF.prevmonth + '"></td><th>' + A_TCALCONF.months[d_date.getMonth()] + ' ' + d_date.getFullYear() + '</th><td id="' + s_pfx + 'NextMonth"' + f_tcalRelDate(d_date, 1) + ' title="' + A_TCALCONF.nextmonth + '"></td>' + (A_TCALCONF.yearscroll ? '<td id="' + s_pfx + 'NextYear"' + f_tcalRelDate(d_date, 1, 'y') + ' title="' + A_TCALCONF.nextyear + '"></td>' : '') + '</tr></tbody></table><table id="' + s_pfx + 'Grid"><tbody><tr>'; // print weekdays titles for (var i = 0; i < 7; i++) s_html += '<th>' + A_TCALCONF.weekdays[(A_TCALCONF.weekstart + i) % 7] + '</th>'; s_html += '</tr>' ; // print calendar table var n_date, n_month, d_current = new Date(d_firstDay); while (d_current.getMonth() == d_date.getMonth() || d_current.getMonth() == d_firstDay.getMonth()) { s_html +='<tr>'; for (var n_wday = 0; n_wday < 7; n_wday++) { a_class = []; n_date = d_current.getDate(); n_month = d_current.getMonth(); if (d_current.getMonth() != d_date.getMonth()) a_class[a_class.length] = s_pfx + 'OtherMonth'; if (d_current.getDay() == 0 || d_current.getDay() == 6) a_class[a_class.length] = s_pfx + 'Weekend'; if (d_current.valueOf() == d_today.valueOf()) a_class[a_class.length] = s_pfx + 'Today'; if (d_current.valueOf() == d_selected.valueOf()) a_class[a_class.length] = s_pfx + 'Selected'; s_html += '<td' + f_tcalRelDate(d_current) + (a_class.length ? ' class="' + a_class.join(' ') + '">' : '>') + n_date + '</td>'; d_current.setDate(++n_date); } s_html +='</tr>'; } s_html +='</tbody></table>'; return s_html; } function f_tcalRelDate (d_date, d_diff, s_units) { var s_units = (s_units == 'y' ? 'FullYear' : 'Month'); var d_result = new Date(d_date); if (d_diff) { d_result['set' + s_units](d_date['get' + s_units]() + d_diff); if (d_result.getDate() != d_date.getDate()) d_result.setDate(0); } return ' onclick="f_tcalUpdate(' + d_result.valueOf() + (d_diff ? ',1' : '') + ')"'; } function f_tcalResetTime (d_date) { d_date.setMilliseconds(0); d_date.setSeconds(0); d_date.setMinutes(0); d_date.setHours(12); return d_date; } // closes calendar and returns all inputs to default state function f_tcalCancel () { var s_pfx = A_TCALCONF.cssprefix; var e_cal = document.getElementById(s_pfx); if (e_cal) e_cal.style.visibility = ''; var a_inputs = f_tcalGetInputs(); for (var n = 0; n < a_inputs.length; n++) f_tcalRemoveClass(a_inputs[n], s_pfx + 'Active'); } function f_tcalUpdate (n_date, b_keepOpen) { var e_input = f_tcalGetInputs(true); if (!e_input) return; d_date = new Date(n_date); var s_pfx = A_TCALCONF.cssprefix; if (b_keepOpen) { var e_cal = document.getElementById(s_pfx); if (!e_cal || e_cal.style.visibility != 'visible') return; e_cal.innerHTML = f_tcalGetHTML(d_date, e_input); } else { e_input.value = f_tcalGenerateDate(d_date, A_TCALCONF.format); f_tcalCancel(); } } function f_tcalOnClick () { // see if already opened var s_pfx = A_TCALCONF.cssprefix; var s_activeClass = s_pfx + 'Active'; var b_close = f_tcalHasClass(this, s_activeClass); // close all clalendars f_tcalCancel(); if (b_close) return; // get position of input f_tcalAddClass(this, s_activeClass); var n_left = f_getPosition (this, 'Left'), n_top = f_getPosition (this, 'Top') + this.offsetHeight; var e_cal = document.getElementById(s_pfx); if (!e_cal) { e_cal = document.createElement('div'); e_cal.onselectstart = function () { return false }; e_cal.id = s_pfx; document.getElementsByTagName("body").item(0).appendChild(e_cal); } e_cal.innerHTML = f_tcalGetHTML(null); e_cal.style.top = n_top + 'px'; e_cal.style.left = (n_left + this.offsetWidth - e_cal.offsetWidth) + 'px'; e_cal.style.visibility = 'visible'; } function f_tcalParseDate (s_date, s_format) { if (!s_date) return; var s_char, s_regexp = '^', a_tokens = {}, a_options, n_token = 0; for (var n = 0; n < s_format.length; n++) { s_char = s_format.charAt(n); if (A_TCALTOKENS_IDX[s_char]) { a_tokens[s_char] = ++n_token; s_regexp += '(' + A_TCALTOKENS_IDX[s_char]['r'] + ')'; } else if (s_char == ' ') s_regexp += '\\s'; else s_regexp += (s_char.match(/[\w\d]/) ? '' : '\\') + s_char; } var r_date = new RegExp(s_regexp + '$'); if (!s_date.match(r_date)) return; var s_val, d_date = f_tcalResetTime(new Date()); d_date.setDate(1); for (n = 0; n < A_TCALTOKENS.length; n++) { s_char = A_TCALTOKENS[n]['t']; if (!a_tokens[s_char]) continue; s_val = RegExp['$' + a_tokens[s_char]]; d_date = A_TCALTOKENS[n]['p'](d_date, s_val); } return d_date; } function f_tcalGenerateDate (d_date, s_format) { var s_char, s_date = ''; for (var n = 0; n < s_format.length; n++) { s_char = s_format.charAt(n); s_date += A_TCALTOKENS_IDX[s_char] ? A_TCALTOKENS_IDX[s_char]['g'](d_date) : s_char; } return s_date; } function f_tcalGetInputs (b_active) { var a_inputs = document.getElementsByTagName('input'), e_input, s_rel, a_result = []; for (n = 0; n < a_inputs.length; n++) { e_input = a_inputs[n]; if (!e_input.type || e_input.type != 'text') continue; if (!f_tcalHasClass(e_input, 'tcal')) continue; if (b_active && f_tcalHasClass(e_input, A_TCALCONF.cssprefix + 'Active')) return e_input; a_result[a_result.length] = e_input; } return b_active ? null : a_result; } function f_tcalHasClass (e_elem, s_class) { var s_classes = e_elem.className; if (!s_classes) return false; var a_classes = s_classes.split(' '); for (var n = 0; n < a_classes.length; n++) if (a_classes[n] == s_class) return true; return false; } function f_tcalAddClass (e_elem, s_class) { if (f_tcalHasClass (e_elem, s_class)) return; var s_classes = e_elem.className; e_elem.className = (s_classes ? s_classes + ' ' : '') + s_class; } function f_tcalRemoveClass (e_elem, s_class) { var s_classes = e_elem.className; if (!s_classes || s_classes.indexOf(s_class) == -1) return false; var a_classes = s_classes.split(' '), a_newClasses = []; for (var n = 0; n < a_classes.length; n++) { if (a_classes[n] == s_class) continue; a_newClasses[a_newClasses.length] = a_classes[n]; } e_elem.className = a_newClasses.join(' '); return true; } function f_getPosition (e_elemRef, s_coord) { var n_pos = 0, n_offset, e_elem = e_elemRef; while (e_elem) { n_offset = e_elem["offset" + s_coord]; n_pos += n_offset; e_elem = e_elem.offsetParent; } e_elem = e_elemRef; while (e_elem != document.body) { n_offset = e_elem["scroll" + s_coord]; if (n_offset && e_elem.style.overflow == 'scroll') n_pos -= n_offset; e_elem = e_elem.parentNode; } return n_pos; } function f_tcalInit () { if (!document.getElementsByTagName) return; var e_input, a_inputs = f_tcalGetInputs(); for (var n = 0; n < a_inputs.length; n++) { e_input = a_inputs[n]; e_input.onclick = f_tcalOnClick; f_tcalAddClass(e_input, A_TCALCONF.cssprefix + 'Input'); } window.A_TCALTOKENS_IDX = {}; for (n = 0; n < A_TCALTOKENS.length; n++) A_TCALTOKENS_IDX[A_TCALTOKENS[n]['t']] = A_TCALTOKENS[n]; } function f_tcalAddOnload (f_func) { if (document.addEventListener) { window.addEventListener('load', f_func, false); } else if (window.attachEvent) { window.attachEvent('onload', f_func); } else { var f_onLoad = window.onload; if (typeof window.onload != 'function') { window.onload = f_func; } else { window.onload = function() { f_onLoad(); f_func(); } } } } f_tcalAddOnload (f_tcalInit);
import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; const ArrowUpCircle = forwardRef(({ color = 'currentColor', size = 24, ...rest }, ref) => { return ( <svg ref={ref} xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...rest} > <circle cx="12" cy="12" r="10" /> <polyline points="16 12 12 8 8 12" /> <line x1="12" y1="16" x2="12" y2="8" /> </svg> ); }); ArrowUpCircle.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; ArrowUpCircle.displayName = 'ArrowUpCircle'; export default ArrowUpCircle;
(function () { 'use strict'; var gulp = require('gulp'); var gutil = require('gulp-util'); var injectdep = require('gulp-inject'); var bowerFiles = require('main-bower-files'); var angularFilesort = require('gulp-angular-filesort'); var order = require('gulp-order'); var argv = require('yargs').argv; var paths = require('./path.json'); // inject js gulp.task('inject:js', ['inject:init'], function () { return gulp.src(paths.indexSrc) .pipe(injectdep( gulp.src(paths.js, { read: true // true it's needed by angularFilesort() }) .pipe(angularFilesort()), { ignorePath: paths.ignorePath, addRootSlash: paths.addRootSlash })) .pipe(gulp.dest(paths.dest)); }); // inject css gulp.task('inject:css', ['inject:js'], function () { return gulp.src(paths.indexSrc) .pipe(injectdep( gulp.src(paths.css, { read: false }), { ignorePath: paths.ignorePath, addRootSlash: paths.addRootSlash })) .pipe(gulp.dest(paths.dest)); }); // inject bower components gulp.task('inject:bower', ['inject:css'], function () { return gulp.src(paths.indexSrc) .pipe( injectdep( gulp.src( bowerFiles(), { read: false } ) .pipe(order(paths.bowerOrder)), { ignorePath: paths.ignorePath, addRootSlash: paths.addRootSlash, starttag: '<!-- bower:{{ext}} -->' } ) ) .pipe( injectdep( gulp.src( paths.vendors, { read: false } ), { ignorePath: paths.ignorePath, addRootSlash: paths.addRootSlash, starttag: '<!-- vendor:{{ext}} -->' } ) ) .pipe(gulp.dest(paths.dest)); }); gulp.task('inject:init', function () { var fs = require('fs'); var rename = require('gulp-rename'); var gulpNgConfig = require('gulp-ng-config'); var config; var configString; var configFile = 'local-config.json'; if (argv.production) { configFile = 'production-config.json'; } try { configString = fs.readFileSync(configFile); config = JSON.parse(configString); } catch (err) { gutil.log('There has been an error parsing your JSON. A default values will be created'); config = { socketUrl: 'http://192.168.33.10:3000', restBaseUrl: 'http://192.168.33.10:3000' }; configString = JSON.stringify(config); try { fs.writeFileSync(configFile, configString, 'utf8'); } catch (err) { console.log('There has been an error saving your configuration data.'); console.log(err.message); return; } } gulp.src(configFile) .pipe(gulpNgConfig('xyz.socket.chat.env')) .pipe(gulp.dest(paths.envFolder)); return gulp.src(paths.template) .pipe(rename('index.html')) .pipe(gulp.dest(paths.dest)); }); gulp.task('inject', ['inject:bower']); })();
import React, {Component} from 'react'; import styles from './styles.scss'; class TopMenuProfile extends Component { render() { return ( <ul> <li style={{display: 'inline', verticalAlign: 'middle'}}><img className={styles.profileImage} src="http://image.xboxlive.com/global/t.434f07d2/tile/0/28002" /></li> <li style={{display: 'inline-block', verticalAlign: 'middle'}}> <ul style={{listStyle: 'none', paddingLeft: '0.5vw'}}> <li style={{position: 'relative', top: '0.5vw'}}><b>Yotam</b></li> <li className={styles.statusOnlineCircle}></li> <li style={{fontSize: '0.75vw', display: 'inline-block'}}>Online</li> <li style={{display: 'inline-block', color: '#617009'}}> <i className="fa fa-angle-down" aria-hidden="true" style={{position: 'relative', top:'0.7vw', fontSize:'1.75vw'}}></i> </li> </ul> </li> </ul> ); } } export default TopMenuProfile;
var redis = require('redis').createClient(); var uuid = require('node-uuid'); var mongoose = require('mongoose'); var request = require('request'); var Alarm = mongoose.model('Alarm'); var timeGen = function (){ var t = new Date; var m = t.getMinutes(), h = t.getHours() return 1111; } var running_alarm_step = {}; var running_alarm_step_counter = {}; var playPluginWithId = function (id, attr, stream, cb){ try { var p = require(process.cwd() + '/plugins/' + id + '/index.js'); p(stream, attr, cb); } catch (e){ console.log(e); return stream.status(500).send('FAILERINO'); cb(e); } } module.exports = { stream: function (req, res, next){ var id = req.params.id; Alarm.getAlarmByUuid(id, function (err, alarm){ if(err) return res.send(500); if(!alarm) return res.send(404); if(running_alarm_step_counter[uuid] == undefined){ console.log('FIRST REQUEST'); running_alarm_step_counter[uuid] = 0; } if(running_alarm_step_counter[uuid] % 2 == 0){ running_alarm_step_counter[uuid] += 1; console.log('IGNORING REQUEST'); return res.send(500); } else { if(running_alarm_step && running_alarm_step[uuid] >= 0){ console.log('STEP:' + running_alarm_step[uuid]); var i = running_alarm_step[uuid]; var to_run = Object.keys(alarm.plugins)[i]; if(!to_run){ console.log('NOMOAR'); delete running_alarm_step[uuid]; return res.send(404); } console.log('RUN-STEP', to_run); var attr = alarm.plugins[to_run] || {}; running_alarm_step[uuid] += 1; playPluginWithId(to_run, attr, res, function (err){ console.log(err, 'Pluging finished playing'); }); } else if ( alarm.enable && alarm.time ){ console.log('Saying good morning'); running_alarm_step[uuid] = 0; playPluginWithId('alarm', {text: 'Good morning!', lang: 'en'}, res, function (err){ console.log(err, 'Pluging finished playing'); }); } else { res.send('NON PLAYERINOS'); } } }); }, setup: function (req, res, next){ redis.incr('client_counter', function (err, count){ var id = uuid.v1(); var major = parseInt(count / 65536, 10); var minor = parseInt(count % 65536); var stringId = 'id:'+major+'-'+minor; redis.set(stringId, id); redis.set('uuid:'+id, major+'-'+minor); res.send({ minor: minor, major: major, client_id: id, stream_url: '/stream/' + id }); }); }, shutup: function (req, res, next){ var id = req.params.id; res.status(200).end(); }, erase: function (req, res, next){ var id = req.params.id; if(streams && streams[id]){ streams[id].close(); delete streams[id]; } redis.get('uuid:'+id, function (err, ids){ if(err){ res.status(500).end(); next(); } if(!ids){ res.status(404).end(); next(); } redis.del('uuid:'+id); redis.del('id:'+ids); res.status(200).end(); next(); }); } }
'use strict'; app.factory('accountService', function ($http, $q, $location, localStorageService, tsBBSettings) { var serviceBase = tsBBSettings.apiBaseUri; var accountServiceFactory = {}; var _authentication = { token: '', email: '', authenticated: false }; var _users = function () { var deferred = $q.defer(); $http .get(serviceBase + 'account/users') .then(function (response) { deferred.resolve(response); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }; var _login = function (user) { var userData = { email: user.email, password: user.password }; var deferred = $q.defer(); $http .post(serviceBase + 'account/login', userData) .then(function (response) { _authentication.token = response.data.token; _authentication.email = response.data.Email; _authentication.authenticated = true; localStorageService.set('userData', _authentication); deferred.resolve(response); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }; var _register = function (user) { var userData = { email: user.email, password: user.password }; var deferred = $q.defer(); $http .post(serviceBase + 'account/register', userData) .then(function (response) { deferred.resolve(response); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }; var _logOut = function () { localStorageService.remove('userData'); _authentication.authenticated = false; _authentication.token = ""; $location.path('/'); }; var _userData = function () { var userData = localStorageService.get('userData'); if (userData) { _authentication.authenticated = userData.authenticated; } }; var _authorize = function (accountService) { if (accountService && accountService.authentication.authenticated === true) return true; throw new AuthorizationError("User not authenticated."); }; accountServiceFactory.users = _users; accountServiceFactory.login = _login; accountServiceFactory.register = _register; accountServiceFactory.logOut = _logOut; accountServiceFactory.userData = _userData; accountServiceFactory.authentication = _authentication; accountServiceFactory.authorize = _authorize; return accountServiceFactory; } ); // Custom error type function AuthorizationError(description) { this.forbidden = "Forbidden"; this.message = description || this.forbidden; this.description = description || this.message; } AuthorizationError.prototype = Object.create(Error.prototype); AuthorizationError.prototype.constructor = AuthorizationError;
search_result['4536']=["topic_0000000000000AE7.html","PaymentException(String, Exception) Constructor",""];
"use strict" module.exports = imshow var consoleImg = require("console-image") var savePixels = require("save-pixels") var colorize = require("./do-colorize.js") function imshow(array, options) { colorize(array, options, function(img) { consoleImg(savePixels(img, "canvas")) }) }