code
stringlengths
2
1.05M
function overviewCtr($scope, $http) { Highcharts.setOptions({global: {useUTC: true}}); $scope.chartConfig = { options: { chart: { type: 'spline', zoomType: 'xy' }, tooltip: { formatter: function () { return '<b>' + this.series.name + '</b><br/>时间 : ' + Highcharts.dateFormat('%H:%M:%S', new Date(this.x * 1000)) + ' 值 : ' + this.y; } } }, title: {}, xAxis: { labels: { formatter: function () { return Highcharts.dateFormat('%H:%M', new Date(this.value * 1000)) } } }, yAxis: { title: {} }, series: [{name: '平均', data: []}] }; $http.get('/emc/data/avgday.json').success(function (data) { if (typeof(data) == "undefined") return; $scope.ajaxHistoryData = {average: []}; for (var item in data) { var time = Number(data[item].time); $scope.ajaxHistoryData.average.push([time, { 'flow': Number(data[item].flow), 'count': Number(data[item].count), 'requests': Number(data[item].requests) }]); } $scope.switchChart(0); }); $scope.switchChart = function (p) { if (typeof($scope.ajaxHistoryData) == "undefined") return; var textMap = ["人数", "流量", "请求"]; var nameMap = ["count", "flow", "requests"]; function chartDataAdapter(dataObject, proName) { var res = []; for (var item in dataObject) { res.unshift({ x: dataObject[item][0] * 3600, y: Number(dataObject[item][1][proName]) }); } return res; } $scope.chartMode = p; $scope.chartConfig.title.text = "平均" + textMap[p]; $scope.chartConfig.yAxis.title.text = textMap[p]; $scope.chartConfig.series[0].data = chartDataAdapter($scope.ajaxHistoryData.average, nameMap[p]); } } function mapviewCtr($scope) { $.getScript("/emc/js/maploader.js"); } function detailCtr($scope, $routeParams, $http) { Highcharts.setOptions({global: {useUTC: false}}); switch ($routeParams.id) { case "library": $scope.PageTitle = "图书馆 详细信息"; $http.get('/emc/data/detail_library.json').success(ajaxCallback); $http.get('/emc/data/history_library.json').success(historyCallback); break; case "cafeteria": $scope.PageTitle = "食堂 详细信息"; $http.get('/emc/data/detail_cafeteria.json').success(ajaxCallback); $http.get('/emc/data/history_cafeteria.json').success(historyCallback); break; case "classroom": $scope.PageTitle = "教室 详细信息"; $http.get('/emc/data/detail_classroom.json').success(ajaxCallback); $http.get('/emc/data/history_classroom.json').success(historyCallback); break; default: $scope.PageTitle = "详细信息"; } $scope.chartConfig = { options: { chart: { type: 'area', zoomType: 'xy' }, plotOptions: { area: { stacking: 'normal', lineColor: '#666666', lineWidth: 1, marker: { enabled: false } } }, tooltip: { shared: true, valueSuffix: '' } }, title: { text: '' }, xAxis: { labels: { formatter: function () { return Highcharts.dateFormat('%H:%M', new Date((this.value-8) * 3600 * 1000)) } }, title: { text: '时间' } }, yAxis: { title: { text: '' } }, series: [], credits: { enabled: false } }; function ajaxCallback(data) { $scope.detailData = data; $scope.row = {user: "用户", flow: "流量", request: "请求"}; var slaveChartData = []; for (var i in $scope.detailData) { slaveChartData.push([$scope.detailData[i].location, $scope.detailData[i].count - 0]); } $scope.slave_chartConfig = { title: { text: '用户分布' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, color: '#000000', connectorColor: '#000000', format: '<b>{point.name}</b>: {point.percentage:.1f} %' } } }, credits: { enabled: false }, series: [{ data: slaveChartData, type: 'pie', name: '用户人数' }] }; } //ajaxCallback END function historyCallback(data) { var his_data = data; if (typeof(his_data) == "undefined") return; var tmpHistoryObj = {count: {}, requests: {}, bytes: {}}; for (var item in his_data) { if (typeof(his_data[item].time) == "undefined") continue; var time = Number(his_data[item].time); if (tmpHistoryObj.count[his_data[item].location] == undefined) tmpHistoryObj.count[his_data[item].location] = []; tmpHistoryObj.count[his_data[item].location].unshift({ x: time, y: Number(his_data[item].count) }); } for (var item in his_data) { if (typeof(his_data[item].time) == "undefined") continue; var time = Number(his_data[item].time); if (tmpHistoryObj.requests[his_data[item].location] == undefined) tmpHistoryObj.requests[his_data[item].location] = []; tmpHistoryObj.requests[his_data[item].location].unshift({ x: time, y: Number(his_data[item].requests) }); } for (var item in his_data) { if (typeof(his_data[item].time) == "undefined") continue; var time = Number(his_data[item].time); if (tmpHistoryObj.bytes[his_data[item].location] == undefined) tmpHistoryObj.bytes[his_data[item].location] = []; tmpHistoryObj.bytes[his_data[item].location].unshift({ x: time, y: Number(his_data[item].bytes) }); } $scope.chartData = {count: [], requests: [], bytes: []}; for (var name in tmpHistoryObj.count) { if (tmpHistoryObj.count.hasOwnProperty(name)) { $scope.chartData.count.push({"name": name, "data": tmpHistoryObj.count[name]}); } } for (var name in tmpHistoryObj.requests) { if (tmpHistoryObj.requests.hasOwnProperty(name)) { $scope.chartData.requests.push({"name": name, "data": tmpHistoryObj.requests[name]}); } } for (var name in tmpHistoryObj.bytes) { if (tmpHistoryObj.bytes.hasOwnProperty(name)) { $scope.chartData.bytes.push({"name": name, "data": tmpHistoryObj.bytes[name]}); } } $scope.switchChart = function (p) { $scope.chartMode = p; if (p == 0) { $scope.chartConfig.series = $scope.chartData.count; $scope.chartConfig.title.text = "平均人数变化趋势"; $scope.chartConfig.yAxis.title.text = "平均人数"; $scope.chartConfig.options.tooltip.valueSuffix = " 人"; } else if (p == 1) { $scope.chartConfig.series = $scope.chartData.requests; $scope.chartConfig.title.text = "平均请求数变化趋势"; $scope.chartConfig.yAxis.title.text = "平均请求数"; $scope.chartConfig.options.tooltip.valueSuffix = " 次"; } else { $scope.chartConfig.series = $scope.chartData.bytes; $scope.chartConfig.title.text = "平均流量变化趋势"; $scope.chartConfig.yAxis.title.text = "平均流量"; $scope.chartConfig.options.tooltip.valueSuffix = " Bytes"; } }; $scope.switchChart(0); } } function similarCtr($scope, $http) { $scope.findSimilar = function(user_id) { $http.get('http://maview.us/emc/api/similar/'+String(user_id)).success(function (data) { if (typeof(data) == "undefined") return; $scope.result = data; }); }; } function scoreCtr($scope, $http) { $scope.chartConfig = { options: { chart: { type: 'spline', zoomType: 'xy' }, tooltip: { } }, title: { text:"学霸指数成长变化" }, xAxis: { labels: { } }, yAxis: { title: {} }, series: [{name: '学霸指数', data: []}] }; $scope.getScore = function(user_id) { $http.get('http://maview.us/emc/api/score/'+String(user_id)).success(function (data) { if (typeof(data) == "undefined") return; $scope.result = {}; $scope.result.score = String((Number(data.score)*100).toFixed(1)) + " %"; }); }; $scope.result = {score: "0.0 %"}; }
var mssql = require('mssql'); var config = { user: 'wbuser', password: 'Hide0313', server: 'wbcompnay-sample.database.windows.net', // You can use 'localhost\\instance' to connect to named instance database: 'wb-sqldb', stream: true, // You can enable streaming globally options: { encrypt: true // Use this if you're on Windows Azure } } var http = require('http'); var express = require('express'); var path = require('path'); var app = express(); var bodyParser = require('body-parser'); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname,'public'))); //var server = http.createServer(function(request, response) { // response.writeHead(200, {"Content-Type": "text/plain"}); // response.end("Hello Azure!!"); //}); var port = process.env.PORT || 1338; //server.listen(port); app.get('/', function (req, res) { console.log("root"); res.render('index', { title: 'APIサンプル'}); }); app.get('/chart', function (req, res) { console.log("chart"); res.render('chart'); }); app.get('/connectsql', function (req, res) { console.log("connecting..."); mssql.connect(config, function(err) { var request = new mssql.Request(); request.query('select * from onoue',function(err,recordset) { if(err) console.log(err) console.log(recordset); }); }); }); app.listen(port,function(){ console.log("Running on port " + port); });
var test = require('tape') , rhumb = require('../../src/rhumb') , utils = require('../utils') test('Parsing should find a partial part with fixed left and right', function (t) { t.plan(7) var results = rhumb._parse('/left{page}right') , matchFunction = results.segments[0].matchFunction t.deepEqual(results.segments, [ utils.partialSegment('left{var}right', ['page'], matchFunction) ], 'has one partial segment with fixed left and right') t.ok(rhumb._parse('/left{page}right').leadingSlash, 'has a leading slash') t.notOk(rhumb._parse('/left{page}right').trailingSlash, 'has no trailing slash') t.deepEqual(matchFunction('middleright'), null, 'when partial is not match no results are returned') t.deepEqual(matchFunction('leftright'), null, 'when empty partial match no results are returned') t.deepEqual(matchFunction('leftmiddleright'), { page: 'middle' }, 'match function finds word in middle') t.deepEqual(matchFunction('left-middle-right'), { page: '-middle-' }, 'match function finds word in middle') }) test('Parsing should find a partial part with fixed right', function (t) { t.plan(7) var results = rhumb._parse('/{page}right') , matchFunction = results.segments[0].matchFunction t.deepEqual(results.segments, [ utils.partialSegment('{var}right', ['page'], matchFunction) ], 'has one partial segment with fixed right') t.ok(rhumb._parse('/{page}right').leadingSlash, 'has a leading slash') t.notOk(rhumb._parse('/{page}right').trailingSlash, 'has no trailing slash') t.deepEqual(matchFunction('left'), null, 'when partial is not match no results are returned') t.deepEqual(matchFunction('right'), null, 'when empty partial match no results are returned') t.deepEqual(matchFunction('leftright'), { page: 'left' }, 'match function finds word on the left') t.deepEqual(matchFunction('left-middle-right'), { page: 'left-middle-' }, 'match function finds word on the left') }) test('Parsing should find a partial part with fixed left', function (t) { t.plan(7) var results = rhumb._parse('/left{page}') , matchFunction = results.segments[0].matchFunction t.deepEqual(results.segments, [ utils.partialSegment('left{var}', ['page'], matchFunction) ], 'has one partial segment with fixed left') t.ok(rhumb._parse('/left{page}').leadingSlash, 'has a leading slash') t.notOk(rhumb._parse('/left{page}').trailingSlash, 'has no trailing slash') t.deepEqual(matchFunction('right'), null, 'when partial is not match no results are returned') t.deepEqual(matchFunction('left'), null, 'when empty partial match no results are returned') t.deepEqual(matchFunction('leftright'), { page: 'right' }, 'match function finds word on the right') t.deepEqual(matchFunction('left-middle-right'), { page: '-middle-right' }, 'match function finds word on the right') }) test('Parsing should find a partial part with many variables', function (t) { t.plan(6) var results = rhumb._parse('/{day}-{month}-{year}') , matchFunction = results.segments[0].matchFunction t.deepEqual(results.segments, [ utils.partialSegment('{var}-{var}-{var}', ['day', 'month', 'year'], matchFunction) ], 'has one partial segment with three variables') t.ok(rhumb._parse('/{day}-{month}-{year}').leadingSlash, 'has a leading slash') t.notOk(rhumb._parse('/{day}-{month}-{year}').trailingSlash, 'has no trailing slash') t.deepEqual(matchFunction('07.03.2017'), null, 'when partial is not match no results are returned') t.deepEqual(matchFunction('-03-2017'), null, 'when empty partial match no results are returned') t.deepEqual(matchFunction('07-03-2017'), { day: '07', month: '03', year: '2017' }, 'match function find values of all variables') })
/** * @module Config * @desc require.js config */ requirejs.config({ /* * baseUrl is set in HTML to be 'assets-dev/js/' * or 'assets/js/' for stage and production */ /** Aliases for paths */ paths: { models: 'src/models/', jquery: 'lib/jquery', backbone: 'lib/backbone', lodash: 'lib/lodash', text: 'lib/text', bootstrap: 'lib/bootstrap' }, /** Dependencies for non-AMD stuff */ shim: { bootstrap: ['jquery'], backbone: { deps: [ 'jquery', 'lodash' ], exports: 'backbone' } }, /** Stop Backbone calling Underscore.js, we want Lodash */ map: { '*': { 'underscore': 'lodash' } } }); /** * Init the main app view * @requires src/models/base-model */ require([ 'backbone', 'src/views/app' ], function (Backbone, AppView) { 'use strict'; new AppView(); });
import $ from 'jquery' /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0): util.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ const Util = (($) => { /** * ------------------------------------------------------------------------ * Private TransitionEnd Helpers * ------------------------------------------------------------------------ */ const TRANSITION_END = 'transitionend' const MAX_UID = 1000000 const MILLISECONDS_MULTIPLIER = 1000 // Shoutout AngusCroll (https://goo.gl/pxwQGp) function toType(obj) { return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase() } function getSpecialTransitionEndEvent() { return { bindType: TRANSITION_END, delegateType: TRANSITION_END, handle(event) { if ($(event.target).is(this)) { return event.handleObj.handler.apply(this, arguments) // eslint-disable-line prefer-rest-params } return undefined // eslint-disable-line no-undefined } } } function transitionEndEmulator(duration) { let called = false $(this).one(Util.TRANSITION_END, () => { called = true }) setTimeout(() => { if (!called) { Util.triggerTransitionEnd(this) } }, duration) return this } function setTransitionEndSupport() { $.fn.emulateTransitionEnd = transitionEndEmulator $.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent() } /** * -------------------------------------------------------------------------- * Public Util Api * -------------------------------------------------------------------------- */ const Util = { TRANSITION_END: 'bsTransitionEnd', getUID(prefix) { do { // eslint-disable-next-line no-bitwise prefix += ~~(Math.random() * MAX_UID) // "~~" acts like a faster Math.floor() here } while (document.getElementById(prefix)) return prefix }, getSelectorFromElement(element) { let selector = element.getAttribute('data-target') if (!selector || selector === '#') { selector = element.getAttribute('href') || '' } try { const $selector = $(document).find(selector) return $selector.length > 0 ? selector : null } catch (err) { return null } }, getTransitionDurationFromElement(element) { if (!element) { return 0 } // Get transition-duration of the element let transitionDuration = $(element).css('transition-duration') const floatTransitionDuration = parseFloat(transitionDuration) // Return 0 if element or transition duration is not found if (!floatTransitionDuration) { return 0 } // If multiple durations are defined, take the first transitionDuration = transitionDuration.split(',')[0] return parseFloat(transitionDuration) * MILLISECONDS_MULTIPLIER }, reflow(element) { return element.offsetHeight }, triggerTransitionEnd(element) { $(element).trigger(TRANSITION_END) }, // TODO: Remove in v5 supportsTransitionEnd() { return Boolean(TRANSITION_END) }, isElement(obj) { return (obj[0] || obj).nodeType }, typeCheckConfig(componentName, config, configTypes) { for (const property in configTypes) { if (Object.prototype.hasOwnProperty.call(configTypes, property)) { const expectedTypes = configTypes[property] const value = config[property] const valueType = value && Util.isElement(value) ? 'element' : toType(value) if (!new RegExp(expectedTypes).test(valueType)) { throw new Error( `${componentName.toUpperCase()}: ` + `Option "${property}" provided type "${valueType}" ` + `but expected type "${expectedTypes}".`) } } } } } setTransitionEndSupport() return Util })($) export default Util
/* Thing > CreativeWork > MusicPlaylist - A collection of music tracks in playlist form.. Generated automatically by the reactGenerator. */ var MusicPlaylist= React.createClass({ getDefaultProps: function(){ return { } }, render: function(){ var props = this.props.props; var comment; if( props.comment ){ if( props.comment instanceof Array ){ comment = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] comment = comment.concat( props.comment.map( function(result, index){ return ( <Comment {...result} key={index} /> ) }) ); comment.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { comment = ( <Comment props={ props.comment } /> ); } } var copyrightYear; if( props.copyrightYear ){ if( props.copyrightYear instanceof Array ){ copyrightYear = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] copyrightYear = copyrightYear.concat( props.copyrightYear.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. copyrightYear is a Number.'></div> ) }) ); copyrightYear.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { copyrightYear = ( <div data-advice='Put your HTML here. copyrightYear is a Number.'></div> ); } } var hasPart; if( props.hasPart ){ if( props.hasPart instanceof Array ){ hasPart = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] hasPart = hasPart.concat( props.hasPart.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); hasPart.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { hasPart = ( <CreativeWork props={ props.hasPart } /> ); } } var version; if( props.version ){ if( props.version instanceof Array ){ version = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] version = version.concat( props.version.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. version is a Number.'></div> ) }) ); version.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { version = ( <div data-advice='Put your HTML here. version is a Number.'></div> ); } } var producer; if( props.producer ){ if( props.producer instanceof Array ){ producer = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] producer = producer.concat( props.producer.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. producer is a Person or Organization.'></div> ) }) ); producer.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { producer = ( <div data-advice='Put your HTML here. producer is a Person or Organization.'></div> ); } } var creator; if( props.creator ){ if( props.creator instanceof Array ){ creator = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] creator = creator.concat( props.creator.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. creator is a Person or Organization.'></div> ) }) ); creator.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { creator = ( <div data-advice='Put your HTML here. creator is a Person or Organization.'></div> ); } } var publishingPrinciples; if( props.publishingPrinciples ){ if( props.publishingPrinciples instanceof Array ){ publishingPrinciples = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] publishingPrinciples = publishingPrinciples.concat( props.publishingPrinciples.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. publishingPrinciples is a URL.'></div> ) }) ); publishingPrinciples.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { publishingPrinciples = ( <div data-advice='Put your HTML here. publishingPrinciples is a URL.'></div> ); } } var text; if( props.text ){ if( props.text instanceof Array ){ text = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] text = text.concat( props.text.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. text is a Text.'></div> ) }) ); text.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { text = ( <div data-advice='Put your HTML here. text is a Text.'></div> ); } } var image; if( props.image ){ if( props.image instanceof Array ){ image = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] image = image.concat( props.image.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. image is a URL or ImageObject.'></div> ) }) ); image.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { image = ( <div data-advice='Put your HTML here. image is a URL or ImageObject.'></div> ); } } var citation; if( props.citation ){ if( props.citation instanceof Array ){ citation = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] citation = citation.concat( props.citation.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. citation is a CreativeWork or Text.'></div> ) }) ); citation.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { citation = ( <div data-advice='Put your HTML here. citation is a CreativeWork or Text.'></div> ); } } var sameAs; if( props.sameAs ){ if( props.sameAs instanceof Array ){ sameAs = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] sameAs = sameAs.concat( props.sameAs.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. sameAs is a URL.'></div> ) }) ); sameAs.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { sameAs = ( <div data-advice='Put your HTML here. sameAs is a URL.'></div> ); } } var datePublished; if( props.datePublished ){ if( props.datePublished instanceof Array ){ datePublished = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] datePublished = datePublished.concat( props.datePublished.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. datePublished is a Date.'></div> ) }) ); datePublished.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { datePublished = ( <div data-advice='Put your HTML here. datePublished is a Date.'></div> ); } } var commentCount; if( props.commentCount ){ if( props.commentCount instanceof Array ){ commentCount = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] commentCount = commentCount.concat( props.commentCount.map( function(result, index){ return ( <Integer {...result} key={index} /> ) }) ); commentCount.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { commentCount = ( <Integer props={ props.commentCount } /> ); } } var associatedMedia; if( props.associatedMedia ){ if( props.associatedMedia instanceof Array ){ associatedMedia = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] associatedMedia = associatedMedia.concat( props.associatedMedia.map( function(result, index){ return ( <MediaObject {...result} key={index} /> ) }) ); associatedMedia.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { associatedMedia = ( <MediaObject props={ props.associatedMedia } /> ); } } var alternativeHeadline; if( props.alternativeHeadline ){ if( props.alternativeHeadline instanceof Array ){ alternativeHeadline = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] alternativeHeadline = alternativeHeadline.concat( props.alternativeHeadline.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. alternativeHeadline is a Text.'></div> ) }) ); alternativeHeadline.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { alternativeHeadline = ( <div data-advice='Put your HTML here. alternativeHeadline is a Text.'></div> ); } } var accountablePerson; if( props.accountablePerson ){ if( props.accountablePerson instanceof Array ){ accountablePerson = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accountablePerson = accountablePerson.concat( props.accountablePerson.map( function(result, index){ return ( <Person {...result} key={index} /> ) }) ); accountablePerson.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accountablePerson = ( <Person props={ props.accountablePerson } /> ); } } var video; if( props.video ){ if( props.video instanceof Array ){ video = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] video = video.concat( props.video.map( function(result, index){ return ( <VideoObject {...result} key={index} /> ) }) ); video.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { video = ( <VideoObject props={ props.video } /> ); } } var url; if( props.url ){ if( props.url instanceof Array ){ url = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] url = url.concat( props.url.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. url is a URL.'></div> ) }) ); url.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { url = ( <div data-advice='Put your HTML here. url is a URL.'></div> ); } } var typicalAgeRange; if( props.typicalAgeRange ){ if( props.typicalAgeRange instanceof Array ){ typicalAgeRange = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] typicalAgeRange = typicalAgeRange.concat( props.typicalAgeRange.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. typicalAgeRange is a Text.'></div> ) }) ); typicalAgeRange.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { typicalAgeRange = ( <div data-advice='Put your HTML here. typicalAgeRange is a Text.'></div> ); } } var contributor; if( props.contributor ){ if( props.contributor instanceof Array ){ contributor = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] contributor = contributor.concat( props.contributor.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. contributor is a Person or Organization.'></div> ) }) ); contributor.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { contributor = ( <div data-advice='Put your HTML here. contributor is a Person or Organization.'></div> ); } } var additionalType; if( props.additionalType ){ if( props.additionalType instanceof Array ){ additionalType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] additionalType = additionalType.concat( props.additionalType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. additionalType is a URL.'></div> ) }) ); additionalType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { additionalType = ( <div data-advice='Put your HTML here. additionalType is a URL.'></div> ); } } var thumbnailUrl; if( props.thumbnailUrl ){ if( props.thumbnailUrl instanceof Array ){ thumbnailUrl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] thumbnailUrl = thumbnailUrl.concat( props.thumbnailUrl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. thumbnailUrl is a URL.'></div> ) }) ); thumbnailUrl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { thumbnailUrl = ( <div data-advice='Put your HTML here. thumbnailUrl is a URL.'></div> ); } } var mainEntity; if( props.mainEntity ){ if( props.mainEntity instanceof Array ){ mainEntity = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] mainEntity = mainEntity.concat( props.mainEntity.map( function(result, index){ return ( <Thing {...result} key={index} /> ) }) ); mainEntity.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { mainEntity = ( <Thing props={ props.mainEntity } /> ); } } var alternateName; if( props.alternateName ){ if( props.alternateName instanceof Array ){ alternateName = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] alternateName = alternateName.concat( props.alternateName.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. alternateName is a Text.'></div> ) }) ); alternateName.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { alternateName = ( <div data-advice='Put your HTML here. alternateName is a Text.'></div> ); } } var accessibilityFeature; if( props.accessibilityFeature ){ if( props.accessibilityFeature instanceof Array ){ accessibilityFeature = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accessibilityFeature = accessibilityFeature.concat( props.accessibilityFeature.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. accessibilityFeature is a Text.'></div> ) }) ); accessibilityFeature.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accessibilityFeature = ( <div data-advice='Put your HTML here. accessibilityFeature is a Text.'></div> ); } } var interactivityType; if( props.interactivityType ){ if( props.interactivityType instanceof Array ){ interactivityType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] interactivityType = interactivityType.concat( props.interactivityType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. interactivityType is a Text.'></div> ) }) ); interactivityType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { interactivityType = ( <div data-advice='Put your HTML here. interactivityType is a Text.'></div> ); } } var publication; if( props.publication ){ if( props.publication instanceof Array ){ publication = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] publication = publication.concat( props.publication.map( function(result, index){ return ( <PublicationEvent {...result} key={index} /> ) }) ); publication.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { publication = ( <PublicationEvent props={ props.publication } /> ); } } var discussionUrl; if( props.discussionUrl ){ if( props.discussionUrl instanceof Array ){ discussionUrl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] discussionUrl = discussionUrl.concat( props.discussionUrl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. discussionUrl is a URL.'></div> ) }) ); discussionUrl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { discussionUrl = ( <div data-advice='Put your HTML here. discussionUrl is a URL.'></div> ); } } var author; if( props.author ){ if( props.author instanceof Array ){ author = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] author = author.concat( props.author.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. author is a Person or Organization.'></div> ) }) ); author.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { author = ( <div data-advice='Put your HTML here. author is a Person or Organization.'></div> ); } } var headline; if( props.headline ){ if( props.headline instanceof Array ){ headline = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] headline = headline.concat( props.headline.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. headline is a Text.'></div> ) }) ); headline.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { headline = ( <div data-advice='Put your HTML here. headline is a Text.'></div> ); } } var review; if( props.review ){ if( props.review instanceof Array ){ review = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] review = review.concat( props.review.map( function(result, index){ return ( <Review {...result} key={index} /> ) }) ); review.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { review = ( <Review props={ props.review } /> ); } } var encoding; if( props.encoding ){ if( props.encoding instanceof Array ){ encoding = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] encoding = encoding.concat( props.encoding.map( function(result, index){ return ( <MediaObject {...result} key={index} /> ) }) ); encoding.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { encoding = ( <MediaObject props={ props.encoding } /> ); } } var character; if( props.character ){ if( props.character instanceof Array ){ character = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] character = character.concat( props.character.map( function(result, index){ return ( <Person {...result} key={index} /> ) }) ); character.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { character = ( <Person props={ props.character } /> ); } } var contentRating; if( props.contentRating ){ if( props.contentRating instanceof Array ){ contentRating = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] contentRating = contentRating.concat( props.contentRating.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. contentRating is a Text.'></div> ) }) ); contentRating.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { contentRating = ( <div data-advice='Put your HTML here. contentRating is a Text.'></div> ); } } var mainEntityOfPage; if( props.mainEntityOfPage ){ if( props.mainEntityOfPage instanceof Array ){ mainEntityOfPage = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] mainEntityOfPage = mainEntityOfPage.concat( props.mainEntityOfPage.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. mainEntityOfPage is a CreativeWork or URL.'></div> ) }) ); mainEntityOfPage.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { mainEntityOfPage = ( <div data-advice='Put your HTML here. mainEntityOfPage is a CreativeWork or URL.'></div> ); } } var educationalAlignment; if( props.educationalAlignment ){ if( props.educationalAlignment instanceof Array ){ educationalAlignment = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] educationalAlignment = educationalAlignment.concat( props.educationalAlignment.map( function(result, index){ return ( <AlignmentObject {...result} key={index} /> ) }) ); educationalAlignment.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { educationalAlignment = ( <AlignmentObject props={ props.educationalAlignment } /> ); } } var exampleOfWork; if( props.exampleOfWork ){ if( props.exampleOfWork instanceof Array ){ exampleOfWork = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] exampleOfWork = exampleOfWork.concat( props.exampleOfWork.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); exampleOfWork.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { exampleOfWork = ( <CreativeWork props={ props.exampleOfWork } /> ); } } var editor; if( props.editor ){ if( props.editor instanceof Array ){ editor = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] editor = editor.concat( props.editor.map( function(result, index){ return ( <Person {...result} key={index} /> ) }) ); editor.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { editor = ( <Person props={ props.editor } /> ); } } var provider; if( props.provider ){ if( props.provider instanceof Array ){ provider = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] provider = provider.concat( props.provider.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. provider is a Person or Organization.'></div> ) }) ); provider.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { provider = ( <div data-advice='Put your HTML here. provider is a Person or Organization.'></div> ); } } var isPartOf; if( props.isPartOf ){ if( props.isPartOf instanceof Array ){ isPartOf = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] isPartOf = isPartOf.concat( props.isPartOf.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); isPartOf.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { isPartOf = ( <CreativeWork props={ props.isPartOf } /> ); } } var recordedAt; if( props.recordedAt ){ if( props.recordedAt instanceof Array ){ recordedAt = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] recordedAt = recordedAt.concat( props.recordedAt.map( function(result, index){ return ( <Event {...result} key={index} /> ) }) ); recordedAt.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { recordedAt = ( <Event props={ props.recordedAt } /> ); } } var accessibilityHazard; if( props.accessibilityHazard ){ if( props.accessibilityHazard instanceof Array ){ accessibilityHazard = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accessibilityHazard = accessibilityHazard.concat( props.accessibilityHazard.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. accessibilityHazard is a Text.'></div> ) }) ); accessibilityHazard.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accessibilityHazard = ( <div data-advice='Put your HTML here. accessibilityHazard is a Text.'></div> ); } } var dateModified; if( props.dateModified ){ if( props.dateModified instanceof Array ){ dateModified = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] dateModified = dateModified.concat( props.dateModified.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. dateModified is a Date.'></div> ) }) ); dateModified.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { dateModified = ( <div data-advice='Put your HTML here. dateModified is a Date.'></div> ); } } var timeRequired; if( props.timeRequired ){ if( props.timeRequired instanceof Array ){ timeRequired = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] timeRequired = timeRequired.concat( props.timeRequired.map( function(result, index){ return ( <Duration {...result} key={index} /> ) }) ); timeRequired.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { timeRequired = ( <Duration props={ props.timeRequired } /> ); } } var description; if( props.description ){ if( props.description instanceof Array ){ description = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] description = description.concat( props.description.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. description is a Text.'></div> ) }) ); description.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { description = ( <div data-advice='Put your HTML here. description is a Text.'></div> ); } } var track; if( props.track ){ if( props.track instanceof Array ){ track = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] track = track.concat( props.track.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. track is a ItemList or MusicRecording.'></div> ) }) ); track.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { track = ( <div data-advice='Put your HTML here. track is a ItemList or MusicRecording.'></div> ); } } var learningResourceType; if( props.learningResourceType ){ if( props.learningResourceType instanceof Array ){ learningResourceType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] learningResourceType = learningResourceType.concat( props.learningResourceType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. learningResourceType is a Text.'></div> ) }) ); learningResourceType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { learningResourceType = ( <div data-advice='Put your HTML here. learningResourceType is a Text.'></div> ); } } var award; if( props.award ){ if( props.award instanceof Array ){ award = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] award = award.concat( props.award.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. award is a Text.'></div> ) }) ); award.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { award = ( <div data-advice='Put your HTML here. award is a Text.'></div> ); } } var dateCreated; if( props.dateCreated ){ if( props.dateCreated instanceof Array ){ dateCreated = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] dateCreated = dateCreated.concat( props.dateCreated.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. dateCreated is a Date.'></div> ) }) ); dateCreated.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { dateCreated = ( <div data-advice='Put your HTML here. dateCreated is a Date.'></div> ); } } var translator; if( props.translator ){ if( props.translator instanceof Array ){ translator = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] translator = translator.concat( props.translator.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. translator is a Person or Organization.'></div> ) }) ); translator.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { translator = ( <div data-advice='Put your HTML here. translator is a Person or Organization.'></div> ); } } var offers; if( props.offers ){ if( props.offers instanceof Array ){ offers = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] offers = offers.concat( props.offers.map( function(result, index){ return ( <Offer {...result} key={index} /> ) }) ); offers.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { offers = ( <Offer props={ props.offers } /> ); } } var copyrightHolder; if( props.copyrightHolder ){ if( props.copyrightHolder instanceof Array ){ copyrightHolder = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] copyrightHolder = copyrightHolder.concat( props.copyrightHolder.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. copyrightHolder is a Person or Organization.'></div> ) }) ); copyrightHolder.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { copyrightHolder = ( <div data-advice='Put your HTML here. copyrightHolder is a Person or Organization.'></div> ); } } var releasedEvent; if( props.releasedEvent ){ if( props.releasedEvent instanceof Array ){ releasedEvent = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] releasedEvent = releasedEvent.concat( props.releasedEvent.map( function(result, index){ return ( <PublicationEvent {...result} key={index} /> ) }) ); releasedEvent.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { releasedEvent = ( <PublicationEvent props={ props.releasedEvent } /> ); } } var position; if( props.position ){ if( props.position instanceof Array ){ position = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] position = position.concat( props.position.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. position is a Integer or Text.'></div> ) }) ); position.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { position = ( <div data-advice='Put your HTML here. position is a Integer or Text.'></div> ); } } var genre; if( props.genre ){ if( props.genre instanceof Array ){ genre = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] genre = genre.concat( props.genre.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. genre is a Text.'></div> ) }) ); genre.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { genre = ( <div data-advice='Put your HTML here. genre is a Text.'></div> ); } } var schemaVersion; if( props.schemaVersion ){ if( props.schemaVersion instanceof Array ){ schemaVersion = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] schemaVersion = schemaVersion.concat( props.schemaVersion.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. schemaVersion is a URL or Text.'></div> ) }) ); schemaVersion.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { schemaVersion = ( <div data-advice='Put your HTML here. schemaVersion is a URL or Text.'></div> ); } } var contentLocation; if( props.contentLocation ){ if( props.contentLocation instanceof Array ){ contentLocation = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] contentLocation = contentLocation.concat( props.contentLocation.map( function(result, index){ return ( <Place {...result} key={index} /> ) }) ); contentLocation.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { contentLocation = ( <Place props={ props.contentLocation } /> ); } } var educationalUse; if( props.educationalUse ){ if( props.educationalUse instanceof Array ){ educationalUse = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] educationalUse = educationalUse.concat( props.educationalUse.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. educationalUse is a Text.'></div> ) }) ); educationalUse.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { educationalUse = ( <div data-advice='Put your HTML here. educationalUse is a Text.'></div> ); } } var accessibilityAPI; if( props.accessibilityAPI ){ if( props.accessibilityAPI instanceof Array ){ accessibilityAPI = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accessibilityAPI = accessibilityAPI.concat( props.accessibilityAPI.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. accessibilityAPI is a Text.'></div> ) }) ); accessibilityAPI.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accessibilityAPI = ( <div data-advice='Put your HTML here. accessibilityAPI is a Text.'></div> ); } } var publisher; if( props.publisher ){ if( props.publisher instanceof Array ){ publisher = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] publisher = publisher.concat( props.publisher.map( function(result, index){ return ( <Organization {...result} key={index} /> ) }) ); publisher.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { publisher = ( <Organization props={ props.publisher } /> ); } } var about; if( props.about ){ if( props.about instanceof Array ){ about = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] about = about.concat( props.about.map( function(result, index){ return ( <Thing {...result} key={index} /> ) }) ); about.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { about = ( <Thing props={ props.about } /> ); } } var potentialAction; if( props.potentialAction ){ if( props.potentialAction instanceof Array ){ potentialAction = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] potentialAction = potentialAction.concat( props.potentialAction.map( function(result, index){ return ( <Action {...result} key={index} /> ) }) ); potentialAction.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { potentialAction = ( <Action props={ props.potentialAction } /> ); } } var name; if( props.name ){ if( props.name instanceof Array ){ name = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] name = name.concat( props.name.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. name is a Text.'></div> ) }) ); name.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { name = ( <div data-advice='Put your HTML here. name is a Text.'></div> ); } } var license; if( props.license ){ if( props.license instanceof Array ){ license = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] license = license.concat( props.license.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. license is a CreativeWork or URL.'></div> ) }) ); license.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { license = ( <div data-advice='Put your HTML here. license is a CreativeWork or URL.'></div> ); } } var aggregateRating; if( props.aggregateRating ){ if( props.aggregateRating instanceof Array ){ aggregateRating = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] aggregateRating = aggregateRating.concat( props.aggregateRating.map( function(result, index){ return ( <AggregateRating {...result} key={index} /> ) }) ); aggregateRating.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { aggregateRating = ( <AggregateRating props={ props.aggregateRating } /> ); } } var workExample; if( props.workExample ){ if( props.workExample instanceof Array ){ workExample = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] workExample = workExample.concat( props.workExample.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); workExample.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { workExample = ( <CreativeWork props={ props.workExample } /> ); } } var sourceOrganization; if( props.sourceOrganization ){ if( props.sourceOrganization instanceof Array ){ sourceOrganization = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] sourceOrganization = sourceOrganization.concat( props.sourceOrganization.map( function(result, index){ return ( <Organization {...result} key={index} /> ) }) ); sourceOrganization.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { sourceOrganization = ( <Organization props={ props.sourceOrganization } /> ); } } var numTracks; if( props.numTracks ){ if( props.numTracks instanceof Array ){ numTracks = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] numTracks = numTracks.concat( props.numTracks.map( function(result, index){ return ( <Integer {...result} key={index} /> ) }) ); numTracks.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { numTracks = ( <Integer props={ props.numTracks } /> ); } } var inLanguage; if( props.inLanguage ){ if( props.inLanguage instanceof Array ){ inLanguage = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] inLanguage = inLanguage.concat( props.inLanguage.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. inLanguage is a Language or Text.'></div> ) }) ); inLanguage.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { inLanguage = ( <div data-advice='Put your HTML here. inLanguage is a Language or Text.'></div> ); } } var isFamilyFriendly; if( props.isFamilyFriendly ){ if( props.isFamilyFriendly instanceof Array ){ isFamilyFriendly = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] isFamilyFriendly = isFamilyFriendly.concat( props.isFamilyFriendly.map( function(result, index){ return ( <Boolean {...result} key={index} /> ) }) ); isFamilyFriendly.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { isFamilyFriendly = ( <Boolean props={ props.isFamilyFriendly } /> ); } } var audience; if( props.audience ){ if( props.audience instanceof Array ){ audience = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] audience = audience.concat( props.audience.map( function(result, index){ return ( <Audience {...result} key={index} /> ) }) ); audience.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { audience = ( <Audience props={ props.audience } /> ); } } var accessibilityControl; if( props.accessibilityControl ){ if( props.accessibilityControl instanceof Array ){ accessibilityControl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accessibilityControl = accessibilityControl.concat( props.accessibilityControl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. accessibilityControl is a Text.'></div> ) }) ); accessibilityControl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accessibilityControl = ( <div data-advice='Put your HTML here. accessibilityControl is a Text.'></div> ); } } var keywords; if( props.keywords ){ if( props.keywords instanceof Array ){ keywords = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] keywords = keywords.concat( props.keywords.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. keywords is a Text.'></div> ) }) ); keywords.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { keywords = ( <div data-advice='Put your HTML here. keywords is a Text.'></div> ); } } var mentions; if( props.mentions ){ if( props.mentions instanceof Array ){ mentions = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] mentions = mentions.concat( props.mentions.map( function(result, index){ return ( <Thing {...result} key={index} /> ) }) ); mentions.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { mentions = ( <Thing props={ props.mentions } /> ); } } var audio; if( props.audio ){ if( props.audio instanceof Array ){ audio = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] audio = audio.concat( props.audio.map( function(result, index){ return ( <AudioObject {...result} key={index} /> ) }) ); audio.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { audio = ( <AudioObject props={ props.audio } /> ); } } var isBasedOnUrl; if( props.isBasedOnUrl ){ if( props.isBasedOnUrl instanceof Array ){ isBasedOnUrl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] isBasedOnUrl = isBasedOnUrl.concat( props.isBasedOnUrl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. isBasedOnUrl is a URL.'></div> ) }) ); isBasedOnUrl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { isBasedOnUrl = ( <div data-advice='Put your HTML here. isBasedOnUrl is a URL.'></div> ); } } return (<div title='MusicPlaylist' className='MusicPlaylist entity'> { comment } { copyrightYear } { hasPart } { version } { producer } { creator } { publishingPrinciples } { text } { image } { citation } { sameAs } { datePublished } { commentCount } { associatedMedia } { alternativeHeadline } { accountablePerson } { video } { url } { typicalAgeRange } { contributor } { additionalType } { thumbnailUrl } { mainEntity } { alternateName } { accessibilityFeature } { interactivityType } { publication } { discussionUrl } { author } { headline } { review } { encoding } { character } { contentRating } { mainEntityOfPage } { educationalAlignment } { exampleOfWork } { editor } { provider } { isPartOf } { recordedAt } { accessibilityHazard } { dateModified } { timeRequired } { description } { track } { learningResourceType } { award } { dateCreated } { translator } { offers } { copyrightHolder } { releasedEvent } { position } { genre } { schemaVersion } { contentLocation } { educationalUse } { accessibilityAPI } { publisher } { about } { potentialAction } { name } { license } { aggregateRating } { workExample } { sourceOrganization } { numTracks } { inLanguage } { isFamilyFriendly } { audience } { accessibilityControl } { keywords } { mentions } { audio } { isBasedOnUrl } </div>); } });
module.exports = initSockets; function initSockets(server){ var io = require('socket.io')(server); var noOfUsers = 0; io.on('connection', function (client) { console.log('Client connected...'); noOfUsers++; console.log(client.id); // client.on('join', function (data) { // console.log(data); // // client.broadcast.emit('broad', "user is connected"); // }); client.on('subscribe', function(room){ console.log("user joined "+room); client.join(room); }) client.on('disconnect', function(){ noOfUsers--; console.log(client.id) console.log("A user has disconnected"); }); client.on('messages', function (data) { // client.emit('broad', data); client.broadcast.to(data.roomId).emit('broad', data); console.log(data); }); }); }
'use strict' var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var basename = path.basename(module.filename); var env = process.env.NODE_ENV || 'development'; var config = require(__dirname + '/../config/config.json')[env]; var db = {}; if (config.use_env_variable) { var sequelize = new Sequelize(process.env[config.use_env_variable]); } else { var sequelize = new Sequelize(config.database, config.username, config.password, config); } fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); }) .forEach(function(file) { var model = sequelize['import'](path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
import input from "./input"; import file from "./file"; import select from "./select"; import textarea from "./textarea"; import date from "./date"; import checkbox from "./checkbox"; import toggler from "./toggler"; import buttons from "./buttons-list"; import addressfinder from "./address-finder"; import pikaday from "./pikaday"; import loqate from "./loqate"; import datepicker from "./datepicker"; import monthyear from "./month-year"; export default { text: input, password: input, email: input, number: input, select, file, textarea, date, checkbox, toggler, buttons, addressfinder, pikaday, loqate, datepicker, monthyear };
import React from 'react'; import ReactDOM from 'react-dom'; import { transform } from 'babel-standalone'; import * as ReactToolbox from 'react-toolbox'; import style from './style'; const ERROR_TIMEOUT = 500; const Preview = React.createClass({ propTypes: { className: React.PropTypes.string, code: React.PropTypes.string.isRequired, scope: React.PropTypes.object }, getDefaultProps () { return { className: '', scope: { React, ...ReactToolbox } }; }, getInitialState () { return { error: null }; }, componentDidMount () { this.executeCode(); }, componentDidUpdate (prevProps) { clearTimeout(this.timeoutID); if (this.props.code !== prevProps.code) { this.executeCode(); } }, setTimeout () { clearTimeout(this.timeoutID); this.timeoutID = setTimeout(...arguments); }, compileCode () { const code = ` (function (${Object.keys(this.props.scope).join(', ')}, mountNode) { ${this.props.code} });`; return transform(code, { presets: ['es2015', 'stage-0', 'react'] }).code; }, buildScope (mountNode) { return Object.keys(this.props.scope).map((key) => { return this.props.scope[key]; }).concat(mountNode); }, executeCode () { const mountNode = this.refs.mount; const scope = this.buildScope(mountNode); try { ReactDOM.unmountComponentAtNode(mountNode); } catch (e) { console.error(e); } try { const compiledCode = this.compileCode(); /*eslint-disable no-eval*/ const Component = eval(compiledCode)(...scope); ReactDOM.render(Component, mountNode); if (this.state.error) { this.setState({error: null}); } } catch (err) { this.setTimeout(() => { this.setState({error: err.toString()}); }, ERROR_TIMEOUT); } }, render () { let className = style.preview; if (this.props.className) className += ` ${this.props.className}`; return ( <div className={className}> {this.state.error !== null ? <span className={style.error}>{this.state.error}</span> : null} <div ref="mount" className={style.content} /> </div> ); } }); export default Preview;
import { join } from 'path' import test from 'ava' import osenv from 'osenv' import { exists, touchp, rm } from '../../src/utils/fs' import clean from '../../src/commands/clean' const tempDir = join(osenv.tmpdir(), 'tempDir') const buildDir = join(tempDir, 'build') const tempFile = join(buildDir, 'tempFile') const config = { FE_CONFIG_FILE: 'FE_CONFIG_FILE', BUILD_DIR: buildDir } test.before(async t => { await touchp(tempFile) }) test('Faild if no appRoot spec', async t => { await clean(null, { config, BUILD_DIR: buildDir }) t.true(await exists(tempFile)) }) test('Faild if no BUILD_DIR spec', async t => { await clean(null, { config, appRoot: tempDir }) t.true(await exists(tempFile)) }) test('clean build success', async t => { await clean(null, { config, appRoot: tempDir, BUILD_DIR: buildDir }) t.true(!await exists(tempFile)) t.true(await exists(buildDir)) }) test.after(async t => { await rm(tempDir) })
/// fix message var moment = require('moment'); // convert a date object into a fix formatted timestamp var getUTCTimeStamp = function(date){ return moment(date).utc().format('YYYYMMDD-HH:mm:ss.SSS'); } var Msg = function() { var self = this; // map of field number (as a string) to field value self._fields = {}; self._define_field = function(field_id, name, opt) { var validator = (opt && opt.validator) ? opt.validator : function(v) { return v; }; Object.defineProperty(self, name, { get: function() { return self.get(field_id); }, set: function(value) { self.set(field_id, validator(value)); } }); }; self._define_field('49', 'SenderCompID'); self._define_field('56', 'TargetCompID'); self._define_field('50', 'SenderSubID'); self._define_field('35', 'MsgType'); self._define_field('34', 'MsgSeqNum'); self._define_field('52', 'SendingTime'); }; // constants Msg.kFieldSeparator = String.fromCharCode(1); Msg.prototype.get = function(field_id) { var self = this; return self._fields[field_id]; }; Msg.prototype.set = function(field_id, value) { var self = this; if (value instanceof Date) { value = getUTCTimeStamp(value); } self._fields[field_id] = value; } Msg.prototype.serialize = function() { var self = this; var header_arr = []; var body_arr = []; var fields = self._fields; header_arr.push('35=' + self.MsgType); header_arr.push('52=' + self.SendingTime); header_arr.push('49=' + self.SenderCompID); header_arr.push('56=' + self.TargetCompID); header_arr.push('34=' + self.MsgSeqNum); // manually inserted var ignore = ['8', '9', '35', '10', '52', '49', '56', '34']; for (var tag in fields) { if (fields.hasOwnProperty(tag) && ignore.indexOf(tag) === -1 && typeof fields[tag] !== 'undefined' && fields[tag] !== null) { body_arr.push(tag + '=' + fields[tag]); } } var headermsg = header_arr.join(Msg.kFieldSeparator); var bodymsg = body_arr.join(Msg.kFieldSeparator); var out = []; out.push('8=' + 'FIX.4.2'); // TODO variable // if there is no body, then only one separator will be added // if there is a body, then there will be another separator var sep_count = 1; if (bodymsg.length > 0) { sep_count += 1; } out.push('9=' + (headermsg.length + bodymsg.length + sep_count)); out.push(headermsg); if (bodymsg.length > 0) { out.push(bodymsg); } var outmsg = out.join(Msg.kFieldSeparator); outmsg += Msg.kFieldSeparator; return outmsg + '10=' + Msg.checksum(outmsg) + Msg.kFieldSeparator; }; Msg.checksum = function(str) { var chksm = 0; for (var i = 0; i < str.length; ++i) { chksm += str.charCodeAt(i); } chksm = chksm % 256; var checksumstr = ''; if (chksm < 10) { checksumstr = '00' + (chksm + ''); } else if (chksm >= 10 && chksm < 100) { checksumstr = '0' + (chksm + ''); } else { checksumstr = '' + (chksm + ''); } return checksumstr; }; Msg.parse = function(raw) { var Msgs = require('./msgs'); var fix = {}; var keyvals = raw.split(Msg.kFieldSeparator); keyvals.forEach(function(kv) { if (kv.length === 0) { return; } // a field could have an = in it, don't see why not var components = kv.split('='); var id = components.shift(); fix[id] = components.join('='); }); // TODO validate header var type = fix['35']; if (!type) { throw new Error('no MsgType in fix message'); } var msg_t = Msgs.types[type]; if (!msg_t) { throw new Error('no such message type: ' + type); } var msg = new msg_t(); msg._fields = fix; return msg; }; module.exports = Msg;
import ProfitModule from './profit' import ProfitController from './profit.controller'; import ProfitComponent from './profit.component'; import ProfitTemplate from './profit.html'; describe('Profit', () => { let $rootScope, makeController; beforeEach(window.module(ProfitModule.name)); beforeEach(inject((_$rootScope_) => { $rootScope = _$rootScope_; makeController = () => { return new ProfitController(); }; })); describe('Module', () => { // top-level specs: i.e., routes, injection, naming }); describe('Controller', () => { // controller specs it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller let controller = makeController(); expect(controller).to.have.property('name'); }); }); describe('Template', () => { // template specs // tip: use regex to ensure correct bindings are used e.g., {{ }} it('has name in template [REMOVE]', () => { expect(ProfitTemplate).to.match(/{{\s?vm\.name\s?}}/g); }); }); describe('Component', () => { // component/directive specs let component = ProfitComponent(); it('includes the intended template',() => { expect(component.template).to.equal(ProfitTemplate); }); it('uses `controllerAs` syntax', () => { expect(component).to.have.property('controllerAs'); }); it('invokes the right controller', () => { expect(component.controller).to.equal(ProfitController); }); }); });
var units = { datacenter: { unitStats: { name: 'SysAdmin', attack: 0, security: 25, power: 500, price: 2000 } }, personal_computer: { unitStats: { name: 'Zombie computer', attack: 10, security: 0, power: 10, price: 300 } }, cave: { unitStats: { name: 'Hacker', attack: 25, security: 0, power: 0, price: 2000 } } }; module.exports = units;
import React, { Component } from 'react' import { View, ScrollView } from 'react-native' import { ArticleComponent, CustomStatusBar } from 'components' class ArticleScreenContainer extends Component { render() { const { article } = this.props; return ( <View style={{ flex: 1 }}> <ScrollView> <ArticleComponent article={article} /> </ScrollView> </View> ) } } export default ArticleScreenContainer;
print("============== Test Sleep ==========="); Thread.sleep(10); print("success");
angular.module('seed.hello', [ 'ui.router' ]) .config(function ($stateProvider) { $stateProvider .state('hello', { url: '/', templateUrl: 'hello/hello.tpl.html', controller: 'HelloController as hello' }) ; }) .controller('HelloController', function HelloController() { var helloCtrl = this; helloCtrl.hello = "Hello, World!"; }) ;
(function(define) { 'use strict'; define(function(require) { return function(Variable) { function StringVar(values, options) { this.values = new Variable.Vector(values).mutable(true); } StringVar.prototype = Object.create(Variable.prototype); StringVar.prototype.asScalar = function asScalar() { return this.map(parseFloat, true, 'scalar').names(this.names()); }; return StringVar; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { 'use strict'; module.exports = factory(require); }));
function outerProduct(dimensions) { if (!Array.isArray(dimensions)) throw new Error("Array expected"); if (!dimensions.length) return []; var results = []; var positions = []; var lengths = []; var skips = []; var i; var dimsCount = dimensions.length; var skipMul = 1; var dim; var result; var shouldSkip; var len; // prepare our states for (i = 0; i < dimsCount; i++) { var dimSize = dimensions[i].length; lengths[i] = dimSize; positions[i] = 0; skips.push(skipMul); skipMul *= dimSize; } // build product for (i = 0; i < skipMul; i++) { result = results[i] = []; for (dim = 0; dim < dimsCount; dim++) { shouldSkip = i % skips[dim] == 0; len = lengths[dim]; if (shouldSkip) { positions[dim] = (positions[dim] + 1) % len; } result.push(dimensions[dim][positions[dim]]); } } return results; }; module.exports = outerProduct;
angular.module('plunker').service('broker', function() { this.client = Stomp.client('ws://calimero:61614'); this.connected = false; }); angular.module('plunker').run(function($q, broker) { var deferred = $q.defer(); // create new deferred object broker.client.connect({}, function(frame) { // connection OK broker.connected = true; deferred.resolve('Promise resolved'); }, function(frame) { // NO connection broker.connected = false; deferred.reject('Promise rejected'); }); broker.deferred = deferred.promise; });
//! Creates a ckeditor instance. Contains options for taking callbacks involved with saving changes. /* global CKEDITOR */ import React from 'react'; import { connect } from 'dva'; /** * After the CKEditor plugin has loaded, initialize the editor */ function awaitCk(rand) { setTimeout(() => { let ckeditorLoaded = true; try{ CKEDITOR; } catch(e) { if(e.name == 'ReferenceError') { ckeditorLoaded = false; } } if(ckeditorLoaded) { CKEDITOR.replace( `ckeditor-${rand}` ); } else { awaitCk(rand); } }, 50); } class CKEditor extends React.Component { componentDidMount() { // add a script tag onto the document that loads the CKEditor script let ckeditor_src = document.createElement('script'); ckeditor_src.type = 'text/javascript'; ckeditor_src.async = true; ckeditor_src.src='/ckeditor/ckeditor.js'; document.getElementById('ckeditor-' + this.props.rand).appendChild(ckeditor_src); // wait for the CKEditor script to load and then initialize the editor awaitCk(this.props.rand); // register our id as the active editor instance this.props.dispatch({type: 'documents/setEditorId', id: this.props.rand}); } shouldComponentUpdate(...args) { return false; } render() { return ( <textarea id={'ckeditor-' + this.props.rand} /> ); } } CKEditor.propTypes = { rand: React.PropTypes.number.isRequired, }; export default connect()(CKEditor);
//Using the JavaScript language, have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers. // //Use the Parameter Testing feature in the box below to test your code with different arguments. //Initial solution -- 4 pts for correctness //When the input was (1,2,3,4) your output was incorrect. //2. When the input was (54,49,1,0,7,4) your output was incorrect. //3. When the input was (3,4,5,7) your output was incorrect. //friggin toughy! function ArrayAdditionI(arr) { function compare(a,b) { return a - b } var sortedArr = arr.sort(compare); var highestNum = sortedArr.pop(); console.log(highestNum); console.log(sortedArr); var highestTotal = 0; for(var i = 0; i < sortedArr.length; i++) { highestTotal += sortedArr[i]; } console.log(highestTotal, ' hT') if(highestTotal < highestNum) { return false; } if(highestTotal === highestNum) { return true; } if(highestTotal > highestNum) { var recSubTotal = highestNum; console.log(recSubTotal, ' rST from if highestTotal >'); function recursiveSubtractor(sortedArr) { if(recSubTotal === 0){ return true; } for(var j = sortedArr.length; j > 0; j--) { if((recSubTotal -= sortedArr[j]) >= 0) { recSubTotal -= sortedArr[j] } if((recSubTotal -= sortedArr[j]) < 0 ){ for(var k = 0; k < sortedArr.length - j; k++ ) { function recAdder(sortedArr) { if(recSubTotal === 0) { return true; } if((recSubTotal += sortedArr[k]) > 0 ) { return false; } if((recSubTotal += sortedArr[k]) <= 0) { recAdder(sortedArr); } } } } } recursiveSubtractor(sortedArr); } recursiveSubtractor(sortedArr); } return false; } var testArr = [1,2,3,4,22]; var testArr2 = [1,2,3,4,10]; ArrayAdditionI(testArr2);
'use strict'; var expect = require('expect.js'); var Flaggr = require('../index'); var _ = require('lodash'); var async = require('async'); describe('Flaggr', function() { it('If you initialize with an incorrect flaggr it should throw an error', function(done) { var config = { adapter: 'weird-flaggr' }; var flaggr = new Flaggr(config); flaggr.on('error', function(err) { expect(err).to.be.ok(); done(); }); }); it('It should default to the memory flaggr if none passed', function(done) { var flaggr = new Flaggr(); flaggr.on('ready', function() { expect(flaggr.adapter.name).to.be('memory'); done(); }); }); describe('Instance', function() { var flaggr; var featureKey = 'uploader'; var fakeFeatureKey = featureKey + '-fake'; var checkNumberOfFeatures = _.curry(function(expectedNumberOfFeatures, next) { flaggr.features(function(err, features) { expect(features).to.have.length(expectedNumberOfFeatures); next(err); }); }); var addFeature = _.curry(function(feature, next) { flaggr.add(feature, next); }); var checkFeatureEnabled = _.curry(function(feature, shouldbeEnabled, next) { flaggr.isEnabled(feature, function(err, isEnabled) { expect(isEnabled).to.be(shouldbeEnabled); next(); }); }); before(function(done) { flaggr = new Flaggr(); flaggr.on('ready', done); }); before(function(done) { flaggr.disconnect(done); }); describe('API', function() { it('should return an empty list of features if there are none', function(done) { checkNumberOfFeatures(0, done); }); it('should allow adding a feature by name', function(done) { flaggr.add(featureKey, function(err) { if (err) return done(err); checkNumberOfFeatures(1, done); }); }); it('should not allow a new feature if a feature with the same name is already there', function(done) { flaggr.add(featureKey, function(err) { if (err) return done(err); checkNumberOfFeatures(1, done); }); }); it('should not allow a new feature if a feature with the same name is already there', function(done) { flaggr.add(featureKey, function(err) { if (err) return done(err); checkNumberOfFeatures(1, done); }); }); it('should do nothing if it tries to remove a feature that is not on the feature list', function(done) { flaggr.remove(fakeFeatureKey, function(err) { if (err) return done(err); checkNumberOfFeatures(1, done); }); }); it('should remove a feature that is on the feature list', function(done) { flaggr.remove(featureKey, function(err) { if (err) return done(err); checkNumberOfFeatures(0, done); }); }); it('should return null when trying to retrieve a feature that does not exist', function(done) { flaggr.get(featureKey, function(err, feature) { if (err) return done(err); expect(feature).not.to.be.ok(); done(); }); }); it('should return a feature when it actually exists', function(done) { var getFeature = _.curry(function(key, next) { flaggr.get(key, function(err, feature) { if (err) return next(err); expect(feature).to.be.ok(); next(); }); }); async.series([ addFeature(featureKey), getFeature(featureKey) ], done); }); }); describe('gates', function() { describe('boolean', function() { it('should do nothing when trying to enable a feature that doesnt exist', function(done) { flaggr.enable(fakeFeatureKey, function(err) { if (err) return done(err); checkNumberOfFeatures(1, done); }); }); it('should do nothing when trying to enable a feature that is already enabled', function(done) { flaggr.enable(featureKey, function(err) { if (err) return done(err); flaggr.get(featureKey, function(err, feature) { expect(feature.enabled).to.be(true); done(); }); }); }); it('should enable a feature that is disabled', function(done) { var disableFeature = _.curry(function(key, next) { flaggr.disable(key, function(err) { if (err) return next(err); next(); }); }); var enableFeature = _.curry(function(key, next) { flaggr.enable(key, function(err) { if (err) return next(err); next(); }); }); var checkFeatureEnabled = _.curry(function(key, next) { flaggr.get(key, function(err, feature) { if (err) return next(err); expect(feature).to.be.ok(); expect(feature.enabled).to.be(true); next(); }); }); async.series([ disableFeature(featureKey), enableFeature(featureKey), checkFeatureEnabled(featureKey) ], done); }); }); describe('group', function() { var groupName = 'admins'; var groupProp = 'admin'; var groupValue = true; var groupMemberAdmin = { admin: true }; var groupMemberNonAdmin = { admin: false }; var checkEnabled = _.curry(function(key, groupName, groupMember, shouldBeEnabled, next) { var opts = { group: groupName, groupMember: groupMember }; flaggr.isEnabled(featureKey, opts, function(err, enabled) { expect(err).not.to.be.ok(); expect(enabled).to.be(shouldBeEnabled); next(); }); }); it('should return disable if a group does not exist', function(done) { checkEnabled(fakeFeatureKey, groupName, groupMemberAdmin, false, done); }); it('should allow to register a group and default to enabled', function(done) { flaggr.registerGroup(featureKey, groupName, groupProp, groupValue, function(err) { expect(err).not.to.be.ok(); async.parallel([ checkEnabled(featureKey, groupName, groupMemberAdmin, true), checkEnabled(featureKey, groupName, groupMemberNonAdmin, false) ], function(err) { expect(err).not.to.be.ok(); done(); }); }); }); it('should do nothing when trying to enable a feature that is already enabled', function(done) { flaggr.enableGroup(featureKey, groupName, function(err) { expect(err).not.to.be.ok(); done(); }); }); it('should disable a feature', function(done) { var test = function(next) { flaggr.disableGroup(featureKey, groupName, next); }; async.series([ checkEnabled(featureKey, groupName, groupMemberAdmin, true), test, checkEnabled(featureKey, groupName, groupMemberAdmin, false) ], function(err) { expect(err).not.to.be.ok(); done(); }); }); it('should enable a feature if a feature is disabled', function(done) { var test = function(next) { flaggr.enableGroup(featureKey, groupName, next); }; async.series([ checkEnabled(featureKey, groupName, groupMemberAdmin, false), test, checkEnabled(featureKey, groupName, groupMemberAdmin, true) ], function(err) { expect(err).not.to.be.ok(); done(); }); }); it('should return enabled if a boolean gate exist for the feature even if the group is disabled', function(done) { var disableGroup = function(next) { flaggr.disableGroup(featureKey, groupName, next); }; var enableGroup = function(next) { flaggr.enableGroup(featureKey, groupName, next); }; async.series([ disableGroup, checkFeatureEnabled(featureKey, true), enableGroup ], function(err) { expect(err).not.to.be.ok(); done(); }); }); it('should return disabled if a boolean gate exist for the feature even if the group is enabled', function(done) { var enableFeature = function(next) { flaggr.enable(featureKey, next); }; var disableFeature = function(next) { flaggr.disable(featureKey, next); }; var enableGroup = function(next) { flaggr.enableGroup(featureKey, groupName, next); }; async.series([ enableGroup, disableFeature, checkFeatureEnabled(featureKey, false), enableFeature ], function(err) { expect(err).not.to.be.ok(); done(); }); }); }); describe('user', function() { var allowedUser = { id: 1 }; var nonAllowedUser = { id: 5 }; var checkEnabled = _.curry(function(key, user, shouldBeEnabled, next) { var opts = { user: user }; flaggr.isEnabled(featureKey, opts, function(err, enabled) { expect(err).not.to.be.ok(); expect(enabled).to.be(shouldBeEnabled); next(); }); }); it('should return disable if a user has not been added', function(done) { checkEnabled(fakeFeatureKey, allowedUser, false, done); }); it('should throw an error if the object passed doesnt have an id property', function(done) { flaggr.enableUser(featureKey, { other_id: 12 }, function(err) { expect(err).to.be.ok(); done(); }); }); it('should allow to register a user and default to enabled', function(done) { flaggr.registerUser(featureKey, allowedUser, function(err) { expect(err).not.to.be.ok(); async.parallel([ checkEnabled(featureKey, allowedUser, true), checkEnabled(featureKey, nonAllowedUser, false) ], function(err) { expect(err).not.to.be.ok(); done(); }); }); }); it('should do nothing when trying to enable a feature that is already enabled', function(done) { flaggr.registerUser(featureKey, allowedUser, function(err) { expect(err).not.to.be.ok(); done(); }); }); it('should disable a feature', function(done) { var test = function(next) { flaggr.disableUser(featureKey, allowedUser, next); }; async.series([ checkEnabled(featureKey, allowedUser, true), test, checkEnabled(featureKey, allowedUser, false) ], function(err) { expect(err).not.to.be.ok(); done(); }); }); it('should enable a feature if a feature is disabled', function(done) { var test = function(next) { flaggr.enableUser(featureKey, allowedUser, next); }; async.series([ checkEnabled(featureKey, allowedUser, false), test, checkEnabled(featureKey, allowedUser, true) ], function(err) { expect(err).not.to.be.ok(); done(); }); }); it('should return enabled if a boolean gate exist for the feature even if the group is disabled', function(done) { var disableUser = function(next) { flaggr.disableUser(featureKey, allowedUser, next); }; var enableUser = function(next) { flaggr.enableUser(featureKey, allowedUser, next); }; async.series([ disableUser, checkFeatureEnabled(featureKey, true), enableUser ], function(err) { expect(err).not.to.be.ok(); done(); }); }); it('should return disabled if a boolean gate exist for the feature even if the group is enabled', function(done) { var enableFeature = function(next) { flaggr.enable(featureKey, next); }; var disableFeature = function(next) { flaggr.disable(featureKey, next); }; var enableUser = function(next) { flaggr.enableUser(featureKey, allowedUser, next); }; async.series([ enableUser, disableFeature, checkFeatureEnabled(featureKey, false), enableFeature ], function(err) { expect(err).not.to.be.ok(); done(); }); }); }); }); }); });
'use strict'; var express = require('express'); var log = require('../lib/logging').getLogger('routes/index'); var router = express.Router(); var passport = require('passport'); var config = require('../lib/config'); var uuid = require('uuid4'); var validator = require('../lib/validate'); var apis = require('../api/index'); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: config.title, username: validator.getUsername(req) }); }); router.get('/login', function(req, res) { res.render('login', { title: config.title }); }); // Authenticate using the 'local' strategy router.post('/login', function(req, res, next) { passport.authenticate('local', function(err, user) { if (err) { return next(err); } if (!user) { return res.json(401, { error: 'message' }); } // User has authenticated correctly. Create a JWT token log.debug('User <' + user.username + '> authenticated okay'); var token = validator.signToken({ username: user.username }); log.info('User <' + user.username + '> logged in'); var csrfToken = uuid(); res.cookie('jwt', token, { httpOnly: true, secure: true }); res.cookie('X-CSRF-Token', csrfToken, { secure: true }); // res.cookie('nextUrl', req.originalUrl, { httpOnly: true, secure: true }); if (req.cookies && req.cookies.nextUrl) { res.clearCookie('nextUrl'); res.redirect(req.cookies.nextUrl); } else { res.redirect('/'); } })(req, res, next); }); router.get('/logout', function(req, res) { if (validator.isJwtPresent(req)) { try { var token = validator.validateToken(req.cookies.jwt); log.info('User <' + token.username + '> logged out'); } catch (err) { log.error('Invalid JWT token'); } } else { log.info('logout called, but user doesn\'t appear to be logged in'); } res.clearCookie('jwt'); res.clearCookie('X-CSRF-Token'); res.clearCookie('nextUrl'); res.redirect('/'); }); router.post('/apis/add', function(req, res, next) { apis.add(req, res, next); }); router.get('/apiui', function(req, res) { res.render('api', { username: validator.getUsername(req) }); }); module.exports = router;
const Database = require("./Database"); var database = new Database('movie-friends.db'); module.exports = function user (req, res) { if (!req.session.authenticated) { res.redirect('/login'); } else { var sameUser = false; var admin = false; var canAdd = false; var gender = 1; var friendList = []; database.getUserById(req.params.id, function (user) { if (user) { database.getRatingsFromUserId(req.params.id, function (ratings) { if (req.session.userId == req.params.id) { sameUser = true; } database.getRoleById(req.session.userId, function (role) { if (role.role == 2) { admin = true; } if (user.gender == 'F') { gender = 0; } database.getFriendsById(req.params.id, function (friends) { for (var i = 0; i < friends.length; i++) { if (friends[i].userIdFirst != req.session.userId && friends[i].userIdSecond != req.session.userId) { canAdd = true; } else { canAdd = false; } var friendId = (user.id == friends[i].userIdFirst ? friends[i].userIdSecond : friends[i].userIdFirst); database.getUserById(friendId, function (user) { friendList.push(user); }); } if (friends.length === 0) { canAdd = true; } res.render('user.hbs', { user: user, ratings: ratings, sameUser: sameUser, admin: admin, canAdd: canAdd, friends: friendList, session: req.session }); }); }); }); } else { res.redirect(404, '/users'); } }); } };
module.exports = { libsass: { options: { loadPath: ['bower_components/foundation/scss'] }, files: [{ expand: true, cwd: 'assets/styles', src: ['application.scss', 'components.scss'], dest: 'dist/css', ext: '.css' }] } };
const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const FaviconsWebpackPlugin = require('favicons-webpack-plugin') module.exports = { entry: [ 'react-hot-loader/patch', 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './index.js', ], output: { filename: 'static/[name].[hash].js', path: path.resolve(__dirname, 'build'), }, resolve: { alias: { components: path.resolve(__dirname, 'src/components'), views: path.resolve(__dirname, 'src/views'), reducers: path.resolve(__dirname, 'src/reducers'), images: path.resolve(__dirname, 'assets/images'), config: path.resolve(__dirname, 'src/config'), models: path.resolve(__dirname, 'src/models'), actions: path.resolve(__dirname, 'src/actions'), data: path.resolve(__dirname, 'assets/data'), utils: path.resolve(__dirname, 'src/utils'), }, extensions: ['.js', '.jsx'], }, module: { rules: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: [["es2015", { "modules": false }], 'stage-3', 'react'], plugins: 'react-hot-loader/babel', cacheDirectory: true, }, }, }, { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], }, { test: /\.(png|jpg)$/, use: 'url-loader?limit=10000?url=false', }, { test: /\.svg$/, loader: 'svg-sprite-loader?' + JSON.stringify({ name: '[name]_[hash]', prefixize: true, }) } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'lib', minChunks: (module) => { return module.context && module.context.indexOf('node_modules') !== -1; }, }), new HtmlWebpackPlugin({ template: './index.html', }), new webpack.ProvidePlugin({ React: 'react', }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new CopyWebpackPlugin([ { from: path.resolve(__dirname, 'assets/data'), to: 'data', }, ]), new FaviconsWebpackPlugin({ logo: 'images/shop-icon.png', prefix: 'icons/', }) ], devServer: { contentBase: path.resolve(__dirname, 'build'), compress: true, historyApiFallback: true, hot: true, }, devtool: 'inline-source-map', };
define(["can/map/attributes", "warp/figure"], function(map, Figure) { "use strict"; return map.extend({ attributes: { "figure": function(raw) { return new Figure(raw); } } }, {}); });
// Updates OwnerIDs in Flats and Residents tables // var linkTable = 'flats_residents'; var sourceTable = 'users'; var targetTable1 = 'residents'; var targetTable2 = 'flats'; var users; var flats; var residents; var links; exports.seed = function(knex, Promise) { return getUsers() .then(getResidents) // get all rows of Residents tables .then(getFlats) .then(getLinks) .then(updateOwnerIds); function getUsers() { return knex.select('id', 'first_name', 'last_name').from(sourceTable); } function getResidents(rows) { users = rows; // console.log('Users: '); console.log(rows); return knex.select().from(targetTable1); } function getFlats(rows){ residents = rows; // console.log('Residents: '); console.log(rows); return knex.select().from(targetTable2) } function getLinks(rows){ flats = rows; // console.log('Flats: '); console.log(rows); rids = residents.map(each => each.id); return knex.select().from(linkTable); } function updateOwnerIds(rows){ links = rows; // console.log('Links: '); console.log(rows); let userId; let results = []; let uresident; let uflat; let firstName; let lastName; residents.forEach(eachResident => { // console.log('User Id: '); console.log(userId); firstName = eachResident.first_name; lastName = eachResident.last_name; userId = getUserId(firstName, lastName); if(userId) { uresident = updateResident(eachResident.id, userId); results.push( uresident ); uflat = updateFlat(eachResident.id, userId); if(uflat) { results.push( uflat ); } } }); return Promise.all(results); } function getUserId(fname, lname){ let fusers = users.filter(eachUser => eachUser.first_name === fname && eachUser.last_name === lname); // console.log('eachResident...'); console.log(eachResident); // console.log('fusers: '); console.log(fusers); if(fusers.length < 1) { return null } return fusers[0].id; } function updateResident(rid, uid){ return knex(targetTable1) .where('id', '=', rid) .update({ owner_id: uid }); } function updateFlat(rid, uid){ // console.log('rid: '+rid+'; uid: '+uid); let flinks = links.filter(eachLink => eachLink.resident_id === rid); let fid = flinks[0].flat_id; // console.log('fid: '+fid); let flat = flats.filter(eachFlat => eachFlat.id === fid); // console.log('Flat: '); console.log(flat); if(flat[0].owner_id !== 0) return null; return knex(targetTable2) .where('id', '=', fid) .update({ owner_id: uid }); } }
'use strict'; const assert = require('assert'); const Browscap = require('../src/index.js'); suite('checking for issue 1978. (8 tests)', function () { test('issue-1978-A ["Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPT/65 Mobile/15G77"]', function () { const browscap = new Browscap(); const browser = browscap.getBrowser('Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPT/65 Mobile/15G77'); assert.strictEqual(browser['Comment'], 'Opera Touch Generic', 'Expected actual "Comment" to be \'Opera Touch Generic\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser'], 'Opera Touch', 'Expected actual "Browser" to be \'Opera Touch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Bits'], '32', 'Expected actual "Browser_Bits" to be \'32\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Maker'], 'Opera Software ASA', 'Expected actual "Browser_Maker" to be \'Opera Software ASA\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Version'], '0.0', 'Expected actual "Version" to be \'0.0\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform'], 'iOS', 'Expected actual "Platform" to be \'iOS\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Version'], '11.4', 'Expected actual "Platform_Version" to be \'11.4\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Description'], 'iPod, iPhone & iPad', 'Expected actual "Platform_Description" to be \'iPod, iPhone & iPad\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Bits'], '32', 'Expected actual "Platform_Bits" to be \'32\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Maker'], 'Apple Inc', 'Expected actual "Platform_Maker" to be \'Apple Inc\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaApplets'], true, 'Expected actual "JavaApplets" to be true (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Name'], 'iPhone', 'Expected actual "Device_Name" to be \'iPhone\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Maker'], 'Apple Inc', 'Expected actual "Device_Maker" to be \'Apple Inc\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Code_Name'], 'iPhone', 'Expected actual "Device_Code_Name" to be \'iPhone\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Brand_Name'], 'Apple', 'Expected actual "Device_Brand_Name" to be \'Apple\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Name'], 'WebKit', 'Expected actual "RenderingEngine_Name" to be \'WebKit\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Maker'], 'Apple Inc', 'Expected actual "RenderingEngine_Maker" to be \'Apple Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); }); test('issue-1978-B ["Mozilla/5.0 (Linux; Android 8.1.0; Mi A1 Build/OPM1.171019.019) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36 OPT/1.8.26"]', function () { const browscap = new Browscap(); const browser = browscap.getBrowser('Mozilla/5.0 (Linux; Android 8.1.0; Mi A1 Build/OPM1.171019.019) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36 OPT/1.8.26'); assert.strictEqual(browser['Comment'], 'Opera Touch 1.8', 'Expected actual "Comment" to be \'Opera Touch 1.8\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser'], 'Opera Touch', 'Expected actual "Browser" to be \'Opera Touch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Bits'], '32', 'Expected actual "Browser_Bits" to be \'32\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Maker'], 'Opera Software ASA', 'Expected actual "Browser_Maker" to be \'Opera Software ASA\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Version'], '1.8', 'Expected actual "Version" to be \'1.8\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform'], 'Android', 'Expected actual "Platform" to be \'Android\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Version'], '8.1', 'Expected actual "Platform_Version" to be \'8.1\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Description'], 'Android OS', 'Expected actual "Platform_Description" to be \'Android OS\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Bits'], '32', 'Expected actual "Platform_Bits" to be \'32\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Maker'], 'Google Inc', 'Expected actual "Platform_Maker" to be \'Google Inc\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Name'], 'Mi A1', 'Expected actual "Device_Name" to be \'Mi A1\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Maker'], 'Xiaomi Tech', 'Expected actual "Device_Maker" to be \'Xiaomi Tech\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Code_Name'], 'Mi A1', 'Expected actual "Device_Code_Name" to be \'Mi A1\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Brand_Name'], 'Xiaomi', 'Expected actual "Device_Brand_Name" to be \'Xiaomi\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Name'], 'Blink', 'Expected actual "RenderingEngine_Name" to be \'Blink\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Maker'], 'Google Inc', 'Expected actual "RenderingEngine_Maker" to be \'Google Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); }); test('issue-1978-C ["Mozilla/5.0 (Linux; Android 7.0; Moto G (4) Build/NPJS25.93-14-18) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36 OPT/1.7.21"]', function () { const browscap = new Browscap(); const browser = browscap.getBrowser('Mozilla/5.0 (Linux; Android 7.0; Moto G (4) Build/NPJS25.93-14-18) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36 OPT/1.7.21'); assert.strictEqual(browser['Comment'], 'Opera Touch 1.7', 'Expected actual "Comment" to be \'Opera Touch 1.7\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser'], 'Opera Touch', 'Expected actual "Browser" to be \'Opera Touch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Bits'], '32', 'Expected actual "Browser_Bits" to be \'32\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Maker'], 'Opera Software ASA', 'Expected actual "Browser_Maker" to be \'Opera Software ASA\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Version'], '1.7', 'Expected actual "Version" to be \'1.7\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform'], 'Android', 'Expected actual "Platform" to be \'Android\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Version'], '7.0', 'Expected actual "Platform_Version" to be \'7.0\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Description'], 'Android OS', 'Expected actual "Platform_Description" to be \'Android OS\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Bits'], '32', 'Expected actual "Platform_Bits" to be \'32\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Maker'], 'Google Inc', 'Expected actual "Platform_Maker" to be \'Google Inc\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Name'], 'Moto G4', 'Expected actual "Device_Name" to be \'Moto G4\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Maker'], 'Motorola', 'Expected actual "Device_Maker" to be \'Motorola\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Code_Name'], 'G4', 'Expected actual "Device_Code_Name" to be \'G4\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Brand_Name'], 'Motorola', 'Expected actual "Device_Brand_Name" to be \'Motorola\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Name'], 'Blink', 'Expected actual "RenderingEngine_Name" to be \'Blink\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Maker'], 'Google Inc', 'Expected actual "RenderingEngine_Maker" to be \'Google Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); }); test('issue-1978-D ["Mozilla/5.0 (Linux; Android 8.0.0; F8331 Build/41.3.A.2.157) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36 OPT/1.8.27"]', function () { const browscap = new Browscap(); const browser = browscap.getBrowser('Mozilla/5.0 (Linux; Android 8.0.0; F8331 Build/41.3.A.2.157) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36 OPT/1.8.27'); assert.strictEqual(browser['Comment'], 'Opera Touch 1.8', 'Expected actual "Comment" to be \'Opera Touch 1.8\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser'], 'Opera Touch', 'Expected actual "Browser" to be \'Opera Touch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Bits'], '32', 'Expected actual "Browser_Bits" to be \'32\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Maker'], 'Opera Software ASA', 'Expected actual "Browser_Maker" to be \'Opera Software ASA\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Version'], '1.8', 'Expected actual "Version" to be \'1.8\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform'], 'Android', 'Expected actual "Platform" to be \'Android\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Version'], '8.0', 'Expected actual "Platform_Version" to be \'8.0\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Description'], 'Android OS', 'Expected actual "Platform_Description" to be \'Android OS\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Bits'], '32', 'Expected actual "Platform_Bits" to be \'32\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Maker'], 'Google Inc', 'Expected actual "Platform_Maker" to be \'Google Inc\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Name'], 'Xperia XZ', 'Expected actual "Device_Name" to be \'Xperia XZ\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Maker'], 'Sony', 'Expected actual "Device_Maker" to be \'Sony\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Code_Name'], 'F8331', 'Expected actual "Device_Code_Name" to be \'F8331\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Brand_Name'], 'Sony', 'Expected actual "Device_Brand_Name" to be \'Sony\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Name'], 'Blink', 'Expected actual "RenderingEngine_Name" to be \'Blink\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Maker'], 'Google Inc', 'Expected actual "RenderingEngine_Maker" to be \'Google Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); }); test('issue-1978-E ["Mozilla/5.0 (Linux; Android 8.1.0; TA-1021 Build/OPR1.170623.026) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36 OPT/1.9.31"]', function () { const browscap = new Browscap(); const browser = browscap.getBrowser('Mozilla/5.0 (Linux; Android 8.1.0; TA-1021 Build/OPR1.170623.026) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36 OPT/1.9.31'); assert.strictEqual(browser['Comment'], 'Opera Touch 1.9', 'Expected actual "Comment" to be \'Opera Touch 1.9\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser'], 'Opera Touch', 'Expected actual "Browser" to be \'Opera Touch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Bits'], '32', 'Expected actual "Browser_Bits" to be \'32\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Maker'], 'Opera Software ASA', 'Expected actual "Browser_Maker" to be \'Opera Software ASA\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Version'], '1.9', 'Expected actual "Version" to be \'1.9\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform'], 'Android', 'Expected actual "Platform" to be \'Android\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Version'], '8.1', 'Expected actual "Platform_Version" to be \'8.1\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Description'], 'Android OS', 'Expected actual "Platform_Description" to be \'Android OS\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Bits'], '32', 'Expected actual "Platform_Bits" to be \'32\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Maker'], 'Google Inc', 'Expected actual "Platform_Maker" to be \'Google Inc\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Name'], '6', 'Expected actual "Device_Name" to be \'6\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Maker'], 'Nokia', 'Expected actual "Device_Maker" to be \'Nokia\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Code_Name'], 'TA-1021', 'Expected actual "Device_Code_Name" to be \'TA-1021\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Brand_Name'], 'Nokia', 'Expected actual "Device_Brand_Name" to be \'Nokia\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Name'], 'Blink', 'Expected actual "RenderingEngine_Name" to be \'Blink\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Maker'], 'Google Inc', 'Expected actual "RenderingEngine_Maker" to be \'Google Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); }); test('issue-1978-F ["Mozilla/5.0 (Linux; Android 7.0; F3112 Build/33.3.A.1.97) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/69.0.3497.91 Mobile Safari/537.36 OPT/1.10.33"]', function () { const browscap = new Browscap(); const browser = browscap.getBrowser('Mozilla/5.0 (Linux; Android 7.0; F3112 Build/33.3.A.1.97) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/69.0.3497.91 Mobile Safari/537.36 OPT/1.10.33'); assert.strictEqual(browser['Comment'], 'Opera Touch 1.10', 'Expected actual "Comment" to be \'Opera Touch 1.10\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser'], 'Opera Touch', 'Expected actual "Browser" to be \'Opera Touch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Bits'], '32', 'Expected actual "Browser_Bits" to be \'32\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Maker'], 'Opera Software ASA', 'Expected actual "Browser_Maker" to be \'Opera Software ASA\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Version'], '1.10', 'Expected actual "Version" to be \'1.10\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform'], 'Android', 'Expected actual "Platform" to be \'Android\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Version'], '7.0', 'Expected actual "Platform_Version" to be \'7.0\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Description'], 'Android OS', 'Expected actual "Platform_Description" to be \'Android OS\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Bits'], '32', 'Expected actual "Platform_Bits" to be \'32\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Maker'], 'Google Inc', 'Expected actual "Platform_Maker" to be \'Google Inc\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Name'], 'Xperia XA Dual SIM', 'Expected actual "Device_Name" to be \'Xperia XA Dual SIM\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Maker'], 'Sony', 'Expected actual "Device_Maker" to be \'Sony\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Code_Name'], 'F3112', 'Expected actual "Device_Code_Name" to be \'F3112\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Brand_Name'], 'Sony', 'Expected actual "Device_Brand_Name" to be \'Sony\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Name'], 'Blink', 'Expected actual "RenderingEngine_Name" to be \'Blink\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Maker'], 'Google Inc', 'Expected actual "RenderingEngine_Maker" to be \'Google Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); }); test('issue-1978-G ["Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPT/69 Mobile/16A366"]', function () { const browscap = new Browscap(); const browser = browscap.getBrowser('Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPT/69 Mobile/16A366'); assert.strictEqual(browser['Comment'], 'Opera Touch Generic', 'Expected actual "Comment" to be \'Opera Touch Generic\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser'], 'Opera Touch', 'Expected actual "Browser" to be \'Opera Touch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Bits'], '32', 'Expected actual "Browser_Bits" to be \'32\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Maker'], 'Opera Software ASA', 'Expected actual "Browser_Maker" to be \'Opera Software ASA\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Version'], '0.0', 'Expected actual "Version" to be \'0.0\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform'], 'iOS', 'Expected actual "Platform" to be \'iOS\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Version'], '12.0', 'Expected actual "Platform_Version" to be \'12.0\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Description'], 'iPod, iPhone & iPad', 'Expected actual "Platform_Description" to be \'iPod, iPhone & iPad\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Bits'], '32', 'Expected actual "Platform_Bits" to be \'32\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Maker'], 'Apple Inc', 'Expected actual "Platform_Maker" to be \'Apple Inc\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaApplets'], true, 'Expected actual "JavaApplets" to be true (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Name'], 'iPhone', 'Expected actual "Device_Name" to be \'iPhone\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Maker'], 'Apple Inc', 'Expected actual "Device_Maker" to be \'Apple Inc\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Code_Name'], 'iPhone', 'Expected actual "Device_Code_Name" to be \'iPhone\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Brand_Name'], 'Apple', 'Expected actual "Device_Brand_Name" to be \'Apple\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Name'], 'WebKit', 'Expected actual "RenderingEngine_Name" to be \'WebKit\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Maker'], 'Apple Inc', 'Expected actual "RenderingEngine_Maker" to be \'Apple Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); }); test('issue-1978-H ["Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPT/1.10.36 Mobile/15G77"]', function () { const browscap = new Browscap(); const browser = browscap.getBrowser('Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPT/1.10.36 Mobile/15G77'); assert.strictEqual(browser['Comment'], 'Opera Touch Generic', 'Expected actual "Comment" to be \'Opera Touch Generic\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser'], 'Opera Touch', 'Expected actual "Browser" to be \'Opera Touch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Bits'], '32', 'Expected actual "Browser_Bits" to be \'32\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Maker'], 'Opera Software ASA', 'Expected actual "Browser_Maker" to be \'Opera Software ASA\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Version'], '0.0', 'Expected actual "Version" to be \'0.0\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform'], 'iOS', 'Expected actual "Platform" to be \'iOS\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Version'], '11.4', 'Expected actual "Platform_Version" to be \'11.4\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Description'], 'iPod, iPhone & iPad', 'Expected actual "Platform_Description" to be \'iPod, iPhone & iPad\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Bits'], '32', 'Expected actual "Platform_Bits" to be \'32\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Platform_Maker'], 'Apple Inc', 'Expected actual "Platform_Maker" to be \'Apple Inc\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['JavaApplets'], true, 'Expected actual "JavaApplets" to be true (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Name'], 'iPhone', 'Expected actual "Device_Name" to be \'iPhone\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Maker'], 'Apple Inc', 'Expected actual "Device_Maker" to be \'Apple Inc\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Code_Name'], 'iPhone', 'Expected actual "Device_Code_Name" to be \'iPhone\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['Device_Brand_Name'], 'Apple', 'Expected actual "Device_Brand_Name" to be \'Apple\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Name'], 'WebKit', 'Expected actual "RenderingEngine_Name" to be \'WebKit\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); assert.strictEqual(browser['RenderingEngine_Maker'], 'Apple Inc', 'Expected actual "RenderingEngine_Maker" to be \'Apple Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')'); }); });
var httpUtilities = require('./utilities/http.js'); module.exports = { httpUtilities: httpUtilities };
import express from 'express'; import mongoose from 'mongoose'; import crypto from 'crypto'; import uuid from 'node-uuid'; import async from 'async'; import { setError , setOk } from '../lib/utils'; //初始化router const router = express.Router(); //导入User的Model const User = mongoose.model('User'); module.exports= function (app) { app.use("/reg",router); }; //用户注册 router.post('/', function (req, res) { const { name , password , email } = req.body ; const passHash = crypto.createHash('md5').update(password).digest('hex'); var userEntity = new User({ name, password:passHash, email, id:uuid.v4() }); //查看用户名是否唯一 User.checkUser({name},(err,user)=>{ if(err){ return res.status(200).json(setError()); } if(user){ //存在,则已经占用 return res.status(200).json(setError({msg:"用户名已经被占用!"})); } //查看邮箱是否唯一 User.checkUser({email},(err,user)=>{ if(err){ return res.status(200).json(setError()); } if(user){ //存在,则已经占用 return res.status(200).json(setError({msg:"邮箱已经被占用!"})); } userEntity.save((err,user)=>{ if(!err){ req.session.user = user; res.status(200).json(setOk()); } }); }) }); /* async.waterfall([ User.findByName({name:userEntity.name},function(cb){ return cb(); }), function ]);*/ //查找是否有同名的 /* User.findByName({name:userEntity.name},(error,user)=>{ if(!user){ userEntity.save((err,user)=>{ if(!err){ res.status(200).json(setOk()); } }); }else { res.json(setError()) } })*/ });
version https://git-lfs.github.com/spec/v1 oid sha256:31aa4b2f1987602d9f153a58b9f436dd61355423b2c603bbf7a6929488a5a2bf size 19383
import { define, } from './variable.js'; /** * Define static property * @param {Object} target target object * @param {String} name property name * @param {AnyType} value property value */ export default function ( target, name, value ) { return define( target, name, { value, writable : false, enumerable : false, configurable : false, } ); };
const Mi5OpcuaServer = require('./../models/opcua-server'); const content = { Mi5: { type: 'Folder', content: { Output: { type: 'Folder', content: { Connected: { type: 'Variable', dataType: 'Boolean', initValue: true }, Voltage: { type: 'Variable', dataType: 'Double', initValue: 2.345 } } }, Input: { type: 'Folder', content: { Methode: { type: 'Method' }, Auto: { type: 'Object' } } } } } }; let server; describe('Mi5 OPC UA Server', function() { describe('Server', function() { it('should start the server without error', function() { server = new Mi5OpcuaServer(4841, { content: content }); server.once('init', () => { server.addElementToAddressSpace('RootFolder', {browseName: 'Mi5', type: 'Folder', nodeId: 'ns=4;s=Mi5'}); }) }); it('should do soemthing else', function() { let variable = server.getVariable('ns=4;s=Mi5.Output.Connected'); variable.onChange(console.log); }); }); });
module.exports = { //state //actions UPDATE_LOCATION: "UPDATE_LOCATION", UPDATE_TAGS: "UPDATE_TAGS" }
var FilesSandbox = require('./FilesSandbox'); function FilesSandboxAggregate() { if (!(this instanceof FilesSandboxAggregate)) { return new FilesSandboxAggregate(); } this.filesSandbox = new FilesSandbox(); this.processedItems = []; } FilesSandboxAggregate.prototype.runFiles = function (files, transformator, onResult) { var self = this; self.filesSandbox.runFiles(files, transformator, function (err, result, filePath) { self.processedItems.push({ error: err, filePath: filePath, result: result }); return true; }, function () { onResult(null, self.processedItems); }); }; module.exports = FilesSandboxAggregate;
define(function(require) { var $ = require('$'); var router = require('lavaca/mvc/Router'); var viewManager = require('lavaca/mvc/ViewManager'); var HomeController = require('app/net/HomeController'); describe('Home Controller', function() { beforeEach(function(){ $('body').append('<div id="view-root"></div>'); viewManager = (new viewManager.constructor()).setEl('#view-root'); router = (new router.constructor()).setViewManager(viewManager); router.add({ '/': [HomeController, 'index', {}] }); }); afterEach(function(){ $('#view-root').remove(); }); it('can be instantiated', function() { var controller = new HomeController(router, viewManager); expect(controller instanceof HomeController).toBe(true); expect(controller.router).toBe(router); expect(controller.viewManager).toBe(viewManager); }); }); });
$(document).ready(function(){ // animation scroll $(window).scroll(function(){ var scrollY = $(this).scrollTop(); var heightPart1 = $("#part1").offset().top; var heightPart2 = $("#part2").offset().top; var heightPart3 = $("#part3").offset().top; var recently = $(".recently").offset().top; if(scrollY >= (heightPart1 - 630)){ $("#part1 .img").addClass('animateLeft'); $("#part1 .text").addClass('animateRight'); } if(scrollY >= (heightPart2 - 630)){ $("#part2 .text").addClass('animateLeft'); $("#part2 .img").addClass('animateRight'); } if(scrollY >= (heightPart3 - 630)){ $("#part3 .img").addClass('animateLeft'); $("#part3 .text").addClass('animateRight'); } if(scrollY >= (recently - 630)){ $(".row2 img").addClass('animateBottom'); } }); // slider var owl = $('.owl-carousel'); owl.owlCarousel({ items: 1, loop: true, margin: 10, nav: true, dots: true, lazyLoad: true, autoplay: true, autoplayTimeout:4000, smartSpeed: 750, }); // click more $(".more p").click(() => { var heightScroll = $(".space").offset().top; $("body").animate({ scrollTop: heightScroll },1200); }); // change content => show content $("#showImage").css({'display' : 'none'}); $("#menu a").click((e) => { e.preventDefault(); }) $("#showProduct").click(() => { $("#changeContent").css({'transform' : 'translateX(100%)'}); setTimeout(() => { $("#changeContent").css({ 'display' : 'none', 'transform' : 'translateX(0)' }); $("#showImage").css({'display' : 'block'}); },500); }); // change content => show images of shop $("#showShop").click(() => { $("#showImage").css({'transform' : 'translateX(-100%)'}); setTimeout(() => { $("#showImage").css({ 'display' : 'none', 'transform' : 'translateX(0)' }); $("#changeContent").css({'display' : 'block'}); },500); }); // open modal $('.modal_images img').click(function() { $('.modal').css({'display' : 'block'}); $("body").css({'overflow-y' : 'hidden'}); $(".modal-content").attr('src',this.src); }); // close modal $(".close").click(function() { $('.modal-content').addClass('animateOut'); setTimeout(() => { $('.modal').css({'display' : 'none'}); $("body").css({'overflow-y' : 'auto'}); $('.modal-content').removeClass('animateOut'); },350); }); })
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** * Base class for ccs.Tween objects. * @class * @extends ccs.ProcessBase */ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ _tweenData:null, _to:null, _from:null, _between:null, _movementBoneData:null, _bone:null, _frameTweenEasing:0, _betweenDuration:0, _totalDuration:0, _toIndex:0, _fromIndex:0, _animation:null, _passLastFrame:false, ctor:function () { ccs.ProcessBase.prototype.ctor.call(this); this._tweenData = null; this._to = null; this._from = null; this._between = null; this._bone = null; this._movementBoneData = null; this._frameTweenEasing = ccs.TweenType.linear; this._toIndex = 0; this._fromIndex = 0; this._animation = null; this._passLastFrame = false; }, /** * init with a CCBone * @param {ccs.Bone} bone * @return {Boolean} */ init:function (bone) { this._from = new ccs.FrameData(); this._between = new ccs.FrameData(); this._bone = bone; this._tweenData = this._bone.getTweenData(); this._tweenData.displayIndex = -1; this._animation = this._bone.getArmature() != null ? this._bone.getArmature().getAnimation() : null; return true; }, /** * play animation by animation name. * @param {Number} animationName The animation name you want to play * @param {Number} durationTo * he frames between two animation changing-over.It's meaning is changing to this animation need how many frames * -1 : use the value from CCMovementData get from flash design panel * @param {Number} durationTween he * frame count you want to play in the game.if _durationTween is 80, then the animation will played 80 frames in a loop * -1 : use the value from CCMovementData get from flash design panel * @param {Number} loop * Whether the animation is loop. * loop < 0 : use the value from CCMovementData get from flash design panel * loop = 0 : this animation is not loop * loop > 0 : this animation is loop * @param {Number} tweenEasing * CCTween easing is used for calculate easing effect * TWEEN_EASING_MAX : use the value from CCMovementData get from flash design panel * -1 : fade out * 0 : line * 1 : fade in * 2 : fade in and out */ play:function (movementBoneData, durationTo, durationTween, loop, tweenEasing) { ccs.ProcessBase.prototype.play.call(this, durationTo, durationTween, loop, tweenEasing); if(loop){ this._loopType = CC_ANIMATION_TYPE_TO_LOOP_FRONT; }else{ this._loopType = CC_ANIMATION_TYPE_NO_LOOP; } this._totalDuration = 0; this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; var difMovement = movementBoneData != this._movementBoneData; this._movementBoneData = movementBoneData; this._rawDuration = this._movementBoneData.duration; var nextKeyFrame = this._movementBoneData.getFrameData(0); this._tweenData.displayIndex = nextKeyFrame.displayIndex; if (this._bone.getArmature().getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED) { ccs.TransformHelp.nodeSub(this._tweenData, this._bone.getBoneData()); this._tweenData.scaleX += 1; this._tweenData.scaleY += 1; } if (this._rawDuration==0) { this._loopType = CC_ANIMATION_TYPE_SINGLE_FRAME; if (durationTo == 0) { this.setBetween(nextKeyFrame, nextKeyFrame); } else { this.setBetween(this._tweenData, nextKeyFrame); } this._frameTweenEasing = ccs.TweenType.linear; } else if (this._movementBoneData.frameList.length > 1) { this._durationTween = durationTween * this._movementBoneData.scale; if (loop && this._movementBoneData.delay != 0) { this.setBetween(this._tweenData, this.tweenNodeTo(this.updateFrameData(1 - this._movementBoneData.delay), this._between)); } else { if (!difMovement || durationTo == 0) this.setBetween(nextKeyFrame, nextKeyFrame); else this.setBetween(this._tweenData, nextKeyFrame); } } this.tweenNodeTo(0); }, gotoAndPlay: function (frameIndex) { ccs.ProcessBase.prototype.gotoFrame.call(this, frameIndex); this._totalDuration = 0; this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; this._isPlaying = true; this._isComplete = this._isPause = false; this._currentPercent = this._curFrameIndex / this._rawDuration; this._currentFrame = this._nextFrameIndex * this._currentPercent; }, gotoAndPause: function (frameIndex) { this.gotoAndPlay(frameIndex); this.pause(); }, /** * update will call this handler, you can handle your logic here */ updateHandler:function () { var locCurrentPercent = this._currentPercent; var locLoopType = this._loopType; if (locCurrentPercent >= 1) { switch (locLoopType) { case CC_ANIMATION_TYPE_SINGLE_FRAME: locCurrentPercent = 1; this._isComplete = true; this._isPlaying = false; break; case CC_ANIMATION_TYPE_NO_LOOP: locLoopType = CC_ANIMATION_TYPE_MAX; if (this._durationTween <= 0) { locCurrentPercent = 1; } else { locCurrentPercent = (locCurrentPercent - 1) * this._nextFrameIndex / this._durationTween; } if (locCurrentPercent >= 1) { locCurrentPercent = 1; this._isComplete = true; this._isPlaying = false; break; } else { this._nextFrameIndex = this._durationTween; this._currentFrame = locCurrentPercent * this._nextFrameIndex; this._totalDuration = 0; this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; break; } case CC_ANIMATION_TYPE_TO_LOOP_FRONT: locLoopType = CC_ANIMATION_TYPE_LOOP_FRONT; this._nextFrameIndex = this._durationTween > 0 ? this._durationTween : 1; if (this._movementBoneData.delay != 0) { this._currentFrame = (1 - this._movementBoneData.delay) * this._nextFrameIndex; locCurrentPercent = this._currentFrame / this._nextFrameIndex; } else { locCurrentPercent = 0; this._currentFrame = 0; } this._totalDuration = 0; this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; break; case CC_ANIMATION_TYPE_MAX: locCurrentPercent = 1; this._isComplete = true; this._isPlaying = false; break; default: this._currentFrame = ccs.fmodf(this._currentFrame, this._nextFrameIndex); break; } } if (locCurrentPercent < 1 && locLoopType < CC_ANIMATION_TYPE_TO_LOOP_BACK) { locCurrentPercent = Math.sin(locCurrentPercent * cc.PI / 2); } this._currentPercent = locCurrentPercent; this._loopType = locLoopType; if (locLoopType > CC_ANIMATION_TYPE_TO_LOOP_BACK) { locCurrentPercent = this.updateFrameData(locCurrentPercent); } if (this._frameTweenEasing != ccs.TweenType.tweenEasingMax) { this.tweenNodeTo(locCurrentPercent); } }, /** * Calculate the between value of _from and _to, and give it to between frame data * @param {ccs.FrameData} from * @param {ccs.FrameData} to */ setBetween:function (from, to, limit) { if (typeof limit == "undefined") { limit = true; } do { if (from.displayIndex < 0 && to.displayIndex >= 0) { this._from.copy(to); this._between.subtract(to, to, limit); break; } if (to.displayIndex < 0 && from.displayIndex >= 0) { this._from.copy(from); this._between.subtract(to, to, limit); break; } this._from.copy(from); this._between.subtract(from, to, limit); } while (0); if (!from.isTween){ this._tweenData.copy(from); this._tweenData.isTween = true; } this.arriveKeyFrame(from); }, /** * Update display index and process the key frame event when arrived a key frame * @param {ccs.FrameData} keyFrameData */ arriveKeyFrame:function (keyFrameData) { if (keyFrameData) { var locBone = this._bone; var displayIndex = keyFrameData.displayIndex; var displayManager = locBone.getDisplayManager(); if (!displayManager.getForceChangeDisplay()) { displayManager.changeDisplayByIndex(displayIndex, false); } this._tweenData.zOrder = keyFrameData.zOrder; locBone.updateZOrder(); locBone.setBlendType(keyFrameData.blendType); var childAramture = locBone.getChildArmature(); if (childAramture) { if (keyFrameData.movement != "") { childAramture.getAnimation().play(keyFrameData.movement); } } } }, /** * According to the percent to calculate current CCFrameData with tween effect * @param {Number} percent * @param {ccs.FrameData} node * @return {ccs.FrameData} */ tweenNodeTo:function (percent, node) { if (!node) { node = this._tweenData; } var locFrom = this._from; var locBetween = this._between; if (!locFrom.isTween){ percent = 0; } node.x = locFrom.x + percent * locBetween.x; node.y = locFrom.y + percent * locBetween.y; node.scaleX = locFrom.scaleX + percent * locBetween.scaleX; node.scaleY = locFrom.scaleY + percent * locBetween.scaleY; node.skewX = locFrom.skewX + percent * locBetween.skewX; node.skewY = locFrom.skewY + percent * locBetween.skewY; this._bone.setTransformDirty(true); if (node && locBetween.isUseColorInfo) this.tweenColorTo(percent, node); return node; }, tweenColorTo:function(percent,node){ var locFrom = this._from; var locBetween = this._between; node.a = locFrom.a + percent * locBetween.a; node.r = locFrom.r + percent * locBetween.r; node.g = locFrom.g + percent * locBetween.g; node.b = locFrom.b + percent * locBetween.b; this._bone.updateColor(); }, /** * Calculate which frame arrived, and if current frame have event, then call the event listener * @param {Number} currentPercent * @param {Boolean} activeFrame * @return {Number} */ updateFrameData:function (currentPercent) { if (currentPercent > 1 && this._movementBoneData.delay != 0) { currentPercent = ccs.fmodf(currentPercent,1); } var playedTime = this._rawDuration * currentPercent; var from, to; var locTotalDuration = this._totalDuration,locBetweenDuration = this._betweenDuration, locToIndex = this._toIndex; // if play to current frame's front or back, then find current frame again if (playedTime < locTotalDuration || playedTime >= locTotalDuration + locBetweenDuration) { /* * get frame length, if this._toIndex >= _length, then set this._toIndex to 0, start anew. * this._toIndex is next index will play */ var length = this._movementBoneData.frameList.length; var frames = this._movementBoneData.frameList; if (playedTime < frames[0].frameID){ from = to = frames[0]; this.setBetween(from, to); return currentPercent; } else if (playedTime >= frames[length - 1].frameID) { if (this._passLastFrame) { from = to = frames[length - 1]; this.setBetween(from, to); return currentPercent; } this._passLastFrame = true; } else { this._passLastFrame = false; } do { this._fromIndex = locToIndex; from = frames[this._fromIndex]; locTotalDuration = from.frameID; locToIndex = this._fromIndex + 1; if (locToIndex >= length) { locToIndex = 0; } to = frames[locToIndex]; //! Guaranteed to trigger frame event if(from.event&& !this._animation.isIgnoreFrameEvent()){ this._animation.frameEvent(this._bone, from.event,from.frameID, playedTime); } if (playedTime == from.frameID|| (this._passLastFrame && this._fromIndex == length-1)){ break; } } while (playedTime < from.frameID || playedTime >= to.frameID); locBetweenDuration = to.frameID - from.frameID; this._frameTweenEasing = from.tweenEasing; this.setBetween(from, to, false); this._totalDuration = locTotalDuration; this._betweenDuration = locBetweenDuration; this._toIndex = locToIndex; } currentPercent = locBetweenDuration == 0 ? 0 : (playedTime - locTotalDuration) / locBetweenDuration; /* * if frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ var tweenType = (this._frameTweenEasing != ccs.TweenType.linear) ? this._frameTweenEasing : this._tweenEasing; if (tweenType != ccs.TweenType.tweenEasingMax&&tweenType != ccs.TweenType.linear) { currentPercent = ccs.TweenFunction.tweenTo(0, 1, currentPercent, 1, tweenType); } return currentPercent; }, /** * animation setter * @param {ccs.ArmatureAnimation} animation */ setAnimation:function (animation) { this._animation = animation; }, /** * animation getter * @return {ccs.ArmatureAnimation} */ getAnimation:function () { return this._animation; }, release:function () { this._from = null; this._between = null; } }); /** * allocates and initializes a ArmatureAnimation. * @constructs * @param {ccs.Bone} bone * @return {ccs.ArmatureAnimation} * @example * // example * var animation = ccs.ArmatureAnimation.create(); */ ccs.Tween.create = function (bone) { var tween = new ccs.Tween(); if (tween && tween.init(bone)) { return tween; } return null; };
import fs from 'fs' import _ from 'underscore' import path from 'path' import glob from 'glob-all' import yaml from 'js-yaml' import brief from './index' import {clone, flatten, singularize, strip} from './util' export default class DataSource { /** * creates a new instance of the data source at path * @param {path} path - the absolute path to data source. * @param {type} type - what type of data source is this */ constructor(pathname, id, options) { this.path = pathname this.id = id this.options = options || {} this.dirname = path.dirname(this.path) this.type = path.extname(this.path).toLowerCase().replace('.','') if(this.options.type){ this.type = this.options.type } } get content(){ return fs.readFileSync(this.path).toString() } get data(){ if(this.type === 'json'){ return JSON.parse(this.content) } if(this.type === 'yaml' || this.type === 'yml'){ return yaml.safeLoad(this.content, 'utf8') } if(this.type === 'csv'){ throw('CSV Is not implemented yet') } return JSON.parse(this.content) } static repo(briefcase, options={}){ if(!options.extensions){ options.extensions = briefcase.config.data_extensions } let {extensions} = options extensions = extensions || 'csv,json,yml,yaml' return attach(briefcase.config.data_path, {extensions}) } } function normalize(path, root){ return path.replace(root + '/', '').replace(/.\w+$/,'') } export function attach(root, options={}){ let extensions = options.extensions.split(',').map(ext => strip(ext).toLowerCase()) let files = flatten(extensions.map(ext => glob.sync(path.join(root,'**/*.' + ext)))) let wrapper = _(files.map(file => new DataSource(file, normalize(file,root)))) wrapper.at = function(pathAlias){ return wrapper.find(data_source => pathAlias.toLowerCase() === data_source.id) } return wrapper }
const request = require('./Http/Client/RequestClient'), configuration = require('./configuration'), APIHelper = require('./APIHelper'); function promiseRequest ({ url, params, query, headers, body, options}) { if (!url) { return Promise.reject(new Error('need url')); } let urlTemplate = `${configuration.BASEURI}${url}`; if (params) { Object.keys(params).forEach(key => { urlTemplate = `${urlTemplate}{${key}}/`; }); urlTemplate = urlTemplate.slice(0, -1); } const queryBuilder = APIHelper.appendUrlWithTemplateParameters(urlTemplate, params); const queryUrl = APIHelper.cleanUrl(queryBuilder); let _headers = { 'accept': 'application/json', 'Authorization': `Bearer ${configuration.oAuthAccessToken}` }; if (headers) { _headers = Object.assign(_headers, headers); } let _body = {}; if (body) { _body = Object.assign(_body, body); } APIHelper.cleanObject(_body); let _options = { queryUrl: queryUrl, method: 'POST', headers: _headers, form : _body, }; if (options) { _options = Object.assign(_options, options); } return new Promise((resolve, reject) => { request(_options, (error, response, context) => { if (error) { reject({ message: error.message, code: error.code }); } else if (response.statusCode >= 200 && response.statusCode <= 206) { resolve(JSON.parse(response.body)); } else { reject({ message: 'HTTP Response Not OK', code: response.statusCode, response: response.body }); } }); }) } module.exports = promiseRequest;
'use strict'; module.exports = function (grunt) { // Unified Watch Object var watchFiles = { serverViews: ['app/views/**/*.*'], serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'], clientViews: ['public/modules/**/views/**/*.html'], clientJS: ['public/js/*.js', 'public/modules/**/*.js'], clientCSS: ['public/modules/**/*.css'], mochaTests: ['app/tests/**/*.js'] }; // Project Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { serverViews: { files: watchFiles.serverViews, options: { livereload: true } }, serverJS: { files: watchFiles.serverJS, tasks: ['jshint'], options: { livereload: true } }, clientViews: { files: watchFiles.clientViews, options: { livereload: true, } }, clientJS: { files: watchFiles.clientJS, tasks: ['jshint'], options: { livereload: true } }, clientCSS: { files: watchFiles.clientCSS, tasks: ['csslint'], options: { livereload: true } } }, jshint: { all: { src: watchFiles.clientJS.concat(watchFiles.serverJS), options: { jshintrc: true } } }, csslint: { options: { csslintrc: '.csslintrc', }, all: { src: watchFiles.clientCSS } }, uglify: { production: { options: { mangle: false }, files: { 'public/dist/application.min.js': 'public/dist/application.js' } } }, cssmin: { combine: { files: { 'public/dist/application.min.css': '<%= applicationCSSFiles %>' } } }, nodemon: { dev: { script: 'server.js', options: { nodeArgs: ['--debug'], ext: 'js,html', watch: watchFiles.serverViews.concat(watchFiles.serverJS) } } }, 'node-inspector': { custom: { options: { 'web-port': 1337, 'web-host': 'localhost', 'debug-port': 5858, 'save-live-edit': true, 'no-preload': true, 'stack-trace-limit': 50, 'hidden': [] } } }, ngAnnotate: { production: { files: { 'public/dist/application.js': '<%= applicationJavaScriptFiles %>' } } }, concurrent: { default: ['nodemon', 'watch'], debug: ['nodemon', 'watch', 'node-inspector'], options: { logConcurrentOutput: true, limit: 10 } }, env: { test: { NODE_ENV: 'test' }, secure: { NODE_ENV: 'secure' } }, mochaTest: { src: watchFiles.mochaTests, options: { reporter: 'spec', require: 'server.js' } }, karma: { unit: { configFile: 'karma.conf.js' } } }); // Load NPM tasks require('load-grunt-tasks')(grunt); // Making grunt default to force in order not to break the project. grunt.option('force', true); // A Task for loading the configuration object grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function () { var init = require('./config/init')(); var config = require('./config/config'); grunt.config.set('applicationJavaScriptFiles', config.assets.js); grunt.config.set('applicationCSSFiles', config.assets.css); }); // Default task(s). grunt.registerTask('default', ['lint', 'concurrent:default']); // Debug task. grunt.registerTask('debug', ['lint', 'concurrent:debug']); // Secure task(s). grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']); // Lint task(s). grunt.registerTask('lint', ['jshint', 'csslint']); // Build task(s). grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']); // Test task. grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']); };
let s = document.createElement('script'); s.src = chrome.extension.getURL('dist/gCal.min.js'); s.onload = function() { this.remove(); }; (document.head || document.documentElement).appendChild(s);
var subdomainer = require('./subdomainer.js'); var sub = new subdomainer('settings.json'); var rl = require('readline'); var i = rl.createInterface({ input: process.stdin, output: process.stdout }); var ask = function(){ i.question("What is the name of subdomain you would like to create? \nName:", function(subdomain) { if( sub.addSubdomain(subdomain) ) console.log("\n" + subdomain + " added"); i.question("\n Add another? [N/y] :", function(yesNo){ if(yesNo.toLowerCase() == "y"){ ask(); }else{ i.close(); process.stdin.destroy(); } }); }); }; ask();
var config = module.exports; config['Test Suites'] = { rootPath: '../', environment: 'node', libs: ['lib/pp.js'], tests: ['test/**/*-test.coffee'], extensions: [require('buster-coffee')] }; /* config['Browser Tests'] = { extends: 'Test Suites', environment: 'browser', sources: ['lib/pp.js'] }; config['Node Test'] = { extends: 'Test Suites', environment: 'node' }; */
module.exports = createApp var express = require('express') var session = require('express-session') var uuid = require('node-uuid') var cors = require('cors') var vhost = require('vhost') var path = require('path') var WcMiddleware = require('wc_express').middleware var Sequelize = require('sequelize') var express = require('express') var program = require('commander') var bodyParser = require('body-parser') var https = require('https') var fs = require('fs') var debug = require('debug')('qpm_media:create-app') var addmedia = require('./handlers/addmedia') var balance = require('qpm_balance').handlers.balance var buffer = require('./handlers/buffer') var cache = require('./handlers/cache') var download = require('./handlers/download') var home = require('./handlers/home') var random_rate = require('./handlers/random_rate') var audio = require('./handlers/random_rate_audio') var video = require('./handlers/random_rate_video') var rate = require('./handlers/rate') var search = require('./handlers/search') var static = require('./handlers/static') var tag = require('./handlers/tag') var top = require('./handlers/top') var wc_db = require('wc_db') var corsSettings = cors({ methods: [ 'OPTIONS', 'HEAD', 'GET', 'PATCH', 'POST', 'PUT', 'DELETE' ], exposedHeaders: 'User, Location, Link, Vary, Last-Modified, ETag, Accept-Patch, Updates-Via, Allow, Content-Length', credentials: true, maxAge: 1728000, origin: true }) function createApp (argv, sequelize, config) { var app = express() // Session var sessionSettings = { secret: uuid.v1(), saveUninitialized: false, resave: false } sessionSettings.cookie = { secure: true } app.use(session(sessionSettings)) app.use('/', WcMiddleware(corsSettings)) app.use( bodyParser.json() ) // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })) var config = require('../config/config') sequelize = wc_db.getConnection(config.db) debug(config) app.use(function(req,res, next) { res.locals.sequelize = sequelize res.locals.config = config next() }) app.set('view engine', 'ejs') config.ui = config.ui || {} config.ui.tabs = [ {"label" : "Home", "uri" : "/"}, {"label" : "Balance", "uri" : "/balance"}, {"label" : "Images", "uri" : "/random_rate"}, {"label" : "Audio", "uri" : "/random_rate_audio"}, {"label" : "Video", "uri" : "/random_rate_video"}, {"label" : "Rate", "uri" : "/rate"}, {"label" : "Top", "uri" : "/top"}, {"label" : "Tags", "uri" : "/tag"}, {"label" : "Search", "uri" : "/search"} ] config.ui.name = "Media" //app.use('/static', express.static('public')) app.get('/static/*', static) app.get('/download/*', download) app.post('/addmedia', addmedia) app.get('/balance', balance) app.get('/buffer', buffer) app.get('/cache', cache) app.get('/random_rate', random_rate) app.get('/random_rate_audio', audio) app.get('/random_rate_video', video) app.all('/rate', rate) app.get('/search', search) app.all('/tag', tag) app.get('/top', top) app.get('/', home) return app }
var gulp = require('gulp'); require('./gulp/boot'); gulp.task('default', ['scripts:bower', 'scripts:reactjs', 'scripts:app']);
module.exports = { CHANNEL_ID: ' ', CHANNEL_SERECT: ' ', MID: ' ' }
export default class Memo { constructor({ id, title, body }) { this.id = id; this.title = title; this.body = body; } static createNew() { return new Memo({ title: '', body: '', }); } }
const { spawn } = require("child_process"); const path = require("path"); const images = require("../.private/images.json"); images.forEach(img => { const { _id: name, picture } = img; const ext = picture.match(/\.(.{3})$/)[1]; const file = `${name.replace(/\s/, "_")}.${ext}`; const filepath = path.resolve(__dirname, "..", ".private", "pictures", file); const wget = spawn("wget", [picture, "-O", filepath]); wget.on('close', (code) => { console.log('exit ' + code + ' for ' + filepath); }); });
'use strict'; /*! * Collection * https://github.com/kobezzza/Collection * * Released under the MIT license * https://github.com/kobezzza/Collection/blob/master/LICENSE */ import { Collection } from '../core'; import { isArray, isFunction } from '../helpers/types'; import { any } from '../helpers/gcc'; /** * Returns true if all elements in the collection matches by the specified condition * * @see Collection.prototype.forEach * @param {($$CollectionFilter|$$CollectionSingleBase)=} [opt_filter] - function filter or an array of functions * @param {?$$CollectionSingleBase=} [opt_params] - additional parameters * @return {(boolean|!Promise<boolean>)} */ Collection.prototype.every = function (opt_filter, opt_params) { let p = opt_params || {}; if (!isArray(opt_filter) && !isFunction(opt_filter)) { p = opt_filter || p; opt_filter = null; } this._initParams(p, opt_filter); p = any(Object.assign(Object.create(this.p), p, {mult: false, result: true})); p.inverseFilter = !p.inverseFilter; const returnVal = any(this.forEach(() => p.result = false, p)); if (returnVal !== this) { return returnVal; } return p.result; };
(function (root, factory) { if (typeof define === "function" && define.amd) { define([], factory); } else if (typeof module === "object" && module.exports) { module.exports = factory(); } else { root.yalla = factory(); root.Context = root.Context || root.yalla.Context; root.render = root.render || root.yalla.render; root.plug = root.plug || root.yalla.plug; root.uuidv4 = root.uuidv4 || root.yalla.uuidv4; root.Event = root.Event || root.yalla.Event; } }(typeof self !== "undefined" ? self : eval("this"), function () { /* The MIT License (MIT) Copyright (c) 2017-present, Arif Rachim 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. */ let isChrome = "chrome" in window && "webstore" in window.chrome; const Event = { SYNCING_DONE : "syncingdone" }; const cloneNodeTree = (node) => { if (isChrome) { return node.cloneNode(true); } else { let clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false); let child = node.firstChild; while (child) { clone.appendChild(cloneNodeTree(child)); child = child.nextSibling; } return clone; } }; const isPromise = (object) => { return (typeof object === "object" && "constructor" in object && object.constructor.name === "Promise"); }; const uuidv4 = () => "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0, v = c === "x" ? r : (r & 0x3 | 0x8); return v.toString(16); }); class Template { destroy() { throw new Error("Please implement template.destroy "); } } const attributeReflectToPropsMap = { "INPUT": ["VALUE"] }; const attributeChangesReflectToProperties = (attributeName, nodeName) => { attributeName = attributeName.toUpperCase(); nodeName = nodeName.toUpperCase(); return attributeReflectToPropsMap[nodeName] ? attributeReflectToPropsMap[nodeName].indexOf(attributeName) >= 0 : false; }; const parentTagMap = { "col": "colgroup", "td": "tr", "area": "map", "tbody": "table", "tfoot": "table", "th": "tr", "thead": "table", "tr": "tbody", "caption": "table", "colgroup": "table", "li": "ul", "g": "svg", "circle": "svg", "rect": "svg", "polygon": "svg", "eclipse": "svg", "text": "svg" }; const isMinimizationAttribute = (node) => { return ["checked", "compact", "declare", "defer", "disabled", "ismap", "noresize", "noshade", "nowrap", "selected"].indexOf(node.nodeName) >= 0; }; const getPath = (node) => { if (node.nodeType === Node.ATTRIBUTE_NODE) { return getPath(node.ownerElement).concat([{name: node.nodeName}]); } let i = 0; let child = node; while ((child = child.previousSibling) !== null) { i++; } let path = []; path.push(i); if (node.parentNode && node.parentNode.parentNode) { return getPath(node.parentNode).concat(path); } return path; }; const getNode = (path, documentFragment) => { return path.reduce((content, path) => { if (typeof path === "number") { return content.childNodes[path]; } else { return content.attributes[path.name]; } }, documentFragment); }; const buildActualAttributeValue = (nodeValue, valueIndexes, templateValues) => { let actualAttributeValue = nodeValue; let valFiltered = valueIndexes.map(valueIndex => templateValues[(valueIndex)]); valueIndexes.forEach((valueIndex, index) => { actualAttributeValue = actualAttributeValue.replace(`<!--${valueIndex}-->`, valFiltered[index]); }); return actualAttributeValue; }; class HtmlTemplateCollection extends Template { constructor(items, keyFn, templateFn, context) { super(); this.items = items; this.keyFn = typeof keyFn === "string" ? ((item) => item[keyFn]) : keyFn; this.templateFn = templateFn; this.context = context; this.keys = []; this.templates = {}; this.initialzed = false; } iterateRight(callback) { if (!this.initialzed) { let index = this.items.length - 1; while (index >= 0) { let item = this.items[index]; let key = this.keyFn.apply(this, [item, index]); let template = this.templateFn.apply(this, [item, index]); if (callback) { callback.apply(null, [item, key, template, index]); } index--; this.keys.push(key); this.templates[key] = template; } this.initialzed = true; this.keys.reverse(); } else { let index = this.keys.length - 1; while (index >= 0) { let item = this.items[index]; let key = this.keys[index]; let template = this.templates[key]; if (callback) { callback.apply(null, [item, key, template, index]); } index--; } } } } const isMatch = (newActualValues, values) => { if (newActualValues === values) { return true; } else if (Array.isArray(newActualValues) && Array.isArray(values) && newActualValues.length === values.length) { let isMatch = true; for (let i = 0; i < values.length; i++) { isMatch = isMatch && (newActualValues[i] === values[i]); if (!isMatch) { return false; } } return true; } return false; }; class Marker { constructor(node) { this.node = node; this.attributes = {}; } static from(node) { let element = node; if (node.nodeType === Node.ATTRIBUTE_NODE) { element = node.ownerElement; } element.$data = element.$data || new Marker(element); return element.$data; } } class HtmlTemplate extends Template { constructor(strings, values, context) { super(); this.strings = strings; this.values = values; this.context = context; this.key = this.strings.join("").trim(); this.nodeValueIndexArray = null; this.documentFragment = null; } static lookNodeValueArray(nodeValue) { let result = []; let pointerStart = nodeValue.indexOf("<!--"); let pointerEnd = nodeValue.indexOf("-->", pointerStart); while (pointerEnd < nodeValue.length && pointerEnd >= 0 && pointerStart >= 0) { result.push(nodeValue.substring((pointerStart + 4), pointerEnd)); pointerStart = nodeValue.indexOf("<!--", (pointerEnd + 3)); pointerEnd = nodeValue.indexOf("-->", pointerStart); } return result; } static getProperTemplateTag(contentText) { let openTag = contentText.substring(1, contentText.indexOf(">")); openTag = (openTag.indexOf(" ") > 0 ? openTag.substring(0, openTag.indexOf(" ")) : openTag).toLowerCase(); let rootTag = parentTagMap[openTag]; rootTag = rootTag || "div"; let template = rootTag === "svg" ? document.createElementNS("http://www.w3.org/2000/svg","svg") : document.createElement(rootTag); template.innerHTML = contentText; return template; } static applyValues(nextHtmlTemplate, nodeValueIndexArray) { let newValues = nextHtmlTemplate.values; let context = nextHtmlTemplate.context; if (!nodeValueIndexArray) { return; } nodeValueIndexArray.forEach((nodeValueIndex) => { if(nodeValueIndex == null){ return; } let {node, valueIndexes, values} = nodeValueIndex; let newActualValues = Array.isArray(valueIndexes) ? valueIndexes.map((valueIndex) => newValues[(valueIndex)]) : newValues[valueIndexes]; let nodeName = node.nodeName; let isEvent = node.nodeType === Node.ATTRIBUTE_NODE && nodeName.indexOf("on") === 0; // if values are match, or ifts named eventListener then we dont need to perform update if (isMatch(newActualValues, values) || (isEvent && newActualValues[0].name)) { return; } if (node.nodeType === Node.ATTRIBUTE_NODE) { let marker = Marker.from(node); let nodeValue = nodeValueIndex.nodeValue; if (isEvent) { let valueIndex = valueIndexes[0]; node.ownerElement[nodeName] = newValues[valueIndex]; marker.attributes[nodeName] = newValues[valueIndex]; } else { let plugOrPromiseValue = newValues.reduce((plugOrPromise,newValue,index) => { if(newValue instanceof Plug || isPromise(newValue)){ plugOrPromise.push({index,value:newValue}); } return plugOrPromise; },[]); if(plugOrPromiseValue.length>0){ node.ownerElement.id = node.ownerElement.id || uuidv4(); let id = node.ownerElement.id; context.addEventListener(Event.SYNCING_DONE,()=>{ let node = document.getElementById(id); if (!node) { node = context.root.getElementsByTagName("*")[id]; } plugOrPromiseValue.forEach(({index,value}) => { let valueIndex = index; let attributeNode = node.getAttributeNode(nodeName); let setContent = (value) => { let marker = Marker.from(node); let {nodeValue:template,valueIndexes,newValues:templateValue} = marker.attributes[nodeName]; newValues[valueIndex] = value; HtmlTemplate.updateAttributeValue(nodeValue, valueIndexes, newValues, attributeNode); }; if(value instanceof Plug){ value.factory.apply(null,[{ node : attributeNode, name : nodeName, getContent : () => { let marker = Marker.from(node); let {newValues:templateValue} = marker.attributes[nodeName]; return newValues[valueIndex]; }, setContent }]); } if(isPromise(value)){ value.then(setContent); } }); }); }else{ HtmlTemplate.updateAttributeValue(nodeValue, valueIndexes, newValues, node); } marker.attributes[nodeName] = {template : nodeValue,valueIndexes,templateValue : newValues}; } } if (node.nodeType === Node.TEXT_NODE) { node.nodeValue = buildActualAttributeValue(nodeValueIndex.nodeValue, valueIndexes, newValues); } if (node.nodeType === Node.COMMENT_NODE) { let value = newValues[valueIndexes]; Outlet.from(node).setContent(value,context); } nodeValueIndex.values = newActualValues; }); } static updateAttributeValue(attributeValue, valueIndexes, newValues, attributeNode) { let nodeName = attributeNode.nodeName; let actualAttributeValue = buildActualAttributeValue(attributeValue, valueIndexes, newValues); if (isMinimizationAttribute(attributeNode)) { attributeNode.ownerElement[nodeName] = actualAttributeValue.trim() === "true"; attributeNode.ownerElement.setAttribute(nodeName, ""); } else { attributeNode.ownerElement.setAttribute(nodeName, actualAttributeValue); if (attributeChangesReflectToProperties(nodeName, attributeNode.ownerElement.nodeName)) { attributeNode.ownerElement[nodeName] = actualAttributeValue; } } if (nodeName.indexOf(".bind") >= 0) { let attributeName = nodeName.substring(0, nodeName.indexOf(".bind")); attributeNode.ownerElement.setAttribute(attributeName, actualAttributeValue); attributeNode.ownerElement.removeAttribute(nodeName); } return actualAttributeValue; } buildTemplate(templateString) { this.documentFragment = HtmlTemplate.getProperTemplateTag(templateString); this.nodeValueIndexArray = this.buildNodeValueIndex(this.documentFragment, this.documentFragment.nodeName); HtmlTemplate.applyValues(this, this.nodeValueIndexArray); } buildNodeValueIndex(documentFragment, documentFragmentNodeName) { let childNodes = documentFragment.childNodes; let nodeValueIndexArray = []; let node = childNodes[0]; if (undefined === node) { return nodeValueIndexArray; } do { if (node.nodeType === Node.ELEMENT_NODE) { let attributes = node.attributes; let k = attributes.length; for (let attributeIndex = 0; attributeIndex < k; attributeIndex++) { let nodeValue = attributes[attributeIndex].nodeValue; let nodeValueIndexMap = HtmlTemplate.lookNodeValueArray(nodeValue); let valueIndexes = nodeValueIndexMap.map(x => x.match(/[\w\.]+/)[0]).map(i => parseInt(i)); if (valueIndexes && valueIndexes.length > 0) { nodeValueIndexArray.push({node: attributes[attributeIndex], valueIndexes, nodeValue}); } } nodeValueIndexArray = nodeValueIndexArray.concat(this.buildNodeValueIndex(node, node.nodeName)); } if (node.nodeType === Node.TEXT_NODE && documentFragmentNodeName.toUpperCase() === "STYLE") { let nodeValue = node.nodeValue; let nodeValueIndexMap = HtmlTemplate.lookNodeValueArray(nodeValue); let valueIndexes = nodeValueIndexMap.map(x => x.match(/[\w\.]+/)[0]).map(i => parseInt(i)); if (valueIndexes && valueIndexes.length > 0) { nodeValueIndexArray.push({node, valueIndexes, nodeValue}); } } if (node.nodeType === Node.COMMENT_NODE) { let nodeValue = node.nodeValue; node.nodeValue = "outlet"; nodeValueIndexArray.push({node: node, valueIndexes: parseInt(nodeValue)}); } node = node.nextSibling; } while (node); return nodeValueIndexArray; } constructTemplate() { if (!this.context.hasCache(this.key)) { let templateString = this.buildStringSequence(); this.buildTemplate(templateString); return this.context.cache(this.key, this); } let htmlTemplate = this.context.cache(this.key); let promisesPlaceholder = htmlTemplate.documentFragment.querySelectorAll("span[data-async-outlet]"); let promisesPlaceHolderLength = promisesPlaceholder.length; while(promisesPlaceHolderLength--){ let promisePlaceholder = promisesPlaceholder[promisesPlaceHolderLength]; if(promisePlaceholder.nextSibling){ let outlet = Outlet.from(promisePlaceholder.nextSibling); outlet.clearContent(); } } return htmlTemplate; } buildStringSequence() { return this.strings.reduce((result, string, index) => { return index === 0 ? string : `${result}<!--${(index - 1)}-->${string}`; }, "").trim(); } } class Context { constructor() { this.cacheInstance = {}; this.syncCallbackStack = []; this.html = (strings, ...values) => new HtmlTemplate(strings, values, this); this.htmlCollection = (arrayItems, keyFn, templateFn) => new HtmlTemplateCollection(arrayItems, keyFn, templateFn, this); this.listeners = {}; } hasCache(key) { return key in this.cacheInstance; } cache(key, data) { if (!this.hasCache(key)) { this.cacheInstance[key] = data; } return this.cacheInstance[key]; } addSyncCallback(callback) { this.syncCallbackStack.push(callback); } addEventListener(event,callback,calledOnce=false){ let token = `${event}:${uuidv4()}`; this.listeners[event] = this.listeners[event] || []; let listener = this.listeners[event]; listener.push({token,callback,calledOnce}); return token; } removeEventListener(token){ let [event,tokenId] = token.split(":"); let listener = this.listeners[event]; listener = listener.filter(callbackItem => callbackItem.token != tokenId); this.listeners[event] = listener; } dispatchEvent(event,...payload){ if(!(event in this.listeners)){ return; } let listener = this.listeners[event]; let markForRemoval = []; listener.forEach(callbackItem => { callbackItem.callback.apply(null,payload); if(callbackItem.calledOnce){ let [event,tokenId] = callbackItem.token.split(":"); markForRemoval.push(tokenId); } }); if(markForRemoval.length > 0){ listener = listener.filter(callbackItem => { return markForRemoval.indexOf(callbackItem.token) < 0 }); } this.listeners[event] = listener; } clearSyncCallbacks() { this.syncCallbackStack.forEach((callback) => callback.apply()); this.syncCallbackStack = []; this.dispatchEvent(Event.SYNCING_DONE); } } const getTemporaryOutlet = (id, context) => { let templateContent = document.getElementById(id); if (!templateContent) { templateContent = context.root.getElementsByTagName("*")[id]; } if(templateContent){ let commentNode = templateContent.nextSibling; templateContent.remove(); return Outlet.from(commentNode); } return false; }; class Outlet { constructor(commentNode) { this.commentNode = commentNode; this.content = null; } static from(node) { if (node instanceof Comment) { node.$data = node.$data || new Outlet(node); return node.$data; } else { if (!node.$outlet) { node.$outlet = document.createComment("outlet"); node.appendChild(node.$outlet); } return Outlet.from(node.$outlet); } } constructTextContent() { this.content = this.commentNode.previousSibling; } constructHtmlTemplateCollectionContent(htmlTemplateCollection) { this.content = new HtmlTemplateCollectionInstance(htmlTemplateCollection, this); this.content.instance = {}; let pointer = this.commentNode; htmlTemplateCollection.iterateRight((item, key) => { do { pointer = pointer.previousSibling; } while (pointer.nodeType !== Node.COMMENT_NODE && pointer.nodeValue !== "outlet-child"); this.content.instance[key] = pointer; }); } constructHtmlTemplateContent(htmlTemplate) { if(htmlTemplate === undefined){ return; } let childNodesLength = htmlTemplate.context.cache(htmlTemplate.key).documentFragment.childNodes.length; this.content = new HtmlTemplateInstance(htmlTemplate, this); let sibling = this.commentNode; while (childNodesLength--) { sibling = sibling.previousSibling; this.content.instance.push(sibling); } this.content.instance.reverse(); } makeTemporaryOutlet(context){ let id = uuidv4(); this.setHtmlTemplateContent(context.html`<span id="${id}" style="display: none" data-async-outlet>outlet</span>`); return id; }; setContent(template,context) { if (isPromise(template)) { if (this.content === null) { let id = this.makeTemporaryOutlet(context); template.then((result) => { let outlet = getTemporaryOutlet(id, context); if(outlet){ outlet.setContent(result); syncNode(result, outlet.commentNode); } }); } else { template.then((result) => { this.setContent(result); }); } } else if (template instanceof Plug) { if (this.content === null) { let id = this.makeTemporaryOutlet(context); context.addEventListener(Event.SYNCING_DONE,() => { let outlet = getTemporaryOutlet(id, context); if(outlet){ template.factory.apply(null, [{ getContent : () => outlet.currentContent, setContent : (value) =>{ outlet.setContent.apply(outlet,[value]); outlet.currentContent = value; } }]); } },true); } else { let self = this; template.factory.apply(null, [{ getContent : () => self.currentContent, setContent : (value) => { self.setContent.apply(self,[value]); self.currentContent = value; } }]); } } else if (template instanceof HtmlTemplate) { this.setHtmlTemplateContent(template); } else if (template instanceof HtmlTemplateCollection) { this.setHtmlTemplateCollectionContent(template); } else { this.setTextContent(template); } } setTextContent(text) { if (this.content instanceof Text) { this.content.nodeValue = text; } else { this.clearContent(); this.content = document.createTextNode(text); this.commentNode.parentNode.insertBefore(this.content, this.commentNode); } } setHtmlTemplateCollectionContent(htmlTemplateCollection) { let clearContentWasCalled = false; if (this.content && !(this.content instanceof HtmlTemplateCollectionInstance)) { clearContentWasCalled = true; this.clearContent(); } this.content = this.content || new HtmlTemplateCollectionInstance(htmlTemplateCollection, this); this.content.applyValues(htmlTemplateCollection); if (clearContentWasCalled) { syncNode(htmlTemplateCollection, this.commentNode); } } setHtmlTemplateContent(htmlTemplate) { let clearContentWasCalled = false; let contentHasSameKey = this.content && this.content instanceof HtmlTemplateInstance ? this.content.template.key === htmlTemplate.key : false; if (this.content !== null && !contentHasSameKey) { this.clearContent(); clearContentWasCalled = true; } if (!this.content) { let template = htmlTemplate.constructTemplate(); this.content = new HtmlTemplateInstance(template, this); } this.content.applyValues(htmlTemplate); if (clearContentWasCalled) { syncNode(htmlTemplate, this.commentNode); } } clearContent() { if (this.content !== null) { if (this.content instanceof Template) { this.content.destroy(); } else { this.content.remove(); } this.content = null; } } firstChildNode() { if (this.content instanceof HtmlTemplateInstance) { return this.content.instance[0]; } else if (this.content instanceof HtmlTemplateCollectionInstance) { let firstKey = this.content.template.keys[0]; let outlet = Outlet.from(this.content.instance[firstKey]); return outlet.firstChildNode(); } else { return this.content; } } validateInstancePosition() { if (this.content instanceof HtmlTemplateInstance) { this.content.instance.reduceRight((pointer, ctn) => { if (pointer.previousSibling !== ctn) { pointer.parentNode.insertBefore(ctn, pointer); } return ctn; }, this.commentNode); } else if (this.content instanceof HtmlTemplateCollectionInstance) { // not required since we already sync when rendering } else { if (this.commentNode.previousSibling !== this.content) { this.commentNode.parentNode.insertBefore(this.content, this.commentNode); } } } } class HtmlTemplateCollectionInstance extends Template { constructor(templateCollection, outlet) { super(); this.template = templateCollection; this.outlet = outlet; this.instance = null; } applyValues(newHtmlTemplateCollection) { let context = newHtmlTemplateCollection.context; if (this.instance === null) { this.instance = {}; let outletPointer = this.outlet.commentNode; newHtmlTemplateCollection.iterateRight((item, key, template) => { let childPlaceholder = Outlet.from(document.createComment("outlet-child")); outletPointer.parentNode.insertBefore(childPlaceholder.commentNode, outletPointer); Outlet.from(childPlaceholder.commentNode).setContent(template,context); outletPointer = childPlaceholder.firstChildNode(); this.instance[key] = childPlaceholder.commentNode; }); } else { newHtmlTemplateCollection.iterateRight(); if (newHtmlTemplateCollection.items.length === 0) { if (this.outlet.commentNode.parentNode.$htmlCollectionInstanceChild && this.outlet.commentNode.parentNode.$htmlCollectionInstanceChild.length === 1) { let parentNode = this.outlet.commentNode.parentNode; parentNode.innerText = ""; parentNode.appendChild(this.outlet.commentNode); this.instance = {}; } } else { let oldHtmlTemplateCollection = this.template; oldHtmlTemplateCollection.keys.forEach((key) => { let keyIsDeleted = newHtmlTemplateCollection.keys.indexOf(key) < 0; if (keyIsDeleted) { let commentNode = this.instance[key]; Outlet.from(commentNode).clearContent(); commentNode.remove(); delete this.instance[key]; } }); } let outletPointer = this.outlet.commentNode; newHtmlTemplateCollection.iterateRight((item, key, template) => { let commentNode = this.instance[key]; if (commentNode) { let childOutlet = Outlet.from(commentNode); childOutlet.setContent(template); if (outletPointer.previousSibling !== commentNode) { outletPointer.parentNode.insertBefore(commentNode, outletPointer); childOutlet.validateInstancePosition(); } outletPointer = childOutlet.firstChildNode(); } else { let childPlaceholder = Outlet.from(document.createComment("outlet-child")); outletPointer.parentNode.insertBefore(childPlaceholder.commentNode, outletPointer); Outlet.from(childPlaceholder.commentNode).setContent(template,context); outletPointer = childPlaceholder.firstChildNode(); this.instance[key] = childPlaceholder.commentNode; this.template.context.addSyncCallback(() => syncNode(template, childPlaceholder.commentNode)); } }); this.template = newHtmlTemplateCollection; } } destroy() { this.template.keys.forEach((key) => { let childPlaceholderCommentNode = this.instance[key]; Outlet.from(childPlaceholderCommentNode).clearContent(); childPlaceholderCommentNode.remove(); delete this.instance[key]; }); this.outlet = null; this.instance = null; this.template = null; } } class HtmlTemplateInstance extends Template { constructor(template, outlet) { super(); this.template = template; this.outlet = outlet; this.instance = []; this.nodeValueIndexArray = null; } applyValues(newHtmlTemplate) { if (this.instance === null || this.instance.length === 0) { HtmlTemplate.applyValues(newHtmlTemplate, this.template.nodeValueIndexArray); let documentFragment = this.template.documentFragment; let cloneNode = cloneNodeTree(documentFragment); let commentNode = this.outlet.commentNode; let cloneChildNode = cloneNode.childNodes[0]; let nextSibling = null; do { this.instance.push(cloneChildNode); nextSibling = cloneChildNode.nextSibling; commentNode.parentNode.insertBefore(cloneChildNode, commentNode); cloneChildNode = nextSibling; } while (cloneChildNode); } else if (this.nodeValueIndexArray) { HtmlTemplate.applyValues(newHtmlTemplate, this.nodeValueIndexArray); } } destroy() { this.instance.forEach((instance) => instance.remove()); this.nodeValueIndexArray = null; this.outlet = null; this.template = null; } } const validateIsFunction = (functionToCheck,error) => { let isFunction = functionToCheck && typeof functionToCheck === 'function'; if(!isFunction){ throw new Error(error); } }; const applyAttributeValue = (actualNode, valueIndexes, templateValues, nodeValue) => { let marker = Marker.from(actualNode); let nodeName = actualNode.nodeName; let isEvent = nodeName.indexOf("on") === 0; if (isEvent) { let valueIndex = valueIndexes[0]; validateIsFunction(templateValues[valueIndex],`Event listener ${actualNode.nodeName} should be a function (event) => {}'`); marker.attributes[nodeName] = templateValues[valueIndex]; actualNode.ownerElement.setAttribute(nodeName, "return false;"); actualNode.ownerElement[nodeName] = templateValues[valueIndex]; } else { marker.attributes[nodeName] = { template : nodeValue, valueIndexes, templateValue : templateValues }; } }; const applyOutletValue = (actualNode, templateValues, valueIndexes) => { let outlet = Outlet.from(actualNode); let value = templateValues[valueIndexes]; if (value instanceof HtmlTemplate) { outlet.constructHtmlTemplateContent(value); syncNode(value, outlet.commentNode); } else if (value instanceof HtmlTemplateCollection) { outlet.constructHtmlTemplateCollectionContent(value); syncNode(value, outlet.commentNode); } else { outlet.constructTextContent(); } }; const mapNodeValueIndexArray = (nodeValueIndex, docFragment, templateValues = []) => { let {nodeValue, valueIndexes} = nodeValueIndex; let path = getPath(nodeValueIndex.node); let actualNode = getNode(path, docFragment); if(!actualNode){ return; } let values = Array.isArray(valueIndexes) ? valueIndexes.map(index => templateValues[index]) : templateValues[valueIndexes]; let isStyleNode = actualNode.parentNode && actualNode.parentNode.nodeName.toUpperCase() === "STYLE"; if (isStyleNode) { return {node: actualNode, valueIndexes, nodeValue, values}; } else if (actualNode.nodeType === Node.ATTRIBUTE_NODE) { applyAttributeValue(actualNode, valueIndexes, templateValues, nodeValue); return {node: actualNode, valueIndexes, nodeValue, values}; } else { applyOutletValue(actualNode, templateValues, valueIndexes); return {node: actualNode, valueIndexes, values}; } }; const syncNode = (nextTemplate, node) => { let outlet = Outlet.from(node); if (outlet.content && outlet.content instanceof HtmlTemplateInstance) { let htmlTemplateInstance = outlet.content; let originalTemplate = htmlTemplateInstance.template; let templateValues = nextTemplate.values; let docFragment = {childNodes: htmlTemplateInstance.instance}; if (originalTemplate.nodeValueIndexArray === null) { let cacheTemplate = originalTemplate.context.cache(originalTemplate.key); docFragment = {childNodes: outlet.content.instance}; htmlTemplateInstance.nodeValueIndexArray = cacheTemplate.nodeValueIndexArray.map(nodeValueIndex => mapNodeValueIndexArray(nodeValueIndex, docFragment, templateValues)); } else { htmlTemplateInstance.nodeValueIndexArray = originalTemplate.nodeValueIndexArray.map(nodeValueIndex => mapNodeValueIndexArray(nodeValueIndex, docFragment, templateValues)); } } if (outlet.content && outlet.content instanceof HtmlTemplateCollectionInstance) { let htmlTemplateCollectionInstance = outlet.content; let templates = htmlTemplateCollectionInstance.template.templates; let keys = htmlTemplateCollectionInstance.template.keys; outlet.commentNode.parentNode.$htmlCollectionInstanceChild = outlet.commentNode.parentNode.$htmlCollectionInstanceChild || []; outlet.commentNode.parentNode.$htmlCollectionInstanceChild.push(outlet.commentNode); keys.forEach(key => { let template = templates[key]; let commentNode = htmlTemplateCollectionInstance.instance[key]; let outlet = Outlet.from(commentNode); if (outlet.content === null) { if (template instanceof HtmlTemplate) { outlet.constructHtmlTemplateContent(template.context.cache(template.key)); syncNode(template, commentNode); } } else { if (outlet.content instanceof HtmlTemplateInstance) { syncNode(template, commentNode); } } }); } }; const syncContent = function (templateValue,node) { if (!node.$synced) { syncNode(templateValue, node); node.$synced = true; } }; const setContent = (templateValue,node) => { templateValue.context.root = templateValue.context.root || node; Outlet.from(node).setContent(templateValue); }; const executeWithIdleCallback = (callback) => { if ("requestIdleCallback" in window) { requestIdleCallback(callback); } else { callback(); } }; const executeWithRequestAnimationFrame = (callback) => { if ("requestAnimationFrame" in window) { requestAnimationFrame(callback); } else { callback(); } }; const render = (templateValue, node , immediateEffect = true) => { if("Promise" in window){ return new Promise(resolve => { let update = ()=>{ setContent.apply(null,[templateValue,node]); resolve(); }; if(immediateEffect){ executeWithRequestAnimationFrame(update); }else{ executeWithIdleCallback(update); } }).then(()=>{ return new Promise(resolve => { executeWithIdleCallback(()=>{ syncContent.apply(null,[templateValue,node]); resolve(); }); }); }).then(() => { return new Promise(resolve => { executeWithIdleCallback(() =>{ templateValue.context.clearSyncCallbacks(); resolve(); }); }); }); }else{ let thencallback = {then:()=>{}}; setTimeout(()=>{ setContent(templateValue,node); syncContent(templateValue,node); templateValue.context.clearSyncCallbacks(); thencallback.then.apply(null,[]); },0); return thencallback; } }; class Plug { constructor(factory) { this.factory = factory; } } const plug = (callback) => { return new Plug(callback); }; return {Context, render, plug, uuidv4, Event}; }));
#!/usr/bin/env node const csv = require('fast-csv'); const fs = require('fs'); const St2C = require('../lib/stoptimes/st2c.js'); const numCPUs = require('os').cpus().length; // Fragment stop_times.txt according to the number of available CPU cores var stopTimes = fs.createReadStream('stop_times.txt', { encoding: 'utf8', objectMode: true }) .pipe(csv.parse({ objectMode: true, headers: true, quote: '"' })) .on('error', function (e) { console.error(e); }); var connectionsPool = createWriteStreams('connections'); var connIndex = -1; var currentTrip = null; var printedRows = 0; var connectionRules = stopTimes.pipe(new St2C()); connectionRules.on('error', err => { console.error(err.message); process.exit(-1); }) connectionRules.on('data', row => { if (connIndex === -1) { for (let i in connectionsPool) { connectionsPool[i].write(Object.keys(row)); } } if (row['trip_id'] !== currentTrip) { currentTrip = row['trip_id']; connIndex = connIndex < numCPUs - 1 ? connIndex + 1 : 0; } connectionsPool[connIndex].write(Object.values(row)) printedRows++; }); connectionRules.on('end', () => { for (let i in connectionsPool) { connectionsPool[i].end(); } console.error('Converted ' + printedRows + ' stop_times to connections'); }); function createWriteStreams(name) { let writers = []; for (let i = 0; i < numCPUs; i++) { const stream = csv.format(); stream.pipe(fs.createWriteStream(name + '_' + i + '.txt', { encoding: 'utf8' })); writers.push(stream); } return writers; }
/*global $ */ $(document).ready(function () { "use strict"; $('.menu > ul > li:has( > ul)').addClass('menu-dropdown-icon'); //Checks if li has sub (ul) and adds class for toggle icon - just an UI $('.menu > ul > li > ul:not(:has(ul))').addClass('normal-sub'); //Checks if drodown menu's li elements have anothere level (ul), if not the dropdown is shown as regular dropdown, not a mega menu (thanks Luka Kladaric) $(".menu > ul").before("<a href=\"#\" class=\"menu-mobile\">Navigation</a>"); //Adds menu-mobile class (for mobile toggle menu) before the normal menu //Mobile menu is hidden if width is more then 959px, but normal menu is displayed //Normal menu is hidden if width is below 959px, and jquery adds mobile menu //Done this way so it can be used with wordpress without any trouble $(".menu > ul > li").hover(function (e) { if ($(window).width() > 943) { $(this).children("ul").stop(true, false).fadeToggle(150); e.preventDefault(); } }); //If width is more than 943px dropdowns are displayed on hover $(".menu > ul > li").click(function () { if ($(window).width() <= 943) { $(this).children("ul").fadeToggle(150); } }); //If width is less or equal to 943px dropdowns are displayed on click (thanks Aman Jain from stackoverflow) $(".menu-mobile").click(function (e) { $(".menu > ul").toggleClass('show-on-mobile'); e.preventDefault(); }); //when clicked on mobile-menu, normal menu is shown as a list, classic rwd menu story (thanks mwl from stackoverflow) });
import $ from 'jquery' import { defer } from 'underscore' import Plugin from 'extplug/Plugin' import chatFacade from 'plug/facades/chatFacade' import Events from 'plug/core/Events' import { before } from 'meld' const UP = 38 const DOWN = 40 const HISTORY_MAX = 50 export default Plugin.extend({ name: 'Chat History', description: 'Adds shell-style chat history. ' + 'Use up+down keys to scroll through your previous messages.', init(id, ext) { this._super(id, ext) this.onKeyDown = this.onKeyDown.bind(this) }, enable() { this._super() this.history = this.settings.get('history') || [] this.index = this.history.length this.current = '' this.$field = $('#chat-input-field').on('keydown', this.onKeyDown) this.advice = before(chatFacade, 'sendChat', (msg) => { this.history.push(msg) if (this.history.length > HISTORY_MAX) { this.history.shift() } // set it to a clone so Backbone triggers change events this.settings.set('history', this.history.slice()) this.index = this.history.length this.current = '' }) Events.on('chat:afterreceive', this.plugCubedCompat, this) }, disable() { this._super() this.$field.off('keydown', this.onKeyDown) this.advice.remove() Events.off('chat:afterreceive', this.plugCubedCompat) }, // clear plugCubed's chat history list if available, // to prevent collisions plugCubedCompat() { if (window.plugCubedUserData && window.plugCubedUserData[-1] && window.plugCubedUserData[-1].latestInputs) { window.plugCubedUserData[-1].latestInputs = [] } }, onKeyDown(e) { if (e.keyCode === UP) { if (this.index >= this.history.length) { this.current = this.$field.val() } if (this.index > 0) { defer(() => { this.$field.val(this.history[--this.index]) }) } } if (e.keyCode === DOWN) { if (this.index < this.history.length) { defer(() => { this.$field.val(this.history[++this.index] || this.current) }) } } } })
(function() { 'use strict' var gulp = require('gulp') var minify = require('gulp-minify') var Server = require('karma').Server gulp.task('build', function(){ return gulp.src('humanize.js') .pipe(gulp.dest('dist')) .pipe(minify( { ext: { min: '.min.js' } })) .pipe(gulp.dest('dist')) }) gulp.task('test', function(done){ new Server({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done).start(); }) gulp.task('default', ['test', 'build']) })();
import React from "react" import PropTypes from "prop-types" import styled from "react-emotion" import { Link } from "gatsby" import Img from "gatsby-image" import { HorizontalScrollerItem } from "../shared/horizontal-scroller" import StarIcon from "react-icons/lib/md/star" import ArrowDownwardIcon from "react-icons/lib/md/arrow-downward" import { rhythm, options } from "../../utils/typography" import presets, { colors } from "../../utils/presets" const MAX_DESCRIPTION_LENGTH = 100 const EcosystemFeaturedItemRoot = styled(HorizontalScrollerItem)` margin-right: ${rhythm(options.blockMarginBottom)}; ${presets.Tablet} { border-bottom: 1px solid ${colors.gray.superLight}; box-shadow: none; margin: 0; padding: 0; width: auto; } ` export const BlockLink = styled(Link)` background: #fff; border-radius: ${presets.radiusLg}px; box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1); display: flex; flex-direction: column; height: 100%; padding: ${rhythm(3 / 4)}; ${presets.Tablet} { border-radius: 0; box-shadow: none; transition: all ${presets.animation.speedDefault} ${presets.animation.curveDefault}; } ${presets.Desktop} { :hover { background: ${colors.ui.whisper}; } } ` const Header = styled(`header`)` align-items: flex-start; display: flex; justify-content: space-between; h3 { color: ${colors.gatsbyDark}; font-size: 1rem; margin: 0; } span { align-items: center; color: ${colors.lilac}; display: flex; font-size: 0.8125rem; font-family: ${options.systemFontFamily.join(`,`)}; padding-left: 5px; svg { fill: ${colors.gray.light}; height: 1.2em; margin-left: 2px; width: 1.2em; } } ` const Digest = styled(`div`)` display: flex; flex-grow: 1; font-family: ${options.systemFontFamily.join(`,`)}; justify-content: space-between; padding: ${rhythm(0.5)} 0 0; ` const Thumbnail = styled(`div`)` height: 64px; padding-right: ${rhythm(2 / 3)}; margin-top: ${rhythm(1 / 12)}; img { border: 1px solid ${colors.gray.superLight}; } ` const Description = styled(`p`)` color: ${colors.gray.lightCopy}; flex-grow: 1; font-size: 0.85rem; margin: 0; ` const EcosystemFeaturedItem = ({ item, className }) => { const { slug, name, description, stars, humanDownloadsLast30Days, thumbnail, } = item const cutTooLongDescription = str => { if (str.length > MAX_DESCRIPTION_LENGTH) { return `${str.substring(0, MAX_DESCRIPTION_LENGTH)}...` } return str } return ( <EcosystemFeaturedItemRoot className={className}> <BlockLink to={slug}> <Header> <h3>{name}</h3> {humanDownloadsLast30Days && ( <span> {humanDownloadsLast30Days} <ArrowDownwardIcon /> </span> )} {stars && ( <span> {stars} <StarIcon /> </span> )} </Header> <Digest> {thumbnail && ( <Thumbnail> <Img fixed={thumbnail} alt="" /> </Thumbnail> )} <Description>{cutTooLongDescription(description)}</Description> </Digest> </BlockLink> </EcosystemFeaturedItemRoot> ) } EcosystemFeaturedItem.propTypes = { item: PropTypes.object.isRequired, className: PropTypes.string, } export default EcosystemFeaturedItem
define("daemons.exec", ["api.v1.exec"], function (api) { "use strict"; return { name: 'exec', type: 'daemon', fullName: 'Execution Manager', immediateRun: true, runParams: {}, api: api, init: function (system) { function loadMissingPackage(name, success, fail) { exec('xpm install ' + name, { end: success, error: fail }); } function exec(command, caller, guiContainer) { command = command.trim().replace(/\s+/g, ' '); caller = caller ? api.completeCaller(caller) : api.getEmptyCaller(); var split = command.split(' '), program = split.shift(), params, frame, taskId; params = { id: null, // Will be added later, in system.runTask() method. args: api.extractArgs(split), // `cmd arg1 arg2` keys: api.extractKeys(split), // `cmd -k --key` vars: api.extractVars(split), // `cmd VAR=value` all: split.slice(), raw: command, frame: null // Will be defined below. }; if (guiContainer) { frame = system.createFrame(guiContainer); } else if (~params.keys.indexOf('--gui')) { frame = system.createFrame(null); } else { frame = null; } params.frame = frame; taskId = system.runTask(program, params, caller); if (taskId !== false) { frame && frame.hostTask(taskId); guiContainer && guiContainer.setAttribute('x-running', 'true'); } else { loadMissingPackage(program, function () { exec(command, caller, guiContainer); }, function () { caller.error('No such program.'); }); } } var defaultExec; return { start: function (params) { defaultExec = system.exec; system.exec = exec; }, stop: function (purge) { system.exec = defaultExec; defaultExec = null; } }; } }; });
'use strict'; function pages_controller () { this.about = function (req, res) { res.render('pages/about'); } } module.exports = pages_controller;
/** * @file videojs-contrib-media-sources.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalWindow = require('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _flashMediaSource = require('./flash-media-source'); var _flashMediaSource2 = _interopRequireDefault(_flashMediaSource); var _htmlMediaSource = require('./html-media-source'); var _htmlMediaSource2 = _interopRequireDefault(_htmlMediaSource); var _videoJs = require('video.js'); var _videoJs2 = _interopRequireDefault(_videoJs); var urlCount = 0; // ------------ // Media Source // ------------ var defaults = { // how to determine the MediaSource implementation to use. There // are three available modes: // - auto: use native MediaSources where available and Flash // everywhere else // - html5: always use native MediaSources // - flash: always use the Flash MediaSource polyfill mode: 'auto' }; // store references to the media sources so they can be connected // to a video element (a swf object) // TODO: can we store this somewhere local to this module? _videoJs2['default'].mediaSources = {}; /** * Provide a method for a swf object to notify JS that a * media source is now open. * * @param {String} msObjectURL string referencing the MSE Object URL * @param {String} swfId the swf id */ var open = function open(msObjectURL, swfId) { var mediaSource = _videoJs2['default'].mediaSources[msObjectURL]; if (mediaSource) { mediaSource.trigger({ type: 'sourceopen', swfId: swfId }); } else { throw new Error('Media Source not found (Video.js)'); } }; /** * Check to see if the native MediaSource object exists and supports * an MP4 container with both H.264 video and AAC-LC audio. * * @return {Boolean} if native media sources are supported */ var supportsNativeMediaSources = function supportsNativeMediaSources() { return !!_globalWindow2['default'].MediaSource && !!_globalWindow2['default'].MediaSource.isTypeSupported && _globalWindow2['default'].MediaSource.isTypeSupported('video/mp4;codecs="avc1.4d400d,mp4a.40.2"'); }; /** * An emulation of the MediaSource API so that we can support * native and non-native functionality such as flash and * video/mp2t videos. returns an instance of HtmlMediaSource or * FlashMediaSource depending on what is supported and what options * are passed in. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/MediaSource * @param {Object} options options to use during setup. */ var MediaSource = function MediaSource(options) { var settings = _videoJs2['default'].mergeOptions(defaults, options); this.MediaSource = { open: open, supportsNativeMediaSources: supportsNativeMediaSources }; // determine whether HTML MediaSources should be used if (settings.mode === 'html5' || settings.mode === 'auto' && supportsNativeMediaSources()) { return new _htmlMediaSource2['default'](); } else if (_videoJs2['default'].getTech('Flash')) { return new _flashMediaSource2['default'](); } throw new Error('Cannot use Flash or Html5 to create a MediaSource for this video'); }; exports.MediaSource = MediaSource; MediaSource.open = open; MediaSource.supportsNativeMediaSources = supportsNativeMediaSources; /** * A wrapper around the native URL for our MSE object * implementation, this object is exposed under videojs.URL * * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/URL */ var URL = { /** * A wrapper around the native createObjectURL for our objects. * This function maps a native or emulated mediaSource to a blob * url so that it can be loaded into video.js * * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL * @param {MediaSource} object the object to create a blob url to */ createObjectURL: function createObjectURL(object) { var objectUrlPrefix = 'blob:vjs-media-source/'; var url = undefined; // use the native MediaSource to generate an object URL if (object instanceof _htmlMediaSource2['default']) { url = _globalWindow2['default'].URL.createObjectURL(object.nativeMediaSource_); object.url_ = url; return url; } // if the object isn't an emulated MediaSource, delegate to the // native implementation if (!(object instanceof _flashMediaSource2['default'])) { url = _globalWindow2['default'].URL.createObjectURL(object); object.url_ = url; return url; } // build a URL that can be used to map back to the emulated // MediaSource url = objectUrlPrefix + urlCount; urlCount++; // setup the mapping back to object _videoJs2['default'].mediaSources[url] = object; return url; } }; exports.URL = URL; _videoJs2['default'].MediaSource = MediaSource; _videoJs2['default'].URL = URL;
// >>> WARNING THIS PAGE WAS AUTO-GENERATED - DO NOT EDIT!!! <<< import MultipleChoiceWithOtherPage from '../multiple-choice.page' class ConstrainingInnovationGovernmentPage extends MultipleChoiceWithOtherPage { constructor() { super('constraining-innovation-government') } clickConstrainingInnovationGovernmentAnswerHigh() { browser.element('[id="constraining-innovation-government-answer-1"]').click() return this } clickConstrainingInnovationGovernmentAnswerMedium() { browser.element('[id="constraining-innovation-government-answer-2"]').click() return this } clickConstrainingInnovationGovernmentAnswerLow() { browser.element('[id="constraining-innovation-government-answer-3"]').click() return this } clickConstrainingInnovationGovernmentAnswerNotImportant() { browser.element('[id="constraining-innovation-government-answer-4"]').click() return this } } export default new ConstrainingInnovationGovernmentPage()
var fs = require('fs'); var mkdirp = require('mkdirp').sync; var removeDir = require('rimraf').sync; var Resurrect = require('../lib/resurrect'); var compare = require('fast-json-patch').compare; var path = require('path'); var $ = require('cheerio'); var Matter = require('../../build/matter-dev.js'); Matter.Example = require('../../demo/js/Examples.js'); Matter.Demo = require('../../demo/js/Demo.js'); var demo, frames = 10, refsPath = 'test/node/refs', diffsPath = 'test/node/diffs'; var update = arg('--update'), updateAll = typeof arg('--updateAll') !== 'undefined', diff = arg('--diff'); var resurrect = new Resurrect({ cleanup: true, revive: false }), created = [], changed = []; var test = function() { var demos = getDemoNames(); removeDir(diffsPath); if (diff) { mkdirp(diffsPath); } for (var i = 0; i < demos.length; i += 1) { demo = demos[i]; var hasChanged = false, hasCreated = false, forceUpdate = update === demo || updateAll, worldStartPath = refsPath + '/' + demo + '/' + demo + '-0.json', worldEndPath = refsPath + '/' + demo + '/' + demo + '-' + frames + '.json', worldStartDiffPath = diffsPath + '/' + demo + '/' + demo + '-0.json', worldEndDiffPath = diffsPath + '/' + demo + '/' + demo + '-' + frames + '.json'; var _demo = Matter.Demo.create(), engine = Matter.Example.engine(_demo), runner = Matter.Runner.create(); _demo.engine = engine; _demo.engine.render = {}; _demo.engine.render.options = {}; _demo.runner = runner; _demo.render = { options: {} }; if (!(demo in Matter.Example)) { throw '\'' + demo + '\' is not defined in Matter.Example'; } Matter.Demo.reset(_demo); Matter.Example[demo](_demo); var worldStart = JSON.parse(resurrect.stringify(engine.world, precisionLimiter)); for (var j = 0; j <= frames; j += 1) { Matter.Runner.tick(runner, engine, j * runner.delta); } var worldEnd = JSON.parse(resurrect.stringify(engine.world, precisionLimiter)); if (fs.existsSync(worldStartPath)) { var worldStartRef = JSON.parse(fs.readFileSync(worldStartPath)); var worldStartDiff = compare(worldStartRef, worldStart); if (worldStartDiff.length !== 0) { if (diff) { writeFile(worldStartDiffPath, JSON.stringify(worldStartDiff, precisionLimiter, 2)); } if (forceUpdate) { hasCreated = true; writeFile(worldStartPath, JSON.stringify(worldStart, precisionLimiter, 2)); } else { hasChanged = true; } } } else { hasCreated = true; writeFile(worldStartPath, JSON.stringify(worldStart, precisionLimiter, 2)); } if (fs.existsSync(worldEndPath)) { var worldEndRef = JSON.parse(fs.readFileSync(worldEndPath)); var worldEndDiff = compare(worldEndRef, worldEnd); if (worldEndDiff.length !== 0) { if (diff) { writeFile(worldEndDiffPath, JSON.stringify(worldEndDiff, precisionLimiter, 2)); } if (forceUpdate) { hasCreated = true; writeFile(worldEndPath, JSON.stringify(worldEnd, precisionLimiter, 2)); } else { hasChanged = true; } } } else { hasCreated = true; writeFile(worldEndPath, JSON.stringify(worldEnd, precisionLimiter, 2)); } if (hasChanged) { changed.push("'" + demo + "'"); process.stdout.write('x'); } else if (hasCreated) { created.push("'" + demo + "'"); process.stdout.write('+'); } else { process.stdout.write('.'); } } if (created.length > 0) { console.log('\nupdated', created.join(', ')); } var isOk = changed.length === 0 ? 1 : 0; console.log(''); if (isOk) { console.log('ok'); } else { console.log('\nchanges detected on:'); console.log(changed.join(', ')); console.log('\nreview, then --update [name] or --updateAll'); console.log('use --diff for diff log'); } setTimeout(function() { process.exit(!isOk); }, 100); }; var precisionLimiter = function(key, value) { if (typeof value === 'number') { return parseFloat(value.toFixed(5)); } return value; }; function arg(name) { var index = process.argv.indexOf(name); if (index >= 0) { return process.argv[index + 1] || true; } return undefined; } var getDemoNames = function() { var demos = [], skip = [ 'terrain', 'svg', 'concave', 'slingshot', 'views', 'raycasting', 'events', 'collisionFiltering', 'sleeping', 'attractors' ]; $('#demo-select option', fs.readFileSync('demo/index.html').toString()) .each(function() { var name = $(this).val(); if (skip.indexOf(name) === -1) { demos.push(name); } }); return demos; }; var writeFile = function(filePath, string) { mkdirp(path.dirname(filePath)); fs.writeFileSync(filePath, string); }; test();
var CMDC = { sourceLinkRoot: '//10.20.240.179:8000/NJS_PRS/src/', //sourceLinkRoot: '//10.20.240.179:8000/NJS_PRS/output/', dc: {}, playAgain : false, bhObj : {}, timeout : 1000, eventOff : false, isInclude : function (name) { var js = /js$/i.test(name); var es = document.getElementsByTagName(js ? 'script' : 'link'); for (var i = 0; i < es.length; i++) if (es[i][js ? 'src' : 'href'].indexOf(name) !== -1)return true; return false; }, loadSource : function() { if(CMDC.isInclude('cmdcg.js')) return var oHead = document.getElementsByTagName('HEAD').item(0), pfScript = document.createElement("script"), mScript = document.createElement("script"), mgScript = document.createElement("script"), mdScript = document.createElement("script"), mainScript = document.createElement("script"), alertScript = document.createElement("script"), bhScript = document.createElement("script"), alertCss = document.createElement("link"), tipScript = document.createElement("script"), tipCss = document.createElement("link"), sourceLinkRoot = CMDC.sourceLinkRoot; pfScript.src = sourceLinkRoot + "js/polyfill.js"; mScript.src = sourceLinkRoot + "js/matter-dev.js"; mgScript.src = sourceLinkRoot + "js/matter-tools.gui.js"; mdScript.src = sourceLinkRoot + "js/matter-tools.demo.js"; bhScript.src = sourceLinkRoot + "js/cmdcbh.js"; mainScript.src = sourceLinkRoot + "js/cmdcg.js"; alertScript.src = sourceLinkRoot + "js/simpleAlert.js"; alertCss.href = sourceLinkRoot + "css/simpleAlert.css"; alertCss.rel = 'stylesheet'; alertCss.type = 'text/css'; tipScript.src = sourceLinkRoot + "js/tipso.min.js"; tipCss.href = sourceLinkRoot + "css/tipso.min.css"; tipCss.rel = 'stylesheet'; tipCss.type = 'text/css'; oHead.appendChild(alertCss); oHead.appendChild(tipCss); oHead.appendChild(pfScript); oHead.appendChild(mScript); setTimeout(function () { // oHead.appendChild(mgScript); oHead.appendChild(mdScript); oHead.appendChild(mainScript); oHead.appendChild(alertScript); oHead.appendChild(tipScript); oHead.appendChild(bhScript); }, 500) }, removejscssfile : function(filename, filetype){ var targetelement=(filetype==="js")? "script" : (filetype==="css")? "link" : "none"; var targetattr=(filetype==="js")? "src" : (filetype==="css")? "href" : "none"; var allsuspects=document.getElementsByTagName(targetelement); for (var i=allsuspects.length; i>=0; i--){ if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) && allsuspects[i].getAttribute(targetattr).indexOf(filename)!==-1){ allsuspects[i].parentNode.removeChild(allsuspects[i]); } } }, clearSource : function(){ var removejscssfile = CMDC.removejscssfile removejscssfile(sourceLinkRoot+"js/simpleAlert.js", 'js') removejscssfile(sourceLinkRoot+"js/tipso.min.js", 'js') removejscssfile(sourceLinkRoot+"js/matter-dev.js", 'js') removejscssfile(sourceLinkRoot+"js/polyfill.js", 'js') removejscssfile(sourceLinkRoot+"js/matter-tools.demo.js", 'js') removejscssfile(sourceLinkRoot+"js/cmdcg.js", 'js') removejscssfile(sourceLinkRoot+"js/cmdcbh.js", 'js') removejscssfile(sourceLinkRoot+"css/simpleAlert.css", 'css') removejscssfile(sourceLinkRoot+"css/tipso.min.css", 'css') } }; (function() { //设置屏幕宽度的最小支持 if(document.documentElement.clientWidth < 1263) return CMDC.loadSource(); var play = function() { var obj = { toolbar: { title: '天猫双11主场', url: '', }, tools: { inspector: false, gui: false }, startExample: 'cmdcg', examples: [ { name: 'DOLL_CATCHING', id: 'cmdcg', init: DC.do, sourceLink: CMDC.sourceLinkRoot + 'js/cmdcg.js' }, ] } var dc = CMDC.dc; dc = MatterTools.Demo.create(obj); document.body.appendChild(dc.dom.root); MatterTools.Demo.start(dc); } setTimeout(function(){ // bhObj = doblackhole(); // var st = setTimeout(function(){ // bhObj.dispose(); // play(); // }, timeout* 6); // bhObj.init(function(res){ // if(res === 1){ // clearTimeout(st); // play(); // } // }) play(); // bhObj.init() // setTimeout(function(){ // play(); // }, timeout) }, CMDC.timeout); })();
// // SmoothScroll for websites v1.4.6 (Balazs Galambosi) // http://www.smoothscroll.net/ // // Licensed under the terms of the MIT license. // // You may use it in your theme if you credit me. // It is also free to use on any individual website. // // Exception: // The only restriction is to not publish any // extension for browsers or native application // without getting a written permission first. // (function () { console.log('this is a test'); // Scroll Variables (tweakable) var defaultOptions = { // Scrolling Core frameRate : 150, // [Hz] animationTime : 400, // [ms] stepSize : 100, // [px] // Pulse (less tweakable) // ratio of "tail" to "acceleration" pulseAlgorithm : true, pulseScale : 4, pulseNormalize : 1, // Acceleration accelerationDelta : 50, // 50 accelerationMax : 3, // 3 // Keyboard Settings keyboardSupport : true, // option arrowScroll : 50, // [px] // Other fixedBackground : true, excluded : '' }; var options = defaultOptions; // Other Variables var isExcluded = false; var isFrame = false; var direction = { x: 0, y: 0 }; var initDone = false; var root = document.documentElement; var activeElement; var observer; var refreshSize; var deltaBuffer = []; var isMac = /^Mac/.test(navigator.platform); var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; var arrowKeys = { 37: 1, 38: 1, 39: 1, 40: 1 }; /*********************************************** * INITIALIZE ***********************************************/ /** * Tests if smooth scrolling is allowed. Shuts down everything if not. */ function initTest() { if (options.keyboardSupport) { addEvent('keydown', keydown); } } /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (initDone || !document.body) return; initDone = true; var body = document.body; var html = document.documentElement; var windowHeight = window.innerHeight; var scrollHeight = body.scrollHeight; // check compat mode for root element root = (document.compatMode.indexOf('CSS') >= 0) ? html : body; activeElement = body; initTest(); // Checks if this script is running in a frame if (top != self) { isFrame = true; } /** * Safari 10 fixed it, Chrome fixed it in v45: * This fixes a bug where the areas left and right to * the content does not trigger the onmousewheel event * on some pages. e.g.: html, body { height: 100% } */ else if (isOldSafari && scrollHeight > windowHeight && (body.offsetHeight <= windowHeight || html.offsetHeight <= windowHeight)) { var fullPageElem = document.createElement('div'); fullPageElem.style.cssText = 'position:absolute; z-index:-10000; ' + 'top:0; left:0; right:0; height:' + root.scrollHeight + 'px'; document.body.appendChild(fullPageElem); // DOM changed (throttled) to fix height var pendingRefresh; refreshSize = function () { if (pendingRefresh) return; // could also be: clearTimeout(pendingRefresh); pendingRefresh = setTimeout(function () { if (isExcluded) return; // could be running after cleanup fullPageElem.style.height = '0'; fullPageElem.style.height = root.scrollHeight + 'px'; pendingRefresh = null; }, 500); // act rarely to stay fast }; setTimeout(refreshSize, 10); addEvent('resize', refreshSize); // TODO: attributeFilter? var config = { attributes: true, childList: true, characterData: false // subtree: true }; observer = new MutationObserver(refreshSize); observer.observe(body, config); if (root.offsetHeight <= windowHeight) { var clearfix = document.createElement('div'); clearfix.style.clear = 'both'; body.appendChild(clearfix); } } // disable fixed background if (!options.fixedBackground && !isExcluded) { body.style.backgroundAttachment = 'scroll'; html.style.backgroundAttachment = 'scroll'; } } /** * Removes event listeners and other traces left on the page. */ function cleanup() { observer && observer.disconnect(); removeEvent(wheelEvent, wheel); removeEvent('mousedown', mousedown); removeEvent('keydown', keydown); removeEvent('resize', refreshSize); removeEvent('load', init); } /************************************************ * SCROLLING ************************************************/ var que = []; var pending = false; var lastScroll = Date.now(); /** * Pushes scroll actions to the scrolling queue. */ function scrollArray(elem, left, top) { directionCheck(left, top); if (options.accelerationMax != 1) { var now = Date.now(); var elapsed = now - lastScroll; if (elapsed < options.accelerationDelta) { var factor = (1 + (50 / elapsed)) / 2; if (factor > 1) { factor = Math.min(factor, options.accelerationMax); left *= factor; top *= factor; } } lastScroll = Date.now(); } // push a scroll command que.push({ x: left, y: top, lastX: (left < 0) ? 0.99 : -0.99, lastY: (top < 0) ? 0.99 : -0.99, start: Date.now() }); // don't act if there's a pending queue if (pending) { return; } var scrollWindow = (elem === document.body); var step = function (time) { var now = Date.now(); var scrollX = 0; var scrollY = 0; for (var i = 0; i < que.length; i++) { var item = que[i]; var elapsed = now - item.start; var finished = (elapsed >= options.animationTime); // scroll position: [0, 1] var position = (finished) ? 1 : elapsed / options.animationTime; // easing [optional] if (options.pulseAlgorithm) { position = pulse(position); } // only need the difference var x = (item.x * position - item.lastX) >> 0; var y = (item.y * position - item.lastY) >> 0; // add this to the total scrolling scrollX += x; scrollY += y; // update last values item.lastX += x; item.lastY += y; // delete and step back if it's over if (finished) { que.splice(i, 1); i--; } } // scroll left and top if (scrollWindow) { window.scrollBy(scrollX, scrollY); } else { if (scrollX) elem.scrollLeft += scrollX; if (scrollY) elem.scrollTop += scrollY; } // clean up if there's nothing left to do if (!left && !top) { que = []; } if (que.length) { requestFrame(step, elem, (1000 / options.frameRate + 1)); } else { pending = false; } }; // start a new queue of actions requestFrame(step, elem, 0); pending = true; } /*********************************************** * EVENTS ***********************************************/ /** * Mouse wheel handler. * @param {Object} event */ function wheel(event) { if (!initDone) { init(); } var target = event.target; // leave early if default action is prevented // or it's a zooming event with CTRL if (event.defaultPrevented || event.ctrlKey) { return true; } // leave embedded content alone (flash & pdf) if (isNodeName(activeElement, 'embed') || (isNodeName(target, 'embed') && /\.pdf/i.test(target.src)) || isNodeName(activeElement, 'object') || target.shadowRoot) { return true; } var deltaX = -event.wheelDeltaX || event.deltaX || 0; var deltaY = -event.wheelDeltaY || event.deltaY || 0; if (isMac) { if (event.wheelDeltaX && isDivisible(event.wheelDeltaX, 120)) { deltaX = -120 * (event.wheelDeltaX / Math.abs(event.wheelDeltaX)); } if (event.wheelDeltaY && isDivisible(event.wheelDeltaY, 120)) { deltaY = -120 * (event.wheelDeltaY / Math.abs(event.wheelDeltaY)); } } // use wheelDelta if deltaX/Y is not available if (!deltaX && !deltaY) { deltaY = -event.wheelDelta || 0; } // line based scrolling (Firefox mostly) if (event.deltaMode === 1) { deltaX *= 40; deltaY *= 40; } var overflowing = overflowingAncestor(target); // nothing to do if there's no element that's scrollable if (!overflowing) { // except Chrome iframes seem to eat wheel events, which we need to // propagate up, if the iframe has nothing overflowing to scroll if (isFrame && isChrome) { // change target to iframe element itself for the parent frame Object.defineProperty(event, "target", {value: window.frameElement}); return parent.wheel(event); } return true; } // check if it's a touchpad scroll that should be ignored if (isTouchpad(deltaY)) { return true; } // scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes if (Math.abs(deltaX) > 1.2) { deltaX *= options.stepSize / 120; } if (Math.abs(deltaY) > 1.2) { deltaY *= options.stepSize / 120; } scrollArray(overflowing, deltaX, deltaY); event.preventDefault(); scheduleClearCache(); } /** * Keydown event handler. * @param {Object} event */ function keydown(event) { var target = event.target; var modifier = event.ctrlKey || event.altKey || event.metaKey || (event.shiftKey && event.keyCode !== key.spacebar); // our own tracked active element could've been removed from the DOM if (!document.body.contains(activeElement)) { activeElement = document.activeElement; } // do nothing if user is editing text // or using a modifier key (except shift) // or in a dropdown // or inside interactive elements var inputNodeNames = /^(textarea|select|embed|object)$/i; var buttonTypes = /^(button|submit|radio|checkbox|file|color|image)$/i; if ( event.defaultPrevented || inputNodeNames.test(target.nodeName) || isNodeName(target, 'input') && !buttonTypes.test(target.type) || isNodeName(activeElement, 'video') || isInsideYoutubeVideo(event) || target.isContentEditable || modifier ) { return true; } // [spacebar] should trigger button press, leave it alone if ((isNodeName(target, 'button') || isNodeName(target, 'input') && buttonTypes.test(target.type)) && event.keyCode === key.spacebar) { return true; } // [arrwow keys] on radio buttons should be left alone if (isNodeName(target, 'input') && target.type == 'radio' && arrowKeys[event.keyCode]) { return true; } var shift, x = 0, y = 0; var overflowing = overflowingAncestor(activeElement); if (!overflowing) { // Chrome iframes seem to eat key events, which we need to // propagate up, if the iframe has nothing overflowing to scroll return (isFrame && isChrome) ? parent.keydown(event) : true; } var clientHeight = overflowing.clientHeight; if (overflowing == document.body) { clientHeight = window.innerHeight; } switch (event.keyCode) { case key.up: y = -options.arrowScroll; break; case key.down: y = options.arrowScroll; break; case key.spacebar: // (+ shift) shift = event.shiftKey ? 1 : -1; y = -shift * clientHeight * 0.9; break; case key.pageup: y = -clientHeight * 0.9; break; case key.pagedown: y = clientHeight * 0.9; break; case key.home: y = -overflowing.scrollTop; break; case key.end: var scroll = overflowing.scrollHeight - overflowing.scrollTop; var scrollRemaining = scroll - clientHeight; y = (scrollRemaining > 0) ? scrollRemaining + 10 : 0; break; case key.left: x = -options.arrowScroll; break; case key.right: x = options.arrowScroll; break; default: return true; // a key we don't care about } scrollArray(overflowing, x, y); event.preventDefault(); scheduleClearCache(); } /** * Mousedown event only for updating activeElement */ function mousedown(event) { activeElement = event.target; } /*********************************************** * OVERFLOW ***********************************************/ var uniqueID = (function () { var i = 0; return function (el) { return el.uniqueID || (el.uniqueID = i++); }; })(); var cache = {}; // cleared out after a scrolling session var clearCacheTimer; //setInterval(function () { cache = {}; }, 10 * 1000); function scheduleClearCache() { clearTimeout(clearCacheTimer); clearCacheTimer = setInterval(function () { cache = {}; }, 1*1000); } function setCache(elems, overflowing) { for (var i = elems.length; i--;) cache[uniqueID(elems[i])] = overflowing; return overflowing; } // (body) (root) // | hidden | visible | scroll | auto | // hidden | no | no | YES | YES | // visible | no | YES | YES | YES | // scroll | no | YES | YES | YES | // auto | no | YES | YES | YES | function overflowingAncestor(el) { var elems = []; var body = document.body; var rootScrollHeight = root.scrollHeight; do { var cached = cache[uniqueID(el)]; if (cached) { return setCache(elems, cached); } elems.push(el); if (rootScrollHeight === el.scrollHeight) { var topOverflowsNotHidden = overflowNotHidden(root) && overflowNotHidden(body); var isOverflowCSS = topOverflowsNotHidden || overflowAutoOrScroll(root); if (isFrame && isContentOverflowing(root) || !isFrame && isOverflowCSS) { return setCache(elems, getScrollRoot()); } } else if (isContentOverflowing(el) && overflowAutoOrScroll(el)) { return setCache(elems, el); } } while (el = el.parentElement); } function isContentOverflowing(el) { return (el.clientHeight + 10 < el.scrollHeight); } // typically for <body> and <html> function overflowNotHidden(el) { var overflow = getComputedStyle(el, '').getPropertyValue('overflow-y'); return (overflow !== 'hidden'); } // for all other elements function overflowAutoOrScroll(el) { var overflow = getComputedStyle(el, '').getPropertyValue('overflow-y'); return (overflow === 'scroll' || overflow === 'auto'); } /*********************************************** * HELPERS ***********************************************/ function addEvent(type, fn) { window.addEventListener(type, fn, false); } function removeEvent(type, fn) { window.removeEventListener(type, fn, false); } function isNodeName(el, tag) { return (el.nodeName||'').toLowerCase() === tag.toLowerCase(); } function directionCheck(x, y) { x = (x > 0) ? 1 : -1; y = (y > 0) ? 1 : -1; if (direction.x !== x || direction.y !== y) { direction.x = x; direction.y = y; que = []; lastScroll = 0; } } var deltaBufferTimer; if (window.localStorage && localStorage.SS_deltaBuffer) { try { // #46 Safari throws in private browsing for localStorage deltaBuffer = localStorage.SS_deltaBuffer.split(','); } catch (e) { } } function isTouchpad(deltaY) { if (!deltaY) return; if (!deltaBuffer.length) { deltaBuffer = [deltaY, deltaY, deltaY]; } deltaY = Math.abs(deltaY); deltaBuffer.push(deltaY); deltaBuffer.shift(); clearTimeout(deltaBufferTimer); deltaBufferTimer = setTimeout(function () { try { // #46 Safari throws in private browsing for localStorage localStorage.SS_deltaBuffer = deltaBuffer.join(','); } catch (e) { } }, 1000); return !allDeltasDivisableBy(120) && !allDeltasDivisableBy(100); } function isDivisible(n, divisor) { return (Math.floor(n / divisor) == n / divisor); } function allDeltasDivisableBy(divisor) { return (isDivisible(deltaBuffer[0], divisor) && isDivisible(deltaBuffer[1], divisor) && isDivisible(deltaBuffer[2], divisor)); } function isInsideYoutubeVideo(event) { var elem = event.target; var isControl = false; if (document.URL.indexOf ('www.youtube.com/watch') != -1) { do { isControl = (elem.classList && elem.classList.contains('html5-video-controls')); if (isControl) break; } while (elem = elem.parentNode); } return isControl; } var requestFrame = (function () { return (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback, element, delay) { window.setTimeout(callback, delay || (1000/60)); }); })(); var MutationObserver = (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver); var getScrollRoot = (function() { var SCROLL_ROOT; return function() { if (!SCROLL_ROOT) { var dummy = document.createElement('div'); dummy.style.cssText = 'height:10000px;width:1px;'; document.body.appendChild(dummy); var bodyScrollTop = document.body.scrollTop; var docElScrollTop = document.documentElement.scrollTop; window.scrollBy(0, 3); if (document.body.scrollTop != bodyScrollTop) (SCROLL_ROOT = document.body); else (SCROLL_ROOT = document.documentElement); window.scrollBy(0, -3); document.body.removeChild(dummy); } return SCROLL_ROOT; }; })(); /*********************************************** * PULSE (by Michael Herf) ***********************************************/ /** * Viscous fluid with a pulse for part and decay for the rest. * - Applies a fixed force over an interval (a damped acceleration), and * - Lets the exponential bleed away the velocity over a longer interval * - Michael Herf, http://stereopsis.com/stopping/ */ function pulse_(x) { var val, start, expx; // test x = x * options.pulseScale; if (x < 1) { // acceleartion val = x - (1 - Math.exp(-x)); } else { // tail // the previous animation ended here: start = Math.exp(-1); // simple viscous drag x -= 1; expx = 1 - Math.exp(-x); val = start + (expx * (1 - start)); } return val * options.pulseNormalize; } function pulse(x) { if (x >= 1) return 1; if (x <= 0) return 0; if (options.pulseNormalize == 1) { options.pulseNormalize /= pulse_(1); } return pulse_(x); } /*********************************************** * FIRST RUN ***********************************************/ var userAgent = window.navigator.userAgent; var isEdge = /Edge/.test(userAgent); // thank you MS var isChrome = /chrome/i.test(userAgent) && !isEdge; var isSafari = /safari/i.test(userAgent) && !isEdge; var isMobile = /mobile/i.test(userAgent); var isIEWin7 = /Windows NT 6.1/i.test(userAgent) && /rv:11/i.test(userAgent); var isOldSafari = isSafari && (/Version\/8/i.test(userAgent) || /Version\/9/i.test(userAgent)); var isEnabledForBrowser = (isChrome || isSafari || isIEWin7) && !isMobile; var wheelEvent; if ('onwheel' in document.createElement('div')) wheelEvent = 'wheel'; else if ('onmousewheel' in document.createElement('div')) wheelEvent = 'mousewheel'; if (wheelEvent && isEnabledForBrowser) { addEvent(wheelEvent, wheel); addEvent('mousedown', mousedown); addEvent('load', init); } /*********************************************** * PUBLIC INTERFACE ***********************************************/ function SmoothScroll(optionsToSet) { for (var key in optionsToSet) if (defaultOptions.hasOwnProperty(key)) options[key] = optionsToSet[key]; } SmoothScroll.destroy = cleanup; if (window.SmoothScrollOptions) // async API SmoothScroll(window.SmoothScrollOptions); if (typeof define === 'function' && define.amd) define(function() { return SmoothScroll; }); else if ('object' == typeof exports) module.exports = SmoothScroll; else window.SmoothScroll = SmoothScroll; })();
{ HELLO_WORLD : "Hallo Welt!", OK : "Ok" }
import Ember from 'ember'; export default Ember.Route.extend({ model() { return Ember.RSVP.hash({ emailItems: Ember.RSVP.Promise.cast( [{ name: 'Send me an email', description: 'This Action will send you an HTML based email. Images and links are supported.', }] ), headerItem: {title: 'Choose action', step:4} }); } });
import _ from 'lodash'; const { concatToJoiObject, mergeJoiObject, } = requireF('core/services/CommonServices'); const ValidatorConstants = requireF('core/services/verifier/ValidatorConstants'); const PKValidator = requireF('core/services/verifier/request/PKValidator'); const WhereValidator = requireF('core/services/verifier/request/WhereValidator'); const IncludeValidator = requireF('core/services/verifier/request/IncludeValidator'); const OrderValidator = requireF('core/services/verifier/request/OrderValidator'); const LimitValidator = requireF('core/services/verifier/request/LimitValidator'); const OffsetValidator = requireF('core/services/verifier/request/OffsetValidator'); const PayloadValidator = requireF('core/services/verifier/request/PayloadValidator'); const TokenValidator = requireF('core/services/verifier/request/TokenValidator'); const validatorClasses = { pk: { class: PKValidator, source: 'params', }, pk2: { class: PKValidator, source: 'params', }, where: { class: WhereValidator, source: 'query', }, include: { class: IncludeValidator, source: 'query', }, order: { class: OrderValidator, source: 'query', }, limit: { class: LimitValidator, source: 'query', }, offset: { class: OffsetValidator, source: 'query', }, payload: { class: PayloadValidator, source: 'payload', }, token: { class: TokenValidator, source: 'query', }, }; const ModelResolver = requireF('core/services/resolvers/ModelResolver'); export default class ValidatorGenerator { constructor() { const modelResolver = new ModelResolver(); this.models = modelResolver.getAllModels(); } build(method) { const { APPLICABLE_METHODS, } = ValidatorConstants; const validators = {}; const methodName = method.substring(method.indexOf('.') + 1); let targetModelName = method.replace(methodName, ''); targetModelName = targetModelName.substring(0, targetModelName.length - 1); _.forEach(APPLICABLE_METHODS[methodName], (sourceMethod) => { if (_.has(validatorClasses, sourceMethod)) { const classConfig = validatorClasses[sourceMethod]; const classIntance = new classConfig['class'](this.models, this.models[targetModelName], sourceMethod); // eslint-disable-line const validations = concatToJoiObject( classIntance.build(), _.get(validators, classConfig.source), ); _.set(validators, classConfig.source, validations); } }); const tokenValidator = new validatorClasses['token']['class'](); // eslint-disable-line const tokenValidation = concatToJoiObject( tokenValidator.build(), _.get(validators, validatorClasses.token.source), ); _.set(validators, validatorClasses.token.source, tokenValidation); return validators; } buildMultiple(methodNames) { const self = this; const { VALIDATABLE_REQUEST, } = ValidatorConstants; let allValidators = {}; _.forEach(_.castArray(methodNames), (methodName) => { const validators = self.build(methodName); allValidators = mergeJoiObject(allValidators, validators, VALIDATABLE_REQUEST); }); return allValidators; } }
/** * @jsx React.DOM */ //send component snowUI.wallet.send = React.createClass({displayName: 'send', getInitialState: function() { var _this = this return { requesting:false, mounted:false, ready:this.props.ready, confirm:false, unlock:false, receipt: false, transaction: false, error: false, persist: {} }; }, componentWillReceiveProps: function (nextProps) { var _this = this if(snowUI.debug) snowLog.log('send will receive props',this.state.unlock,nextProps.config.unlocked) //this.setState({ready:nextProps.ready}) if(this.state.unlock === true && nextProps.config.unlocked === true) { if(snowUI.debug) snowLog.log('send set to confirm') this.setState({unlock:false,confirm:true}); } else { if(this.props.config.wallet !== nextProps.config.wallet)this.getData(nextProps,function(resp){_this.setState({accounts:resp.accounts,data:resp.data,snowmoney:resp.snowmoney,mounted:true,ready:nextProps.ready}) }) } }, componentDidUpdate: function () { var _this = this if(snowUI.debug) snowLog.log('send did update',this.props) snowUI.watchLoader(); $('[rel=popover]').popover(); $('.bstooltip').tooltip() }, componentDidMount: function() { }, killTooltip: function() { $('.snow-send #changeamountspan').tooltip('destroy'); $('.snow-send #sendcoinamount').tooltip('destroy'); $('.snow-send #convamountspan').tooltip('destroy'); }, componentWillMount: function() { var _this = this if(snowUI.debug) snowLog.log('send did mount',this.props) this.getData(this.props,function(resp){ _this.setState({data:resp.data,snowmoney:resp.snowmoney,accounts:resp.accounts,mounted:true}) }) this.killTooltip(); $('.snow-send #convamount').html(' ') $('[rel=qrpopover]').popover(); }, componentWillUpdate: function() { this.killTooltip(); $('.snow-send #convamount').html(' ') }, componentWillUnMount: function() { this.setState({mounted:false,data:false,ready:false}) }, getData: function (props,cb) { if(snowUI.debug) snowLog.log('send data',props) var url = "/api/snowcoins/local/wallet", data = { wallet:props.config.wallet,moon:props.config.moon}, _this = this; snowUI.ajax.GET(url,data,function(resp) { if(snowUI.debug) snowLog.log(resp) if(resp.success === true) { cb(resp) } else { snowUI.flash('error',resp.error,3500) _this.props.setWalletState({connectError:true}) } }) return false }, addressBook: function(e) { var url= "/api/snowcoins/local/contacts", data= { wallet:this.props.config.wally.key}, _this = this; snowUI.ajax.GET(url,data,function(resp) { if(snowUI.debug) snowLog.log(resp) if(resp.success === true) { _this.setState({addressBookHtml:resp.html}); snowUI.methods.modals.addressBook.open(); } else { snowUI.flash('error',resp.error,3500) } }) return false }, saveAddressForm: function(e) { if(snowUI.debug) snowLog.log('change save address'); var fields = $('#sendcoinshowname'); if(fields.css('display') === 'none') { fields.toggle(400); } else { fields.toggle(false); } }, watchAmount: function(e) { var currentwally = this.props.config.wally; var snowmoney = this.state.snowmoney; var getfrom=$('.snow-send #snowchangefrom').attr('data-snowticker'); var enteredamount=parseFloat($('.snow-send #sendcoinamount').val()); if(isNaN(enteredamount))enteredamount=0; var stamp=$('.snow-send #snowchangefrom').attr('data-snowstamp'); if(getfrom===currentwally.cointicker) { stamp='$ '; var to=currentwally.currency,from=getfrom; } else { stamp=' '+currentwally.coinstamp; var from=getfrom,to=currentwally.cointicker; } //if(snowUI.debug) snowLog.log('keyup',from,to,snowmoney[from][to]); if(snowmoney[from][to] && snowmoney[from][to].price) { showvalue=snowmoney[from][to].price * enteredamount; if(to==='usd' || to==='eur'){ $('.snow-send #sendcointrueamount').val(enteredamount.toFixed(8).replace(/\.?0+$/, "")); showvalue=parseFloat(showvalue.toFixed(2)); } else { $('.snow-send #sendcointrueamount').val(showvalue.toFixed(8).replace(/\.?0+$/, "")); showvalue=parseFloat(showvalue.toFixed(8)); } $('.snow-send #changeamountbefore').text(''); $('.snow-send #changeamountafter').text(''); if(to==='usd')$('.snow-send #changeamountbefore').text(stamp); else $('.snow-send #changeamountafter').text(' ' + stamp); $('.snow-send #convamount').text(parseFloat(snowmoney[from][to].price).toFixed(8).replace(/\.?0+$/, "")); $('.snow-send #changeamount').text(showvalue ); } else { $('.snow-send #sendcointrueamount').val(enteredamount.toFixed(8).replace(/\.?0+$/, "")); } $('.snow-send #convamountspan').tooltip('destroy'); $('.snow-send #convamountspan').tooltip({title:'1 ' + from + ' to ' + to + ' equals '}).tooltip('show'); var balspan = $('.snow-send .snow-balance-body').find('span').first(), availbal = parseFloat($('.snow-send #snow-balance-input').val()), minus = $('.snow-send #sendcointrueamount').val(), changebalance = availbal - parseFloat(minus); balspan.text(changebalance.formatMoney(8,',','.')); }, watchTicker: function(e) { var currentwally = this.props.config.wally; var snowmoney = this.state.snowmoney; var theLi = $(e.target).closest('li') var changeto=theLi.text(); var changestamp=theLi.attr('data-snowstamp'); var changeticker=theLi.attr('data-snowticker'); var currentticker=$('.snow-send #snowchangefrom').attr('data-snowticker'); var ddclass = 'bg-info'; if(changeticker===currentwally.cointicker) { $('.snow-send #sendcoinamount').addClass('active').next().next().removeClass('active'); $('.snow-send #changeamountspan').tooltip('destroy'); $('.snow-send #sendcoinamount').tooltip({title:'We will send this many ' + currentwally.cointicker}).tooltip('show'); } else { $('.snow-send #sendcoinamount').removeClass('active').next().next().addClass('active'); $('.snow-send #sendcoinamount').tooltip('destroy'); $('.snow-send #changeamountspan').tooltip({title:'We will send this many ' + currentwally.cointicker}).tooltip('show'); } if(changeticker!=currentticker) { $('.snow-send #snowchangefrom').attr('data-snowticker',changeticker); $('.snow-send #snowchangefrom').attr('data-snowstamp',changestamp); $('.snow-send #changestamp').children().first().text(changeto); $('.snow-send #sendcoinamount').focus(); if(changeticker==='usd' || changeticker==='eur')$('.snow-send #sendcoinamount').prop('step','0.01'); else if(changeticker==='ltc' || changeticker==='btc')$('.snow-send #sendcoinamount').prop('step','0.001'); else $('.snow-send #sendcoinamount').prop('step','1'); } }, walletForm: function(e) { e.preventDefault() var _this = this; var currentwally = this.props.config.wally; var next = true; var ticker = $('.snow-send .change-coin-stamp').attr('data-snowticker'); var amount = parseFloat($('.snow-send #sendcointrueamount').val()); var to = $('.snow-send #sendcointoaddress').val(); var bal = parseFloat($('.snow-send-body .snow-balance-body').text().replace(/,/g,'')); var from = $('.snow-send #sendcoinfromaccount').val(); if(snowUI.debug) snowLog.log('send',parseInt(amount)); if(amount<=0 || isNaN(amount) || amount===Infinity) { $(".snow-send #sendcoinamount").parent().addClass('has-error'); next=false; } if(to==='') { $(".snow-send #sendcointoaddress").parent().addClass('has-error'); next=false; } if(next===true) { var saveAs = $(".snow-send #sendcoinaddressname").val(), saveAddress = $(".snow-send #sendcoinsaveaddr").val(); if(snowUI.debug) snowLog.log("save address? ",saveAddress) if(saveAddress === 'save' && saveAs) { var url = "/api/snowcoins/local/contacts", data = { stop:1,wallet:currentwally.key,action:'add',name:saveAs,address:to}; snowUI.ajax.GET(url,data,function(resp) { if(snowUI.debug) snowLog.log(resp) if(resp.success === true) { snowUI.flash('success','Address saved as ' + saveAs,3500) } else { snowUI.flash('error',"Address saved previously",3500) } }); } var options = { amount: amount, ticker: ticker, to: to, balance: bal, from: from, saveAs: saveAs, memo: $(".snow-send #sendcoinmemo").val(), message: $(".snow-send #sendcointomessage").val() }; _this.setState({confirm:true,unlock:false,persist:options}); } }, sendConfirmed: function() { var _this = this, nowtime=new Date().getTime(), command=(this.state.persist.from==='_default')?'send':'sendfromaccount', url= "/api/snowcoins/local/gated", data = { checkauth:nowtime,account:this.state.persist.from,comment:this.state.persist.memo,commentto:this.state.persist.message,wallet: this.props.config.wally.key,command:command,amount:this.state.persist.amount,toaddress:this.state.persist.to}; if(_this.props.config.unlocked === false) { _this.setState({confirm:true,unlock:true}); snowUI.methods.modals.unlockWallet.open(); return false; } else { snowUI.ajax.GET(url,data,function(resp) { if(snowUI.debug) snowLog.log(resp) if(resp.success === true) { _this.setState({persist:{},confirm:false,receipt:true,transaction:resp.tx}); } else { _this.setState({confirm:false,error:resp.error,}); } }); return false; } }, cancelConfirm: function() { var _this = this; this.getData(this.props,function(resp){ _this.setState({ data:resp.data, snowmoney:resp.snowmoney, accounts:resp.accounts, mounted:true, persist:{}, confirm:false, receipt:false, transaction:false, error:false }); }); }, render: function() { var _this = this; if(this.state.receipt) { /* confirm sending coins */ return (React.DOM.div({id: "snow-send", className: "snow-send bs-example"}, React.DOM.div({style: {padding:'5px 20px'}}, React.DOM.div({className: "col-xs-12 "}, React.DOM.h4({className: "profile-form__heading"}, "Send Coin Transaction") ), React.DOM.div({dangerouslySetInnerHTML: {__html: _this.state.transaction}}), React.DOM.p(null), React.DOM.button({className: "btn btn-default ", onClick: _this.cancelConfirm}, "Return") ) )) } else if(this.state.confirm) { if(snowUI.debug) snowLog.log('wallet confirm send') var currentwally = this.props.config.wally; var html='<div><div class="adderror" style="dispaly:none;"></div> <span class="send-modal-amount">'+parseFloat(this.state.persist.amount).formatMoney(8)+'</span><span class="coinstamp">'+currentwally.coinstamp+'</span></div><div class="send-modal-text"> to address<p><strong>'+this.state.persist.to+'</strong></p>from account<p class="send-modal-account1"><strong>'+this.state.persist.from+'</strong></p><p><span class="snow-balance-span1" style="font-weight:bold">'+(this.state.persist.balance).formatMoney(8)+'</span> <span class="coinstamp">'+currentwally.coinstamp+' wallet balance after send</span><div id="3456756" style="display:none;">to='+this.state.persist.to+'<br />&account='+this.state.persist.from+'<br />&amount='+this.state.persist.amount+'<br />&checkauth={generate-on-submit}<br />&sendnow=yes</div></p></div>'; /* confirm sending coins */ return (React.DOM.div({id: "snow-send", className: "snow-send bs-example"}, React.DOM.div({style: {padding:'5px 20px'}}, React.DOM.div({className: "col-xs-12 "}, React.DOM.h4({className: "profile-form__heading"}, "Confirm Send Coins") ), React.DOM.div({dangerouslySetInnerHTML: {__html: html}}), React.DOM.button({onClick: _this.sendConfirmed, className: _this.props.config.unlocked ? "btn btn-warning" : "btn "}, _this.props.config.unlocked ? "Send Coins Now" : "Unlock Wallet"), React.DOM.span(null, "   "), React.DOM.button({className: "btn btn-default ", onClick: _this.cancelConfirm}, "Cancel") ) )) } else if(this.state.mounted) { var snowmoney = this.state.snowmoney; var wally = this.props.config.wally; var tickerlist = function() { var lis = [(React.DOM.li({key: "lit", onClick: _this.watchTicker, className: "change-coin-stamp", role: "presentation", 'data-snowstamp': _this.props.config.wally.coinstamp, 'data-snowticker': _this.props.config.wally.cointicker}, React.DOM.a(null, " ", _this.props.config.wally.cointicker.toUpperCase())))] if (snowmoney['usd'][wally.cointicker] && snowmoney['usd'][wally.cointicker].price) lis.push(React.DOM.li({key: "lit1", onClick: _this.watchTicker, role: "presentation", 'data-snowstamp': "USD", 'data-snowticker': "usd", className: "change-coin-stamp"}, React.DOM.a(null, "USD"))) if (snowmoney['eur'][wally.cointicker] && snowmoney['eur'][wally.cointicker].price) lis.push(React.DOM.li({key: "lit2", onClick: _this.watchTicker, role: "presentation", 'data-snowstamp': "EUR", 'data-snowticker': "eur", className: "change-coin-stamp"}, React.DOM.a(null, "EUR"))) if (snowmoney['btc'][wally.cointicker] && snowmoney['btc'][wally.cointicker].price) lis.push(React.DOM.li({key: "lit3", onClick: _this.watchTicker, role: "presentation", 'data-snowstamp': "BTC", 'data-snowticker': "btc", className: "change-coin-stamp"}, React.DOM.a(null, "BTC"))) if (snowmoney['ltc'][wally.cointicker] && snowmoney['ltc'][wally.cointicker].price) lis.push(React.DOM.li({key: "lit4", onClick: _this.watchTicker, role: "presentation", 'data-snowstamp': "LTC", 'data-snowticker': "ltc", className: "change-coin-stamp"}, React.DOM.a(null, "LTC"))) if (wally.cointicker!='doge' && snowmoney['doge'][wally.cointicker] && snowmoney['doge'][wally.cointicker].price) lis.push(React.DOM.li({key: "lit5", onClick: _this.watchTicker, role: "presentation", 'data-snowstamp': "doge", 'data-snowticker': "doge", className: "change-coin-stamp"}, React.DOM.a(null, "DOGE"))) return lis } if(this.state.accounts instanceof Array) { var accs = this.state.accounts.map(function(v) { return ( React.DOM.option({key: v.name, value: v.name}, v.name) ); }); } else { var accs = '<option value="">no accounts found</option>' } /* check for accounts and addresses in the url */ var param = {from:{},to:{}} var pFrom = _this.props.config.params.indexOf('from'), pTo = _this.props.config.params.indexOf('to'); // if there is a from in the url grab the next param which can be an account or address param.from.account = pFrom!==-1 ? _this.props.config.params[pFrom+1] : ''; param.from.address = pFrom!==-1 ? _this.props.config.params[pFrom+1] : ''; // if there is a to in the url grab the next param which should be an address param.to.address = pTo!==-1 ? _this.props.config.params[pTo+1] : ''; return ( React.DOM.div(null, React.DOM.div({id: "snow-send", className: "snow-send bs-example"}, React.DOM.div({className: "col-xs-12 col-sm-offset-1 col-sm-10 col-md-10 col-lg-10"}, React.DOM.div({id: "prettysuccess", style: {display:'none'}}, React.DOM.div({className: "alert alert-success alert-dismissable"}, React.DOM.button({'data-dismiss': "alert", 'aria-hidden': "true", className: "close"}, "×"), React.DOM.p(null) ) ), React.DOM.div({id: "prettyerror", style: {display:_this.state.error ? 'block' : 'none'}}, React.DOM.div({className: "alert alert-danger alert-dismissable"}, React.DOM.button({'data-dismiss': "alert", 'aria-hidden': "true", className: "close"}, "×"), React.DOM.p(null, _this.state.error) ) ), React.DOM.form({onSubmit: this.walletForm, id: "snowsendcoin", className: "snow-block-lg"}, React.DOM.div({className: "snow-block-heading"}), React.DOM.div({className: "form-group input-group"}, React.DOM.span({className: "input-group-addon input-group-sm coinstamp"}, React.DOM.div({className: "dropdown"}, React.DOM.a({id: "snowchangefrom", 'data-toggle': "dropdown", 'data-snowstamp': _this.props.config.wally.coinstamp, 'data-snowticker': _this.props.config.wally.cointicker, className: "dropdown-toggle"}, React.DOM.span({id: "changestamp"}, _this.props.config.wally.cointicker.toUpperCase(), " "), "  ", React.DOM.span({className: "caret"}) ), React.DOM.ul({role: "menu", 'aria-labelledby': "dda2", className: "dropdown-menu"}, tickerlist() ) ) ), React.DOM.span({id: "convamountspan", 'data-toggle': "tooltip", 'data-placement': "top", 'data-container': "#snow-send", className: "input-group-addon input-group-sm coinstamp bstooltip"}, React.DOM.span({id: "convamount"}) ), React.DOM.input({required: "required", type: "text", pattern: "[-+]?[0-9]*[.,]?[0-9]+", defaultValue: this.state.persist.amount, id: "sendcoinamount", name: "sendcoinamount", placeholder: "Amount", 'data-toggle': "tooltip", 'data-placement': "top", 'data-container': "#snow-send", className: "form-control coinstamp bstooltip watchme active", title: "We will send this amount", onChange: _this.watchAmount, onKeyUp: _this.watchAmount, onFocus: _this.watchAmount}), React.DOM.input({id: "sendcointrueamount", type: "hidden", defaultValue: this.state.persist.amount || "0"}), React.DOM.span({id: "changeamountspan", 'data-toggle': "tooltip", 'data-placement': "top", 'data-container': "#snow-send", className: "input-group-addon input-group-sm coinstamp watchme"}, React.DOM.span({id: "changeamountbefore"}, "$ "), React.DOM.span({id: "changeamount"}, "0"), React.DOM.span({id: "changeamountafter"}) ) ), React.DOM.div({style: {textAlign:'right',marginTop:-5}}, React.DOM.a({rel: "popover", 'data-container': "body", 'data-toggle': "popover", 'data-placement': "left", 'data-html': "true", 'data-content': "The left bookend selects the currency you want to enter. The right bookend will show you a converted amount. <br /><br /> Select " + _this.props.config.wally.cointicker.toUpperCase() + " to see a conversion to " + _this.props.config.wally.currency.toUpperCase() + ". You will send the amount entered in the blue box<br /><br /> Select another currency to convert the entered amount to " + _this.props.config.wally.cointicker.toUpperCase() + ". The right bookend will be blue and the amount you send. ", className: "helppopover"}, "help")), React.DOM.div({style: {textAlign:'left'}, className: "snow-send-body"}, React.DOM.div({className: "snow-balance-body"}, React.DOM.span(null, parseFloat(_this.state.data.balance).formatMoney()), React.DOM.input({id: "snow-balance-input", type: "hidden", value: parseFloat(_this.state.data.balance)}), " ", React.DOM.span({style: {color:'#ccc'}, className: "coinstamp"}, " ", _this.props.config.wally.coinstamp, "   after sending") ) ), React.DOM.div({className: "form-group input-group"}, React.DOM.span({className: "input-group-addon input-group-sm coinstamp"}, "From"), React.DOM.select({id: "sendcoinfromaccount", name: "sendcoinfromaccount", className: "form-control coinstamp", defaultValue: this.state.persist.from || param.from.account}, accs ) ), React.DOM.div({className: "form-group input-group"}, React.DOM.span({className: "input-group-addon input-group-sm coinstamp"}, "To"), React.DOM.input({required: "required", id: "sendcointoaddress", name: "sendcointoaddress", placeholder: "Coin Address", defaultValue: this.state.persist.to || param.to.address, className: "form-control coinstamp"}), React.DOM.span({style: {cursor:'pointer'}, onClick: _this.addressBook, className: "input-group-addon input-group-sm glyphicon glyphicon-user"}) ), React.DOM.div({className: "form-group input-group"}, React.DOM.span({className: "input-group-addon input-group-sm coinstamp"}, React.DOM.input({type: "checkbox", id: "sendcoinsaveaddr", value: "save", onChange: _this.saveAddressForm}) ), React.DOM.label({style: {textAlign:'left'}, className: "form-control coinstamp"}, "Save this address to my contacts") ), React.DOM.div({id: "sendcoinshowname", style: {display:'none'}, className: "form-group input-group bg-info"}, React.DOM.span({className: "input-group-addon input-group-sm coinstamp"}, "Name"), React.DOM.input({id: "sendcoinaddressname", name: "sendcoinaddressname", placeholder: "name for address", className: "form-control coinstamp", defaultValue: this.state.persist.saveAs}) ), React.DOM.div({className: "form-group input-group"}, React.DOM.span({className: "input-group-addon input-group-sm coinstamp"}, "Message "), React.DOM.input({id: "sendcointomessage", name: "sendcointomessage", placeholder: "message", className: "form-control coinstamp", defaultValue: this.state.persist.message}) ), React.DOM.div({className: "form-group input-group"}, React.DOM.span({className: "input-group-addon input-group-sm coinstamp"}, "Memo"), React.DOM.input({id: "sendcoinmemo", name: "sendcoinmemo", placeholder: "memo", className: "form-control coinstamp", defaultValue: this.state.persist.memo}) ), React.DOM.div({className: "form-group"}, React.DOM.button({type: "submit", id: "buttonsend", className: "btn btn-sm snowsendcoin"}, "Send Coin") ), React.DOM.div({className: "clearfix"}) ) ), React.DOM.div({className: "clearfix"}) ), snowUI.snowModals.addressBook.call(this) ) ); } else { return (React.DOM.div(null)) } } }); /** * 2014 snowkeeper * github.com/snowkeeper * npmjs.org/snowkeeper * * Peace :0) * * */
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import React from 'react'; import fs from 'fs'; import mkdirp from 'mkdirp'; import ReactDOM from 'react-dom/server'; import Router, {routes, blogMeta} from './routes'; import Html from './components/Html'; import globals from './globals' var customRoutes = Router.routes.map(route => { return route.path; //route.path.slice(globals.publicUrl.length); }).filter(path => path.length && path.indexOf('*') == -1 && path.indexOf(':') == -1); Object.keys(routes).concat(customRoutes).forEach(processRoute); // render tags (() => { var tags = []; Object.keys(blogMeta).forEach(async slug => { var post = blogMeta[slug]; if (post.tags) { post.tags.forEach(tag => { if (tags.indexOf(tag) == -1) { tags.push(tag); } }) } }); console.log('unique tags', tags); var baseTagRoute = globals.publicUrl+'/tag/' tags.forEach(tag => processRoute(baseTagRoute+tag)) })(); async function dispatch(route) { return new Promise(async (resolve, reject) => { const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => { css.push(value) }, onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value }; console.log("dispatching", route); await Router.dispatch({ path: route, context }, (state, component) => { try { data.body = ReactDOM.renderToString(component); data.css = css.join(''); console.log("dispatched ", route); } catch (error) { console.log(error); } }); if (globals.publicUrl == '') { data.base = '/' } else { data.base = globals.publicUrl + '/'; } const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); resolve(html); }) } async function processRoute(route) { const writePath = path.relative(globals.publicUrl.length ? globals.publicUrl : '/', route) console.log('write path', writePath); const filePath = path.join(__dirname, 'public', writePath, 'index.html'); console.log("writing to", filePath); mkdirp.sync(path.dirname(filePath)); var html = await dispatch(route); fs.writeFile(filePath, html); }
'use strict'; const mcping = require('./'); if (process.argv.length < 4) { console.log('Usage: node demo.js <host> <port>'); process.exit(1); } const host = process.argv[2]; const port = parseInt(process.argv[3]); mcping.ping_all({host, port}, function(err, response, type) { if (err) { console.log('ping '+type+' error',err); return; } console.log('received ping_'+type,response); });
const http = require('http') const rocky = require('..') const proxy = rocky() // Enable replay sequentially proxy .replaySequentially() proxy .forward('http://localhost:3001') .replay('http://localhost:3002') .replay('http://localhost:3002') .replay('http://localhost:3002') proxy .get('/*') proxy.listen(3000) // Target servers http.createServer(function (req, res) { setTimeout(function () { console.log('1) Forward server reached') res.writeHead(200) res.end() }, 100) }).listen(3001) http.createServer(function (req, res) { setTimeout(function () { console.log('3) Then the replay server is reached') res.writeHead(204) res.end() }, 1000) }).listen(3002) // Test requests http.get('http://localhost:3000/users/pepe', function (res) { console.log('2) Response from target server:', res.statusCode) })
import { expect, assert } from 'chai' import { makeAStore } from './helpers/store' import { mountRootComponent, ReduxComponent, action, selector } from 'redux-components' import ComponentList from '..' class BaseComponent extends ReduxComponent { static verbs = ['SCOPED_SET'] reducer(state = {}, action) { switch(action.type) { case this.SCOPED_SET: return action.payload || {} default: return state } } @action({ isDispatcher: true }) set(x) { return { type: this.SCOPED_SET, payload: x } } @selector() get(state) { return state } } describe("basic tests", () => { it("should work", () => { var store = makeAStore() var MyComponentList = ComponentList(() => BaseComponent) var myComponentList = new MyComponentList() mountRootComponent(store, myComponentList) myComponentList.push(true) myComponentList.get(0).set("hi") myComponentList.push(true) myComponentList.get(1).set("world") assert.deepEqual(myComponentList.map((x) => x.get()), ["hi", "world"]) myComponentList.splice(0, 1) assert(myComponentList.get(0).get() === "world") }) it("should observe toArray", () => { var store = makeAStore() var MyComponentList = ComponentList(() => BaseComponent) var myComponentList = new MyComponentList() mountRootComponent(store, myComponentList) myComponentList.toArray.subscribe({ next: (val) => console.log("!!!! next", val) }) myComponentList.push(true) }) })
import * as api from '../api'; export const FETCHING_ADDONS = 'FETCHING_ADDONS' export const RECEIVED_ADDONS = 'RECEIVED_ADDONS' export function deleteAddon(addonId) { return function(dispatch, getState) { const projectId = getState().project.get('id'); dispatch(deletingAddon(addonId)); if (addonId < 0) { dispatch(deletedAddon(addonId)); } else { return api.delet(`/projects/${projectId}/integrations/${addonId}`) .then(resp => { dispatch(deletedAddon(addonId)); }, resp => { throw new Error(`Failed to delete addon #${addonId}`); }); } } } export function deletingAddon(id) { return { type: 'DELETING_ADDON', id } } export function deletedAddon(id) { return { type: 'DELETED_ADDON', id } } export function newAddon(kind) { const id = (+new Date()) * -1; return { type: 'NEW_ADDON', kind, id } } export function fetchAddons() { function shouldFetch(state) { return state.addons.get('isFetching') === false } return function(dispatch, getState) { const state = getState(); const projectId = state.project.get('id'); if (shouldFetch(state)) { dispatch(fetchingAddons()); return api.get(`/projects/${projectId}/addons`) .then(resp => { dispatch(receivedAddons(resp.addon)); }, resp => { throw new Error('Failed to fetch project addons.'); }); } else { return Promise.resolve(); } } } export function fetchingAddons() { return { type: FETCHING_ADDONS } } export function receivedAddons(addons) { return { type: RECEIVED_ADDONS, items: addons } } export function saveAddon(id, kind, data) { return function(dispatch, getState) { const state = getState(); const projectId = state.project.get('id'); const body = JSON.stringify({ kind, data }); let push; if (id < 0) { push = api.post(`/projects/${projectId}/integrations`, { body }); } else { push = api.patch(`/projects/${projectId}/integrations/${id}`, { body }); } return push.then(resp => { dispatch(changedAddon(resp.addon, id)); }, resp => { throw new Error(`Failed to save addon ${kind} #${id}.`) }); } } export function changedAddon(addon, prevId) { return { type: 'CHANGED_ADDON', addon, prevId } }
/** * Interaction for the Menu module * * @author Jesse Dobbelaere <jesse@dobbelaere-ae.be> */ jsBackend.menu = { // constructor init: function() { // do meta if ($('#title').length > 0) $('#title').doMeta(); } }; $(jsBackend.menu.init);
$(function(){ document.onkeydown=function(event){ var e = event || window.event || arguments.callee.caller.arguments[0]; if(e && e.keyCode==13){ $("#submitForm").click(); return false; } }; var vform = $("#LoginForm").Validform({ tiptype:3, showAllError:true, }); $("#submitForm").click(function(){ if(!vform.check()) return false; var fm = $("#LoginForm")[0]; var data = new FormData(fm); $.ajax({ type:"POST", url:"AmLogin.html", processData:false, contentType:false, data:data, dataType:"json", success:function(data){ var json = eval(data); if(json.isOk == 'error'){ layer.alert(json.message, {icon:5}); }else{ window.location.href="AmWelcome.html"; } }, error:function(){ layer.alert('网络不稳定,请稍后再试!', {icon:5}); } }); }); });
/* eslint-disable func-names, prefer-arrow-callback, no-unused-expressions */ // Third party components const {expect} = require('chai'); const logger = require('winston'); // Local components const SchemaRoute = require('../../../app/routes/schemas'); // Setup logger.level = 'error'; describe('routes/schemas.js', function () { describe('Route', function () { it('should define a parameter handler for Collection parameter', function (done) { const app = { use: (router) => { expect(router).to.have.property('params'); expect(router.params).to.have.property('Collection'); done(); } }; SchemaRoute(app); }); it('should define correct routes', function (done) { const app = { use: (router) => { expect(router).to.have.property('stack'); expect(router.stack).to.have.lengthOf(2); expect(router.stack[0]).to.have.property('route'); expect(router.stack[1]).to.have.property('route'); expect(router.stack[0].route).to.have.property('path', '/api/v0/schemas.:format?'); expect(router.stack[1].route).to.have.property('path', '/api/v0/schemas/:Collection.:format?'); done(); } }; SchemaRoute(app); }); }); });
var noflo = require('noflo'); exports.getComponent = function () { var c = new noflo.Component(); c.inPorts.add('in', function (event, payload) { if (event !== 'data') { return; } // Do something with the packet, then payload = payload.sort(); c.outPorts.out.send(payload); }); c.outPorts.add('out'); return c; };
const Lab = require('lab') const Code = require('code') const async = require('async') const server = require('../').hapi const lab = exports.lab = Lab.script() const token = require('../auth/token') const aux = token.createJwt('admin') const auxA = token.createJwt('john.doe') const auxB = token.createJwt('jane.doe') const auxC = token.createJwt('conor.mcgregor') const auxD = token.createJwt('tuda.chavaile') const auxTeam = token.createJwt('johny.team') const userA = { id: 'john.doe', name: 'John Doe', mail: 'john@doe.com', role: 'company', company: [{ edition: '25-SINFO', company: 'SINFO' }] } const achievementA = { id: 'stand-' + userA.company[0].company + '-', name: 'Went to stand', kind: 'stand', value: 10, validity: { from: new Date(), to: new Date(new Date().getTime() + (1000 * 60 * 60)) // 1 h } } const userB = { id: 'jane.doe', name: 'Jane Doe', mail: 'jane@ufc.com', role: 'user' } const userC = { id: 'conor.mcgregor', name: 'Conner Mcgregor', mail: 'conor@ufc.com', role: 'company', company: [{ edition: '25-SINFO', company: 'UFC' }] } const userD = { id: 'tuda.chavaile', name: 'Tudarete Chavaile', mail: 'tuda@chavaile.com', role: 'company', company: [{ edition: '25-SINFO', company: 'Chavaile.Inc' }] } const achievementD = { id: 'stand-' + userD.company[0].company + '-', name: 'Went to stand', event: '25-SINFO', kind: 'stand', value: 10, validity: { from: new Date(), to: new Date(new Date().getTime() + (1000 * 60 * 60)) // 1 h } } const userTeam = { id: 'johny.team', name: 'johny team', mail: 'johny@sinfo.org', role: 'team' } const credentialsAdmin = { user: { id: 'admin', name: 'John Doe' }, bearer: aux.token, scope: 'admin' } const credentialsA = { user: userA, bearer: auxA.token, scope: 'company' } const credentialsB = { user: userB, bearer: auxB.token, scope: 'user' } const credentialsC = { user: userC, bearer: auxC.token, scope: 'company' } const credentialsD = { user: userD, bearer: auxD.token, scope: 'company' } const credentialsTeam = { user: userTeam, bearer: auxTeam.token, scope: 'team' } const linkA = { userId: credentialsA.user.id, attendeeId: credentialsB.user.id, editionId: userA.company[0].edition, notes: { otherObservations: 'Jane had a great sence of humor' } } const linkB = { userId: credentialsA.user.id, attendeeId: credentialsD.user.id, editionId: userA.company[0].edition } const linkC = { userId: credentialsA.user.id, attendeeId: credentialsC.user.id, editionId: userA.company[0].edition, notes: { otherObservations: '' } } const changesToA = { notes: { otherObservations: 'Jane had a great sence of humor and great Perl skils' } } lab.experiment('Link', () => { lab.before((done) => { const optionsA = { method: 'POST', url: '/users', credentials: credentialsAdmin, payload: userA } const optionsB = { method: 'POST', url: '/users', credentials: credentialsAdmin, payload: userB } const optionsC = { method: 'POST', url: '/users', credentials: credentialsAdmin, payload: userC } const optionsD = { method: 'POST', url: '/users', credentials: credentialsAdmin, payload: userD } const optionsTeam = { method: 'POST', url: '/users', credentials: credentialsAdmin, payload: userTeam } const optionsAchievementA = { method: 'POST', url: '/achievements', credentials: credentialsAdmin, payload: achievementA } const optionsAchievementD = { method: 'POST', url: '/achievements', credentials: credentialsAdmin, payload: achievementD } async.parallel([ (cb) => { server.inject(optionsA, (response) => { return cb() }) }, (cb) => { server.inject(optionsB, (response) => { return cb() }) }, (cb) => { server.inject(optionsC, (response) => { return cb() }) }, (cb) => { server.inject(optionsD, (response) => { return cb() }) }, (cb) => { server.inject(optionsTeam, (response) => { return cb() }) }, (cb) => { server.inject(optionsAchievementA, (response) => { return cb() }) }, (cb) => { server.inject(optionsAchievementD, (response) => { return cb() }) } ], (_, results) => { done() }) }) lab.after((done) => { const optionsA = { method: 'DELETE', url: '/users/' + userA.id, credentials: credentialsAdmin } const optionsB = { method: 'DELETE', url: '/users/' + userB.id, credentials: credentialsAdmin } const optionsC = { method: 'DELETE', url: '/users/' + userC.id, credentials: credentialsAdmin } const optionsD = { method: 'DELETE', url: '/users/' + userD.id, credentials: credentialsAdmin } const optionsTeam = { method: 'DELETE', url: '/users/' + userTeam.id, credentials: credentialsAdmin } const optionsAchievementA = { method: 'DELETE', url: '/achievements/' + achievementA.id, credentials: credentialsAdmin } const optionsAchievementD = { method: 'DELETE', url: '/achievements/' + achievementD.id, credentials: credentialsAdmin } async.parallel([ (cb) => { server.inject(optionsA, (response) => { return cb() }) }, (cb) => { server.inject(optionsB, (response) => { return cb() }) }, (cb) => { server.inject(optionsC, (response) => { return cb() }) }, (cb) => { server.inject(optionsD, (response) => { return cb() }) }, (cb) => { server.inject(optionsTeam, (response) => { return cb() }) }, (cb) => { server.inject(optionsAchievementA, (response) => { return cb() }) }, (cb) => { server.inject(optionsAchievementD, (response) => { return cb() }) } ], (_, results) => { done() }) }) lab.test('Create link ok as company', (done) => { const options = { method: 'POST', url: `/company/${userA.company[0].company}/link`, credentials: credentialsA, payload: linkA } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(201) Code.expect(result).to.be.instanceof(Object) Code.expect(result.user).to.equal(linkA.userId) Code.expect(result.company).to.equal(userA.company[0].company) Code.expect(result.edition).to.equal(linkA.editionId) Code.expect(result.attendee).to.equal(linkA.attendeeId) Code.expect(result.notes.otherObservations).to.equal(linkA.notes.otherObservations) done() }) }) lab.test('Create Link empty string as company', (done) => { const options = { method: 'POST', url: `/company/${userA.company[0].company}/link`, credentials: credentialsA, payload: linkC } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(201) Code.expect(result).to.be.instanceof(Object) Code.expect(result.user).to.equal(linkC.userId) Code.expect(result.company).to.equal(userA.company[0].company) Code.expect(result.edition).to.equal(linkC.editionId) Code.expect(result.attendee).to.equal(linkC.attendeeId) Code.expect(result.notes.otherObservations).to.be.empty() done() }) }) lab.test('Create Link null note as company', (done) => { const options = { method: 'POST', url: `/company/${userA.company[0].company}/link`, credentials: credentialsA, payload: linkB } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(201) Code.expect(result).to.be.instanceof(Object) Code.expect(result.user).to.equal(linkB.userId) Code.expect(result.company).to.equal(userA.company[0].company) Code.expect(result.edition).to.equal(linkB.editionId) Code.expect(result.attendee).to.equal(linkB.attendeeId) Code.expect(result.notes).to.be.instanceof(Object) done() }) }) lab.test('Sign B as company I day I', (done) => { const sign = { editionId: '25-SINFO', day: 'Monday' } const options = { method: 'POST', url: `/company/${userA.company[0].company}/sign/${userB.id}`, credentials: credentialsA, payload: sign } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(200) Code.expect(result).to.be.instanceof(Object) Code.expect(result.signatures[0].edition).to.equal(sign.editionId) Code.expect(result.signatures[0].day).to.equal(sign.day) Code.expect(result.signatures[0].signatures.filter(s => s.companyId === userA.company[0].company).length).to.equal(1) done() }) }) lab.test('Sign B as company II day I', (done) => { const sign = { editionId: '25-SINFO', day: 'Monday' } const options = { method: 'POST', url: `/company/${userD.company[0].company}/sign/${userB.id}`, credentials: credentialsD, payload: sign } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(200) Code.expect(result).to.be.instanceof(Object) Code.expect(result.signatures[0].edition).to.equal(sign.editionId) Code.expect(result.signatures[0].day).to.equal(sign.day) Code.expect(result.signatures[0].signatures.filter(s => s.companyId === userA.company[0].company).length).to.equal(1) done() }) }) lab.test('Sign B as company I day II', (done) => { const sign = { editionId: '25-SINFO', day: 'Thursday' } const options = { method: 'POST', url: `/company/${userA.company[0].company}/sign/${userB.id}`, credentials: credentialsA, payload: sign } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(200) Code.expect(result).to.be.instanceof(Object) Code.expect(result.signatures[1].edition).to.equal(sign.editionId) Code.expect(result.signatures[1].day).to.equal(sign.day) Code.expect(result.signatures[1].signatures.filter(s => s.companyId === userA.company[0].company).length).to.equal(1) done() }) }) lab.test('Redeem Card day II as User', (done) => { const options = { method: 'POST', url: `/users/${userB.id}/redeem-card`, credentials: credentialsTeam, payload: { day: 'Thursday', editionId: '25-SINFO' } } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(422) done() }) }) lab.test('Get as company', (done) => { const options = { method: 'Get', url: `/company/${userA.company[0].company}/link/${linkA.attendeeId}?editionId=${linkA.editionId}`, credentials: credentialsA } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(200) Code.expect(result.user).to.equal(linkA.userId) Code.expect(result.company).to.equal(userA.company[0].company) Code.expect(result.edition).to.equal(linkA.editionId) Code.expect(result.attendee).to.equal(linkA.attendeeId) Code.expect(result.notes.otherObservations).to.equal(linkA.notes.otherObservations) done() }) }) lab.test('Get other company as company', (done) => { const options = { method: 'Get', url: `/company/${userA.company[0].company}/link/${linkA.attendeeId}?editionId=${linkA.editionId}`, credentials: credentialsC } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(404) done() }) }) lab.test('Update remove note as company', (done) => { const options = { method: 'PUT', url: `/company/${userA.company[0].company}/link/${linkA.attendeeId}?editionId=${linkA.editionId}`, credentials: credentialsA, payload: { notes: null } } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(200) Code.expect(result).to.be.instanceof(Object) Code.expect(result.user).to.equal(linkA.userId) Code.expect(result.company).to.equal(userA.company[0].company) Code.expect(result.edition).to.equal(linkA.editionId) Code.expect(result.attendee).to.equal(linkA.attendeeId) Code.expect(result.notes.otherObservations).to.equal('') done() }) }) lab.test('Update as company', (done) => { const options = { method: 'PUT', url: `/company/${userA.company[0].company}/link/${linkA.attendeeId}?editionId=${linkA.editionId}`, credentials: credentialsA, payload: changesToA } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(200) Code.expect(result).to.be.instanceof(Object) Code.expect(result.user).to.equal(linkA.userId) Code.expect(result.company).to.equal(userA.company[0].company) Code.expect(result.edition).to.equal(linkA.editionId) Code.expect(result.attendee).to.equal(linkA.attendeeId) Code.expect(result.notes.otherObservations).to.equal(changesToA.notes.otherObservations) done() }) }) lab.test('Update Non Existing as company', (done) => { const options = { method: 'PUT', url: `/company/NullConsulting/link/${linkA.attendeeId}?editionId=${linkA.editionId}`, credentials: credentialsA, payload: changesToA } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(404) done() }) }) lab.test('List as company', (done) => { const options = { method: 'Get', url: `/company/${userA.company[0].company}/link?editionId=${linkA.editionId}`, credentials: credentialsA } server.inject(options, (response) => { const result = response.result // result.sort() Code.expect(response.statusCode).to.equal(200) Code.expect(result).to.be.instanceof(Array) Code.expect(result[0].user).to.equal(linkA.userId) Code.expect(result[0].company).to.equal(userA.company[0].company) done() }) }) lab.test('List Non Existing as company', (done) => { const options = { method: 'Get', url: `/company/NullConsulting/link?editionId=${linkA.editionId}`, credentials: credentialsA } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(404) done() }) }) lab.test('Create same as company', (done) => { const options = { method: 'POST', url: `/company/${userA.company[0].company}/link`, credentials: credentialsA, payload: linkA } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(409) done() }) }) lab.test('Delete A as company', (done) => { const options = { method: 'DELETE', url: `/company/${userA.company[0].company}/link/${linkA.attendeeId}?editionId=${linkA.editionId}`, credentials: credentialsA } server.inject(options, (response) => { const result = response.result Code.expect(response.statusCode).to.equal(200) Code.expect(result).to.be.instanceof(Object) Code.expect(result.user).to.equal(linkA.userId) Code.expect(result.company).to.equal(userA.company[0].company) Code.expect(result.edition).to.equal(linkA.editionId) Code.expect(result.attendee).to.equal(linkA.attendeeId) Code.expect(result.notes.otherObservations).to.equal(changesToA.notes.otherObservations) done() }) }) lab.test('Delete B as company', (done) => { const options = { method: 'DELETE', url: `/company/${userA.company[0].company}/link/${linkB.attendeeId}?editionId=${linkB.editionId}`, credentials: credentialsA } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(200) done() }) }) lab.test('Delete C as company', (done) => { const options = { method: 'DELETE', url: `/company/${userA.company[0].company}/link/${linkC.attendeeId}?editionId=${linkC.editionId}`, credentials: credentialsA } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(200) done() }) }) lab.test('Create as user', (done) => { const options = { method: 'POST', url: `/company/${userA.company[0].company}/link`, credentials: credentialsB, payload: linkA } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(403) done() }) }) lab.test('Get as user', (done) => { const options = { method: 'GET', url: `/company/${userA.company[0].company}/link/${linkA.attendeeId}?editionId=${linkA.editionId}`, credentials: credentialsB } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(403) done() }) }) lab.test('List as user', (done) => { const options = { method: 'GET', url: `/company/${userA.company[0].company}/link?editionId=${linkA.editionId}`, credentials: credentialsB } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(403) done() }) }) lab.test('Delete as user', (done) => { const options = { method: 'GET', url: `/company/${userA.company[0].company}/link/${linkA.attendeeId}?editionId=${linkA.editionId}`, credentials: credentialsB } server.inject(options, (response) => { Code.expect(response.statusCode).to.equal(403) done() }) }) })
'use strict'; angular.module('somerledSheltiesApp') .config(function ($stateProvider) { $stateProvider .state('main', { url: '/', templateUrl: 'app/main/main.html', controller: 'MainCtrl' }); });
'use strict'; /** * @ngdoc function * @name publicApp.controller:AboutCtrl * @description * # AboutCtrl * Controller of the publicApp */ angular.module('publicApp') .controller('AboutCtrl', function ($scope) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; });
const state = { is_login: false, self_user: {}, is_cordova: false, city: { "count": 209, "id": 290, "n": "北京", "pinyinFull": "Beijing", "pinyinShort": "bj" } } // mutations const mutations = { 'SET_SELF_USER' (state, user) { state.self_user = user; }, 'SET_IS_LOGIN' (state, is_login) { state.is_login = is_login; }, 'UPDATE_SELF_USER' (state, userinfo) { for (let key in userinfo) { state.self_user[key] = userinfo[key]; } }, 'SET_IS_CORDOVA' (state, is_cordova) { state.is_cordova = is_cordova; }, 'SET_CITY' (state, city) { state.city = city; }, } export default { state, mutations }
/** * Created by Vincent Peybernes on 20/02/14. */ var fs = require('fs'); var JsonBinded = require('../libs/model/jsonBind'); var FSAdapter = require('../libs/adapter/fs-adapter'); var jsonExpect = { "name": "test", "number": 1, "boolean": true, "object": { "name": "test", "number": 1 } }, jsonLength = Object.getOwnPropertyNames(jsonExpect).length; var jsonReadFile = "test/resources/readTest.json"; var jsonWriteFile = "test/resources/writeTest.json"; var jsonPath = "test/resources/readTest.json", jsonWritePath = "test/resources/writeTest.json", jsonUnWritePath = "test/resources/"; module.exports = { enumTest: function(test){ var bind = new JsonBinded(undefined, jsonExpect); test.deepEqual(bind, jsonExpect); test.equals(typeof bind._save, "function", "Save"); test.done(); }, fs: { get: function(test){ var bind = new JsonBinded({}, new JsonBinded.FSAdapter({path:jsonReadFile})); bind._get(function(err){ test.equals(err, undefined, "JSON get err"); test.deepEqual(this, jsonExpect, 'JSON get'); test.done(); }); }, save: function(test){ var bind = new JsonBinded(jsonExpect, new JsonBinded.FSAdapter({path:jsonWriteFile})); bind._save(function(err){ test.equals(err, undefined, "JSON save err"); var file = fs.readFileSync(jsonWriteFile); test.equals(file, JSON.stringify(jsonExpect), "JSON save"); fs.unlinkSync(jsonWriteFile); test.done(); }); }, synchronize: function(test){ var jsonExpect = {foo: 'bar'}; var bind = new JsonBinded(jsonExpect, new JsonBinded.FSAdapter({path:jsonWriteFile})); jsonExpect.test = 'test'; bind.test = jsonExpect.test; bind._save(function(err){ test.equals(err, undefined, 'Synch error') var file = fs.readFileSync(jsonWriteFile); test.equals(file, JSON.stringify(jsonExpect), 'Synch'); fs.unlinkSync(jsonWriteFile); test.done(); }); } } };
return function(obj){ return obj && typeof obj === 'object' && typeof object.then === 'function'; }
import layout from '../templates/components/context-menu'; import invokeAction from 'ember-invoke-action'; import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { htmlSafe } from '@ember/string'; import { reads } from '@ember/object/computed'; import { computed, get } from '@ember/object'; export default Component.extend({ tagName: '', layout, contextMenu: service('context-menu'), isActive: reads('contextMenu.isActive'), renderLeft: reads('contextMenu.renderLeft'), items: reads('contextMenu.items'), _selection: reads('contextMenu.selection'), details: reads('contextMenu.details'), clickEvent: reads('contextMenu.event'), selection: computed('_selection.[]', function () { return [].concat(this._selection); }), didInsertElement() { this._super(...arguments); this.setWormholeTarget(); }, setWormholeTarget() { let id = 'wormhole-context-menu'; let target = document.querySelectorAll(`#${id}`); if (target.length === 0) { document.body.insertAdjacentHTML('beforeend', `<div id="${id}"></div>`); } }, position: computed('contextMenu.position.{left,top}', function () { let { left, top } = get(this, 'contextMenu.position') || {}; return htmlSafe(`left: ${left}px; top: ${top}px;`); }), itemIsDisabled: computed('selection.[]', 'details', function () { let selection = this.selection || []; let details = this.details; return function (item) { let disabled = item.disabled; if (!item.action && !item.subActions) { return true; } if (typeof disabled === 'function') { return disabled(selection, details); } return disabled; }; }), clickAction: computed('clickEvent', 'details', 'selection.[]', function () { let selection = this.selection; let details = this.details; let event = this.clickEvent; return function (item) { invokeAction(item, 'action', selection, details, event); }; }), });
// Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 2014-06-10 using // generator-karma 0.8.2 module.exports = function(config) { config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: '../', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/bower_components/angular-animate/angular-animate.js', 'app/bower_components/angular-cookies/angular-cookies.js', 'app/bower_components/angular-resource/angular-resource.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-sanitize/angular-sanitize.js', 'app/bower_components/angular-touch/angular-touch.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ 'PhantomJS' ], // Which plugins to enable plugins: [ 'karma-phantomjs-launcher', 'karma-jasmine' ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
angular.module('yapp') .controller('DashboardCtrl', function($scope, $state) { $scope.$state = $state; }) .controller('TransactionCtrl', function($scope, $state,$http) { $scope.$state = $state; $scope.submit = function() { var poster= $http.post("scripts/transaction.php/?pk=:pk&a=:a", {pk: $scope.pk, a:$scope.a}, {headers: {'Content-Type': 'application/json'} }) .then(function (response) { console.log( response); console.log("working"); }); $location.path('/dashboard'); return false; } }) .controller('OverviewCtrl', function($scope, $state,$http) { var poststats = $http.get('scripts/getStats.php') poststats.then(function(result) { $scope.pk = result.data.cle_public; $scope.a = result.data.solde; }); $scope.$state = $state; }) .controller('ProcessCtrl', function($scope, $state) { $scope.$state = $state; $scope.submit = function() { $location.path('/dashboard'); return false; } }) .controller('LoginCtrl', function($scope, $location) { $scope.submit = function() { $location.path('/dashboard'); return false; } });
/* * XPath.js - Pure JavaScript implementation of XPath 2.0 parser and evaluator * * Copyright (c) 2012 Sergey Ilinsky * Dual licensed under the MIT and GPL licenses. * * */ /* 10.4 Comparison Operators on Duration, Date and Time Values op:yearMonthDuration-less-than op:yearMonthDuration-greater-than op:dayTimeDuration-less-than op:dayTimeDuration-greater-than op:duration-equal op:dateTime-equal op:dateTime-less-than op:dateTime-greater-than op:date-equal op:date-less-than op:date-greater-than op:time-equal op:time-less-than op:time-greater-than op:gYearMonth-equal op:gYear-equal op:gMonthDay-equal op:gMonth-equal op:gDay-equal 10.6 Arithmetic Operators on Durations op:add-yearMonthDurations op:subtract-yearMonthDurations op:multiply-yearMonthDuration op:divide-yearMonthDuration op:divide-yearMonthDuration-by-yearMonthDuration op:add-dayTimeDurations op:subtract-dayTimeDurations op:multiply-dayTimeDuration op:divide-dayTimeDuration op:divide-dayTimeDuration-by-dayTimeDuration 10.8 Arithmetic Operators on Durations, Dates and Times op:subtract-dateTimes op:subtract-dates op:subtract-times op:add-yearMonthDuration-to-dateTime op:add-dayTimeDuration-to-dateTime op:subtract-yearMonthDuration-from-dateTime op:subtract-dayTimeDuration-from-dateTime op:add-yearMonthDuration-to-date op:add-dayTimeDuration-to-date op:subtract-yearMonthDuration-from-date op:subtract-dayTimeDuration-from-date op:add-dayTimeDuration-to-time op:subtract-dayTimeDuration-from-time */ // 10.4 Comparison Operators on Duration, Date and Time Values // op:yearMonthDuration-less-than($arg1 as xs:yearMonthDuration, $arg2 as xs:yearMonthDuration) as xs:boolean hStaticContext_operators["yearMonthDuration-less-than"] = function(oLeft, oRight) { return new cXSBoolean(fOperator_yearMonthDuration_toMonths(oLeft) < fOperator_yearMonthDuration_toMonths(oRight)); }; // op:yearMonthDuration-greater-than($arg1 as xs:yearMonthDuration, $arg2 as xs:yearMonthDuration) as xs:boolean hStaticContext_operators["yearMonthDuration-greater-than"] = function(oLeft, oRight) { return new cXSBoolean(fOperator_yearMonthDuration_toMonths(oLeft) > fOperator_yearMonthDuration_toMonths(oRight)); }; // op:dayTimeDuration-less-than($arg1 as dayTimeDuration, $arg2 as dayTimeDuration) as xs:boolean hStaticContext_operators["dayTimeDuration-less-than"] = function(oLeft, oRight) { return new cXSBoolean(fOperator_dayTimeDuration_toSeconds(oLeft) < fOperator_dayTimeDuration_toSeconds(oRight)); }; // op:dayTimeDuration-greater-than($arg1 as dayTimeDuration, $arg2 as dayTimeDuration) as xs:boolean hStaticContext_operators["dayTimeDuration-greater-than"] = function(oLeft, oRight) { return new cXSBoolean(fOperator_dayTimeDuration_toSeconds(oLeft) > fOperator_dayTimeDuration_toSeconds(oRight)); }; // op:duration-equal($arg1 as xs:duration, $arg2 as xs:duration) as xs:boolean hStaticContext_operators["duration-equal"] = function(oLeft, oRight) { return new cXSBoolean(oLeft.negative == oRight.negative && fOperator_yearMonthDuration_toMonths(oLeft) == fOperator_yearMonthDuration_toMonths(oRight) && fOperator_dayTimeDuration_toSeconds(oLeft) == fOperator_dayTimeDuration_toSeconds(oRight)); }; // op:dateTime-equal($arg1 as xs:dateTime, $arg2 as xs:dateTime) as xs:boolean hStaticContext_operators["dateTime-equal"] = function(oLeft, oRight) { return fOperator_compareDateTimes(oLeft, oRight, 'eq'); }; // op:dateTime-less-than($arg1 as xs:dateTime, $arg2 as xs:dateTime) as xs:boolean hStaticContext_operators["dateTime-less-than"] = function(oLeft, oRight) { return fOperator_compareDateTimes(oLeft, oRight, 'lt'); }; //op:dateTime-greater-than($arg1 as xs:dateTime, $arg2 as xs:dateTime) as xs:boolean hStaticContext_operators["dateTime-greater-than"] = function(oLeft, oRight) { return fOperator_compareDateTimes(oLeft, oRight, 'gt'); }; // op:date-equal($arg1 as xs:date, $arg2 as xs:date) as xs:boolean hStaticContext_operators["date-equal"] = function(oLeft, oRight) { return fOperator_compareDates(oLeft, oRight, 'eq'); }; // op:date-less-than($arg1 as xs:date, $arg2 as xs:date) as xs:boolean hStaticContext_operators["date-less-than"] = function(oLeft, oRight) { return fOperator_compareDates(oLeft, oRight, 'lt'); }; // op:date-greater-than($arg1 as xs:date, $arg2 as xs:date) as xs:boolean hStaticContext_operators["date-greater-than"] = function(oLeft, oRight) { return fOperator_compareDates(oLeft, oRight, 'gt'); }; // op:time-equal($arg1 as xs:time, $arg2 as xs:time) as xs:boolean hStaticContext_operators["time-equal"] = function(oLeft, oRight) { return fOperator_compareTimes(oLeft, oRight, 'eq'); }; // op:time-less-than($arg1 as xs:time, $arg2 as xs:time) as xs:boolean hStaticContext_operators["time-less-than"] = function(oLeft, oRight) { return fOperator_compareTimes(oLeft, oRight, 'lt'); }; // op:time-greater-than($arg1 as xs:time, $arg2 as xs:time) as xs:boolean hStaticContext_operators["time-greater-than"] = function(oLeft, oRight) { return fOperator_compareTimes(oLeft, oRight, 'gt'); }; // op:gYearMonth-equal($arg1 as xs:gYearMonth, $arg2 as xs:gYearMonth) as xs:boolean hStaticContext_operators["gYearMonth-equal"] = function(oLeft, oRight) { return fOperator_compareDateTimes( new cXSDateTime(oLeft.year, oLeft.month, fXSDate_getDaysForYearMonth(oLeft.year, oLeft.month), 0, 0, 0, oLeft.timezone == null ? this.timezone : oLeft.timezone), new cXSDateTime(oRight.year, oRight.month, fXSDate_getDaysForYearMonth(oRight.year, oRight.month), 0, 0, 0, oRight.timezone == null ? this.timezone : oRight.timezone), 'eq' ); }; // op:gYear-equal($arg1 as xs:gYear, $arg2 as xs:gYear) as xs:boolean hStaticContext_operators["gYear-equal"] = function(oLeft, oRight) { return fOperator_compareDateTimes( new cXSDateTime(oLeft.year, 1, 1, 0, 0, 0, oLeft.timezone == null ? this.timezone : oLeft.timezone), new cXSDateTime(oRight.year, 1, 1, 0, 0, 0, oRight.timezone == null ? this.timezone : oRight.timezone), 'eq' ); }; // op:gMonthDay-equal($arg1 as xs:gMonthDay, $arg2 as xs:gMonthDay) as xs:boolean hStaticContext_operators["gMonthDay-equal"] = function(oLeft, oRight) { return fOperator_compareDateTimes( new cXSDateTime(1972, oLeft.month, oLeft.day, 0, 0, 0, oLeft.timezone == null ? this.timezone : oLeft.timezone), new cXSDateTime(1972, oRight.month, oRight.day, 0, 0, 0, oRight.timezone == null ? this.timezone : oRight.timezone), 'eq' ); }; // op:gMonth-equal($arg1 as xs:gMonth, $arg2 as xs:gMonth) as xs:boolean hStaticContext_operators["gMonth-equal"] = function(oLeft, oRight) { return fOperator_compareDateTimes( new cXSDateTime(1972, oLeft.month, fXSDate_getDaysForYearMonth(1972, oRight.month), 0, 0, 0, oLeft.timezone == null ? this.timezone : oLeft.timezone), new cXSDateTime(1972, oRight.month, fXSDate_getDaysForYearMonth(1972, oRight.month), 0, 0, 0, oRight.timezone == null ? this.timezone : oRight.timezone), 'eq' ); }; // op:gDay-equal($arg1 as xs:gDay, $arg2 as xs:gDay) as xs:boolean hStaticContext_operators["gDay-equal"] = function(oLeft, oRight) { return fOperator_compareDateTimes( new cXSDateTime(1972, 12, oLeft.day, 0, 0, 0, oLeft.timezone == null ? this.timezone : oLeft.timezone), new cXSDateTime(1972, 12, oRight.day, 0, 0, 0, oRight.timezone == null ? this.timezone : oRight.timezone), 'eq' ); }; // 10.6 Arithmetic Operators on Durations // op:add-yearMonthDurations($arg1 as xs:yearMonthDuration, $arg2 as xs:yearMonthDuration) as xs:yearMonthDuration hStaticContext_operators["add-yearMonthDurations"] = function(oLeft, oRight) { return fOperator_yearMonthDuration_fromMonths(fOperator_yearMonthDuration_toMonths(oLeft) + fOperator_yearMonthDuration_toMonths(oRight)); }; // op:subtract-yearMonthDurations($arg1 as xs:yearMonthDuration, $arg2 as xs:yearMonthDuration) as xs:yearMonthDuration hStaticContext_operators["subtract-yearMonthDurations"] = function(oLeft, oRight) { return fOperator_yearMonthDuration_fromMonths(fOperator_yearMonthDuration_toMonths(oLeft) - fOperator_yearMonthDuration_toMonths(oRight)); }; // op:multiply-yearMonthDuration($arg1 as xs:yearMonthDuration, $arg2 as xs:double) as xs:yearMonthDuration hStaticContext_operators["multiply-yearMonthDuration"] = function(oLeft, oRight) { return fOperator_yearMonthDuration_fromMonths(fOperator_yearMonthDuration_toMonths(oLeft) * oRight); }; // op:divide-yearMonthDuration($arg1 as xs:yearMonthDuration, $arg2 as xs:double) as xs:yearMonthDuration hStaticContext_operators["divide-yearMonthDuration"] = function(oLeft, oRight) { return fOperator_yearMonthDuration_fromMonths(fOperator_yearMonthDuration_toMonths(oLeft) / oRight); }; // op:divide-yearMonthDuration-by-yearMonthDuration($arg1 as xs:yearMonthDuration, $arg2 as xs:yearMonthDuration) as xs:decimal hStaticContext_operators["divide-yearMonthDuration-by-yearMonthDuration"] = function(oLeft, oRight) { return new cXSDecimal(fOperator_yearMonthDuration_toMonths(oLeft) / fOperator_yearMonthDuration_toMonths(oRight)); }; // op:add-dayTimeDurations($arg1 as xs:dayTimeDuration, $arg2 as xs:dayTimeDuration) as xs:dayTimeDuration hStaticContext_operators["add-dayTimeDurations"] = function(oLeft, oRight) { return fOperator_dayTimeDuration_fromSeconds(fOperator_dayTimeDuration_toSeconds(oLeft) + fOperator_dayTimeDuration_toSeconds(oRight)); }; // op:subtract-dayTimeDurations($arg1 as xs:dayTimeDuration, $arg2 as xs:dayTimeDuration) as xs:dayTimeDuration hStaticContext_operators["subtract-dayTimeDurations"] = function(oLeft, oRight) { return fOperator_dayTimeDuration_fromSeconds(fOperator_dayTimeDuration_toSeconds(oLeft) - fOperator_dayTimeDuration_toSeconds(oRight)); }; // op:multiply-dayTimeDurations($arg1 as xs:dayTimeDuration, $arg2 as xs:double) as xs:dayTimeDuration hStaticContext_operators["multiply-dayTimeDuration"] = function(oLeft, oRight) { return fOperator_dayTimeDuration_fromSeconds(fOperator_dayTimeDuration_toSeconds(oLeft) * oRight); }; // op:divide-dayTimeDurations($arg1 as xs:dayTimeDuration, $arg2 as xs:double) as xs:dayTimeDuration hStaticContext_operators["divide-dayTimeDuration"] = function(oLeft, oRight) { return fOperator_dayTimeDuration_fromSeconds(fOperator_dayTimeDuration_toSeconds(oLeft) / oRight); }; // op:divide-dayTimeDuration-by-dayTimeDuration($arg1 as xs:dayTimeDuration, $arg2 as xs:dayTimeDuration) as xs:decimal hStaticContext_operators["divide-dayTimeDuration-by-dayTimeDuration"] = function(oLeft, oRight) { return new cXSDecimal(fOperator_dayTimeDuration_toSeconds(oLeft) / fOperator_dayTimeDuration_toSeconds(oRight)); }; // 10.8 Arithmetic Operators on Durations, Dates and Times // op:subtract-dateTimes($arg1 as xs:dateTime, $arg2 as xs:dateTime) as xs:dayTimeDuration hStaticContext_operators["subtract-dateTimes"] = function(oLeft, oRight) { throw "Operator function '" + "subtract-dateTimes" + "' not implemented"; }; // op:subtract-dates($arg1 as xs:date, $arg2 as xs:date) as xs:dayTimeDuration hStaticContext_operators["subtract-dates"] = function(oLeft, oRight) { throw "Operator function '" + "subtract-dates" + "' not implemented"; }; // op:subtract-times($arg1 as xs:time, $arg2 as xs:time) as xs:dayTimeDuration hStaticContext_operators["subtract-times"] = function(oLeft, oRight) { return fOperator_dayTimeDuration_fromSeconds(fOperator_time_toSeconds(oLeft) - fOperator_time_toSeconds(oRight)); }; // op:add-yearMonthDuration-to-dateTime($arg1 as xs:dateTime, $arg2 as xs:yearMonthDuration) as xs:dateTime hStaticContext_operators["add-yearMonthDuration-to-dateTime"] = function(oLeft, oRight) { return fOperator_addYearMonthDuration2DateTime(oLeft, oRight, '+'); }; // op:add-dayTimeDuration-to-dateTime($arg1 as xs:dateTime, $arg2 as xs:dayTimeDuration) as xs:dateTime hStaticContext_operators["add-dayTimeDuration-to-dateTime"] = function(oLeft, oRight) { return fOperator_addDayTimeDuration2DateTime(oLeft, oRight, '+'); }; // op:subtract-yearMonthDuration-from-dateTime($arg1 as xs:dateTime, $arg2 as xs:yearMonthDuration) as xs:dateTime hStaticContext_operators["subtract-yearMonthDuration-from-dateTime"] = function(oLeft, oRight) { return fOperator_addYearMonthDuration2DateTime(oLeft, oRight, '-'); }; // op:subtract-dayTimeDuration-from-dateTime($arg1 as xs:dateTime, $arg2 as xs:dayTimeDuration) as xs:dateTime hStaticContext_operators["subtract-dayTimeDuration-from-dateTime"] = function(oLeft, oRight) { return fOperator_addDayTimeDuration2DateTime(oLeft, oRight, '-'); }; // op:add-yearMonthDuration-to-date($arg1 as xs:date, $arg2 as xs:yearMonthDuration) as xs:date hStaticContext_operators["add-yearMonthDuration-to-date"] = function(oLeft, oRight) { return fOperator_addYearMonthDuration2DateTime(oLeft, oRight, '+'); }; // op:add-dayTimeDuration-to-date($arg1 as xs:date, $arg2 as xs:dayTimeDuration) as xs:date hStaticContext_operators["add-dayTimeDuration-to-date"] = function(oLeft, oRight) { return fOperator_addDayTimeDuration2DateTime(oLeft, oRight, '+'); }; // op:subtract-yearMonthDuration-from-date($arg1 as xs:date, $arg2 as xs:yearMonthDuration) as xs:date hStaticContext_operators["subtract-yearMonthDuration-from-date"] = function(oLeft, oRight) { return fOperator_addYearMonthDuration2DateTime(oLeft, oRight, '-'); }; // op:subtract-dayTimeDuration-from-date($arg1 as xs:date, $arg2 as xs:dayTimeDuration) as xs:date hStaticContext_operators["subtract-dayTimeDuration-from-date"] = function(oLeft, oRight) { return fOperator_addDayTimeDuration2DateTime(oLeft, oRight, '-'); }; // op:add-dayTimeDuration-to-time($arg1 as xs:time, $arg2 as xs:dayTimeDuration) as xs:time hStaticContext_operators["add-dayTimeDuration-to-time"] = function(oLeft, oRight) { var oValue = new cXSTime(oLeft.hours, oLeft.minutes, oLeft.seconds, oLeft.timezone); oValue.hours += oRight.hours; oValue.minutes += oRight.minutes; oValue.seconds += oRight.seconds; // return fXSTime_normalize(oValue); }; // op:subtract-dayTimeDuration-from-time($arg1 as xs:time, $arg2 as xs:dayTimeDuration) as xs:time hStaticContext_operators["subtract-dayTimeDuration-from-time"] = function(oLeft, oRight) { var oValue = new cXSTime(oLeft.hours, oLeft.minutes, oLeft.seconds, oLeft.timezone); oValue.hours -= oRight.hours; oValue.minutes -= oRight.minutes; oValue.seconds -= oRight.seconds; // return fXSTime_normalize(oValue); }; function fOperator_compareTimes(oLeft, oRight, sComparator) { var nLeft = fOperator_time_toSeconds(oLeft), nRight = fOperator_time_toSeconds(oRight); return new cXSBoolean(sComparator == 'lt' ? nLeft < nRight : sComparator == 'gt' ? nLeft > nRight : nLeft == nRight); }; function fOperator_compareDates(oLeft, oRight, sComparator) { return fOperator_compareDateTimes(cXSDateTime.cast(oLeft), cXSDateTime.cast(oRight), sComparator); }; function fOperator_compareDateTimes(oLeft, oRight, sComparator) { // Adjust object time zone to Z and compare as strings var oTimezone = new cXSDayTimeDuration(0, 0, 0, 0), sLeft = fFunction_dateTime_adjustTimezone(oLeft, oTimezone).toString(), sRight = fFunction_dateTime_adjustTimezone(oRight, oTimezone).toString(); return new cXSBoolean(sComparator == 'lt' ? sLeft < sRight : sComparator == 'gt' ? sLeft > sRight : sLeft == sRight); }; function fOperator_addYearMonthDuration2DateTime(oLeft, oRight, sOperator) { var oValue; if (oLeft instanceof cXSDate) oValue = new cXSDate(oLeft.year, oLeft.month, oLeft.day, oLeft.timezone, oLeft.negative); else if (oLeft instanceof cXSDateTime) oValue = new cXSDateTime(oLeft.year, oLeft.month, oLeft.day, oLeft.hours, oLeft.minutes, oLeft.seconds, oLeft.timezone, oLeft.negative); // oValue.year = oValue.year + oRight.year * (sOperator == '-' ?-1 : 1); oValue.month = oValue.month + oRight.month * (sOperator == '-' ?-1 : 1); // fXSDate_normalize(oValue, true); // Correct day if out of month range var nDay = fXSDate_getDaysForYearMonth(oValue.year, oValue.month); if (oValue.day > nDay) oValue.day = nDay; // return oValue; }; function fOperator_addDayTimeDuration2DateTime(oLeft, oRight, sOperator) { var oValue; if (oLeft instanceof cXSDate) { oValue = new cXSDate(oLeft.year, oLeft.month, oLeft.day, oLeft.timezone, oLeft.negative); oValue.day = oValue.day + oRight.day * (sOperator == '-' ?-1 : 1); fXSDate_normalize(oValue); } else if (oLeft instanceof cXSDateTime) { oValue = new cXSDateTime(oLeft.year, oLeft.month, oLeft.day, oLeft.hours, oLeft.minutes, oLeft.seconds, oLeft.timezone, oLeft.negative); oValue.seconds = oValue.seconds + oRight.seconds * (sOperator == '-' ?-1 : 1); oValue.minutes = oValue.minutes + oRight.minutes * (sOperator == '-' ?-1 : 1); oValue.hours = oValue.hours + oRight.hours * (sOperator == '-' ?-1 : 1); oValue.day = oValue.day + oRight.day * (sOperator == '-' ?-1 : 1); fXSDateTime_normalize(oValue); } return oValue; }; // xs:dayTimeDuration to/from seconds function fOperator_dayTimeDuration_toSeconds(oDuration) { return (((oDuration.day * 24 + oDuration.hours) * 60 + oDuration.minutes) * 60 + oDuration.seconds) * (oDuration.negative ? -1 : 1); }; function fOperator_dayTimeDuration_fromSeconds(nValue) { var bNegative =(nValue = cMath.round(nValue)) < 0, nDays = ~~((nValue = cMath.abs(nValue)) / 86400), nHours = ~~((nValue -= nDays * 3600 * 24) / 3600), nMinutes= ~~((nValue -= nHours * 3600) / 60), nSeconds = nValue -= nMinutes * 60; return new cXSDayTimeDuration(nDays, nHours, nMinutes, nSeconds, bNegative); }; // xs:yearMonthDuration to/from months function fOperator_yearMonthDuration_toMonths(oDuration) { return (oDuration.year * 12 + oDuration.month) * (oDuration.negative ? -1 : 1); }; function fOperator_yearMonthDuration_fromMonths(nValue) { var nNegative =(nValue = cMath.round(nValue)) < 0, nYears = ~~((nValue = cMath.abs(nValue)) / 12), nMonths = nValue -= nYears * 12; return new cXSYearMonthDuration(nYears, nMonths, nNegative); }; // xs:time to seconds function fOperator_time_toSeconds(oTime) { return oTime.seconds + (oTime.minutes - (oTime.timezone != null ? oTime.timezone % 60 : 0) + (oTime.hours - (oTime.timezone != null ? ~~(oTime.timezone / 60) : 0)) * 60) * 60; };
exports.logger = (req, res, next) => { console.log(req.url); next(); };
var ws; function startWebsocket(wsOnMessage) { ws = new WebSocket("wss://"+location.hostname+(location.port ? ':'+location.port: '') + "/ws"); ws.onmessage = wsOnMessage; ws.onclose = function(evt) { console.log("Connection was closed. Reconnecting..."); setTimeout(startWebsocket(wsOnMessage), 3000); }; ws.onopen = function(evt) { console.log('opening websocket') }; } function showOkMessage(msg) { id = "msg" + new Date().getTime(); $(".content").prepend("<aside id='"+id+"' style='display: none;'>"+msg+"</aside>"); $("#"+id).slideDown("slow"); setTimeout(function(id) { console.log(id); $("#"+id).slideUp("slow", function() {$("#"+id).hide();} ); }, 5000, id); } var wsOnMessage = function(evt) { console.log("received:", evt.data); msg = JSON.parse(evt.data); if(msg.hasOwnProperty("error")) { if (msg.error == 123) window.location.href = '/login'; } else { if (msg.hasOwnProperty("newImageUrl")) { showOkMessage("<p>New image uploaded <a href='"+msg.newImageUrl+"'>here</a></p>"); } $("#"+msg.deviceId).effect("highlight", {color:"#1f8dd6"}, 500); $("#"+msg.deviceId+" .last-contact").text(msg.lastContact); $("#"+msg.deviceId+" .deviceCommands").show(); $("#"+msg.deviceId+" .deviceStatus").text("Online"); if (msg.hasOwnProperty("values")) { for(i=0; i<msg.values.length; i++) { $("#"+msg.deviceId+" .values [data-variable="+msg.values[i].id+"] .sensor-value").text(msg.values[i].value) } } } };
var Service = require('node-windows').Service; // Create a new service object var svc = new Service({ name: 'ioBroker', script: require('path').join(__dirname, 'controller.js') }); // Listen for the "uninstall" event so we know when it's done. svc.on('uninstall', function() { console.log('Uninstall complete.'); console.log('The service exists: ', svc.exists); }); // Uninstall the service. svc.uninstall();
import Ember from 'ember'; import StyleManagerMixin from 'ui-selectize/mixins/style-manager'; import { module, test } from 'qunit'; module('Unit | Mixin | style manager'); // Replace this with your real tests. test('it works', function(assert) { var StyleManagerObject = Ember.Object.extend(StyleManagerMixin); var subject = StyleManagerObject.create(); assert.ok(subject); });
/** * Module dependencies. */ var _ = require('lodash'), S = require('string'), fs = require('fs'), mkdirp = require('mkdirp'), request = require('request'), cheerio = require('cheerio'); // Process command line arguments var argv = require('minimist')(process.argv.slice(2)); // List of valid genres var genres = [ 'Action', 'Adventure', 'Animation', 'Comedy', 'Crime', 'Drama', 'Family', 'Fantasy', 'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Short', 'Thriller', 'War', 'Western' ]; // Set default genre and total number of scripts var genre = 'Action'; var total = 0; //Counter to stop when total is reached var totalCounter = 0; // Check if it's a valid genre and if a total number of scripts was given if (!argv.genre && !argv.total) console.log('Getting all the scripts for movies of ' + genre); else if(!argv.genre && argv.total){ total = argv.total; console.log('Getting ' + total + ' random scripts for movies of ' + genre); } else if (!_.contains(genres, argv.genre)) return console.log('Sorry, invalid genre.'); else { genre = argv.genre; if(argv.total){ total = argv.total; console.log('Getting ' + total + ' random scripts for movies of ' + genre); }else{ console.log('Getting all scripts for movies of ' + genre); } } // Get list of script URLs request('http://www.imsdb.com/feeds/genre.php?genre=' + genre, {rejectUnauthorized: false}, function (error, response, html) { if (error || response.statusCode !== 200) { console.log(error); return; } // RegEx URLs var pattern = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/ig; var urls = html.match(pattern) || []; // Validate if(urls.length === 0) return null; // Remove invalid script URLs var cleaned = _.remove(urls, function (url) { return S(url).contains('.html'); }); // Create directory if doesn't exist checkDirectory(function () { // Loop through script URLs cleaned.forEach(function (url, index, array) { console.log(url); // Call for every script URL saveScript(url); }); }); }); function saveScript (scriptURL) { //Randomly choosing if script shall be saved if (total != 0){ if(totalCounter == total) return; var totalRandomNumber = Math.floor((Math.random()*100)+1); if(totalRandomNumber % 3 != 0) return; // Don't save } // Request the script page request(scriptURL, {rejectUnauthorized: false}, function (error, response, html) { // Handle error if (error || response.statusCode !== 200) { console.log(error); return; } // Extract page contents var $ = cheerio.load(html); var script = $('table:nth-child(2)').text(); // Remove whitespace and extra text //script = S(script).collapseWhitespace(); script = script.replace('Search IMSDb',''); // Get a clean title var title = S($('title').text()).chompRight(' Script at IMSDb.').slugify().s; // Return if no script (probably TV episode, slightly different URL) if (script.length < 1) return; // Write to file fs.writeFile('scripts/' + genre + '/' + title + '.txt', script, function (err) { if (err) console.log(err); else console.log('Saved ' + title); }); //Increment total counter }); if(total != 0) ++totalCounter; } function checkDirectory (callback) { // Create directory if it doesn't exist fs.exists('scripts/' + genre + '/', function (exists) { if (!exists) { mkdirp('scripts/' + genre + '/', function (err) { if (err) return console.log('Failed to make directory for ' + genre); // Execute callback callback(); }); } // Execute callback callback(); }); };
'use strict'; var should = require('should'), request = require('supertest'), app = require('../../server'), mongoose = require('mongoose'), User = mongoose.model('User'), Scadaimage = mongoose.model('Scadaimage'), agent = request.agent(app); /** * Globals */ var credentials, user, scadaimage; /** * Scadaimage routes tests */ describe('Scadaimage CRUD tests', function() { beforeEach(function(done) { // Create user credentials credentials = { username: 'username', password: 'password' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new Scadaimage user.save(function() { scadaimage = { name: 'Scadaimage Name' }; done(); }); }); it('should be able to save Scadaimage instance if logged in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Scadaimage agent.post('/scadaimages') .send(scadaimage) .expect(200) .end(function(scadaimageSaveErr, scadaimageSaveRes) { // Handle Scadaimage save error if (scadaimageSaveErr) done(scadaimageSaveErr); // Get a list of Scadaimages agent.get('/scadaimages') .end(function(scadaimagesGetErr, scadaimagesGetRes) { // Handle Scadaimage save error if (scadaimagesGetErr) done(scadaimagesGetErr); // Get Scadaimages list var scadaimages = scadaimagesGetRes.body; // Set assertions (scadaimages[0].user._id).should.equal(userId); (scadaimages[0].name).should.match('Scadaimage Name'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save Scadaimage instance if not logged in', function(done) { agent.post('/scadaimages') .send(scadaimage) .expect(401) .end(function(scadaimageSaveErr, scadaimageSaveRes) { // Call the assertion callback done(scadaimageSaveErr); }); }); it('should not be able to save Scadaimage instance if no name is provided', function(done) { // Invalidate name field scadaimage.name = ''; agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Scadaimage agent.post('/scadaimages') .send(scadaimage) .expect(400) .end(function(scadaimageSaveErr, scadaimageSaveRes) { // Set message assertion (scadaimageSaveRes.body.message).should.match('Please fill Scadaimage name'); // Handle Scadaimage save error done(scadaimageSaveErr); }); }); }); it('should be able to update Scadaimage instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Scadaimage agent.post('/scadaimages') .send(scadaimage) .expect(200) .end(function(scadaimageSaveErr, scadaimageSaveRes) { // Handle Scadaimage save error if (scadaimageSaveErr) done(scadaimageSaveErr); // Update Scadaimage name scadaimage.name = 'WHY YOU GOTTA BE SO MEAN?'; // Update existing Scadaimage agent.put('/scadaimages/' + scadaimageSaveRes.body._id) .send(scadaimage) .expect(200) .end(function(scadaimageUpdateErr, scadaimageUpdateRes) { // Handle Scadaimage update error if (scadaimageUpdateErr) done(scadaimageUpdateErr); // Set assertions (scadaimageUpdateRes.body._id).should.equal(scadaimageSaveRes.body._id); (scadaimageUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of Scadaimages if not signed in', function(done) { // Create new Scadaimage model instance var scadaimageObj = new Scadaimage(scadaimage); // Save the Scadaimage scadaimageObj.save(function() { // Request Scadaimages request(app).get('/scadaimages') .end(function(req, res) { // Set assertion res.body.should.be.an.Array.with.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single Scadaimage if not signed in', function(done) { // Create new Scadaimage model instance var scadaimageObj = new Scadaimage(scadaimage); // Save the Scadaimage scadaimageObj.save(function() { request(app).get('/scadaimages/' + scadaimageObj._id) .end(function(req, res) { // Set assertion res.body.should.be.an.Object.with.property('name', scadaimage.name); // Call the assertion callback done(); }); }); }); it('should be able to delete Scadaimage instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Scadaimage agent.post('/scadaimages') .send(scadaimage) .expect(200) .end(function(scadaimageSaveErr, scadaimageSaveRes) { // Handle Scadaimage save error if (scadaimageSaveErr) done(scadaimageSaveErr); // Delete existing Scadaimage agent.delete('/scadaimages/' + scadaimageSaveRes.body._id) .send(scadaimage) .expect(200) .end(function(scadaimageDeleteErr, scadaimageDeleteRes) { // Handle Scadaimage error error if (scadaimageDeleteErr) done(scadaimageDeleteErr); // Set assertions (scadaimageDeleteRes.body._id).should.equal(scadaimageSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete Scadaimage instance if not signed in', function(done) { // Set Scadaimage user scadaimage.user = user; // Create new Scadaimage model instance var scadaimageObj = new Scadaimage(scadaimage); // Save the Scadaimage scadaimageObj.save(function() { // Try deleting Scadaimage request(app).delete('/scadaimages/' + scadaimageObj._id) .expect(401) .end(function(scadaimageDeleteErr, scadaimageDeleteRes) { // Set message assertion (scadaimageDeleteRes.body.message).should.match('User is not logged in'); // Handle Scadaimage error error done(scadaimageDeleteErr); }); }); }); afterEach(function(done) { User.remove().exec(); Scadaimage.remove().exec(); done(); }); });
/** * @fileOverview Kansas logger facilities. */ var chai = require('chai'); var expect = chai.expect; var kansas = require('../..'); describe('Logger', function() { it('Will emit "message" events', function(done) { function onMessage(msgObj) { // Sample Object // // { // level: 200, // name: 'kansas.main.redis', // meta: undefined, // rawArgs: // [ 'getClient() :: Creating client using host, port:', // 'localhost', // 6379 ], // date: Sat Mar 01 2014 19:14:47 GMT+0200 (EET), // message: 'getClient() :: Creating client using host, port: localhost 6379' // } expect(msgObj).to.be.an('Object'); expect(msgObj).to.have.property('level'); expect(msgObj).to.have.property('name'); expect(msgObj).to.have.property('date'); expect(msgObj).to.have.property('message'); } var api = kansas({console: false}); api.on('message', onMessage); api.connect().then(function() { api.removeListener('message', onMessage); done(); }).catch(done); }); it('Will not emit any "message" events if logging is off', function(done) { var api = kansas({logging: false}); api.on('message', done); api.connect().then(function() { api.removeListener('message', done); done(); }).catch(done); }); });
const Dog = require('../models/dog'); exports.postDogs = function(req, res) { console.log(req.body.image); const dog = new Dog(); dog.name = req.body.name; dog.merits = req.body.merits; if (!req.body.image) { dog.image = 'http://image.spreadshirtmedia.com/image-server/v1/designs/12337518,width=200,height=200'; } else { dog.image = 'http://image.spreadshirtmedia.com/image-server/v1/designs/12337518,width=200,height=200'; } console.log(dog); dog.save(function(err) { if (err) res.send(err); res.json({ message: 'dog added !', data: dog }); }); }; exports.getDogs = function(req, res) { Dog.find(function(err, dogs) { if (err) res.send(err); res.json(dogs); }); }; exports.getDog = function(req, res) { Dog.findById(req.params.dog_id, function(err, dog) { if (err) res.send(err); res.json(dog); }); }; exports.putDog = function(req, res) { Dog.findById(req.params.dog_id, function(err, dog) { if (err) res.send(err); dog.image = req.body.image; dog.save(function(errs) { if (err) res.send(errs); res.json(dog); }); }); }; exports.deleteDog = function(req, res) { Dog.findByIdAndRemove(req.params.dog_id, function(err) { if (err) res.send(err); res.json({ message: 'Deleted!' }); }); };
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * StoppagesEntry Schema */ var StoppagesEntrySchema = new Schema({ date: { type: Date, required: 'Please fill date name' }, shift: { type: String, required: 'Please fill shift name' }, machineCode: { type: Number, required: 'Please fill machineCode name' }, stoppageReason: { type: String, required: 'Please fill stoppageReason name' }, stopInMinutes: { type: Number, required: 'Please fill stopInMinutes name' }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('StoppagesEntry', StoppagesEntrySchema);
mix.declare("mix.coll.MultiMap", ["mix.Utils", "mix.Detector", "mix.Constants"], function(Utils, Detector, Constants) { "use strict"; var isSymbolAvailable = Detector.symbol.has("for"); var hashSymbol = isSymbolAvailable ? window.Symbol.for("_hash_") : "_hash_"; var hashFn = isSymbolAvailable ? window.Symbol.for("_hashFn_") : "_hashFn_"; var bucketsCount = isSymbolAvailable ? window.Symbol.for("_bucketsCount_") : "_bucketsCount_"; var valuesCount = isSymbolAvailable ? window.Symbol.for("_valuesCount_") : "_valuesCount_"; var iteratorSymbol = Detector.symbol.iterator ? window.Symbol.iterator : "@@iterator"; function hashCode(o) { return o; } function MultiMap(hashCodeFn) { this[hashFn] = Utils.isFunction(hashCodeFn) ? hashCodeFn : hashCode; this[hashSymbol] = {}; this[bucketsCount] = 0; this[valuesCount] = 0; } MultiMap.prototype.hash = function hash() { return this[hashSymbol]; }; MultiMap.prototype.key = function key(k) { return this[hashFn](k); }; MultiMap.prototype.add = function add(k, v) { "use strict"; var key = this.key(k); var hash = this.hash(); var bucket = hash[key]; if(bucket === undefined) { hash[key] = bucket = []; this[bucketsCount] += 1; } if(arguments.length > 2) { for(var i = 0, o = bucket.length, l = arguments.length; i < l; i++) { bucket[i + o] = arguments[1 + i]; } this[valuesCount] += (l - 1); } else { bucket[bucket.length] = v; this[valuesCount] += 1; } return this; }; /** * Iterates over all elements in this map * @param fn a function(value, key, map) * @param thisArg to be used as <b>this</b> for callback call * @returns {MultiMap} this */ MultiMap.prototype.forEach = function forEach(fn, thisArg) { Utils.awaitFunction(fn); var hash = this.hash(); for(var k in hash) { fn.call(thisArg, hash[k], k, this); } return this; }; MultiMap.prototype.set = function set(k, v) { "use strict"; var key = this.key(k); var hash = this.hash(); var bucket = hash[key]; v = Utils.isArray(v) ? v : [v]; var diff = v.length; if(bucket !== undefined) { diff -= bucket.length; } else { this[bucketsCount] += 1; } hash[key] = v; this[valuesCount] += diff; return this; }; MultiMap.prototype.get = function get(k) { "use strict"; var key = this.key(k); var hash = this.hash(); var bucket = hash[key]; return bucket || Constants.EMPTY_ARRAY; }; MultiMap.prototype["delete"] = function(k) { "use strict"; var key = this.key(k); var hash = this.hash(); var bucket = hash[key]; if(bucket !== undefined) { delete hash[key]; this[valuesCount] -= bucket.length; this[bucketsCount] -= 1; return true; } return false; }; MultiMap.prototype.entries = MultiMap.prototype[iteratorSymbol] = function entries() { "use strict"; var index = 0; var hash = this.hash(); var keys = Object.keys(hash); var iter = { next: function EntryInterator() { var done = index >= keys.length; return { done: done, value: done ? undefined : [keys[index], hash[keys[index++]]] }; } }; iter[iteratorSymbol] = function() { return iter; }; return iter; }; MultiMap.prototype.keys = function keys() { "use strict"; var index = 0; var hash = this.hash(); var keys = Object.keys(hash); var iter = { next: function KeyIterator() { var done = index >= keys.length; return { done: done, value: done ? undefined : keys[index++] }; } }; iter[iteratorSymbol] = function() { return iter; }; return iter; }; MultiMap.prototype.values = function values() { "use strict"; var index = 0; var hash = this.hash(); var keys = Object.keys(hash); var iter = { next: function ValueIterator() { var done = index >= keys.length; return { done: done, value: done ? undefined : hash[keys[index++]] }; } }; iter[iteratorSymbol] = function() { return iter; }; return iter; }; MultiMap.prototype.has = function has(k) { "use strict"; return this.key(k) in this.hash(); }; MultiMap.prototype.clear = function clear() { "use strict"; var hash = this.hash(); for(var k in hash) { delete hash[k]; } this[valuesCount] = this[bucketsCount] = 0; return this; }; MultiMap.prototype.toString = function toString() { return "[object MultiMap]"; }; MultiMap.prototype.clone = function clone() { var hash = this.hash(); var c = new MultiMap(this[hashFn]); for(var k in hash) { c.set(k, hash[k].concat()); } return c; }; Object.defineProperty(MultiMap.prototype, "size", { get: function size() { "use strict"; return this[bucketsCount]; } }); Object.defineProperty(MultiMap.prototype, "count", { get: function count() { "use strict"; return this[valuesCount]; } }); return MultiMap; });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _rcNotification = require('rc-notification'); var _rcNotification2 = _interopRequireDefault(_rcNotification); var _icon = require('../icon'); var _icon2 = _interopRequireDefault(_icon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var defaultTop = 24; var notificationInstance = void 0; var defaultDuration = 4.5; function getNotificationInstance() { if (notificationInstance) { return notificationInstance; } notificationInstance = _rcNotification2["default"].newInstance({ prefixCls: 'ant-notification', style: { top: defaultTop, right: 0 } }); return notificationInstance; } function notice(args) { var prefixCls = args.prefixCls || 'ant-notification-notice'; var duration = void 0; if (args.duration === undefined) { duration = defaultDuration; } else { duration = args.duration; } var iconType = ''; switch (args.icon) { case 'success': iconType = 'check-circle-o'; break; case 'info': iconType = 'info-circle-o'; break; case 'error': iconType = 'cross-circle-o'; break; case 'warning': iconType = 'exclamation-circle-o'; break; default: iconType = 'info-circle'; } getNotificationInstance().notice({ content: _react2["default"].createElement( 'div', { className: prefixCls + '-content ' + (args.icon ? prefixCls + '-with-icon' : '') }, args.icon ? _react2["default"].createElement(_icon2["default"], { className: prefixCls + '-icon ' + prefixCls + '-icon-' + args.icon, type: iconType }) : null, _react2["default"].createElement( 'div', { className: prefixCls + '-message' }, args.message ), _react2["default"].createElement( 'div', { className: prefixCls + '-description' }, args.description ), args.btn ? _react2["default"].createElement( 'span', { className: prefixCls + '-btn' }, args.btn ) : null ), duration: duration, closable: true, onClose: args.onClose, key: args.key, style: {} }); } var api = { open: function open(args) { notice(args); }, close: function close(key) { if (notificationInstance) { notificationInstance.removeNotice(key); } }, config: function config(options) { if ('top' in options) { defaultTop = options.top; } if ('duration' in options) { defaultDuration = options.duration; } }, destroy: function destroy() { if (notificationInstance) { notificationInstance.destroy(); notificationInstance = null; } } }; ['success', 'info', 'warning', 'error'].forEach(function (type) { api[type] = function (args) { return api.open(_extends({}, args, { icon: type })); }; }); api.warn = api.warning; exports["default"] = api; module.exports = exports['default'];
'use strict'; const _ = require('lodash'); const path = require('path'); const logger = require('./log'); let fs = require('fs-extra'); // eslint-disable-line module.exports = (incrementalBuildsEnabled, patternlab) => { const paths = patternlab.config.paths; if (incrementalBuildsEnabled) { logger.info('Incremental builds enabled.'); return Promise.resolve(); } else { return Promise.all( _.map(patternlab.uikits, (uikit) => { return fs.emptyDir( path.join(process.cwd(), uikit.outputDir, paths.public.patterns) ); }) ).catch((reason) => { logger.error(reason); }); } };