code
stringlengths
2
1.05M
/* * script-analyze * https://github.com/makepanic/script-analyze * * Copyright (c) 2013 Christian * Licensed under the MIT license. */ 'use strict'; var provider = require('./provider/csvProvider'), analyze = require('./analyze/analyze'); exports.loadList = function(path) { return provider(path); }; exports.analyze = function(data, analyzedOne){ return analyze(data, analyzedOne); };
export * from './Button'; export * from './Card'; export * from './CardSection'; export * from './Header'; export * from './Spinner'; export * from './TextInputBox';
'use strict'; var createPointCloudRenderer = require('gl-pointcloud2d'); var str2RGBArray = require('../../lib/str2rgbarray'); var findExtremes = require('../../plots/cartesian/autorange').findExtremes; var getTraceColor = require('../scatter/get_trace_color'); function Pointcloud(scene, uid) { this.scene = scene; this.uid = uid; this.type = 'pointcloud'; this.pickXData = []; this.pickYData = []; this.xData = []; this.yData = []; this.textLabels = []; this.color = 'rgb(0, 0, 0)'; this.name = ''; this.hoverinfo = 'all'; this.idToIndex = new Int32Array(0); this.bounds = [0, 0, 0, 0]; this.pointcloudOptions = { positions: new Float32Array(0), idToIndex: this.idToIndex, sizemin: 0.5, sizemax: 12, color: [0, 0, 0, 1], areaRatio: 1, borderColor: [0, 0, 0, 1] }; this.pointcloud = createPointCloudRenderer(scene.glplot, this.pointcloudOptions); this.pointcloud._trace = this; // scene2d requires this prop } var proto = Pointcloud.prototype; proto.handlePick = function(pickResult) { var index = this.idToIndex[pickResult.pointId]; // prefer the readout from XY, if present return { trace: this, dataCoord: pickResult.dataCoord, traceCoord: this.pickXYData ? [this.pickXYData[index * 2], this.pickXYData[index * 2 + 1]] : [this.pickXData[index], this.pickYData[index]], textLabel: Array.isArray(this.textLabels) ? this.textLabels[index] : this.textLabels, color: this.color, name: this.name, pointIndex: index, hoverinfo: this.hoverinfo }; }; proto.update = function(options) { this.index = options.index; this.textLabels = options.text; this.name = options.name; this.hoverinfo = options.hoverinfo; this.bounds = [Infinity, Infinity, -Infinity, -Infinity]; this.updateFast(options); this.color = getTraceColor(options, {}); }; proto.updateFast = function(options) { var x = this.xData = this.pickXData = options.x; var y = this.yData = this.pickYData = options.y; var xy = this.pickXYData = options.xy; var userBounds = options.xbounds && options.ybounds; var index = options.indices; var len; var idToIndex; var positions; var bounds = this.bounds; var xx, yy, i; if(xy) { positions = xy; // dividing xy.length by 2 and truncating to integer if xy.length was not even len = xy.length >>> 1; if(userBounds) { bounds[0] = options.xbounds[0]; bounds[2] = options.xbounds[1]; bounds[1] = options.ybounds[0]; bounds[3] = options.ybounds[1]; } else { for(i = 0; i < len; i++) { xx = positions[i * 2]; yy = positions[i * 2 + 1]; if(xx < bounds[0]) bounds[0] = xx; if(xx > bounds[2]) bounds[2] = xx; if(yy < bounds[1]) bounds[1] = yy; if(yy > bounds[3]) bounds[3] = yy; } } if(index) { idToIndex = index; } else { idToIndex = new Int32Array(len); for(i = 0; i < len; i++) { idToIndex[i] = i; } } } else { len = x.length; positions = new Float32Array(2 * len); idToIndex = new Int32Array(len); for(i = 0; i < len; i++) { xx = x[i]; yy = y[i]; idToIndex[i] = i; positions[i * 2] = xx; positions[i * 2 + 1] = yy; if(xx < bounds[0]) bounds[0] = xx; if(xx > bounds[2]) bounds[2] = xx; if(yy < bounds[1]) bounds[1] = yy; if(yy > bounds[3]) bounds[3] = yy; } } this.idToIndex = idToIndex; this.pointcloudOptions.idToIndex = idToIndex; this.pointcloudOptions.positions = positions; var markerColor = str2RGBArray(options.marker.color); var borderColor = str2RGBArray(options.marker.border.color); var opacity = options.opacity * options.marker.opacity; markerColor[3] *= opacity; this.pointcloudOptions.color = markerColor; // detect blending from the number of points, if undefined // because large data with blending hits performance var blend = options.marker.blend; if(blend === null) { var maxPoints = 100; blend = x.length < maxPoints || y.length < maxPoints; } this.pointcloudOptions.blend = blend; borderColor[3] *= opacity; this.pointcloudOptions.borderColor = borderColor; var markerSizeMin = options.marker.sizemin; var markerSizeMax = Math.max(options.marker.sizemax, options.marker.sizemin); this.pointcloudOptions.sizeMin = markerSizeMin; this.pointcloudOptions.sizeMax = markerSizeMax; this.pointcloudOptions.areaRatio = options.marker.border.arearatio; this.pointcloud.update(this.pointcloudOptions); // add item for autorange routine var xa = this.scene.xaxis; var ya = this.scene.yaxis; var pad = markerSizeMax / 2 || 0.5; options._extremes[xa._id] = findExtremes(xa, [bounds[0], bounds[2]], {ppad: pad}); options._extremes[ya._id] = findExtremes(ya, [bounds[1], bounds[3]], {ppad: pad}); }; proto.dispose = function() { this.pointcloud.dispose(); }; function createPointcloud(scene, data) { var plot = new Pointcloud(scene, data.uid); plot.update(data); return plot; } module.exports = createPointcloud;
version https://git-lfs.github.com/spec/v1 oid sha256:9a2347f894a613431f6e4463d2367747337be183d8e837f8b4dfb9b63465830f size 80662
'use strict'; var gulp = require('gulp'), install = require('gulp-install'), conflict = require('gulp-conflict'), template = require('gulp-template'), rename = require('gulp-rename'), inquirer = require('inquirer'); var debug = require('gulp-debug'); var defaultQuestions = require('./questions'); var transformDefault = require('./transforms'); function DefaultTask(options) { function defaultTask(cb) { function scaffold(answers) { var answers = transformDefault.map(answers); function renameFiles(file) { if (file.basename[0] === '_') { file.basename = '.' + file.basename.slice(1); } } if (!answers.moveon) { return cb(); } gulp .src(options.templatesDir + '/default/**') .pipe(template(answers)) .pipe(rename(renameFiles)) //.pipe(conflict('./')) .pipe(gulp.dest('./')) .pipe(install()) .on('finish', cb); } //Ask inquirer.prompt(defaultQuestions, scaffold); } gulp.task('default', defaultTask); return gulp; } module.exports = DefaultTask;
class ColorChangingLine extends Polygon { constructor(length) { super([ new Line(new Point(-length, 0), new Point(length, 0), ColorMapper.randomColor()) ]); this.MAX_ITERATIONS = 120; this.iteration = 0; } draw(canvas) { if (this.iteration > this.MAX_ITERATIONS) { this.iteration = 1; this.lines[0].color = ColorMapper.randomColor(); } this.iteration++; super.draw(canvas); } }
exports.session_path = __home + '/session'; exports.start = function (server, callback) { if (require('fs').existsSync(exports.session_path) == false) require('fs').mkdirSync(exports.session_path); var conf = server.vhost.middleware; if (!conf.session) conf.session = {}; if (!conf.session.expired) conf.session.expired = '1w'; if (typeof conf.session.expired == 'string') { conf.session.expired = conf.session.expired.replace('s', '*1000*'); conf.session.expired = conf.session.expired.replace('m', '*60*1000*'); conf.session.expired = conf.session.expired.replace('h', '*60*60*1000*'); conf.session.expired = conf.session.expired.replace('d', '*24*60*60*1000*'); conf.session.expired = conf.session.expired.replace('w', '*7*24*60*60*1000*'); if (!conf.session.host) conf.session.host = server.hostname; var tmp = conf.session.expired.split('*'); conf.session.expired = 1; for (var i = 0; i < tmp.length; i++) conf.session.expired *= (tmp[i].length > 0 ? tmp[i] : '1'); } var cookies = server.cookies; var uuid = cookies.uuid; var session = checkUUID(server); var sessionFilePath = exports.session_path + '/' + uuid + ".json"; session.set = function (key, val) { session.storage[key] = val; require('fs').writeFileSync( sessionFilePath, JSON.stringify(session) ); }; session.get = function (key) { return session.storage[key]; }; session.del = function (key) { delete session.storage[key]; require('fs').writeFileSync(sessionFilePath, JSON.stringify(session)); }; callback(session); } var checkUUID = function (server) { var sessionInfo = {} var sessionhost = ''; if (server.vhost.middleware.session.host) sessionhost = server.vhost.middleware.session.host; else sessionhost = server.hostname; var preUUID = server.cookies.uuid; if (preUUID != null && require('fs').existsSync(exports.session_path + '/' + preUUID + '.json')) { sessionInfo = JSON.parse(require('fs').readFileSync(exports.session_path + '/' + preUUID + '.json')); if (sessionInfo.host == sessionhost) { var sessionDate = new Date(sessionInfo.date); var now = new Date(); var diff = now - sessionDate; if (diff < server.vhost.middleware.session.expired) { sessionInfo.date = new Date().toString(); require('fs').writeFileSync(exports.session_path + '/' + preUUID + '.json', JSON.stringify(sessionInfo)); return JSON.parse(require('fs').readFileSync(exports.session_path + '/' + preUUID + '.json')); } else { require('fs').unlinkSync(exports.session_path + '/' + preUUID + '.json', JSON.stringify(sessionInfo)); } } } var uuid = require('node-uuid').v4(); while (require('fs').existsSync(exports.session_path + '/' + uuid + '.json') == true) uuid = require('node-uuid').v4(); sessionInfo.uuid = uuid; sessionInfo.host = sessionhost; sessionInfo.port = server.port; sessionInfo.date = new Date().toString(); sessionInfo.expired = server.vhost.middleware.session.expired; sessionInfo.storage = {}; require('fs').writeFileSync(exports.session_path + '/' + uuid + '.json', JSON.stringify(sessionInfo)); server.response.setHeader("Set-Cookie", ['uuid=' + uuid + '; Domain=' + sessionInfo.host + '; Path=/']); return sessionInfo; }
function propertySelected(value) { $('#displayProperty').text(value); $.ajax({ url : '/dashboard/__breakdown/' + value, type : 'GET', success : function(response) { console.log(JSON.parse(response)) populateTable(JSON.parse(response)); }, failure : function(response) { console.log(response); } }); } function populateTable(groups) { var $table = $('#table'); var $input = $('#submit'); var keys = Object.keys(groups).sort(); $table.empty(); $table.append("<th>Property<td>Number of Hackers</td></th>"); for (var i = 0; i < keys.length; i++) { var $row = $('<tr class="property-value"><td class="prop">' + keys[i] + '</td><td class="count">' + groups[keys[i]] + '</td></tr>'); $row.click(function() { $(this).toggleClass("selected"); $input.prop('disabled', !$table.has('.selected').length); }); $table.append($row); } } function cleanup() { var property = $('#property-selector').val(); var replacedValues = {}; var newValue = $('#newValue').val(); $('#table').find('.selected .prop').each(function(index, elt) { replacedValues[elt.innerHTML] = newValue; }); var $display = $('#display'); function showStatus(success, msg) { $display.toggleClass('success', success); $display.toggleClass('failure', !success); if (msg) { $display.text(msg); } } if (!newValue) { showStatus(false, "You must input a replacement string"); return; } if (!property) { showStatus(false, "You must choose a property"); return; } data = { "property" : property, "jsonKeys" : replacedValues }; $.ajax({ url : '/dashboard/__cleanup', type : 'POST', data : JSON.stringify(data), success: function(response) { response = JSON.parse(response); showStatus(response.success, response.msg); }, failure: function() { showStatus(false, "Server Error"); } }); }
'use strict'; const ipc = require('ipc'); const renderBadge = require('./render-badge'); let notificationCounter = 0; module.exports = () => { //require('electron-notification-shim')(); const OldNotification = Notification; Notification = function (title, options) { // Send this to main thread. // Catch it in your main 'app' instance with `ipc.on`. // Then send it back to the view, if you want, with `event.returnValue` or `event.sender.send()`. notificationCounter++; let opts = { body: '', data: null, dir: 'auto', icon: '', lang: '', onclick: null, onclose: null, onerror: null, onshow: null, silent: false, tag: '', title, badge: renderBadge(notificationCounter.toString()), count: notificationCounter }; // Send the native Notification. // You can't catch it, that's why we're doing all of this. :) console.log('innan', opts); opts = Object.assign(opts, options); ipc.send('notification-shim', opts); console.log('efter', opts); return opts; //return new OldNotification(title, options); }; Notification.prototype = OldNotification.prototype; Notification.permission = OldNotification.permission; Notification.requestPermission = OldNotification.requestPermission; ipc.on('reset-notifications', () => notificationCounter = 0); };
/* * img-stats * https://github.com/jlembeck/img-stats * * Copyright (c) 2013 Jeffrey Lembeck * Licensed under the MIT license. */ /*global require:true, console:true*/ (function(exports) { "use strict"; var fs = require( 'fs' ); var isPng = function( data ){ var d = data.slice(0, 16); return d === "89504e470d0a1a0a"; }; var isSVG = function( data ){ for( var i=0, l = data.length; i < l; i++ ){ var d = data.slice(i, i+2).toString( 'hex' ); if( d === "73" ){ i=i+2; d = data.slice( i, i+2 ).toString( 'hex' ); if( d === "76" ){ i=i+2; d = data.slice( i, i+2 ).toString( 'hex' ); if( d === "67" ){ return true; } } } } return false; }; var getDimensions = function( data ){ var ret={} ,i=8; for( var l = data.length; i < l; i++ ){ var d = data.slice(i, i+4).toString( 'hex' ); if( d === "49484452" ){ i = i+4; break; } } ret.width = parseInt(data.slice( i, i+4 ).toString( 'hex' ) , 16 ); i = i+4; ret.height = parseInt(data.slice( i, i+4 ).toString( 'hex' ) , 16 ); return ret; }; var padHexStringToTwoDigits = function( num ) { return ( num.length === 1 ? "0" : "" ) + num; }; exports.stats = function( filename , callback ) { var ret = {}; if( !filename ){ throw new Error("Needs a filename"); } var data, hexData = [], hexString = ""; if( fs.readFileSync ) { data = fs.readFileSync( filename ); hexString = data.toString( "hex" ); } else { // PhantomJS compatible data = fs.open( filename, "r+b" ).read(); for(var j=0, k=data.length; j<k; j++) { hexData.push( padHexStringToTwoDigits( data.charCodeAt(j).toString(16) )); } hexString = hexData.join(""); } if( isPng( hexString ) ){ var i = 16, l; for( l = hexString.length; i < l; i++ ){ var d = hexString.slice(i, i+8); if( d === "49484452" ){ i = i+8; break; } } ret.width = parseInt(hexString.slice( i, i+8 ).toString( 16 ) , 16 ); i = i+8; ret.height = parseInt(hexString.slice( i, i+8 ).toString( 16 ) , 16 ); ret.type = "PNG"; } else if( isSVG( hexString ) ){ ret.type = "SVG"; } callback( ret ); }; }(typeof exports === 'object' && exports || this));
import React, {Component} from 'react'; import ReactDOMServer from 'react-dom/server' import counterpart from 'counterpart'; import mapboxgl from 'mapbox-gl'; import PropTypes from 'prop-types'; import SatelliteControl from './map/satellite-control'; import CameraControl from './map/camera-control'; class Map extends Component { getChildContext() { return {map: this.map}; } mapId() { return `map${this.props.mapIndex || ""}`; } mapClass() { let className = "map" if (this.props.mapIndex == 0) className = className + " left"; if (this.props.mapIndex == 1) className = className + " right"; return className; } mapStyle(props) { if (props.mapStyle == 'satellite') { return (new SatelliteControl).styles.satellite; } else { return props.mapboxStyle; } } setMap(props) { const mapStyle = this.mapStyle(props); mapboxgl.accessToken = props.mapboxAccessToken; this.map = new mapboxgl.Map({ container: this.mapId(), style: mapStyle, center: props.center, zoom: props.zoom, bearing: props.bearing, pitch: props.pitch, preserveDrawingBuffer: true, customAttribution: `<a href="/terms">${counterpart('terms.title')}</a> | &copy; Citylines.co contributors` }); this.map.addControl(new mapboxgl.NavigationControl()); this.map.addControl(new SatelliteControl({ defaultStyle: props.mapboxStyle, currentStyle: mapStyle, onStyleChange: this.props.onSatelliteToggle })); this.map.addControl(new CameraControl({ onClick: this.props.onCameraClick })); this.map.on('moveend', () => { if (typeof props.onMove === 'function') props.onMove(this.map); }); this.map.on('load', () => { this.mapLoaded = true; this.forceUpdate(); if (typeof props.onLoad === 'function') props.onLoad(this.map); }); this.map.on("mousemove", (e) => { if (this.props.disableMouseEvents) return; const point = [e.point.x,e.point.y]; const features = this.queryRenderedFeatures(point); const lngLat = [e.lngLat.lng, e.lngLat.lat] this.map.getCanvas().style.cursor = features.length ? 'pointer' : ''; if (typeof this.props.onMouseMove === 'function') this.props.onMouseMove(lngLat, features); }); this.map.on('click', (e) => { if (this.props.disableMouseEvents) return; const point = [e.point.x,e.point.y]; const features = this.queryRenderedFeatures(point); const lngLat = [e.lngLat.lng, e.lngLat.lat] if (typeof this.props.onMouseClick === 'function') this.props.onMouseClick(lngLat, features); }); } // taken/inspired from https://docs.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/ getUniqueFeatures(array) { const existingFeatureKeys = {}; // Because features come from tiled vector data, feature geometries may be split // or duplicated across tile boundaries and, as a result, features may appear // multiple times in query results. const uniqueFeatures = array.filter((el) => { const key = el.properties.klass + '-' + el.properties.id; if (existingFeatureKeys[key]) { return false; } else { existingFeatureKeys[key] = true; return true; } }); return uniqueFeatures; } queryRenderedFeatures(point){ const features = this.map.queryRenderedFeatures(point, {layers: this.props.mouseEventsLayerNames}); return this.getUniqueFeatures(features); } componentDidMount(){ if (this.props.center && !this.map) { this.setMap(this.props); } } componentWillUnmount() { if (this.map) { this.map.remove(); this.map.removed = true; } } UNSAFE_componentWillReceiveProps(nextProps) { if (nextProps.center && !this.map) { this.setMap(nextProps); } else if (nextProps.center && nextProps.center != this.props.center && JSON.stringify(nextProps.center) != JSON.stringify(this.props.center)) { let current = this.map.getCenter().wrap(); current = [current.lng.toFixed(6), current.lat.toFixed(6)]; if (JSON.stringify(nextProps.center) != JSON.stringify(current)) { this.map.flyTo({center: nextProps.center}); } } if (nextProps.zoom && nextProps.zoom != this.props.zoom) { if (this.map.getZoom().toFixed(2) != nextProps.zoom) { this.map.flyTo({zoom: nextProps.zoom}); } } } render() { return ( <div className={this.mapClass()}> <div id={this.mapId()} className="map"></div> { this.mapLoaded && this.props.children } </div> ) } } Map.childContextTypes = { map: PropTypes.object } class Source extends Component { constructor(props, context) { super(props, context); this.map = context.map; this.load(); } componentWillUnmount(){ if (this.map.removed) { return; } this.props.layers.map(layer => this.map.removeLayer(layer.id) ); this.map.removeSource(this.props.name); } load() { this.map.addSource(this.props.name, { type: 'geojson', data: this.props.data }); } render() { return ( <div> { this.props.layers && this.props.layers.map(layer => <Layer key={layer.id} id={layer.id} map={this.context.map} source={this.props.name} type={layer.type} paint={layer.paint} filter={layer.filter} /> ) } </div> ) } } Source.contextTypes = { map: PropTypes.object } class Layer extends Component { componentDidMount(){ this.map = this.props.map; this.load(); } UNSAFE_componentWillReceiveProps(nextProps, nextContext) { if (nextProps.filter && nextProps.filter !== this.props.filter) { this.map.setFilter(this.props.id, nextProps.filter); } } load() { this.map.addLayer({ id: this.props.id, source: this.props.source, type: this.props.type, paint: this.props.paint }); this.map.setFilter(this.props.id, this.props.filter); } shouldComponentUpdate() { return false; } render() { return null; } } class Popup extends Component { componentDidMount() { this.map = this.context.map; this.load(this.props); } UNSAFE_componentWillReceiveProps(nextProps) { if (nextProps.point != this.props.point) { this.load(nextProps); } } load(props) { this.popup = new mapboxgl.Popup() .setLngLat(props.point) .setHTML(ReactDOMServer.renderToStaticMarkup(props.children)) .addTo(this.map) .on('close', () => { if (typeof props.onClose === 'function') props.onClose(); }); } shouldComponentUpdate() { return false; } render() { return null; } } Popup.contextTypes = { map: PropTypes.object } export {Map, Source, Popup};
var Definition = require('../definitionBase'), util = require('util'), _ = require('lodash'), dotty = require('dotty'), debug = require('debug')('denormalizer:eventExtender'); /** * EventExtender constructor * @param {Object} meta Meta infos like: { name: 'name', version: 1, payload: 'some.path' } * @param {Function || String} evtExtFn Function handle * `function(evt, col, callback){}` * @constructor */ function EventExtender (meta, evtExtFn) { Definition.call(this, meta); meta = meta || {}; if (!evtExtFn || !(_.isFunction(evtExtFn))) { var err = new Error('extender function not injected!'); debug(err); throw err; } this.version = meta.version || 0; this.aggregate = meta.aggregate || null; this.context = meta.context || null; this.payload = meta.payload || null; this.id = meta.id || null; this.evtExtFn = evtExtFn; } util.inherits(EventExtender, Definition); _.extend(EventExtender.prototype, { /** * Injects the needed collection. * @param {Object} collection The collection object to inject. */ useCollection: function (collection) { if (!collection || !_.isObject(collection)) { var err = new Error('Please pass a valid collection!'); debug(err); throw err; } this.collection = collection; }, /** * Loads the appropriate viewmodel by id. * @param {String} id The viewmodel id. * @param {Function} callback The function that will be called when this action has finished * `function(err, vm){}` */ loadViewModel: function (id, callback) { this.collection.loadViewModel(id, callback); }, /** * Loads a viewModel array by optional query and query options. * @param {Object} query The query to find the viewModels. (mongodb style) [optional] * @param {Object} queryOptions The query options. (mongodb style) [optional] * @param {Function} callback The function, that will be called when the this action is completed. * `function(err, vms){}` vms is of type Array. */ findViewModels: function (query, queryOptions, callback) { if (typeof query === 'function') { callback = query; query = {}; queryOptions = {}; } if (typeof queryOptions === 'function') { callback = queryOptions; queryOptions = {}; } this.collection.findViewModels(query, queryOptions, callback); }, /** * Extracts the id from the event or generates a new one. * @param {Object} evt The event object. * @param {Function} callback The function that will be called when this action has finished * `function(err, id){}` */ extractId: function (evt, callback) { if (this.id && dotty.exists(evt, this.id)) { debug('found viewmodel id in event'); return callback(null, dotty.get(evt, this.id)); } if (this.getNewIdForThisEventExtender) { debug('[' + this.name + '] found eventextender id getter in event'); return this.getNewIdForThisEventExtender(evt, callback); } debug('not found viewmodel id in event, generate new id'); this.collection.getNewId(callback); }, /** * Extends the event. * @param {Object} evt The event object. * @param {Function} callback The function that will be called when this action has finished * `function(err, extendedEvent){}` */ extend: function (evt, callback) { var self = this; var payload = evt; if (self.payload && self.payload !== '') { payload = dotty.get(evt, self.payload); } if (self.evtExtFn.length === 3) { if (self.id) { self.extractId(evt, function (err, id) { if (err) { debug(err); return callback(err); } self.loadViewModel(id, function (err, vm) { if (err) { debug(err); return callback(err); } try { self.evtExtFn(_.cloneDeep(payload), vm, function () { try { callback.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }); } catch (e) { debug(e); process.emit('uncaughtException', e); } }); }); return; } try { self.evtExtFn(_.cloneDeep(payload), self.collection, function () { try { callback.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }); } catch (e) { debug(e); process.emit('uncaughtException', e); } return; } if (self.evtExtFn.length === 1) { try { var res = self.evtExtFn(evt); try { callback(null, res); } catch (e) { debug(e); process.emit('uncaughtException', e); } } catch (e) { debug(e); process.emit('uncaughtException', e); } return; } if (self.evtExtFn.length === 2) { if (!self.collection || !self.id) { try { self.evtExtFn(evt, function () { try { callback.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }); } catch (e) { debug(e); process.emit('uncaughtException', e); } return; } self.extractId(evt, function (err, id) { if (err) { debug(err); return callback(err); } self.loadViewModel(id, function (err, vm) { if (err) { debug(err); return callback(err); } try { var res = self.evtExtFn(_.cloneDeep(payload), vm); try { callback(null, res); } catch (e) { debug(e); process.emit('uncaughtException', e); } } catch (e) { debug(e); process.emit('uncaughtException', e); } }); }); } }, /** * Inject idGenerator for eventextender function if no id found. * @param {Function} fn The function to be injected. * @returns {EventExtender} to be able to chain... */ useAsId: function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 2) { this.getNewIdForThisEventExtender = fn; return this; } this.getNewIdForThisEventExtender = function (evt, callback) { callback(null, fn(evt)); }; return this; }, }); module.exports = EventExtender;
$(document).on('keydown', function(e) { // F1 if (e.which == 112) { e.preventDefault(); //console.log('F1'); repeat_last(); return false; } }); $(document).on('click', '#repeat-button', function() { //console.log('repeat button clicked'); repeat_last(); }); $(document).on('click', '#junk-button', function() { //console.log('junk button clicked'); junk_images(); }); // Trigger action when the contexmenu is about to be shown $(document).bind("contextmenu", function (event) { // Avoid the real one event.preventDefault(); // Show contextmenu $("#family-menu").finish().toggle(100). // In the right position (the mouse) css({ top: event.pageY + "px", left: event.pageX + "px", }); }); // If the document is clicked somewhere $(document).bind("mousedown", function (e) { // If the clicked element is not the menu if (!$(e.target).parents("#family-menu").length > 0) { // Hide it $("#family-menu").hide(100); } }); $(document).ready(function() { $("ul#family-menu li").hover(function () { $(this).children('ul').show(); }, function() { $(this).children('ul').hide(); }); }); function junk_images() { var children = $('#selectable').children('.ui-selected'); var children_array = jQuery.makeArray(children); selected_ids = []; for (i = 0; i < children_array.length; i++) { selected_ids.push(children_array[i].children[0].id); } var children_string = selected_ids.join(', '); $.ajax({ url: '/junk_images', data: jQuery.param({ 'image_id': children_string, }), type: 'POST', success: function(response) { //console.log("success " + response); var selectable = $('#selectable'); selectable.children().remove('.ui-selected'); console.log('removing junked images'); }, error: function(error) { //console.log("error " + error); } }); } function repeat_last() { var repeat_family = $('#repeat-family'); var repeat_genus = $('#repeat-genus'); var repeat_species = $('#repeat-species'); var family_id = repeat_family.data('id'); var family_name = repeat_family.data('name'); var genus_id = repeat_genus.data('id'); var genus_name = repeat_genus.data('name'); var species_id = repeat_species.data('id'); var species_name = repeat_species.data('name'); if (family_id == 'None' && family_name == 'None') { family_id = null; family_name = null; genus_id = null; genus_name = null; species_id = null; species_name = null; } else if (genus_id == 'None' && genus_name == 'None') { genus_id = null; genus_name = null; species_id = null; species_name = null; } else if (species_id == 'None' && species_name == 'None') { species_id = null; species_name = null; } update_labels({ 'top': '50%', 'left': '50%', 'transform': 'translate(-50%, -50%)'}, { 'family_id': family_id, 'family_name': family_name, 'genus_id': genus_id, 'genus_name': genus_name, 'species_id': species_id, 'species_name': species_name, }); } function update_labels(message, selection) { var species_id = selection['species_id']; var species_name = selection['species_name']; var genus_id = selection['genus_id']; var genus_name = selection['genus_name']; var family_id = selection['family_id']; var family_name = selection['family_name']; var children = $('#selectable').children('.ui-selected'); // hide it AFTER the action was triggered $("#family-menu").hide(100); var children_array = jQuery.makeArray(children); selected_ids = []; for (i = 0; i < children_array.length; i++) { selected_ids.push(children_array[i].children[0].id); } var children_string = selected_ids.join(', '); $.ajax({ url: '/update_labels', data: jQuery.param({ 'species_id': species_id, 'species_name': species_name, 'genus_id': genus_id, 'genus_name': genus_name, 'family_id': family_id, 'family_name': family_name, 'image_id': children_string, }), type: 'POST', success: function(response) { //console.log("success " + response); // confirm that the number of rows updated in database matches the number of images selected var result = JSON.parse(response); var rows_updated = result['rows_updated']; //console.log('success: ' + rows_updated); if (children.length != rows_updated) alert(children.length + ' images were selected, but ' + rows_updated + ' were updated in the database!'); // display the most specific name we have for each image var name; //console.log(species_name + " " + genus_name + " " + family_name); var repeat_family = $('#repeat-family'); if (family_name != null) { repeat_family.text(family_name); repeat_family.data('id', family_id); repeat_family.data('name', family_name); } else { repeat_family.text('None'); repeat_family.data('id', 'None'); repeat_family.data('name', 'None'); } var repeat_genus = $('#repeat-genus'); if (genus_name != null) { repeat_genus.text(genus_name); repeat_genus.data('id', genus_id); repeat_genus.data('name', genus_name); } else { repeat_genus.text('None'); repeat_genus.data('id', 'None'); repeat_genus.data('name', 'None'); } var repeat_species = $('#repeat-species'); if (species_name != null) { repeat_species.text(species_name); repeat_species.data('id', species_id); repeat_species.data('name', species_name); } else { repeat_species.text('None'); repeat_species.data('id', 'None'); repeat_species.data('name', 'None'); } if (species_name != null) name = species_name; else if (genus_name != null) name = genus_name; else if (family_name != null) name = family_name; else name = "unknown"; for (i = 0; i < children.length; i++) { var child = children[i].children[1]; child.innerHTML = name; } var image_str = " image"; if (rows_updated > 1) image_str += "s"; // ensure the message is on-screen by placing it under the cursor $('.toast').text(rows_updated + image_str + " labeled as " + name).fadeIn(250).delay(500).fadeOut(250).css({ top: message['top'], left: message['left'], transform: message['transform'], }); }, error: function(error) { //console.log("error " + error); } }); } $(document).ready(function() { $(function(){ // trigger only when the direct descendant list item is clicked $('#species-menu > li').on('click', function(e) { var species_clicked = $(this); var genus_clicked = species_clicked.closest('#genus-menu > li'); var family_clicked = genus_clicked.closest('#family-menu > li'); var species_id = species_clicked.attr('id'); var species_name = species_clicked.attr('data-action'); var genus_id = genus_clicked.attr('id'); var genus_name = genus_clicked.attr('data-action'); var family_id = family_clicked.attr('id'); var family_name = family_clicked.attr('data-action'); // need to make these null explicitly, because the context menu // labels are not converted to json before being passed if (species_id == "None" && species_name == "None") { species_id = null; species_name = null; } if (genus_id == "None" && genus_name == "None") { genus_id = null; genus_name = null; } console.log( "species_id: " + species_id + ", species_name: " + species_name + ", " + "genus_id: " + genus_id + ", genus_name: " + genus_name + ", " + "family_id: " + family_id + ", family_name: " + family_name ); e.stopPropagation(); update_labels({ 'top': e.pageY + 'px', 'left': e.pageX + 'px', 'transform': '' }, { 'species_id': species_id, 'species_name': species_name, 'genus_id': genus_id, 'genus_name': genus_name, 'family_id': family_id, 'family_name': family_name, }); }); $('#genus-menu > li').on('click', function(e) { var genus_clicked = $(this); var family_clicked = genus_clicked.closest('#family-menu > li'); var species_id = null; var species_name = null; var genus_id = genus_clicked.attr('id'); var genus_name = genus_clicked.attr('data-action'); var family_id = family_clicked.attr('id'); var family_name = family_clicked.attr('data-action'); if (genus_id == "None" && genus_name == "None") { genus_id = null; genus_name = null; } console.log( "species_id: " + species_id + ", species_name: " + species_name + ", " + "genus_id: " + genus_id + ", genus_name: " + genus_name + ", " + "family_id: " + family_id + ", family_name: " + family_name ); e.stopPropagation(); update_labels({ 'top': e.pageY + 'px', 'left': e.pageX + 'px', 'transform': ''}, { 'species_id': species_id, 'species_name': species_name, 'genus_id': genus_id, 'genus_name': genus_name, 'family_id': family_id, 'family_name': family_name, }); }); $('#family-menu > li').on('click', function(e) { var family_clicked = $(this); var species_id = null; var species_name = null; var genus_id = null; var genus_name = null; var family_id = family_clicked.attr('id'); var family_name = family_clicked.attr('data-action'); if (family_id == "None" && family_name == "None") { family_id = null; family_name = null; } console.log( "species_id: " + species_id + ", species_name: " + species_name + ", " + "genus_id: " + genus_id + ", genus_name: " + genus_name + ", " + "family_id: " + family_id + ", family_name: " + family_name ); e.stopPropagation(); update_labels({ 'top': e.pageY + 'px', 'left': e.pageX + 'px', 'transform': ''}, { 'species_id': species_id, 'species_name': species_name, 'genus_id': genus_id, 'genus_name': genus_name, 'family_id': family_id, 'family_name': family_name, }); }); }); });
export default class ngbCytoscapeToolbarPanelController { constructor() { } static get UID() { return 'ngbCytoscapeToolbarPanelController'; } zoomIn() { this.actionsManager.zoomIn(); } zoomOut() { this.actionsManager.zoomOut(); } restoreDefault() { this.actionsManager.restoreDefault(); } }
'use strict'; /** * @ngdoc function * @name sbAdminApp.controller:MainCtrl * @description * # MainCtrl * Controller of the sbAdminApp */ angular.module('sbAdminApp') .controller('UsersCtrl', function($scope,$position,$state,$cookies,UsersService) { console.log("UsersCtrl") $scope.data = { users:[] }; $scope.radioModel = 'Activo'; UsersService.getUsers().then( function succes(response){ $scope.data.users = response; } ); $scope.active = function(user){ user.active = true; console.log(user) UsersService.unBlockUser(user).then( function succes(response){ console.log(response); } ); } $scope.inactive = function(user){ user.active = false; console.log(user) UsersService.blockUser(user).then( function succes(response){ console.log(response); } ); } });
import Ember from 'ember'; export default Ember.Controller.extend({ notifications: Ember.inject.service(), args: Ember.computed.alias('model'), actions: { confirmAccept: function () { var args = this.get('args'), editorController, model, transition; if (Ember.isArray(args)) { editorController = args[0]; transition = args[1]; model = editorController.get('model'); } if (!transition || !editorController) { this.get('notifications').showNotification('抱歉,系统故障。请将此问题提交至 Ghost 开发团队。', {type: 'error'}); return true; } // definitely want to clear the data store and post of any unsaved, client-generated tags model.updateTags(); if (model.get('isNew')) { // the user doesn't want to save the new, unsaved post, so delete it. model.deleteRecord(); } else { // roll back changes on model props model.rollback(); } // setting isDirty to false here allows willTransition on the editor route to succeed editorController.set('isDirty', false); // since the transition is now certain to complete, we can unset window.onbeforeunload here window.onbeforeunload = null; transition.retry(); }, confirmReject: function () { } }, confirm: { accept: { text: '离开此页', buttonClass: 'btn btn-red' }, reject: { text: '留在此页', buttonClass: 'btn btn-default btn-minor' } } });
import * as TYPE from '../mutation-types' const state = { searchHistory: { hotData: [], historyData: [], timeStamp: '' } } /* api getters can use all */ const getters = { searchHistory: state => state.searchHistory } const mutations = { [TYPE.SEARCH_HISTORY_INIT] (state, {searchHistory}) { state.searchHistory.hotData = searchHistory.hotData state.searchHistory.historyData = searchHistory.historyData state.searchHistory.timeStamp = searchHistory.timeStamp }, [TYPE.SEARCH_HISTORY_UPDATE] (state, {searchHistory}) { state.searchHistory.historyData = searchHistory.historyData } } const actions = { intHistory ({commit}, {searchHistory}) { commit(TYPE.SEARCH_HISTORY_INIT, {searchHistory}) }, updateHistory ({commit}, {searchHistory}) { commit(TYPE.SEARCH_HISTORY_UPDATE, {searchHistory}) } } export default { state, getters, actions, mutations }
// # Backup Database // Provides for backing up the database before making potentially destructive changes var fs = require('fs-extra'), path = require('path'), Promise = require('bluebird'), config = require('../../config'), common = require('../../lib/common'), urlUtils = require('../../lib/url-utils'), exporter = require('../exporter'), writeExportFile, backup; writeExportFile = function writeExportFile(exportResult) { var filename = path.resolve(urlUtils.urlJoin(config.get('paths').contentPath, 'data', exportResult.filename)); return fs.writeFile(filename, JSON.stringify(exportResult.data)).return(filename); }; const readBackup = async (filename) => { const parsedFileName = path.parse(filename); const sanitized = `${parsedFileName.name}${parsedFileName.ext}`; const backupPath = path.resolve(urlUtils.urlJoin(config.get('paths').contentPath, 'data', sanitized)); const exists = await fs.pathExists(backupPath); if (exists) { const backup = await fs.readFile(backupPath); return JSON.parse(backup); } else { return null; } }; /** * ## Backup * does an export, and stores this in a local file * @returns {Promise<*>} */ backup = function backup(options) { common.logging.info('Creating database backup'); options = options || {}; var props = { data: exporter.doExport(options), filename: exporter.fileName(options) }; return Promise.props(props) .then(writeExportFile) .then(function successMessage(filename) { common.logging.info('Database backup written to: ' + filename); return filename; }); }; module.exports = { backup, readBackup };
/* eslint-disable func-names, prefer-arrow-callback, no-unused-expressions */ // Third party components const stream = require('stream'); const {expect} = require('chai'); const Promise = require('bluebird'); // Local components require('../../../app/models/build.js'); require('../../../app/models/testcase.js'); require('../../../app/models/results.js'); const ResultsController = require('../../../app/controllers/results.js'); const MockResponse = require('./mocking/MockResponse.js'); const mockJunitXml = require('./mocking/MockJunitXmlTests.js'); const {setup, reset, teardown} = require('../../utils/mongomock'); // Test variables let controller = null; describe('controllers/results.js', function () { // Create fresh DB before(setup); before(function () { // Test that controller can be initialized before other tests controller = new ResultsController(); }); beforeEach(reset); after(teardown); describe('streamToString', function () { it('should concat streamed data correctly', function () { const mockedStream = stream.Readable(); mockedStream._read = function () { }; const stringPromise = ResultsController.streamToString(mockedStream); // Stream mock data mockedStream.emit('data', 'chunk1'); mockedStream.emit('data', 'chunk2'); mockedStream.emit('data', 'chunk3'); mockedStream.emit('end'); return expect(stringPromise).to.eventually.equal('chunk1chunk2chunk3'); }); }); describe('handleJunitXml', function () { it('should result in message created 2 results', function () { // Valid case, proper junit xml return controller.handleJunitXml(mockJunitXml.valid).then((value) => { expect(value).to.not.have.property('error'); expect(value).to.have.property('ok'); expect(value).to.have.property('message', 'created 2 results'); }); }); it('should be rejected when input is invalid xml', function () { return expect(controller.handleJunitXml('Invalid xml! 823y49')).to.be.rejectedWith(Error); }); it('should be rejected when input is not JunitXml', function () { return expect(controller.handleJunitXml(mockJunitXml.typo)).to.be.rejectedWith(TypeError); }); }); describe('createFromJunitXml', function () { let req; let res; beforeEach(function () { controller = new ResultsController(); req = {busboy: stream.Readable()}; req.busboy._read = function () { }; res = new MockResponse((value) => { expect(value).to.have.property('error'); }, (value) => { expect(value).to.equal(400); }); }); it('should result in ok', function () { controller.streamToString = () => Promise.resolve('combined_stream_string'); controller.handleJunitXml = () => Promise.resolve('ok'); const createPromise = controller.createFromJunitXml(req, res); req.busboy.emit('file', 'mockFieldName', 'mockFile', 'mockFilename', 'mockEncoding', 'mockMimetype'); return expect(createPromise).to.eventually.equal('ok'); }); it('should be rejected when streamToString is rejected', function () { controller.streamToString = () => Promise.reject(new Error('Make-believe error from streamToString')); controller.handleJunitXml = () => Promise.resolve('ok'); const createPromise = controller.createFromJunitXml(req, res); req.busboy.emit('file', 'mockFieldName', 'mockFile', 'mockFilename', 'mockEncoding', 'mockMimetype'); return expect(createPromise).to.be.rejectedWith(Error); }); it('should be rejected when handleJunitXml is rejected', function () { controller.streamToString = () => Promise.reject(new Error('Make-believe error from streamToString')); controller.handleJunitXml = () => Promise.resolve('ok'); const createPromise = controller.createFromJunitXml(req, res); req.busboy.emit('file', 'mockFieldName', 'mockFile', 'mockFilename', 'mockEncoding', 'mockMimetype'); return expect(createPromise).to.be.rejectedWith(Error); }); }); describe('buildDownload', function () { it('should call getBuildRef and redirect to build route', function (done) { let buildCalled = false; const req = { params: {Index: 90123}, Result: {getBuildRef() { buildCalled = true; return '5'; }} }; let redirectCalled = false; const res = { redirect(url) { expect(url.indexOf('/5/')).to.not.equal(-1, 'url should contain build id substring /5/'); expect(url.indexOf('/90123/')).to.not.equal(-1, 'url should contain Index substring /90123/'); expect(buildCalled).to.equal(true, 'getBuildRef should be called before redirect'); redirectCalled = true; } }; ResultsController.buildDownload(req, res); expect(buildCalled).to.equal(true, 'build should be called at some point'); expect(redirectCalled).to.equal(true, 'redirect should be called at some point'); done(); }); }); });
Parts = new Meteor.Collection('parts');
var utility = { 'articleTitle':'', 'apiUrl':'https://en.wikipedia.org/w/api.php?callback=?', 'revisionUrl' : 'https://en.wikipedia.org/w/index.php?oldid=', 'redirectTitle' : function(title){ var check_redirect_dict = { 'action':'query', 'format':'json', 'titles':title, 'redirects':'' }; var that = this; return $.getJSON(that.apiUrl,check_redirect_dict,function(data){ if (-1 in data['query']['pages']){ that.articleTitle = false; } else{ query = data['query']; if ('redirects' in query){ console.log(query['redirects'][0]['to']); that.articleTitle = query['redirects'][0]['to']; } else that.articleTitle = title; } }); }, 'searchTitle' : function(parent, string){ var that = this; var search_dict = { 'action':'opensearch', 'format':'json', 'search':string, 'namespace':0, 'suggest':'', 'limit':5 }; $.getJSON(that.apiUrl,search_dict,function(data){ $('.suggestionDropdown').attr('data-length',data[1].length); console.log(data); $(parent + ' .suggestionDropdown li').each(function(index){ if (data[1][index]){ $(this).text(data[1][index]); } else{ $(this).text(''); } }); }); }, 'languageDropdown': function(parent,languages){ var dropdown = $(parent + ' .languageDropdown ul'); var count = 0; for (language in languages){ if( count % 6 == 0 ){ var subList = $('<li><ul></ul></li>'); dropdown.append(subList); var subList = subList.find('ul'); } var li = $('<li></li>').text(languages[language]).attr('data-language',language); subList.append(li); count ++ ; } }, 'changeUrlLanguage': function(language){ this.apiUrl = 'https://'+language+'.wikipedia.org/w/api.php?callback=?'; this.revisionUrl = 'https://'+language+'.wikipedia.org/w/index.php?oldid='; }, 'translate': function(language){ language = translation[language] ? language : 'en'; translations = translation[language]; $('[data-translate]').each(function(index){ element = $(this); if (element.prop('tagName') == 'INPUT'){ if (element.attr('value')){ element.attr('value',translations[element.attr('data-translate')]); } else{ element.attr('placeholder',translations[element.attr('data-translate')]); } } else if (element.attr('data-title')){ element.attr('data-title',translations[element.attr('data-translate')]); } else{ element.text(translations[element.attr('data-translate')]); } }); } }; var infoBox = function (revInfo){ for (key in revInfo){ if(key == 'revid'){ var urlBase = utility.revisionUrl+revInfo[key]; var anchor =$('<a>'+revInfo[key]+'</a>').attr({'target':'_blank','href':urlBase}); $('#infoBox .revisionLink').html(anchor); } else if(key == 'timestamp'){ $('#infoBox .editDate').html(revInfo[key]); } else if(key == 'user'){ $('#infoBox .userName').html(revInfo[key]); } else{ var minor = revInfo[key]?revInfo[key]:''; $('#infoBox .minor').html(minor); } } }; function wikiSlider(options){ var postDict ={ rvdir:'older', format:'json', action:'query', prop:'revisions', titles:'', rvprop:'user|timestamp|flags|ids|size', rvlimit:'max', rawcontinue: '' }; this.height = options.height; this.barGraphBarwidth = options.barGraphBarwidth; this.enlargedBarGraphBarwidth = options.enlargedBarGraphBarwidth; /* Callbacks for the Primary & Secondry slider*/ this.primarySliderCallback = null ; this.secondrySliderCallback = null; if (options.primarySliderMoveCallback && typeof(options.primarySliderMoveCallback) === 'function'){ this.primarySliderCallback = options.primarySliderMoveCallback; } if (options.secondrySliderMoveCallback && typeof(options.secondrySliderMoveCallback) === 'function'){ this.secondrySliderCallback = options.secondrySliderMoveCallback; } /* Used Variables */ var svgWidth = 0; var hoverUser = ''; var completeRevData = [], secondrySliderSelection = []; var rvContinueHash = true,gettingDataFlag = true; var yscale = null, yscale2 = null, xscale = null; var brush = null; var peg = null,pegScale = null,pegHandle,pegHandleContainer; var toolTipDiv, svg, svgBox, svgEnlargedBox; var primaryContainer, primaryGraph, secondaryContainer, secondaryGraph, newGraph; var outerLength = 25, enlargedLength = 65; var endLine, startDate, endDate; var progressBar,progressBarWidth = 5; var bars; var timeFormat = "%Y-%m-%dT%H:%M:%SZ"; var timeParse = d3.time.format(timeFormat); /* Selected Edits*/ this.selectedEdits = []; this.pegMoved = true; var that = this; var outerScrollDateUpdate = function (){ var barGraphBarGap = 1; var outerWidth = $('#outer').width(); var outerViewportHidden = $('#outer').eq(0).scrollLeft(); var outerViewportStart = outerViewportHidden/(that.barGraphBarwidth + barGraphBarGap); var outerViewportEnd = (outerViewportHidden + outerWidth)/(that.barGraphBarwidth + barGraphBarGap); var outerViewportShown = completeRevData.slice(outerViewportStart,outerViewportEnd); $('#outerEndDate').html(timeParse.parse(outerViewportShown[0].timestamp).toDateString().slice(4)); $('#outerStartDate').html(timeParse.parse(outerViewportShown[outerViewportShown.length -1].timestamp).toDateString().slice(4)); console.log('outer scroll'); }; this.init = function(){ /*Enlarged view toggle*/ d3.select('.enlargedButton').on('click',function(){ if (d3.select('#enlarged').style('height').split('px')[0] > 20){ d3.select('#enlarged').style({'height':'15px','top':'145px'}).select('svg').style('display','none'); d3.select(this).classed('up',false); d3.select(this).classed('down',true); } else{ d3.select('#enlarged').style({'height':enlargedLength*2+'px', top:0+'px'}).select('svg').style('display','block'); d3.select(this).classed('down',false); d3.select(this).classed('up',true); } }); /* tooltip div */ tooltipDiv = d3.select("body").append("div").attr("class", "tooltip").style("opacity", 0); svg = d3.select('#outer').append('svg').attr({'height':outerLength*2,'width':600}); svgBox = svg.append('g').attr({'transform':'translate(0,0)'}); svgEnlarged = d3.select('#enlarged').append('svg').attr({'height':enlargedLength*2,'width':450}); /*Baseline in enlarged graph*/ d3.select('#enlarged svg').append('line').attr({'x1':0,'x2':450, 'y1':enlargedLength+progressBarWidth/2,'y2':enlargedLength+progressBarWidth/2, 'stroke':'#d0eeed', 'stroke-width':progressBarWidth}); progressBar = d3.select('#enlarged svg').append('line').attr({'x1':0,'x2':450, 'y1':enlargedLength+progressBarWidth/2,'y2':enlargedLength+progressBarWidth/2, 'stroke':'#1ebce2', 'stroke-width':0}); d3.select('#enlarged svg').append('line').attr({'x1':0,'x2':0, 'y1':10,'y2':enlargedLength+progressBarWidth/2, 'stroke':'gray', 'stroke-width':'.5'}); endLine = d3.select('#enlarged svg').append('line').attr({'x1':450,'x2':450, 'y1':10,'y2':enlargedLength+progressBarWidth/2, 'stroke':'gray', 'stroke-width':'.5'}); svgEnlargedBox = svgEnlarged.append('g').attr('transform','translate(0,0)'); primaryContainer = svgBox.append('g').attr('id','primaryContainer'); primaryGraph = primaryContainer.append('g').attr('id','primaryGraph'); //Commenting out Edit size //primaryContainer.append('text').text('Edit Size').attr({'x':10,'y':10,'class':'legendText'}); secondaryContainer = svgEnlargedBox.append('g').attr({'id':'secondaryContainer'}); secondaryGraph = secondaryContainer.append('g').attr('id','secondaryGraph'); startDate = secondaryContainer.append('text').attr({'x':0,'y':15}).style('font-size',9); endDate = secondaryContainer.append('text').attr({'x':450,'y':15}).style('font-size',9); $('#outer').scroll(outerScrollDateUpdate); /* Calling it direcly with getData by the user*/ //this.getData(); }; this.getData = function(title){ if(title){ postDict['titles'] = title; } if (gettingDataFlag && rvContinueHash){ //console.log('postDict',postDict); $.getJSON(utility.apiUrl,postDict,function(data){ if ('query-continue' in data){ rvContinueHash = data['query-continue'].revisions.rvcontinue; postDict['rvcontinue'] = rvContinueHash; } else{ rvContinueHash = null; } console.log(rvContinueHash); if (!rvContinueHash) $('#olderEditsInfo').hide(); var resultKey = Object.keys(data.query.pages); var revData = data.query.pages[resultKey].revisions; completeRevData = completeRevData.concat(revData); parsedData = that.parseData(completeRevData); that.fixScales(); that.addData(primaryGraph,completeRevData,yscale); that.callBrush(); gettingDataFlag = true; $('#outer').scroll(); }).error(function() { gettingDataFlag = true; }); gettingDataFlag = false; } else{ return; } }; this.cleanUp = function () { completeRevData = []; rvContinueHash = true; postDict ={ rvdir:'older', format:'json', action:'query', prop:'revisions', titles:'', rvprop:'user|timestamp|flags|ids|size', rvlimit:'max', rawcontinue:'' }; }; //Cleanup big time /** To highlight the revision currently being animated **/ this.modifySecondryGraph = function(field,value) { newGraph.filter(function(d){ if(d[field] == value){ progressBar.attr('x1',d.lastX); pegHandleContainer.transition().duration(750).call(peg.extent([d.lastX, d.lastX])).call(peg.event); return true; } }); }; //Cleanup big time /** To get the list of revisions selected in the slider **/ this.getSelection = function () { var brushExtent = brush.extent(); var start = Math.floor(brushExtent[0]/(that.barGraphBarwidth+1)); var end = Math.ceil(brushExtent[1]/(that.barGraphBarwidth+1)); return completeRevData.slice(start,end); }; this.getSecondrySliderSelection = function (i){ return i ? that.getSelection().slice(0,i+1).reverse():that.getSelection().reverse(); }; this.parseData = function(data){ data.forEach(function(d,i,array){ if(array[i+1]){ d.editSize = d.size - array[i+1].size; //Edit direction positive or negative if (d.editSize >= 0){ d.dir = 'p'; } else{ d.dir = 'n'; d.editSize = d.editSize * -1; } if (i == 0 ){ d.timeDiff = 0; } else{ d.timeDiff = Math.floor((timeParse.parse(array[i-1].timestamp) - timeParse.parse(d.timestamp) ) /86400000); } } else{ d.editSize = null; d.timeDiff = 0; } //console.log(d.editSize); if (d.parentid == 0){ d.editSize = d.size; d.timeDiff = 0; d.dir = 'p'; } if ('minor' in d){ d.minor = true; } else{ d.minor = false; } d.date = timeParse.parse(d.timestamp); }); data.svgWidth = data.length*(that.barGraphBarwidth+1) < 100 ? 100 : data.length*(that.barGraphBarwidth+1); data.yscale = [0,d3.max(data, function(d) { return d.editSize; })]; }; this.fixScales = function (){ if(xscale == null){ yscale = d3.scale.pow().exponent(.4).domain([0,d3.max(completeRevData, function(d) { return d.editSize; })]) .range([1,outerLength]); yscale2 = d3.scale.pow().exponent(.4).domain([0,d3.max(completeRevData, function(d) { return d.editSize; })]) .range([3,enlargedLength]); xscale = d3.scale.linear().domain([0,completeRevData.svgWidth]).range([0,completeRevData.svgWidth]); //cleanup pegscale pegScale = d3.scale.linear().domain([0,completeRevData.svgWidth]).range([0,completeRevData.svgWidth]); diffscale = d3.scale.linear().domain([0,d3.max(completeRevData, function(d) { return d.timeDiff; })]).range([0,10]); } else{ yscale.domain([0,d3.max(completeRevData, function(d) { return d.editSize; })]); yscale2.domain([0,d3.max(completeRevData, function(d) { return d.editSize; })]); xscale.domain([0,completeRevData.svgWidth]).range([0,completeRevData.svgWidth]); diffscale.domain([0,d3.max(completeRevData, function(d) { return d.timeDiff; })]); } svg.attr('width',completeRevData.svgWidth); }; this.addData = function (rect,data,yscale){ bars = rect.selectAll('rect').data(data); bars.enter().append("rect"); bars.attr({ 'x':function(d,i){ return i * that.barGraphBarwidth + i; }, 'y':function(d,i){ return d.dir == 'p' ? outerLength - yscale(d.editSize) : outerLength; }, 'width':that.barGraphBarwidth, 'height':function(d,i){ return yscale(d.editSize); }, 'class':function(d,i){ return d.dir == 'p' ? 'blue':'red'; }, 'timestamp':function(d){ return d.timestamp; } }); bars.exit().remove(); }; this.callBrush = function (){ if (brush != null){ brush.x(xscale); d3.select('#primaryBrush').call(brush); } else{ brush = d3.svg.brush().x(xscale).extent([0, 70]).on("brush", brushmove); var brushg = svgBox.append("g").attr("class", "brush") .attr("id","primaryBrush") .call(brush); brushg.selectAll("rect").attr("height", 100) .attr("y",0); //Cleanup brushg.selectAll(".resize rect").attr("width",2).attr("x",-2); //remove it from here $('#outer').scroll(); //Fix it //brushmove(); } temp(); cleanupProgressBar(); }; this.callPeg = function(){ if (peg != null){ peg.x(pegScale); d3.select('#peg').call(peg); } else{ peg = d3.svg.brush().x(pegScale).extent([0,0]).on("brush", pegMove); pegHandleContainer = svgEnlargedBox.append("g") .attr("id","peg") .call(peg); pegHandleContainer.selectAll(".extent,.resize").remove(); pegHandleContainer.select(".background") .attr("height", enlargedLength * 2); /* Peg */ pegHandle = pegHandleContainer.append("g"); pegHandle.append("rect") .attr("class", "peg") .attr("height",enlargedLength * 2) .attr("width",2) .attr("y", 0); pegHandle.append("rect") .attr("class", "peg") .attr("height",5) .attr("width",10) .attr("y", 0) .attr("x",-4); } var lastEditX = 0; newGraph.filter(function(d){ lastEditX = d.lastX; }); pegHandleContainer.call(peg.event) .transition() // gratuitous intro! .duration(750) .call(peg.extent([lastEditX,lastEditX])) .call(peg.event); }; this.handleScroll = function (){ //d3.select('#outer').transition().property('scrollLeft',brush.extent()[0]); $('#outer').scrollLeft(brush.extent()[0]); }; this.fixWidth = function (width){ d3.select('#enlarged svg').style('width',width).select('line').attr('x2',width); endLine.attr({'x1':width,'x2':width}); }; function brushmove(){ var brushExtent = brush.extent(); var slid_s = d3.event.target.extent(); if(slid_s[1] - slid_s[0] < 100){ /* the secondary slider */ temp(); if (brushExtent[1]> completeRevData.length*(that.barGraphBarwidth + 1) - 50){ //userNotification('load'); that.getData(); } } else{ d3.event.target.extent([slid_s[0],slid_s[0]+95]); d3.event.target(d3.select(this)); } /*Calling Primary Slider callback*/ cleanupProgressBar(); if (that.primarySliderCallback){ that.primarySliderCallback(); } } function cleanupProgressBar(){ progressBar.attr('stroke-width',0); }; this.refreshProgressBar = function (d){ progressBar.attr({'stroke-width':progressBarWidth, 'x1':d.lastX, 'x2':d.lastX+progressBarWidth }); }; function highlightSelectedEdit(graph,field,id,color){ graph.filter(function(d){ return d[field] == id; }).style({'fill':color}); }; function cleanupHighlightSelectedEdit(graph,field,id,color,type){ graph.filter(function(d){ return type ? !(d[field] == id) : d[field] == id; }).style({'fill':color}); }; function temp(){ var brushExtent = brush.extent(); var new_graph = completeRevData.slice(Math.floor(brushExtent[0]/(that.barGraphBarwidth+1)),Math.ceil(brushExtent[1]/(that.barGraphBarwidth+1)) ); if (new_graph.length){ var diffScaleAbs = 0; var lastX = 0; //console.log(brushExtent); newGraph = secondaryGraph.selectAll("rect").data(new_graph); newGraph.enter().append("rect"); newGraph.attr("x",function(d,i){ diffScaleAbs += d.timeDiff*3; lastX = diffScaleAbs + i*that.enlargedBarGraphBarwidth + i; d.lastX = lastX; return lastX; }) .attr("y",function(d,i){ return d.dir == 'p' ? enlargedLength - yscale2(d.editSize) : enlargedLength+progressBarWidth;}) .attr("width",that.enlargedBarGraphBarwidth) .attr("height",function(d){ return yscale2(d.editSize); }) .attr("class",function(d){ return d.dir=='p'?'pointer blue':'pointer red'; }) .attr("timeDiff",function(d){ return d.timeDiff; }) .attr("data-title",function(d){ return d.user; }) .attr("number",function(d,i){ return i; }); ; newGraph.exit().remove(); cleanupHighlightSelectedEdit(newGraph,'user',hoverUser,'#929396',1); highlightSelectedEdit(newGraph,'user',hoverUser,'gold'); startDate.text(timeParse.parse(new_graph[0].timestamp).toDateString().slice(4)); endDate.text(timeParse.parse(new_graph[new_graph.length-1].timestamp).toDateString().slice(4)).attr({'x':lastX-47}); enlargedBarGraphSvgWidth = lastX + that.enlargedBarGraphBarwidth; that.fixWidth(enlargedBarGraphSvgWidth); pegScale.domain([0,enlargedBarGraphSvgWidth]).range([0,enlargedBarGraphSvgWidth]); that.callPeg(); } } var pegMove = function(){ console.log('Peg moved'); var relaxedSelectedBar; //temp fix, to bring the correct edit into focus when the primary brush is moved var value = peg.extent()[0]+1; if (d3.event.sourceEvent) { // not a programmatic event value = pegScale.invert(d3.mouse(this)[0]); peg.extent([value, value]); that.pegMoved = true; //Pausing if the player is playing if (that.primarySliderCallback){ that.primarySliderCallback(); cleanupProgressBar(); } } selectedBar = newGraph.filter(function(d,i){ if (d.lastX < value && value < d.lastX + that.enlargedBarGraphBarwidth){ cleanupHighlightSelectedEdit(bars,'user',hoverUser,'gray',0); cleanupHighlightSelectedEdit(newGraph,'user',hoverUser,'#929396',0); hoverUser = d.user; highlightSelectedEdit(bars,'user',hoverUser,'gold'); highlightSelectedEdit(newGraph,'user',hoverUser,'gold'); var revInfo = { 'revid': d.revid, 'user': d.user, 'timestamp': d.timestamp.slice(0,10), 'minor': d.minor ? 'M' : null }; infoBox(revInfo); } if (d.lastX < value){ relaxedSelectedBar = i; } return d.lastX < value && value < d.lastX + that.enlargedBarGraphBarwidth; }); //Getting the selected edits that.selectedEdits = that.getSecondrySliderSelection(relaxedSelectedBar); console.log(selectedBar); pegHandle.attr("transform","translate("+pegScale(value)+")"); }; return this; }
import {TokenService} from '@/services' import {mutationTypes} from "./user"; const types = { CHECK_TOKEN: 'checkToken', DELETE_TOKEN: 'deleteToken', CREATE_TOKEN: 'createToken' }; const token = { state: {}, mutations: {}, actions: { [types.CHECK_TOKEN]({commit, getters}){ return new Promise((resolve, reject) => { if (!getters.session.token) { return resolve(false) } TokenService.get() .then(res => resolve(true)) .catch(err => { console.error(err) commit(mutationTypes.CHANGE_SESSION, {token: null}) resolve(false) }) }) }, [types.DELETE_TOKEN]({commit, getters}) { return TokenService.delete(getters.session.token) .then(res => { commit(mutationTypes.CHANGE_SESSION, {token: null}) }) }, [types.CREATE_TOKEN]({commit}, data) { return TokenService.post(data) .then(res => { const token = res.headers.authorization; commit(mutationTypes.CHANGE_SESSION, {token: token}) }) } } } export default token
//Using this filter to render unicode based cards in html form filters.filter('unsafe', ['$sce', function ($sce) { return $sce.trustAsHtml; }]);
/** * Created by Exper1ence on 2017/1/17. */ import Component from '../Component'; import gakk1, {V} from '../../gakk1'; import {func,} from '../util'; // export default class Draggable extends Component { // awake({}) { // return { // _dir: -1, // _last: null, // } // } // // render({}, {style.scss,}) { // const {width, height, ...rest}=style.scss; // return ( // <div // style.scss={{ // ...style.scss, // overflow: 'hidden', // }} // > // <div // style.scss={{ // width: width + 20, // height: height + 20, // overflow: 'scroll', // marginRight: '-20px', // }} // > // <div // style.scss={{ // width, // height, // backgroundColor: 'green', // }} // > // asdasdasd // </div> // </div> // </div> // ) // } // }
import Phaser from 'phaser' /** * Class for handling input interaction with keyboard and touch devices */ export default class { constructor({ game }) { this.jump = false this.game = game // add handling for spacebar let space = this.game.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR) space.onDown.add(() => { this.jump = true }) // add handling for tapping this.game.input.onDown.add(() => { this.jump = true }) } /** * Should we jump? * Crappy handling for supporting both tapping and spacebar * @return {Boolean} */ shouldJump() { // remember value let jump = this.jump // reset it to false this.jump = false // return original value return jump } }
Ext.define("Com.GatotKaca.ERP.module.GeneralSetup.view.grids.District",{extend:"Ext.grid.Panel",store:"Com.GatotKaca.ERP.module.GeneralSetup.store.District",alias:"widget.griddistrict",id:"griddistrict",layout:{type:"fit"},bodyStyle:"background : transparent",title:"District List",border:true,columns:[{xtype:"rownumberer",width:"11%"},{text:"Province",dataIndex:"province_name",width:"40%"},{text:"Name",dataIndex:"district_name",width:"47%"}],tbar:[{fieldLabel:'<span data-qtip="Type a keyword and press enter">Search</span>',xtype:"textfield",emptyText:"Type a keyword and press enter",enableKeyEvents:true,labelWidth:55,width:"100%",action:"search"}],bbar:["->",{text:"Refresh",xtype:"button",iconCls:"icon-arrow_refresh",action:"refresh"}]});
#!/usr/bin/env node /** * Created by zhs007 on 15/10/22. */ var fs = require('fs'); var process = require('process'); var iconv = require('iconv-lite'); var Iconv = require('iconv-lite').Iconv; var glob = require('glob'); var argv = require('yargs') .option('i', { alias : 'input', demand: true, default: 'gbk', describe: 'input charset', type: 'string' }) .option('o', { alias : 'output', demand: true, default: 'utf8', describe: 'output charset', type: 'string' }) .option('b', { alias : 'bom', demand: false, describe: 'BOM', type: 'boolean' }) .usage('Usage: chgcharset files [options]') .example('chgcharset **/*.lua -i gbk -o utf8 --bom', 'chg abc.lua charset from gbk to utf8 with BOM') .help('h') .alias('h', 'help') .epilog('copyright 2015') .argv; var basearr = argv._; if (basearr == undefined || basearr.length < 1) { console.log('Usage: chgcharset files [options]'); process.exit(1); } function isEquBuffer(src, dest) { if (src.length == dest.length) { for (var i = 0; i < src.length; ++i) { console.log('src: ' + src[i]); console.log('dest: ' + dest[i]); if (src[i] != dest[i]) { return false; } } return true; } return false; } function chgCharset(buf, srccharset, destcharset) { var outstr = iconv.decode(buf, srccharset); return iconv.encode(outstr, destcharset); } function checkCharset(buf, charset) { return true; //var destbuf = chgCharset(buf, charset, charset); //if (isEquBuffer(buf, destbuf)) { // return true; //} // //return false; var outstr = iconv.decode(buf, charset); var str = buf.toString(); return buf.toString() == outstr; } function hasBOM(buf) { return buf.length >= 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf; } function cutBOM(buf) { var destbuf = new Buffer(buf.length - 3); for (var i = 0; i < destbuf.length; ++i) { destbuf[i] = buf[i + 3]; } return destbuf; } function addBOM(buf) { var destbuf = new Buffer(buf.length + 3); destbuf[0] = 0xef; destbuf[1] = 0xbb; destbuf[2] = 0xbf; for (var i = 0; i < buf.length; ++i) { destbuf[i + 3] = buf[i]; } return destbuf; } var srccharset = argv.input; var destcharset = argv.output; var bom = argv.bom; for (var j = 0; j < basearr.length; ++j) { var lstfile = glob.sync(basearr[j]); for (var i = 0; i < lstfile.length; ++i) { var srcfile = lstfile[i]; if (fs.existsSync(srcfile)) { var srcbuf = fs.readFileSync(srcfile); var srcbom = hasBOM(srcbuf); if (srcbom) { if (srccharset != 'utf8') { console.log('Err: ' + srcfile + ' charset is utf8-bom'); continue; } srcbuf = cutBOM(srcbuf); } if (checkCharset(srcbuf, srccharset)) { var destbuf = chgCharset(srcbuf, srccharset, destcharset); if (bom) { fs.writeFileSync(srcfile, addBOM(destbuf)); } else { fs.writeFileSync(srcfile, destbuf); } } else { console.log('Err: ' + srcfile + ' charset is not ' + srccharset); continue; } } console.log(srcfile + ' OK!'); } }
/** * Copyright (c) 2016-present ZENOME, Inc. * All rights reserved. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ (function() { var NodeGit = require("nodegit"); var util_github = new Object(); try { util_github.clone = function(meta, cb) { console.log('cloning ' + meta.cloneurl); var localPath = require("path").join(__dirname, meta.appkey); var cloneOptions = {}; cloneOptions.fetchOpts = { callbacks: { certificateCheck: function() { return 1; }, credentials: function() { return NodeGit.Cred.userpassPlaintextNew(meta.github_token, "x-oauth-basic"); } } }; var cloneRepository = NodeGit.Clone(meta.cloneurl, localPath, cloneOptions); var getMostRecentCommit = function(repository) { return repository.getBranchCommit("master"); }; var getCommitMessage = function(commit) { return commit.message(); }; var getCommitId = function(commit) { return commit.id(); }; var errorAndAttemptOpen = function() { NodeGit.Repository.open(localPath) .then(getMostRecentCommit) .then(getCommitId) .then(function(commitid) { console.log('------------- commit id on error:' + commitid); cb(new Error('error'), commitid); }); }; cloneRepository.catch(errorAndAttemptOpen) .then(function(repository) { repository.getMasterCommit() .then(getCommitId) .then(function(commitid) { console.log('------------- commit id:' + commitid); cb(null, commitid); }); }); } } catch(e) { console.log(e); } module.exports = util_github; })();
var Promise = require('bluebird'), fs = require('fs'), semver = require('semver'), packageInfo = require('../../package.json'), errors = require('./errors'), config = require('./config'); function GhostServer(rootApp) { this.rootApp = rootApp; this.httpServer = null; this.connections = {}; this.connectionId = 0; this.upgradeWarning = setTimeout(this.logUpgradeWarning.bind(this), 5000); // Expose config module for use externally. this.config = config; } GhostServer.prototype.connection = function (socket) { var self = this; self.connectionId += 1; socket._ghostId = self.connectionId; socket.on('close', function () { delete self.connections[this._ghostId]; }); self.connections[socket._ghostId] = socket; }; // Most browsers keep a persistent connection open to the server // which prevents the close callback of httpServer from returning // We need to destroy all connections manually GhostServer.prototype.closeConnections = function () { var self = this; Object.keys(self.connections).forEach(function (socketId) { var socket = self.connections[socketId]; if (socket) { socket.destroy(); } }); }; GhostServer.prototype.logStartMessages = function () { // Tell users if their node version is not supported, and exit if (!semver.satisfies(process.versions.node, packageInfo.engines.node)) { console.log( '\nERROR: Unsupported version of Node'.red, '\nGhost needs Node version'.red, packageInfo.engines.node.yellow, 'you are using version'.red, process.versions.node.yellow, '\nPlease go to http://nodejs.org to get a supported version'.green ); process.exit(0); } // Startup & Shutdown messages if (process.env.NODE_ENV === 'production') { console.log( 'Ghost is running...'.green, '\nYour blog is now available on', config.url, '\nCtrl+C to shut down'.grey ); } else { console.log( ('Ghost is running in ' + process.env.NODE_ENV + '...').green, '\nListening on', config.getSocket() || config.server.host + ':' + config.server.port, '\nUrl configured as:', config.url, '\nCtrl+C to shut down'.grey ); } function shutdown() { console.log('\nGhost has shut down'.red); if (process.env.NODE_ENV === 'production') { console.log( '\nYour blog is now offline' ); } else { console.log( '\nGhost was running for', Math.round(process.uptime()), 'seconds' ); } process.exit(0); } // ensure that Ghost exits correctly on Ctrl+C and SIGTERM process. removeAllListeners('SIGINT').on('SIGINT', shutdown). removeAllListeners('SIGTERM').on('SIGTERM', shutdown); }; GhostServer.prototype.logShutdownMessages = function () { console.log('Ghost is closing connections'.red); }; GhostServer.prototype.logUpgradeWarning = function () { errors.logWarn( 'Ghost no longer starts automatically when using it as an npm module.', 'If you\'re seeing this message, you may need to update your custom code.', 'Please see the docs at http://tinyurl.com/npm-upgrade for more information.' ); }; /** * Starts the ghost server listening on the configured port. * Alternatively you can pass in your own express instance and let Ghost * start lisetning for you. * @param {Object=} externalApp Optional express app instance. * @return {Promise} */ GhostServer.prototype.start = function (externalApp) { var self = this, rootApp = externalApp ? externalApp : self.rootApp; // ## Start Ghost App return new Promise(function (resolve) { if (config.getSocket()) { // Make sure the socket is gone before trying to create another try { fs.unlinkSync(config.getSocket()); } catch (e) { // We can ignore this. } self.httpServer = rootApp.listen( config.getSocket() ); fs.chmod(config.getSocket(), '0660'); } else { if(global.ACESDK) { config.server.host = '0.0.0.0'; } self.httpServer = rootApp.listen( config.server.port, config.server.host ); } self.httpServer.on('error', function (error) { if (error.errno === 'EADDRINUSE') { errors.logError( '(EADDRINUSE) Cannot start Ghost.', 'Port ' + config.server.port + ' is already in use by another program.', 'Is another Ghost instance already running?' ); } else { errors.logError( '(Code: ' + error.errno + ')', 'There was an error starting your server.', 'Please use the error code above to search for a solution.' ); } process.exit(-1); }); self.httpServer.on('connection', self.connection.bind(self)); self.httpServer.on('listening', function () { self.logStartMessages(); clearTimeout(self.upgradeWarning); resolve(self); }); }); }; // Returns a promise that will be fulfilled when the server stops. // If the server has not been started, the promise will be fulfilled // immediately GhostServer.prototype.stop = function () { var self = this; return new Promise(function (resolve) { if (self.httpServer === null) { resolve(self); } else { self.httpServer.close(function () { self.httpServer = null; self.logShutdownMessages(); resolve(self); }); self.closeConnections(); } }); }; // Restarts the ghost application GhostServer.prototype.restart = function () { return this.stop().then(this.start.bind(this)); }; // To be called after `stop` GhostServer.prototype.hammertime = function () { console.log('Can\'t touch this'.green); return Promise.resolve(this); }; module.exports = GhostServer;
module.exports = { 'env': { 'es6': true }, 'extends': 'standard', 'globals': { 'Atomics': 'readonly', 'SharedArrayBuffer': 'readonly' }, 'parserOptions': { 'ecmaVersion': 2018, 'sourceType': 'module' }, 'rules': { } }
import Layer from './components/layer/Layer'; import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<Layer />, document.getElementById('content'));
// Karma configuration // Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'], plugins: [ 'karma-mocha', 'karma-chai', 'karma-sinon-chai', 'karma-chrome-launcher', 'karma-phantomjs-launcher', 'karma-jquery', 'karma-chai-jquery' ], // list of files / patterns to load in the browser files: [ 'bower/angular/angular.js', 'bower/angular-mocks/angular-mocks.js', 'dist/ng-affix.js', 'test/unit/**/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var __chunk_1 = require('./chunk-14c82365.js'); var __chunk_5 = require('./chunk-13e039f5.js'); // // // // // // // // // // // // // // // var script = { name: 'NavbarBurger', props: { isOpened: { type: Boolean, default: false } } }; /* script */ const __vue_script__ = script; /* template */ var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('a',_vm._g({staticClass:"navbar-burger burger",class:{ 'is-active': _vm.isOpened },attrs:{"role":"button","aria-label":"menu","aria-expanded":_vm.isOpened}},_vm.$listeners),[_c('span',{attrs:{"aria-hidden":"true"}}),_c('span',{attrs:{"aria-hidden":"true"}}),_c('span',{attrs:{"aria-hidden":"true"}})])}; var __vue_staticRenderFns__ = []; /* style */ const __vue_inject_styles__ = undefined; /* scoped */ const __vue_scope_id__ = undefined; /* module identifier */ const __vue_module_identifier__ = undefined; /* functional template */ const __vue_is_functional_template__ = false; /* style inject */ /* style inject SSR */ var NavbarBurger = __chunk_5.__vue_normalize__( { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ }, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined ); var isTouch = typeof window !== 'undefined' && ('ontouchstart' in window || navigator.msMaxTouchPoints > 0); var events = isTouch ? ['touchstart', 'click'] : ['click']; var instances = []; function processArgs(bindingValue) { var isFunction = typeof bindingValue === 'function'; if (!isFunction && __chunk_1._typeof(bindingValue) !== 'object') { throw new Error("v-click-outside: Binding value should be a function or an object, typeof ".concat(bindingValue, " given")); } return { handler: isFunction ? bindingValue : bindingValue.handler, middleware: bindingValue.middleware || function (isClickOutside) { return isClickOutside; }, events: bindingValue.events || events }; } function onEvent(_ref) { var el = _ref.el, event = _ref.event, handler = _ref.handler, middleware = _ref.middleware; var isClickOutside = event.target !== el && !el.contains(event.target); if (!isClickOutside) { return; } if (middleware(event, el)) { handler(event, el); } } function bind(el, _ref2) { var value = _ref2.value; var _processArgs = processArgs(value), _handler = _processArgs.handler, middleware = _processArgs.middleware, events = _processArgs.events; var instance = { el: el, eventHandlers: events.map(function (eventName) { return { event: eventName, handler: function handler(event) { return onEvent({ event: event, el: el, handler: _handler, middleware: middleware }); } }; }) }; instance.eventHandlers.forEach(function (_ref3) { var event = _ref3.event, handler = _ref3.handler; return document.addEventListener(event, handler); }); instances.push(instance); } function update(el, _ref4) { var value = _ref4.value; var _processArgs2 = processArgs(value), _handler2 = _processArgs2.handler, middleware = _processArgs2.middleware, events = _processArgs2.events; // `filter` instead of `find` for compat with IE var instance = instances.filter(function (instance) { return instance.el === el; })[0]; instance.eventHandlers.forEach(function (_ref5) { var event = _ref5.event, handler = _ref5.handler; return document.removeEventListener(event, handler); }); instance.eventHandlers = events.map(function (eventName) { return { event: eventName, handler: function handler(event) { return onEvent({ event: event, el: el, handler: _handler2, middleware: middleware }); } }; }); instance.eventHandlers.forEach(function (_ref6) { var event = _ref6.event, handler = _ref6.handler; return document.addEventListener(event, handler); }); } function unbind(el) { // `filter` instead of `find` for compat with IE var instance = instances.filter(function (instance) { return instance.el === el; })[0]; instance.eventHandlers.forEach(function (_ref7) { var event = _ref7.event, handler = _ref7.handler; return document.removeEventListener(event, handler); }); } var directive = { bind: bind, update: update, unbind: unbind, instances: instances }; var FIXED_TOP_CLASS = 'is-fixed-top'; var BODY_FIXED_TOP_CLASS = 'has-navbar-fixed-top'; var BODY_SPACED_FIXED_TOP_CLASS = 'has-spaced-navbar-fixed-top'; var FIXED_BOTTOM_CLASS = 'is-fixed-bottom'; var BODY_FIXED_BOTTOM_CLASS = 'has-navbar-fixed-bottom'; var BODY_SPACED_FIXED_BOTTOM_CLASS = 'has-spaced-navbar-fixed-bottom'; var BODY_CENTERED_CLASS = 'has-navbar-centered'; var isFilled = function isFilled(str) { return !!str; }; var script$1 = { name: 'BNavbar', components: { NavbarBurger: NavbarBurger }, directives: { clickOutside: directive }, // deprecated, to replace with default 'value' in the next breaking change model: { prop: 'active', event: 'update:active' }, props: { type: [String, Object], transparent: { type: Boolean, default: false }, fixedTop: { type: Boolean, default: false }, fixedBottom: { type: Boolean, default: false }, active: { type: Boolean, default: false }, centered: { type: Boolean, default: false }, wrapperClass: { type: String }, closeOnClick: { type: Boolean, default: true }, mobileBurger: { type: Boolean, default: true }, spaced: Boolean, shadow: Boolean }, data: function data() { return { internalIsActive: this.active, _isNavBar: true // Used internally by NavbarItem }; }, computed: { isOpened: function isOpened() { return this.internalIsActive; }, computedClasses: function computedClasses() { var _ref; return [this.type, (_ref = {}, __chunk_1._defineProperty(_ref, FIXED_TOP_CLASS, this.fixedTop), __chunk_1._defineProperty(_ref, FIXED_BOTTOM_CLASS, this.fixedBottom), __chunk_1._defineProperty(_ref, BODY_CENTERED_CLASS, this.centered), __chunk_1._defineProperty(_ref, 'is-spaced', this.spaced), __chunk_1._defineProperty(_ref, 'has-shadow', this.shadow), __chunk_1._defineProperty(_ref, 'is-transparent', this.transparent), _ref)]; } }, watch: { active: { handler: function handler(active) { this.internalIsActive = active; }, immediate: true }, fixedTop: { handler: function handler(isSet) { this.checkIfFixedPropertiesAreColliding(); if (isSet) { // TODO Apply only one of the classes once PR is merged in Bulma: // https://github.com/jgthms/bulma/pull/2737 this.setBodyClass(BODY_FIXED_TOP_CLASS); this.spaced && this.setBodyClass(BODY_SPACED_FIXED_TOP_CLASS); } else { this.removeBodyClass(BODY_FIXED_TOP_CLASS); this.removeBodyClass(BODY_SPACED_FIXED_TOP_CLASS); } }, immediate: true }, fixedBottom: { handler: function handler(isSet) { this.checkIfFixedPropertiesAreColliding(); if (isSet) { // TODO Apply only one of the classes once PR is merged in Bulma: // https://github.com/jgthms/bulma/pull/2737 this.setBodyClass(BODY_FIXED_BOTTOM_CLASS); this.spaced && this.setBodyClass(BODY_SPACED_FIXED_BOTTOM_CLASS); } else { this.removeBodyClass(BODY_FIXED_BOTTOM_CLASS); this.removeBodyClass(BODY_SPACED_FIXED_BOTTOM_CLASS); } }, immediate: true } }, methods: { toggleActive: function toggleActive() { this.internalIsActive = !this.internalIsActive; this.emitUpdateParentEvent(); }, closeMenu: function closeMenu() { if (this.closeOnClick) { this.internalIsActive = false; this.emitUpdateParentEvent(); } }, emitUpdateParentEvent: function emitUpdateParentEvent() { this.$emit('update:active', this.internalIsActive); }, setBodyClass: function setBodyClass(className) { if (typeof window !== 'undefined') { document.body.classList.add(className); } }, removeBodyClass: function removeBodyClass(className) { if (typeof window !== 'undefined') { document.body.classList.remove(className); } }, checkIfFixedPropertiesAreColliding: function checkIfFixedPropertiesAreColliding() { var areColliding = this.fixedTop && this.fixedBottom; if (areColliding) { throw new Error('You should choose if the BNavbar is fixed bottom or fixed top, but not both'); } }, genNavbar: function genNavbar(createElement) { var navBarSlots = [this.genNavbarBrandNode(createElement), this.genNavbarSlotsNode(createElement)]; if (!isFilled(this.wrapperClass)) { return this.genNavbarSlots(createElement, navBarSlots); } // It wraps the slots into a div with the provided wrapperClass prop var navWrapper = createElement('div', { class: this.wrapperClass }, navBarSlots); return this.genNavbarSlots(createElement, [navWrapper]); }, genNavbarSlots: function genNavbarSlots(createElement, slots) { return createElement('nav', { staticClass: 'navbar', class: this.computedClasses, attrs: { role: 'navigation', 'aria-label': 'main navigation' }, directives: [{ name: 'click-outside', value: this.closeMenu }] }, slots); }, genNavbarBrandNode: function genNavbarBrandNode(createElement) { return createElement('div', { class: 'navbar-brand' }, [this.$slots.brand, this.genBurgerNode(createElement)]); }, genBurgerNode: function genBurgerNode(createElement) { if (this.mobileBurger) { var defaultBurgerNode = createElement('navbar-burger', { props: { isOpened: this.isOpened }, on: { click: this.toggleActive } }); var hasBurgerSlot = !!this.$scopedSlots.burger; return hasBurgerSlot ? this.$scopedSlots.burger({ isOpened: this.isOpened, toggleActive: this.toggleActive }) : defaultBurgerNode; } }, genNavbarSlotsNode: function genNavbarSlotsNode(createElement) { return createElement('div', { staticClass: 'navbar-menu', class: { 'is-active': this.isOpened } }, [this.genMenuPosition(createElement, 'start'), this.genMenuPosition(createElement, 'end')]); }, genMenuPosition: function genMenuPosition(createElement, positionName) { return createElement('div', { staticClass: "navbar-".concat(positionName) }, this.$slots[positionName]); } }, beforeDestroy: function beforeDestroy() { if (this.fixedTop) { var className = this.spaced ? BODY_SPACED_FIXED_TOP_CLASS : BODY_FIXED_TOP_CLASS; this.removeBodyClass(className); } else if (this.fixedBottom) { var _className = this.spaced ? BODY_SPACED_FIXED_BOTTOM_CLASS : BODY_FIXED_BOTTOM_CLASS; this.removeBodyClass(_className); } }, render: function render(createElement, fn) { return this.genNavbar(createElement); } }; /* script */ const __vue_script__$1 = script$1; /* template */ /* style */ const __vue_inject_styles__$1 = undefined; /* scoped */ const __vue_scope_id__$1 = undefined; /* module identifier */ const __vue_module_identifier__$1 = undefined; /* functional template */ const __vue_is_functional_template__$1 = undefined; /* style inject */ /* style inject SSR */ var Navbar = __chunk_5.__vue_normalize__( {}, __vue_inject_styles__$1, __vue_script__$1, __vue_scope_id__$1, __vue_is_functional_template__$1, __vue_module_identifier__$1, undefined, undefined ); // // // // // // // // // // // // // var clickableWhiteList = ['div', 'span', 'input']; var script$2 = { name: 'BNavbarItem', inheritAttrs: false, props: { tag: { type: String, default: 'a' }, active: Boolean }, methods: { /** * Keypress event that is bound to the document */ keyPress: function keyPress(_ref) { var key = _ref.key; if (key === 'Escape' || key === 'Esc') { this.closeMenuRecursive(this, ['NavBar']); } }, /** * Close parent if clicked outside. */ handleClickEvent: function handleClickEvent(event) { var isOnWhiteList = clickableWhiteList.some(function (item) { return item === event.target.localName; }); if (!isOnWhiteList) { var parent = this.closeMenuRecursive(this, ['NavbarDropdown', 'NavBar']); if (parent && parent.$data._isNavbarDropdown) this.closeMenuRecursive(parent, ['NavBar']); } }, /** * Close parent recursively */ closeMenuRecursive: function closeMenuRecursive(current, targetComponents) { if (!current.$parent) return null; var foundItem = targetComponents.reduce(function (acc, item) { if (current.$parent.$data["_is".concat(item)]) { current.$parent.closeMenu(); return current.$parent; } return acc; }, null); return foundItem || this.closeMenuRecursive(current.$parent, targetComponents); } }, mounted: function mounted() { if (typeof window !== 'undefined') { this.$el.addEventListener('click', this.handleClickEvent); document.addEventListener('keyup', this.keyPress); } }, beforeDestroy: function beforeDestroy() { if (typeof window !== 'undefined') { this.$el.removeEventListener('click', this.handleClickEvent); document.removeEventListener('keyup', this.keyPress); } } }; /* script */ const __vue_script__$2 = script$2; /* template */ var __vue_render__$1 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c(_vm.tag,_vm._g(_vm._b({tag:"component",staticClass:"navbar-item",class:{ 'is-active': _vm.active }},'component',_vm.$attrs,false),_vm.$listeners),[_vm._t("default")],2)}; var __vue_staticRenderFns__$1 = []; /* style */ const __vue_inject_styles__$2 = undefined; /* scoped */ const __vue_scope_id__$2 = undefined; /* module identifier */ const __vue_module_identifier__$2 = undefined; /* functional template */ const __vue_is_functional_template__$2 = false; /* style inject */ /* style inject SSR */ var NavbarItem = __chunk_5.__vue_normalize__( { render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 }, __vue_inject_styles__$2, __vue_script__$2, __vue_scope_id__$2, __vue_is_functional_template__$2, __vue_module_identifier__$2, undefined, undefined ); // var script$3 = { name: 'BNavbarDropdown', directives: { clickOutside: directive }, props: { label: String, hoverable: Boolean, active: Boolean, right: Boolean, arrowless: Boolean, boxed: Boolean, closeOnClick: { type: Boolean, default: true }, collapsible: Boolean }, data: function data() { return { newActive: this.active, isHoverable: this.hoverable, _isNavbarDropdown: true // Used internally by NavbarItem }; }, watch: { active: function active(value) { this.newActive = value; } }, methods: { showMenu: function showMenu() { this.newActive = true; }, /** * See naming convetion of navbaritem */ closeMenu: function closeMenu() { this.newActive = !this.closeOnClick; if (this.hoverable && this.closeOnClick) { this.isHoverable = false; } }, checkHoverable: function checkHoverable() { if (this.hoverable) { this.isHoverable = true; } } } }; /* script */ const __vue_script__$3 = script$3; /* template */ var __vue_render__$2 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{directives:[{name:"click-outside",rawName:"v-click-outside",value:(_vm.closeMenu),expression:"closeMenu"}],staticClass:"navbar-item has-dropdown",class:{ 'is-hoverable': _vm.isHoverable, 'is-active': _vm.newActive },on:{"mouseenter":_vm.checkHoverable}},[_c('a',{staticClass:"navbar-link",class:{ 'is-arrowless': _vm.arrowless, 'is-active': _vm.newActive && _vm.collapsible },attrs:{"role":"menuitem","aria-haspopup":"true","href":"#"},on:{"click":function($event){$event.preventDefault();_vm.newActive = !_vm.newActive;}}},[(_vm.label)?[_vm._v(_vm._s(_vm.label))]:_vm._t("label")],2),_c('div',{directives:[{name:"show",rawName:"v-show",value:(!_vm.collapsible || (_vm.collapsible && _vm.newActive)),expression:"!collapsible || (collapsible && newActive)"}],staticClass:"navbar-dropdown",class:{ 'is-right': _vm.right, 'is-boxed': _vm.boxed, }},[_vm._t("default")],2)])}; var __vue_staticRenderFns__$2 = []; /* style */ const __vue_inject_styles__$3 = undefined; /* scoped */ const __vue_scope_id__$3 = undefined; /* module identifier */ const __vue_module_identifier__$3 = undefined; /* functional template */ const __vue_is_functional_template__$3 = false; /* style inject */ /* style inject SSR */ var NavbarDropdown = __chunk_5.__vue_normalize__( { render: __vue_render__$2, staticRenderFns: __vue_staticRenderFns__$2 }, __vue_inject_styles__$3, __vue_script__$3, __vue_scope_id__$3, __vue_is_functional_template__$3, __vue_module_identifier__$3, undefined, undefined ); var Plugin = { install: function install(Vue) { __chunk_5.registerComponent(Vue, Navbar); __chunk_5.registerComponent(Vue, NavbarItem); __chunk_5.registerComponent(Vue, NavbarDropdown); } }; __chunk_5.use(Plugin); exports.BNavbar = Navbar; exports.BNavbarDropdown = NavbarDropdown; exports.BNavbarItem = NavbarItem; exports.default = Plugin;
import Icon from '../../components/Icon.vue' Icon.register({ 'brands/wodu': { width: 640, height: 512, paths: [ { d: 'M178.4 339.7h-37.3l-28.9-116.2h-0.5l-28.5 116.2h-38l-45.2-170.8h37.5l27 116.2h0.5l29.7-116.2h35.2l29.2 117.7h0.5l28-117.7h36.8zM271.4 212.7c39 0 64.1 25.8 64.1 65.3 0 39.2-25.1 65-64.1 65-38.7 0-63.9-25.8-63.9-65 0-39.5 25.1-65.3 63.9-65.3zM271.4 317.5c23.2 0 30.1-19.9 30.1-39.5 0-19.9-6.9-39.7-30.1-39.7-27.7 0-29.9 19.9-29.9 39.7 0 19.6 6.9 39.5 29.9 39.5zM435.1 323.9h-0.5c-7.9 13.4-21.8 19.1-37.5 19.1-37.3 0-55.5-32-55.5-66.2 0-33.2 18.4-64.1 54.8-64.1 14.6 0 28.9 6.2 36.8 18.4h0.2v-62.2h34v170.8h-32.3v-15.8zM405.4 238.3c-22.2 0-29.9 19.1-29.9 39.5 0 19.4 8.8 39.7 29.9 39.7 22.5 0 29.2-19.6 29.2-39.9 0-20.1-7.2-39.2-29.2-39.2zM593 339.7h-32.3v-17.2h-0.7c-8.6 13.9-23.4 20.6-37.8 20.6-36.1 0-45.2-20.3-45.2-50.9v-76.1h34v69.8c0 20.3 6 30.4 21.8 30.4 18.4 0 26.3-10.3 26.3-35.4v-64.8h34v123.6zM602.5 302.9h37.5v36.8h-37.5v-36.8z' } ] } })
// Regular expression that matches all symbols in the `Lao` script as per Unicode v4.1.0: /[\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC\u0EDD]/;
'use strict'; describe('Service: mockDataService', function () { // load the service's module beforeEach(module('script2Bit')); // instantiate service var mockDataService; beforeEach(inject(function (_mockDataService_) { mockDataService = _mockDataService_; })); it('should do something', function () { expect(!!mockDataService).toBe(true); }); });
export { default as Module } from './Module'; export { default as EventsPage } from './EventsPage'; export { default as FormsPage } from './Forms/FormsPage';
const Definition = Jymfony.Component.DependencyInjection.Definition; class CustomDefinition extends Definition { } module.exports = CustomDefinition;
var JThreadPoolManager = Java.type('net.arnx.rhinode.core.ThreadPoolManager'); var JCompletableFuture = Java.type('java.util.concurrent.CompletableFuture'); var JPromiseException = Java.type('net.arnx.rhinode.core.PromiseException'); var JCompletionException = Java.type('java.util.concurrent.CompletionException'); var Promise = function(resolver, futures) { var that = this; if (resolver instanceof JCompletableFuture) { that._future = resolver; that._futures = futures; } else { var global = Function('return this')(); var executor = function() { var status, result; (0, Java.synchronized(resolver, global))(function(value) { status = 'fulfilled'; result = value; }, function(reason) { status = 'rejected'; result = reason; }); if (status == 'fulfilled') { return { result: result }; } else if (status == 'rejected') { throw new JPromiseException(result); } }; that._future = JCompletableFuture.supplyAsync(executor, JThreadPoolManager.get()); } }; Promise.all = function(array) { var futures = array.map(function(elem) { if (elem instanceof Promise) { return elem._future; } return Promise.resolve(elem)._future; }); return new Promise(JCompletableFuture.allOf(futures), futures); }; Promise.race = function(array) { var futures = array.map(function(elem) { if (elem instanceof Promise) { return elem._future; } return Promise.resolve(elem)._future; }); return new Promise(JCompletableFuture.anyOf(futures)); }; Promise.resolve = function(value) { if (value instanceof Promise) { return value; } else if (value != null && (typeof value === 'function' || typeof value === 'object') && typeof value.then === 'function') { return new Promise(function(fulfill, reject) { try { return { result: value.then(fulfill, reject) } } catch (e) { throw new JPromiseException(e); } }); } else { return new Promise(JCompletableFuture.completedFuture({ result: value })); } }; Promise.reject = function(value) { return new Promise(function(fulfill, reject) { reject(value); }); }; Promise.prototype.then = function(onFulfillment, onRejection) { var that = this; return new Promise(that._future.handle(new java.util.function.BiFunction({ apply: function(success, error) { if (success == null && error == null && that._futures != null) { success = { result: that._futures.map(function(elem) { return elem.get().result; }) }; } if (success != null) { if (typeof onFulfillment === 'function') { try { return { result: (0, onFulfillment)(success.result) }; } catch (e) { return { result: (0, onRejection)(e) }; } } return success; } else if (error != null) { if (error instanceof JCompletionException) { error = error.getCause(); } var cerror = error; do { if (cerror instanceof JPromiseException) { break; } } while ((cerror = cerror.getCause()) != null); if (typeof onRejection === 'function') { var reason = error; if (cerror instanceof JPromiseException) { reason = cerror.getResult(); } return { result: (0, onRejection)(reason) }; } throw error; } } }))); }; Promise.prototype.catch = function(onRejection) { return this.then(null, onRejection); }; module.exports = Promise;
(function ($, w) { var dateFormat = function() { var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function(val, len) { val = String(val); len = len || 2; while (val.length < len) val = "0" + val; return val; }; // Regexes and supporting functions are cached through closure return function(date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } // Passing date through Date applies Date.parse, if necessary date = date ? new Date(date) : new Date; if (isNaN(date)) throw SyntaxError("invalid date"); mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = { d: d, dd: pad(d), ddd: dF.i18n.dayNames[D], dddd: dF.i18n.dayNames[D + 7], m: m + 1, mm: pad(m + 1), mmm: dF.i18n.monthNames[m], mmmm: dF.i18n.monthNames[m + 12], yy: String(y).slice(2), yyyy: y, h: H % 12 || 12, hh: pad(H % 12 || 12), H: H, HH: pad(H), M: M, MM: pad(M), s: s, ss: pad(s), l: pad(L, 3), L: pad(L > 99 ? Math.round(L / 10) : L), t: H < 12 ? "a" : "p", tt: H < 12 ? "am" : "pm", T: H < 12 ? "A" : "P", TT: H < 12 ? "AM" : "PM", Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] }; return mask.replace(token, function($0) { return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); }); }; }(); // Some common format strings dateFormat.masks = { "default": "ddd mmm dd yyyy HH:MM:ss", shortDate: "m/d/yy", mediumDate: "mmm d, yyyy", longDate: "mmmm d, yyyy", fullDate: "dddd, mmmm d, yyyy", shortTime: "h:MM TT", mediumTime: "h:MM:ss TT", longTime: "h:MM:ss TT Z", isoDate: "yyyy-mm-dd", isoTime: "HH:MM:ss", isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" }; // Internationalization strings dateFormat.i18n = { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; // For convenience... Date.prototype.format = function(mask, utc) { return dateFormat(this, mask, utc); }; w.Helper = { setDateFormat: function (format) { if ( typeof(format) === 'string' ) Helper.format = format.trim(); }, setDateLink: function (format) { if ( typeof(format) === 'string' ) Helper.dateLinkFormat = format.trim(); }, daysInMonth: function (year, month) { return new Date(year, month, 0).getDate(); }, dayName: function (year, month, day) { var _dayNameIndex = new Date(year, month-1, day).getDay(); var _dayNames = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat']; var _dayNamesInArabic = ['الاحد', 'الاثنين', 'الثلاثاء', 'الاربعاء', 'الخميس', 'الجمعة', 'السبت']; return _dayNamesInArabic[_dayNameIndex]; }, daysInMonthObject: function (year, month) { var numberOfDaysInMonth = Helper.daysInMonth(year, month); if ( typeof(Helper.format) === 'undefined' ) Helper.format = 'yyyy-mm-dd'; var daysInMonthObject = []; for ( var i=1; i<= numberOfDaysInMonth; i++) { var _tmp = new Date(year, month-1, i); daysInMonthObject.push( { number: i, name: Helper.dayName(year, month, i), date: _tmp.format(Helper.format), } ) } return daysInMonthObject; }, } w.calender = { init: function () { calender.prepare(); calender.events(); calender.buildYears(); calender.buildMonths(); calender.yearsAndMonthsOwl(); $(document).on('calenderReady', function () { $('#dateSlider').find('.owl-item').has('.today').addClass('selected'); var isCurrentYear = calender.currentYear == $('#year').find('.owl-item.active').children('div').text().trim(); var isCurrentMonth = calender.currentMonth == $('#month').find('.owl-item.active').children('div').attr('data-month').trim(); if ( isCurrentYear && isCurrentMonth ) { for (var i = 1; i < calender.currentDay; i++) { $('.days .owl-next').trigger('click'); }; } }); }, selectedDate: function () { var day = $('#dateSlider').find('.selected').children('div').first().data('date'); if ( ! day ) return null; var year = $('#year').find('.owl-item.active').children('div').text().trim(); var month = $('#month').find('.owl-item.active').children('div').attr('data-month').trim(); return year + '/' + month + '/' + day; }, prepare: function () { calender.daysTemplate = _.template( $('#calender-days-template').html() ); calender.yearsTemplate = _.template( $('#calender-years-template').html() ); calender.monthsTemplate = _.template( $('#calender-months-template').html() ); calender.yearsRange = parseInt( $('.date-slider').attr('data-years-range') ); calender.now = new Date( $('.date-slider').attr('data-now') ); calender.currentYear = calender.now.getFullYear(); calender.currentMonth = calender.now.getMonth() + 1; calender.currentDay = calender.now.getDate(); }, buildYears: function () { $('#year').html( calender.yearsTemplate({ range: calender.yearsRange, currentYear: calender.currentYear }) ); }, buildMonths: function () { $('#month').html( calender.monthsTemplate({ currentMonth: calender.currentMonth }) ); }, yearsAndMonthsOwl: function () { $("#year, #month").owlCarousel({ rtl:true, loop:true, nav:true, rewindNav : true, responsive:{ 0:{ items:1 }, 600:{ items:1 }, 1000:{ items:1 } } }); }, events: function () { $("#year, #month").on('changed.owl.carousel', function (){ clearTimeout(calender._timeout); calender._timeout = setTimeout( function () { if ( calender.daysOwlObject !== undefined ) { calender.daysOwlObject.destroy(); } var year = parseInt( $('#year').find('.owl-item.active').children('div').text().trim() ); var month = parseInt( $('#month').find('.owl-item.active').children('div').attr('data-month').trim() ); calender.buildDays( Helper.daysInMonthObject(year, month) ); calender.daysOwl(); }, 100 ); }); $('#dateSlider').on('click', '.owl-item', function () { $(this).siblings().removeClass('selected'); $(this).addClass('selected'); /* delete later */ var then = calender.selectedDate(); if ( then != null ) $('#preview').removeClass('hidden').find('h1').text( then ); /* // */ }); /*$('.date-slider').on('click', '.owl-next, .owl-prev',function () { $('#dateSlider').find('.owl-item').removeClass('selected'); });*/ }, buildDays: function (data) { var year = parseInt( $('#year').find('.owl-item.active').children('div').text().trim() ); var month = parseInt( $('#month').find('.owl-item.active').children('div').attr('data-month').trim() ); $('#dateSlider').html( calender.daysTemplate({ data: data, currentDay: calender.currentDay, currentMonth: calender.currentMonth, currentYear: calender.currentYear, selectedMonth: month, selectedYear: year, }) ); }, daysOwl: function () { $("#dateSlider").owlCarousel({ rtl:true, nav:true, responsive:{ 1000:{ items:15 } } }); calender.daysOwlObject = $("#dateSlider").data('owlCarousel'); $(document).trigger('calenderReady'); } } $(document).ready(function () { calender.init(); }); })(jQuery, window);
/** * AssetController * * @description :: Server-side logic for managing assets * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ var _ = require('lodash'); var path = require('path'); var actionUtil = require('sails/lib/hooks/blueprints/actionUtil'); var Promise = require('bluebird'); module.exports = { /** * Download a release artifact * * Note: if a filename is specified, nothing but the filetype is used. * This is because Squirrel.Windows does a poor job of parsing the filename, * and so we must fake the filenames of x32 and x64 versions to be the same. * * (GET /download/latest/:platform?': 'AssetController.download') * (GET /download/:version/:platform?/:filename?': 'AssetController.download') * (GET /download/channel/:channel/:platform?': 'AssetController.download') * (GET /download/flavor/:flavor/latest/:platform?': 'AssetController.download') * (GET /download/flavor/:flavor/:version/:platform?/:filename?': 'AssetController.download') * (GET /download/flavor/:flavor/channel/:channel/:platform?': 'AssetController.download') */ download: function(req, res) { var channel = req.params.channel; var version = req.params.version || undefined; var filename = req.params.filename; var filetype = req.query.filetype; const flavor = req.params.flavor || 'default'; // We accept multiple platforms (x64 implies x32) var platforms; var platform = req.param('platform'); if (platform) { platforms = [platform]; } // Normalize filetype by prepending with period if (_.isString(filetype) && filetype[0] !== '.') { filetype = '.' + filetype; } else if (filename) { filetype = filename.substr(filename.lastIndexOf('.')); } // Detect platform from useragent if (!platforms) { platforms = PlatformService.detectFromRequest(req); if (!platforms) { return res.serverError( 'No platform specified and detecting one was unsuccessful.' ); } } else { platforms = PlatformService.sanitize(platforms); } if (!version) { channel = channel || 'stable'; } new Promise(function(resolve, reject) { var assetOptions = UtilityService.getTruthyObject({ platform: platforms, filetype: filetype }); sails.log.debug('Asset requested with options', assetOptions); if (version || channel) { Version .find(UtilityService.getTruthyObject({ name: version, channel: channel, flavor })) .sort({ createdAt: 'desc' }) // the latest version maybe has no assets, for example // the moment between creating a version and uploading assets, // so find more than 1 version and use the one containing assets. .limit(10) .populate('assets', assetOptions) .then(function(versions) { if (!versions || !versions.length) { return resolve(); } // sort versions by `name` instead of `createdAt`, // an lower version could be deleted then be created again, // thus it has newer `createdAt`. versions = versions.sort(UtilityService.compareVersion); var version = versions[0]; var version; for (var i = 0; i < versions.length; i++) { version = versions[i]; if (version.assets && version.assets.length) { break; } } if (!version.assets || !version.assets.length) { return resolve(); } // Sorting filename in ascending order prioritizes other files // over zip archives is both are available and matched. return resolve(_.orderBy( version.assets, ['filetype', 'createdAt'], ['asc', 'desc'] )[0]); }) .catch(reject); } else { Asset .find(assetOptions) .sort({ createdAt: 'desc' }) .limit(1) .then(resolve) .catch(reject); } }) .then(function(asset) { if (!asset || !asset.fd) { let noneFoundMessage = `The ${flavor} flavor has no download available`; if (platforms) { if (platforms.length > 1) { noneFoundMessage += ' for platforms ' + platforms.toString(); } else { noneFoundMessage += ' for platform ' + platforms[0]; } } noneFoundMessage += version ? ' for version ' + version : ''; noneFoundMessage += channel ? ' (' + channel + ') ' : ''; noneFoundMessage += filename ? ' with filename ' + filename : ''; noneFoundMessage += filetype ? ' with filetype ' + filetype : ''; return res.notFound(noneFoundMessage); } // Serve asset & log analytics return AssetService.serveFile(req, res, asset); }) // Catch any unhandled errors .catch(res.negotiate); }, create: function(req, res) { // Create data object (monolithic combination of all parameters) // Omit the blacklisted params (like JSONP callback param, etc.) var data = actionUtil.parseValues(req); if (!data.version) { return res.badRequest('A version is required.'); } if (_.isString(data.version)) { // Only a id was provided, normalize data.version = { id: data.version }; } else if (data.version && data.version.id) { // Valid request, but we only want the id data.version = { id: data.version.id }; } else { return res.badRequest('Invalid version provided.'); } // Check that the version exists (or its `_default` flavor equivalent) Version .find({ id: [data.version.id, `${data.version.id}_default`] }) .then(versions => { if (!versions || !versions.length) { return res.notFound('The specified `version` does not exist'); } data.version.id = versions[versions.length - 1].id; // Set upload request timeout to 10 minutes req.setTimeout(10 * 60 * 1000); req.file('file').upload(sails.config.files, function whenDone(err, uploadedFiles) { if (err) { return res.negotiate(err); } // If an unexpected number of files were uploaded, respond with an // error. if (uploadedFiles.length !== 1) { return res.badRequest('No file was uploaded'); } var uploadedFile = uploadedFiles[0]; var fileExt = path.extname(uploadedFile.filename); sails.log.debug('Creating asset with name', data.name || uploadedFile.filename); var hashPromise; if (fileExt === '.nupkg') { // Calculate the hash of the file, as it is necessary for windows // files hashPromise = AssetService.getHash(uploadedFile.fd); } else if (fileExt === '.exe' || fileExt === '.zip') { hashPromise = AssetService.getHash( uploadedFile.fd, "sha512", "base64" ); } else { hashPromise = Promise.resolve(''); } hashPromise .then(function(fileHash) { // Create new instance of model using data from params Asset .create(_.merge({ name: uploadedFile.filename, hash: fileHash, filetype: fileExt, fd: uploadedFile.fd, size: uploadedFile.size }, data)) .exec(function created(err, newInstance) { // Differentiate between waterline-originated validation errors // and serious underlying issues. Respond with badRequest if a // validation error is encountered, w/ validation info. if (err) return res.negotiate(err); // If we have the pubsub hook, use the model class's publish // method to notify all subscribers about the created item. if (req._sails.hooks.pubsub) { if (req.isSocket) { Asset.subscribe(req, newInstance); Asset.introduce(newInstance); } Asset.publishCreate(newInstance, !req.options.mirror && req); } // Send JSONP-friendly response if it's supported res.created(newInstance); }); }) .catch(res.negotiate); }); }); }, destroy: function(req, res) { var pk = actionUtil.requirePk(req); var query = Asset.findOne(pk); query.populate('version'); query .then(function foundRecord(record) { if (!record) return res.notFound( 'No record found with the specified `name`.' ); // Delete the file & remove from db return Promise.join( AssetService.destroy(record, req), AssetService.deleteFile(record), function() {}) .then(function success() { res.ok(record); }); }) .error(res.negotiate); } };
import Base from 'simple-auth/authenticators/base'; import Configuration from './../configuration'; /** Authenticator that conforms to OAuth 2 ([RFC 6749](http://tools.ietf.org/html/rfc6749)), specifically the _"Resource Owner Password Credentials Grant Type"_. This authenticator supports access token refresh (see [RFC 6740, section 6](http://tools.ietf.org/html/rfc6749#section-6)). _The factory for this authenticator is registered as `'simple-auth-authenticator:oauth2-password-grant'` in Ember's container._ @class OAuth2 @namespace SimpleAuth.Authenticators @module simple-auth-oauth2/authenticators/oauth2 @extends Base */ export default Base.extend({ /** Triggered when the authenticator refreshes the access token (see [RFC 6740, section 6](http://tools.ietf.org/html/rfc6749#section-6)). @event sessionDataUpdated @param {Object} data The updated session data */ /** The endpoint on the server the authenticator acquires the access token from. This value can be configured via [`SimpleAuth.Configuration.OAuth2#serverTokenEndpoint`](#SimpleAuth-Configuration-OAuth2-serverTokenEndpoint). @property serverTokenEndpoint @type String @default '/token' */ serverTokenEndpoint: '/token', /** The endpoint on the server the authenticator uses to revoke tokens. Only set this if the server actually supports token revokation. This value can be configured via [`SimpleAuth.Configuration.OAuth2#serverTokenRevocationEndpoint`](#SimpleAuth-Configuration-OAuth2-serverTokenRevocationEndpoint). @property serverTokenRevocationEndpoint @type String @default null */ serverTokenRevocationEndpoint: null, /** Sets whether the authenticator automatically refreshes access tokens. This value can be configured via [`SimpleAuth.Configuration.OAuth2#refreshAccessTokens`](#SimpleAuth-Configuration-OAuth2-refreshAccessTokens). @property refreshAccessTokens @type Boolean @default true */ refreshAccessTokens: true, /** @property _refreshTokenTimeout @private */ _refreshTokenTimeout: null, /** @method init @private */ init: function() { this.serverTokenEndpoint = Configuration.serverTokenEndpoint; this.serverTokenRevocationEndpoint = Configuration.serverTokenRevocationEndpoint; this.refreshAccessTokens = Configuration.refreshAccessTokens; }, /** Restores the session from a set of session properties; __will return a resolving promise when there's a non-empty `access_token` in the `data`__ and a rejecting promise otherwise. This method also schedules automatic token refreshing when there are values for `refresh_token` and `expires_in` in the `data` and automatic token refreshing is not disabled (see [`Authenticators.OAuth2#refreshAccessTokens`](#SimpleAuth-Authenticators-OAuth2-refreshAccessTokens)). @method restore @param {Object} data The data to restore the session from @return {Ember.RSVP.Promise} A promise that when it resolves results in the session being authenticated */ restore: function(data) { var _this = this; return new Ember.RSVP.Promise(function(resolve, reject) { var now = (new Date()).getTime(); if (!Ember.isEmpty(data.expires_at) && data.expires_at < now) { if (_this.refreshAccessTokens) { _this.refreshAccessToken(data.expires_in, data.refresh_token).then(function(data) { resolve(data); }, reject); } else { reject(); } } else { if (Ember.isEmpty(data.access_token)) { reject(); } else { _this.scheduleAccessTokenRefresh(data.expires_in, data.expires_at, data.refresh_token); resolve(data); } } }); }, /** Authenticates the session with the specified `credentials`; the credentials are send via a _"POST"_ request to the [`Authenticators.OAuth2#serverTokenEndpoint`](#SimpleAuth-Authenticators-OAuth2-serverTokenEndpoint) and if they are valid the server returns an access token in response (see http://tools.ietf.org/html/rfc6749#section-4.3). __If the credentials are valid and authentication succeeds, a promise that resolves with the server's response is returned__, otherwise a promise that rejects with the error is returned. This method also schedules automatic token refreshing when there are values for `refresh_token` and `expires_in` in the server response and automatic token refreshing is not disabled (see [`Authenticators.OAuth2#refreshAccessTokens`](#SimpleAuth-Authenticators-OAuth2-refreshAccessTokens)). @method authenticate @param {Object} credentials The credentials to authenticate the session with @return {Ember.RSVP.Promise} A promise that resolves when an access token is successfully acquired from the server and rejects otherwise */ authenticate: function(credentials) { var _this = this; return new Ember.RSVP.Promise(function(resolve, reject) { var data = { grant_type: 'password', username: credentials.identification, password: credentials.password }; _this.makeRequest(_this.serverTokenEndpoint, data).then(function(response) { Ember.run(function() { var expiresAt = _this.absolutizeExpirationTime(response.expires_in); _this.scheduleAccessTokenRefresh(response.expires_in, expiresAt, response.refresh_token); if (!Ember.isEmpty(expiresAt)) { response = Ember.merge(response, { expires_at: expiresAt }); } resolve(response); }); }, function(xhr, status, error) { Ember.run(function() { reject(xhr.responseJSON || xhr.responseText); }); }); }); }, /** Cancels any outstanding automatic token refreshes and returns a resolving promise. @method invalidate @param {Object} data The data of the session to be invalidated @return {Ember.RSVP.Promise} A resolving promise */ invalidate: function(data) { var _this = this; function success(resolve) { Ember.run.cancel(_this._refreshTokenTimeout); delete _this._refreshTokenTimeout; resolve(); } return new Ember.RSVP.Promise(function(resolve, reject) { if (!Ember.isEmpty(_this.serverTokenRevocationEndpoint)) { var requests = []; Ember.A(['access_token', 'refresh_token']).forEach(function(tokenType) { if (!Ember.isEmpty(data[tokenType])) { requests.push(_this.makeRequest(_this.serverTokenRevocationEndpoint, { token_type_hint: tokenType, token: data[tokenType] })); } }); Ember.$.when.apply(Ember.$, requests).always(function(responses) { success(resolve); }); } else { success(resolve); } }); }, /** Sends an `AJAX` request to the `url`. This will always be a _"POST"_ request with content type _"application/x-www-form-urlencoded"_ as specified in [RFC 6749](http://tools.ietf.org/html/rfc6749). This method is not meant to be used directly but serves as an extension point to e.g. add _"Client Credentials"_ (see [RFC 6749, section 2.3](http://tools.ietf.org/html/rfc6749#section-2.3)). @method makeRequest @param {Object} url The url to send the request to @param {Object} data The data to send with the request, e.g. username and password or the refresh token @return {Deferred object} A Deferred object (see [the jQuery docs](http://api.jquery.com/category/deferred-object/)) that is compatible to Ember.RSVP.Promise; will resolve if the request succeeds, reject otherwise @protected */ makeRequest: function(url, data) { return Ember.$.ajax({ url: url, type: 'POST', data: data, dataType: 'json', contentType: 'application/x-www-form-urlencoded' }); }, /** @method scheduleAccessTokenRefresh @private */ scheduleAccessTokenRefresh: function(expiresIn, expiresAt, refreshToken) { var _this = this; if (this.refreshAccessTokens) { var now = (new Date()).getTime(); if (Ember.isEmpty(expiresAt) && !Ember.isEmpty(expiresIn)) { expiresAt = new Date(now + expiresIn * 1000).getTime(); } var offset = (Math.floor(Math.random() * 5) + 5) * 1000; if (!Ember.isEmpty(refreshToken) && !Ember.isEmpty(expiresAt) && expiresAt > now - offset) { Ember.run.cancel(this._refreshTokenTimeout); delete this._refreshTokenTimeout; if (!Ember.testing) { this._refreshTokenTimeout = Ember.run.later(this, this.refreshAccessToken, expiresIn, refreshToken, expiresAt - now - offset); } } } }, /** @method refreshAccessToken @private */ refreshAccessToken: function(expiresIn, refreshToken) { var _this = this; var data = { grant_type: 'refresh_token', refresh_token: refreshToken }; return new Ember.RSVP.Promise(function(resolve, reject) { _this.makeRequest(_this.serverTokenEndpoint, data).then(function(response) { Ember.run(function() { expiresIn = response.expires_in || expiresIn; refreshToken = response.refresh_token || refreshToken; var expiresAt = _this.absolutizeExpirationTime(expiresIn); var data = Ember.merge(response, { expires_in: expiresIn, expires_at: expiresAt, refresh_token: refreshToken }); _this.scheduleAccessTokenRefresh(expiresIn, null, refreshToken); _this.trigger('sessionDataUpdated', data); resolve(data); }); }, function(xhr, status, error) { Ember.Logger.warn('Access token could not be refreshed - server responded with ' + error + '.'); reject(); }); }); }, /** @method absolutizeExpirationTime @private */ absolutizeExpirationTime: function(expiresIn) { if (!Ember.isEmpty(expiresIn)) { return new Date((new Date().getTime()) + expiresIn * 1000).getTime(); } } });
var path = require('path'), fs = require('fs-extended'); module.exports = function(dest, options) { var file = path.join(dest, "composer.json"); if (fs.existsSync(file)) { var data = fs.readFileSync(file, { encoding: 'utf8' }); if (data) { var pkg = JSON.parse(data); pkg.name = typeof options.name === 'string' ? options.name : pkg.name; pkg.description = typeof options.description === 'string' ? options.description : pkg.description; pkg.version = typeof options.version === 'string' ? options.version : pkg.version; data = JSON.stringify(pkg, null, 2); fs.writeFileSync(file, data, 'utf8'); } } };
/*jslint node: true, nomen: true */ module.exports = function (childProcess, gearman) { 'use strict'; var syncUserProfileOnPostsByUserId, syncedCallback; syncUserProfileOnPostsByUserId = function (id, syncedCallback, worker) { var filteredId = parseInt(id, 10), cmdParams, cmd; if (isNaN(filteredId)) { syncedCallback({error: true, message: 'User ID received is not a number.'}); return; } cmdParams = '--controller search --action sync-user-profile-on-posts --uid ' + filteredId; cmd = 'php ' + __dirname + '/../../../bin/services ' + cmdParams; childProcess.exec(cmd, function (error, stdout, stderr) { if (error === null) { syncedCallback({error: false, message: stdout}, worker); return; } syncedCallback({error: true, message: stderr}, worker); }); }; syncedCallback = function (result, worker) { if (result.error) { worker.error(); console.error(result.message + '\n'); return; } worker.end(); console.info(result.message + '\n'); }; exports.setUpSyncUserProfileOnPostsFromUserWorker = function () { gearman.registerWorker('syncUserProfileOnPosts', function (payload, worker) { var uid = payload.toString('utf-8'); syncUserProfileOnPostsByUserId(uid, syncedCallback, worker); worker.end(); }); }; return exports; };
import _ from 'lodash'; const ModelResolver = requireF('core/services/resolvers/ModelResolver'); exports.register = async (server, options, next) => { const modelResolver = new ModelResolver(); const userModel = modelResolver.getModel('user'); server.ext('onRequest', async (request, reply) => { if (!request.auth.credentials && (!(_.has(request, 'query.token') || _.has(request, 'headers.authorization')))) { const anonymousUser = await userModel.findOne({ where: { username: 'anonymous', }, }); const defaultCredentials = _.pick(anonymousUser, ['id', 'username']); // eslint-disable-next-line no-param-reassign request.auth.credentials = defaultCredentials; } reply.continue(); }); return next(); }; exports.register.attributes = { name: 'package-default-user', version: '1.0.0', };
'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _utilJs = require('./../util.js'); /** @test {CoverageBuilder} */ describe('Coverage:', function () { /** @test {CoverageBuilder#exec} */ it('has coverage.json', function () { var json = _fs2['default'].readFileSync('./test/fixture/esdoc/coverage.json', { encoding: 'utf8' }).toString(); var coverage = JSON.parse(json); _utilJs.assert.equal(coverage.coverage, '79.06%'); _utilJs.assert.equal(coverage.expectCount, 86); _utilJs.assert.equal(coverage.actualCount, 68); _utilJs.assert.deepEqual(coverage.files, { 'src/ForTestDoc/AbstractDoc.js': { 'expectCount': 3, 'actualCount': 0 }, 'src/ForTestDoc/ClassDoc.js': { 'expectCount': 1, 'actualCount': 0 }, 'src/ForTestDoc/ClassDocBuilder.js': { 'expectCount': 2, 'actualCount': 0 }, 'src/MyClass.js': { 'expectCount': 36, 'actualCount': 31 }, 'src/MyError.js': { 'expectCount': 1, 'actualCount': 1 }, 'src/MyEvent.js': { 'expectCount': 1, 'actualCount': 1 }, 'src/MyInterface.js': { 'expectCount': 3, 'actualCount': 3 }, 'src/ExtendNest.js': { 'expectCount': 2, 'actualCount': 2 }, 'src/ReactJSX.js': { 'expectCount': 2, 'actualCount': 2 }, 'src/SeparateExport.js': { 'expectCount': 3, 'actualCount': 0 }, 'src/OtherClass/SuperMyClass.js': { 'expectCount': 19, 'actualCount': 19 }, 'src/myFunction.js': { 'expectCount': 8, 'actualCount': 6 }, 'src/myVariable.js': { 'expectCount': 5, 'actualCount': 3 } }); }); });
angular.module('PlayersApp').controller('contactController', ['$http', '$scope', contactController]); function contactController($http, $scope) { $(document).ready(function() { $('#contact_form').bootstrapValidator({ // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { name: { validators: { stringLength: { min: 2, }, notEmpty: { message: 'Please enter your name' } } }, email: { validators: { notEmpty: { message: 'Please enter your email address' }, emailAddress: { message: 'Please enter a valid email address' } } }, comment: { validators: { stringLength: { min: 10, max: 500, message:'Please enter at least 10 characters and no more than 500' }, notEmpty: { message: 'Please enter your message' } } } } }) .on('success.form.bv', function(e) { $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ... $('#contact_form').data('bootstrapValidator').resetForm(); // Prevent form submission e.preventDefault(); // Get the form instance var $form = $(e.target); // Get the BootstrapValidator instance var bv = $form.data('bootstrapValidator'); $http.get('/contact/' + $scope.name + '/' + $scope.email +'/' + $scope.message) }); }); }
import triggerBeforeSoftRestore from "./triggerBeforeSoftRestore"; import triggerAfterSoftRestore from "./triggerAfterSoftRestore"; const documentSoftRestore = function(args = {}) { const { doc, simulation = true, trusted = false } = args; // Stop execution, if we are not on the server, when the "simulation" flag is // not set. if (!simulation && !Meteor.isServer) { return; } const Class = doc.constructor; const Collection = Class.getCollection(); // Restore only when document has the "_id" field (it's persisted). if (Class.isNew(doc) || !doc._id) { return 0; } // Check if a class is secured. if (Class.isSecured("softRestore") && Meteor.isServer && !trusted) { throw new Meteor.Error( 403, "Soft restoring from the client is not allowed" ); } // Trigger before events. triggerBeforeSoftRestore(doc, trusted); // Prepare selector. const selector = { _id: doc._id }; // Prepare modifier. const modifier = { $set: {} }; const behavior = Class.getBehavior("softremove")[0]; modifier.$set[behavior.options.removedFieldName] = false; if (behavior.options.hasRemovedAtField) { modifier.$unset = { [behavior.options.removedAtFieldName]: "" }; } // Restore a document. const result = Collection._collection.update(selector, modifier); // Trigger after events. triggerAfterSoftRestore(doc, trusted); return result; }; export default documentSoftRestore;
'use strict'; describe('Service: PodcastFeed', function () { // load the service's module beforeEach(module('robitApp')); // instantiate service var Podcastfeed; beforeEach(inject(function (_PodcastFeed_) { PodcastFeed = _PodcastFeed_; })); it('should do something', function () { expect(!!PodcastFeed).toBe(true); }); });
const assert = require('assert'); const jyson = require('./../../../lib/jyson'); describe('jyson.basic.spec: a basic template', () => { beforeEach(() => { this.templateFunction = jyson.buildTemplateFunction({ a: 'a', b: 'b', c: 'c', }); }); it('must convert an object to "json"', () => { const input = { a: 1, b: 2, c: 3 }; const json = this.templateFunction(input); expect(json.a).toBe(input.a); expect(json.b).toBe(input.b); expect(json.c).toBe(input.c); }); it('must ignore additional values', () => { const input = { a: 1, b: 2, c: 3, d: 4 }; const json = this.templateFunction(input); expect(Object.keys(json)).toContain('a'); expect(Object.keys(json)).not.toContain('d'); }); it('must use null for missing objects', () => { const input = { a: 1, c: 3 }; const json = this.templateFunction(input); expect(json.b).toBeNull(); }); it('must error if it encounters an unexpected array', () => { const input = { a: [1], }; try { this.templateFunction(input); return Promise.reject('an error should have been thrown'); } catch(error) { expect(error).toBeInstanceOf(assert.AssertionError); expect(error.message).toBe('jyson encountered an array when it was not expecting one: a'); } }); it('must convert arrays "json"', () => { const input = [ { a:1 }, { b:2 }, { c:3 } ]; const json = this.templateFunction(input); expect(json).toEqual([ { a:1, b:null, c:null }, { a:null, b:2, c:null }, { a:null, b:null, c:3 } ]); }); it('must convert deep arrays "json"', () => { this.templateFunction = jyson.buildTemplateFunction({ a: { a: 'a.a' }, b: { b: 'b.b' }, c: { c: 'c.c' }, }); const input = [ { a:{ a: 1 } }, { b:{ b: 2 } }, { c:{ c: 3 } } ]; const json = this.templateFunction(input); expect(json).toEqual([ { a:{ a:1 }, b:{ b: null }, c:{ c: null } }, { a:{ a:null }, b:{ b: 2 }, c:{ c: null } }, { a:{ a:null }, b:{ b: null }, c:{ c: 3 } } ]); }); it('must convert an object with properties "json"', () => { const input = {}; Object.defineProperty(input, 'a', { get: () => { return 1; }, set: () => { }, enumerable: true, configurable: false }); Object.defineProperty(input, 'b', { get: () => { return 2; }, set: () => { }, enumerable: true, configurable: false }); Object.defineProperty(input, 'c', { get: () => { return 3; }, set: () => { }, enumerable: true, configurable: false }); const json = this.templateFunction(input); expect(json.a).toBe(1); expect(json.b).toBe(2); expect(json.c).toBe(3); }); });
var db = require('../db.js'); var Post = db.model('Post', { username: {type: String, required: true}, body: {type:String, required: true}, date: {type:Date, required:true, default:Date.now} }); module.exports = Post;
'use strict'; const chai = require('chai'); const assert = chai.assert; const fetch = require('node-fetch'); const co = require('co'); const stringify = require('querystring').stringify; const auth = require('../src/auth'); const crud = require('../src/crud'); describe('authentication', () => { const port = process.env.PORT || 4000; const rootUrl = 'http://localhost:' + port; let accessToken = null; it('should log in with username and password', co.wrap(function* () { const loginRes = yield fetch(rootUrl + '/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: stringify({ grant_type: 'password', client_id: 'webapp', client_secret: 'secret', username: 'test_user', password: 'test_password' }) }); assert.equal(loginRes.status, 200); const loginJson = yield loginRes.json(); assert.isNotNull(loginJson.access_token); assert.equal(loginJson.token_type, 'bearer'); accessToken = loginJson.access_token; })); it('should not load resources if there is no token', co.wrap(function* () { const messagesRes = yield fetch(rootUrl + '/messages'); assert.equal(messagesRes.status, 400); })); it('should load resources if token is present', co.wrap(function* () { const messagesRes = yield fetch(rootUrl + '/messages', { headers: { 'Authorization': 'Bearer ' + accessToken } }); assert.equal(messagesRes.status, 200); const messagesJson = yield messagesRes.json(); assert.equal(messagesJson.data[0].id, '11', ''); })); before(() => { auth.listen(port); crud.setConfig({ port: 5000 }); crud.start(); }); after(() => { auth.close(); crud.close(); }); });
define(['exports', 'aurelia-templating', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaPal) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.CssAnimator = undefined; exports.configure = configure; var CssAnimator = exports.CssAnimator = function () { function CssAnimator() { this.useAnimationDoneClasses = false; this.animationEnteredClass = 'au-entered'; this.animationLeftClass = 'au-left'; this.isAnimating = false; this.verifyKeyframesExist = true; } CssAnimator.prototype._addMultipleEventListener = function _addMultipleEventListener(el, s, fn) { var evts = s.split(' '); for (var i = 0, ii = evts.length; i < ii; ++i) { el.addEventListener(evts[i], fn, false); } }; CssAnimator.prototype._removeMultipleEventListener = function _removeMultipleEventListener(el, s, fn) { var evts = s.split(' '); for (var i = 0, ii = evts.length; i < ii; ++i) { el.removeEventListener(evts[i], fn, false); } }; CssAnimator.prototype._getElementAnimationDelay = function _getElementAnimationDelay(element) { var styl = _aureliaPal.DOM.getComputedStyle(element); var prop = void 0; var delay = void 0; if (styl.getPropertyValue('animation-delay')) { prop = 'animation-delay'; } else if (styl.getPropertyValue('-webkit-animation-delay')) { prop = '-webkit-animation-delay'; } else if (styl.getPropertyValue('-moz-animation-delay')) { prop = '-moz-animation-delay'; } else { return 0; } delay = styl.getPropertyValue(prop); delay = Number(delay.replace(/[^\d\.]/g, '')); return delay * 1000; }; CssAnimator.prototype._getElementAnimationNames = function _getElementAnimationNames(element) { var styl = _aureliaPal.DOM.getComputedStyle(element); var prefix = void 0; if (styl.getPropertyValue('animation-name')) { prefix = ''; } else if (styl.getPropertyValue('-webkit-animation-name')) { prefix = '-webkit-'; } else if (styl.getPropertyValue('-moz-animation-name')) { prefix = '-moz-'; } else { return []; } var animationNames = styl.getPropertyValue(prefix + 'animation-name'); return animationNames ? animationNames.split(' ') : []; }; CssAnimator.prototype._performSingleAnimate = function _performSingleAnimate(element, className) { var _this = this; this._triggerDOMEvent(_aureliaTemplating.animationEvent.animateBegin, element); return this.addClass(element, className, true).then(function (result) { _this._triggerDOMEvent(_aureliaTemplating.animationEvent.animateActive, element); if (result !== false) { return _this.removeClass(element, className, true).then(function () { _this._triggerDOMEvent(_aureliaTemplating.animationEvent.animateDone, element); }); } return false; }).catch(function () { _this._triggerDOMEvent(_aureliaTemplating.animationEvent.animateTimeout, element); }); }; CssAnimator.prototype._triggerDOMEvent = function _triggerDOMEvent(eventType, element) { var evt = _aureliaPal.DOM.createCustomEvent(eventType, { bubbles: true, cancelable: true, detail: element }); _aureliaPal.DOM.dispatchEvent(evt); }; CssAnimator.prototype._animationChangeWithValidKeyframe = function _animationChangeWithValidKeyframe(animationNames, prevAnimationNames) { var newAnimationNames = animationNames.filter(function (name) { return prevAnimationNames.indexOf(name) === -1; }); if (newAnimationNames.length === 0) { return false; } if (!this.verifyKeyframesExist) { return true; } var keyframesRuleType = window.CSSRule.KEYFRAMES_RULE || window.CSSRule.MOZ_KEYFRAMES_RULE || window.CSSRule.WEBKIT_KEYFRAMES_RULE; var styleSheets = document.styleSheets; try { for (var i = 0; i < styleSheets.length; ++i) { var cssRules = null; try { cssRules = styleSheets[i].cssRules; } catch (e) {} if (!cssRules) { continue; } for (var j = 0; j < cssRules.length; ++j) { var cssRule = cssRules[j]; if (cssRule.type === keyframesRuleType) { if (newAnimationNames.indexOf(cssRule.name) !== -1) { return true; } } } } } catch (e) {} return false; }; CssAnimator.prototype.animate = function animate(element, className) { var _this2 = this; if (Array.isArray(element)) { return Promise.all(element.map(function (el) { return _this2._performSingleAnimate(el, className); })); } return this._performSingleAnimate(element, className); }; CssAnimator.prototype.runSequence = function runSequence(animations) { var _this3 = this; this._triggerDOMEvent(_aureliaTemplating.animationEvent.sequenceBegin, null); return animations.reduce(function (p, anim) { return p.then(function () { return _this3.animate(anim.element, anim.className); }); }, Promise.resolve(true)).then(function () { _this3._triggerDOMEvent(_aureliaTemplating.animationEvent.sequenceDone, null); }); }; CssAnimator.prototype._stateAnim = function _stateAnim(element, direction, doneClass) { var _this4 = this; var auClass = 'au-' + direction; var auClassActive = auClass + '-active'; return new Promise(function (resolve, reject) { var classList = element.classList; _this4._triggerDOMEvent(_aureliaTemplating.animationEvent[direction + 'Begin'], element); if (_this4.useAnimationDoneClasses) { classList.remove(_this4.animationEnteredClass); classList.remove(_this4.animationLeftClass); } classList.add(auClass); var prevAnimationNames = _this4._getElementAnimationNames(element); var _animStart = void 0; var animHasStarted = false; _this4._addMultipleEventListener(element, 'webkitAnimationStart animationstart', _animStart = function animStart(evAnimStart) { if (evAnimStart.target !== element) { return; } animHasStarted = true; _this4.isAnimating = true; _this4._triggerDOMEvent(_aureliaTemplating.animationEvent[direction + 'Active'], element); evAnimStart.stopPropagation(); evAnimStart.target.removeEventListener(evAnimStart.type, _animStart); }, false); var _animEnd = void 0; _this4._addMultipleEventListener(element, 'webkitAnimationEnd animationend', _animEnd = function animEnd(evAnimEnd) { if (!animHasStarted) { return; } if (evAnimEnd.target !== element) { return; } evAnimEnd.stopPropagation(); classList.remove(auClassActive); classList.remove(auClass); evAnimEnd.target.removeEventListener(evAnimEnd.type, _animEnd); if (_this4.useAnimationDoneClasses && doneClass !== undefined && doneClass !== null) { classList.add(doneClass); } _this4.isAnimating = false; _this4._triggerDOMEvent(_aureliaTemplating.animationEvent[direction + 'Done'], element); resolve(true); }, false); var parent = element.parentElement; var attrib = 'data-animator-pending' + direction; var cleanupAnimation = function cleanupAnimation() { var animationNames = _this4._getElementAnimationNames(element); if (!_this4._animationChangeWithValidKeyframe(animationNames, prevAnimationNames)) { classList.remove(auClassActive); classList.remove(auClass); _this4._removeMultipleEventListener(element, 'webkitAnimationEnd animationend', _animEnd); _this4._removeMultipleEventListener(element, 'webkitAnimationStart animationstart', _animStart); _this4._triggerDOMEvent(_aureliaTemplating.animationEvent[direction + 'Timeout'], element); resolve(false); } parent && parent.setAttribute(attrib, +(parent.getAttribute(attrib) || 1) - 1); }; if (parent !== null && parent !== undefined && (parent.classList.contains('au-stagger') || parent.classList.contains('au-stagger-' + direction))) { var offset = +(parent.getAttribute(attrib) || 0); parent.setAttribute(attrib, offset + 1); var delay = _this4._getElementAnimationDelay(parent) * offset; _this4._triggerDOMEvent(_aureliaTemplating.animationEvent.staggerNext, element); setTimeout(function () { classList.add(auClassActive); cleanupAnimation(); }, delay); } else { classList.add(auClassActive); cleanupAnimation(); } }); }; CssAnimator.prototype.enter = function enter(element) { return this._stateAnim(element, 'enter', this.animationEnteredClass); }; CssAnimator.prototype.leave = function leave(element) { return this._stateAnim(element, 'leave', this.animationLeftClass); }; CssAnimator.prototype.removeClass = function removeClass(element, className) { var _this5 = this; var suppressEvents = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return new Promise(function (resolve, reject) { var classList = element.classList; if (!classList.contains(className) && !classList.contains(className + '-add')) { resolve(false); return; } if (suppressEvents !== true) { _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.removeClassBegin, element); } if (classList.contains(className + '-add')) { classList.remove(className + '-add'); classList.add(className); } classList.remove(className); var prevAnimationNames = _this5._getElementAnimationNames(element); var _animStart2 = void 0; var animHasStarted = false; _this5._addMultipleEventListener(element, 'webkitAnimationStart animationstart', _animStart2 = function animStart(evAnimStart) { if (evAnimStart.target !== element) { return; } animHasStarted = true; _this5.isAnimating = true; if (suppressEvents !== true) { _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.removeClassActive, element); } evAnimStart.stopPropagation(); evAnimStart.target.removeEventListener(evAnimStart.type, _animStart2); }, false); var _animEnd2 = void 0; _this5._addMultipleEventListener(element, 'webkitAnimationEnd animationend', _animEnd2 = function animEnd(evAnimEnd) { if (!animHasStarted) { return; } if (evAnimEnd.target !== element) { return; } if (!element.classList.contains(className + '-remove')) { resolve(true); } evAnimEnd.stopPropagation(); classList.remove(className); classList.remove(className + '-remove'); evAnimEnd.target.removeEventListener(evAnimEnd.type, _animEnd2); _this5.isAnimating = false; if (suppressEvents !== true) { _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.removeClassDone, element); } resolve(true); }, false); classList.add(className + '-remove'); var animationNames = _this5._getElementAnimationNames(element); if (!_this5._animationChangeWithValidKeyframe(animationNames, prevAnimationNames)) { classList.remove(className + '-remove'); classList.remove(className); _this5._removeMultipleEventListener(element, 'webkitAnimationEnd animationend', _animEnd2); _this5._removeMultipleEventListener(element, 'webkitAnimationStart animationstart', _animStart2); if (suppressEvents !== true) { _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.removeClassTimeout, element); } resolve(false); } }); }; CssAnimator.prototype.addClass = function addClass(element, className) { var _this6 = this; var suppressEvents = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return new Promise(function (resolve, reject) { var classList = element.classList; if (suppressEvents !== true) { _this6._triggerDOMEvent(_aureliaTemplating.animationEvent.addClassBegin, element); } if (classList.contains(className + '-remove')) { classList.remove(className + '-remove'); classList.remove(className); } var _animStart3 = void 0; var animHasStarted = false; _this6._addMultipleEventListener(element, 'webkitAnimationStart animationstart', _animStart3 = function animStart(evAnimStart) { if (evAnimStart.target !== element) { return; } animHasStarted = true; _this6.isAnimating = true; if (suppressEvents !== true) { _this6._triggerDOMEvent(_aureliaTemplating.animationEvent.addClassActive, element); } evAnimStart.stopPropagation(); evAnimStart.target.removeEventListener(evAnimStart.type, _animStart3); }, false); var _animEnd3 = void 0; _this6._addMultipleEventListener(element, 'webkitAnimationEnd animationend', _animEnd3 = function animEnd(evAnimEnd) { if (!animHasStarted) { return; } if (evAnimEnd.target !== element) { return; } if (!element.classList.contains(className + '-add')) { resolve(true); } evAnimEnd.stopPropagation(); classList.add(className); classList.remove(className + '-add'); evAnimEnd.target.removeEventListener(evAnimEnd.type, _animEnd3); _this6.isAnimating = false; if (suppressEvents !== true) { _this6._triggerDOMEvent(_aureliaTemplating.animationEvent.addClassDone, element); } resolve(true); }, false); var prevAnimationNames = _this6._getElementAnimationNames(element); classList.add(className + '-add'); var animationNames = _this6._getElementAnimationNames(element); if (!_this6._animationChangeWithValidKeyframe(animationNames, prevAnimationNames)) { classList.remove(className + '-add'); classList.add(className); _this6._removeMultipleEventListener(element, 'webkitAnimationEnd animationend', _animEnd3); _this6._removeMultipleEventListener(element, 'webkitAnimationStart animationstart', _animStart3); if (suppressEvents !== true) { _this6._triggerDOMEvent(_aureliaTemplating.animationEvent.addClassTimeout, element); } resolve(false); } }); }; return CssAnimator; }(); function configure(config, callback) { var animator = config.container.get(CssAnimator); config.container.get(_aureliaTemplating.TemplatingEngine).configureAnimator(animator); if (typeof callback === 'function') { callback(animator); } } });
/*global document, window, setTimeout, clearTimeout, module, test, asyncTest, ok, equal, start, Boot*/ (function () { "use strict"; module("Boot.getCSS"); test("Environment", function () { ok(window.Boot, 'Boot is defined.'); ok(window.Boot.getCSS, 'Boot.getCSS is defined.'); }); asyncTest("Load a single stylesheet.", function () { Boot.getCSS("css/css1.css"); ok(true); start(); }); asyncTest("Load a stylesheet and execute callback.", function () { Boot.getCSS("css/css2.css", function () { ok(true); start(); }); }); asyncTest("Load the same stylesheet and only execute callback.", function () { Boot.getCSS("css/css2.css", function () { ok(true); start(); }); }); }());
/* jshint node: true */ 'use strict'; var autoprefixer = require( 'broccoli-autoprefixer' ); var path = require( 'path' ); var mergeTrees = require( 'broccoli-merge-trees' ); var Funnel = require( 'broccoli-funnel' ); var compileLess = require( 'broccoli-less-single' ); var componentClassPrefix; var fingerprintDefaults = require( 'broccoli-asset-rev/lib/default-options' ); /** * A variable to hold the state of whether ember-cli-less is installed * * @type {Boolean} */ var isLessAddonInstalled = false; /** * Traverses an array and removes duplicate elements * * @param {Array} array * @returns {Array} */ var unique = function( array ) { var isDuplicateElement = {}; var uniqueArray = []; var arrayLength = array.length; for( var i = 0; i < arrayLength; i++ ) { if ( !isDuplicateElement[ array[ i ] ] ) { isDuplicateElement[ array[ i ] ] = true; uniqueArray.push( array[ i ] ); } } return uniqueArray; }; module.exports = { name: 'sl-ember-components', config: function() { return { 'componentClassPrefix': componentClassPrefix }; }, /** * Name used for LESS-generated CSS file placed in vendor tree * * @returns {String} */ getCssFileName: function() { return this.name + '.css'; }, /** * Whether this module is being accessed by an addon or an app * * @returns {Boolean} */ isAddon: function() { var keywords = this.project.pkg.keywords; return ( keywords && keywords.indexOf( 'ember-addon' ) !== -1 ) ? true : false; }, /** * Adds LESS-generated CSS into vendor tree of consuming app to be imported in included() * * Only does so if the consuming app is not making use of the ember-cli-less addon * * @param {Object} tree * @returns {Object} */ treeForVendor: function( tree ) { var vendorTree = tree; if ( !this.isAddon() && !isLessAddonInstalled ) { var folder = ( Number( process.version.match( /^v(\d+)/ )[1] ) >= 5 ) ? this.name : '../'; var compiledLessTree = compileLess( new Funnel( path.join( this.nodeModulesPath, folder, 'app' ) ), 'styles/' + this.name + '.less', this.getCssFileName(), { modifyVars: { 'component-class-prefix': componentClassPrefix } } ); compiledLessTree = autoprefixer( compiledLessTree, { browsers: [ 'Android 2.3', 'Android >= 4', 'Chrome >= 20', 'Firefox >= 24', 'Explorer >= 8', 'iOS >= 6', 'Opera >= 12', 'Safari >= 6' ] } ); vendorTree = ( tree ) ? mergeTrees([ tree, compiledLessTree ]) : compiledLessTree; } return vendorTree; }, included: function( app ) { this._super.included( app ); var addonOptions = app.options[ 'sl-ember-components' ]; if ( addonOptions && addonOptions.componentClassPrefix ) { componentClassPrefix = addonOptions.componentClassPrefix; } else { componentClassPrefix = this.name; } var fingerprintOptions = app.options.fingerprint; if ( fingerprintOptions.enabled ) { var fingerprintDefaultsSorted = fingerprintDefaults.extensions.sort(); var fingerprintOptionsSorted = fingerprintOptions.extensions.sort(); var fingerprintExtensionsSetToDefaults = ( fingerprintOptionsSorted.length === fingerprintDefaultsSorted.length ) && fingerprintOptionsSorted.every( function( element, index ) { return element === fingerprintDefaultsSorted[ index ]; }); if ( fingerprintExtensionsSetToDefaults ) { app.options.fingerprint.extensions.push( 'eot', 'svg', 'ttf', 'woff', 'woff2' ); app.options.fingerprint.extensions = unique( app.options.fingerprint.extensions ); } } // ------------------------------------------------------------------------- // CSS isLessAddonInstalled = 'ember-cli-less' in app.registry.availablePlugins; if ( !this.isAddon() && !isLessAddonInstalled ) { app.import( 'vendor/' + this.getCssFileName() ); } // ------------------------------------------------------------------------- // Javascript app.import( app.bowerDirectory + '/bootstrap/dist/js/bootstrap.js' ); app.import( app.bowerDirectory + '/bootstrap-datepicker/js/bootstrap-datepicker.js' ); app.import( app.bowerDirectory + '/highcharts/highcharts.src.js' ); app.import( app.bowerDirectory + '/jquery-mousewheel/jquery.mousewheel.js' ); app.import( app.bowerDirectory + '/moment/min/moment-with-locales.js' ); app.import( app.bowerDirectory + '/moment-timezone/builds/moment-timezone-with-data.js' ); app.import( app.bowerDirectory + '/rxjs/dist/rx.all.js' ); app.import( app.bowerDirectory + '/select2/select2.js' ); app.import( app.bowerDirectory + '/typeahead.js/dist/typeahead.bundle.js' ); app.import( app.bowerDirectory + '/jquery.fn.twbs-responsive-pagination/src/twbsResponsivePagination.js' ); }, /** * Copy Twitter Bootstrap fonts into namespaced assets folder * * @param {String} type * @param {Object} tree * @returns {Object} */ preprocessTree: function( type, tree ) { var fonts = new Funnel( 'bower_components/bootstrap', { srcDir: 'fonts', destDir: this.name + '/assets/fonts', include: [ 'glyphicons-halflings-regular.*' ] }); return mergeTrees( [ tree, fonts ], { overwrite: true } ); } };
export const PlatformThemesResourceKinds = function () { 'ngInject'; const model = {}; model.all = [ {name: 'Internal route', kind: 'internal_route'}, {name: 'External link', kind: 'external_link'}, {name: 'Support request form', kind: 'support_request'}, {name: 'Plain text', kind: 'plain_text'} ]; return model; };
let colors = ["red", "blue", "green"]; // Creates an array with three strings let names = []; // Creates an empty array let values = [1,2,]; // Creates an array with 2 items
var Howl = require('../../bower_components/howler/howler.min').Howl; var names = ['bell', 'bass', 'snap', 'flutter', 'bitty']; var extensions = ['mp3', 'ogg', 'wav']; var sounds = {}; names.forEach(function (name) { var urls = extensions.map(function (ext) { return name + '.' + ext; }); sounds[name] = new Howl({ urls: urls }); }); module.exports = sounds;
window.payerIds = [ "Ohana Health Plan (WellCare of Hawaii) OHANA HEALTH PLAN (WCOHP)", "AARP AARP HEALTH PLAN (AARP)", "AFTRA Health Fund AFTRA HEALTH FUND (258)", "Administrative Services Inc. ADMINISTRATIVE SERVICES (ASINC)", "Advantra Freedom ADVANTRA FREEDOM (453)", "Advantra Savings COVENTRY ADVANTRA SAVINGS (456)", "Aetna AETNA (2)", "Aetna Long Term Care AETNA LONG TERM CARE (00225)", "Allied Benefit Services Inc. ALLIED BENEFIT SERVICES INC (ABSYS)", "AmeriChoice of New Jersey AMERICHOICE OF NJ (00091)", "AmeriHealth Mercy Health Plan AMERIHEALTH MERCY (AHMHP)", "American Family Insurance Group - Medicare Supplemental and PPO Policies AMERICAN FAMILY INSURANCE GROUP (AMFAM)", "American Family Life Assurance Co. (AFLAC) AFLAC-DENTAL (AFLAC)", "American General Life & Accident AMC AMERICAN GENERAL (00237)", "American National Insurance Company AMERICAN NATIONAL INSURANCE (ANICO)", "American National Life Insurance Company of Texas AMERICAN NATIONAL LIFE INS TX (ANTEX)", "American Republic Insurance AMERICAN REPUBLIC INS (224)", "Amerigroup Corporation AMERIGROUP (AMGRP)", "Ameritas Life Insurance Company AMERITAS LIFE (425)", "Antares Management Solutions ANTARES (ANTAR)", "Assurant Health ASSURANT HEALTH (252)", "Blue Shield of California BLUE SHIELD OF CALIFORNIA (00361)", "Best Life and Health BEST LIFE AND HEALTH (257)", "BlueChoice HealthPlan of South Carolina Medicaid (HMO) BLUECHOICE HEALPLAN SC MEDICAID (BCHSC)", "Bluegrass Family Health BLUEGRASS FAMILY HEALTH (BFHLT)", "Bravo Health Inc. BRAVO HEALTH (ELDER)", "CHAMPVA - HAC DEPT of VA HEALTH ADMIN CENTER (232)", "CHC Florida/VISTA/Summit CHC FLORIDA/VISTA/SUMMIT (512)", "CIGNA CIGNA (1)", "CIGNA HealthCare CIGNA (1)", "CIGNA HealthCare - HMO CIGNA (1)", "CIGNA HealthCare - PPO CIGNA (1)", "CarePlus Health Plan CAREPLUS HEALTH PLAN (324)", "Carelink Advantra CHC CARELINK (ADVANTRA) (160)", "Carelink Health Plan CHC CARELINK (ADVANTRA) (160)", "Carelink Medicaid CHC CARELINK MEDICAID (182)", "Carenet COVENTRY HEALTH CARE CARENET (190)", "CeltiCare CELTICARE (CELTI)", "Cenpatico - Kentucky CENPATICO - KENTUCKY (CBHKY)", "Cenpatico - Massachusetts CENPATICO - MASSACHUSETTS (CBHMA)", "Cenpatico Behavioral Health CENPATICO - MASSACHUSETTS (CBHMA)", "Cenpatico Behavioral Health (Indiana) CENPATICO - INDIANA (CBNIN)", "Cenpatico-Indiana CENPATICO - INDIANA (CBNIN)", "Central Reserve Insurance Company (Non-Medicare Supplement) CENTRAL RESERVE (CTRSV)", "Central SeniorCare TEXANPLUS SOUTHEAST TEXAS AREA (TXNSE)", "Central States Funds CENTRAL STATES FUND (CSFND)", "Chesapeake National Life Insurance (HealthMarkets) CHESAPEAKE NATIONAL LIFE (207)", "Children of Women Vietnam Veterans-VA HAC DEPT OF VA HEALTH ADMIN CENTER (232)", "Christian Brothers Services PRINCIPAL LIFE INSURANCE COMPANY (143)", "Cigna Voluntary Limited Medical (aka Cigna Voluntary) CIGNA (STRHG)", "Connecticut General CIGNA (1)", "Continental General Insurance Company (Non-Medicare Supplement) CONTINENTAL GENERAL (CTLGN)", "Cooperative Benefit Administrators COOPERATIVE BENEFIT ADMINISTRATORS (223)", "Coresource - Maryland Pennsylvania & Illinois CORESOURCE-MD\\PA\\AND IL (Includes NC and IN.) (236)", "Coresource - Ohio CORESOURCE-OH (239)", "Coresource Little Rock CORESOURCE-LITTLE ROCK (205)", "Coventry Advantra (Texas New Mexico Arizona) ADVANTRA (TEXAS\\NEW MEXICO\\ARIZONA ONLY) (504)", "Coventry Health Care Federal COVENTRY HEALTH CARE FEDERAL (509)", "Coventry Health Care of Delaware Inc. CHC OF DELAWARE (166)", "Coventry Health Care of Georgia Inc. CHC OF GEORGIA (154)", "Coventry Health Care of Iowa Inc. CHC OF IOWA (170)", "Coventry Health Care of Kansas Inc. CHC OF KANSAS (172)", "Coventry Health Care of Louisiana Inc. CHC OF LOUISIANA (158)", "Coventry Health Care of Nebraska Inc. CHC OF NEBRASKA (176)", "Coventry Health and Life (Oklahoma) COVENTRY HEALTH AND LIFE (OK ONLY) (441)", "Coventry Health and Life (Tennessee Only) COVENTRY HEALTH AND LIFE (TN ONLY) (455)", "Coventry Health and Life-Nevada COVENTRY HEALTH AND LIFE_NEVADA (505)", "Coventry Healthcare National Network COVENTRY HEALTHCARE NATIONAL NETWORK (250)", "Coventry-Missouri COVENTRY MISSOURI (507)", "CoventryCares COVENTRYCARES (510)", "CoventryOne COVENTRYONE (COVON)", "Diamond Plan DIAMOND PLAN (177)", "Directors Guild of America - Producers DIRECTOR\u2019S GUILD (259)", "EQUICORE CIGNA (1)", "EQUICORE - PPO CIGNA (1)", "Evercare UNITED HEALTH CARE (112)", "Fallon Health Plan FALLON HEALTH PLAN (272)", "Federated Insurance Company FEDERATED INSURANCE COMPANY (262)", "First Ameritas of New York FIRST AMERITAS OF NEW YORK (426)", "Fortis Benefits Insurance Company ASSURANT HEALTH-UNION SECURITY (253)", "Fortis Life Insurance Company ASSURANT HEALTH-TIME INSURANCE (252)", "Fresenius Medical Care FRESENIUS MEDICAL CARE (FRSMC)", "Generations Healthcare GENERATIONS HEALTHCARE (GENHC)", "Golden Triangle Physician Alliance/SelectCare of Texas (GTPA) GTPA (TXNSE)", "Government Employees Hospital Association GOVERNMENT EMPLOYEES HOSPITAL ASSOC (GEHA)", "Great-West Healthcare GREAT WEST HEALTHCARE (328)", "Group Health Plan - CMR GROUP HEALTH PLAN (GHP) (184)", "HEALTHe Exchange HEALTHE EXCHANGE (THEXI)", "HIPNY HEALTH PLAN OF NEW YORK (HIPNY)", "Harmony Health Plan (WellCare of Florida) HARMONY HEALTH PLAN (WCHHP)", "Harvard Pilgrim HealthCare HAVARD PILGRIM HEALTHCARE (HPHC)", "Health 123/Tripoint/Vanderbilt Health Plan VANDERBILT (43)", "Health Alliance Plan HEALTH ALLIANCE (HAPMC)", "Health America Inc./Health Assurance/Advantra HEALTHAMERICA AND HEALTHASSURANCE (148)", "Health Future LLC. AMC HEALTH FUTURE (246)", "Health Net National HEALTH NET (HNNC)", "Health Net of Arizona HEALTH NET (213)", "Health Net of the Northeast Inc. HEALTH NET (213)", "Health Partners of Philadelphia HEALTH PARTNERS OF PHILADELPHIA (288)", "HealthEZ HEALTHEZ (AMTPA)", "HealthEase (WellCare of Florida) HEALTHEASE (WCHEA)", "HealthEase Kids (WellCare of Florida) HEALTHEASE KIDS (WCHEK)", "HealthPlus of Michigan HEALTHPLUS OF MICHIGAN (HLTPM)", "HealthSmart Benefit Solutions HEALTHSMART BENEFIT SOLUTIONS (HSBS)", "Healthcare USA HEALTHCARE USA (HCUSA) (186)", "Healthfirst of New Jersey HEALTHFIRST OF NEW JERSEY (HFNJ)", "Healthfirst of New York HEALTHFIRST OF NEW YORK (240)", "Horizon New Jersey Health HORIZON NJ HEALTH (HNJH)", "Humana HUMANA (HUMANA)", "J. F. Molloy and Associates Inc. PRINCIPAL LIFE INSURANCE COMPANY (143)", "John Alden Life Insurance Company (Assurant Health) ASSURANT HEALTH-JOHN ALDEN LIFE (254)", "Kaiser Foundation Health Plan of Colorado KAISER FOUNDATION HEALTH PLAN OF CO (277)", "Kaiser Foundation Health Plan of Georgia KAISER PERMANENTE OF GEORGIA (281)", "Kaiser Foundation Health Plan of Northern CA Region KAISER PERMANENTE OF NORTH CA (282)", "Kaiser Foundation Health Plan of Ohio KAISER FOUNDATION HEALTH PLAN OF OH (280)", "Kaiser Foundation Health Plan of Southern CA Region KAISER PERMANENTE OF SOUTH CA (283)", "Kaiser Foundation Health Plan of the Mid-Atlantic States Inc. KAISER FOUNDATION HP MID ATLANTIC (276)", "Kaiser Foundation Health Plan of the Northwest KAISER FOUNDATION HEALTH PLAN OF NW (279)", "Kaiser Foundation Health Plan Inc. - Hawaii Region KAISER FOUNDATION HEALTH PLAN OF HI (278)", "Katy Medical Group TEXANPLUS SOUTHEAST TEXAS AREA (TXNSE)", "Kentucky Spirit Health Plan KENTUCKY SPIRIT HEALTH PLAN (CKYHP)", "Key Benefit Administrators - Indianapolis KEY BENEFIT ADMINISTRATORS (KEYIN)", "Keystone Mercy Health Plan KEYSTONE MERCY HEALTH PLAN (KYMHP)", "MDWise Hoosier Alliance MDWISE HOOSIER ALLIANCE (MDWHA)", "MHNet Behavioral Health MHNet BEHAVIORAL HEALTH (514)", "MHNet Behavioral Health MHNet BEHAVIORAL HEALTH (00514)", "MMSI MMSI MAYO HEALTH (85)", "MVP Health Plan of NY MVP HEALTH CARE NY (432)", "Mail Handlers Benefit Plan MAIL HANDLERS BENEFIT PLAN (251)", "Managed Health Services Indiana MANAGED HEALTH SERVICES INDIANA (CMHIN)", "Maricopa Care Advantage (Arizona) MARICOPA CARE ADVANTAGE (ARIZONA) (MCAA)", "Maricopa Health Plan (Arizona) MARICOPA HEALTH PLAN (ARIZONA) (MHPA)", "Medica MEDICA (404)", "Medical Mutual of Ohio MEDICAL MUTUAL OF OHIO (211)", "Mega Life - Oklahoma City MEGALIFE - OKC (365)", "Mega Life and Health Insurance Company (HealthMarkets) MEGA LIFE AND HEALTH (248)", "Memorial Clinical Associates/SelectCare of Texas (MCA) TEXANPLUS SOUTHEAST TEXAS AREA (TXNSE)", "Mid-West National Life Insurance (HealthMarkets) MID WEST NATIONAL LIFE INSURANCE (206)", "Molina Healthcare of California MOLINA HEALTHCARE OF CALIFORNIA (222)", "Molina Healthcare of Florida MOLINA HEALTHCARE OF FLORIDA (506)", "Molina Healthcare of Michigan MOLINA HEALTHCARE OF MICHIGAN (226)", "Molina Healthcare of Missouri MOLINA HEALTHCARE OF MISSOURI (513)", "Molina Healthcare of Ohio MOLINA HEALTHCARE OF OHIO (445)", "Molina Healthcare of Texas MOLINA HEALTHCARE OF TEXAS (451)", "Molina Healthcare of Utah MOLINA HEALTHCARE OF UTAH (227)", "Molina Healthcare of Washington MOLINA HEALTHCARE OF WASHINGTON (228)", "Mutual of Omaha MUTUAL OF OMAHA (MOONE)", "National Association of Letter Carriers NALC (214)", "Nationwide Specialty Health aka Nationwide Health Plan NATIONWIDE (86)", "Nippon Life Benefits NIPPON LIFE BENEFITS (NIPON)", "Nippon Life Insurance Company of America NIPPON LIFE INSURANCE CO OF AMERICA (144)", "Northwest Diagnostic Clinic/SelectCare of Texas (NWDC) NWDC (TXNSE)", "Novasys Health NOVASYS HEALTH (NOVAS)", "Omnicare Health Plan of Michigan OMNICARE (MICHIGAN) (284)", "Oxford Health Plans OXFORD HEALTH PLANS (16)", "PHCS Savility Payers PHCS SAVILITY PAYERS (PHCSS)", "PacifiCare of California PACIFICARE OF CALIFORNIA (10)", "PacifiCare of Oklahoma PACIFICARE OF OKLAHOMA (35)", "PacifiCare of Oregon PACIFICARE OF OREGON (34)", "PacifiCare of Texas PACIFICARE OF TEXAS (36)", "PacifiCare of Washington PACIFICARE OF WASHINGTON (49)", "Passport Advantage PASSPORT ADVANTAGE (PPADV)", "Passport Health Plan PASSPORT HEALTH PLAN (PPHPC)", "Personal Insurance Administrators (PIA) PERSONAL INSURANCE ADMIN (PIANC)", "PersonalCare/Coventry Health of Illinois PERSONALCARE/COVENTRY HEALTH OF ILLINOIS (179)", "Physicians Mutual PHYSICIANS MUTUAL (287)", "Pinnacle Physician Management Org TEXANPLUS SOUTHEAST TEXAS AREA (TXNSE)", "Pittman and Associates PITTMAN AND ASSOCIATES (454)", "Poly-America Medical & Dental Benefits Plan AMC POLY AMERICA (244)", "Preferred Health Systems PERFERRED HEALTH SYSTEMS (263)", "Principal Financial Group PRINCIPAL LIFE INSURANCE COMPANY (143)", "Principal Life Insurance Company PRINCIPAL LIFE INSURANCE COMPANY (143)", "Priority Health PRIORITY HEALTH (PRHTH)", "Promina ASO PROMINA ASO (193)", "QuikTrip Corporation QUIKTRIP (QKTRP)", "Rocky Mountain Health Plan ROCKY MOUNTAIN HEALTH PLAN (347)", "SAMBA Health Benefit Plan SPECIAL AGENTS MUTUAL BENEFIT (SAMBA)", "Secure Horisons Oregon PACIFICARE OF OREGON (34)", "Secure Horizons California PACIFICARE OF CALIFORNIA (10)", "Secure Horizons Oklahoma PACIFICARE OF OKLAHOMA (35)", "Secure Horizons Texas PACIFICARE OF TEXAS (36)", "Secure Horizons Washington PACIFICARE OF WASHINGTON (49)", "Select Health of South Carolina SELECT HEALTH OF SOUTH CAROLINA (SHSC)", "Select Senior Clinic TEXANPLUS SOUTHEAST TEXAS AREA (TXNSE)", "SelectCare of Texas (Kelsey-Seybold) TEXANPLUS SOUTHEAST TEXAS AREA (TXNSE)", "Significa Benefit Services Inc. SIGNIFICA (191)", "Southern Health Services Inc. SOUTHERN HEALTH SERVICES (SHS) (156)", "Spina Bifida - VA HAC DEPT OF VA HEALTH ADMIN CENTER (232)", "Standard Life and Accident Insurance Company STD LIFE AND ACCIDENT INSURANCE (SLAIC)", "StayWell STAYWELL (WCSWA)", "StayWell Kids STAYWELL KIDS (WCSWK)", "Texan Plus (North Texas Area) TEXANPLUS NORTH TEXAS AREA (TXNNT)", "Texan Plus (Southeast Texas Area) TEXANPLUS SOUTHEAST TEXAS AREA (TXNSE)", "Texas First Health Plan (TOPA) TEXANPLUS NORTH TEXAS AREA (TXNNT)", "Three Rivers Health Plans (Unison Health Plan) THREE RIVERS HEALTH PLANS (198)", "Time Insurance Company ASSURANT HEALTH-TIME INSURANCE (252)", "Today's Health TODAYS HEALTH (TDHLT)", "Today's Options TODAYS OPTIONS (TDOPT)", "Touchstone Health PSO AMC TOUCHSTONE PSO (78)", "Touchstone Health/Health Net SmartChoice AMC TOUCHSTONE (265)", "TransAmerica Life Insurance (HealthMarkets) TRANSAMERICA LIFE (208)", "Tribute/SelectCare of Oklahoma TRIBUTE SELECTCARE OF OKLAHOMA (TSCOK)", "Tricare (CHAMPUS) TRICARE (80)", "Trustmark TRUSTMARK (233)", "Tufts Health Plan TUFTS (114)", "USAA Life Insurance Company USAA (USAA)", "UniCare UNICARE (UNICR)", "Union Pacific Railroad Employes Health System UNION PACIFIC RAILROAD EMPLOYES HEALTH (UPREH)", "Union Security Insurance Company ASSURANT HEALTH-UNION SECURITY (253)", "Unison Health Plan / Better Health Plans BETTER HEALTH PLANS (199)", "UnitedHealthcare UNITED HEALTH CARE (112)", "UnitedHealthcare Plans of Puerto Rico UNITED HEALTH CARE (112)", "UnitedHealthcare of Alabama UNITED HEALTH CARE (112)", "UnitedHealthcare of Arizona Inc. UNITED HEALTH CARE (112)", "UnitedHealthcare of Arkansas UNITED HEALTH CARE (112)", "UnitedHealthcare of California-Northern California UNITED HEALTH CARE (112)", "UnitedHealthcare of California-Southern California UNITED HEALTH CARE (112)", "UnitedHealthcare of Colorado Inc. UNITED HEALTH CARE (112)", "UnitedHealthcare of Florida UNITED HEALTH CARE (112)", "UnitedHealthcare of Georgia UNITED HEALTH CARE (112)", "UnitedHealthcare of Illinois UNITED HEALTH CARE (112)", "UnitedHealthcare of Kentucky UNITED HEALTH CARE (112)", "UnitedHealthcare of Louisiana UNITED HEALTH CARE (112)", "UnitedHealthcare of Mississippi UNITED HEALTH CARE (112)", "UnitedHealthcare of New England UNITED HEALTH CARE (112)", "UnitedHealthcare of New York (includes NY & NJ) UNITED HEALTH CARE (112)", "UnitedHealthcare of North Carolina Inc. UNITED HEALTH CARE (112)", "UnitedHealthcare of Ohio UNITED HEALTH CARE (112)", "UnitedHealthcare of Tennessee UNITED HEALTH CARE (112)", "UnitedHealthcare of Texas - Dallas UNITED HEALTH CARE (112)", "UnitedHealthcare of Texas - Houston UNITED HEALTH CARE (112)", "UnitedHealthcare of Upstate New York UNITED HEALTH CARE (112)", "UnitedHealthcare of Utah UNITED HEALTH CARE (112)", "UnitedHealthcare of Virginia UNITED HEALTH CARE (112)", "UnitedHealthcare of the Midlands - HMO (Choice Select) UNITED HEALTH CARE (112)", "UnitedHealthcare of the Midlands - PPO (Choice Plus Select Plus Self Fund UNITED HEALTH CARE (112)", "UnitedHealthcare of the Midwest-Choice Choice Plus Select Select Plus UNITED HEALTH CARE (112)", "UnitedHealthcare of the Midwest-Medicare Complete (f. PHP of Midwest PHP o UNITED HEALTH CARE (112)", "University Physicians Care Advantage (Arizona) UNIVERSITY PHYSICIANS CARE ADV (UPCAA)", "University Physicians Healthcare Group (Arizona) UNIVERSITY PHYSICIANS HEALTHCARE GRP (UPHGA)", "University of Missouri UNIVERSITY OF MISSOURI (COVUM)", "VA Fee Basis Programs VA FEE BASIS PROGRAM (231)", "VA Health Admin Ctr (CHAMPVA/Spina Bifida/Children of Women Vietnam Vets) DEPT OF VA HEALTH ADMIN CENTER (232)", "VISTA (Medicaid Florida Health Kids Long Term Care products only) VISTA (MCD\\FHK\\LTC) (508)", "Vanderbilt VANDERBILT (43)", "Vantage Health Plan Inc. VANTAGE HEALTH (VHPLA)", "Village Family Practice TEXANPLUS SOUTHEAST TEXAS AREA (TXNSE)", "Vytra HEALTH PLAN OF NEW YORK (VYTRA)", "WEB-TPA Inc WEB-TPA (WBTPA)", "WellCare Health Plans (WellCare of FL GA NY CT NJ LA OH TX) WELLCARE HEALTH PLANS (WCHP)", "Wellpath WELLPATH SELECT (CAROLINAS) (164)", "World Insurance Company WORLD INSURANCE (81)", "Writers Guild - Industry Health Plan WRITER\u2019S GUILD (260)", "Anthem Blue Cross California BLUE CROSS OF CALIFORNIA (39)", "BCBS of Alabama - Medicare Part B BLUE CROSS BLUE SHIELD OF ALABAMA (423)", "Blue Cross Blue Shield of Alabama BLUE CROSS BLUE SHIELD OF ALABAMA (266)", "Blue Cross Blue Shield of Alaska (Premera) BCBS ALASKA (BCAKC)", "Blue Cross Blue Shield of Arizona BLUE CROSS BLUE SHIELD AZ (90)", "Blue Cross Blue Shield of Arkansas BLUE CROSS BLUE SHIELD AR (BCARC)", "Blue Cross Blue Shield of Colorado BLUE CROSS BLUE SHIELD CO (BCCOC)", "Blue Cross Blue Shield of Connecticut BLUE CROSS BLUE SHIELD CT (BCCTC)", "Blue Cross Blue Shield of District of Columbia (CareFirst) BCBS OF DC (BCDCC)", "Blue Cross Blue Shield of Florida BCBS OF FL (267)", "Blue Cross Blue Shield of Georgia BCBS OF GEORGIA (151)", "Blue Cross Blue Shield of Illinois BLUE CROSS BLUE SHIELD OF ILLINOIS (268)", "Blue Cross Blue Shield of Indiana BLUE CROSS BLUE SHIELD INDIANA (BCINC)", "Blue Cross Blue Shield of Iowa BLUE CROSS BLUE SHEILD IA (BCIAC)", "Blue Cross Blue Shield of Kansas BCBS KANSAS (BCKSC)", "Blue Cross Blue Shield of Kansas City BCBS KS CITY (BCKCC)", "Blue Cross Blue Shield of Kentucky BCBS OF KY (BCKYC)", "Blue Cross Blue Shield of Louisiana BLUE CROSS BLUE SHIELD LA (83)", "Blue Cross Blue Shield of Maine BLUE CROSS BLUE SHIELD ME (BCMEC)", "Blue Cross Blue Shield of Maryland (CareFirst) BCBS OF MD (BCMDC)", "Blue Cross Blue Shield of Massachusetts BLUE CROSS BLUE SHEILD MA (139)", "Blue Cross Blue Shield of Michigan (Dental) BLUE CROSS BLUE SHIELD MI (BCMID)", "Blue Cross Blue Shield of Michigan (Institutional) BLUE CROSS BLUE SHIELD MI (BCMII)", "Blue Cross Blue Shield of Michigan (Professional) BLUE CROSS BLUE SHIELD MI (BCMIP)", "Blue Cross Blue Shield of Minnesota BCBS OF MN (269)", "Blue Cross Blue Shield of Mississippi BLUE CROSS BLUE SHIELD MISSISSIPPI (75)", "Blue Cross Blue Shield of Missouri BLUE CROSS BLUE SHIELD MO (BCMOC)", "Blue Cross Blue Shield of Nebraska BLUE CROSS BLUE SHIELD OF NEBRASKA (BCNEC)", "Blue Cross Blue Shield of Nevada BLUE CROSS BLUE SHIELD NV (BCNVC)", "Blue Cross Blue Shield of New Hampshire BLUE CROSS BLUE SHIELD NH (BCNHC)", "Blue Cross Blue Shield of New Mexico BLUE CROSS BLUE SHIELD NEW MEXICO (270)", "Blue Cross Blue Shield of New York (Empire) EMPIRE HEALTH CHOICE ASSURANCE INC (44)", "Blue Cross Blue Shield of North Carolina BCBS NC (BCNCC)", "Blue Cross Blue Shield of North Dakota BCBS ND (BCNDC)", "Blue Cross Blue Shield of Ohio BLUE CROSS BLUE SHIELD OH (BCOHC)", "Blue Cross Blue Shield of Oregon (Regence) REGENCE BLUECROSS BLUESHIELD OF OR (BCORC)", "Blue Cross Blue Shield of Pennsylvania - Highmark BLUE CROSS BLUE SHIELD PA (440)", "Blue Cross Blue Shield of Rhode Island BLUE CROSS BLUE SHIELD RI (BCRIC)", "Blue Cross Blue Shield of South Carolina BCBS SC (BCSCC)", "Blue Cross Blue Shield of South Dakota BLUE CROSS BLUE SHEILD SD (BCSDC)", "Blue Cross Blue Shield of Tennessee BLUE CROSS BLUE 2100A SHIELD OF TENNESSEE (BCTNC)", "Blue Cross Blue Shield of Texas BLUE CROSS BLUE SHIELD TEXAS (271)", "Blue Cross Blue Shield of Virginia BLUE CROSS BLUE SHIELD VA (BCVAC)", "Blue Cross Blue Shield of Wisconsin (Anthem) BLUE CROSS BLUE SHIELD WI (BCWIC)", "Blue Cross Blue Shield of Wyoming BCBS WY (BCWYC)", "Blue Cross of Idaho BLUE CROSS IDAHO (BCIDC)", "Blue Cross of Northeastern Pennsylvania BCOFNEPA (BCNPC)", "Blue Cross of Washington (Premera) BC WASHINGTON (BCWAC)", "Blue Shield of Washington (Regence) REGENCE BLUE SHIELD (BSWAC)", "Capital Blue Cross (Pennsylvania) CAPITAL BLUE CROSS (BCCBC)", "Empire Blue Cross and Blue Shield EMPIRE HEALTH CHOICE ASSURANCE INC (44)", "Freedom Blue FREEDOM BLUE (FRBLU)", "Horizon Blue Cross Blue Shield of New Jersey BLUE CROSS BLUE SHIELD NJ (87)", "Horizon Healthcare of NY BLUE CROSS BLUE SHIELD NJ (87)", "Independence Blue Cross INDEPENDENCE BLUE CROSS (BCIBC)", "Mississippi State Employees and Teachers Health Plan MS SEHP (82)", "Mountain State MOUNTAIN STATE (MTNST)", "Wellchoice of NJ EMPIRE HEALTH CHOICE ASSURANCE INC (44)", "Absolute Total Care ABSOLUTE TOTAL CARE (CTOTL)", "Affinity Health Plan AFFINITY HEALTH PLAN (AFNTY)", "Alabama Medicaid ALABAMA MEDICAID (72)", "Alabama Medicaid ALABAMA MEDICAID (AID40)", "Arizona Medicaid AZ MEDICAID (69)", "Arizona Medicaid AZ MEDICAID (AID37)", "Arkansas Medicaid ARKANSAS MEDICAID (54)", "Arkansas Medicaid ARKANSAS MEDICAID (AID26)", "Blue Choice Medicaid Managed Care MI MICHILD (403)", "Bridgeway Arizona Eligibility Host BRIDGEWAY ARIZONA (CBRID)", "Buckeye Community Health BUCKEYE COMMUNITY HEALTH (CBUCK)", "California Medicaid CA MEDICAID (25)", "California Medicaid - Medi-Cal CA MEDICAID (AID11)", "Cenpatico Behavioral Health CENPATICO - GEORGIA (CBHGA)", "Cenpatico Behavioral Health (Arizona) CENPATICO - ARIZONA (CBHAZ)", "Cenpatico Behavioral Health (Florida) CENPATICO - FLORIDA (CBHFL)", "Cenpatico Behavioral Health (Kansas) CENPATICO - KANSAS (CBHKS)", "Cenpatico Behavioral Health (Ohio) CENPATICO - OHIO (CBHOH)", "Cenpatico Behavioral Health (South Carolina) CENPATICO - SOUTH CAROLINA (CBHSC)", "Cenpatico-Arizona CENPATICO - ARIZONA (CBHAZ)", "Cenpatico-Florida CENPATICO - FLORIDA (CBHFL)", "Cenpatico-Georgia CENPATICO - GEORGIA (CBHGA)", "Cenpatico-Kansas CENPATICO - KANSAS (CBHKS)", "Cenpatico-Ohio CENPATICO - OHIO (CBHOH)", "Cenpatico-South Carolina CENPATICO - SOUTH CAROLINA (CBHSC)", "Colorado Medicaid COLORADO MEDICAID (27)", "Colorado Medicaid COLORADO MEDICAID (AID14)", "Connecticut Medicaid CONNECTICUT MEDICAID (52)", "Connecticut Medicaid CONNECTICUT MEDICAID (AID24)", "Coventry Nebraska Medicaid COVENTRY NEBRASKA MEDICAID (511)", "Florida Medicaid FLORIDA MEDICAID (23)", "Florida Medicaid FLORIDA MEDICAID (AID01)", "Georgia Medicaid GEORGIA MEDICAID (28)", "Georgia Medicaid GEORGIA MEDICAID (AID15)", "Group Practice Affiliates GROUP PRACTICE AFFILIATES (CGRPR)", "Hawaii Medicaid HAWAII MEDICAID (AID53)", "Idaho Medicaid IDAHO MEDICAID (67)", "Idaho Medicaid IDAHO MEDICAID (AID35)", "Illinois Medicaid (IDPA) ILLINOIS MEDICAID (53)", "Illinois Medicaid (IDPA) ILLINOIS MEDICAID (AID25)", "Indiana Medicaid INDIANA MEDICAID (30)", "Indiana Medicaid INDIANA MEDICAID (AID16)", "Integrated Mental Health Services INTEGRATED MENTAL HEALTH SERVICES (CBHTX)", "Iowa Medicaid IOWA MEDICAID (68)", "Iowa Medicaid IOWA MEDICAID (AID36)", "Kansas Medicaid KANSAS MEDICAID (50)", "Kansas Medicaid KANSAS MEDICAID (AID22)", "Kentucky Medicaid KENTUCKY MEDICAID (AID31)", "Louisiana Medicaid LOUISIANA MEDICAID (74)", "Louisiana Medicaid LOUISIANA MEDICAID (AID42)", "Managed Health Services Wisconsin MANAGED HEALTH SERVICES WISCONSIN (CMHWI)", "Massachusetts Medicaid MASS MEDICAID (145)", "Massachusetts Medicaid MASS MEDICAID (AID45)", "Michigan Medicaid - Dept of Community Health - Medical Services Admin MICHIGAN MEDICAID (AID55)", "Minnesota Medicaid MINNESOTA MEDICAID (70)", "Minnesota Medicaid MINNESOTA MEDICAID (AID38)", "Mississippi Medicaid MISSISSIPPI MEDICAID (46)", "Mississippi Medicaid MISSISSIPPI MEDICAID (AID20)", "Missouri Medicaid MO MEDICAID (21)", "Missouri Medicaid MO MEDICAID (AID03)", "Montana Medicaid - DPHHS/Health Policy Services Division MONTANA MEDICAID (AID57)", "Nevada Medicaid - First Health Services Corp NEVADA MEDICAID (AID58)", "New Hampshire Medicaid NEW HAMPSHIRE MEDICAID (147)", "New Hampshire Medicaid NEW HAMPSHIRE MEDICAID (AID47)", "New Jersey Medicaid NEW JERSEY MEDICAID (40)", "New Jersey Medicaid NEW JERSEY MEDICAID (AID19)", "New Mexico Medicaid NEW MEXICO MEDICAID (58)", "New Mexico Medicaid NEW MEXICO MEDICAID (AID27)", "New York Medicaid NEW YORK MEDICAID (32)", "New York Medicaid NEW YORK MEDICAID (AID18)", "North Carolina Medicaid NORTH CAROLINA MEDICAID (47)", "North Carolina Medicaid NORTH CAROLINA MEDICAID (AID21)", "North Dakota Medicaid NORTH DAKOTA MEDICAID (AID59)", "Ohio Medicaid OHIO MEDICAID (14)", "Ohio Medicaid OHIO MEDICAID (AID09)", "Oklahoma Medicaid OKLAHOMA MEDICAID (64)", "Oklahoma Medicaid OKLAHOMA MEDICAID (AID32)", "Oregon Medicaid OREGON MEDICAID (77)", "Oregon Medicaid OREGON MEDICAID (AID44)", "Peach State Health Plan PEACH STATE HEALTH PLAN (CPSHP)", "Pennsylvania Medicaid PA MEDICAID (61)", "Pennsylvania Medicaid PA MEDICAID (AID29)", "South Dakota Medicaid SOUTH DAKOTA MEDICAID (59)", "South Dakota Medicaid SOUTH DAKOTA MEDICAID (AID28)", "Sunshine State Health Plan SUNSHINE STATE HEALTH PLAN (CSSHP)", "Superior HealthPlan SUPERIOR HEALTHPLAN TEXAS (CSHPT)", "Tennessee Medicaid TENNCARE (26)", "Tennessee Medicaid (TennCare) TENNCARE (AID13)", "Texas Medicaid TEXAS MEDICAID (22)", "Texas Medicaid TEXAS MEDICAID (AID05)", "Vermont Medicaid VERMONT MEDICAID (62)", "Vermont Medicaid VERMONT MEDICAID (AID30)", "Virginia Medicaid VIRGINIA MEDICAID (51)", "Virginia Medicaid VIRGINIA MEDICAID (AID23)", "Washington Medicaid WASHINGTON MEDICAID (20)", "Washington Medicaid WASHINGTON MEDICAID (AID07)", "West Virginia Medicaid WV MEDICAID (65)", "West Virginia Medicaid WV MEDICAID (AID33)", "Wisconsin Chronic Disease Program WI MEDICAID CHRONIC DISEASE PROGRAM (WICDP)", "Wisconsin Medicaid WISCONSIN MEDICAID (73)", "Wisconsin Medicaid WISCONSIN MEDICAID (AID41)", "Wisconsin Well Woman Program WI MEDICAID WELL WOMAN PROGRAM (WIWWP)", "Wyoming Medicaid WYOMING MEDICAID (66)", "Wyoming Medicaid WYOMING MEDICAID (AID34)", "Advantage by Bridgeway Health Solutions ADVANTAGE BY BRIDGEWAY HEALTH SOLTN (CBRIA)", "Advantage by Buckeye Community Health Plan ADVANTAGE BY BUCKEYE COMMUNITY HPLN (CBUCA)", "Advantage by Managed Health Services ADVANTAGE BY MANAGED HEALTH SERVICES (CMHSA)", "Advantage by Superior HealthPlan Services ADVANTAGE BY SUPERIOR HEALTHPLAN (CSHPA)", "CSA Fraternal Life - Medicare Supplement CSA FRATERNAL MEDICARE SUPPLEMENT (CSAMS)", "Carpenters' Health and Welfare Trust Fund of St. Louis CARPENTER\u2019S HEALTH AND WELFARE (CHWSL)", "Central Reserve Life Insurance Company - Medicare Supplement CENTRAL RESERVE MEDICARE SUPPLEMENT (CRLMS)", "Continental General Insurance Company - Medicare Supplement CONTINENTAL GENERAL MEDICARE SUPP (CGIMS)", "Essence Healthcare ESSENCE HEALTHCARE (ESSNC)", "Great American Life Insurance Company - Medicare Supplement GREAT AMERICAN INS MEDICARE SUPP (GAIMS)", "Loyal American Life Insurance Company - Medicare Supplement LOYAL AMERICAN MEDICARE SUPPLEMENT (LALMS)", "Medicare Part A & B - All States MEDICARE (431)", "Provident American Life & Health Insurance Company - Medicare Supplement PROVIDENT AMERICAN MEDICARE SUPP (PRVMS)", "SPJST - Medicare Supplement SPJST MEDICARE SUPPLEMENT (SPJMS)", "United Teacher Associates Insurance Company - Medicare Supplement UNITED TEACHER ASSOC MEDICARE SUPP (UTAMS)", "VNS CHOICE Medicare VISITING NURSE SERVICE OF NY (VNSNY)" ]
// lonTree.js // Interface and implementation for the longitude interval tree // Required: // - IntervalTree var it = require('./intervalTree'); // LATLON // Convert degrees to radians Number.prototype.toRad = function(){ return (this*Math.PI) / 180; }; var toRad = function(degree){ return (degree*Math.PI) / 180; }; // Convert radians to degrees Number.prototype.toDeg = function(){ return (this*180) / Math.PI; }; var toDeg = function(degree){ return (degree*180) / Math.PI; }; /** * * http://www.movable-type.co.uk/scripts/latlon.js * * Creates a point on the earth's surface at the supplied latitude / longitude * * @constructor * @param {Number} lat: latitude in numeric degrees * @param {Number} lon: longitude in numeric degrees * @param {Number} [rad=6371]: radius of earth if different value is required from standard 6,371km */ function LatLon(lat, lon, rad) { if (typeof(rad) == 'undefined') rad = 6371; // earth's mean radius in km // only accept numbers or valid numeric strings this._lat = typeof(lat)=='number' ? lat : typeof(lat)=='string' && lat.trim()!='' ? +lat : NaN; this._lon = typeof(lon)=='number' ? lon : typeof(lon)=='string' && lon.trim()!='' ? +lon : NaN; this._radius = typeof(rad)=='number' ? rad : typeof(rad)=='string' && trim(lon)!='' ? +rad : NaN; } /** * * http://www.movable-type.co.uk/scripts/latlon.js * * Returns the destination point from this point having travelled the given distance (in km) on the * given initial bearing (bearing may vary before destination is reached) * * see http://williams.best.vwh.net/avform.htm#LL * * @param {Number} brng: Initial bearing in degrees * @param {Number} dist: Distance in km * @returns {LatLon} Destination point */ LatLon.prototype.destinationPoint = function(brng, dist) { dist = typeof(dist)=='number' ? dist : typeof(dist)=='string' && dist.trim()!='' ? +dist : NaN; dist = dist/this._radius; // convert dist to angular distance in radians brng = brng.toRad(); // var lat1 = this._lat.toRad(), lon1 = this._lon.toRad(); var lat2 = Math.asin( Math.sin(lat1)*Math.cos(dist) + Math.cos(lat1)*Math.sin(dist)*Math.cos(brng) ); var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(dist)*Math.cos(lat1), Math.cos(dist)-Math.sin(lat1)*Math.sin(lat2)); lon2 = (lon2+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180º return new LatLon(lat2.toDeg(), lon2.toDeg()); }; /** * Returns the distance from this point to the supplied point, in km * (using Haversine formula) * * from: Haversine formula - R. W. Sinnott, "Virtues of the Haversine", * Sky and Telescope, vol 68, no 2, 1984 * * @param {LatLon} point: Latitude/longitude of destination point * @param {Number} [precision=4]: no of significant digits to use for returned value * @returns {Number} Distance in km between this point and destination point */ LatLon.prototype.distanceTo = function(point, precision) { // default 4 sig figs reflects typical 0.3% accuracy of spherical model if (typeof precision == 'undefined') precision = 4; var R = this._radius; var lat1 = this._lat.toRad(), lon1 = this._lon.toRad(); var lat2 = point._lat.toRad(), lon2 = point._lon.toRad(); var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon/2) * Math.sin(dLon/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; return d.toFixed(precision); }; // lonTree class function LonTree(k,d){ this.tree = null; this.k = k; this.d = d; // Private methods this.lon = function(data){ return data.lon; }; this.lat = function(data){ return data.lat; }; this.breakCondition = function(curr){ return Math.abs(curr.intervalj-curr.intervali) <= 1.25; }; this.addTree = function(node){ node.tree = it.newIntervalTree(-90,90); }; } // IntervalTree essentials var newLonTree = function(k,d){ var retLonTree = new LonTree(k,d); retLonTree.tree = it.newIntervalTree(-180,180,{'tree':it.newIntervalTree(-90,90)}); return retLonTree; }; module.exports.newLonTree = newLonTree; LonTree.prototype.add = function(cloudLat,cloudLon){ var toAdd = it.newCloudCoord(cloudLat,cloudLon,this.k,this.d); this.tree.addCloud(toAdd,this.breakCondition,this.lon,true); }; LonTree.prototype.query = function(queryLat,queryLon){ var latTree = null; var middle = 0; var curr = this.tree.root; var done = false; // Search for the correct LatTree while (!done){ middle = ((curr.intervalj - curr.intervali)/2) + curr.intervali; if (queryLon > middle){ if (curr.right !== null){ curr = curr.right; } else{ latTree = curr.tree; done = true; } } else{ if (curr.left !== null){ curr = curr.left; } else{ latTree = curr.tree; done = true; } } } // Search for the grid points var data = null; curr = latTree.root; done = false; // Search for the correct LatTree while (!done){ middle = ((curr.intervalj - curr.intervali)/2) + curr.intervali; if (queryLat > middle){ if (curr.right !== null){ curr = curr.right; } else{ data = curr.data; done = true; } } else{ if (curr.left !== null){ curr = curr.left; } else{ data = curr.data; done = true; } } } var retItems = []; var queryLatLon = new LatLon(queryLat,queryLon); // Run through data, check distance to query for (var i=0; i<data.length; i++){ var cmp = data[i]; if (typeof(data[i].center) !== 'undefined'){ cmp = data[i].center; } var cmpll = new LatLon(cmp.lat,cmp.lon); var unique = true; for (var j=0; j<retItems.length; j++){ if (cmp === retItems[j]){ unique = false; } } if (queryLatLon.distanceTo(cmpll) <= this.d && unique){ retItems.push(cmp); } } return retItems; }; var sigmaTranslate = function (edges, nodes, node, left, right, height, incrementHeight){ var n = {}; n.id = node.intervali + ' ' + node.intervalj; n.label = '(' + node.intervali + ',' + node.intervalj + ')'; n.y = height; n.x = ((right-left)/2)+left; n.size = 2; nodes = nodes.concat(n); if (node.left === null && node.right === null){ return {'edges':edges, 'nodes':nodes}; } if (node.left !== null){ var e = {}; e.id = Math.random() + 'x'; e.source = n.id; e.target = node.left.intervali + ' ' + node.left.intervalj; edges = edges.concat(e); var ret = sigmaTranslate(edges, nodes, node.left,left,((right-left)/2)+left, height+incrementHeight, incrementHeight); edges = ret.edges; nodes = ret.nodes; } if (node.right !== null){ var e = {}; e.id = Math.random() + 'x'; e.source = n.id; e.target = node.right.intervali + ' ' + node.right.intervalj; edges = edges.concat(e); var ret = sigmaTranslate(edges, nodes, node.right,((right-left)/2)+left,right, height+incrementHeight, incrementHeight); edges = ret.edges; nodes = ret.nodes; } var toReturn = {}; toReturn.edges = edges; toReturn.nodes = nodes; return toReturn; }; var getTranslation = function (lonTree){ var x = sigmaTranslate([],[],lonTree.tree.root,0,2500,0,100); console.log("%j",x); }; module.exports.getTranslation = getTranslation; // var add = function (l){ // l.add(40.7974,-74.481536); // l.add(34.020029,-118.286931); // l.add(29.426468,-98.491233); // l.add(37.62261,-122.37804); // l.add(61.59938,-149.126804); // l.add( 39.653671,-104.959502); // l.add(47.850015,-122.279457); // l.add(52.114942,-106.632519); // l.add(47.622767,-122.33668); // l.add(41.643112,-88.001369); // //var lll = require('./lonTree'); var l = lll.newLonTree(8,8.04672); lll.addLOL(l); lll.getTranslation(l.tree); // }; // module.exports.addLOL = add;
Type.registerNamespace("Strings"); Strings.OfficeOM = function() { }; Strings.OfficeOM.registerClass("Strings.OfficeOM"); Strings.OfficeOM.L_APICallFailed = "Volanie API zlyhalo"; Strings.OfficeOM.L_APINotSupported = "API nie je podporované"; Strings.OfficeOM.L_ActivityLimitReached = "Dosiahol sa limit aktivít."; Strings.OfficeOM.L_AddBindingFromPromptDefaultText = "Vykonajte výber."; Strings.OfficeOM.L_AddinIsAlreadyRequestingToken = "Doplnok si už vyžaduje prístupový token."; Strings.OfficeOM.L_AddinIsAlreadyRequestingTokenMessage = "Operácia zlyhala, pretože tento doplnok si už vyžaduje prístupový token."; Strings.OfficeOM.L_ApiNotFoundDetails = "Metóda alebo vlastnosť {0} je súčasťou množiny požiadaviek rozhrania {1}, ktoré nie je k dispozícii vo vašej verzii aplikácie {2}."; Strings.OfficeOM.L_AppNameNotExist = "Názov doplnku pre {0} neexistuje."; Strings.OfficeOM.L_AppNotExistInitializeNotCalled = "Aplikácia {0} neexistuje. Nevolá sa Microsoft.Office.WebExtension.initialize(reason)."; Strings.OfficeOM.L_AttemptingToSetReadOnlyProperty = "Prebieha pokus o nastavenie vlastnosti {0} určenej iba na čítanie."; Strings.OfficeOM.L_BadSelectorString = "Reťazec odovzdaný do selektora je nesprávne naformátovaný alebo nie je podporovaný."; Strings.OfficeOM.L_BindingCreationError = "Chyba pri vytváraní väzby"; Strings.OfficeOM.L_BindingNotExist = "Zadaná väzba neexistuje."; Strings.OfficeOM.L_BindingToMultipleSelection = "Nesúvislý výber nie je podporovaný."; Strings.OfficeOM.L_BrowserAPINotSupported = "Tento prehliadač nepodporuje požadované API."; Strings.OfficeOM.L_CallbackNotAFunction = "Spätné volanie musí byť typom funkcie, bolo typom {0}."; Strings.OfficeOM.L_CannotApplyPropertyThroughSetMethod = "Zmeny vlastnosti {0} nemožno použiť prostredníctvom metódy object.set."; Strings.OfficeOM.L_CannotNavigateTo = "Objekt sa nachádza na mieste, kde nie je podporovaná navigácia."; Strings.OfficeOM.L_CannotRegisterEvent = "Obsluha udalostí sa nedá zaregistrovať."; Strings.OfficeOM.L_CannotWriteToSelection = "Do aktuálneho výberu nie je možné vykonať zápis."; Strings.OfficeOM.L_CellDataAmountBeyondLimits = "Poznámka: V tabuľke sa odporúča mať menej ako 20 000 buniek."; Strings.OfficeOM.L_CellFormatAmountBeyondLimits = "Poznámka: Odporúča sa mať menej ako 100 súprav formátovania nastavených volaním formátovania rozhrania API."; Strings.OfficeOM.L_CloseFileBeforeRetrieve = "Pred získaním ďalšieho súboru zavolajte closeAsync v aktuálnom súbore."; Strings.OfficeOM.L_CoercionTypeNotMatchBinding = "Zadaný typ koercie nie je kompatibilný s týmto typom väzby."; Strings.OfficeOM.L_CoercionTypeNotSupported = "Zadaný typ koercie nie je podporovaný."; Strings.OfficeOM.L_ColIndexOutOfRange = "Hodnota indexu stĺpca je mimo povoleného rozsahu. Použite hodnotu (0 alebo vyššiu), ktorá je menšia ako počet stĺpcov."; Strings.OfficeOM.L_ConfirmCancelMessage = "Ľutujeme, nemôžeme pokračovať."; Strings.OfficeOM.L_ConfirmDialog = "Dôverujete doméne {0}, kde je táto relácia balíka Office hosťovaná?"; Strings.OfficeOM.L_ConfirmRefreshMessage = "Ak chcete pokračovať, odstráňte doplnok a pridajte ho znova alebo obnovte stránku."; Strings.OfficeOM.L_ConnectionFailureWithDetails = "Požiadavka zlyhala s kódom stavu {0}, kódom chyby {1} a nasledujúcim chybovým hlásením: {2}"; Strings.OfficeOM.L_ConnectionFailureWithStatus = "Požiadavka zlyhala s kódom stavu {0}."; Strings.OfficeOM.L_ContinueButton = "Pokračovať"; Strings.OfficeOM.L_CustomFunctionDefinitionMissing = "V Excel.Script.CustomFunctions musí existovať vlastnosť s týmto názvom, ktorá predstavuje definíciu funkcie."; Strings.OfficeOM.L_CustomFunctionImplementationMissing = "Vlastnosť s týmto názvom v Excel.Script.CustomFunctions, ktorá predstavuje definíciu funkcie, musí obsahovať vlastnosť call implementujúcu funkciu."; Strings.OfficeOM.L_CustomFunctionNameCannotSplit = "Názov funkcie musí obsahovať neprázdny priestor názvov a neprázdny krátky názov."; Strings.OfficeOM.L_CustomFunctionNameContainsBadChars = "Názov funkcie môže obsahovať iba písmená, číslice, znaky podčiarknutia a bodky."; Strings.OfficeOM.L_CustomXmlError = "Vlastná chyba XML."; Strings.OfficeOM.L_CustomXmlExceedQuotaMessage = "XPath obmedzuje výber 1024 položiek."; Strings.OfficeOM.L_CustomXmlExceedQuotaName = "Dosiahol sa limit výberu"; Strings.OfficeOM.L_CustomXmlNodeNotFound = "Zadaný uzol sa nenašiel."; Strings.OfficeOM.L_CustomXmlOutOfDateMessage = "Údaje sú neaktuálne. Načítať objekt znova."; Strings.OfficeOM.L_CustomXmlOutOfDateName = "Neaktuálne údaje"; Strings.OfficeOM.L_DataNotMatchBindingSize = "Poskytnutý dátový objekt nezodpovedá veľkosti aktuálneho výberu."; Strings.OfficeOM.L_DataNotMatchBindingType = "Zadaný dátový objekt nie je kompatibilný s typom väzby."; Strings.OfficeOM.L_DataNotMatchCoercionType = "Typ zadaného dátového objektu nie je kompatibilný s aktuálnym výberom."; Strings.OfficeOM.L_DataNotMatchSelection = "Poskytnutý dátový objekt nie je kompatibilný s tvarom alebo rozmermi aktuálneho výberu."; Strings.OfficeOM.L_DataReadError = "Chyba pri čítaní údajov"; Strings.OfficeOM.L_DataStale = "Neaktuálne údaje"; Strings.OfficeOM.L_DataWriteError = "Chyba pri zápise údajov"; Strings.OfficeOM.L_DataWriteReminder = "Pripomenutie zapisovania údajov"; Strings.OfficeOM.L_DialogAddressNotTrusted = "Doména URL nie je zahrnutá v prvku AppDomains v manifeste a nie je subdoménou zdrojového umiestnenia."; Strings.OfficeOM.L_DialogAlreadyOpened = "Operácia zlyhala, pretože tento doplnok už má aktívne dialógové okno."; Strings.OfficeOM.L_DialogInvalidScheme = "Schéma URL adresy nie je podporovaná. Použite namiesto toho HTTPS."; Strings.OfficeOM.L_DialogNavigateError = "Chyba navigácie v dialógovom okne"; Strings.OfficeOM.L_DialogOK = "OK"; Strings.OfficeOM.L_DialogRequireHTTPS = "Protokol HTTP nie je podporovaný. Použite namiesto toho HTTPS."; Strings.OfficeOM.L_DisplayDialogError = "Chyba zobrazenia dialógového okna"; Strings.OfficeOM.L_DocumentReadOnly = "Požadovaná operácia nie je v aktuálnom režime dokumentu povolená."; Strings.OfficeOM.L_ElementMissing = "Nepodarilo sa nám naformátovať bunku tabuľky, pretože niektoré hodnoty parametra chýbajú. Ešte raz skontrolujte parametre a skúste to znova."; Strings.OfficeOM.L_EventHandlerAdditionFailed = "Obsluhu udalostí sa nepodarilo pridať."; Strings.OfficeOM.L_EventHandlerNotExist = "Zadaná obsluha udalostí sa pre túto väzbu nenašla."; Strings.OfficeOM.L_EventHandlerRemovalFailed = "Obsluhu udalostí sa nepodarilo odstrániť." Strings.OfficeOM.L_EventRegistrationError = "Chyba pri registrácii udalosti"; Strings.OfficeOM.L_FileTypeNotSupported = "Zadaný typ súboru nie je podporovaný."; Strings.OfficeOM.L_FormatValueOutOfRange = "Hodnota je mimo povoleného rozsahu."; Strings.OfficeOM.L_FormattingReminder = "Pripomenutie formátovania"; Strings.OfficeOM.L_FunctionCallFailed = "Volanie funkcie {0} zlyhalo, kód chyby: {1}."; Strings.OfficeOM.L_GetDataIsTooLarge = "Požadovaná množina údajov je príliš veľká."; Strings.OfficeOM.L_GetDataParametersConflict = "Uvedené parametre sú v konflikte."; Strings.OfficeOM.L_GetSelectionNotSupported = "Aktuálny výber nie je podporovaný."; Strings.OfficeOM.L_HostError = "Chyba hostiteľa"; Strings.OfficeOM.L_ImplicitGetAuthContextMissing = "Chýba funkcia na získanie autentifikácie kontextu"; Strings.OfficeOM.L_ImplicitNotLoaded = "Modul sa nenačíta pred získaním tokenu"; Strings.OfficeOM.L_InValidOptionalArgument = "neplatný voliteľný argument"; Strings.OfficeOM.L_IndexOutOfRange = "Index mimo rozsahu."; Strings.OfficeOM.L_InitializeNotReady = "Office.js sa ešte úplne nenačítal. Skúste to znovu neskôr alebo pridajte funkcii Office.initialize svoj inicializačný kód."; Strings.OfficeOM.L_InternalError = "Vnútorná chyba"; Strings.OfficeOM.L_InternalErrorDescription = "Vyskytla sa interná chyba."; Strings.OfficeOM.L_InvalidAPICall = "Neplatné volanie API"; Strings.OfficeOM.L_InvalidApiArgumentsMessage = "Neplatné vstupné argumenty."; Strings.OfficeOM.L_InvalidApiCallInContext = "V aktuálnom kontexte je volanie API neplatné."; Strings.OfficeOM.L_InvalidArgument = "Argument {0} pre túto situáciu nefunguje, chýba alebo nemá správny formát."; Strings.OfficeOM.L_InvalidArgumentGeneric = "Argumenty odovzdané funkcii nefungujú v tejto situácii, chýbajú alebo nie sú v správnom formáte."; Strings.OfficeOM.L_InvalidBinding = "Neplatná väzba"; Strings.OfficeOM.L_InvalidBindingError = "Chyba neplatnej väzby"; Strings.OfficeOM.L_InvalidBindingOperation = "Neplatná operácia väzby"; Strings.OfficeOM.L_InvalidCellsValue = "Minimálne jeden parameter bunky má hodnotu, ktorá nie je povolená. Ešte raz skontrolujte hodnoty a skúste to znova."; Strings.OfficeOM.L_InvalidCoercion = "Neplatný typ koercie"; Strings.OfficeOM.L_InvalidColumnsForBinding = "Uvedené stĺpce sú neplatné."; Strings.OfficeOM.L_InvalidDataFormat = "Formát zadaného dátového objektu nie je platný."; Strings.OfficeOM.L_InvalidDataObject = "Neplatný dátový objekt"; Strings.OfficeOM.L_InvalidFormat = "Chyba neplatného formátu"; Strings.OfficeOM.L_InvalidFormatValue = "Minimálne jeden parameter formátu má hodnotu, ktorá nie je povolená. Ešte raz skontrolujte hodnoty a skúste to znova."; Strings.OfficeOM.L_InvalidGetColumns = "Uvedené stĺpce sú neplatné."; Strings.OfficeOM.L_InvalidGetRowColumnCounts = "Zadané hodnoty počtu riadkov alebo počtu stĺpcov nie sú platné."; Strings.OfficeOM.L_InvalidGetRows = "Uvedené riadky sú neplatné."; Strings.OfficeOM.L_InvalidGetStartRowColumn = "Zadané hodnoty začiatočného riadka alebo začiatočného stĺpca nie sú platné."; Strings.OfficeOM.L_InvalidGrant = "Chýba predbežná autorizácia."; Strings.OfficeOM.L_InvalidGrantMessage = "Chýba povolenie tohto doplnku."; Strings.OfficeOM.L_InvalidNamedItemForBindingType = "Zadaný typ väzby nie je kompatibilný so zadanou pomenovanou položkou."; Strings.OfficeOM.L_InvalidNode = "Neplatný uzol"; Strings.OfficeOM.L_InvalidObjectPath = "Cesta k objektu {0} nefunguje pre to, čo sa snažíte urobiť. Ak používate objekt v rámci viacerých volaní funkcie context.sync a mimo sekvenčného spúšťania dávky .run, na spravovanie životnosti objektu použite metódy context.trackedObjects.add() a context.trackedObjects.remove()."; Strings.OfficeOM.L_InvalidOperationInCellEditMode = "Excel je v režime úpravy bunky. Ukončite režim úprav stlačením klávesu ENTER alebo TAB alebo výberom inej bunky, a potom to skúste znova."; Strings.OfficeOM.L_InvalidOrTimedOutSession = "Neplatná relácia alebo relácia s uplynutým časovým limitom"; Strings.OfficeOM.L_InvalidOrTimedOutSessionMessage = "Platnosť relácie balíka Office uplynula alebo je neplatná. Ak chcete pokračovať, obnovte stránku."; Strings.OfficeOM.L_InvalidParameters = "Funkcia {0} má neplatné parametre."; Strings.OfficeOM.L_InvalidReadForBlankRow = "Zadaný riadok je prázdny."; Strings.OfficeOM.L_InvalidRequestContext = "Objekt sa nedá použiť v kontextoch rôznych žiadostí."; Strings.OfficeOM.L_InvalidResourceUrl = "Bola zadaná neplatná URL adresa zdroja aplikácie."; Strings.OfficeOM.L_InvalidResourceUrlMessage = "V manifeste bola zadaná neplatná URL adresa zdroja."; Strings.OfficeOM.L_InvalidSSOAddinMessage = "Pre tento doplnok nie je podporované rozhranie API identity."; Strings.OfficeOM.L_InvalidSelectionForBindingType = "Nie je možné vytvoriť väzbu s aktuálnym výberom a so zadaným typom väzby."; Strings.OfficeOM.L_InvalidSetColumns = "Uvedené stĺpce sú neplatné."; Strings.OfficeOM.L_InvalidSetRows = "Uvedené riadky sú neplatné."; Strings.OfficeOM.L_InvalidSetStartRowColumn = "Zadané hodnoty začiatočného riadka alebo začiatočného stĺpca nie sú platné."; Strings.OfficeOM.L_InvalidTableOptionValue = "Minimálne jeden parameter tableOptions má hodnotu, ktorá nie je povolená. Ešte raz skontrolujte hodnoty a skúste to znova."; Strings.OfficeOM.L_InvalidValue = "Neplatná hodnota"; Strings.OfficeOM.L_MemoryLimit = "Prekročil sa limit pamäte"; Strings.OfficeOM.L_MissingParameter = "Chýbajúci parameter"; Strings.OfficeOM.L_MissingRequiredArguments = "chýba niekoľko požadovaných argumentov"; Strings.OfficeOM.L_MultipleNamedItemFound = "Našlo sa viacero objektov s rovnakým názvom."; Strings.OfficeOM.L_NamedItemNotFound = "Pomenovaná položka neexistuje."; Strings.OfficeOM.L_NavOutOfBound = "Operácia zlyhala, pretože index je mimo rozsahu."; Strings.OfficeOM.L_NetworkProblem = "Problém so sieťou"; Strings.OfficeOM.L_NetworkProblemRetrieveFile = "Získaniu súboru zabránil problém so sieťou."; Strings.OfficeOM.L_NewWindowCrossZone = "Nastavenia zabezpečenia vo vašom prehliadači nám bránia vo vytvorení dialógového okna. Skúste iný prehliadač alebo {0} tak, aby doména {1} a doména zobrazená na paneli s adresou boli v rovnakej zóne zabezpečenia."; Strings.OfficeOM.L_NewWindowCrossZoneConfigureBrowserLink = "nakonfigurujte prehliadač"; Strings.OfficeOM.L_NewWindowCrossZoneErrorString = "Obmedzenia prehliadača nám zabránili vo vytvorení dialógového okna. Doména dialógového okna a doména hostiteľa doplnku nie sú v rovnakej zóne zabezpečenia."; Strings.OfficeOM.L_NoCapability = "Nemáte dostatočné povolenia na vykonanie tejto akcie."; Strings.OfficeOM.L_NoHttpsWAC = "Táto relácia balíka Office nepoužíva zabezpečené pripojenie. Odporúčame vám vykonať ďalšie preventívne opatrenia."; Strings.OfficeOM.L_NonUniformPartialGetNotSupported = "Parametre súradnice nie je možné použiť s typom koercie Tabuľka, keď tabuľka obsahuje zlúčené bunky."; Strings.OfficeOM.L_NonUniformPartialSetNotSupported = "Parametre súradnice nie je možné použiť s typom koercie Tabuľka, keď tabuľka obsahuje zlúčené bunky."; Strings.OfficeOM.L_NotImplemented = "Funkcia {0} nie je implementovaná."; Strings.OfficeOM.L_NotSupported = "Funkcia {0} nie je podporovaná."; Strings.OfficeOM.L_NotSupportedBindingType = "Zadaný typ väzby {0} nie je podporovaný."; Strings.OfficeOM.L_NotSupportedEventType = "Zadaný typ udalosti {0} nie je podporovaný."; Strings.OfficeOM.L_NotTrustedWAC = "Tento doplnok bol zakázaný, aby ste ostali v bezpečí. Ak chcete naďalej používať doplnok, potvrďte, že táto položka je hosťovaná v dôveryhodnej doméne alebo ju otvorte v počítačovej aplikácii balíka Office."; Strings.OfficeOM.L_OperationCancelledError = "Operácia bola zrušená"; Strings.OfficeOM.L_OperationCancelledErrorMessage = "Používateľ zrušil operáciu."; Strings.OfficeOM.L_OperationNotSupported = "Operácia nie je podporovaná."; Strings.OfficeOM.L_OperationNotSupportedOnMatrixData = "Zdieľaný obsah musí byť vo formáte tabuľky. Údaje naformátujte ako tabuľku a skúste to znova."; Strings.OfficeOM.L_OperationNotSupportedOnThisBindingType = "Operácia nie je v tomto type väzby podporovaná."; Strings.OfficeOM.L_OsfControlTypeNotSupported = "Typ OsfControl nie je podporovaný."; Strings.OfficeOM.L_OutOfRange = "Mimo rozsahu"; Strings.OfficeOM.L_OverwriteWorksheetData = "Operácia nastavenia zlyhala, pretože poskytnutý dátový objekt prepíše alebo posunie údaje."; Strings.OfficeOM.L_PermissionDenied = "Povolenie odmietnuté"; Strings.OfficeOM.L_PropertyDoesNotExist = "Vlastnosť {0} sa v objekte nenachádza."; Strings.OfficeOM.L_PropertyNotLoaded = "Vlastnosť {0} nie je dostupná. Pred čítaním hodnoty vlastnosti zavolajte metódu načítania na objekt, ktorý je súčasťou, a zavolajte funkciu context.sync() v kontexte priradenej žiadosti."; Strings.OfficeOM.L_ReadSettingsError = "Chyba nastavení čítania"; Strings.OfficeOM.L_RedundantCallbackSpecification = "Spätné volanie nie je možné určiť ani v zozname argumentov ani vo voliteľnom objekte."; Strings.OfficeOM.L_RequestPayloadSizeLimitExceededMessage = "Veľkosť údajovej časti požiadavky prekročila limit. Pozrite si dokumentáciu: https://docs.microsoft.com/office/dev/add-ins/concepts/resource-limits-and-performance-optimization#excel-add-ins."; Strings.OfficeOM.L_RequestTimeout = "Volanie sa vykonáva príliš dlho."; Strings.OfficeOM.L_RequestTokenUnavailable = "Toto API bolo obmedzené, aby sa spomalila rýchlosť volania."; Strings.OfficeOM.L_ResponsePayloadSizeLimitExceededMessage = "Veľkosť údajovej časti odpovede prekročila limit. Pozrite si dokumentáciu: https://docs.microsoft.com/office/dev/add-ins/concepts/resource-limits-and-performance-optimization#excel-add-ins."; Strings.OfficeOM.L_RowIndexOutOfRange = "Hodnota indexu riadka je mimo povoleného rozsahu. Použite hodnotu (0 alebo vyššiu), ktorá je menšia ako počet riadkov."; Strings.OfficeOM.L_RunMustReturnPromise = "Dávková funkcia presunutá do metódy .run nevrátila sľub. Funkcia musí vrátiť sľub, aby bolo možné po dokončení operácie dávky uvoľniť všetky automaticky sledované objekty. Sľub zvyčajne vrátite vrátením odpovede z funkcie context.sync()."; Strings.OfficeOM.L_SSOClientError = "V žiadosti o overenie z balíka Office sa vyskytla chyba."; Strings.OfficeOM.L_SSOClientErrorMessage = "V klientovi sa vyskytla neočakávaná chyba."; Strings.OfficeOM.L_SSOConnectionLostError = "Počas procesu prihlásenia sa prerušilo spojenie."; Strings.OfficeOM.L_SSOConnectionLostErrorMessage = "Počas procesu prihlásenia sa prerušilo spojenie a používateľ nemusí byť prihlásený. Pravdepodobne to spôsobili nastavenia konfigurácie prehliadača používateľa, ako napríklad zóny zabezpečenia."; Strings.OfficeOM.L_SSOServerError = "V poskytovateľovi overenia sa vyskytla chyba."; Strings.OfficeOM.L_SSOServerErrorMessage = "Na serveri sa vyskytla neočakávaná chyba."; Strings.OfficeOM.L_SSOUnsupportedPlatform = "V tejto platforme sa nepodporuje rozhranie API."; Strings.OfficeOM.L_SSOUserConsentNotSupportedByCurrentAddinCategory = "Tento doplnok nepodporuje súhlas používateľa."; Strings.OfficeOM.L_SSOUserConsentNotSupportedByCurrentAddinCategoryMessage = "Operácia zlyhala, pretože tento doplnok nepodporuje súhlas používateľa v tejto kategórii"; Strings.OfficeOM.L_SaveSettingsError = "Chyba nastavení ukladania"; Strings.OfficeOM.L_SelectionCannotBound = "S aktuálnym výberom nie je možné vytvoriť väzbu."; Strings.OfficeOM.L_SelectionNotSupportCoercionType = "Aktuálny výber nie je kompatibilný so zadaným typom koercie."; Strings.OfficeOM.L_SetDataIsTooLarge = "Zadaný dátový objekt je príliš veľký."; Strings.OfficeOM.L_SetDataParametersConflict = "Uvedené parametre sú v konflikte."; Strings.OfficeOM.L_SettingNameNotExist = "Zadaný názov nastavenia neexistuje."; Strings.OfficeOM.L_SettingsAreStale = "Nastavenia sa nepodarilo uložiť, pretože nie sú aktuálne."; Strings.OfficeOM.L_SettingsCannotSave = "Nastavenia sa nepodarilo uložiť."; Strings.OfficeOM.L_SettingsStaleError = "Chyba zastaraných nastavení"; Strings.OfficeOM.L_ShowWindowDialogNotification = "{0} chce zobraziť nové okno."; Strings.OfficeOM.L_ShowWindowDialogNotificationAllow = "Povoliť"; Strings.OfficeOM.L_ShowWindowDialogNotificationIgnore = "Ignorovanie"; Strings.OfficeOM.L_ShuttingDown = "Operácia zlyhala, pretože údaje na serveri nie sú aktuálne."; Strings.OfficeOM.L_SliceSizeNotSupported = "Zadaná veľkosť výseku nie je podporovaná."; Strings.OfficeOM.L_SpecifiedIdNotExist = "Zadaná identifikácia neexistuje."; Strings.OfficeOM.L_Timeout = "Časový limit operácie uplynul."; Strings.OfficeOM.L_TooManyArguments = "priveľa argumentov"; Strings.OfficeOM.L_TooManyIncompleteRequests = "Počkajte, kým sa dokončí predchádzajúce volanie."; Strings.OfficeOM.L_TooManyOptionalFunction = "viacero voliteľných funkcií v zozname parametrov"; Strings.OfficeOM.L_TooManyOptionalObjects = "viacero voliteľných objektov v zozname parametrov"; Strings.OfficeOM.L_UnknownBindingType = "Tento typ väzby nie je podporovaný."; Strings.OfficeOM.L_UnsupportedDataObject = "Poskytnutý typ dátového objektu nie je podporovaný."; Strings.OfficeOM.L_UnsupportedEnumeration = "Nepodporovaná enumerácia"; Strings.OfficeOM.L_UnsupportedEnumerationMessage = "Aktuálna hostiteľská aplikácia nepodporuje enumeráciu."; Strings.OfficeOM.L_UnsupportedUserIdentity = "Typ identity používateľa nie je podporovaný."; Strings.OfficeOM.L_UnsupportedUserIdentityMessage = "Typ identity používateľa nie je podporovaný."; Strings.OfficeOM.L_UserAborted = "Používateľ prerušil žiadosť o súhlas."; Strings.OfficeOM.L_UserAbortedMessage = "Používateľ nevyjadril súhlas s povoleniami doplnku."; Strings.OfficeOM.L_UserClickIgnore = "Používateľ sa rozhodol ignorovať toto dialógové okno."; Strings.OfficeOM.L_UserNotSignedIn = "V Office nie je prihlásený žiaden používateľ."; Strings.OfficeOM.L_ValueNotLoaded = "Hodnota výsledného objektu zatiaľ nebola načítaná. Pred čítaním vlastnosti hodnoty zavolajte príkaz context.sync() pre daný kontext požiadavky."; Strings.OfficeOM.L_WorkbookHiddenMessage = "Požiadavka na JavaScript API zlyhala, pretože zošit bol skrytý. Odkryte zošit a skúste to znova."; Strings.OfficeOM.L_WriteNotSupportedWhenModalDialogOpen = "Operácia zapisovania nie je podporovaná pre Office, keď je otvorené modálne dialógové okno.";
"use strict"; var Renderer = require("./renderer"); var Camera = require("./camera"); var Vector = require("./math/vector"); var Action = require("./enums").Action; function MovingDots(amount, msPerUpdate) { this.max = amount + 1; this.current = 0; this.msPerUpdate = msPerUpdate; this.timeSinceLastUpdate = 0; } MovingDots.prototype.update = function (delta) { this.timeSinceLastUpdate += delta; if (this.timeSinceLastUpdate >= this.msPerUpdate) { this.current = (this.current + 1) % this.max; this.timeSinceLastUpdate = 0; } }; // jscs: disable MovingDots.prototype.toString = function () { return new Array(this.current + 1).join("."); }; // jscs: enable function getYOffset(index, player, extraOffset) { extraOffset = extraOffset || 0; return -1 * ((index + 1) % 2) * (player.size.y + extraOffset); } function LoadingScreen(players, currentPlayer, background, loadingProgress, canvas) { this.players = players; this.currentPlayer = currentPlayer; this.background = background; this.dots = new MovingDots(3, 500); this.loadingProgress = loadingProgress; this.renderer = new Renderer(canvas.getContext("2d"), false, 1); var size = new Vector(canvas.width, canvas.height); this.renderer.init(new Camera(new Vector(), size)); this.savedSizes = []; var startingPositionX = canvas.width / 3; var startingPositionY = canvas.height / 2; var positionX = startingPositionX; var proximityCoeff = 0.8; for (var i = 0; i < players.length; i++) { if (i === currentPlayer) { var offsetX = proximityCoeff * players[i].size.x * (players.length - 1.5) / 2; players[i].position.x = startingPositionX + offsetX; var offsetY = players[i].size.y * 1.5; players[i].position.y = startingPositionY + offsetY; } else { players[i].position.x = positionX; players[i].position.y = startingPositionY + getYOffset(i, players[i]); positionX += players[i].size.x * proximityCoeff; } players[i].playAnimation(Action.walk, Vector.up); this.savedSizes[i] = players[i].size.clone(); } this.previousTime = 0; this.loop = this.render.bind(this); this.animationFrameId = requestAnimationFrame(this.loop); } LoadingScreen.prototype.render = function (/* timestamp */) { var delta = 1000 / 30; this.renderer.render(delta, [this.players], [], this.background, false); for (var i = 0; i < this.players.length; i++) { var progress = this.loadingProgress[i]; var textX = this.players[i].position.x + this.players[i].size.x / 2; var extraOffset = 20; // Magic var textY = this.players[i].position.y - getYOffset(i + 1, this.players[i]) + extraOffset; if (i === this.currentPlayer) { textY = this.players[i].position.y + this.players[i].size.y + extraOffset; } var textPos = new Vector(textX, textY); this.renderer.renderText((progress * 100).toFixed(0) + "%", textPos, "white", undefined, true); this.players[i].size = this.savedSizes[i].multiply(progress); } this.dots.update(delta); this.renderer.renderText("Marching towards the tower" + this.dots, new Vector("center", -50), "white", "32px Segoe UI", true); this.animationFrameId = requestAnimationFrame(this.loop); }; LoadingScreen.prototype.destroy = function () { for (var i = 0; i < this.players.length; i++) { this.players[i].size = this.savedSizes[i]; } cancelAnimationFrame(this.animationFrameId); }; module.exports = LoadingScreen;
// Saves options to chrome.storage function save_options() { var allowed_external_urls = document.getElementById('allowed_external_urls').value; chrome.storage.sync.set({ allowed_external_urls: allowed_external_urls }, function() { // Update status to let user know options were saved. var status = document.getElementById('status'); status.textContent = 'Options saved.'; setTimeout(function() { status.textContent = ''; }, 750); }); } // Restores select box and checkbox state using the preferences // stored in chrome.storage. function restore_options() { // Use default value color = 'red' and likesColor = true. chrome.storage.sync.get({ allowed_external_urls: 'bit.ly' }, function(items) { console.log(items); document.getElementById('allowed_external_urls').value = items.allowed_external_urls; }); } document.addEventListener('DOMContentLoaded', restore_options); document.getElementById('save').addEventListener('click', save_options);
import React from 'react'; import {render} from 'react-dom'; import {Provider} from 'react-redux'; import configureStore from './store/configureStore'; import AppRouter from './store/router'; require('./components/styles/main.scss'); const store = configureStore({}); render( <Provider store={store}> <AppRouter /> </Provider>, document.getElementById('main') );
import YHT from "../utils/yht"; export default class UserStore { constructor() { YHT.subscribe("user.login", self, "onUserLogin") } onUserLogin(params) { console.log("onUserLogin: "+params) } }
(function (window, angular) { 'use strict'; angular.module('ea.controllers') .controller('LoginCtrl', ['$scope', '$state', 'bk.utils', 'ea.authentication', 'ea.toastr', 'externalLogins', function ($scope, $state, utils, authentication, toastr, externalLogins) { var ctrl = this; utils.errorContext.init(this); this.modal = $scope.$dismiss !== undefined;//call as modal dialog this.externalLogins = externalLogins; this.model = { userName: undefined, password: undefined, }; this.submitForm = function () { if (this.form.$valid) { authentication.logIn(this.model) .catch(function (error) { utils.errorContext.set(ctrl, error.error_description); }); } }; this.externalLogin = function (external) { authentication.externalLogin(external); }; $scope.$on('ea:authentication:token', function (event, service) { if (service.isAuthenticated()) { if (ctrl.modal) { $scope.$close(true); } else { $state.go('home', { congratulation: 'on' }); } } }); $scope.$on('ea:authentication:externallogin', function (event, token) { // направен е опит да се влезе с публичен профил и този профил не е регистриран var params = { loginProvider: token.provider, token: token.access_token, userName: token.userName, email: token.email }; $state.go('account.externalloginconfirmation', params, { location: false }); }); $scope.$on('ea:authentication:externallogin:error', function (event, data) { toastr.error(data.error); }); }]); })(window, window.angular);
/** * This class implements the component event domain. All classes extending from * {@link Ext.Component} are included in this domain. The matching criteria uses * {@link Ext.ComponentQuery}. * * @protected */ Ext.define('Ext.app.domain.Component', { extend: 'Ext.app.EventDomain', singleton: true });
import ReactDOM from 'react-dom'; import { scryRenderedDOMComponentsWithClass, scryRenderedDOMComponentsWithTag } from 'react-addons-test-utils'; export function setProps(props) { this.instance.setState(props); } export function extractRootDOMNode() { this.elements.rootDOMNode = ReactDOM.findDOMNode(this.instance); } export function findClass(className) { const elements = scryRenderedDOMComponentsWithClass(this.instance, className); if (Array.isArray(elements) && elements.length === 1) { this.elements.result = elements[0]; } else { this.elements.result = elements; } } export function findTag(tag) { const elements = scryRenderedDOMComponentsWithTag(this.instance, tag); if (Array.isArray(elements) && elements.length === 1) { this.elements[tag] = elements[0]; } else { this.elements[tag] = elements; } }
'use strict'; angular.module('alchemy').directive('alchDropdown', function(){ return { restrict: 'EA', transclude: true, replace: true, scope: { 'dropdown' : '=alchDropdown' }, templateUrl: 'component/templates/dropdown.html', controller: ['$scope', function($scope) { $scope.setHover = function(item, mousein) { if (mousein) { item.active = true; if (item.type === 'flyout') { $scope.flyout = item.items; $scope.flyout.show = true; } } else { if ($scope.flyout) { $scope.flyout.show = false; } item.active = false; } }; $scope.isRight = function(direction) { return direction === 'right'; }; }] }; });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Type2 = require('./Type'); var _Type3 = _interopRequireDefault(_Type2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * # TypeParameterApplication * */ var TypeParameterApplication = function (_Type) { _inherits(TypeParameterApplication, _Type); function TypeParameterApplication() { var _ref; var _temp, _this, _ret; _classCallCheck(this, TypeParameterApplication); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = TypeParameterApplication.__proto__ || Object.getPrototypeOf(TypeParameterApplication)).call.apply(_ref, [this].concat(args))), _this), _this.typeName = 'TypeParameterApplication', _this.typeInstances = [], _temp), _possibleConstructorReturn(_this, _ret); } _createClass(TypeParameterApplication, [{ key: 'collectErrors', value: function collectErrors(validation, path, input) { var parent = this.parent, typeInstances = this.typeInstances; return parent.collectErrors.apply(parent, [validation, path, input].concat(_toConsumableArray(typeInstances))); } }, { key: 'accepts', value: function accepts(input) { var parent = this.parent, typeInstances = this.typeInstances; return parent.accepts.apply(parent, [input].concat(_toConsumableArray(typeInstances))); } }, { key: 'acceptsType', value: function acceptsType(input) { return this.parent.acceptsType(input); } }, { key: 'hasProperty', value: function hasProperty(name) { var inner = this.parent; if (inner && typeof inner.hasProperty === 'function') { var _ref2; return (_ref2 = inner).hasProperty.apply(_ref2, [name].concat(_toConsumableArray(this.typeInstances))); } else { return false; } } }, { key: 'getProperty', value: function getProperty(name) { var inner = this.parent; if (inner && typeof inner.getProperty === 'function') { var _ref3; return (_ref3 = inner).getProperty.apply(_ref3, [name].concat(_toConsumableArray(this.typeInstances))); } } }, { key: 'toString', value: function toString() { var parent = this.parent, typeInstances = this.typeInstances; var name = parent.name; if (typeInstances.length) { var items = []; for (var i = 0; i < typeInstances.length; i++) { var typeInstance = typeInstances[i]; items.push(typeInstance.toString()); } return name + '<' + items.join(', ') + '>'; } else { return name; } } }, { key: 'toJSON', value: function toJSON() { return { typeName: this.typeName, typeInstances: this.typeInstances }; } }]); return TypeParameterApplication; }(_Type3.default); exports.default = TypeParameterApplication;
/** * OpenFB is a micro-library that lets you integrate your JavaScript application with Facebook. * OpenFB works for both BROWSER-BASED apps and CORDOVA/PHONEGAP apps. * This library has no dependency: You don't need (and shouldn't use) the Facebook SDK with this library. Whe running in * Cordova, you also don't need the Facebook Cordova plugin. There is also no dependency on jQuery. * OpenFB allows you to login to Facebook and execute any Facebook Graph API request. * @author Christophe Coenraets @ccoenraets * @version 0.2 */ angular.module('openfb', []) .factory('OpenFB', function ($rootScope, $q, $window, $http) { var FB_LOGIN_URL = 'https://www.facebook.com/dialog/oauth', // By default we store fbtoken in sessionStorage. This can be overriden in init() tokenStore = window.localStorage, fbAppId, oauthRedirectURL, // Because the OAuth login spans multiple processes, we need to keep the success/error handlers as variables // inside the module instead of keeping them local within the login function. deferredLogin, // Indicates if the app is running inside Cordova runningInCordova, // Used in the exit event handler to identify if the login has already been processed elsewhere (in the oauthCallback function) loginProcessed; /*document.addEventListener("deviceready", function () { runningInCordova = true; }, false);*/ /** * Initialize the OpenFB module. You must use this function and initialize the module with an appId before you can * use any other function. * @param appId - The id of the Facebook app * @param redirectURL - The OAuth redirect URL. Optional. If not provided, we use sensible defaults. * @param store - The store used to save the Facebook token. Optional. If not provided, we use sessionStorage. */ function init(appId, cordova, redirectURL, store) { fbAppId = appId; if (redirectURL) oauthRedirectURL = redirectURL; if (store) tokenStore = store; runningInCordova = cordova; } /** * Login to Facebook using OAuth. If running in a Browser, the OAuth workflow happens in a a popup window. * If running in Cordova container, it happens using the In-App Browser. Don't forget to install the In-App Browser * plugin in your Cordova project: cordova plugins add org.apache.cordova.inappbrowser. * @param fbScope - The set of Facebook permissions requested */ function login(fbScope) { if (!fbAppId) { return error({error: 'Facebook App Id not set.'}); } var loginWindow; fbScope = fbScope || ''; deferredLogin = $q.defer(); loginProcessed = false; logout(); // Check if an explicit oauthRedirectURL has been provided in init(). If not, infer the appropriate value if (!oauthRedirectURL) { if (runningInCordova) { oauthRedirectURL = 'https://www.facebook.com/connect/login_success.html'; } else { // Trying to calculate oauthRedirectURL based on the current URL. var index = document.location.href.indexOf('index.html'); if (index > 0) { oauthRedirectURL = document.location.href.substring(0, index) + 'oauthcallback.html'; } else { return alert("Can't reliably infer the OAuth redirect URI. Please specify it explicitly in openFB.init()"); } } } loginWindow = window.open(FB_LOGIN_URL + '?client_id=' + fbAppId + '&redirect_uri=' + oauthRedirectURL + '&response_type=token&display=popup&scope=' + fbScope, '_blank', 'location=no'); // If the app is running in Cordova, listen to URL changes in the InAppBrowser until we get a URL with an access_token or an error if (runningInCordova) { loginWindow.addEventListener('loadstart', function (event) { var url = event.url; if (url.indexOf("access_token=") > 0 || url.indexOf("error=") > 0) { loginWindow.close(); oauthCallback(url); } }); loginWindow.addEventListener('exit', function () { // Handle the situation where the user closes the login window manually before completing the login process deferredLogin.reject({error: 'user_cancelled', error_description: 'User cancelled login process', error_reason: "user_cancelled"}); }); } // Note: if the app is running in the browser the loginWindow dialog will call back by invoking the // oauthCallback() function. See oauthcallback.html for details. return deferredLogin.promise; } /** * Called either by oauthcallback.html (when the app is running the browser) or by the loginWindow loadstart event * handler defined in the login() function (when the app is running in the Cordova/PhoneGap container). * @param url - The oautchRedictURL called by Facebook with the access_token in the querystring at the ned of the * OAuth workflow. */ function oauthCallback(url) { // Parse the OAuth data received from Facebook var queryString, obj; loginProcessed = true; if (url.indexOf("access_token=") > 0) { queryString = url.substr(url.indexOf('#') + 1); obj = parseQueryString(queryString); tokenStore['fbtoken'] = obj['access_token']; deferredLogin.resolve(); } else if (url.indexOf("error=") > 0) { queryString = url.substring(url.indexOf('?') + 1, url.indexOf('#')); obj = parseQueryString(queryString); deferredLogin.reject(obj); } else { deferredLogin.reject(); } } /** * Application-level logout: we simply discard the token. */ function logout() { tokenStore['fbtoken'] = undefined; } /** * Helper function to de-authorize the app * @param success * @param error * @returns {*} */ function revokePermissions() { return api({method: 'DELETE', path: '/me/permissions'}) .success(function () { console.log('Permissions revoked'); }); } /** * Lets you make any Facebook Graph API request. * @param obj - Request configuration object. Can include: * method: HTTP method: GET, POST, etc. Optional - Default is 'GET' * path: path in the Facebook graph: /me, /me.friends, etc. - Required * params: queryString parameters as a map - Optional */ function api(obj) { var method = obj.method || 'GET', params = obj.params || {}; params['access_token'] = tokenStore['fbtoken']; return $http({method: method, url: 'https://graph.facebook.com' + obj.path, params: params}) .error(function(data, status, headers, config) { if (data.error && data.error.type === 'OAuthException') { $rootScope.$emit('OAuthException'); } }); } /** * Helper function for a POST call into the Graph API * @param path * @param params * @returns {*} */ function post(path, params) { return api({method: 'POST', path: path, params: params}); } /** * Helper function for a GET call into the Graph API * @param path * @param params * @returns {*} */ function get(path, params) { return api({method: 'GET', path: path, params: params}); } function parseQueryString(queryString) { var qs = decodeURIComponent(queryString), obj = {}, params = qs.split('&'); params.forEach(function (param) { var splitter = param.split('='); obj[splitter[0]] = splitter[1]; }); return obj; } return { init: init, login: login, logout: logout, revokePermissions: revokePermissions, api: api, post: post, get: get, oauthCallback: oauthCallback } });
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { routerContext } from 'react-router/PropTypes'; import { FormattedMessage } from 'react-intl'; import Match from 'react-router/Match'; import Helmet from 'react-helmet'; import OrderList from '../../components/OrdersList'; import Button from '../../components/Button'; import { compose } from 'redux'; import { ordersConnector, ordersSelector } from '../../utils/ordersService'; import styles from './styles.scss'; import FaPlus from 'react-icons/lib/fa/plus'; import messages from './messages'; import OrderModal from '../OrderModal'; import MealModal from '../MealModal'; export class ActiveOrdersPage extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { orders: PropTypes.array.isRequired, currentUser: PropTypes.string, params: PropTypes.object.isRequired, }; static contextTypes = { router: routerContext, }; render() { const { orders, params, currentUser } = this.props; const { router } = this.context; const newPath = params.order ? `/${params.order}/new` : '/new'; return ( <div> <Helmet title="Active Orders - AmciuApp" /> <div className={styles.actions}> <Button className={styles.buttonFullsize} to={newPath}> <FaPlus /> <FormattedMessage {...messages.createOrder} /> </Button> </div> <OrderList orders={orders} activeKey={params.order} onFocus={(id) => router.transitionTo(`/${id}`)} onAddMeal={(id) => router.transitionTo(`/${id}/new-meal`)} currentUser={currentUser} /> <Match pattern="/:order?/new" component={OrderModal} /> <Match pattern="/:order?/new-meal" component={MealModal} /> </div> ); } } function mapDispatchToProps(dispatch) { return { dispatch, }; } export default compose( ordersConnector, connect((state) => ({ currentUser: (state.getIn(['firebase', 'auth']) || {}).displayName, orders: ordersSelector(state) .filter(([, order]) => !order.archived), }), mapDispatchToProps) )(ActiveOrdersPage);
var _ = require('./util') var config = require('./config') var Watcher = require('./watcher') var textParser = require('./parsers/text') var expParser = require('./parsers/expression') /** * A directive links a DOM element with a piece of data, * which is the result of evaluating an expression. * It registers a watcher with the expression and calls * the DOM update function when a change is triggered. * * @param {String} name * @param {Node} el * @param {Vue} vm * @param {Object} descriptor * - {String} expression * - {String} [arg] * - {Array<Object>} [filters] * @param {Object} def - directive definition object * @param {Vue|undefined} host - transclusion host target * @constructor */ function Directive (name, el, vm, descriptor, def, host) { // public this.name = name this.el = el this.vm = vm // copy descriptor props this.raw = descriptor.raw this.expression = descriptor.expression this.arg = descriptor.arg this.filters = descriptor.filters // private this._descriptor = descriptor this._host = host this._locked = false this._bound = false // init this._bind(def) } var p = Directive.prototype /** * Initialize the directive, mixin definition properties, * setup the watcher, call definition bind() and update() * if present. * * @param {Object} def */ p._bind = function (def) { if (this.name !== 'cloak' && this.el && this.el.removeAttribute) { this.el.removeAttribute(config.prefix + this.name) } if (typeof def === 'function') { this.update = def } else { _.extend(this, def) } this._watcherExp = this.expression this._checkDynamicLiteral() if (this.bind) { this.bind() } if (this._watcherExp && (this.update || this.twoWay) && (!this.isLiteral || this._isDynamicLiteral) && !this._checkStatement()) { // wrapped updater for context var dir = this var update = this._update = this.update ? function (val, oldVal) { if (!dir._locked) { dir.update(val, oldVal) } } : function () {} // noop if no update is provided // pre-process hook called before the value is piped // through the filters. used in v-repeat. var preProcess = this._preProcess ? _.bind(this._preProcess, this) : null var watcher = this._watcher = new Watcher( this.vm, this._watcherExp, update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess } ) if (this._initValue != null) { watcher.set(this._initValue) } else if (this.update) { this.update(watcher.value) } } this._bound = true } /** * check if this is a dynamic literal binding. * * e.g. v-component="{{currentView}}" */ p._checkDynamicLiteral = function () { var expression = this.expression if (expression && this.isLiteral) { var tokens = textParser.parse(expression) if (tokens) { var exp = textParser.tokensToExp(tokens) this.expression = this.vm.$get(exp) this._watcherExp = exp this._isDynamicLiteral = true } } } /** * Check if the directive is a function caller * and if the expression is a callable one. If both true, * we wrap up the expression and use it as the event * handler. * * e.g. v-on="click: a++" * * @return {Boolean} */ p._checkStatement = function () { var expression = this.expression if ( expression && this.acceptStatement && !expParser.isSimplePath(expression) ) { var fn = expParser.parse(expression).get var vm = this.vm var handler = function () { fn.call(vm, vm) } if (this.filters) { handler = vm._applyFilters(handler, null, this.filters) } this.update(handler) return true } } /** * Check for an attribute directive param, e.g. lazy * * @param {String} name * @return {String} */ p._checkParam = function (name) { var param = this.el.getAttribute(name) if (param !== null) { this.el.removeAttribute(name) } return param } /** * Teardown the watcher and call unbind. */ p._teardown = function () { if (this._bound) { this._bound = false if (this.unbind) { this.unbind() } if (this._watcher) { this._watcher.teardown() } this.vm = this.el = this._watcher = null } } /** * Set the corresponding value with the setter. * This should only be used in two-way directives * e.g. v-model. * * @param {*} value * @public */ p.set = function (value) { if (this.twoWay) { this._withLock(function () { this._watcher.set(value) }) } } /** * Execute a function while preventing that function from * triggering updates on this directive instance. * * @param {Function} fn */ p._withLock = function (fn) { var self = this self._locked = true fn.call(self) _.nextTick(function () { self._locked = false }) } module.exports = Directive
'use strict' const {Parser: XMLParser} = require('xml2js') const camelCase = require('camelcase') // ------------------------------------------------------------- // Constants. // ------------------------------------------------------------- const OPTIONS = { explicitArray: false, async: false, tagNameProcessors: [x => camelCase(x)] } // ------------------------------------------------------------- // Module. // ------------------------------------------------------------- function parseXML (xml) { if (!xml) { throw new Error('XML input was null or empty') } let data new XMLParser(OPTIONS).parseString(xml, function (err, result) { if (err || !result) { throw new Error('Failed to parse XML file') } // Values are nested in the "product", "game" or "company" root node. // We need to detect and ignore this root element. if (result.game) { data = result.game data.type = 'product' } else if (result.product) { data = result.product data.type = 'product' } else if (result.company) { data = result.company data.type = 'company' } else { throw new Error('Unrecognized XML file, expected <game> or <company> root tag') } }) return data } // ------------------------------------------------------------- // Exports. // ------------------------------------------------------------- module.exports = { parseXML }
/*! Picturefill - v3.0.0 - 2015-05-14 * http://scottjehl.github.io/picturefill * Copyright (c) 2015 https://github.com/scottjehl/picturefill/blob/master/Authors.txt; Licensed MIT */ !function(a){"use strict";var b,c=0,d=function(){window.picturefill&&a(window.picturefill),(window.picturefill||c>9999)&&clearInterval(b),c++};b=setInterval(d,8),d()}(function(a){"use strict";if(window.addEventListener){var b,c,d,e=window.matchMedia&&matchMedia("print")||{matches:!1},f=a._,g=function(a){return a?-1!=a.indexOf("print")?!0:b?b.apply(this,arguments):void 0:!0},h=function(){e.matches||b||(b=f.matchesMedia,f.matchesMedia=g),!c&&!d&&f.DPR<1.5&&f.cfg.xQuant<1.5&&(c=f.cfg.xQuant,d=f.DPR,f.DPR=1.5,f.cfg.xQuant=1.5),a({mqchange:!0})},i=function(){b&&(f.matchesMedia=b,b=!1),c&&(f.cfg.xQuant=c,c=!1),d&&(f.DPR=d,d=!1),a({reselect:!0})};"onbeforeprint"in window&&(addEventListener("beforeprint",h,!1),addEventListener("afterprint",i,!1))}});
var searchData= [ ['kaborted_120',['kAborted',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298bac322d48ca7a31da858a34182c93d95a2',1,'argcv::error']]], ['kalreadyexists_121',['kAlreadyExists',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298baf392f3d98680947e215f3737ffe37577',1,'argcv::error']]], ['kcancelled_122',['kCancelled',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298bafaf3007626cb68f872fee372629cc0b9',1,'argcv::error']]], ['kdataloss_123',['kDataLoss',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba3091f217270643822380de6dfce2a949',1,'argcv::error']]], ['kdeadlineexceeded_124',['kDeadlineExceeded',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298baf0995b2d9505e3c1a76f61abaf2df867',1,'argcv::error']]], ['kfailedprecondition_125',['kFailedPrecondition',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba4f0afa04b5ebda4875421c22c7248eae',1,'argcv::error']]], ['kinternal_126',['kInternal',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba71b13c3d12ccef0b42b2ae2b1092c88a',1,'argcv::error']]], ['kinvalidargument_127',['kInvalidArgument',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298baf480a4050a7f28e48bc777886e7c0769',1,'argcv::error']]], ['kmodeappend_128',['kModeAppend',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9aea38a73578409d18ad40dc9cb9d349ce',1,'argcv::io']]], ['kmodechardevice_129',['kModeCharDevice',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9a7647e27e962c7614225d9bd03d2fad94',1,'argcv::io']]], ['kmodedevice_130',['kModeDevice',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9a4341e42c350023742b119ab955636fb6',1,'argcv::io']]], ['kmodedir_131',['kModeDir',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9a44557345a7e9ea874e764c35931447f2',1,'argcv::io']]], ['kmodeexclusive_132',['kModeExclusive',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9ad748eeebf972431b4b484652c61297e6',1,'argcv::io']]], ['kmodeirregular_133',['kModeIrregular',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9a9c43ae12407c7f4b7f098a0ad517ae90',1,'argcv::io']]], ['kmodenamedpipe_134',['kModeNamedPipe',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9a33a9ca6e22e5efd22be10e48996a5ea9',1,'argcv::io']]], ['kmodeperm_135',['kModePerm',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9aeb91ed7686b938a330711f28610ea661',1,'argcv::io']]], ['kmodesetgid_136',['kModeSetgid',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9aa49f0b8317189b24c943b220890096b7',1,'argcv::io']]], ['kmodesetuid_137',['kModeSetuid',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9a8757f6f7bda76189a384e384b1bd6947',1,'argcv::io']]], ['kmodesocket_138',['kModeSocket',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9addf541900ce4fc537842eae35dbfd3fe',1,'argcv::io']]], ['kmodesticky_139',['kModeSticky',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9acd782ae4b63d6c0cec47e98739922d7b',1,'argcv::io']]], ['kmodesymlink_140',['kModeSymlink',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9acf262e2a15d2b4f53e19782e61e17ae7',1,'argcv::io']]], ['kmodetemporary_141',['kModeTemporary',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9a2953078c5581bda53580eb346d3e63e1',1,'argcv::io']]], ['kmodetype_142',['kModeType',['../namespaceargcv_1_1io.html#a13c6afd603d5cfc59aa2aee504b9e7a9a90b53e451b28a4a6214bfee9000fbd70',1,'argcv::io']]], ['knotfound_143',['kNotFound',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba3c2b92640c5f0efd3a66f14c7598a700',1,'argcv::error']]], ['kok_144',['kOk',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba07a5c8c63e96b490c59fc97df97b40b8',1,'argcv::error']]], ['koutofrange_145',['kOutOfRange',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba1f6d10f0eaea6ecd5bfaf139637a7946',1,'argcv::error']]], ['kpermissiondenied_146',['kPermissionDenied',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298baf6affb39f781e38679e17de9aa269d11',1,'argcv::error']]], ['kresourceexhausted_147',['kResourceExhausted',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba09072b88b0047d8ed579ac59070cffea',1,'argcv::error']]], ['kseekcurrent_148',['kSeekCurrent',['../namespaceargcv_1_1io.html#aef6b4f1f0b858341e7ba9c8ea6774352a668b0be180fa3c0e7b285ed9b0681a2d',1,'argcv::io']]], ['kseekend_149',['kSeekEnd',['../namespaceargcv_1_1io.html#aef6b4f1f0b858341e7ba9c8ea6774352ac5f1a28c76f58df141437f74a1c57714',1,'argcv::io']]], ['kseekstart_150',['kSeekStart',['../namespaceargcv_1_1io.html#aef6b4f1f0b858341e7ba9c8ea6774352aab4d9f5c26b67de0689764744993cb8f',1,'argcv::io']]], ['kunauthenticated_151',['kUnauthenticated',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba23148e95df74017eb23b3c2cf99fdfba',1,'argcv::error']]], ['kunavailable_152',['kUnavailable',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba9ba1d153b5262dd6e31448bb7a1a7d48',1,'argcv::error']]], ['kunimplemented_153',['kUnimplemented',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298ba444e80ffbfff2fdddc9b085fbeb3f1b8',1,'argcv::error']]], ['kunknown_154',['kUnknown',['../namespaceargcv_1_1error.html#a6f8b33bed60c971b643c3eac9167298babb275a25dad4133abf748ea6d53ce0dd',1,'argcv::error']]] ];
(function() { "use strict"; var root = this, Chart = root.Chart, helpers = Chart.helpers; Chart.defaults.global.elements.rectangle = { backgroundColor: Chart.defaults.global.defaultColor, borderWidth: 0, borderColor: Chart.defaults.global.defaultColor, }; Chart.elements.Rectangle = Chart.Element.extend({ draw: function() { var ctx = this._chart.ctx; var vm = this._view; var halfWidth = vm.width / 2, leftX = vm.x - halfWidth, rightX = vm.x + halfWidth, top = vm.base - (vm.base - vm.y), halfStroke = vm.borderWidth / 2; // Canvas doesn't allow us to stroke inside the width so we can // adjust the sizes to fit if we're setting a stroke on the line if (vm.borderWidth) { leftX += halfStroke; rightX -= halfStroke; top += halfStroke; } ctx.beginPath(); ctx.fillStyle = vm.backgroundColor; ctx.strokeStyle = vm.borderColor; ctx.lineWidth = vm.borderWidth; // It'd be nice to keep this class totally generic to any rectangle // and simply specify which border to miss out. ctx.moveTo(leftX, vm.base); ctx.lineTo(leftX, top); ctx.lineTo(rightX, top); ctx.lineTo(rightX, vm.base); ctx.fill(); if (vm.borderWidth) { ctx.stroke(); } }, height: function() { var vm = this._view; return vm.base - vm.y; }, inRange: function(mouseX, mouseY) { var vm = this._view; var inRange = false; if (vm) { if (vm.y < vm.base) { inRange = (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.y && mouseY <= vm.base); } else { inRange = (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.base && mouseY <= vm.y); } } return inRange; }, inLabelRange: function(mouseX) { var vm = this._view; if (vm) { return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2); } else { return false; } }, tooltipPosition: function() { var vm = this._view; return { x: vm.x, y: vm.y }; }, }); }).call(window);
var today = new Date; var current_year = today.getFullYear(); var current_month = today.getMonth(); function countPeriod(m_start, y_start, m_end, y_end) { var months = 12*(y_end - y_start) + m_end - m_start; var month_num = months % 12; var year_num = Math.floor(months/12); return [year_num, month_num]; } function isPlural(num) { if (num>1) return 's'; else return ''; } function showPeriod(m_start, y_start, m_end, y_end) { var period = countPeriod(m_start, y_start, m_end, y_end); if (period[0]==0) { return period[1]+" month"+isPlural(period[1]); } else if (period[1]==0) { return period[0]+" year"+isPlural(period[0]); } else { return period[0]+" year"+isPlural(period[0])+ " "+ period[1]+" month"+isPlural(period[1]); } } function setText(id_name, text) { var node = document.getElementById(id_name); node.innerText = text; } setText("current_year", new Date().getFullYear()); setText("last_period", showPeriod(3,2013, new Date().getMonth(), new Date().getFullYear())); setText("total_period", showPeriod(8, 2011, new Date().getMonth(), new Date().getFullYear()));
context ('Show Character', function () { beforeEach (() => { cy.open (); cy.loadTestAssets (); }); it ('Displays the character correctly', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y happy with fadeIn', 'y Tada!' ] }); cy.start (); cy.get ('[data-sprite="happy"]').should ('be.visible'); cy.get ('[data-sprite="happy"]').should('have.class', 'fadeIn'); }); it ('Displays the character in the right position', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y happy at center', 'y Tada!' ] }); cy.start (); cy.get ('[data-sprite="happy"]').should ('be.visible'); }); it ('Adds the center position by default if none was provided', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y happy', 'y Tada!' ] }); cy.start (); cy.get ('[data-sprite="happy"]').should ('have.class', 'center'); cy.get ('[data-sprite="happy"]').should ('have.data', 'position', 'center'); }); it ('Sets the data position property correctly when one is provided', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y happy at left', 'y Tada!' ] }); cy.start (); cy.get ('[data-sprite="happy"]').should ('have.class', 'left'); cy.get ('[data-sprite="happy"]').should ('have.data', 'position', 'left'); }); // it ('Reuses the data position property as the position for a sprite if none is provided in a later statement', function () { // this.monogatari.setting ('TypeAnimation', false); // this.monogatari.script ({ // 'Start': [ // 'show character y happy at left', // 'One', // 'show character y angry with fadeIn', // 'Two' // ] // }); // cy.start (); // cy.get ('[data-sprite="happy"]').should ('have.class', 'left'); // cy.get ('[data-sprite="happy"]').should ('have.data', 'position', 'left'); // cy.proceed (); // cy.get ('[data-sprite="angry"]').should ('have.class', 'left'); // cy.get ('[data-sprite="angry"]').should ('have.data', 'position', 'left'); // }); it ('Resets the position if none is provided in a later statement', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y happy at left', 'One', 'show character y angry with fadeIn', 'Two' ] }); cy.start (); cy.get ('[data-sprite="happy"]').should ('have.class', 'left'); cy.get ('[data-sprite="happy"]').should ('have.data', 'position', 'left'); cy.proceed (); cy.get ('[data-sprite="angry"]').should ('have.class', 'center'); cy.get ('[data-sprite="angry"][data-position="center"]').should ('exist'); }); it ('Clears the previous classes from the image correctly', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y happy with fadeIn', 'y Tada!', 'show character y happy with rollInLeft', ] }); cy.start (); cy.get ('[data-sprite="happy"]').should ('be.visible'); cy.get ('[data-sprite="happy"]').should('have.class', 'fadeIn'); cy.proceed(); cy.get ('[data-sprite="happy"]').should ('be.visible'); cy.get ('[data-sprite="happy"]').should('not.have.class', 'fadeIn'); cy.get ('[data-sprite="happy"]').should('have.class', 'rollInLeft'); }); it ('Engages the end-animation once the main one is over.', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y normal at center with fadeIn end-fadeOut', 'y Tada!', 'show character y happy at center with fadeIn end-fadeOut', 'wait 5000', //'show character y happy with rollInLeft', ] }); cy.start (); cy.get ('[data-sprite="happy"]').should ('not.be.visible'); }); it ('Rollbacks to the right sprite', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show image polaroid', 'y One', 'show character y normal at left', 'm Two', 'show character y angry at left with fadeIn', 'hide image polaroid', 'show image christmas.png center with fadeIn', 'm Three', 'y Four', 'hide image christmas.png with fadeOut', 'y Five', 'play music theme with fade 5', 'y Six', 'show character y normal at left with fadeIn', 'm Seven', 'Eight' ] }); cy.start (); // Going forward cy.get ('[data-image="polaroid"]').should ('be.visible'); cy.get ('text-box').contains ('One'); cy.proceed (); cy.get ('[data-sprite="normal"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y normal at left']); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left']); cy.proceed (); cy.get ('[data-sprite="angry"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y angry at left with fadeIn']); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character y angry at left with fadeIn']); cy.get ('[data-image="polaroid"]').should ('not.be.visible'); cy.get ('[data-image="christmas.png"]').should ('be.visible'); cy.get ('text-box').contains ('Three'); cy.proceed (); cy.get ('text-box').contains ('Four'); cy.proceed (); cy.get ('[data-image="christmas.png"]').should ('not.be.visible'); cy.get ('text-box').contains ('Five'); cy.proceed (); cy.get ('text-box').contains ('Six'); cy.proceed (); cy.get ('[data-sprite="normal"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y normal at left with fadeIn']); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character y angry at left with fadeIn', 'show character y normal at left with fadeIn']); cy.get ('[data-sprite="angry"]').should ('not.exist'); cy.get ('text-box').contains ('Seven'); cy.proceed (); cy.get ('text-box').contains ('Eight'); // Going backward cy.rollback (); cy.get ('text-box').contains ('Seven'); cy.rollback (); cy.get ('[data-sprite="angry"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y angry at left with fadeIn']); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character y angry at left with fadeIn']); cy.get ('[data-sprite="normal"]').should ('not.be.visible'); cy.get ('text-box').contains ('Six'); cy.rollback (); cy.get ('text-box').contains ('Five'); cy.rollback (); cy.get ('[data-image="christmas.png"]').should ('be.visible'); cy.get ('text-box').contains ('Four'); cy.rollback (); cy.get ('text-box').contains ('Three'); cy.rollback (); cy.get ('[data-sprite="angry"]').should ('not.be.visible'); cy.get ('[data-sprite="normal"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y normal at left']); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left']); cy.get ('[data-image="polaroid"]').should ('be.visible'); cy.get ('[data-image="christmas.png"]').should ('not.be.visible'); cy.get ('text-box').contains ('Two'); cy.rollback (); cy.get ('[data-sprite="normal"]').should ('not.be.visible'); cy.get ('text-box').contains ('One'); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('be.empty'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('be.empty'); }); it ('Updates the sprite corectly on consecutive show statements', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y happy with fadeIn', 'show character y angry with fadeIn', 'y Tada!' ] }); cy.start (); cy.get ('[data-sprite="happy"]').should ('not.be.visible'); cy.get ('[data-sprite="angry"]').should ('be.visible'); cy.get ('[data-sprite="angry"]').should('have.class', 'fadeIn'); }); it ('Doesn\'t duplicate sprites on consecutive end animations', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y normal at left with end-fadeOut', 'y Tada!', 'show character y happy at left with fadeIn end-fadeOut', 'y Tada!', //'show character y happy with rollInLeft', ] }); cy.start (); cy.get ('[data-sprite="normal"]').should ('be.visible'); cy.proceed(); cy.get ('[data-sprite="normal"]').should ('not.be.visible'); cy.get ('[data-sprite="happy"]').should ('be.visible'); }); it ('Displays and rolls back to the right sprite when multiple are present', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y normal at left', 'show character m normal at right', 'y One', 'show character m angry at right', 'm Two', 'show character y angry at left', 'y Three' ] }); cy.start (); // Going forward cy.get ('[data-character="y"][data-sprite="normal"]').should ('be.visible'); cy.get ('[data-character="m"][data-sprite="normal"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character m normal at right']); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y normal at left', 'show character m normal at right']); cy.get ('text-box').contains ('One'); cy.proceed (); cy.get ('[data-character="y"][data-sprite="normal"]').should ('be.visible'); cy.get ('[data-character="m"][data-sprite="angry"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character m normal at right', 'show character m angry at right']); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y normal at left', 'show character m angry at right']); cy.get ('text-box').contains ('Two'); cy.proceed (); cy.get ('[data-character="y"][data-sprite="angry"]').should ('be.visible'); cy.get ('[data-character="m"][data-sprite="angry"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character m normal at right', 'show character m angry at right', 'show character y angry at left']); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character m angry at right', 'show character y angry at left']); cy.get ('text-box').contains ('Three'); cy.rollback (); cy.get ('[data-character="y"][data-sprite="normal"]').should ('be.visible'); cy.get ('[data-character="m"][data-sprite="angry"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character m normal at right', 'show character m angry at right']); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character m angry at right', 'show character y normal at left']); cy.get ('text-box').contains ('Two'); cy.rollback (); cy.get ('[data-character="y"][data-sprite="normal"]').should ('be.visible'); cy.get ('[data-character="m"][data-sprite="normal"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character m normal at right']); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y normal at left', 'show character m normal at right']); cy.get ('text-box').contains ('One'); }); it ('Restores state after load correctly', function () { this.monogatari.setting ('TypeAnimation', false); this.monogatari.script ({ 'Start': [ 'show character y normal at left', 'show character m normal at right', 'y One', 'end' ] }); cy.start (); // Going forward cy.get ('[data-character="y"][data-sprite="normal"]').should ('be.visible'); cy.get ('[data-character="m"][data-sprite="normal"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character m normal at right']); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y normal at left', 'show character m normal at right']); cy.get ('text-box').contains ('One'); cy.save(1).then(() => { cy.proceed (); cy.get('main-screen').should ('be.visible'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('be.empty'); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('be.empty'); cy.load(1).then(() => { cy.get('main-screen').should ('not.be.visible'); cy.get('game-screen').should ('be.visible'); cy.get ('[data-character="y"][data-sprite="normal"]').should ('be.visible'); cy.get ('[data-character="m"][data-sprite="normal"]').should ('be.visible'); cy.wrap (this.monogatari).invoke ('history', 'character').should ('deep.equal', ['show character y normal at left', 'show character m normal at right']); cy.wrap (this.monogatari).invoke ('state', 'characters').should ('deep.equal', ['show character y normal at left', 'show character m normal at right']); cy.get ('text-box').contains ('One'); }); }); }); });
'use strict' /* eslint-disable no-console */ const multaddr = require('multiaddr') const PeerId = require('peer-id') const Node = require('./libp2p-bundle.js') const { stdinToStream, streamToConsole } = require('./stream') async function run() { // Create a new libp2p node with the given multi-address const idListener = await PeerId.createFromJSON(require('./peer-id-listener')) const nodeListener = new Node({ peerId: idListener, addresses: { listen: ['/ip4/0.0.0.0/tcp/10333'] } }) // Log a message when a remote peer connects to us nodeListener.connectionManager.on('peer:connect', (connection) => { console.log('connected to: ', connection.remotePeer.toB58String()) }) // Handle messages for the protocol await nodeListener.handle('/chat/1.0.0', async ({ stream }) => { // Send stdin to the stream stdinToStream(stream) // Read the stream and output to console streamToConsole(stream) }) // Start listening await nodeListener.start() // Output listen addresses to the console console.log('Listener ready, listening on:') nodeListener.multiaddrs.forEach((ma) => { console.log(ma.toString() + '/p2p/' + idListener.toB58String()) }) } run()
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // 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. export default `\ #version 300 es #define SHADER_NAME wboit-layer-fragment-shader precision highp float; in vec4 vColor; in float isValid; layout(location=0) out vec4 accumColor; layout(location=1) out float accumAlpha; float weight1(float z, float a) { return a; } float weight2(float z, float a) { return clamp(pow(min(1.0, a * 10.0) + 0.01, 3.0) * 1e8 * pow(1.0 - z * 0.9, 3.0), 1e-2, 3e3); } float weight3(float z, float a) { return a * (1.0 - z * 0.9) * 10.0; } void main(void) { if (isValid < 0.5) { discard; } vec4 color = vColor; DECKGL_FILTER_COLOR(color, geometry); color.rgb *= color.a; float w = weight3(gl_FragCoord.z, color.a); accumColor = vec4(color.rgb * w, color.a); accumAlpha = color.a * w; } `;
// All symbols in the `Braille` script as per Unicode v4.0.1: [ '\u2800', '\u2801', '\u2802', '\u2803', '\u2804', '\u2805', '\u2806', '\u2807', '\u2808', '\u2809', '\u280A', '\u280B', '\u280C', '\u280D', '\u280E', '\u280F', '\u2810', '\u2811', '\u2812', '\u2813', '\u2814', '\u2815', '\u2816', '\u2817', '\u2818', '\u2819', '\u281A', '\u281B', '\u281C', '\u281D', '\u281E', '\u281F', '\u2820', '\u2821', '\u2822', '\u2823', '\u2824', '\u2825', '\u2826', '\u2827', '\u2828', '\u2829', '\u282A', '\u282B', '\u282C', '\u282D', '\u282E', '\u282F', '\u2830', '\u2831', '\u2832', '\u2833', '\u2834', '\u2835', '\u2836', '\u2837', '\u2838', '\u2839', '\u283A', '\u283B', '\u283C', '\u283D', '\u283E', '\u283F', '\u2840', '\u2841', '\u2842', '\u2843', '\u2844', '\u2845', '\u2846', '\u2847', '\u2848', '\u2849', '\u284A', '\u284B', '\u284C', '\u284D', '\u284E', '\u284F', '\u2850', '\u2851', '\u2852', '\u2853', '\u2854', '\u2855', '\u2856', '\u2857', '\u2858', '\u2859', '\u285A', '\u285B', '\u285C', '\u285D', '\u285E', '\u285F', '\u2860', '\u2861', '\u2862', '\u2863', '\u2864', '\u2865', '\u2866', '\u2867', '\u2868', '\u2869', '\u286A', '\u286B', '\u286C', '\u286D', '\u286E', '\u286F', '\u2870', '\u2871', '\u2872', '\u2873', '\u2874', '\u2875', '\u2876', '\u2877', '\u2878', '\u2879', '\u287A', '\u287B', '\u287C', '\u287D', '\u287E', '\u287F', '\u2880', '\u2881', '\u2882', '\u2883', '\u2884', '\u2885', '\u2886', '\u2887', '\u2888', '\u2889', '\u288A', '\u288B', '\u288C', '\u288D', '\u288E', '\u288F', '\u2890', '\u2891', '\u2892', '\u2893', '\u2894', '\u2895', '\u2896', '\u2897', '\u2898', '\u2899', '\u289A', '\u289B', '\u289C', '\u289D', '\u289E', '\u289F', '\u28A0', '\u28A1', '\u28A2', '\u28A3', '\u28A4', '\u28A5', '\u28A6', '\u28A7', '\u28A8', '\u28A9', '\u28AA', '\u28AB', '\u28AC', '\u28AD', '\u28AE', '\u28AF', '\u28B0', '\u28B1', '\u28B2', '\u28B3', '\u28B4', '\u28B5', '\u28B6', '\u28B7', '\u28B8', '\u28B9', '\u28BA', '\u28BB', '\u28BC', '\u28BD', '\u28BE', '\u28BF', '\u28C0', '\u28C1', '\u28C2', '\u28C3', '\u28C4', '\u28C5', '\u28C6', '\u28C7', '\u28C8', '\u28C9', '\u28CA', '\u28CB', '\u28CC', '\u28CD', '\u28CE', '\u28CF', '\u28D0', '\u28D1', '\u28D2', '\u28D3', '\u28D4', '\u28D5', '\u28D6', '\u28D7', '\u28D8', '\u28D9', '\u28DA', '\u28DB', '\u28DC', '\u28DD', '\u28DE', '\u28DF', '\u28E0', '\u28E1', '\u28E2', '\u28E3', '\u28E4', '\u28E5', '\u28E6', '\u28E7', '\u28E8', '\u28E9', '\u28EA', '\u28EB', '\u28EC', '\u28ED', '\u28EE', '\u28EF', '\u28F0', '\u28F1', '\u28F2', '\u28F3', '\u28F4', '\u28F5', '\u28F6', '\u28F7', '\u28F8', '\u28F9', '\u28FA', '\u28FB', '\u28FC', '\u28FD', '\u28FE', '\u28FF' ];
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. var _ = require('lodash'); var dsl = require('./ringpop-assert'); var events = require('./events'); var getClusterSizes = require('./it-tests').getClusterSizes; var prepareCluster = require('./test-util').prepareCluster; var prepareWithStatus = require('./test-util').prepareWithStatus; var test2 = require('./test-util').test2; test2('ringpop should accept labels that are present in the bootstrap list', getClusterSizes(2), 20000, function init(t, tc, callback) { // insert labels into the node before the sut is bootstrapped tc.fakeNodes[0].labels = { "hello": "world" }; callback(); }, prepareCluster(function(t, tc, n) { return [ dsl.assertStats(t, tc, n+1, 0, 0, { 0: { labels: { "hello": "world" } } }), ];}) ); test2('ringpop should accept labels for a node with a higher incarnation number from the node itself', getClusterSizes(2), 20000, prepareCluster(function(t, tc, n) { return [ // feed the sut with label information for nodeIx 0 dsl.changeStatus(t, tc, 0, 0, { subjectIncNoDelta: +1, status: 'alive', labels: { "hello": "world" }, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // assert that nodeIx 0 has its labels set on the sut dsl.assertStats(t, tc, n+1, 0, 0, { 0: { labels: { "hello": "world" } } }), ];}) ); test2('ringpop should accept labels for a node with a higher incarnation number from another node', getClusterSizes(2), 20000, prepareCluster(function(t, tc, n) { return [ // feed the sut with label information for nodeIx 0 dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: +1, status: 'alive', labels: { "hello": "world" }, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // assert that nodeIx 0 has its labels set on the sut dsl.assertStats(t, tc, n+1, 0, 0, { 1: { labels: { "hello": "world" } } }), ];}) ); test2('ringpop should not accept labels for a node with a lower incarnation number', getClusterSizes(2), 20000, prepareCluster(function(t, tc, n) { return [ // feed the sut with label information for nodeIx 0 dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: -1, status: 'alive', labels: { "hello": "world" }, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // assert that nodeIx 0 has its labels set on the sut dsl.assertStats(t, tc, n+1, 0, 0, { 1: { labels: undefined } }), ];}) ); // The most likely assert to fail will be the last assert in this test where the // winning labels are compared to the labels that were chosen after the first // round of label gossipping test2('ringpop should deterministically pick labels on conflict', getClusterSizes(2), 20000, prepareCluster(function(t, tc, n) { // keep track of the labels that won the first time around var winningLabels = {}; // two pairs of labels var labels1 = { "hello": "world" }; var labels2 = { "hello": "goodbye" }; return [ // send the sut the first pair of labels on inc+1, these will always // be accepted because the incarnation number is higher dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: +1, status: 'alive', labels: labels1, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // make sure these labels are accepted dsl.assertMembership(t, tc, { 1: { labels: labels1 } }), // send the sut the second pair of labels on the same inc # as before // these might or might not be accepted depending on the rules to be // determined for deterministically picking 1 pair of labels dsl.changeStatus(t, tc, 0, 1, { // this time it should not increment the incarnation number as // it needs to be gossiped with the same version to see which of // the two states wins. subjectIncNoDelta: 0, status: 'alive', labels: labels2, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // use a function to get a reference back to the member status // returned for the node and store the labels that were chosen as // the winning labels dsl.assertMembership(t, tc, { 1: function storeWinningLabels(memberStatus) { // copy the winning labels into the placeholder object since // it needs to be passed to the validator function below on // test construction time. _.extend(winningLabels, memberStatus.labels); // to prevent the assertion happening in assert membership // we return true to indicate the 'test' passed. return true; } }), // ================ // MID WAY // ================ // now that we have established which pair was chosen in the first // round we are going to do the same on a higher incarnation number // in the other order. // first send the second pair dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: +1, status: 'alive', labels: labels2, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // make sure these labels are accepted dsl.assertMembership(t, tc, { 1: { labels: labels2 } }), // sending the first pair dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: 0, status: 'alive', labels: labels1, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // validate that the second iteration picked the same winning labels // as the first iteration to ensure convergence when there are // conflicting labels being gossipped around. dsl.assertMembership(t, tc, { 1: { labels: winningLabels } }), ]; }) ); test2('different labels should be accepted on a higher incarnation number', getClusterSizes(2), 20000, prepareCluster(function(t, tc, n) { // two pairs of labels var labels1 = { "hello": "world" }; var labels2 = { "hello": "goodbye" }; return [ // feed the sut with the first pair of labels dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: +1, status: 'alive', labels: labels1, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // assert that the first pair is accepted dsl.assertMembership(t, tc, { 1: { labels: labels1 } }), // feed the sut with the second pair of labels dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: +2, status: 'alive', labels: labels2, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // assert that the second pair is accepted dsl.assertMembership(t, tc, { 1: { labels: labels2 } }), ]; }) ); test2('ringpop doesn\'t reincarnate if it hears the wrong labels that are not preferred', getClusterSizes(2), 20000, prepareCluster(function(t, tc, n) { return [ // do not disable node dsl.sendPing(t, tc, 0, { sourceIx: 0, subjectIx: 'sut', status: 'alive', // the hash for these labels is -1017766696 which is lower than 0 // since it will not be preferred ringpop will ignore the gossip labels: { "hello": "world", "foo": "baz" } }), dsl.waitForPingResponse(t, tc, 0, 1, true), // check if piggyback update has no effect on incarnation number dsl.assertStats(t, tc, n+1, 0, 0), ];}) ); test2('ringpop reincarnates if it hears the wrong labels', getClusterSizes(2), 20000, prepareCluster(function(t, tc, n) { return [ // do not disable node dsl.sendPing(t, tc, 0, { sourceIx: 0, subjectIx: 'sut', status: 'alive', // the hash for these labels is 1613250528 which is higher than 0 // this causes the node to prefere this set of labels over his own, // which will trigger a reincarnation. labels: { "hello": "world" } }), dsl.waitForPingResponse(t, tc, 0, 1, true), // validate that the piggybacked ping cause the incarnation number to // have increased. dsl.assertBumpedIncarnationNumber(t, tc), dsl.assertStats(t, tc, n+1, 0, 0), ];}) ); // begin with alive node testLabelOverrideOnStatusChange('alive', 'suspect'); testLabelOverrideOnStatusChange('alive', 'faulty'); testLabelOverrideOnStatusChange('alive', 'leave'); testLabelOverrideOnStatusChange('alive', 'tombstone'); // begin with suspect node testLabelOverrideOnStatusChange('suspect', 'faulty'); testLabelOverrideOnStatusChange('suspect', 'leave'); testLabelOverrideOnStatusChange('suspect', 'tombstone'); // begin with faulty node testLabelOverrideOnStatusChange('faulty', 'leave'); testLabelOverrideOnStatusChange('faulty', 'tombstone'); // begin with leave node testLabelOverrideOnStatusChange('leave', 'tombstone'); // since nodes might miss updates on changes they should always accept labels if // the status updates, even if these labels differ from the labels that were // previously known to the node. function testLabelOverrideOnStatusChange(firstStatus, secondStatus) { test2('different labels should be accepted on a state override from ' + firstStatus + ' to ' + secondStatus , getClusterSizes(2), 20000, prepareCluster(function(t, tc, n) { // two pairs of labels var labels1 = { "hello": "world" }; var labels2 = { "hello": "goodbye" }; return [ // feed the sut with the first pair of labels dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: +1, status: firstStatus, labels: labels1, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // assert that the first pair is accepted dsl.assertMembership(t, tc, { 1: { labels: labels1 } }), // feed the sut with the second pair of labels dsl.changeStatus(t, tc, 0, 1, { subjectIncNoDelta: +1, status: secondStatus, labels: labels2, }), dsl.waitForPingResponse(t, tc, 0, 0, true), // assert that the second pair is accepted dsl.assertMembership(t, tc, { 1: { labels: labels2 } }), ]; }) ); };
'use strict'; var memo = function() { // load requirements var _sqlite = require('sqlite3').verbose(), _coordinate = require('./coordinate'); var _db = null; var _env = null; var _init = function(env) { _env = env; if (!_db) { _db = new _sqlite.Database(_env.dbFile); } }; var _del = function() { if (_db) { _db.close(); } }; var _now = function() { return new Date().toISOString(); }; var _escape = function(str) { return str.replace('/', '//') .replace("'", "''") .replace('[', '/[') .replace(']', '/]') .replace('%', '/%') .replace('&', '/&') .replace('_', '/_') .replace('(', '/(') .replace(')', '/)'); }; var _getCoordinate = function(callback) { return _coordinate.Get(function(err, data) { if (err) { // ignore } return callback(null, data); }); }; var _getAll = function(callback) { return _db.all( 'SELECT * FROM `memos` WHERE ' + "`status` != 'DELETED' " + 'ORDER BY `last_hit` DESC', callback ); }; var _touchById = function(id, callback) { return _db.run( 'UPDATE `memos` SET ' + "`status` = 'NORMAL', " + "`last_hit` = ?, " + '`hits` = `hits` + 1 WHERE' + '`id` = ?', [_now(), id], callback ); }; var _searchByKeyword = function(keyword, callback) { if (keyword) { return _db.all( 'SELECT * FROM `memos` WHERE ' + "`memo` LIKE '%" + _escape(keyword) + "%' AND " + "`status` != 'DELETED' " + 'ORDER BY `last_hit` DESC', callback ); } else { return _getAll(callback); } }; var _matchAll = function(memo, callback) { return _db.all( 'SELECT * FROM `memos` WHERE `memo` = ?', memo, callback ); }; var _getById = function(id, callback) { return _db.get( 'SELECT * FROM `memos` WHERE `id` = ?', id, function(err, data) { if (err) { return callback(err); } return _touchById(id, function(tErr, tData) { callback(tErr, data); }) } ); }; var _delById = function(id, callback) { return _db.run( 'UPDATE `memos` SET ' + "`status` = 'DELETED', " + "`deleted_at` = ? WHERE " + '`id` = ? AND ' + "`status` != 'DELETED'", [_now(), id], function(err, data) { if (err) { return callback(err); } if (!this.changes) { return callback('Memo not found'); } return callback(err, data); } ); }; var _add = function(memo, callback) { return _getCoordinate(function(err, coordinate) { if (err) { return callback(err); } return _db.run( 'INSERT INTO `memos` ' + '(`memo` , `created_at`, `updated_at`, `deleted_at`,' + ' `status`, `last_hit` , `hits` , `coordinate`) ' + 'VALUES ' + "(?, ?, ?, ?, 'NORMAL', ?, 1, ?)", [memo, _now(), _now(), _now(), _now(), coordinate], function(err) { if (err) { return callback(err); } return _getById(this.lastID, callback); } ); }); }; var _touch = function(memo, callback) { return _matchAll(memo, function(err, data) { if (err) { return callback(err); } if (data.length) { return _touchById(data[0].id, function(tErr, tData) { callback(tErr, data[0]); }); } else { return _add(memo, callback); } }); }; var _getTrash = function(callback) { return _db.all( 'SELECT * FROM `memos` ' + "WHERE `status` = 'DELETED' " + 'ORDER BY `deleted_at` DESC', callback ); }; var _emptyTrash = function(callback) { return _db.run( "DELETE FROM `memos` WHERE `status` = 'DELETED'", function(err, data) { if (err) { return callback(err); } if (!this.changes) { return callback('Trash is empty'); } return callback(err, data); } ); }; return { Init : _init, Del : _del, GetAll : _getAll, Search : _searchByKeyword, GetById : _getById, DelById : _delById, Add : _add, Touch : _touch, GetTrash : _getTrash, EmptyTrash : _emptyTrash }; }(); module.exports = memo;
var CNC = require("./CNC"); var arcToBezier = require("svg-arc-to-cubic-bezier").default; // is used var parseSVG = require('svg-path-parser'); module.exports = function convert(argv, path, creasepath){ function doStuff(svg){ var wd = svg.split("\n").join(""); var rgx = new RegExp(/\<path.+?\ d="(.+?)"/g); var resp = []; wd.replace(rgx, function(){ resp.push(arguments[1]); return ""; }); //console.log(resp); return resp; } if(path.charAt(0) == "{"){ path = JSON.parse(path); }else{ path = {size:[500, 500], paths: doStuff(path)}; } var cnc = new CNC([argv.e, argv.d, argv.f, argv.p], argv.s * argv.m, path.size[1] / (path.size[0] / argv.s) * argv.n, argv.l == 0 ? -1 : argv.l); if(argv.c)cut(creasepath, true); cut(path); function cut(path, doordontdothings){ cnc.setTool("cut"); cnc.cardboardSize = [argv.e, doordontdothings ? argv.f : argv.d, argv.f, argv.p]; if(doordontdothings){ cnc.setTool("crease"); if(path.charAt(0) == "{"){ path = JSON.parse(path); }else{ path = {size:[argv.w, argv.h], paths: doStuff(path)}; } } cnc.heightOffset = argv.ho - 2; //0 0 1913.3858, 1417.3228 var scalefactor = [path.size[0], path.size[1]]; var highestX = 0; var highestY = 0; path.paths.forEach(function(pathi){ var parsed = parseSVG(pathi); var lnis = 0; var firstx = 0; var firsty = 0; var currentX = 0; var currentY = 0; var prevcurrentx; var prevcurrenty; parsed.forEach(function(thing, i){ //console.log(thing.x/scalefactor[0] + (thing.relative? currentX/scalefactor[0]:0),thing.y/scalefactor[1] + (thing.relative?currentY/scalefactor[1]:0)); switch(thing.command){ case "lineto": //case "elliptical arc": lnis++; if(lnis == 1){ firstx = currentX / scalefactor[0]; firsty = currentY / scalefactor[1]; } cnc.drawLine(currentX / scalefactor[0], currentY / scalefactor[1], thing.x / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0)); break; case "moveto": break; case "elliptical arc": //break; //lnis++; if(lnis == 1){ firstx = currentX / scalefactor[0]; firsty = currentY / scalefactor[1]; } //console.log(thing); //var cX = thing.x + (thing.relative ? currentX : 0); //var cy = thing.y + (thing.relative ? currentY : 0); var curves = arcToBezier( { px: currentX, py: currentY, cx: thing.x, cy: thing.y, rx: thing.rx, ry: thing.ry, xAxisRotation: thing.xAxisRotation, largeArcFlag: thing.largeArc ? 30 : 0, sweepFlag : thing.sweep ? 30 : 0 } ); var rtg = thing.relative; curves.forEach(function(thing){ console.log(thing, [ [ currentX / scalefactor[0], currentY / scalefactor[1] ], [ thing.x1 / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y1 / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0) ], [ thing.x2 / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y2 / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0) ], [ thing.x / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0)] ]); thing.relative = rtg; cnc.drawBezier([ [ currentX / scalefactor[0], currentY / scalefactor[1] ], [ thing.x1 / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y1 / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0) ], [ thing.x2 / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y2 / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0) ], [ thing.x / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0)] ], 0.1); //break; }); break; case "curveto": lnis++; if(lnis == 1){ firstx = currentX / scalefactor[0]; firsty = currentY / scalefactor[1]; } cnc.drawBezier([[currentX / scalefactor[0], currentY / scalefactor[1]], [thing.x1 / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y1 / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0)], [thing.x2 / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y2 / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0)], [thing.x / scalefactor[0] + (thing.relative ? currentX / scalefactor[0] : 0), thing.y / scalefactor[1] + (thing.relative ? currentY / scalefactor[1] : 0)]], 0.1); break; case "closepath": if(parsed[i - 1].command == "lineto" || parsed[i - 1].command == "curveto"){ cnc.drawLine(firstx, firsty, parsed[i - 1].x / scalefactor[0] + (parsed[i - 1].relative ? prevcurrentx / scalefactor[0] : 0), parsed[i - 1].y / scalefactor[1] + (parsed[i - 1].relative ? prevcurrenty / scalefactor[1] : 0)); } break; default: console.log("WARN: Type " + thing.command + " not supported"); } prevcurrentx = currentX; prevcurrenty = currentY; if(thing.x) if(thing.relative) currentX += thing.x; else currentX = thing.x; if(thing.y) if(thing.relative) currentY += thing.y; else currentY = thing.y; if(currentX)highestX = Math.max(currentX, highestX); if(currentY)highestY = Math.max(currentY, highestY); }); }); console.log("required size is:", highestX, highestY); } /*lines.lines.forEach(function(line){ switch (line.type){ case "line": cnc.drawLine(line.x1,line.y1,line.x2,line.y2); break; case "bezier": cnc.drawBezier(line.bezier, line.quality); } });*/ //cnc.drawBezier(); return cnc.generate(); };
// Karma configuration // This is the base spec for running the integration tests, which use the built // distro of Selleckt instead of browserifying everything on the fly 'use strict'; module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha'], // list of files / patterns to load in the browser files: [ 'test/lib/*.js', 'dist/selleckt.js', 'test/specs/*.js' ], client: { mocha: { reporter: 'html', // change Karma's debug.html to the mocha web reporter ui: 'bdd' } }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome', 'Safari', 'Firefox'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };
'use strict'; (function(){ angular.module('juridicaWebApp') .factory('httpRequestInterceptor', function ($rootScope) { return { request: function($config) { $rootScope.materialPreloader = true; if( $rootScope.token ) { $config.headers['Authorization'] = 'UFG ' + $rootScope.token; } return $config; }, 'response': function(response) { $rootScope.materialPreloader = false; return response; }, }; }); }()); var birthday = new Date("8/1/1985"); var today = new Date(); var years = today.getFullYear() - birthday.getFullYear(); // Reset birthday to the current year. birthday.setFullYear(today.getFullYear()); // If the user's birthday has not occurred yet this year, subtract 1. if (today < birthday) { years--; } document.write("You are " + years + " years old.");
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"Pesquisar",searchButtonTitle:"Pesquisar",clearButtonTitle:"limpar pesquisa",placeholder:"Encontrar um endere\u00e7o ou local",searchIn:"Pesquisar em",all:"Todos",allPlaceholder:"Encontrar um endere\u00e7o ou local",emptyValue:"Por favor, introduza um termo de pesquisa.",untitledResult:"Sem t\u00edtulo",untitledSource:"Fonte sem t\u00edtulo",noResults:"Sem resultados",noResultsFound:"N\u00e3o foram encontrados resultados.",noResultsFoundForValue:"N\u00e3o foram encontrados resultados para {value}.", showMoreResults:"Mostrar mais resultados",hideMoreResults:"Ocultar",searchResult:"Pesquisar resultados",moreResultsHeader:"Mais resultados",useCurrentLocation:"Utilizar localiza\u00e7\u00e3o atual"});
/* global angular */ (function () { 'use strict'; angular.module('agreements') .component('scientillaAgreementVerifiedList', { templateUrl: 'partials/scientilla-agreement-verified-list.html', controller, controllerAs: 'vm', bindings: {} }); controller.$inject = [ 'ProjectService', 'EventsService', 'agreementListSections', 'context', 'ModalService', 'agreementDownloadFileName', 'agreementExportUrl' ]; function controller( ProjectService, EventsService, agreementListSections, context, ModalService, agreementDownloadFileName, agreementExportUrl ) { const vm = this; vm.agreementListSections = agreementListSections; vm.agreements = []; vm.onFilter = onFilter; vm.unverify = (agreement) => ProjectService.unverify(vm.researchEntity, agreement); vm.exportDownload = agreements => ProjectService.exportDownload(agreements, 'csv', agreementDownloadFileName, agreementExportUrl); vm.subResearchEntity = context.getSubResearchEntity(); let query = { where: {} }; const agreementPopulates = ['type', 'verified', 'verifiedUsers', 'verifiedGroups', 'group', 'authors', 'affiliations']; /* jshint ignore:start */ vm.$onInit = async function () { vm.researchEntity = await context.getResearchEntity(); EventsService.subscribeAll(vm, [ EventsService.RESEARCH_ITEM_DRAFT_VERIFIED, EventsService.RESEARCH_ITEM_VERIFIED, EventsService.RESEARCH_ITEM_UNVERIFIED, EventsService.PROJECT_GROUP_CREATED ], updateList); }; /* jshint ignore:end */ vm.$onDestroy = function () { EventsService.unsubscribeAll(vm); }; vm.generateGroup = function (agreement) { ModalService.openGenerateAgreementGroup(agreement); }; function updateList() { return onFilter(query); } /* jshint ignore:start */ async function onFilter(q) { q.where.type = 'project_agreement' vm.agreements = await ProjectService.get(vm.researchEntity, q, false, agreementPopulates); } /* jshint ignore:end */ } })();
/*global define,jasmine,angular,describe,it,expect*/ define(function (require) { 'use strict'; var Field = require('ng-admin/Main/component/service/config/Field'), ListView = require('ng-admin/Main/component/service/config/view/ListView'), DashboardView = require('ng-admin/Main/component/service/config/view/DashboardView'), Entity = require('ng-admin/Main/component/service/config/Entity'); describe("Service: Field config", function () { describe('label', function() { it('should return the camelCased name by default', function () { expect(new Field('myField').label()).toEqual('MyField'); expect(new Field('my_field_1').label()).toEqual('My Field 1'); expect(new Field('my-field-2').label()).toEqual('My Field 2'); expect(new Field('my_field-3').label()).toEqual('My Field 3'); }); it('should allow to set a custom label', function () { var field = new Field('myField').label('foobar'); expect(field.label()).toEqual('foobar'); }); }); describe('type', function () { it('should set type string.', function () { var field = new Field(); field.type('string'); expect(field.type()).toBe('string'); }); it('should have a name even when not set.', function () { var field = new Field(); expect(field.name()).not.toBe(null); }); it('should accept string for template value.', function () { var field = new Field('myField') .type('template') .template('hello!'); expect(field.getTemplateValue()).toEqual('hello!'); }); it('should accept function for template value.', function () { var field = new Field('myField') .type('template') .template(function () { return 'hello function !'; }); expect(field.getTemplateValue()).toEqual('hello function !'); }); it('should not allows type other type.', function () { var field = new Field(); expect(function () { field.type('myType'); }) .toThrow('Type should be one of : "number", "string", "text", "wysiwyg", "email", "date", "boolean", "choice", "choices", "password", "template" but "myType" was given.'); }); }); describe('validation', function() { it('should have sensible defaults', function() { expect(new Field().validation()).toEqual({required: false, minlength : 0, maxlength : 99999}); }); it('should allow to override parts of the validation settings', function() { var field = new Field().validation({ required: true }); expect(field.validation()).toEqual({required: true, minlength : 0, maxlength : 99999}); }); it('should allow to remove parts of the validation settings', function() { var field = new Field().validation({ minlength: null }); expect(field.validation()).toEqual({required: false, maxlength : 99999}); }); }); describe('entity', function () { it('should set view.', function () { var field = new Field('field1'), view = new ListView('list1'); view.setEntity(new Entity('myEntity1')); expect(view.name() + '.' + field.name()).toBe('list1.field1'); }); }); describe('config', function () { it('should call getMappedValue.', function () { function truncate(val) { return 'v' + val; } var field = new Field('field1'); field.map(truncate); expect(field.getMappedValue(123)).toBe('v123'); }); }); }); });
// All symbols in the `Nl` category as per Unicode v7.0.0: [ '\u16EE', '\u16EF', '\u16F0', '\u2160', '\u2161', '\u2162', '\u2163', '\u2164', '\u2165', '\u2166', '\u2167', '\u2168', '\u2169', '\u216A', '\u216B', '\u216C', '\u216D', '\u216E', '\u216F', '\u2170', '\u2171', '\u2172', '\u2173', '\u2174', '\u2175', '\u2176', '\u2177', '\u2178', '\u2179', '\u217A', '\u217B', '\u217C', '\u217D', '\u217E', '\u217F', '\u2180', '\u2181', '\u2182', '\u2185', '\u2186', '\u2187', '\u2188', '\u3007', '\u3021', '\u3022', '\u3023', '\u3024', '\u3025', '\u3026', '\u3027', '\u3028', '\u3029', '\u3038', '\u3039', '\u303A', '\uA6E6', '\uA6E7', '\uA6E8', '\uA6E9', '\uA6EA', '\uA6EB', '\uA6EC', '\uA6ED', '\uA6EE', '\uA6EF', '\uD800\uDD40', '\uD800\uDD41', '\uD800\uDD42', '\uD800\uDD43', '\uD800\uDD44', '\uD800\uDD45', '\uD800\uDD46', '\uD800\uDD47', '\uD800\uDD48', '\uD800\uDD49', '\uD800\uDD4A', '\uD800\uDD4B', '\uD800\uDD4C', '\uD800\uDD4D', '\uD800\uDD4E', '\uD800\uDD4F', '\uD800\uDD50', '\uD800\uDD51', '\uD800\uDD52', '\uD800\uDD53', '\uD800\uDD54', '\uD800\uDD55', '\uD800\uDD56', '\uD800\uDD57', '\uD800\uDD58', '\uD800\uDD59', '\uD800\uDD5A', '\uD800\uDD5B', '\uD800\uDD5C', '\uD800\uDD5D', '\uD800\uDD5E', '\uD800\uDD5F', '\uD800\uDD60', '\uD800\uDD61', '\uD800\uDD62', '\uD800\uDD63', '\uD800\uDD64', '\uD800\uDD65', '\uD800\uDD66', '\uD800\uDD67', '\uD800\uDD68', '\uD800\uDD69', '\uD800\uDD6A', '\uD800\uDD6B', '\uD800\uDD6C', '\uD800\uDD6D', '\uD800\uDD6E', '\uD800\uDD6F', '\uD800\uDD70', '\uD800\uDD71', '\uD800\uDD72', '\uD800\uDD73', '\uD800\uDD74', '\uD800\uDF41', '\uD800\uDF4A', '\uD800\uDFD1', '\uD800\uDFD2', '\uD800\uDFD3', '\uD800\uDFD4', '\uD800\uDFD5', '\uD809\uDC00', '\uD809\uDC01', '\uD809\uDC02', '\uD809\uDC03', '\uD809\uDC04', '\uD809\uDC05', '\uD809\uDC06', '\uD809\uDC07', '\uD809\uDC08', '\uD809\uDC09', '\uD809\uDC0A', '\uD809\uDC0B', '\uD809\uDC0C', '\uD809\uDC0D', '\uD809\uDC0E', '\uD809\uDC0F', '\uD809\uDC10', '\uD809\uDC11', '\uD809\uDC12', '\uD809\uDC13', '\uD809\uDC14', '\uD809\uDC15', '\uD809\uDC16', '\uD809\uDC17', '\uD809\uDC18', '\uD809\uDC19', '\uD809\uDC1A', '\uD809\uDC1B', '\uD809\uDC1C', '\uD809\uDC1D', '\uD809\uDC1E', '\uD809\uDC1F', '\uD809\uDC20', '\uD809\uDC21', '\uD809\uDC22', '\uD809\uDC23', '\uD809\uDC24', '\uD809\uDC25', '\uD809\uDC26', '\uD809\uDC27', '\uD809\uDC28', '\uD809\uDC29', '\uD809\uDC2A', '\uD809\uDC2B', '\uD809\uDC2C', '\uD809\uDC2D', '\uD809\uDC2E', '\uD809\uDC2F', '\uD809\uDC30', '\uD809\uDC31', '\uD809\uDC32', '\uD809\uDC33', '\uD809\uDC34', '\uD809\uDC35', '\uD809\uDC36', '\uD809\uDC37', '\uD809\uDC38', '\uD809\uDC39', '\uD809\uDC3A', '\uD809\uDC3B', '\uD809\uDC3C', '\uD809\uDC3D', '\uD809\uDC3E', '\uD809\uDC3F', '\uD809\uDC40', '\uD809\uDC41', '\uD809\uDC42', '\uD809\uDC43', '\uD809\uDC44', '\uD809\uDC45', '\uD809\uDC46', '\uD809\uDC47', '\uD809\uDC48', '\uD809\uDC49', '\uD809\uDC4A', '\uD809\uDC4B', '\uD809\uDC4C', '\uD809\uDC4D', '\uD809\uDC4E', '\uD809\uDC4F', '\uD809\uDC50', '\uD809\uDC51', '\uD809\uDC52', '\uD809\uDC53', '\uD809\uDC54', '\uD809\uDC55', '\uD809\uDC56', '\uD809\uDC57', '\uD809\uDC58', '\uD809\uDC59', '\uD809\uDC5A', '\uD809\uDC5B', '\uD809\uDC5C', '\uD809\uDC5D', '\uD809\uDC5E', '\uD809\uDC5F', '\uD809\uDC60', '\uD809\uDC61', '\uD809\uDC62', '\uD809\uDC63', '\uD809\uDC64', '\uD809\uDC65', '\uD809\uDC66', '\uD809\uDC67', '\uD809\uDC68', '\uD809\uDC69', '\uD809\uDC6A', '\uD809\uDC6B', '\uD809\uDC6C', '\uD809\uDC6D', '\uD809\uDC6E' ];
module.exports = { '/': { to: '/users' }, 'get /users': { to: 'controller#index' }, 'post|put /users/:id?': { to: 'controller#create' }, 'delete /delete': { to: function *() { this.body = 'delete'; }}, 'get /secure': { to: 'controller#secure', constraint: 'constraint#basic' } };
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'clipboard', 'sl', { copy: 'Kopiraj', copyError: 'Varnostne nastavitve brskalnika ne dopuščajo samodejnega kopiranja. Uporabite kombinacijo tipk na tipkovnici (Ctrl/Cmd+C).', cut: 'Izreži', cutError: 'Varnostne nastavitve brskalnika ne dopuščajo samodejnega izrezovanja. Uporabite kombinacijo tipk na tipkovnici (Ctrl/Cmd+X).', paste: 'Prilepi', pasteArea: 'Prilepi območje', pasteMsg: 'Prosimo, prilepite v sleči okvir s pomočjo tipkovnice (<strong>Ctrl/Cmd+V</strong>) in pritisnite V redu.', securityMsg: 'Zaradi varnostnih nastavitev vašega brskalnika urejevalnik ne more neposredno dostopati do odložišča. Vsebino odložišča ponovno prilepite v to okno.', title: 'Prilepi' } );
var gulp = require('gulp'), del = require('del'), vinylPaths = require('vinyl-paths'), $ = require('gulp-load-plugins')(), spritesmith = require('gulp.spritesmith'); var paths = { scripts: ['src/trumbowyg.js'], langs: ['src/langs/**.js', '!src/langs/en.js'], plugins: ['plugins/*/**.js', '!plugins/*/Gulpfile.js'], sprites: { 'icons-white': 'src/ui/images/icons-white/**.png', 'icons-white-2x': 'src/ui/images/icons-white-2x/**.png', 'icons-black': 'src/ui/images/icons-black/**.png', 'icons-black-2x': 'src/ui/images/icons-black-2x/**.png' }, mainStyle: 'src/ui/sass/trumbowyg.scss', styles: { sass: 'src/ui/sass' } }; var pkg = require('./package.json'); var banner = ['/**', ' * <%= pkg.title %> v<%= pkg.version %> - <%= pkg.description %>', ' * <%= description %>', ' * ------------------------', ' * @link <%= pkg.homepage %>', ' * @license <%= pkg.license %>', ' * @author <%= pkg.author.name %>', ' * Twitter : @AlexandreDemode', ' * Website : <%= pkg.author.url.replace("http://", "") %>', ' */', '\n'].join('\n'); var bannerLight = ['/** <%= pkg.title %> v<%= pkg.version %> - <%= pkg.description %>', ' - <%= pkg.homepage.replace("http://", "") %>', ' - License <%= pkg.license %>', ' - Author : <%= pkg.author.name %>', ' / <%= pkg.author.url.replace("http://", "") %>', ' */', '\n'].join(''); gulp.task('clean', function(){ return gulp.src(['dist/*', 'src/ui/sass/_sprite*.scss']) .pipe(vinylPaths(del)); }); gulp.task('test', ['test-scripts', 'test-langs', 'test-plugins']); gulp.task('test-scripts', function(){ return gulp.src(paths.scripts) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')); }); gulp.task('test-langs', function(){ return gulp.src(paths.langs) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')); }); gulp.task('test-plugins', function(){ return gulp.src(paths.plugins) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')); }); gulp.task('scripts', ['test-scripts'], function(){ return gulp.src(paths.scripts) .pipe($.header(banner, { pkg: pkg, description: 'Trumbowyg core file' })) .pipe($.newer('dist/trumbowyg.js')) .pipe($.concat('trumbowyg.js', { newLine: '\r\n\r\n' })) .pipe(gulp.dest('dist/')) .pipe($.size({ title: 'trumbowyg.js' })) .pipe($.rename({ suffix: '.min' })) .pipe($.uglify()) .pipe($.header(bannerLight, { pkg: pkg })) .pipe(gulp.dest('dist/')) .pipe($.size({ title: 'trumbowyg.min.js' })) }); gulp.task('langs', ['test-langs'], function(){ return gulp.src(paths.langs) .pipe($.rename({ suffix: '.min' })) .pipe($.uglify({ preserveComments: 'all' })) .pipe(gulp.dest('dist/langs/')) }); gulp.task('plugins', ['test-plugins'], function(){ return gulp.src(paths.plugins) .pipe(gulp.dest('dist/plugins/')) .pipe($.rename({ suffix: '.min' })) .pipe($.uglify()) .pipe(gulp.dest('dist/plugins/')) }); gulp.task('sprites', function(){ return makeSprite('white') && makeSprite('white', '-2x') && makeSprite('black') && makeSprite('black', '-2x'); }); function makeSprite(color, resolution){ var suffix = '-' + color + (resolution ? resolution : ''); var sprite = gulp.src(paths.sprites['icons' + suffix]) .pipe(spritesmith({ imgName: 'icons' + suffix + '.png', cssName: '_sprite' + suffix + '.scss', cssTemplate: function(params){ var output = '', e; for(var i in params.items){ e = params.items[i]; output += '$' + e.name + suffix + ': ' + e.px.offset_x + ' ' + e.px.offset_y + ';\n'; } if(params.items.length > 0){ output += '\n\n'; output += '$sprite-height' + suffix + ': ' + params.items[0].px.total_height + ';\n'; output += '$sprite-width' + suffix + ': ' + params.items[0].px.total_width + ';\n'; output += '$icons' + suffix + ': "./images/icons' + suffix + '.png";'; } return output; } })); sprite.img.pipe(gulp.dest('dist/ui/images/')); sprite.css.pipe(gulp.dest(paths.styles.sass)); return sprite.css; } gulp.task('styles', ['sprites'], function(){ return gulp.src(paths.mainStyle) .pipe($.sass({ sass: paths.styles.sass })) .pipe($.autoprefixer(['last 1 version', '> 1%', 'ff >= 20', 'ie >= 8', 'opera >= 12', 'Android >= 2.2'], { cascade: true })) .pipe($.header(banner, { pkg: pkg, description: 'Default stylesheet for Trumbowyg editor' })) .pipe(gulp.dest('dist/ui/')) .pipe($.size({ title: 'trumbowyg.css' })) .pipe($.rename({ suffix: '.min' })) .pipe($.minifyCss()) .pipe($.header(bannerLight, { pkg: pkg })) .pipe(gulp.dest('dist/ui/')) .pipe($.size({ title: 'trumbowyg.min.css' })); }); gulp.task('sass-dist', ['styles'], function(){ return gulp.src('src/ui/sass/**/*.scss') .pipe($.header(banner, { pkg: pkg, description: 'Default stylesheet for Trumbowyg editor' })) .pipe(gulp.dest('dist/ui/sass')) }); gulp.task('watch', function(){ gulp.watch(paths.scripts, ['scripts']); gulp.watch(paths.langs, ['langs']); gulp.watch(paths.plugins, ['plugins']); gulp.watch(paths.mainStyle, ['styles']); gulp.watch(['dist/**', 'dist/*/**'], function(file){ $.livereload.changed(file); }); $.livereload.listen(); }); gulp.task('build', ['scripts', 'langs', 'plugins', 'sass-dist']); gulp.task('default', ['build', 'watch']);
function loadMainContent( pagename ){ //var pagename = pagehash;//pagehash.substring(1, pagehash.length); $( ".container" ).load( pagename , errorResponse); } function loadBeachContent(content){ var src = "/images/" + content; $("#weather").attr("src", src); } function getLocalize(date){ var hours = date.getHours(); var am = "AM"; var minutes = date.getMinutes(); var seconds = date.getSeconds(); if(hours<10){ hours = "0"+hours;}else if (hours>12){hours = hours%12; am="PM";} if(minutes<10){minutes = "0"+minutes;} var formattedTime = hours + ':' + minutes + " " +am; console.log(formattedTime); return formattedTime; } function getRealtime(){ var date = new Date(); var hours = date.getHours(); var am = "AM"; var minutes = date.getMinutes(); var seconds = date.getSeconds(); if(hours<10){ hours = "0"+hours;}else if (hours>12){hours = hours%12; am="PM";} if(minutes<10){minutes = "0"+minutes;} var formattedTime = hours + ':' + minutes + " " +am; return formattedTime; } //ajax error response callback function function errorResponse ( response, status, xhr ) { //parseweather(response); if ( status == "error" ) { var msg = "Sorry but there was an error: "; $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );}};
// import AllImages from '../index'; import expect from 'expect'; // import { shallow } from 'enzyme'; // import React from 'react'; describe('<AllImages />', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(false); }); });
angular .module('app.message') .directive('mumbleMessage', mumbleMessage); mumbleMessage.$inject = []; function mumbleMessage() { var directive = { templateUrl: 'app/message/mumble-message.html', link: link, scope: { message: '=' } }; return directive; function link(scope, element, attrs) { scope.alertClass = function (msgType) { switch (msgType) { case 'info': case 'success': case 'warning': return 'alert-' + msgType; default: return 'alert-danger'; } }; } }
export default function promise() { console.group('Promise'); { console.group('ES-next: Stage-2: Promise.prototype.finally'); { // NOTICE: This code is not supported to babel-plugin-transform-runtime console.warn('This code is not supported to babel-plugin-transform-runtime'); console.warn(` Promise.resolve(2).finally(v => console.log('Promise.resolve(2).finally()', v)); Promise.reject(3).finally(v => console.log('Promise.reject(3).finally()', v)); `); } console.groupEnd(); } console.groupEnd(); }
(function(angular, window) { 'use strict'; /** * Demo modules * @type {Array} */ var modules = [ 'ngx.ui.addressInput', 'ngx.ui.checkboxlist', 'ngx.ui.confirm', 'ngx.ui.dateInput', 'ngx.ui.dialog', 'ngx.ui.geomap', 'ngx.ui.hashtagInput', 'ngx.ui.imageupload', 'ngx.ui.invalid', 'ngx.ui.lightbox', 'ngx.ui.rating', 'ngx.ui.scrollTo', 'ngx.ui.scrollToInvalid', 'ngx.ui.tagsInput', 'ngx.ui.textCurtain', 'ngx.ui.validate', 'ngx.ui.wwwInput', 'ngx.ui.wysiwyg' ]; /** * Initialize application module * @type {*} */ var app = angular.module('ngxDemoApp', ['ngx']); /** * Setup routes */ app.config(function($routeProvider) { angular.forEach(modules, function(name) { $routeProvider.when('/' + name, { templateUrl: 'templates/' + name + '.html', module: name }); }); $routeProvider.otherwise({ redirectTo: '/' + modules[0] }); }); /** * Startup */ app.run(function(ngxDictionary) { ngxDictionary.setLanguage('en'); }); /** * Main controller */ app.controller('ngx', function($scope, $route, $location) { $scope.modules = modules; $scope.$on('$routeChangeSuccess', function(event, route) { $scope.module = route.module; }); $scope.load = function(m) { $location.path('/' + m); }; $scope.getContentClass = function() { return ($scope.module ? $scope.module.replace(/\./g, '-') : ''); }; }); /** * ngx.ui.checkboxlist demo controller */ app.controller('ngx.ui.checkboxlist', function($scope) { $scope.checkboxlist = { items: { 'bb': 'Backbone', 'gc': 'Google Closure', 'jq': 'jQuery', 'ng': 'AngularJS' }, selected: ['ng', 'gc'] }; }); /** * ngx.ui.hashtagInput demo controller */ app.controller('ngx.ui.hashtagInput', function($scope) { $scope.hashtag = '#test'; }); /** * ngx.ui.wwwInput demo controller */ app.controller('ngx.ui.wwwInput', function($scope) { $scope.www = 'lmc.eu'; }); /** * ngx.ui.wysiwyg demo controller */ app.controller('ngx.ui.wysiwyg', function($scope) { $scope.wysiwyg = '<p>lorem ipsum <strong>strong</strong></p>'; }); /** * ngx.ui.tagsInput demo controller */ app.controller('ngx.ui.tagsInput', function($scope) { $scope.tags = ['tag1', 'tag2', 'tag3']; }); /** * ngx.ui.geomap demo controller */ app.controller('ngx.ui.geomap', function($scope) { $scope.coords = { lat: 50.1028650, lon: 14.4568872 }; }); /** * ngx.ui.dialog demo controller */ app.controller('ngx.ui.dialog', function($scope) { $scope.dialog = { input: undefined, submit: function(inputValue, $dialog) { window.alert('submitted ' + (inputValue === undefined ? 'empty' : '"' + inputValue + '"')); $dialog.close(); }, onclose: function() { $scope.dialog.input = undefined; } }; }); /** * ngx.ui.validate demo controller */ app.controller('ngx.ui.validate', function($scope) { $scope.validateEven = function(number) { return (!number || ((number % 2) === 0)); }; $scope.validatePassword = function(cpassword, password) { return (!password && !cpassword) || (password === cpassword); }; $scope.validateFavorites = function(movie, actor, later) { return (later ? true : (movie && actor)); }; }); /** * ngx.ui.rating demo controller */ app.controller('ngx.ui.rating', function($scope) { $scope.ratingLevel = 3; $scope.ratingLevel2 = 2; $scope.ratingLevel3 = 7; $scope.ratingLevel4 = 3; $scope.ratingLevel5 = 3; $scope.ratingLevel6 = 3; $scope.ratingLog = 'ratingLevel6 log:<br>'; $scope.$watch('ratingLevel6', function (level) { $scope.ratingLog += '&bull; level ' + level + ' selected<br>'; }) }); })(window.angular, window);
var alert = new Alert({ 'class': 'alert fade in', content: "<strong>Holy guacamole!</strong> Best check yo self, you're not looking too good.", closable: true }, 'my-alert'); alert.startup(); alert.on('close', function (ev) { console.info('Alert about to be closed'); }); alert.on('closed', function (ev) { console.info('Alert is now closed'); });