code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; var appList = ['./app/index.tsx']; if(process.env.NODE_ENV === 'development') { appList.unshift('webpack/hot/only-dev-server'); } var currentPath = process.cwd(); module.exports = { entry: { app: appList }, output: { path: path.resolve(__dirname, "build"), publicPath: "/", filename: "bundle.js" }, plugins: [new HtmlWebpackPlugin({ template: './app/index.html' })], resolve: { root: [ path.join(currentPath, 'app/assets/stylesheets') ], extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js'] }, module: { loaders: [ { test: /\.tsx?$/, loader: 'ts-loader' }, { test: /\.less$/, loader: 'style!css!less?strictMath' }, { test: /\.css$/, loader: 'style!css' } ] }, devServer: { contentBase: './app', plugins: [ new webpack.HotModuleReplacementPlugin() ] } };
janaagaard75/framework-investigations
old-or-not-typescript/learn-redux/react-redux-counter/webpack.config.js
JavaScript
unlicense
1,059
var GamesList = React.createClass({ getInitialState: function() { return { games: this.props.initialGames }; }, scoreChanged: function(gameId, teamNumber, score) { var game = this.state.games.filter(function(game) { return game.id == gameId; })[0]; game['pool_entry_' + teamNumber + '_score'] = score; this.setState({games:this.state.games}); }, saveGames: function() { $.ajax({ url: 'admin/bracket/score/save', dataType: 'json', data: csrf({games: this.state.games}), cache: false, method: 'post', success: function(data) { // show a spinner instead alert('saved'); }.bind(this), }); }, render: function() { var that = this; var games = this.state.games.map(function(game) { return ( <Game game={game} teams={that.props.teams} rolls={that.props.rolls} key={game.id} scoreChanged={that.scoreChanged}/> ); }); return ( <div> <h2>Round {this.props.round}</h2> {games} <button onClick={this.saveGames}>Save</button> </div> ); } }); var Game = React.createClass({ getInitialState : function() { if (!this.props.game.pool_entry_1_score) { this.props.game.pool_entry_1_score = ''; } if (!this.props.game.pool_entry_2_score) { this.props.game.pool_entry_2_score = ''; } return this.props.game; }, scoreChanged: function(e) { this.props.scoreChanged(this.state.id, e.target.dataset.team, e.target.value); }, render: function() { var team1Name; var team2Name; var state = this.state; this.props.teams.forEach(function(team) { if (team.id == state.pool_entry_1_id) { team1Name = team.name; } if (team.id == state.pool_entry_2_id) { team2Name = team.name; } }); var team1Roll, team2Roll; this.props.rolls.forEach(function(roll) { if (roll.rank == state.pool_entry_1_rank) { team1Roll = roll.roll; } if (roll.rank == state.pool_entry_2_rank) { team2Roll = roll.roll; } }); return ( <div className="game"> <div className="team"><div className="team-name">{team1Name} ({this.state.pool_entry_1_rank} : {team1Roll})</div> <input type="text" value={this.state.pool_entry_1_score} onChange={this.scoreChanged} data-team="1"/></div> <div className="team"><div className="team-name">{team2Name} ({this.state.pool_entry_2_rank} : {team2Roll})</div> <input type="text" value={this.state.pool_entry_2_score} onChange={this.scoreChanged} data-team="2"/></div> </div> ) } }); var teams = globals.pools[0].teams.concat(globals.pools[1].teams.concat(globals.pools[2].teams.concat(globals.pools[3].teams.concat()))); ReactDOM.render( <div> <a href={'admin/bracket/' + globals.bracket.id}>Back To Bracket</a> <GamesList initialGames={globals.games} round={globals.round} teams={teams} rolls={globals.rolls}/> </div>, document.getElementById('bracket-round') );
austinhaws/custom-bracket
public/js/views/bracket-round.js
JavaScript
unlicense
2,838
var bcrypt = require('bcrypt-nodejs'); var crypto = require('crypto'); var mongoose = require('mongoose'); var userSchema = new mongoose.Schema({ email: { type: String, unique: true, lowercase: true }, password: String, facebook: String, twitter: String, google: String, github: String, instagram: String, linkedin: String, tokens: Array, profile: { name: { type: String, default: '' }, gender: { type: String, default: '' }, location: { type: String, default: '' }, website: { type: String, default: '' }, picture: { type: String, default: '' } }, /* * Data related to the Cards. * This should be moved to a separate table * as soon more than one language is supported */ cardsLastGenerated: Date, //have we generated cards for this user today lastWordUsed: { type: Number, default: 0 }, //last word offset from database resetPasswordToken: String, resetPasswordExpires: Date }); /** * Password hashing Mongoose middleware. */ userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(5, function(err, salt) { if (err) { return next(err); } bcrypt.hash(user.password, salt, null, function(err, hash) { if (err) { return next(err); } user.password = hash; next(); }); }); }); /** * Helper method for validationg user's password. */ userSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) { return cb(err); } cb(null, isMatch); }); }; /** * Helper method for getting user's gravatar. */ userSchema.methods.gravatar = function(size) { if (!size) { size = 200; } if (!this.email) { return 'https://gravatar.com/avatar/?s=' + size + '&d=retro'; } var md5 = crypto.createHash('md5').update(this.email).digest('hex'); return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro'; }; module.exports = mongoose.model('User', userSchema);
guilhermeasg/outspeak
models/User.js
JavaScript
unlicense
2,102
define([ 'app', 'collections/tables', 'collections/connections', 'collections/rdf-entities', 'collections/rdf-attributes', 'models/connection', 'models/table', 'views/abstract/base', 'views/shared/message-dialog', 'views/editor/connection-form', 'views/editor/rdf-entity-list', 'views/editor/rdf-attribute-list', 'views/editor/table-list', 'views/editor/table' ], function( app, TablesCollection, ConnectionsCollection, RdfEntitiesCollection, RdfAttributesCollection, ConnectionModel, TableModel, BaseView, MessageDialogView, ConnectionFormView, RdfEntityListView, RdfAttributeListView, TableListView, TableView ) { 'use strict'; var EditorView = BaseView.extend({ className: 'editor container', template: app.fetchTemplate('editor/editor'), events: { 'click .entity-breadcrumb': 'onEntityBreadcrumbClick', 'click .rdf-settings-icon': 'onRdfSettingsIconClick', 'change .rdf-settings input': 'onRdfSettingsInputChange' }, settingsSlideSpeed: 150, initialize: function(options) { options = options || {}; this.conn = new ConnectionModel(); this.table = new TableModel(); this.tables = new TablesCollection(); this.connections = new ConnectionsCollection(); this.rdfEntities = new RdfEntitiesCollection(); this.rdfAttributes = new RdfAttributesCollection(); this.connectionForm = new ConnectionFormView({ connections: this.connections, conn: this.conn }); this.rdfEntityListView = new RdfEntityListView({ collection: this.rdfEntities }); this.rdfAttributeListView = new RdfAttributeListView({ collection: this.rdfAttributes }); this.tableView = new TableView({ model: this.table, rdfAttributes: this.rdfAttributes, rdfEntities: this.rdfEntities }); this.tableListView = new TableListView({ collection: this.tables }); this.tables.fetch({ reset: true }); window.tables = this.tables; $(document).on('click', _.bind(function(e) { if (!$(e.target).hasClass('rdf-settings')) { this.$('.rdf-settings').slideUp(this.settingsSlideSpeed); } }, this)); }, setListeners: function() { BaseView.prototype.setListeners.call(this); this.listenTo(this.conn, 'connect:success', this.onConnect, this); this.listenTo(this.conn, 'disconnect', this.onDisconnect, this); this.listenTo(this.rdfEntityListView, 'selected-item:change', this.onRdfEntityListSelectedItemChange, this); this.listenTo(this.tableListView, 'item:select', this.onTableListItemSelect, this); this.listenTo(this.rdfEntityListView, 'item:branch', this.onRdfEntityListItemBranch, this); this.listenTo(this.table, 'save:success', this.onTableSaveSuccess, this); this.listenTo(this.table, 'save:error', this.defaultActionErrorHandler, this); this.listenTo(this.table, 'save:validationError', this.onTableValidationError, this); this.listenTo(this.table, 'delete:success', this.onTableDeleteSuccess, this); this.listenTo(this.table, 'delete:error', this.defaultActionErrorHandler, this); this.listenTo(this.rdfEntities, 'change:parents', this.onRdfEntitiesParentsChange, this); }, onConnect: function() { this.$('.editor-rdf').slideDown().addClass('collapsed'); this.$('.editor-rdf-title .collapse-arrow').addClass('collapsed'); this.$('.editor-connection').slideUp().removeClass('collapsed'); this.$('.editor-connection-title .collapse-arrow').removeClass('collapsed'); this.rdfEntities.setEndpoint(this.conn.get('endpoint')); this.rdfAttributes.setEndpoint(this.conn.get('endpoint')); this.rdfEntities.fetch(); }, onDisconnect: function() { this.$('.editor-rdf').slideUp().removeClass('collapsed'); this.$('.editor-rdf-title .collapse-arrow').removeClass('collapsed'); this.$('.editor-connection').slideDown().addClass('collapsed'); this.$('.editor-connection-title .collapse-arrow').addClass('collapsed'); this.rdfEntities.reset(); this.rdfAttributes.reset(); }, render: function() { this.$el.html(this.template({ attributesLimit: this.rdfAttributes.limit, attributesOffset: this.rdfAttributes.offset, attributesSort: this.rdfAttributes.sorting, entitiesLimit: this.rdfEntities.limit, entitiesOffset: this.rdfEntities.offset, entitiesLoadRootAttributes: this.rdfEntities.loadRootAttributes })); this.$('.editor-connection-form').html(this.connectionForm.render().$el); this.$('.editor-rdf-entity-list-container').html(this.rdfEntityListView.render().$el); this.$('.editor-rdf-attribute-list-container').html(this.rdfAttributeListView.render().$el); this.$('.editor-table-list-container').html(this.tableListView.render().$el); this.$('.editor-table-container').html(this.tableView.render().$el); this.$('.editor-rdf').resizable({ handles: 's', minHeight: 100, maxHeight: 500 }); this.$('.editor-connection-title').on('click', _.bind(function() { if (this.$('.editor-connection').hasClass('collapsed')) { this.$('.editor-connection').slideUp().removeClass('collapsed'); } else { this.$('.editor-connection').slideDown().addClass('collapsed'); } this.$('.editor-connection-title .collapse-arrow').toggleClass('collapsed'); }, this)); this.$('.editor-rdf-title').on('click', _.bind(function() { if (this.conn.get('connected')) { if (this.$('.editor-rdf').hasClass('collapsed')) { this.$('.editor-rdf').slideUp().removeClass('collapsed'); } else { this.$('.editor-rdf').slideDown().addClass('collapsed'); } this.$('.editor-rdf-title .collapse-arrow').toggleClass('collapsed'); } }, this)); this.$('.editor-relational-title').on('click', _.bind(function() { if (this.$('.editor-relational').hasClass('collapsed')) { this.$('.editor-relational').slideUp().removeClass('collapsed'); } else { this.$('.editor-relational').slideDown().addClass('collapsed'); } this.$('.editor-relational-title .collapse-arrow').toggleClass('collapsed'); }, this)); this.setListeners(); return this; }, onRdfEntitiesParentsChange: function() { var parents = this.rdfEntities.getParentLabels(); var $breadcrumbs = this.$('.entity-breadcrumbs').html('Entities: '); for (var i = 0; i < this.rdfEntities.parents.length; i++) { if (i > 0) { $breadcrumbs.append('<img class="breadcrumb-divider" src="assets/images/arrow_right.png"></img>'); } var en = this.rdfEntities.parents[i]; var $en = $('<li>').addClass('entity-breadcrumb').attr('data-uri', en.get('uri')).html(en.get('label')); $breadcrumbs.append($en); } }, onRdfEntityListSelectedItemChange: function(rdfEntity) { this.rdfAttributes.setRdfEntity(rdfEntity); if (this.rdfEntities.shouldLoadAttributes()) { this.rdfAttributes.fetch(); } }, onTableListItemSelect: function(tableListItem, tableModel) { this.table = tableModel; this.tableView.setModel(tableModel); this.table.loadTableDefinition(); }, onTableDelete: function(model) { (new MessageDialogView()).showMessage('', 'Your relational table has been removed'); this.tables.remove(this.tables.findWhere({ name: model.get('name') })); }, onTableSaveSuccess: function(model) { (new MessageDialogView()).showSuccessMessage('Your relational table has been saved'); this.tables.add(model); }, onEntityBreadcrumbClick: function(e) { var uri = $(e.target).attr('data-uri'); this.rdfEntities.setParentEntityUri(uri); }, onRdfSettingsIconClick: function(e) { var $sett = $(e.target).find('.rdf-settings'); if ($sett.css('display') === 'block') { $sett.slideUp(this.settingsSlideSpeed); } else { $sett.slideDown(this.settingsSlideSpeed); } e.stopPropagation(); }, onRdfEntityListItemBranch: function(itemView, rdfEntity) { this.rdfEntities.setParentEntity(rdfEntity); }, onRdfSettingsInputChange: function(e) { var $input = $(e.target); if ($input.attr('data-type') === 'entities') { if ($input.attr('data-property') === 'limit') { this.rdfEntities.setLimit(parseInt($input.val(), 10)); } else if ($input.attr('data-property') === 'offset') { this.rdfEntities.setOffset(parseInt($input.val(), 10)); } else { this.rdfEntities.setLoadRootAttributes($input.prop('checked')); } } else { if ($input.attr('data-property') === 'limit') { this.rdfAttributes.setLimit(parseInt($input.val(), 10)); } else if ($input.attr('data-property') === 'sort') { this.rdfAttributes.setSort($input.prop('checked')); } else { this.rdfAttributes.setOffset(parseInt($input.val(), 10)); } } this.$('.rdf-settings').slideUp(this.settingsSlideSpeed); } }); return EditorView; });
ilucin/relsem-bridge-frontend
app/views/editor/editor.js
JavaScript
unlicense
9,433
var User = { title : 'Customer', LoginTitleText : 'Register yourself' } module.exports = User;
thakurarun/Basic-nodejs-express-app
samplenode/samplenode/server/model/User.js
JavaScript
unlicense
104
var path = require('path') var fs = require('fs') var crypto = require('crypto') var dirmatch = require('dirmatch') var _ = require('underscore') var handlebars = require('handlebars') var Filter = require('broccoli-glob-filter') var makePartialName = function(partialPath) { var name = partialPath var ext = path.extname(partialPath) if (ext === '.hbs' || ext === '.handlebars') { name = path.basename(partialPath, ext) } return name } var Tree = function(inputTree, options) { if (!(this instanceof Tree)) return new Tree(inputTree, options) if (!options) options = {} if (options.files === undefined) options.files = ['**/*.hbs', '**/*.handlebars'] if (options.targetExtension === undefined) options.targetExtension = 'html' if (options.makePartialName === undefined) options.makePartialName = makePartialName this.handlebars = options.handlebars || handlebars.create() if (options.helpers) this.handlebars.registerHelper(options.helpers) Filter.apply(this, arguments) } Tree.prototype = Object.create(Filter.prototype) Tree.prototype.description = 'Handlebars' Tree.prototype.read = function(readTree) { var _this = this return readTree(this.inputTree).then(function(srcDir) { // Don't cache when context is dynamic if (typeof _this.options.context === 'function') _this.invalidateCache() _this.cachePartials(srcDir) return Filter.prototype.read.call(_this, readTree) }) } Tree.prototype.cachePartials = function(srcDir) { if (!this.options.partials) return var partials = dirmatch(srcDir, this.options.partials) var absPartials = _.map(partials, function(file) { return path.join(srcDir, file) }) var partialsHash = this.hashFiles(absPartials) if (this.cachedPartialsHash !== partialsHash) { this.cachedPartialsHash = partialsHash this.cachedPartials = this.loadPartials(srcDir, partials) this.invalidateCache() } } Tree.prototype.loadPartials = function(srcDir, partialsPaths) { var partials = {} _.each(partialsPaths, function(partialPath) { var name = this.options.makePartialName(partialPath) var content = fs.readFileSync(path.join(srcDir, partialPath), 'utf8') partials[name] = this.handlebars.compile(content) }, this) return partials } Tree.prototype.hashFiles = function(files) { var keys = _.map(files, this.hashFile.bind(this)) return crypto.createHash('md5').update(keys.join('')) } Tree.prototype.processFileContent = function(content, relPath) { var template = this.handlebars.compile(content, {partials: this.cachedPartials}) var context = this.options.context if (typeof this.options.context === 'function') context = context(relPath) return template(this.options.context, { partials: this.cachedPartials }) } module.exports = Tree
sunflowerdeath/broccoli-render-handlebars
index.js
JavaScript
unlicense
2,724
var express = require('express'), app = express(); app.use('/', express.static(__dirname + '/static')); app.listen(process.env.PORT || 8080);
Hardmath123/quackoverflow
index.js
JavaScript
unlicense
147
// Karma configuration // Generated on Mon Mar 16 2015 13:42:33 GMT-0600 (MDT) 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: [ 'jasmine', 'requirejs' ], // list of files / patterns to load in the browser files: [ 'require-config.js', 'test/test-main.js', 'test/mock/*.js', { pattern: 'test/spec/*.spec.js', included: false }, { pattern: 'src/js/*.js', included: false }, { pattern: 'src/widget/*/*.*', included: false }, { pattern: 'config.json', included: false }, { pattern: 'src/widget/date/bootstrap3-datepicker/js/bootstrap-datepicker.js', included: false }, { pattern: 'src/widget/time/bootstrap3-timepicker/js/bootstrap-timepicker.js', included: false }, { pattern: 'lib/jquery-touchswipe/jquery.touchSwipe.js', included: false }, { pattern: 'lib/jquery-xpath/jquery.xpath.js', included: false }, { pattern: 'lib/text/text.js', included: false }, { pattern: 'lib/leaflet/leaflet.js', included: false }, { pattern: 'lib/bootstrap-slider/js/bootstrap-slider.js', included: false }, { pattern: 'lib/Modernizr.js', included: false }, { pattern: 'lib/xpath/build/enketo-xpathjs.js', included: false }, { pattern: 'lib/bower-components/jquery/dist/jquery.js', included: false }, { pattern: 'lib/bower-components/q/q.js', included: false }, ], // 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: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [ 'Chrome', 'ChromeCanary', 'Firefox', 'Safari', 'PhantomJS', 'Opera' ], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false } ); };
ICT4H/dcs-enketo-core
test/karma.conf.js
JavaScript
apache-2.0
3,479
 var currPageIndex = 0; app.initialize(); $(document).ready(function () { //$('.appV').html('v1.17'); //onDocumentReady(); setMenu(); toggleMenu(); }); function onDocumentReady() { SetPagesList(); setBackground(); runPinchzoom(); turnPages(currPageIndex); setPep(); //changeSize(); setZIndex(); setTimeout("setImgList();", 500); } function setImgList() { var imgList = [ 'images/smallTop.png', 'images/middle.png', 'images/smallBottom.png', 'images/largeTop.png', 'images/largeBottom.png', 'images/menu_cats.png', 'images/menu_recipes.png' ]; var imgListLength = imgList.length; for (var i = 0; i < recipesList.length; i++) { imgList[i + 8] = "images/RecipesImages/" + recipesList[i].image; } preload(imgList); } function preload(arrayOfImages) { for (var i = 0; i < arrayOfImages.length; i++) { setTimeout("$('<img />').attr('src', '"+arrayOfImages[i]+"').appendTo('body').css('display', 'none');", 200); } //$(arrayOfImages).each(function () { //}); } function setPep() { $('.ingredientsDiv, .directionsDiv, .text').pep({ useCSSTranslation: false, constrainTo: 'parent', place: false }); } function setBackground() { var picturesArray = new Array(); for (var i = 0; i < categoriesList.length; i++) { picturesArray[i] = categoriesList[i].background; } $('BODY').bgStretcher({ images: picturesArray, imageWidth: 2000, imageHeight: 1200, slideShowSpeed: 1500, anchoring: 'center top', anchoringImg: 'center top', slideShow: false, transitionEffect: 'simpleSlide', slideDirection: 'W', sequenceMode: 'normal', buttonNext: '.next', buttonPrev: '.back', }); } function chkIfIE9() { if (isIE9()) { $('.ingredientsDiv, .directionsDiv, .imgDiv').addClass('hide'); } else { setTimeout(" $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('hide');", 1000); } } function isIE9() { var myNav = navigator.userAgent.toLowerCase(); //alert(myNav); return (myNav.indexOf('msie 9') != -1); } function setZIndex() { $('.ingredientsDiv, .directionsDiv, .imgDiv').click(function () { $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('zIndex2'); $(this).addClass('zIndex2'); }); } var isChangingSize = false; function changeSize() { $('.ingredientsDiv, .directionsDiv').click(function () { if (!isChangingSize) { if ($(this).hasClass('bigSize')) { $(this).removeClass('bigSize'); isChangingSize = true; } else { $(this).addClass('bigSize'); isChangingSize = true; } setTimeout("isChangingSize = false;", 200); } }); } function runPinchzoom() { if (!Hammer.HAS_TOUCHEVENTS && !Hammer.HAS_POINTEREVENTS) { Hammer.plugins.fakeMultitouch(); } var pinchzoom = $('.pinchzoom').each(function () { var hammertime = Hammer($(this).get(0), { transform_always_block: true, transform_min_scale: 1, drag_block_horizontal: true, drag_block_vertical: true, drag_min_distance: 0 }); var rect = $(this).find('.rect').get(0); var posX = 0, posY = 0, scale = 1, last_scale, rotation = 1, last_rotation; hammertime.on('touch drag transform', function (ev) { switch (ev.type) { case 'touch': last_scale = scale; last_rotation = rotation; break; case 'drag': posX = ev.gesture.deltaX; posY = ev.gesture.deltaY; break; case 'transform': rotation = last_rotation + ev.gesture.rotation; scale = Math.max(1, Math.min(last_scale * ev.gesture.scale, 2)); break; } if (rotation == 1) rotation = 0; // transform! var transform = //"translate3d(" + posX + "px," + posY + "px, 0) " + "scale3d(" + scale + "," + scale + ", 1) " + "rotate(" + rotation + "deg) "; rect.style.transform = transform; rect.style.oTransform = transform; rect.style.msTransform = transform; rect.style.mozTransform = transform; rect.style.webkitTransform = transform; rect.style.msTransform = transform; }); }); } // Category class: function category(id, name, background, header_bg) { this.id = id; this.name = name; this.background = background; this.header_bg = header_bg; this.type = 'category'; } // Recipe class: function recipe(cat_id, name, header_bg, description1, description2, image, pdf) { this.cat_id = cat_id; this.name = name; this.header_bg = header_bg; this.description1 = description1; this.description2 = description2; this.image = image; this.pdf = pdf; this.type = 'recipe'; } var categoriesList = new Array(); categoriesList[0] = new category(0, "Main", 'images/bg_main.jpg', ''); categoriesList[1] = new category(1, "Intro", 'images/bg_intro.jpg', ''); categoriesList[2] = new category(10, "Alex & Cathy's Recipes", 'images/bg_owners.jpg', ''); categoriesList[3] = new category(2, "Appetizers", 'images/bg_appetizers.jpg', 'images/cat_appetizers.png'); categoriesList[4] = new category(3, "Main dishes", 'images/bg_main_dishes.jpg', 'images/cat_mainDishes.png'); categoriesList[5] = new category(4, "Desserts", 'images/bg_desserts.jpg', 'images/cat_desserts.png'); categoriesList[6] = new category(5, "Breakfast", 'images/bg_breakfast.jpg', 'images/cat_breakfast.png'); categoriesList[7] = new category(6, "Drinks", 'images/bg_drinks.jpg', 'images/cat_drinks.png'); categoriesList[8] = new category(7, "Sides", 'images/bg_sides.jpg', 'images/cat_sides.png'); categoriesList[9] = new category(8, "Thank You", 'images/bg_thank_you.jpg', ''); //categoriesList[8] = new category(8, "SoupAndBeans", 'images/bg_soup_and_beans.jpg', 'images/cat_soupsAndBeans.png'); var recipesList = new Array(); var pagesList = new Array(); function SetPagesList() { var catID; var index = 0; for (var i = 0; i < categoriesList.length; i++) { catID = categoriesList[i].id; if (catID != 10) { pagesList[index] = categoriesList[i]; index++; } for (var j = 0; j < recipesList.length; j++) { if (recipesList[j].cat_id == catID) { pagesList[index] = recipesList[j]; index++; } } } } var isPageInMove = false; function turnPages(moveToIndex) { if (!isPageInMove && moveToIndex < pagesList.length) { isPageInMove = true; $('.bigSize').removeClass('bigSize'); $('BODY').bgStretcher.pause(); moveToPage = pagesList[moveToIndex]; //alert(moveToPage.name); if (findCurrBackgroundIndex(pagesList[currPageIndex]) != findCurrBackgroundIndex(pagesList[moveToIndex])) { //if (moveToIndex != 0) { var slideNumber = findCurrBackgroundIndex(pagesList[moveToIndex]); $('BODY').bgStretcher.slideShow(null, slideNumber); //if (currPageIndex < moveToIndex) { // $('.next').click(); //} //else { // $('.back').click(); //} //} } if (moveToPage.type == 'category') { //hide the elements - FOR IE9: chkIfIE9(); //////////////////////////// hideElelnent(); if (pagesList[moveToIndex].header_bg == "") { $('.categoryHeaderDiv').hide(0) } else { //$('.headerDiv').hide(); $('.categoryHeaderDiv').fadeIn() $('.categoryHeaderDiv img').attr({ 'src': pagesList[moveToIndex].header_bg, 'alt': pagesList[moveToIndex].name }); $('.categoryHeaderDiv').removeClass('categoryHeaderDivOut'); } $('#container').show(1000); } else { //show the elements - FOR IE9: setTimeout(" $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('hide');", 1000); //////////////////////////// hideElelnent(); $('#container').fadeOut(); setTimeout(function () { setCurrRecipe(pagesList[moveToIndex]); $('.ingredientsDiv, .directionsDiv').each(function () { //alert($(this).css('transition-property')); $(this).removeClass('textOut'); $(this).css('transition-duration', Math.random() / 2 + .5 + 's'); $('.imgDiv').hide(); $('.imgDiv img').load(function () { $('.imgDiv').show(); setTimeout("$('.imgDiv').removeClass('imgOut');", 10); }); $('.imgDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); $('.headerDiv').removeClass('headerOut headerScale'); $('.headerDiv').show(); $('.headerDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); }); }, 1000); } currPageIndex = moveToIndex; setTimeout("isPageInMove = false;", 1000); if (moveToIndex == 0) $('.arrowBack').fadeOut(1000); else if ($('.arrowBack').css('display') == 'none') $('.arrowBack').fadeIn(1000); if (moveToIndex == pagesList.length - 1) $('.arrowNext').fadeOut(1000); else if ($('.arrowNext').css('display') == 'none') $('.arrowNext').fadeIn(1000); } } function findCurrBackgroundIndex(currPage) { var backgroungIndex = 0; if (currPage.type == 'category') { for (var i = 0; i < categoriesList.length; i++) { if (categoriesList[i].id == currPage.id) { backgroungIndex = i; } } } else { for (var i = 0; i < categoriesList.length; i++) { if (categoriesList[i].id == currPage.cat_id) { backgroungIndex = i; } } } return backgroungIndex; } function hideElelnent() { $('.ingredientsDiv, .directionsDiv').each(function () { $(this).addClass('textOut'); $(this).css('transition-duration', Math.random() / 2 + .5 + 's'); }); $('.imgDiv').addClass('imgOut'); $('.imgDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); $('.headerDiv').addClass('headerOut'); $('.categoryHeaderDiv').addClass('categoryHeaderDivOut'); setTimeout(function () { $('.headerDiv').addClass('headerScale'); }, 300); $('.headerDiv').css('transition-duration', Math.random() / 2 + .2 + 's'); } function setCurrRecipe(currRecipe) { $('.ingredientsDiv, .directionsDiv, .imgDiv').css('transition-property', 'none'); $('.headerDiv img').attr({ 'src': currRecipe.header_bg, 'alt': currRecipe.name }); $('.ingredientsDiv_middle p').html(currRecipe.description1); $('.directionsDiv_middle p').html(currRecipe.description2); // $('.printer').attr('href', '/pdf/' + currRecipe.pdf); //$('.printer').attr('href', '#'); $('.printer').unbind('click'); $('.printer').click(function () { //alert('aa'); //window.open(currRecipe.pdf, '_system', 'location=yes'); //window.open('http://docs.google.com/viewer?url=' + currRecipe.pdf, '_blank', 'location=no'); //alert('bb'); //alert(currRecipe.pdf); //window.plugins.childBrowser.showWebPage(currRecipe.pdf, { showLocationBar: false }); window.open(encodeURI(currRecipe.pdf), '_system', 'location=no'); }); if (currRecipe.image == null || currRecipe.image == "") { $('.imgDiv').hide(0); } else { $('.imgDiv img').attr({ 'src': 'images/RecipesImages/' + currRecipe.image, 'alt': currRecipe.name }); $('.imgDiv').show(0); } //$('.ingredientsDiv').css("height", ""); //$('.directionsDiv').css("height", ""); $('.ingredientsDiv, .directionsDiv, .imgDiv').each(function () { $(this).css("width", ""); $(this).css("height", ""); $(this).find('div').each(function () { $(this).css("width", "") $(this).css("height", "") }); //alert(fontSize * currScale); //$('.ingredientsDiv_middle p, .directionsDiv_middle p').css('font-size', fontSize * currScale + 'px'); }); //alert($('.ingredientsDiv').height()); setElementSize(1); $('.ingredientsDiv, .directionsDiv, .imgDiv').css('transition-property', 'all'); } function setElementSize(currScale) { var ingredientsDivTop = 220 * (1 - ((1 - currScale) / 2)); $('.ingredientsDiv').css({ 'top': ingredientsDivTop + 'px', 'left': '80px' }); //$('.ingredientsDiv_middle').height($('.ingredientsDiv_middle p').outerHeight(true)); //$('.directionsDiv_middle').height($('.directionsDiv_middle p').outerHeight(true)); $('.directionsDiv').css({ 'top': ((ingredientsDivTop + $('.ingredientsDiv').height()) + 50) * currScale + 'px', 'left': '80px' }); $('.imgDiv').css({ 'top': (ingredientsDivTop + 50) * currScale + 'px', 'left': '600px' }); //alert($('.ingredientsDiv_middle p').outerHeight(true)); //alert($('.ingredientsDiv_middle').height()); //setTimeout("setElementSizeInner(" + currScale + ");", 1200); setElementSizeInner(currScale); //alert($('directionsDiv').height()); } function setElementSizeInner(currScale) { var ingredientsDivTop = 220 * (1 - ((1 - currScale) / 2)); var fontSize = 15; var directionsDivButtom = ingredientsDivTop + ($('.ingredientsDiv').height() + 50 + $('.directionsDiv').height()) * currScale; //alert($(window).height() + " " + directionsDivButtom + " " + $('.directionsDiv').height()); var callAgain = false; if (($(window).height() * 0.90) < directionsDivButtom) { currScale *= 0.9; callAgain = true; setElementSizeInner(currScale); } //} else { //$('.ingredientsDiv_middle').height($('.ingredientsDiv_middle p').outerHeight(true)); //$('.directionsDiv_middle').height($('.directionsDiv_middle p').outerHeight(true)); //alert(ingredientsDivTop + " " + ($('.ingredientsDiv').height()) * currScale + " " + $('.directionsDiv').css('top')); //$('.ingredientsDiv, .directionsDiv').css('transition-property', 'transform'); $('.imgDiv').width(500 * currScale); $('.imgFrame').css('background-size', $('.imgDiv').width() + 'px ' + $('.imgDiv').height() + 'px'); $('.ingredientsDiv, .directionsDiv').each(function () { var halfTheScale = 1 - ((1 - currScale) / 2); $(this).width($(this).width() * halfTheScale); $(this).height($(this).height() * currScale); $(this).find('div').each(function () { $(this).width($(this).width() * halfTheScale); //$(this).height($(this).height() * currScale); //alert($(this).width() + " " + $(this).height()); $(this).css('background-size', $(this).width() + 'px ' + $(this).height() + 'px'); }); //$('.imgDiv img').width($(this).width()); $('.ingredientsDiv_middle p, .directionsDiv_middle p').css('font-size', fontSize * currScale + 'px'); }); var originalMarginLeft = 80; var totalMarginLeft; if (600 + $('.imgDiv').width() < $(window).width()) { totalMarginLeft = ($(window).width() - (600 + $('.imgDiv').width())) / 2 + 20; } else { totalMarginLeft = 20; } var imgLeftPosition = (-totalMarginLeft * 2 + $(window).width() - $('.imgDiv').width()); $('.ingredientsDiv').css({ 'top': ingredientsDivTop + 'px', 'left': totalMarginLeft + 'px' }); $('.directionsDiv').css({ 'top': ingredientsDivTop + $('.ingredientsDiv').height() + 70 + 'px', 'left': totalMarginLeft + 'px' }); $('.imgDiv').css({ 'left': totalMarginLeft + imgLeftPosition + 'px' }); //if (callAgain) // setElementSizeInner(currScale); } } function setMenu() { for (var i = 0; i < categoriesList.length; i++) { $('<li><a href="#"><span></span></a></li>').appendTo('.menu_cats'); for (var j = 0; j < recipesList.length; j++) { if (recipesList[j].cat_id == categoriesList[i].id) { $('<li><a href="#"><span></span></a></li>').appendTo('.menu_recipe'); } } } $('.menu_cats > li').each(function () { if (categoriesList[$(this).index()].id != 1) { $(this).find('span').text((categoriesList[$(this).index()].name).toUpperCase()); } if ($(this).find('span').html() == "") { $(this).hide(); } }); $('.menu_cats > li > a').click(function () { var catID; $('.menu_recipe li').remove(); for (var i = 0; i < categoriesList.length; i++) { //alert($(this).find('span').html() +' '+ categoriesList[i].name.toUpperCase()); if ($(this).find('span').html().replace("&amp;", "&") == categoriesList[i].name.toUpperCase()) { catID = categoriesList[i].id; if (catID == 0 || catID == 8) { $('.menu_recipe').slideUp(); } else { $('.menu_recipe').slideDown(); } } } if (catID == 0) { turnPages(0); hideMenu(); } else if (catID == 8) { turnPages(51); hideMenu(); } else { var currCatRecipesList = new Array; var index = 0; for (var j = 0; j < pagesList.length; j++) { if (pagesList[j].type == 'recipe' && pagesList[j].cat_id == catID) { $('<li onclick="turnPages(' + j + ');"><span onclick="hideMenu();">' + pagesList[j].name + '</span></li>').appendTo('.menu_recipe'); currCatRecipesList[index] = pagesList[j]; index++; } } } }); } function toggleMenu() { $('.btnMenu').click(function () { $('.menu_cats').slideToggle(); $('.menu_recipe').slideUp(); }); } function hideMenu() { $('.menu_cats, .menu_recipe').slideUp(); }
Webnology-/cookbook2013VeryLast
www/js/javascript.js
JavaScript
apache-2.0
18,944
export { default } from 'ember-table-filterable/components/table-filterable';
clairton/ember-table-filterable
app/components/table-filterable.js
JavaScript
apache-2.0
77
import endsWith from 'lodash/endsWith'; import startsWith from 'lodash/startsWith'; import trim from 'lodash/trim'; const VALID_SLUG_PATTERN = /^([a-z0-9]-?)*[a-z0-9]$/; const VALID_DATED_SLUG_PATTERN = /^([a-z0-9-]|[a-z0-9-][a-z0-9-/]*[a-z0-9-])$/; /** * Returns true if the provided value is a slug. * * @param {string} slug * @param {boolean} [allowSlashes] * * @returns {boolean} */ export default function isValidSlug(slug, allowSlashes = false) { if (!trim(slug)) { return false; } if (startsWith(slug, '-') || startsWith(slug, '/')) { return false; } if (endsWith(slug, '-') || endsWith(slug, '/')) { return false; } const regex = allowSlashes ? VALID_DATED_SLUG_PATTERN : VALID_SLUG_PATTERN; return regex.test(slug); }
gdbots/common-js
src/isValidSlug.js
JavaScript
apache-2.0
767
/** * Copyright 2014 Shape Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { getHexValue, isLineTerminator, isWhiteSpace, isIdentifierStart, isIdentifierPart, isDecimalDigit } from './utils'; import { ErrorMessages } from './errors'; export const TokenClass = { Eof: { name: '<End>' }, Ident: { name: 'Identifier', isIdentifierName: true }, Keyword: { name: 'Keyword', isIdentifierName: true }, NumericLiteral: { name: 'Numeric' }, TemplateElement: { name: 'Template' }, Punctuator: { name: 'Punctuator' }, StringLiteral: { name: 'String' }, RegularExpression: { name: 'RegularExpression' }, Illegal: { name: 'Illegal' }, }; export const TokenType = { EOS: { klass: TokenClass.Eof, name: 'EOS' }, LPAREN: { klass: TokenClass.Punctuator, name: '(' }, RPAREN: { klass: TokenClass.Punctuator, name: ')' }, LBRACK: { klass: TokenClass.Punctuator, name: '[' }, RBRACK: { klass: TokenClass.Punctuator, name: ']' }, LBRACE: { klass: TokenClass.Punctuator, name: '{' }, RBRACE: { klass: TokenClass.Punctuator, name: '}' }, COLON: { klass: TokenClass.Punctuator, name: ':' }, SEMICOLON: { klass: TokenClass.Punctuator, name: ';' }, PERIOD: { klass: TokenClass.Punctuator, name: '.' }, ELLIPSIS: { klass: TokenClass.Punctuator, name: '...' }, ARROW: { klass: TokenClass.Punctuator, name: '=>' }, CONDITIONAL: { klass: TokenClass.Punctuator, name: '?' }, INC: { klass: TokenClass.Punctuator, name: '++' }, DEC: { klass: TokenClass.Punctuator, name: '--' }, ASSIGN: { klass: TokenClass.Punctuator, name: '=' }, ASSIGN_BIT_OR: { klass: TokenClass.Punctuator, name: '|=' }, ASSIGN_BIT_XOR: { klass: TokenClass.Punctuator, name: '^=' }, ASSIGN_BIT_AND: { klass: TokenClass.Punctuator, name: '&=' }, ASSIGN_SHL: { klass: TokenClass.Punctuator, name: '<<=' }, ASSIGN_SHR: { klass: TokenClass.Punctuator, name: '>>=' }, ASSIGN_SHR_UNSIGNED: { klass: TokenClass.Punctuator, name: '>>>=' }, ASSIGN_ADD: { klass: TokenClass.Punctuator, name: '+=' }, ASSIGN_SUB: { klass: TokenClass.Punctuator, name: '-=' }, ASSIGN_MUL: { klass: TokenClass.Punctuator, name: '*=' }, ASSIGN_DIV: { klass: TokenClass.Punctuator, name: '/=' }, ASSIGN_MOD: { klass: TokenClass.Punctuator, name: '%=' }, ASSIGN_EXP: { klass: TokenClass.Punctuator, name: '**=' }, COMMA: { klass: TokenClass.Punctuator, name: ',' }, OR: { klass: TokenClass.Punctuator, name: '||' }, AND: { klass: TokenClass.Punctuator, name: '&&' }, BIT_OR: { klass: TokenClass.Punctuator, name: '|' }, BIT_XOR: { klass: TokenClass.Punctuator, name: '^' }, BIT_AND: { klass: TokenClass.Punctuator, name: '&' }, SHL: { klass: TokenClass.Punctuator, name: '<<' }, SHR: { klass: TokenClass.Punctuator, name: '>>' }, SHR_UNSIGNED: { klass: TokenClass.Punctuator, name: '>>>' }, ADD: { klass: TokenClass.Punctuator, name: '+' }, SUB: { klass: TokenClass.Punctuator, name: '-' }, MUL: { klass: TokenClass.Punctuator, name: '*' }, DIV: { klass: TokenClass.Punctuator, name: '/' }, MOD: { klass: TokenClass.Punctuator, name: '%' }, EXP: { klass: TokenClass.Punctuator, name: '**' }, EQ: { klass: TokenClass.Punctuator, name: '==' }, NE: { klass: TokenClass.Punctuator, name: '!=' }, EQ_STRICT: { klass: TokenClass.Punctuator, name: '===' }, NE_STRICT: { klass: TokenClass.Punctuator, name: '!==' }, LT: { klass: TokenClass.Punctuator, name: '<' }, GT: { klass: TokenClass.Punctuator, name: '>' }, LTE: { klass: TokenClass.Punctuator, name: '<=' }, GTE: { klass: TokenClass.Punctuator, name: '>=' }, INSTANCEOF: { klass: TokenClass.Keyword, name: 'instanceof' }, IN: { klass: TokenClass.Keyword, name: 'in' }, NOT: { klass: TokenClass.Punctuator, name: '!' }, BIT_NOT: { klass: TokenClass.Punctuator, name: '~' }, ASYNC: { klass: TokenClass.Keyword, name: 'async' }, AWAIT: { klass: TokenClass.Keyword, name: 'await' }, ENUM: { klass: TokenClass.Keyword, name: 'enum' }, DELETE: { klass: TokenClass.Keyword, name: 'delete' }, TYPEOF: { klass: TokenClass.Keyword, name: 'typeof' }, VOID: { klass: TokenClass.Keyword, name: 'void' }, BREAK: { klass: TokenClass.Keyword, name: 'break' }, CASE: { klass: TokenClass.Keyword, name: 'case' }, CATCH: { klass: TokenClass.Keyword, name: 'catch' }, CLASS: { klass: TokenClass.Keyword, name: 'class' }, CONTINUE: { klass: TokenClass.Keyword, name: 'continue' }, DEBUGGER: { klass: TokenClass.Keyword, name: 'debugger' }, DEFAULT: { klass: TokenClass.Keyword, name: 'default' }, DO: { klass: TokenClass.Keyword, name: 'do' }, ELSE: { klass: TokenClass.Keyword, name: 'else' }, EXPORT: { klass: TokenClass.Keyword, name: 'export' }, EXTENDS: { klass: TokenClass.Keyword, name: 'extends' }, FINALLY: { klass: TokenClass.Keyword, name: 'finally' }, FOR: { klass: TokenClass.Keyword, name: 'for' }, FUNCTION: { klass: TokenClass.Keyword, name: 'function' }, IF: { klass: TokenClass.Keyword, name: 'if' }, IMPORT: { klass: TokenClass.Keyword, name: 'import' }, LET: { klass: TokenClass.Keyword, name: 'let' }, NEW: { klass: TokenClass.Keyword, name: 'new' }, RETURN: { klass: TokenClass.Keyword, name: 'return' }, SUPER: { klass: TokenClass.Keyword, name: 'super' }, SWITCH: { klass: TokenClass.Keyword, name: 'switch' }, THIS: { klass: TokenClass.Keyword, name: 'this' }, THROW: { klass: TokenClass.Keyword, name: 'throw' }, TRY: { klass: TokenClass.Keyword, name: 'try' }, VAR: { klass: TokenClass.Keyword, name: 'var' }, WHILE: { klass: TokenClass.Keyword, name: 'while' }, WITH: { klass: TokenClass.Keyword, name: 'with' }, NULL: { klass: TokenClass.Keyword, name: 'null' }, TRUE: { klass: TokenClass.Keyword, name: 'true' }, FALSE: { klass: TokenClass.Keyword, name: 'false' }, YIELD: { klass: TokenClass.Keyword, name: 'yield' }, NUMBER: { klass: TokenClass.NumericLiteral, name: '' }, STRING: { klass: TokenClass.StringLiteral, name: '' }, REGEXP: { klass: TokenClass.RegularExpression, name: '' }, IDENTIFIER: { klass: TokenClass.Ident, name: '' }, CONST: { klass: TokenClass.Keyword, name: 'const' }, TEMPLATE: { klass: TokenClass.TemplateElement, name: '' }, ESCAPED_KEYWORD: { klass: TokenClass.Keyword, name: '' }, ILLEGAL: { klass: TokenClass.Illegal, name: '' }, }; const TT = TokenType; const I = TT.ILLEGAL; const F = false; const T = true; const ONE_CHAR_PUNCTUATOR = [ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.NOT, I, I, I, TT.MOD, TT.BIT_AND, I, TT.LPAREN, TT.RPAREN, TT.MUL, TT.ADD, TT.COMMA, TT.SUB, TT.PERIOD, TT.DIV, I, I, I, I, I, I, I, I, I, I, TT.COLON, TT.SEMICOLON, TT.LT, TT.ASSIGN, TT.GT, TT.CONDITIONAL, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.LBRACK, I, TT.RBRACK, TT.BIT_XOR, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.LBRACE, TT.BIT_OR, TT.RBRACE, TT.BIT_NOT, ]; const PUNCTUATOR_START = [ F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, T, T, F, T, T, T, T, T, T, F, T, F, F, F, F, F, F, F, F, F, F, T, T, T, T, T, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, F, T, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, T, T, T, F, ]; export class JsError extends Error { constructor(index, line, column, msg) { super(msg); this.index = index; // Safari defines these properties as non-writable and non-configurable on Error objects try { this.line = line; this.column = column; } catch (e) {} // define these as well so Safari still has access to this info this.parseErrorLine = line; this.parseErrorColumn = column; this.description = msg; this.message = `[${line}:${column}]: ${msg}`; } } function fromCodePoint(cp) { if (cp <= 0xFFFF) return String.fromCharCode(cp); let cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); let cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); return cu1 + cu2; } function decodeUtf16(lead, trail) { return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; } export default class Tokenizer { constructor(source) { this.source = source; this.index = 0; this.line = 0; this.lineStart = 0; this.startIndex = 0; this.startLine = 0; this.startLineStart = 0; this.lastIndex = 0; this.lastLine = 0; this.lastLineStart = 0; this.hasLineTerminatorBeforeNext = false; this.tokenIndex = 0; } saveLexerState() { return { source: this.source, index: this.index, line: this.line, lineStart: this.lineStart, startIndex: this.startIndex, startLine: this.startLine, startLineStart: this.startLineStart, lastIndex: this.lastIndex, lastLine: this.lastLine, lastLineStart: this.lastLineStart, lookahead: this.lookahead, hasLineTerminatorBeforeNext: this.hasLineTerminatorBeforeNext, tokenIndex: this.tokenIndex, }; } restoreLexerState(state) { this.source = state.source; this.index = state.index; this.line = state.line; this.lineStart = state.lineStart; this.startIndex = state.startIndex; this.startLine = state.startLine; this.startLineStart = state.startLineStart; this.lastIndex = state.lastIndex; this.lastLine = state.lastLine; this.lastLineStart = state.lastLineStart; this.lookahead = state.lookahead; this.hasLineTerminatorBeforeNext = state.hasLineTerminatorBeforeNext; this.tokenIndex = state.tokenIndex; } createILLEGAL() { this.startIndex = this.index; this.startLine = this.line; this.startLineStart = this.lineStart; return this.index < this.source.length ? this.createError(ErrorMessages.UNEXPECTED_ILLEGAL_TOKEN, this.source.charAt(this.index)) : this.createError(ErrorMessages.UNEXPECTED_EOS); } createUnexpected(token) { switch (token.type.klass) { case TokenClass.Eof: return this.createError(ErrorMessages.UNEXPECTED_EOS); case TokenClass.Ident: return this.createError(ErrorMessages.UNEXPECTED_IDENTIFIER); case TokenClass.Keyword: if (token.type === TokenType.ESCAPED_KEYWORD) { return this.createError(ErrorMessages.UNEXPECTED_ESCAPED_KEYWORD); } return this.createError(ErrorMessages.UNEXPECTED_TOKEN, token.slice.text); case TokenClass.NumericLiteral: return this.createError(ErrorMessages.UNEXPECTED_NUMBER); case TokenClass.TemplateElement: return this.createError(ErrorMessages.UNEXPECTED_TEMPLATE); case TokenClass.Punctuator: return this.createError(ErrorMessages.UNEXPECTED_TOKEN, token.type.name); case TokenClass.StringLiteral: return this.createError(ErrorMessages.UNEXPECTED_STRING); // the other token classes are RegularExpression and Illegal, but they cannot reach here } // istanbul ignore next throw new Error('Unreachable: unexpected token of class ' + token.type.klass); } createError(message, ...params) { let msg; if (typeof message === 'function') { msg = message(...params); } else { msg = message; } return new JsError(this.startIndex, this.startLine + 1, this.startIndex - this.startLineStart + 1, msg); } createErrorWithLocation(location, message) { /* istanbul ignore next */ let msg = message.replace(/\{(\d+)\}/g, (_, n) => JSON.stringify(arguments[+n + 2])); if (location.slice && location.slice.startLocation) { location = location.slice.startLocation; } return new JsError(location.offset, location.line, location.column + 1, msg); } static cse2(id, ch1, ch2) { return id.charAt(1) === ch1 && id.charAt(2) === ch2; } static cse3(id, ch1, ch2, ch3) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3; } static cse4(id, ch1, ch2, ch3, ch4) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4; } static cse5(id, ch1, ch2, ch3, ch4, ch5) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5; } static cse6(id, ch1, ch2, ch3, ch4, ch5, ch6) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5 && id.charAt(6) === ch6; } static cse7(id, ch1, ch2, ch3, ch4, ch5, ch6, ch7) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5 && id.charAt(6) === ch6 && id.charAt(7) === ch7; } getKeyword(id) { if (id.length === 1 || id.length > 10) { return TokenType.IDENTIFIER; } /* istanbul ignore next */ switch (id.length) { case 2: switch (id.charAt(0)) { case 'i': switch (id.charAt(1)) { case 'f': return TokenType.IF; case 'n': return TokenType.IN; default: break; } break; case 'd': if (id.charAt(1) === 'o') { return TokenType.DO; } break; } break; case 3: switch (id.charAt(0)) { case 'v': if (Tokenizer.cse2(id, 'a', 'r')) { return TokenType.VAR; } break; case 'f': if (Tokenizer.cse2(id, 'o', 'r')) { return TokenType.FOR; } break; case 'n': if (Tokenizer.cse2(id, 'e', 'w')) { return TokenType.NEW; } break; case 't': if (Tokenizer.cse2(id, 'r', 'y')) { return TokenType.TRY; } break; case 'l': if (Tokenizer.cse2(id, 'e', 't')) { return TokenType.LET; } break; } break; case 4: switch (id.charAt(0)) { case 't': if (Tokenizer.cse3(id, 'h', 'i', 's')) { return TokenType.THIS; } else if (Tokenizer.cse3(id, 'r', 'u', 'e')) { return TokenType.TRUE; } break; case 'n': if (Tokenizer.cse3(id, 'u', 'l', 'l')) { return TokenType.NULL; } break; case 'e': if (Tokenizer.cse3(id, 'l', 's', 'e')) { return TokenType.ELSE; } else if (Tokenizer.cse3(id, 'n', 'u', 'm')) { return TokenType.ENUM; } break; case 'c': if (Tokenizer.cse3(id, 'a', 's', 'e')) { return TokenType.CASE; } break; case 'v': if (Tokenizer.cse3(id, 'o', 'i', 'd')) { return TokenType.VOID; } break; case 'w': if (Tokenizer.cse3(id, 'i', 't', 'h')) { return TokenType.WITH; } break; } break; case 5: switch (id.charAt(0)) { case 'a': if (Tokenizer.cse4(id, 's', 'y', 'n', 'c')) { return TokenType.ASYNC; } if (Tokenizer.cse4(id, 'w', 'a', 'i', 't')) { return TokenType.AWAIT; } break; case 'w': if (Tokenizer.cse4(id, 'h', 'i', 'l', 'e')) { return TokenType.WHILE; } break; case 'b': if (Tokenizer.cse4(id, 'r', 'e', 'a', 'k')) { return TokenType.BREAK; } break; case 'f': if (Tokenizer.cse4(id, 'a', 'l', 's', 'e')) { return TokenType.FALSE; } break; case 'c': if (Tokenizer.cse4(id, 'a', 't', 'c', 'h')) { return TokenType.CATCH; } else if (Tokenizer.cse4(id, 'o', 'n', 's', 't')) { return TokenType.CONST; } else if (Tokenizer.cse4(id, 'l', 'a', 's', 's')) { return TokenType.CLASS; } break; case 't': if (Tokenizer.cse4(id, 'h', 'r', 'o', 'w')) { return TokenType.THROW; } break; case 'y': if (Tokenizer.cse4(id, 'i', 'e', 'l', 'd')) { return TokenType.YIELD; } break; case 's': if (Tokenizer.cse4(id, 'u', 'p', 'e', 'r')) { return TokenType.SUPER; } break; } break; case 6: switch (id.charAt(0)) { case 'r': if (Tokenizer.cse5(id, 'e', 't', 'u', 'r', 'n')) { return TokenType.RETURN; } break; case 't': if (Tokenizer.cse5(id, 'y', 'p', 'e', 'o', 'f')) { return TokenType.TYPEOF; } break; case 'd': if (Tokenizer.cse5(id, 'e', 'l', 'e', 't', 'e')) { return TokenType.DELETE; } break; case 's': if (Tokenizer.cse5(id, 'w', 'i', 't', 'c', 'h')) { return TokenType.SWITCH; } break; case 'e': if (Tokenizer.cse5(id, 'x', 'p', 'o', 'r', 't')) { return TokenType.EXPORT; } break; case 'i': if (Tokenizer.cse5(id, 'm', 'p', 'o', 'r', 't')) { return TokenType.IMPORT; } break; } break; case 7: switch (id.charAt(0)) { case 'd': if (Tokenizer.cse6(id, 'e', 'f', 'a', 'u', 'l', 't')) { return TokenType.DEFAULT; } break; case 'f': if (Tokenizer.cse6(id, 'i', 'n', 'a', 'l', 'l', 'y')) { return TokenType.FINALLY; } break; case 'e': if (Tokenizer.cse6(id, 'x', 't', 'e', 'n', 'd', 's')) { return TokenType.EXTENDS; } break; } break; case 8: switch (id.charAt(0)) { case 'f': if (Tokenizer.cse7(id, 'u', 'n', 'c', 't', 'i', 'o', 'n')) { return TokenType.FUNCTION; } break; case 'c': if (Tokenizer.cse7(id, 'o', 'n', 't', 'i', 'n', 'u', 'e')) { return TokenType.CONTINUE; } break; case 'd': if (Tokenizer.cse7(id, 'e', 'b', 'u', 'g', 'g', 'e', 'r')) { return TokenType.DEBUGGER; } break; } break; case 10: if (id === 'instanceof') { return TokenType.INSTANCEOF; } break; } return TokenType.IDENTIFIER; } skipSingleLineComment(offset) { this.index += offset; while (this.index < this.source.length) { /** * @type {Number} */ let chCode = this.source.charCodeAt(this.index); this.index++; if (isLineTerminator(chCode)) { this.hasLineTerminatorBeforeNext = true; if (chCode === 0xD /* "\r" */ && this.source.charCodeAt(this.index) === 0xA /* "\n" */) { this.index++; } this.lineStart = this.index; this.line++; return; } } } skipMultiLineComment() { this.index += 2; const length = this.source.length; let isLineStart = false; while (this.index < length) { let chCode = this.source.charCodeAt(this.index); if (chCode < 0x80) { switch (chCode) { case 42: // "*" // Block comment ends with "*/". if (this.source.charAt(this.index + 1) === '/') { this.index = this.index + 2; return isLineStart; } this.index++; break; case 10: // "\n" isLineStart = true; this.hasLineTerminatorBeforeNext = true; this.index++; this.lineStart = this.index; this.line++; break; case 13: // "\r": isLineStart = true; this.hasLineTerminatorBeforeNext = true; if (this.source.charAt(this.index + 1) === '\n') { this.index++; } this.index++; this.lineStart = this.index; this.line++; break; default: this.index++; } } else if (chCode === 0x2028 || chCode === 0x2029) { isLineStart = true; this.hasLineTerminatorBeforeNext = true; this.index++; this.lineStart = this.index; this.line++; } else { this.index++; } } throw this.createILLEGAL(); } skipComment() { this.hasLineTerminatorBeforeNext = false; let isLineStart = this.index === 0; const length = this.source.length; while (this.index < length) { let chCode = this.source.charCodeAt(this.index); if (isWhiteSpace(chCode)) { this.index++; } else if (isLineTerminator(chCode)) { this.hasLineTerminatorBeforeNext = true; this.index++; if (chCode === 13 /* "\r" */ && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; this.line++; isLineStart = true; } else if (chCode === 47 /* "/" */) { if (this.index + 1 >= length) { break; } chCode = this.source.charCodeAt(this.index + 1); if (chCode === 47 /* "/" */) { this.skipSingleLineComment(2); isLineStart = true; } else if (chCode === 42 /* "*" */) { isLineStart = this.skipMultiLineComment() || isLineStart; } else { break; } } else if (!this.moduleIsTheGoalSymbol && isLineStart && chCode === 45 /* "-" */) { if (this.index + 2 >= length) { break; } // U+003E is ">" if (this.source.charAt(this.index + 1) === '-' && this.source.charAt(this.index + 2) === '>') { // "-->" is a single-line comment this.skipSingleLineComment(3); } else { break; } } else if (!this.moduleIsTheGoalSymbol && chCode === 60 /* "<" */) { if (this.source.slice(this.index + 1, this.index + 4) === '!--') { this.skipSingleLineComment(4); isLineStart = true; } else { break; } } else { break; } } } scanHexEscape2() { if (this.index + 2 > this.source.length) { return -1; } let r1 = getHexValue(this.source.charAt(this.index)); if (r1 === -1) { return -1; } let r2 = getHexValue(this.source.charAt(this.index + 1)); if (r2 === -1) { return -1; } this.index += 2; return r1 << 4 | r2; } scanUnicode() { if (this.source.charAt(this.index) === '{') { // \u{HexDigits} let i = this.index + 1; let hexDigits = 0, ch; while (i < this.source.length) { ch = this.source.charAt(i); let hex = getHexValue(ch); if (hex === -1) { break; } hexDigits = hexDigits << 4 | hex; if (hexDigits > 0x10FFFF) { throw this.createILLEGAL(); } i++; } if (ch !== '}') { throw this.createILLEGAL(); } if (i === this.index + 1) { ++this.index; // This is so that the error is 'Unexpected "}"' instead of 'Unexpected "{"'. throw this.createILLEGAL(); } this.index = i + 1; return hexDigits; } // \uHex4Digits if (this.index + 4 > this.source.length) { return -1; } let r1 = getHexValue(this.source.charAt(this.index)); if (r1 === -1) { return -1; } let r2 = getHexValue(this.source.charAt(this.index + 1)); if (r2 === -1) { return -1; } let r3 = getHexValue(this.source.charAt(this.index + 2)); if (r3 === -1) { return -1; } let r4 = getHexValue(this.source.charAt(this.index + 3)); if (r4 === -1) { return -1; } this.index += 4; return r1 << 12 | r2 << 8 | r3 << 4 | r4; } getEscapedIdentifier() { let id = ''; let check = isIdentifierStart; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); let code = ch.charCodeAt(0); let start = this.index; ++this.index; if (ch === '\\') { if (this.index >= this.source.length) { throw this.createILLEGAL(); } if (this.source.charAt(this.index) !== 'u') { throw this.createILLEGAL(); } ++this.index; code = this.scanUnicode(); if (code < 0) { throw this.createILLEGAL(); } ch = fromCodePoint(code); } else if (code >= 0xD800 && code <= 0xDBFF) { if (this.index >= this.source.length) { throw this.createILLEGAL(); } let lowSurrogateCode = this.source.charCodeAt(this.index); ++this.index; if (!(lowSurrogateCode >= 0xDC00 && lowSurrogateCode <= 0xDFFF)) { throw this.createILLEGAL(); } code = decodeUtf16(code, lowSurrogateCode); ch = fromCodePoint(code); } if (!check(code)) { if (id.length < 1) { throw this.createILLEGAL(); } this.index = start; return id; } check = isIdentifierPart; id += ch; } return id; } getIdentifier() { let start = this.index; let l = this.source.length; let i = this.index; let check = isIdentifierStart; while (i < l) { let ch = this.source.charAt(i); let code = ch.charCodeAt(0); if (ch === '\\' || code >= 0xD800 && code <= 0xDBFF) { // Go back and try the hard one. this.index = start; return this.getEscapedIdentifier(); } if (!check(code)) { this.index = i; return this.source.slice(start, i); } ++i; check = isIdentifierPart; } this.index = i; return this.source.slice(start, i); } scanIdentifier() { let startLocation = this.getLocation(); let start = this.index; // Backslash (U+005C) starts an escaped character. let id = this.source.charAt(this.index) === '\\' ? this.getEscapedIdentifier() : this.getIdentifier(); let slice = this.getSlice(start, startLocation); slice.text = id; let hasEscape = this.index - start !== id.length; let type = this.getKeyword(id); if (hasEscape && type !== TokenType.IDENTIFIER) { type = TokenType.ESCAPED_KEYWORD; } return { type, value: id, slice, escaped: hasEscape }; } getLocation() { return { line: this.startLine + 1, column: this.startIndex - this.startLineStart, offset: this.startIndex, }; } getLastTokenEndLocation() { return { line: this.lastLine + 1, column: this.lastIndex - this.lastLineStart, offset: this.lastIndex, }; } getSlice(start, startLocation) { return { text: this.source.slice(start, this.index), start, startLocation, end: this.index }; } scanPunctuatorHelper() { let ch1 = this.source.charAt(this.index); switch (ch1) { // Check for most common single-character punctuators. case '.': { let ch2 = this.source.charAt(this.index + 1); if (ch2 !== '.') return TokenType.PERIOD; let ch3 = this.source.charAt(this.index + 2); if (ch3 !== '.') return TokenType.PERIOD; return TokenType.ELLIPSIS; } case '(': return TokenType.LPAREN; case ')': case ';': case ',': return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; case '{': return TokenType.LBRACE; case '}': case '[': case ']': case ':': case '?': case '~': return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; default: // "=" (U+003D) marks an assignment or comparison operator. if (this.index + 1 < this.source.length && this.source.charAt(this.index + 1) === '=') { switch (ch1) { case '=': if (this.index + 2 < this.source.length && this.source.charAt(this.index + 2) === '=') { return TokenType.EQ_STRICT; } return TokenType.EQ; case '!': if (this.index + 2 < this.source.length && this.source.charAt(this.index + 2) === '=') { return TokenType.NE_STRICT; } return TokenType.NE; case '|': return TokenType.ASSIGN_BIT_OR; case '+': return TokenType.ASSIGN_ADD; case '-': return TokenType.ASSIGN_SUB; case '*': return TokenType.ASSIGN_MUL; case '<': return TokenType.LTE; case '>': return TokenType.GTE; case '/': return TokenType.ASSIGN_DIV; case '%': return TokenType.ASSIGN_MOD; case '^': return TokenType.ASSIGN_BIT_XOR; case '&': return TokenType.ASSIGN_BIT_AND; // istanbul ignore next default: break; // failed } } } if (this.index + 1 < this.source.length) { let ch2 = this.source.charAt(this.index + 1); if (ch1 === ch2) { if (this.index + 2 < this.source.length) { let ch3 = this.source.charAt(this.index + 2); if (ch1 === '>' && ch3 === '>') { // 4-character punctuator: >>>= if (this.index + 3 < this.source.length && this.source.charAt(this.index + 3) === '=') { return TokenType.ASSIGN_SHR_UNSIGNED; } return TokenType.SHR_UNSIGNED; } if (ch1 === '<' && ch3 === '=') { return TokenType.ASSIGN_SHL; } if (ch1 === '>' && ch3 === '=') { return TokenType.ASSIGN_SHR; } if (ch1 === '*' && ch3 === '=') { return TokenType.ASSIGN_EXP; } } // Other 2-character punctuators: ++ -- << >> && || switch (ch1) { case '*': return TokenType.EXP; case '+': return TokenType.INC; case '-': return TokenType.DEC; case '<': return TokenType.SHL; case '>': return TokenType.SHR; case '&': return TokenType.AND; case '|': return TokenType.OR; // istanbul ignore next default: break; // failed } } else if (ch1 === '=' && ch2 === '>') { return TokenType.ARROW; } } return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; } // 7.7 Punctuators scanPunctuator() { let startLocation = this.getLocation(); let start = this.index; let subType = this.scanPunctuatorHelper(); this.index += subType.name.length; return { type: subType, value: subType.name, slice: this.getSlice(start, startLocation) }; } scanHexLiteral(start, startLocation) { let i = this.index; while (i < this.source.length) { let ch = this.source.charAt(i); let hex = getHexValue(ch); if (hex === -1) { break; } i++; } if (this.index === i) { throw this.createILLEGAL(); } if (i < this.source.length && isIdentifierStart(this.source.charCodeAt(i))) { throw this.createILLEGAL(); } this.index = i; let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: parseInt(slice.text.substr(2), 16), slice }; } scanBinaryLiteral(start, startLocation) { let offset = this.index - start; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch !== '0' && ch !== '1') { break; } this.index++; } if (this.index - start <= offset) { throw this.createILLEGAL(); } if (this.index < this.source.length && (isIdentifierStart(this.source.charCodeAt(this.index)) || isDecimalDigit(this.source.charCodeAt(this.index)))) { throw this.createILLEGAL(); } return { type: TokenType.NUMBER, value: parseInt(this.getSlice(start, startLocation).text.substr(offset), 2), slice: this.getSlice(start, startLocation), octal: false, noctal: false, }; } scanOctalLiteral(start, startLocation) { while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch >= '0' && ch <= '7') { this.index++; } else if (isIdentifierPart(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { break; } } if (this.index - start === 2) { throw this.createILLEGAL(); } return { type: TokenType.NUMBER, value: parseInt(this.getSlice(start, startLocation).text.substr(2), 8), slice: this.getSlice(start, startLocation), octal: false, noctal: false, }; } scanLegacyOctalLiteral(start, startLocation) { let isOctal = true; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch >= '0' && ch <= '7') { this.index++; } else if (ch === '8' || ch === '9') { isOctal = false; this.index++; } else if (isIdentifierPart(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { break; } } let slice = this.getSlice(start, startLocation); if (!isOctal) { this.eatDecimalLiteralSuffix(); return { type: TokenType.NUMBER, slice, value: +slice.text, octal: true, noctal: !isOctal, }; } return { type: TokenType.NUMBER, slice, value: parseInt(slice.text.substr(1), 8), octal: true, noctal: !isOctal, }; } scanNumericLiteral() { let ch = this.source.charAt(this.index); // assert(ch === "." || "0" <= ch && ch <= "9") let startLocation = this.getLocation(); let start = this.index; if (ch === '0') { this.index++; if (this.index < this.source.length) { ch = this.source.charAt(this.index); if (ch === 'x' || ch === 'X') { this.index++; return this.scanHexLiteral(start, startLocation); } else if (ch === 'b' || ch === 'B') { this.index++; return this.scanBinaryLiteral(start, startLocation); } else if (ch === 'o' || ch === 'O') { this.index++; return this.scanOctalLiteral(start, startLocation); } else if (ch >= '0' && ch <= '9') { return this.scanLegacyOctalLiteral(start, startLocation); } } else { let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } } else if (ch !== '.') { // Must be "1".."9" ch = this.source.charAt(this.index); while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } ch = this.source.charAt(this.index); } } this.eatDecimalLiteralSuffix(); if (this.index !== this.source.length && isIdentifierStart(this.source.charCodeAt(this.index))) { throw this.createILLEGAL(); } let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } eatDecimalLiteralSuffix() { let ch = this.source.charAt(this.index); if (ch === '.') { this.index++; if (this.index === this.source.length) { return; } ch = this.source.charAt(this.index); while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { return; } ch = this.source.charAt(this.index); } } // EOF not reached here if (ch === 'e' || ch === 'E') { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); if (ch === '+' || ch === '-') { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); } if (ch >= '0' && ch <= '9') { while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { break; } ch = this.source.charAt(this.index); } } else { throw this.createILLEGAL(); } } } scanStringEscape(str, octal) { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } let ch = this.source.charAt(this.index); if (isLineTerminator(ch.charCodeAt(0))) { this.index++; if (ch === '\r' && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; this.line++; } else { switch (ch) { case 'n': str += '\n'; this.index++; break; case 'r': str += '\r'; this.index++; break; case 't': str += '\t'; this.index++; break; case 'u': case 'x': { let unescaped; this.index++; if (this.index >= this.source.length) { throw this.createILLEGAL(); } unescaped = ch === 'u' ? this.scanUnicode() : this.scanHexEscape2(); if (unescaped < 0) { throw this.createILLEGAL(); } str += fromCodePoint(unescaped); break; } case 'b': str += '\b'; this.index++; break; case 'f': str += '\f'; this.index++; break; case 'v': str += '\u000B'; this.index++; break; default: if (ch >= '0' && ch <= '7') { let octalStart = this.index; let octLen = 1; // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if (ch >= '0' && ch <= '3') { octLen = 0; } let code = 0; while (octLen < 3 && ch >= '0' && ch <= '7') { this.index++; if (octLen > 0 || ch !== '0') { octal = this.source.slice(octalStart, this.index); } code *= 8; code += ch - '0'; octLen++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); } if (code === 0 && octLen === 1 && (ch === '8' || ch === '9')) { octal = this.source.slice(octalStart, this.index + 1); } str += String.fromCharCode(code); } else if (ch === '8' || ch === '9') { throw this.createILLEGAL(); } else { str += ch; this.index++; } } } return [str, octal]; } // 7.8.4 String Literals scanStringLiteral() { let str = ''; let quote = this.source.charAt(this.index); // assert((quote === "\"" || quote === """), "String literal must starts with a quote") let startLocation = this.getLocation(); let start = this.index; this.index++; let octal = null; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === quote) { this.index++; return { type: TokenType.STRING, slice: this.getSlice(start, startLocation), str, octal }; } else if (ch === '\\') { [str, octal] = this.scanStringEscape(str, octal); } else if (isLineTerminator(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { str += ch; this.index++; } } throw this.createILLEGAL(); } scanTemplateElement() { let startLocation = this.getLocation(); let start = this.index; this.index++; while (this.index < this.source.length) { let ch = this.source.charCodeAt(this.index); switch (ch) { case 0x60: { // ` this.index++; return { type: TokenType.TEMPLATE, tail: true, slice: this.getSlice(start, startLocation) }; } case 0x24: { // $ if (this.source.charCodeAt(this.index + 1) === 0x7B) { // { this.index += 2; return { type: TokenType.TEMPLATE, tail: false, slice: this.getSlice(start, startLocation) }; } this.index++; break; } case 0x5C: { // \\ let octal = this.scanStringEscape('', null)[1]; if (octal != null) { throw this.createError(ErrorMessages.NO_OCTALS_IN_TEMPLATES); } break; } case 0x0D: { // \r this.line++; this.index++; if (this.index < this.source.length && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; break; } case 0x0A: // \r case 0x2028: case 0x2029: { this.line++; this.index++; this.lineStart = this.index; break; } default: this.index++; } } throw this.createILLEGAL(); } scanRegExp(str) { let startLocation = this.getLocation(); let start = this.index; let terminated = false; let classMarker = false; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === '\\') { str += ch; this.index++; ch = this.source.charAt(this.index); // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } str += ch; this.index++; } else if (isLineTerminator(ch.charCodeAt(0))) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } else { if (classMarker) { if (ch === ']') { classMarker = false; } } else if (ch === '/') { terminated = true; str += ch; this.index++; break; } else if (ch === '[') { classMarker = true; } str += ch; this.index++; } } if (!terminated) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === '\\') { throw this.createError(ErrorMessages.INVALID_REGEXP_FLAGS); } if (!isIdentifierPart(ch.charCodeAt(0))) { break; } this.index++; str += ch; } return { type: TokenType.REGEXP, value: str, slice: this.getSlice(start, startLocation) }; } advance() { let startLocation = this.getLocation(); this.lastIndex = this.index; this.lastLine = this.line; this.lastLineStart = this.lineStart; this.skipComment(); this.startIndex = this.index; this.startLine = this.line; this.startLineStart = this.lineStart; if (this.lastIndex === 0) { this.lastIndex = this.index; this.lastLine = this.line; this.lastLineStart = this.lineStart; } if (this.index >= this.source.length) { return { type: TokenType.EOS, slice: this.getSlice(this.index, startLocation) }; } let charCode = this.source.charCodeAt(this.index); if (charCode < 0x80) { if (PUNCTUATOR_START[charCode]) { return this.scanPunctuator(); } if (isIdentifierStart(charCode) || charCode === 0x5C /* backslash (\) */) { return this.scanIdentifier(); } // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (charCode === 0x2E) { if (this.index + 1 < this.source.length && isDecimalDigit(this.source.charCodeAt(this.index + 1))) { return this.scanNumericLiteral(); } return this.scanPunctuator(); } // String literal starts with single quote (U+0027) or double quote (U+0022). if (charCode === 0x27 || charCode === 0x22) { return this.scanStringLiteral(); } // Template literal starts with back quote (U+0060) if (charCode === 0x60) { return this.scanTemplateElement(); } if (charCode /* "0" */ >= 0x30 && charCode <= 0x39 /* "9" */) { return this.scanNumericLiteral(); } // Slash (/) U+002F can also start a regex. throw this.createILLEGAL(); } else { if (isIdentifierStart(charCode) || charCode >= 0xD800 && charCode <= 0xDBFF) { return this.scanIdentifier(); } throw this.createILLEGAL(); } } eof() { return this.lookahead.type === TokenType.EOS; } lex() { let prevToken = this.lookahead; this.lookahead = this.advance(); this.tokenIndex++; return prevToken; } }
shapesecurity/shift-parser-js
src/tokenizer.js
JavaScript
apache-2.0
46,755
import React from 'react'; // eslint-disable-next-line import/no-extraneous-dependencies import { mount } from 'enzyme'; // eslint-disable-next-line import/no-extraneous-dependencies import { FacetedSearchIcon } from './FacetedSearchIcon.component'; import getDefaultT from '../../translate'; const t = getDefaultT(); describe('FacetedSearchIcon', () => { it('should render by default', () => { // given const props = { onClick: jest.fn(), t, }; // when const wrapper = mount(<FacetedSearchIcon {...props} />); // then expect(wrapper.html()).toMatchSnapshot(); }); it('should render with button active when active props true', () => { // given const props = { active: true, onClick: jest.fn(), t, }; // when const wrapper = mount(<FacetedSearchIcon {...props} />); // then expect(wrapper.find('button[aria-label="Show faceted search"]').prop('className')).toEqual( 'faceted-search-icon theme-faceted-search-icon tc-icon-toggle theme-tc-icon-toggle theme-active active btn btn-link', ); }); it('should call onClick when trigger click', () => { // given const onClick = jest.fn(); const props = { active: true, onClick, t, }; // when const wrapper = mount(<FacetedSearchIcon {...props} />); wrapper.find('button[aria-label="Show faceted search"]').simulate('click'); // then expect(onClick).toHaveBeenCalled(); expect(onClick.mock.calls.length).toBe(1); }); it('should render the button in loading mode', () => { // given const props = { loading: true, onClick: jest.fn(), t, }; // when const wrapper = mount(<FacetedSearchIcon {...props} />); // then expect(wrapper.html()).toMatchSnapshot(); }); });
Talend/ui
packages/faceted-search/src/components/FacetedSearchIcon/FacetedSearchIcon.component.test.js
JavaScript
apache-2.0
1,710
var _ = require('underscore'); var vcr = require('nock-vcr-recorder-mocha'); var Sdk = require('./../../../lib/clc-sdk.js'); var compute = new Sdk('cloud_user', 'cloud_user_password').computeServices(); var assert = require('assert'); var ServerBuilder = require('./../server-builder.js'); vcr.describe('Create server operation [UNIT]', function () { var DataCenter = compute.DataCenter; var Server = compute.Server; var Group = compute.Group; var builder = new ServerBuilder(compute); it('Should create new server', function (done) { this.timeout(10000); builder.createCentOsVm({ customFields: [ { name: "Type", value: 0 } ] }) .then(builder.deleteServer(done)); }); it('Should create new hyperscale server with anti-affinity policy', function (done) { this.timeout(10000); builder.createCentOsVm({ description: "My hyperscale server", group: { dataCenter: DataCenter.CA_TORONTO_2, name: Group.DEFAULT }, template: { dataCenter: DataCenter.CA_TORONTO_2, operatingSystem: { family: compute.OsFamily.CENTOS, version: "6", architecture: compute.Machine.Architecture.X86_64 } }, machine: { cpu: 1, memoryGB: 1, disks: [ { size: 2 }, { path: "/data", size: 4 } ], antiAffinity: { nameContains: 'policy' } }, type: Server.HYPERSCALE }) .then(compute.servers().findSingle) .then(assertThatServerIsHyperscale) .then(assertThatAntiAffinityPolicyIsSpecified) .then(builder.deleteServer(done)); }); function assertThatServerIsHyperscale(server) { assert.equal(server.type, Server.HYPERSCALE); assert.equal(server.storageType, Server.StorageType.HYPERSCALE); return server; } function assertThatAntiAffinityPolicyIsSpecified(server) { return compute.policies().antiAffinity() .findSingle({ dataCenterId: server.locationId.toLowerCase(), nameContains: 'policy' }) .then(function(policy) { var serverLink = _.findWhere(policy.links, {rel: 'server', id: server.id}); assert(!_.isUndefined(serverLink)); return server; }); } });
CenturyLinkCloud/clc-node-sdk
test/compute-services/servers/create-server-test.js
JavaScript
apache-2.0
2,709
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview tmpnetwork.js contains some temporary networking functions * for browserchannel which will be moved at a later date. */ /** * Namespace for BrowserChannel */ goog.provide('goog.net.tmpnetwork'); goog.require('goog.Uri'); goog.require('goog.net.ChannelDebug'); /** * Default timeout to allow for google.com pings. * @type {number} */ goog.net.tmpnetwork.GOOGLECOM_TIMEOUT = 10000; goog.net.tmpnetwork.testGoogleCom = function(callback, opt_imageUri) { // We need to add a 'rand' to make sure the response is not fulfilled // by browser cache. var uri = opt_imageUri; if (!uri) { uri = new goog.Uri('//www.google.com/images/cleardot.gif'); uri.makeUnique(); } goog.net.tmpnetwork.testLoadImage(uri.toString(), goog.net.tmpnetwork.GOOGLECOM_TIMEOUT, callback); }; /** * Test loading the given image, retrying if necessary. * @param {string} url URL to the iamge. * @param {number} timeout Milliseconds before giving up. * @param {Function} callback Function to call with results. * @param {number} retries The number of times to retry. * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds * between retries - defaults to 0. */ goog.net.tmpnetwork.testLoadImageWithRetries = function(url, timeout, callback, retries, opt_pauseBetweenRetriesMS) { var channelDebug = new goog.net.ChannelDebug(); channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS); if (retries == 0) { // no more retries, give up callback(false); return; } var pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0; retries--; goog.net.tmpnetwork.testLoadImage(url, timeout, function(succeeded) { if (succeeded) { callback(true); } else { // try again goog.global.setTimeout(function() { goog.net.tmpnetwork.testLoadImageWithRetries(url, timeout, callback, retries, pauseBetweenRetries); }, pauseBetweenRetries); } }); }; /** * Test loading the given image. * @param {string} url URL to the iamge. * @param {number} timeout Milliseconds before giving up. * @param {Function} callback Function to call with results. */ goog.net.tmpnetwork.testLoadImage = function(url, timeout, callback) { var channelDebug = new goog.net.ChannelDebug(); channelDebug.debug('TestLoadImage: loading ' + url); var img = new Image(); var timer = null; createHandler = function(result, message) { return function() { try { channelDebug.debug('TestLoadImage: ' + message); goog.net.tmpnetwork.clearImageCallbacks_(img); goog.global.clearTimeout(timer); callback(result); } catch (e) { channelDebug.dumpException(e); } }; }; img.onload = createHandler(true, 'loaded'); img.onerror = createHandler(false, 'error'); img.onabort = createHandler(false, 'abort'); img.ontimeout = createHandler(false, 'timeout'); timer = goog.global.setTimeout(function() { if (img.ontimeout) { img.ontimeout(); } }, timeout); img.src = url; }; /** * Clear handlers to avoid memory leaks. * @param {Image} img The image to clear handlers from. * @private */ goog.net.tmpnetwork.clearImageCallbacks_ = function(img) { // NOTE(user): Nullified individually to avoid compiler warnings // (BUG 658126) img.onload = null; img.onerror = null; img.onabort = null; img.ontimeout = null; };
Digaku/closure-library
closure/goog/net/tmpnetwork.js
JavaScript
apache-2.0
4,070
/** * Created by chensheng on 15/8/3. */ 'use strict'; (function (ns) { ns.Publisher = tp.view.Loader.extend({ events: { 'change [name=publisher_type]': 'publisherType_changeHandler', 'change [name=province]': 'province_changeHandler' }, initialize: function (options) { tp.view.Loader.prototype.initialize.call(this, options); this.optionTemplate = Handlebars.compile('{{#each cities}}<option value="{{.}}">{{.}}</option>{{/each}}'); }, render: function () { tp.view.Loader.prototype.render.call(this); var province = this.model.get('province'); this.$('[name=province]').val(province); this.renderCities(this.model.options.provinces.indexOf(province)); }, renderCities: function (province) { var cities = this.model.options.cities; this.$('[name=city]').html(this.optionTemplate({cities: cities[province]})); }, province_changeHandler: function (event) { var province = event.target.selectedIndex; this.renderCities(province); }, publisherType_changeHandler: function (event) { var className = $(event.currentTarget).data('class'); this.$('.personal, .corp').not('.' + className).addClass('hide'); this.$('.' + className).removeClass('hide'); } }); }(Nervenet.createNameSpace('admin.page')));
RyanTech/admin-v5
js/page/Publisher.js
JavaScript
apache-2.0
1,341
/* * File: app/controller/footerController.js */ Ext.define('webapp.controller.footerController', { extend: 'Ext.app.Controller', refs: { footerLabel2: '#footerLabel2' }, onLaunch: function() { /** * address Label click event를 catch 하도록 설정 */ this.getFooterLabel2().getEl().on('click', function() { var mapwin; // create the window on the first click and reuse on subsequent clicks if(mapwin) { mapwin.show(); } else { mapwin = Ext.create('Ext.window.Window', { autoShow: true, layout: 'fit', title: 'OSCI Location', closeAction: 'hide', width:600, height:500, border: true, x: 40, y: 60, items: { xtype: 'gmappanel', center: { geoCodeAddr: '서울특별시 서초구 서초2동 1337' }, markers: [{ lat: 37.492359, lng: 127.028590, title: 'Gangnam Mirae Tower 805, Saimdang-ro 174(Seocho-dong), Seocho-gu, Seoul, Korea', listeners: { click: function(e){ Ext.Msg.alert('Address', 'Gangnam Mirae Tower 805, Saimdang-ro 174(Seocho-dong), Seocho-gu, Seoul, Korea'); } } }] } }); } }); // Add below script to index.html manually // <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> } });
OpenSourceConsulting/athena-meerkat
console/app/controller/footerController.js
JavaScript
apache-2.0
1,951
$.STRATUS = function (){ var _init = function () { $('#logout').click(_logout) }; var _logout = function (event) { event.preventDefault(); // Workaround to logout user // As HTTP is state-less there is no cross-browser clean way to do $.get(location.href.replace('://', '://x-pdisk-logout@')); }; return { init: _init, }; }(); $(document).ready($.STRATUS.init);
StratusLab/storage
pdisk-server/war/src/main/webapp/media/js/stratuslab.js
JavaScript
apache-2.0
387
/*! * ${copyright} */ sap.ui.define([ "sap/ui/test/_OpaLogger", "sap/ui/base/ManagedObject" ], function (_OpaLogger, ManagedObject) { "use strict"; /** * @class Matchers for Opa5 - needs to implement an isMatching function that returns a boolean and will get a control instance as parameter * @abstract * @extends sap.ui.base.ManagedObject * @public * @name sap.ui.test.matchers.Matcher * @author SAP SE * @since 1.23 */ var Matcher = ManagedObject.extend("sap.ui.test.matchers.Matcher", { metadata : { publicMethods : [ "isMatching" ] }, constructor: function () { this._oLogger = _OpaLogger.getLogger(this.getMetadata().getName()); return ManagedObject.prototype.constructor.apply(this, arguments); }, /** * Checks if the matcher is matching - will get an instance of sap.ui.core.Control as parameter. * * Should be overwritten by subclasses * * @param {sap.ui.core.Control} oControl the control that is checked by the matcher * @return {boolean} true if the Control is matching the condition of the matcher * @protected * @name sap.ui.test.matchers.Matcher#isMatching * @function */ isMatching : function (oControl) { return true; }, /** * @return {object} window of the application under test, or the current window if OPA5 is not loaded * Note: declared matchers are instanciated in the app context (by MatcherFactory) * while users instanciate matchers in the test context (in a waitFor) * @private * @function */ _getApplicationWindow: function () { if (sap.ui.test && sap.ui.test.Opa5) { // matcher context === test context, because Opa5 is loadded return sap.ui.test.Opa5.getWindow(); } else { // matcher context === app context return window; } } }); return Matcher; });
SAP/openui5
src/sap.ui.core/src/sap/ui/test/matchers/Matcher.js
JavaScript
apache-2.0
1,818
var CaoTest = CaoTest || {} //把一个对象的自有属性copy到一个新的对象里 浅克隆 CaoTest.clone = function { objClone = {}; each(obj, function(value, key) { if (obj.hasOwnProperty(key)) objClone[key] = value; }); return objClone; }
jcto/DBWeb
utils/clone.js
JavaScript
apache-2.0
255
/* @flow strict-local */ import { addBreadcrumb } from '@sentry/react-native'; import type { Narrow, Stream, User } from '../types'; import { topicNarrow, streamNarrow, groupNarrow, specialNarrow } from './narrow'; import { isUrlOnRealm } from './url'; const getPathsFromUrl = (url: string = '', realm: string) => { const paths = url .split(realm) .pop() .split('#narrow/') .pop() .split('/'); if (paths.length > 0 && paths[paths.length - 1] === '') { // url ends with / paths.splice(-1, 1); } return paths; }; /** PRIVATE -- exported only for tests. */ export const isInternalLink = (url: string, realm: string): boolean => isUrlOnRealm(url, realm) ? /^(\/#narrow|#narrow)/i.test(url.split(realm).pop()) : false; /** PRIVATE -- exported only for tests. */ export const isMessageLink = (url: string, realm: string): boolean => isInternalLink(url, realm) && url.includes('near'); type LinkType = 'external' | 'home' | 'pm' | 'topic' | 'stream' | 'special'; export const getLinkType = (url: string, realm: string): LinkType => { if (!isInternalLink(url, realm)) { return 'external'; } const paths = getPathsFromUrl(url, realm); if ( (paths.length === 2 && paths[0] === 'pm-with') || (paths.length === 4 && paths[0] === 'pm-with' && paths[2] === 'near') ) { return 'pm'; } if ( (paths.length === 4 || paths.length === 6) && paths[0] === 'stream' && (paths[2] === 'subject' || paths[2] === 'topic') ) { return 'topic'; } if (paths.length === 2 && paths[0] === 'stream') { return 'stream'; } if (paths.length === 2 && paths[0] === 'is' && /^(private|starred|mentioned)/i.test(paths[1])) { return 'special'; } return 'home'; }; /** Decode a dot-encoded string. */ // The Zulip webapp uses this encoding in narrow-links: // https://github.com/zulip/zulip/blob/1577662a6/static/js/hash_util.js#L18-L25 export const decodeHashComponent = (string: string): string => { try { return decodeURIComponent(string.replace(/\./g, '%')); } catch (err) { // `decodeURIComponent` throws strikingly uninformative errors addBreadcrumb({ level: 'info', type: 'decoding', message: 'decodeHashComponent error', data: { input: string }, }); throw err; } }; /** Parse the operand of a `stream` operator, returning a stream name. */ const parseStreamOperand = (operand, streamsById): string => { // "New" (2018) format: ${stream_id}-${stream_name} . const match = /^(\d+)-/.exec(operand); if (match) { const stream = streamsById.get(parseInt(match[0], 10)); if (stream) { return stream.name; } } // Old format: just stream name. This case is relevant indefinitely, // so that links in old conversations continue to work. return decodeHashComponent(operand); }; /** Parse the operand of a `topic` or `subject` operator. */ const parseTopicOperand = operand => decodeHashComponent(operand); /** Parse the operand of a `pm-with` operator. */ const parsePmOperand = (operand, usersById) => { const recipientIds = operand.split('-')[0].split(','); const recipientEmails = []; for (let i = 0; i < recipientIds.length; ++i) { const user = usersById.get(parseInt(recipientIds[i], 10)); if (user === undefined) { return null; } recipientEmails.push(user.email); } return recipientEmails; }; export const getNarrowFromLink = ( url: string, realm: string, usersById: Map<number, User>, streamsById: Map<number, Stream>, ): Narrow | null => { const type = getLinkType(url, realm); const paths = getPathsFromUrl(url, realm); switch (type) { case 'pm': { const recipientEmails = parsePmOperand(paths[1], usersById); if (recipientEmails === null) { return null; } return groupNarrow(recipientEmails); } case 'topic': return topicNarrow(parseStreamOperand(paths[1], streamsById), parseTopicOperand(paths[3])); case 'stream': return streamNarrow(parseStreamOperand(paths[1], streamsById)); case 'special': return specialNarrow(paths[1]); default: return null; } }; export const getMessageIdFromLink = (url: string, realm: string): number => { const paths = getPathsFromUrl(url, realm); return isMessageLink(url, realm) ? parseInt(paths[paths.lastIndexOf('near') + 1], 10) : 0; };
vishwesh3/zulip-mobile
src/utils/internalLinks.js
JavaScript
apache-2.0
4,379
// (C) Copyright 2014 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import FormattedMessage from './FormattedMessage'; const CLASS_ROOT = "legend"; export default class Legend extends Component { constructor(props) { super(props); this._onActive = this._onActive.bind(this); this.state = {activeIndex: this.props.activeIndex}; } componentWillReceiveProps (newProps) { this.setState({activeIndex: newProps.activeIndex}); } _onActive (index) { this.setState({activeIndex: index}); if (this.props.onActive) { this.props.onActive(index); } } _itemColorIndex (item, index) { return item.colorIndex || ('graph-' + (index + 1)); } render () { var classes = [CLASS_ROOT]; if (this.props.series.length === 1) { classes.push(CLASS_ROOT + "--single"); } if (this.props.className) { classes.push(this.props.className); } var totalValue = 0; var items = this.props.series.map(function (item, index) { var legendClasses = [CLASS_ROOT + "__item"]; if (index === this.state.activeIndex) { legendClasses.push(CLASS_ROOT + "__item--active"); } if (item.onClick) { legendClasses.push(CLASS_ROOT + "__item--clickable"); } var colorIndex = this._itemColorIndex(item, index); totalValue += item.value; var valueClasses = [CLASS_ROOT + "__item-value"]; if (1 === this.props.series.length) { valueClasses.push("large-number-font"); } var swatch; if (item.hasOwnProperty('colorIndex')) { swatch = ( <svg className={CLASS_ROOT + "__item-swatch color-index-" + colorIndex} viewBox="0 0 12 12"> <path className={item.className} d="M 5 0 l 0 12" /> </svg> ); } var label; if (item.hasOwnProperty('label')) { label = ( <span className={CLASS_ROOT + "__item-label"}>{item.label}</span> ); } var value; if (item.hasOwnProperty('value')) { value = ( <span className={valueClasses.join(' ')}> {item.value} <span className={CLASS_ROOT + "__item-units"}> {item.units || this.props.units} </span> </span> ); } return ( <li key={item.label || index} className={legendClasses.join(' ')} onClick={item.onClick} onMouseOver={this._onActive.bind(this, index)} onMouseOut={this._onActive.bind(this, null)} > {swatch} {label} {value} </li> ); }, this); // build legend from bottom to top, to align with Meter bar stacking items.reverse(); var total = null; if (this.props.total && this.props.series.length > 1) { total = ( <li className={CLASS_ROOT + "__total"}> <span className={CLASS_ROOT + "__total-label"}> <FormattedMessage id="Total" defaultMessage="Total" /> </span> <span className={CLASS_ROOT + "__total-value"}> {totalValue} <span className={CLASS_ROOT + "__total-units"}>{this.props.units}</span> </span> </li> ); } return ( <ol className={classes.join(' ')} role="presentation"> {items.reverse()} {total} </ol> ); } } Legend.propTypes = { activeIndex: PropTypes.number, onActive: PropTypes.func, series: PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.string, value: PropTypes.number, units: PropTypes.string, colorIndex: PropTypes.oneOfType([ PropTypes.number, // 1-6 PropTypes.string // status ]), onClick: PropTypes.func })).isRequired, total: PropTypes.bool, units: PropTypes.string, value: PropTypes.number };
samogami/grommet
src/js/components/Legend.js
JavaScript
apache-2.0
3,868
const db = require('./db') ; let schema = new db.Schema({ owner: { type: String, indexed: true, required: true }, // user.id name: { type: String, required: true }, path: { type: String, unique: true, required: true }, info: db.Schema.Types.Mixed, content: db.Schema.Types.Mixed }, { timestamps: db.timestamps }); module.exports = db.model('Resource', schema);
arthurmilliken/gateway
models/resource.js
JavaScript
apache-2.0
374
/*jshint browser: true */ /*jshint unused: false */ /*global arangoHelper, _, $, window, arangoHelper, templateEngine, Joi, btoa */ (function() { "use strict"; window.DocumentsView = window.PaginationView.extend({ filters : { "0" : true }, filterId : 0, paginationDiv : "#documentsToolbarF", idPrefix : "documents", addDocumentSwitch: true, activeFilter: false, lastCollectionName: undefined, restoredFilters: [], editMode: false, allowUpload: false, el: '#content', table: '#documentsTableID', template: templateEngine.createTemplate("documentsView.ejs"), collectionContext : { prev: null, next: null }, editButtons: ["#deleteSelected", "#moveSelected"], initialize : function () { this.documentStore = this.options.documentStore; this.collectionsStore = this.options.collectionsStore; this.tableView = new window.TableView({ el: this.table, collection: this.collection }); this.tableView.setRowClick(this.clicked.bind(this)); this.tableView.setRemoveClick(this.remove.bind(this)); }, setCollectionId : function (colid, pageid) { this.collection.setCollection(colid); var type = arangoHelper.collectionApiType(colid); this.pageid = pageid; this.type = type; this.checkCollectionState(); this.collection.getDocuments(this.getDocsCallback.bind(this)); this.collectionModel = this.collectionsStore.get(colid); }, getDocsCallback: function() { //Hide first/last pagination $('#documents_last').css("visibility", "hidden"); $('#documents_first').css("visibility", "hidden"); this.drawTable(); this.renderPaginationElements(); }, events: { "click #collectionPrev" : "prevCollection", "click #collectionNext" : "nextCollection", "click #filterCollection" : "filterCollection", "click #markDocuments" : "editDocuments", "click #indexCollection" : "indexCollection", "click #importCollection" : "importCollection", "click #exportCollection" : "exportCollection", "click #filterSend" : "sendFilter", "click #addFilterItem" : "addFilterItem", "click .removeFilterItem" : "removeFilterItem", "click #deleteSelected" : "deleteSelectedDocs", "click #moveSelected" : "moveSelectedDocs", "click #addDocumentButton" : "addDocumentModal", "click #documents_first" : "firstDocuments", "click #documents_last" : "lastDocuments", "click #documents_prev" : "prevDocuments", "click #documents_next" : "nextDocuments", "click #confirmDeleteBtn" : "confirmDelete", "click .key" : "nop", "keyup" : "returnPressedHandler", "keydown .queryline input" : "filterValueKeydown", "click #importModal" : "showImportModal", "click #resetView" : "resetView", "click #confirmDocImport" : "startUpload", "click #exportDocuments" : "startDownload", "change #newIndexType" : "selectIndexType", "click #createIndex" : "createIndex", "click .deleteIndex" : "prepDeleteIndex", "click #confirmDeleteIndexBtn" : "deleteIndex", "click #documentsToolbar ul" : "resetIndexForms", "click #indexHeader #addIndex" : "toggleNewIndexView", "click #indexHeader #cancelIndex" : "toggleNewIndexView", "change #documentSize" : "setPagesize", "change #docsSort" : "setSorting" }, showSpinner: function() { $('#uploadIndicator').show(); }, hideSpinner: function() { $('#uploadIndicator').hide(); }, showImportModal: function() { $("#docImportModal").modal('show'); }, hideImportModal: function() { $("#docImportModal").modal('hide'); }, setPagesize: function() { var size = $('#documentSize').find(":selected").val(); this.collection.setPagesize(size); this.collection.getDocuments(this.getDocsCallback.bind(this)); }, setSorting: function() { var sortAttribute = $('#docsSort').val(); if (sortAttribute === '' || sortAttribute === undefined || sortAttribute === null) { sortAttribute = '_key'; } this.collection.setSort(sortAttribute); }, returnPressedHandler: function(event) { if (event.keyCode === 13 && $(event.target).is($('#docsSort'))) { this.collection.getDocuments(this.getDocsCallback.bind(this)); } if (event.keyCode === 13) { if ($("#confirmDeleteBtn").attr("disabled") === false) { this.confirmDelete(); } } }, toggleNewIndexView: function () { $('#indexEditView').toggle("fast"); $('#newIndexView').toggle("fast"); this.resetIndexForms(); }, nop: function(event) { event.stopPropagation(); }, resetView: function () { //clear all input/select - fields $('input').val(''); $('select').val('=='); this.removeAllFilterItems(); $('#documentSize').val(this.collection.getPageSize()); $('#documents_last').css("visibility", "visible"); $('#documents_first').css("visibility", "visible"); this.addDocumentSwitch = true; this.collection.resetFilter(); this.collection.loadTotal(); this.restoredFilters = []; //for resetting json upload this.allowUpload = false; this.files = undefined; this.file = undefined; $('#confirmDocImport').attr("disabled", true); this.markFilterToggle(); this.collection.getDocuments(this.getDocsCallback.bind(this)); }, startDownload: function() { var query = this.collection.buildDownloadDocumentQuery(); if (query !== '' || query !== undefined || query !== null) { window.open(encodeURI("query/result/download/" + btoa(JSON.stringify(query)))); } else { arangoHelper.arangoError("Document error", "could not download documents"); } }, startUpload: function () { var result; if (this.allowUpload === true) { this.showSpinner(); result = this.collection.uploadDocuments(this.file); if (result !== true) { this.hideSpinner(); this.hideImportModal(); this.resetView(); arangoHelper.arangoError(result); return; } this.hideSpinner(); this.hideImportModal(); this.resetView(); return; } }, uploadSetup: function () { var self = this; $('#importDocuments').change(function(e) { self.files = e.target.files || e.dataTransfer.files; self.file = self.files[0]; $('#confirmDocImport').attr("disabled", false); self.allowUpload = true; }); }, buildCollectionLink : function (collection) { return "collection/" + encodeURIComponent(collection.get('name')) + '/documents/1'; }, /* prevCollection : function () { if (this.collectionContext.prev !== null) { $('#collectionPrev').parent().removeClass('disabledPag'); window.App.navigate( this.buildCollectionLink( this.collectionContext.prev ), { trigger: true } ); } else { $('#collectionPrev').parent().addClass('disabledPag'); } }, nextCollection : function () { if (this.collectionContext.next !== null) { $('#collectionNext').parent().removeClass('disabledPag'); window.App.navigate( this.buildCollectionLink( this.collectionContext.next ), { trigger: true } ); } else { $('#collectionNext').parent().addClass('disabledPag'); } },*/ markFilterToggle: function () { if (this.restoredFilters.length > 0) { $('#filterCollection').addClass('activated'); } else { $('#filterCollection').removeClass('activated'); } }, //need to make following functions automatically! editDocuments: function () { $('#indexCollection').removeClass('activated'); $('#importCollection').removeClass('activated'); $('#exportCollection').removeClass('activated'); this.markFilterToggle(); $('#markDocuments').toggleClass('activated'); this.changeEditMode(); $('#filterHeader').hide(); $('#importHeader').hide(); $('#indexHeader').hide(); $('#editHeader').slideToggle(200); $('#exportHeader').hide(); }, filterCollection : function () { $('#indexCollection').removeClass('activated'); $('#importCollection').removeClass('activated'); $('#exportCollection').removeClass('activated'); $('#markDocuments').removeClass('activated'); this.changeEditMode(false); this.markFilterToggle(); this.activeFilter = true; $('#importHeader').hide(); $('#indexHeader').hide(); $('#editHeader').hide(); $('#exportHeader').hide(); $('#filterHeader').slideToggle(200); var i; for (i in this.filters) { if (this.filters.hasOwnProperty(i)) { $('#attribute_name' + i).focus(); return; } } }, exportCollection: function () { $('#indexCollection').removeClass('activated'); $('#importCollection').removeClass('activated'); $('#filterHeader').removeClass('activated'); $('#markDocuments').removeClass('activated'); this.changeEditMode(false); $('#exportCollection').toggleClass('activated'); this.markFilterToggle(); $('#exportHeader').slideToggle(200); $('#importHeader').hide(); $('#indexHeader').hide(); $('#filterHeader').hide(); $('#editHeader').hide(); }, importCollection: function () { this.markFilterToggle(); $('#indexCollection').removeClass('activated'); $('#markDocuments').removeClass('activated'); this.changeEditMode(false); $('#importCollection').toggleClass('activated'); $('#exportCollection').removeClass('activated'); $('#importHeader').slideToggle(200); $('#filterHeader').hide(); $('#indexHeader').hide(); $('#editHeader').hide(); $('#exportHeader').hide(); }, indexCollection: function () { this.markFilterToggle(); $('#importCollection').removeClass('activated'); $('#exportCollection').removeClass('activated'); $('#markDocuments').removeClass('activated'); this.changeEditMode(false); $('#indexCollection').toggleClass('activated'); $('#newIndexView').hide(); $('#indexEditView').show(); $('#indexHeader').slideToggle(200); $('#importHeader').hide(); $('#editHeader').hide(); $('#filterHeader').hide(); $('#exportHeader').hide(); }, changeEditMode: function (enable) { if (enable === false || this.editMode === true) { $('#documentsTableID tbody tr').css('cursor', 'default'); $('.deleteButton').fadeIn(); $('.addButton').fadeIn(); $('.selected-row').removeClass('selected-row'); this.editMode = false; this.tableView.setRowClick(this.clicked.bind(this)); } else { $('#documentsTableID tbody tr').css('cursor', 'copy'); $('.deleteButton').fadeOut(); $('.addButton').fadeOut(); $('.selectedCount').text(0); this.editMode = true; this.tableView.setRowClick(this.editModeClick.bind(this)); } }, getFilterContent: function () { var filters = [ ]; var i; for (i in this.filters) { if (this.filters.hasOwnProperty(i)) { var value = $('#attribute_value' + i).val(); try { value = JSON.parse(value); } catch (err) { value = String(value); } if ($('#attribute_name' + i).val() !== ''){ filters.push({ attribute : $('#attribute_name'+i).val(), operator : $('#operator'+i).val(), value : value }); } } } return filters; }, sendFilter : function () { this.restoredFilters = this.getFilterContent(); var self = this; this.collection.resetFilter(); this.addDocumentSwitch = false; _.each(this.restoredFilters, function (f) { if (f.operator !== undefined) { self.collection.addFilter(f.attribute, f.operator, f.value); } }); this.collection.setToFirst(); this.collection.getDocuments(this.getDocsCallback.bind(this)); this.markFilterToggle(); }, restoreFilter: function () { var self = this, counter = 0; this.filterId = 0; $('#docsSort').val(this.collection.getSort()); _.each(this.restoredFilters, function (f) { //change html here and restore filters if (counter !== 0) { self.addFilterItem(); } if (f.operator !== undefined) { $('#attribute_name' + counter).val(f.attribute); $('#operator' + counter).val(f.operator); $('#attribute_value' + counter).val(f.value); } counter++; //add those filters also to the collection self.collection.addFilter(f.attribute, f.operator, f.value); }); }, addFilterItem : function () { // adds a line to the filter widget var num = ++this.filterId; $('#filterHeader').append(' <div class="queryline querylineAdd">'+ '<input id="attribute_name' + num + '" type="text" placeholder="Attribute name">'+ '<select name="operator" id="operator' + num + '" class="filterSelect">'+ ' <option value="==">==</option>'+ ' <option value="!=">!=</option>'+ ' <option value="&lt;">&lt;</option>'+ ' <option value="&lt;=">&lt;=</option>'+ ' <option value="&gt;=">&gt;=</option>'+ ' <option value="&gt;">&gt;</option>'+ '</select>'+ '<input id="attribute_value' + num + '" type="text" placeholder="Attribute value" ' + 'class="filterValue">'+ ' <a class="removeFilterItem" id="removeFilter' + num + '">' + '<i class="icon icon-minus arangoicon"></i></a></div>'); this.filters[num] = true; }, filterValueKeydown : function (e) { if (e.keyCode === 13) { this.sendFilter(); } }, removeFilterItem : function (e) { // removes line from the filter widget var button = e.currentTarget; var filterId = button.id.replace(/^removeFilter/, ''); // remove the filter from the list delete this.filters[filterId]; delete this.restoredFilters[filterId]; // remove the line from the DOM $(button.parentElement).remove(); }, removeAllFilterItems : function () { var childrenLength = $('#filterHeader').children().length; var i; for (i = 1; i <= childrenLength; i++) { $('#removeFilter'+i).parent().remove(); } this.filters = { "0" : true }; this.filterId = 0; }, addDocumentModal: function () { var collid = window.location.hash.split("/")[1], buttons = [], tableContent = [], // second parameter is "true" to disable caching of collection type doctype = arangoHelper.collectionApiType(collid, true); if (doctype === 'edge') { tableContent.push( window.modalView.createTextEntry( 'new-edge-from-attr', '_from', '', "document _id: document handle of the linked vertex (incoming relation)", undefined, false, [ { rule: Joi.string().required(), msg: "No _from attribute given." } ] ) ); tableContent.push( window.modalView.createTextEntry( 'new-edge-to', '_to', '', "document _id: document handle of the linked vertex (outgoing relation)", undefined, false, [ { rule: Joi.string().required(), msg: "No _to attribute given." } ] ) ); tableContent.push( window.modalView.createTextEntry( 'new-edge-key-attr', '_key', undefined, "the edges unique key(optional attribute, leave empty for autogenerated key", 'is optional: leave empty for autogenerated key', false, [ {/*optional validation rules for joi*/} ] ) ); buttons.push( window.modalView.createSuccessButton('Create', this.addEdge.bind(this)) ); window.modalView.show( 'modalTable.ejs', 'Create edge', buttons, tableContent ); return; } else { tableContent.push( window.modalView.createTextEntry( 'new-document-key-attr', '_key', undefined, "the documents unique key(optional attribute, leave empty for autogenerated key", 'is optional: leave empty for autogenerated key', false, [ {/*optional validation rules for joi*/} ] ) ); buttons.push( window.modalView.createSuccessButton('Create', this.addDocument.bind(this)) ); window.modalView.show( 'modalTable.ejs', 'Create document', buttons, tableContent ); } }, addEdge: function () { var collid = window.location.hash.split("/")[1]; var from = $('.modal-body #new-edge-from-attr').last().val(); var to = $('.modal-body #new-edge-to').last().val(); var key = $('.modal-body #new-edge-key-attr').last().val(); var result; if (key !== '' || key !== undefined) { result = this.documentStore.createTypeEdge(collid, from, to, key); } else { result = this.documentStore.createTypeEdge(collid, from, to); } if (result !== false) { //$('#edgeCreateModal').modal('hide'); window.modalView.hide(); window.location.hash = "collection/"+result; } //Error else { arangoHelper.arangoError('Creating edge failed'); } }, addDocument: function() { var collid = window.location.hash.split("/")[1]; var key = $('.modal-body #new-document-key-attr').last().val(); var result; if (key !== '' || key !== undefined) { result = this.documentStore.createTypeDocument(collid, key); } else { result = this.documentStore.createTypeDocument(collid); } //Success if (result !== false) { window.modalView.hide(); window.location.hash = "collection/" + result; } else { arangoHelper.arangoError('Creating document failed'); } }, moveSelectedDocs: function() { var buttons = [], tableContent = [], toDelete = this.getSelectedDocs(); if (toDelete.length === 0) { return; } tableContent.push( window.modalView.createTextEntry( 'move-documents-to', 'Move to', '', false, 'collection-name', true, [ { rule: Joi.string().regex(/^[a-zA-Z]/), msg: "Collection name must always start with a letter." }, { rule: Joi.string().regex(/^[a-zA-Z0-9\-_]*$/), msg: 'Only Symbols "_" and "-" are allowed.' }, { rule: Joi.string().required(), msg: "No collection name given." } ] ) ); buttons.push( window.modalView.createSuccessButton('Move', this.confirmMoveSelectedDocs.bind(this)) ); window.modalView.show( 'modalTable.ejs', 'Move documents', buttons, tableContent ); }, confirmMoveSelectedDocs: function() { var toMove = this.getSelectedDocs(), self = this, toCollection = $('.modal-body').last().find('#move-documents-to').val(); var callback = function() { this.collection.getDocuments(this.getDocsCallback.bind(this)); $('#markDocuments').click(); window.modalView.hide(); }.bind(this); _.each(toMove, function(key) { self.collection.moveDocument(key, self.collection.collectionID, toCollection, callback); }); }, deleteSelectedDocs: function() { var buttons = [], tableContent = []; var toDelete = this.getSelectedDocs(); if (toDelete.length === 0) { return; } tableContent.push( window.modalView.createReadOnlyEntry( undefined, toDelete.length + ' documents selected', 'Do you want to delete all selected documents?', undefined, undefined, false, undefined ) ); buttons.push( window.modalView.createDeleteButton('Delete', this.confirmDeleteSelectedDocs.bind(this)) ); window.modalView.show( 'modalTable.ejs', 'Delete documents', buttons, tableContent ); }, confirmDeleteSelectedDocs: function() { var toDelete = this.getSelectedDocs(); var deleted = [], self = this; _.each(toDelete, function(key) { var result = false; if (self.type === 'document') { result = self.documentStore.deleteDocument( self.collection.collectionID, key ); if (result) { //on success deleted.push(true); self.collection.setTotalMinusOne(); } else { deleted.push(false); arangoHelper.arangoError('Document error', 'Could not delete document.'); } } else if (self.type === 'edge') { result = self.documentStore.deleteEdge(self.collection.collectionID, key); if (result === true) { //on success self.collection.setTotalMinusOne(); deleted.push(true); } else { deleted.push(false); arangoHelper.arangoError('Edge error', 'Could not delete edge'); } } }); this.collection.getDocuments(this.getDocsCallback.bind(this)); $('#markDocuments').click(); window.modalView.hide(); }, getSelectedDocs: function() { var toDelete = []; _.each($('#documentsTableID tbody tr'), function(element) { if ($(element).hasClass('selected-row')) { toDelete.push($($(element).children()[1]).find('.key').text()); } }); return toDelete; }, remove: function (a) { this.docid = $(a.currentTarget).closest("tr").attr("id").substr(4); $("#confirmDeleteBtn").attr("disabled", false); $('#docDeleteModal').modal('show'); }, confirmDelete: function () { $("#confirmDeleteBtn").attr("disabled", true); var hash = window.location.hash.split("/"); var check = hash[3]; //to_do - find wrong event handler if (check !== 'source') { this.reallyDelete(); } }, reallyDelete: function () { var self = this; var row = $(self.target).closest("tr").get(0); var deleted = false; var result; if (this.type === 'document') { result = this.documentStore.deleteDocument( this.collection.collectionID, this.docid ); if (result) { //on success this.collection.setTotalMinusOne(); deleted = true; } else { arangoHelper.arangoError('Doc error'); } } else if (this.type === 'edge') { result = this.documentStore.deleteEdge(this.collection.collectionID, this.docid); if (result === true) { //on success this.collection.setTotalMinusOne(); deleted = true; } else { arangoHelper.arangoError('Edge error'); } } if (deleted === true) { this.collection.getDocuments(this.getDocsCallback.bind(this)); $('#docDeleteModal').modal('hide'); } }, editModeClick: function(event) { var target = $(event.currentTarget); if(target.hasClass('selected-row')) { target.removeClass('selected-row'); } else { target.addClass('selected-row'); } var selected = this.getSelectedDocs(); $('.selectedCount').text(selected.length); _.each(this.editButtons, function(button) { if (selected.length > 0) { $(button).prop('disabled', false); $(button).removeClass('button-neutral'); $(button).removeClass('disabled'); if (button === "#moveSelected") { $(button).addClass('button-success'); } else { $(button).addClass('button-danger'); } } else { $(button).prop('disabled', true); $(button).addClass('disabled'); $(button).addClass('button-neutral'); if (button === "#moveSelected") { $(button).removeClass('button-success'); } else { $(button).removeClass('button-danger'); } } }); }, clicked: function (event) { var self = event.currentTarget; window.App.navigate("collection/" + this.collection.collectionID + "/" + $(self).attr("id").substr(4), true); }, drawTable: function() { this.tableView.setElement($(this.table)).render(); // we added some icons, so we need to fix their tooltips arangoHelper.fixTooltips(".icon_arangodb, .arangoicon", "top"); $(".prettify").snippet("javascript", { style: "nedit", menu: false, startText: false, transparent: true, showNum: false }); }, checkCollectionState: function() { if (this.lastCollectionName === this.collectionName) { if (this.activeFilter) { this.filterCollection(); this.restoreFilter(); } } else { if (this.lastCollectionName !== undefined) { this.collection.resetFilter(); this.collection.setSort('_key'); this.restoredFilters = []; this.activeFilter = false; } } }, render: function() { $(this.el).html(this.template.render({})); this.tableView.setElement($(this.table)).drawLoading(); this.collectionContext = this.collectionsStore.getPosition( this.collection.collectionID ); this.getIndex(); this.breadcrumb(); this.checkCollectionState(); //set last active collection name this.lastCollectionName = this.collectionName; /* if (this.collectionContext.prev === null) { $('#collectionPrev').parent().addClass('disabledPag'); } if (this.collectionContext.next === null) { $('#collectionNext').parent().addClass('disabledPag'); } */ this.uploadSetup(); $("[data-toggle=tooltip]").tooltip(); $('.upload-info').tooltip(); arangoHelper.fixTooltips(".icon_arangodb, .arangoicon", "top"); this.renderPaginationElements(); this.selectActivePagesize(); this.markFilterToggle(); return this; }, rerender : function () { this.collection.getDocuments(this.getDocsCallback.bind(this)); }, selectActivePagesize: function() { $('#documentSize').val(this.collection.getPageSize()); }, renderPaginationElements: function () { this.renderPagination(); var total = $('#totalDocuments'); if (total.length === 0) { $('#documentsToolbarFL').append( '<a id="totalDocuments" class="totalDocuments"></a>' ); total = $('#totalDocuments'); } total.html(this.collection.getTotal() + " document(s)"); }, breadcrumb: function () { this.collectionName = window.location.hash.split("/")[1]; $('#transparentHeader').append( '<div class="breadcrumb">'+ '<a class="activeBread" href="#collections">Collections</a>'+ '<span class="disabledBread">&gt</span>'+ '<a class="disabledBread">'+this.collectionName+'</a>'+ '</div>' ); }, resetIndexForms: function () { $('#indexHeader input').val('').prop("checked", false); $('#newIndexType').val('Cap').prop('selected',true); this.selectIndexType(); }, stringToArray: function (fieldString) { var fields = []; fieldString.split(',').forEach(function(field){ field = field.replace(/(^\s+|\s+$)/g,''); if (field !== '') { fields.push(field); } }); return fields; }, createIndex: function () { //e.preventDefault(); var self = this; var indexType = $('#newIndexType').val(); var result; var postParameter = {}; var fields; var unique; var sparse; switch (indexType) { case 'Cap': var size = parseInt($('#newCapSize').val(), 10) || 0; var byteSize = parseInt($('#newCapByteSize').val(), 10) || 0; postParameter = { type: 'cap', size: size, byteSize: byteSize }; break; case 'Geo': //HANDLE ARRAY building fields = $('#newGeoFields').val(); var geoJson = self.checkboxToValue('#newGeoJson'); var constraint = self.checkboxToValue('#newGeoConstraint'); var ignoreNull = self.checkboxToValue('#newGeoIgnoreNull'); postParameter = { type: 'geo', fields: self.stringToArray(fields), geoJson: geoJson, constraint: constraint, ignoreNull: ignoreNull }; break; case 'Hash': fields = $('#newHashFields').val(); unique = self.checkboxToValue('#newHashUnique'); sparse = self.checkboxToValue('#newHashSparse'); postParameter = { type: 'hash', fields: self.stringToArray(fields), unique: unique, sparse: sparse }; break; case 'Fulltext': fields = ($('#newFulltextFields').val()); var minLength = parseInt($('#newFulltextMinLength').val(), 10) || 0; postParameter = { type: 'fulltext', fields: self.stringToArray(fields), minLength: minLength }; break; case 'Skiplist': fields = $('#newSkiplistFields').val(); unique = self.checkboxToValue('#newSkiplistUnique'); sparse = self.checkboxToValue('#newSkiplistSparse'); postParameter = { type: 'skiplist', fields: self.stringToArray(fields), unique: unique, sparse: sparse }; break; } result = self.collectionModel.createIndex(postParameter); if (result === true) { $('#collectionEditIndexTable tbody tr').remove(); self.getIndex(); self.toggleNewIndexView(); self.resetIndexForms(); } else { if (result.responseText) { var message = JSON.parse(result.responseText); arangoHelper.arangoNotification("Document error", message.errorMessage); } else { arangoHelper.arangoNotification("Document error", "Could not create index."); } } }, prepDeleteIndex: function (e) { this.lastTarget = e; this.lastId = $(this.lastTarget.currentTarget). parent(). parent(). first(). children(). first(). text(); $("#indexDeleteModal").modal('show'); }, deleteIndex: function () { var result = this.collectionModel.deleteIndex(this.lastId); if (result === true) { $(this.lastTarget.currentTarget).parent().parent().remove(); } else { arangoHelper.arangoError("Could not delete index"); } $("#indexDeleteModal").modal('hide'); }, selectIndexType: function () { $('.newIndexClass').hide(); var type = $('#newIndexType').val(); $('#newIndexType'+type).show(); }, checkboxToValue: function (id) { return $(id).prop('checked'); }, getIndex: function () { this.index = this.collectionModel.getIndex(); var cssClass = 'collectionInfoTh modal-text'; if (this.index) { var fieldString = ''; var actionString = ''; $.each(this.index.indexes, function(k, v) { if (v.type === 'primary' || v.type === 'edge') { actionString = '<span class="icon_arangodb_locked" ' + 'data-original-title="No action"></span>'; } else { actionString = '<span class="deleteIndex icon_arangodb_roundminus" ' + 'data-original-title="Delete index" title="Delete index"></span>'; } if (v.fields !== undefined) { fieldString = v.fields.join(", "); } //cut index id var position = v.id.indexOf('/'); var indexId = v.id.substr(position + 1, v.id.length); var selectivity = ( v.hasOwnProperty("selectivityEstimate") ? (v.selectivityEstimate * 100).toFixed(2) + "%" : "n/a" ); var sparse = (v.hasOwnProperty("sparse") ? v.sparse : "n/a"); $('#collectionEditIndexTable').append( '<tr>' + '<th class=' + JSON.stringify(cssClass) + '>' + indexId + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + v.type + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + v.unique + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + sparse + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + selectivity + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + fieldString + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + actionString + '</th>' + '</tr>' ); }); arangoHelper.fixTooltips("deleteIndex", "left"); } } }); }());
abaditsegay/arangodb
js/apps/system/_admin/aardvark/APP/frontend/js/views/documentsView.js
JavaScript
apache-2.0
35,454
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import uiModal from 'angular-ui-bootstrap/src/modal'; import forcegraphComponent from './forcegraph.component'; let forcegraphModule = angular.module('forcegraph', [ uiRouter, uiModal ]) .config(($stateProvider) => { "ngInject"; $stateProvider .state('forcegraph', { url: '/forcegraph', component: 'forcegraph' }); }) .component('forcegraph', forcegraphComponent) .name; export default forcegraphModule;
garrettwong/GDashboard
client/app/components/d3visualizations/forcegraph/forcegraph.js
JavaScript
apache-2.0
510
/** * class for student */ 'use strict' const util = require('util') const Person = require('./person'); function Student() { Person.call(this); } // student继承自person util.inherits(Student, Person); Student.prototype.study = function() { console.log('i am learning...'); }; module.exports = Student;
EvanDylan/node
base/mods/inhertis/student.js
JavaScript
apache-2.0
318
import * as Preact from '#preact'; import {boolean, number, select, withKnobs} from '@storybook/addon-knobs'; import {withAmp} from '@ampproject/storybook-addon'; export default { title: 'amp-twitter-1_0', decorators: [withKnobs, withAmp], parameters: { extensions: [ { name: 'amp-twitter', version: '1.0', }, { name: 'amp-bind', version: '0.1', }, ], experiments: ['bento'], }, }; export const Default = () => { const tweetId = select( 'tweet id', ['1356304203044499462', '495719809695621121', '463440424141459456'], '1356304203044499462' ); const cards = boolean('show cards', true) ? undefined : 'hidden'; const conversation = boolean('show conversation', false) ? undefined : 'none'; return ( <amp-twitter width="300" height="200" data-tweetid={tweetId} data-cards={cards} data-conversation={conversation} /> ); }; export const Moments = () => { const limit = number('limit to', 2); return ( <amp-twitter data-limit={limit} data-momentid="1009149991452135424" width="300" height="200" /> ); }; export const Timelines = () => { const tweetLimit = number('limit to', 5); const timelineSourceType = select( 'source type', ['profile', 'likes', 'list', 'source', 'collection', 'url', 'widget'], 'profile' ); const timelineScreenName = 'amphtml'; const timelineUserId = '3450662892'; return ( <amp-twitter data-tweet-limit={tweetLimit} data-timeline-source-type={timelineSourceType} data-timeline-scree-name={timelineScreenName} data-timeline-user-id={timelineUserId} width="300" height="200" /> ); }; export const DeletedTweet = () => { const withFallback = boolean('include fallback?', true); return ( <amp-twitter width="390" height="330" layout="fixed" data-tweetid="882818033403789316" data-cards="hidden" > <blockquote placeholder> <p lang="en" dir="ltr"> In case you missed it last week, check out our recap of AMP in 2020 ⚡🙌 </p> <p> Watch here ➡️ <br /> <a href="https://t.co/eaxT3MuSAK">https://t.co/eaxT3MuSAK</a> </p> </blockquote> {withFallback && ( <div fallback> An error occurred while retrieving the tweet. It might have been deleted. </div> )} </amp-twitter> ); }; export const InvalidTweet = () => { return ( <amp-twitter width="390" height="330" layout="fixed" data-tweetid="1111111111111641653602164060160" data-cards="hidden" > <blockquote placeholder class="twitter-tweet" data-lang="en"> <p> This placeholder should never change because given tweet-id is invalid. </p> </blockquote> </amp-twitter> ); }; export const MutatedTweetId = () => { return ( <> <button on="tap:AMP.setState({tweetid: '495719809695621121'})"> Change tweet </button> <amp-state id="tweetid"> <script type="application/json">1356304203044499462</script> </amp-state> <amp-twitter width="375" height="472" layout="responsive" data-tweetid="1356304203044499462" data-amp-bind-data-tweetid="tweetid" ></amp-twitter> </> ); };
jpettitt/amphtml
extensions/amp-twitter/1.0/storybook/Basic.amp.js
JavaScript
apache-2.0
3,469
angular.module('app').factory('Entity', function ($resource) { var __apiBase__ = 'http://localhost:8080/GenericBackend/'; return { Model : $resource(__apiBase__ + 'api/models/fqns'), User : $resource(__apiBase__ + 'api/users/:id', {id: '@id', profileId :'@profileId'},{ getPermissions : {method : 'GET', url : __apiBase__ + 'api/userProfileRules/:profileId/allowedPermissions', isArray : true}, changePassword : {method : 'POST', url : __apiBase__ + 'api/users/:id/changePassword', isArray : false}, resetPassword : {method : 'POST', url : __apiBase__ + 'api/users/:id/resetPassword', isArray : false}, activate : {method : 'POST', url : __apiBase__ + 'api/users/:id/activate', isArray : false}, deactivate : {method : 'POST', url : __apiBase__ + 'api/users/:id/deactivate', isArray : false} }), Authentication : $resource(__apiBase__ + 'api/authentication/:id', {id: '@id', newStatus:'@newStatus'},{ login : {method : 'POST', url : __apiBase__ + 'api/authentication/login'}, logout : {method : 'POST', url : __apiBase__ + 'api/authentication/logout'}, getLoggedInUser : {method : 'GET', url : __apiBase__ + 'api/authentication/loggedinUser'} }), Role : $resource(__apiBase__ + 'api/roles/:id', {id: '@id'}), Profile : $resource(__apiBase__ + 'api/profiles/:id', {id: '@id'}), UserProfileRule : $resource(__apiBase__ + 'api/userProfileRules/:id', {id: '@id', newStatus:'@newStatus'},{ togglePermission : {method : 'POST', url : __apiBase__ + 'api/userProfileRules/:id/toggleStatus'} }), SchemeAccess : $resource(__apiBase__ + 'api/schemeAccess/:id', {id: '@id'}, { toggleAccess : {method : 'POST', url : __apiBase__ + 'api/schemeAccess/:id/toggleAccess'}, switchOrganization : {method : 'POST', url : __apiBase__ + 'api/schemeAccess/:id/switchScheme'}, }), UserOrganization : $resource(__apiBase__ + 'api/userOrganizations/:id', {id: '@id'}), Permission : $resource(__apiBase__ + 'api/permissions/:id', {id: '@id'}, { createPermissions : {method : 'POST', url : 'api/permissions/createPermissions'} }), UserPermission : $resource(__apiBase__ + 'api/user_permissions/:userId', {id: '@userId'}), SQLExecutor : $resource(__apiBase__ + 'api/sqlExecutor/:id', {id: '@id'},{ execute : {method : 'POST', url : __apiBase__ + 'api/sqlExecutor/execute', isArray: true} }) } } );
kodero/generic-angular-frontend
app/common/services/EntityFactory.js
JavaScript
apache-2.0
2,708
"use strict"; require('../core/setup'); var $ = require('jquery'), L = require('leaflet'), assert = require('chai').assert, sinon = require('sinon'), Marionette = require('../../shim/backbone.marionette'), App = require('../app'), models = require('./models'), utils = require('./utils'), views = require('./views'), settings = require('../core/settings'), testUtils = require('../core/testUtils'); var sandboxId = 'sandbox', sandboxSelector = '#' + sandboxId, TEST_SHAPE = { 'type': 'MultiPolygon', 'coordinates': [[[-5e6, -1e6], [-4e6, 1e6], [-3e6, -1e6]]] }; var SandboxRegion = Marionette.Region.extend({ el: sandboxSelector }); describe('Draw', function() { before(function() { // Ensure that draw tools are enabled before testing settings.set('draw_tools', [ 'SelectArea', // Boundary Selector 'Draw', // Custom Area or 1 Sq Km stamp 'PlaceMarker', // Delineate Watershed 'ResetDraw', ]); }); beforeEach(function() { $('body').append('<div id="sandbox">'); }); afterEach(function() { $(sandboxSelector).remove(); window.location.hash = ''; testUtils.resetApp(App); }); describe('ToolbarView', function() { // Setup the toolbar controls, enable/disable them, and verify // the correct CSS classes are applied. it('enables/disables toolbar controls when the model enableTools/disableTools methods are called', function() { var sandbox = new SandboxRegion(), $el = sandbox.$el, model = new models.ToolbarModel(), view = new views.ToolbarView({ model: model }); sandbox.show(view); populateSelectAreaDropdown($el, model); // Nothing should be disabled at this point. // Test that toggling the `toolsEnabled` property on the model // will disable all drawing tools. assert.equal($el.find('.disabled').size(), 0); model.disableTools(); assert.equal($el.find('.disabled').size(), 3); model.enableTools(); assert.equal($el.find('.disabled').size(), 0); }); it('adds an AOI to the map after calling getShapeAndAnalyze', function(done) { var successCount = 2, deferred = setupGetShapeAndAnalyze(successCount), success; deferred. done(function() { assert.equal(App.map.get('areaOfInterest'), TEST_SHAPE); success = true; }). fail(function() { success = false; }). always(function() { assert.equal(success, true); done(); }); }); it('fails to add AOI when shape id cannot be retrieved by getShapeAndAnalyze', function(done) { // Set successCount high enough so that the polling will fail. var successCount = 6, deferred = setupGetShapeAndAnalyze(successCount), success; deferred. done(function() { success = true; }). fail(function() { success = false; }). always(function() { assert.equal(success, false); done(); }); }); it('resets the current area of interest on Reset', function() { var setup = setupResetTestObject(); App.map.set('areaOfInterest', TEST_SHAPE); setup.resetRegion.currentView.resetDrawingState(); assert.isNull(App.map.get('areaOfInterest', 'Area of Interest was not removed on reset from the map')); }); it('resets the boundary layer on Reset', function() { var setup = setupResetTestObject(), ofg = L.featureGroup(), testFeature = { "type": "Feature", "geometry": { "type": "Point", "coordinates": [-104.99404, 39.75621] } }; ofg.addLayer(L.geoJson(testFeature)); assert.equal(ofg.getLayers().length, 1); setup.model.set('outlineFeatureGroup', ofg); setup.resetRegion.currentView.resetDrawingState(); assert.equal(ofg.getLayers().length, 0, 'Boundary Layer should have been removed from layer group'); }); it('removes in progress drawing on Reset', function() { var setup = setupResetTestObject(), spy = sinon.spy(utils, 'cancelDrawing'); utils.drawPolygon(setup.map); setup.resetRegion.currentView.resetDrawingState(); assert.equal(spy.callCount, 1); }); }); }); function setupGetShapeAndAnalyze(successCount) { var sandbox = new SandboxRegion(), model = new models.ToolbarModel(), view = new views.ToolbarView({ model: model }), shapeId = 1, e = {latlng: L.latLng(50.5, 30.5)}, ofg = model.get('outlineFeatureGroup'), grid = { callCount: 0, _objectForEvent: function() { //mock grid returns shapeId on second call this.callCount++; if (this.callCount >= successCount) { return {data: {id: shapeId}}; } else { return {}; } } }, tableId = 2; sandbox.show(view); App.restApi = { getPolygon: function() { return $.Deferred().resolve(TEST_SHAPE).promise(); } }; return views.getShapeAndAnalyze(e, model, ofg, grid, tableId); } function setupResetTestObject() { var sandbox = new SandboxRegion(), model = new models.ToolbarModel(), view = new views.ToolbarView({ model: model }), resetRegion = view.getRegion('resetRegion'), map = App.getLeafletMap(); sandbox.show(view); return { sandbox: sandbox, model: model, view: view, resetRegion: resetRegion, map: map }; } function assertTextEqual($el, sel, text) { assert.equal($el.find(sel).text().trim(), text); } function populateSelectAreaDropdown($el, toolbarModel) { // This control should start off in a Loading state. assertTextEqual($el, '#select-area-region button', 'Loading...'); // Load some shapes... toolbarModel.set('predefinedShapeTypes', [ { "endpoint": "http://localhost:4000/0/{z}/{x}/{y}", "display": "Congressional Districts", "name": "tiles" }]); // This dropdown should now be populated. assertTextEqual($el, '#select-area-region button', 'Select by Boundary'); assertTextEqual($el, '#select-area-region li', 'Congressional Districts'); }
lliss/model-my-watershed
src/mmw/js/src/draw/tests.js
JavaScript
apache-2.0
7,248
/** * 添加教师js,主要处理积点的问题。 * 分模块化 * Created by admin on 2016/9/26. */ $(function(){ //第一个问题 var work_load = $('#is_work_load').val(); $("#work_load input[type='checkbox']").live('click', function(e){ var is_work_load = $(this).val(); if($(this).is(':checked') && is_work_load == 1){ $("#is_work_load").val(1); $('#work_load').find(".no").attr('checked', false); $('#work_load').find(".yes").attr('checked', true); }else{ $("#is_work_load").val(0); $('#work_load').find(".no").attr('checked', true); $('#work_load').find(".yes").attr('checked', false); } }); //第二个问题 var teaching_good = $('#is_teaching_good').val(); $("#teaching_good input[type='checkbox']").live('click', function(e){ var is_teaching_good = $(this).val(); if($(this).is(':checked') && is_teaching_good == 1){ $("#is_teaching_good").val(1); $('#teaching_good').find(".no").attr('checked', false); $('#teaching_good').find(".yes").attr('checked', true); }else{ $("#is_teaching_good").val(0); $('#teaching_good').find(".no").attr('checked', true); $('#teaching_good').find(".yes").attr('checked', false); } }); //第三个问题 var teaching_behavior = $('#is_teaching_behavior').val(); $("#teaching_behavior input[type='checkbox']").live('click', function(e){ var is_teaching_behavior = $(this).val(); if($(this).is(':checked') && is_teaching_behavior == 1){ $("#is_teaching_behavior").val(1); $('#teaching_behavior').find(".no").attr('checked', false); $('#teaching_behavior').find(".yes").attr('checked', true); }else{ $("#is_teaching_behavior").val(0); $('#teaching_behavior').find(".no").attr('checked', true); $('#teaching_behavior').find(".yes").attr('checked', false); } }); //第四个问题 var student_statis = $('#is_student_statis').val(); $("#student_statis input[type='checkbox']").live('click', function(e){ var is_student_statis = $(this).val(); if($(this).is(':checked') && is_student_statis == 1){ $("#is_student_statis").val(1); $('#student_statis').find(".no").attr('checked', false); $('#student_statis').find(".yes").attr('checked', true); }else{ $("#is_student_statis").val(0); $('#student_statis').find(".no").attr('checked', true); $('#student_statis').find(".yes").attr('checked', false); } }); //第五个问题 var subject_good = $('#is_subject_good').val(); $("#subject_good input[type='checkbox']").live('click', function(e){ var is_subject_good = $(this).val(); if($(this).is(':checked') && is_subject_good == 1){ $("#is_subject_good").val(1); $('#subject_good').find(".no").attr('checked', false); $('#subject_good').find(".yes").attr('checked', true); }else{ $("#is_subject_good").val(0); $('#subject_good').find(".no").attr('checked', true); $('#subject_good').find(".yes").attr('checked', false); } }); //第六个问题 var academic = $('#is_academic').val(); $("#academic input[type='checkbox']").live('click', function(e){ var is_academic = $(this).val(); if($(this).is(':checked') && is_academic == 1){ $("#is_academic").val(1); $('#academic').find(".no").attr('checked', false); $('#academic').find(".yes").attr('checked', true); }else{ $("#is_academic").val(0); $('#academic').find(".no").attr('checked', true); $('#academic').find(".yes").attr('checked', false); } }); //第七个问题 var organ_sub = $('#is_organ_sub').val(); $("#organ_sub input[type='checkbox']").live('click', function(e){ var is_organ_sub = $(this).val(); if($(this).is(':checked') && is_organ_sub == 1){ $("#is_organ_sub").val(1); $('#organ_sub').find(".no").attr('checked', false); $('#organ_sub').find(".yes").attr('checked', true); }else{ $("#is_organ_sub").val(0); $('#organ_sub').find(".no").attr('checked', true); $('#organ_sub').find(".yes").attr('checked', false); } }); //第八个问题 var school_forum = $('#is_school_forum').val(); $("#school_forum input[type='checkbox']").live('click', function(e){ var is_school_forum = $(this).val(); if($(this).is(':checked') && is_school_forum == 1){ $("#is_school_forum").val(1); $('#school_forum').find(".no").attr('checked', false); $('#school_forum').find(".yes").attr('checked', true); }else{ $("#is_school_forum").val(0); $('#school_forum').find(".no").attr('checked', true); $('#school_forum').find(".yes").attr('checked', false); } }); //第九个问题 var backtone_teacher = $('#is_backtone_teacher').val(); $("#backtone_teacher input[type='checkbox']").live('click', function(e){ var is_backtone_teacher = $(this).val(); if($(this).is(':checked') && is_backtone_teacher == 1){ $("#is_backtone_teacher").val(1); $('#backtone_teacher').find(".no").attr('checked', false); $('#backtone_teacher').find(".yes").attr('checked', true); }else{ $("#is_backtone_teacher").val(0); $('#backtone_teacher').find(".no").attr('checked', true); $('#backtone_teacher').find(".yes").attr('checked', false); } }); //第10个问题 var teach_intern = $('#is_teach_intern').val(); $("#teach_intern input[type='checkbox']").live('click', function(e){ var is_teach_intern = $(this).val(); if($(this).is(':checked') && is_teach_intern == 1){ $("#is_teach_intern").val(1); $('#teach_intern').find(".no").attr('checked', false); $('#teach_intern').find(".yes").attr('checked', true); }else{ $("#is_teach_intern").val(0); $('#teach_intern').find(".no").attr('checked', true); $('#teach_intern').find(".yes").attr('checked', false); } }); //第11个问题 var person_write = $('#is_person_write').val(); $("#person_write input[type='checkbox']").live('click', function(e){ var is_person_write = $(this).val(); if($(this).is(':checked') && is_person_write == 1){ $("#is_teach_intern").val(1); $('#person_write').find(".no").attr('checked', false); $('#person_write').find(".yes").attr('checked', true); }else{ $("#is_person_write").val(0); $('#person_write').find(".no").attr('checked', true); $('#person_write').find(".yes").attr('checked', false); } }); //第12个问题 var semester = $('#is_semester').val(); $("#semester input[type='checkbox']").live('click', function(e){ var is_semester = $(this).val(); if($(this).is(':checked') && is_semester == 1){ $("#is_teach_intern").val(1); $('#semester').find(".no").attr('checked', false); $('#semester').find(".yes").attr('checked', true); }else{ $("#is_semester").val(0); $('#semester').find(".no").attr('checked', true); $('#semester').find(".yes").attr('checked', false); } }); //第13个问题 var head_teacher = $('#is_head_teacher').val(); $("#head_teacher input[type='checkbox']").live('click', function(e){ var is_head_teacher = $(this).val(); if($(this).is(':checked') && is_head_teacher == 1){ $("#is_head_teacher").val(1); $('#head_teacher').find(".no").attr('checked', false); $('#head_teacher').find(".yes").attr('checked', true); }else{ $("#is_head_teacher").val(0); $('#head_teacher').find(".no").attr('checked', true); $('#head_teacher').find(".yes").attr('checked', false); } }); //第14个问题 var learning_exper = $('#is_learning_exper').val(); $("#learning_exper input[type='checkbox']").live('click', function(e){ var is_learning_exper = $(this).val(); if($(this).is(':checked') && is_learning_exper == 1){ $("#is_learning_exper").val(1); $('#learning_exper').find(".no").attr('checked', false); $('#learning_exper').find(".yes").attr('checked', true); }else{ $("#is_learning_exper").val(0); $('#learning_exper').find(".no").attr('checked', true); $('#learning_exper').find(".yes").attr('checked', false); } }); //第15个问题 var class_meeting = $('#is_class_meeting').val(); $("#class_meeting input[type='checkbox']").live('click', function(e){ var is_class_meeting = $(this).val(); if($(this).is(':checked') && is_class_meeting == 1){ $("#is_class_meeting").val(1); $('#class_meeting').find(".no").attr('checked', false); $('#class_meeting').find(".yes").attr('checked', true); }else{ $("#is_class_meeting").val(0); $('#class_meeting').find(".no").attr('checked', true); $('#class_meeting').find(".yes").attr('checked', false); } }); //第16个问题 var good_head_teacher = $('#is_good_head_teacher').val(); $("#good_head_teacher input[type='checkbox']").live('click', function(e){ var is_good_head_teacher = $(this).val(); if($(this).is(':checked') && is_good_head_teacher == 1){ $("#is_good_head_teacher").val(1); $('#good_head_teacher').find(".no").attr('checked', false); $('#good_head_teacher').find(".yes").attr('checked', true); }else{ $("#is_good_head_teacher").val(0); $('#good_head_teacher').find(".no").attr('checked', true); $('#good_head_teacher').find(".yes").attr('checked', false); } }); //第17个问题 var fes_activity = $('#is_fes_activity').val(); $("#fes_activity input[type='checkbox']").live('click', function(e){ var is_fes_activity = $(this).val(); if($(this).is(':checked') && is_fes_activity == 1){ $("#is_fes_activity").val(1); $('#fes_activity').find(".no").attr('checked', false); $('#fes_activity').find(".yes").attr('checked', true); }else{ $("#is_fes_activity").val(0); $('#fes_activity').find(".no").attr('checked', true); $('#fes_activity').find(".yes").attr('checked', false); } }); //第18个问题 var work_for_school = $('#is_work_for_school').val(); $("#work_for_school input[type='checkbox']").live('click', function(e){ var is_work_for_school = $(this).val(); if($(this).is(':checked') && is_work_for_school == 1){ $("#is_work_for_school").val(1); $('#work_for_school').find(".no").attr('checked', false); $('#work_for_school').find(".yes").attr('checked', true); }else{ $("#is_work_for_school").val(0); $('#work_for_school').find(".no").attr('checked', true); $('#work_for_school').find(".yes").attr('checked', false); } }); //第19个问题 var manange_school = $('#is_manange_school').val(); $("#manange_school input[type='checkbox']").live('click', function(e){ var is_manange_school = $(this).val(); if($(this).is(':checked') && is_manange_school == 1){ $("#is_manange_school").val(1); $('#manange_school').find(".no").attr('checked', false); $('#manange_school').find(".yes").attr('checked', true); }else{ $("#is_manange_school").val(0); $('#manange_school').find(".no").attr('checked', true); $('#manange_school').find(".yes").attr('checked', false); } }); //第20个问题 var research_school = $('#is_research_school').val(); $("#research_school input[type='checkbox']").live('click', function(e){ var is_research_school = $(this).val(); if($(this).is(':checked') && is_research_school == 1){ $("#is_research_school").val(1); $('#research_school').find(".no").attr('checked', false); $('#research_school').find(".yes").attr('checked', true); }else{ $("#is_research_school").val(0); $('#research_school').find(".no").attr('checked', true); $('#research_school').find(".yes").attr('checked', false); } }); });
lnc2014/school
template/js/add_per.js
JavaScript
apache-2.0
13,016
var THREE = require('three'); var cgaprocessor = require('./cgaprocessor') // function t(sizes, size, repeat) { // console.log(sizes, size, repeat); // console.log(cgaprocessor._compute_splits( sizes, size, repeat )); // } // t([ { size: 2 } ], 4, true); // t([ { size: 2 } ], 5, true); // t([ { size: 2 }, { size: 2 } ], 4, true); // t([ { size: 2 }, { size: 2 } ], 5, true); // t([ { size: 2, _float: true }, { size: 2 } ], 3, true); // t([ { size: 2 }, { size: 2, _float: true }, { size: 2 } ], 4.5, true); // t([ { size: 2 }, { size: 1, _float: true }, { size: 2, _float: true }, { size: 2 } ], 4.5, true); //var preg = new THREE.BoxGeometry(2,2,2); var preg = new THREE.Geometry(); preg.vertices.push(new THREE.Vector3(0,0,0), new THREE.Vector3(1,1,0), new THREE.Vector3(2,0,0)); preg.faces.push(new THREE.Face3(0,1,2)); //preg.translate(2,0,0); // var preg = new THREE.Geometry(); // preg.vertices.push(new THREE.Vector3(-1,0,0), // new THREE.Vector3(-1,1,0), // new THREE.Vector3(1,0,0)); // preg.faces.push(new THREE.Face3(0,1,2)); // preg.translate(2,0,0); preg.computeBoundingBox(); console.dir(preg.boundingBox); console.log(preg.vertices.length, preg.faces.length); debugger; var g = cgaprocessor.split_geometry('x', preg, 0.5, 1.5); g.computeBoundingBox(); console.dir(g.boundingBox); console.log(g.vertices.length, g.faces.length); g.vertices.forEach( v => console.log(v) ); g.faces.forEach( v => console.log(v.a,v.b,v.c) );
gromgull/cgajs
test/test_splitting.js
JavaScript
apache-2.0
1,531
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { AsyncResolverDef, ResolverReturnDef, SyncResolverDef, VariableSource, getNavigationData, getTimingDataAsync, getTimingDataSync, } from './variable-source'; import {Expander, NOENCODE_WHITELIST} from './url-expander/expander'; import {Services} from '../services'; import {WindowInterface} from '../window-interface'; import { addMissingParamsToUrl, addParamsToUrl, getSourceUrl, isProtocolValid, parseQueryString, parseUrlDeprecated, removeAmpJsParamsFromUrl, removeFragment, } from '../url'; import {dev, rethrowAsync, user} from '../log'; import {getMode} from '../mode'; import {getTrackImpressionPromise} from '../impression.js'; import {hasOwn} from '../utils/object'; import { installServiceInEmbedScope, registerServiceBuilderForDoc, } from '../service'; import {isExperimentOn} from '../experiments'; import {tryResolve} from '../utils/promise'; /** @private @const {string} */ const TAG = 'UrlReplacements'; const EXPERIMENT_DELIMITER = '!'; const VARIANT_DELIMITER = '.'; const GEO_DELIM = ','; const ORIGINAL_HREF_PROPERTY = 'amp-original-href'; const ORIGINAL_VALUE_PROPERTY = 'amp-original-value'; /** * Returns a encoded URI Component, or an empty string if the value is nullish. * @param {*} val * @return {string} */ function encodeValue(val) { if (val == null) { return ''; } return encodeURIComponent(/** @type {string} */(val)); } /** * Returns a function that executes method on a new Date instance. This is a * byte saving hack. * * @param {string} method * @return {!SyncResolverDef} */ function dateMethod(method) { return () => new Date()[method](); } /** * Returns a function that returns property of screen. This is a byte saving * hack. * * @param {!Screen} screen * @param {string} property * @return {!SyncResolverDef} */ function screenProperty(screen, property) { return () => screen[property]; } /** * Class to provide variables that pertain to top level AMP window. */ export class GlobalVariableSource extends VariableSource { /** * @param {!./ampdoc-impl.AmpDoc} ampdoc */ constructor(ampdoc) { super(ampdoc); /** @private {?Promise<?Object<string, string>>} */ this.variants_ = null; /** @private {?Promise<?ShareTrackingFragmentsDef>} */ this.shareTrackingFragments_ = null; } /** * Utility function for setting resolver for timing data that supports * sync and async. * @param {string} varName * @param {string} startEvent * @param {string=} endEvent * @return {!VariableSource} * @private */ setTimingResolver_(varName, startEvent, endEvent) { return this.setBoth(varName, () => { return getTimingDataSync(this.ampdoc.win, startEvent, endEvent); }, () => { return getTimingDataAsync(this.ampdoc.win, startEvent, endEvent); }); } /** @override */ initialize() { /** @const {!./viewport/viewport-impl.Viewport} */ const viewport = Services.viewportForDoc(this.ampdoc); // Returns a random value for cache busters. this.set('RANDOM', () => Math.random()); // Provides a counter starting at 1 per given scope. const counterStore = Object.create(null); this.set('COUNTER', scope => { return counterStore[scope] = (counterStore[scope] | 0) + 1; }); // Returns the canonical URL for this AMP document. this.set('CANONICAL_URL', this.getDocInfoUrl_('canonicalUrl')); // Returns the host of the canonical URL for this AMP document. this.set('CANONICAL_HOST', this.getDocInfoUrl_('canonicalUrl', 'host')); // Returns the hostname of the canonical URL for this AMP document. this.set('CANONICAL_HOSTNAME', this.getDocInfoUrl_('canonicalUrl', 'hostname')); // Returns the path of the canonical URL for this AMP document. this.set('CANONICAL_PATH', this.getDocInfoUrl_('canonicalUrl', 'pathname')); // Returns the referrer URL. this.setAsync('DOCUMENT_REFERRER', /** @type {AsyncResolverDef} */(() => { return Services.viewerForDoc(this.ampdoc).getReferrerUrl(); })); // Like DOCUMENT_REFERRER, but returns null if the referrer is of // same domain or the corresponding CDN proxy. this.setAsync('EXTERNAL_REFERRER', /** @type {AsyncResolverDef} */(() => { return Services.viewerForDoc(this.ampdoc).getReferrerUrl() .then(referrer => { if (!referrer) { return null; } const referrerHostname = parseUrlDeprecated(getSourceUrl(referrer)) .hostname; const currentHostname = WindowInterface.getHostname(this.ampdoc.win); return referrerHostname === currentHostname ? null : referrer; }); })); // Returns the title of this AMP document. this.set('TITLE', () => { // The environment may override the title and set originalTitle. Prefer // that if available. return this.ampdoc.win.document['originalTitle'] || this.ampdoc.win.document.title; }); // Returns the URL for this AMP document. this.set('AMPDOC_URL', () => { return removeFragment( this.addReplaceParamsIfMissing_( this.ampdoc.win.location.href)); }); // Returns the host of the URL for this AMP document. this.set('AMPDOC_HOST', () => { const url = parseUrlDeprecated(this.ampdoc.win.location.href); return url && url.host; }); // Returns the hostname of the URL for this AMP document. this.set('AMPDOC_HOSTNAME', () => { const url = parseUrlDeprecated(this.ampdoc.win.location.href); return url && url.hostname; }); // Returns the Source URL for this AMP document. const expandSourceUrl = () => { const docInfo = Services.documentInfoForDoc(this.ampdoc); return removeFragment(this.addReplaceParamsIfMissing_(docInfo.sourceUrl)); }; this.setBoth('SOURCE_URL', () => expandSourceUrl(), () => getTrackImpressionPromise().then(() => expandSourceUrl())); // Returns the host of the Source URL for this AMP document. this.set('SOURCE_HOST', this.getDocInfoUrl_('sourceUrl', 'host')); // Returns the hostname of the Source URL for this AMP document. this.set('SOURCE_HOSTNAME', this.getDocInfoUrl_('sourceUrl', 'hostname')); // Returns the path of the Source URL for this AMP document. this.set('SOURCE_PATH', this.getDocInfoUrl_('sourceUrl', 'pathname')); // Returns a random string that will be the constant for the duration of // single page view. It should have sufficient entropy to be unique for // all the page views a single user is making at a time. this.set('PAGE_VIEW_ID', this.getDocInfoUrl_('pageViewId')); this.setBoth('QUERY_PARAM', (param, defaultValue = '') => { return this.getQueryParamData_(param, defaultValue); }, (param, defaultValue = '') => { return getTrackImpressionPromise().then(() => { return this.getQueryParamData_(param, defaultValue); }); }); // Returns the value of the given field name in the fragment query string. // Second parameter is an optional default value. // For example, if location is 'pub.com/amp.html?x=1#y=2' then // FRAGMENT_PARAM(y) returns '2' and FRAGMENT_PARAM(z, 3) returns 3. this.setAsync('FRAGMENT_PARAM', this.getViewerIntegrationValue_('fragmentParam', 'FRAGMENT_PARAM')); // Returns the first item in the ancestorOrigins array, if available. this.setAsync('ANCESTOR_ORIGIN', this.getViewerIntegrationValue_('ancestorOrigin', 'ANCESTOR_ORIGIN')); /** * Stores client ids that were generated during this page view * indexed by scope. * @type {?Object<string, string>} */ let clientIds = null; // Synchronous alternative. Only works for scopes that were previously // requested using the async method. this.setBoth('CLIENT_ID', scope => { if (!clientIds) { return null; } return clientIds[dev().assertString(scope)]; }, (scope, opt_userNotificationId, opt_cookieName) => { user().assertString(scope, 'The first argument to CLIENT_ID, the fallback' + /*OK*/' Cookie name, is required'); if (getMode().runtime == 'inabox') { return /** @type {!Promise<ResolverReturnDef>} */(Promise.resolve(null)); } let consent = Promise.resolve(); // If no `opt_userNotificationId` argument is provided then // assume consent is given by default. if (opt_userNotificationId) { consent = Services.userNotificationManagerForDoc(this.ampdoc) .then(service => { return service.get(opt_userNotificationId); }); } return Services.cidForDoc(this.ampdoc).then(cid => { return cid.get({ scope: dev().assertString(scope), createCookieIfNotPresent: true, cookieName: opt_cookieName, }, consent); }).then(cid => { if (!clientIds) { clientIds = Object.create(null); } // A temporary work around to extract Client ID from _ga cookie. #5761 // TODO: replace with "filter" when it's in place. #2198 const cookieName = opt_cookieName || scope; if (cid && cookieName == '_ga') { if (typeof cid === 'string') { cid = extractClientIdFromGaCookie(cid); } else { // TODO(@jridgewell, #11120): remove once #11120 is figured out. // Do not log the CID directly, that's PII. dev().error(TAG, 'non-string cid, what is it?', Object.keys(cid)); } } clientIds[scope] = cid; return cid; }); }); // Returns assigned variant name for the given experiment. this.setAsync('VARIANT', /** @type {AsyncResolverDef} */(experiment => { return this.getVariantsValue_(variants => { const variant = variants[/** @type {string} */(experiment)]; user().assert(variant !== undefined, 'The value passed to VARIANT() is not a valid experiment name:' + experiment); // When no variant assigned, use reserved keyword 'none'. return variant === null ? 'none' : /** @type {string} */(variant); }, 'VARIANT'); })); // Returns all assigned experiment variants in a serialized form. this.setAsync('VARIANTS', /** @type {AsyncResolverDef} */(() => { return this.getVariantsValue_(variants => { const experiments = []; for (const experiment in variants) { const variant = variants[experiment]; experiments.push( experiment + VARIANT_DELIMITER + (variant || 'none')); } return experiments.join(EXPERIMENT_DELIMITER); }, 'VARIANTS'); })); // Returns assigned geo value for geoType or all groups. this.setAsync('AMP_GEO', /** @type {AsyncResolverDef} */(geoType => { return this.getGeo_(geos => { if (geoType) { user().assert(geoType === 'ISOCountry', 'The value passed to AMP_GEO() is not valid name:' + geoType); return /** @type {string} */ (geos[geoType] || 'unknown'); } return /** @type {string} */ (geos.ISOCountryGroups.join(GEO_DELIM)); }, 'AMP_GEO'); })); // Returns incoming share tracking fragment. this.setAsync('SHARE_TRACKING_INCOMING', /** @type {AsyncResolverDef} */( () => { return this.getShareTrackingValue_(fragments => { return fragments.incomingFragment; }, 'SHARE_TRACKING_INCOMING'); })); // Returns outgoing share tracking fragment. this.setAsync('SHARE_TRACKING_OUTGOING', /** @type {AsyncResolverDef} */( () => { return this.getShareTrackingValue_(fragments => { return fragments.outgoingFragment; }, 'SHARE_TRACKING_OUTGOING'); })); // Returns the number of milliseconds since 1 Jan 1970 00:00:00 UTC. this.set('TIMESTAMP', dateMethod('getTime')); // Returns the human readable timestamp in format of // 2011-01-01T11:11:11.612Z. this.set('TIMESTAMP_ISO', dateMethod('toISOString')); // Returns the user's time-zone offset from UTC, in minutes. this.set('TIMEZONE', dateMethod('getTimezoneOffset')); // Returns the IANA timezone code this.set('TIMEZONE_CODE', () => { let tzCode; if ('Intl' in this.ampdoc.win && 'DateTimeFormat' in this.ampdoc.win.Intl) { // It could be undefined (i.e. IE11) tzCode = new Intl.DateTimeFormat().resolvedOptions().timeZone; } return tzCode || ''; }); // Returns a promise resolving to viewport.getScrollTop. this.set('SCROLL_TOP', () => viewport.getScrollTop()); // Returns a promise resolving to viewport.getScrollLeft. this.set('SCROLL_LEFT', () => viewport.getScrollLeft()); // Returns a promise resolving to viewport.getScrollHeight. this.set('SCROLL_HEIGHT', () => viewport.getScrollHeight()); // Returns a promise resolving to viewport.getScrollWidth. this.set('SCROLL_WIDTH', () => viewport.getScrollWidth()); // Returns the viewport height. this.set('VIEWPORT_HEIGHT', () => viewport.getHeight()); // Returns the viewport width. this.set('VIEWPORT_WIDTH', () => viewport.getWidth()); const {screen} = this.ampdoc.win; // Returns screen.width. this.set('SCREEN_WIDTH', screenProperty(screen, 'width')); // Returns screen.height. this.set('SCREEN_HEIGHT', screenProperty(screen, 'height')); // Returns screen.availHeight. this.set('AVAILABLE_SCREEN_HEIGHT', screenProperty(screen, 'availHeight')); // Returns screen.availWidth. this.set('AVAILABLE_SCREEN_WIDTH', screenProperty(screen, 'availWidth')); // Returns screen.ColorDepth. this.set('SCREEN_COLOR_DEPTH', screenProperty(screen, 'colorDepth')); // Returns document characterset. this.set('DOCUMENT_CHARSET', () => { const doc = this.ampdoc.win.document; return doc.characterSet || doc.charset; }); // Returns the browser language. this.set('BROWSER_LANGUAGE', () => { const nav = this.ampdoc.win.navigator; return (nav.language || nav.userLanguage || nav.browserLanguage || '') .toLowerCase(); }); // Returns the user agent. this.set('USER_AGENT', () => { const nav = this.ampdoc.win.navigator; return nav.userAgent; }); // Returns the time it took to load the whole page. (excludes amp-* elements // that are not rendered by the system yet.) this.setTimingResolver_( 'PAGE_LOAD_TIME', 'navigationStart', 'loadEventStart'); // Returns the time it took to perform DNS lookup for the domain. this.setTimingResolver_( 'DOMAIN_LOOKUP_TIME', 'domainLookupStart', 'domainLookupEnd'); // Returns the time it took to connect to the server. this.setTimingResolver_( 'TCP_CONNECT_TIME', 'connectStart', 'connectEnd'); // Returns the time it took for server to start sending a response to the // request. this.setTimingResolver_( 'SERVER_RESPONSE_TIME', 'requestStart', 'responseStart'); // Returns the time it took to download the page. this.setTimingResolver_( 'PAGE_DOWNLOAD_TIME', 'responseStart', 'responseEnd'); // Returns the time it took for redirects to complete. this.setTimingResolver_( 'REDIRECT_TIME', 'navigationStart', 'fetchStart'); // Returns the time it took for DOM to become interactive. this.setTimingResolver_( 'DOM_INTERACTIVE_TIME', 'navigationStart', 'domInteractive'); // Returns the time it took for content to load. this.setTimingResolver_( 'CONTENT_LOAD_TIME', 'navigationStart', 'domContentLoadedEventStart'); // Access: Reader ID. this.setAsync('ACCESS_READER_ID', /** @type {AsyncResolverDef} */(() => { return this.getAccessValue_(accessService => { return accessService.getAccessReaderId(); }, 'ACCESS_READER_ID'); })); // Access: data from the authorization response. this.setAsync('AUTHDATA', /** @type {AsyncResolverDef} */(field => { user().assert(field, 'The first argument to AUTHDATA, the field, is required'); return this.getAccessValue_(accessService => { return accessService.getAuthdataField(field); }, 'AUTHDATA'); })); // Returns an identifier for the viewer. this.setAsync('VIEWER', () => { return Services.viewerForDoc(this.ampdoc) .getViewerOrigin().then(viewer => { return viewer == undefined ? '' : viewer; }); }); // Returns the total engaged time since the content became viewable. this.setAsync('TOTAL_ENGAGED_TIME', () => { return Services.activityForDoc(this.ampdoc).then(activity => { return activity.getTotalEngagedTime(); }); }); // Returns the incremental engaged time since the last push under the // same name. this.setAsync('INCREMENTAL_ENGAGED_TIME', (name, reset) => { return Services.activityForDoc(this.ampdoc).then(activity => { return activity.getIncrementalEngagedTime(name, reset !== 'false'); }); }); this.set('NAV_TIMING', (startAttribute, endAttribute) => { user().assert(startAttribute, 'The first argument to NAV_TIMING, the ' + 'start attribute name, is required'); return getTimingDataSync( this.ampdoc.win, /**@type {string}*/(startAttribute), /**@type {string}*/(endAttribute)); }); this.setAsync('NAV_TIMING', (startAttribute, endAttribute) => { user().assert(startAttribute, 'The first argument to NAV_TIMING, the ' + 'start attribute name, is required'); return getTimingDataAsync( this.ampdoc.win, /**@type {string}*/(startAttribute), /**@type {string}*/(endAttribute)); }); this.set('NAV_TYPE', () => { return getNavigationData(this.ampdoc.win, 'type'); }); this.set('NAV_REDIRECT_COUNT', () => { return getNavigationData(this.ampdoc.win, 'redirectCount'); }); // returns the AMP version number this.set('AMP_VERSION', () => '$internalRuntimeVersion$'); this.set('BACKGROUND_STATE', () => { return Services.viewerForDoc(this.ampdoc).isVisible() ? '0' : '1'; }); this.setAsync('VIDEO_STATE', (id, property) => { const root = this.ampdoc.getRootNode(); const video = user().assertElement( root.getElementById(/** @type {string} */ (id)), `Could not find an element with id="${id}" for VIDEO_STATE`); return Services.videoManagerForDoc(this.ampdoc) .getAnalyticsDetails(video) .then(details => details ? details[property] : ''); }); this.setAsync('STORY_PAGE_INDEX', this.getStoryValue_('pageIndex', 'STORY_PAGE_INDEX')); this.setAsync('STORY_PAGE_ID', this.getStoryValue_('pageId', 'STORY_PAGE_ID')); this.setAsync('FIRST_CONTENTFUL_PAINT', () => { return tryResolve(() => Services.performanceFor(this.ampdoc.win).getFirstContentfulPaint()); }); this.setAsync('FIRST_VIEWPORT_READY', () => { return tryResolve(() => Services.performanceFor(this.ampdoc.win).getFirstViewportReady()); }); this.setAsync('MAKE_BODY_VISIBLE', () => { return tryResolve(() => Services.performanceFor(this.ampdoc.win).getMakeBodyVisible()); }); this.setAsync('AMP_STATE', key => { return Services.bindForDocOrNull(this.ampdoc).then(bind => { if (!bind) { return ''; } return bind.getStateValue(/** @type {string} */ (key)); }); }); } /** * Merges any replacement parameters into a given URL's query string, * preferring values set in the original query string. * @param {string} orig The original URL * @return {string} The resulting URL * @private */ addReplaceParamsIfMissing_(orig) { const {replaceParams} = /** @type {!Object} */ (Services.documentInfoForDoc(this.ampdoc)); if (!replaceParams) { return orig; } return addMissingParamsToUrl(removeAmpJsParamsFromUrl(orig), replaceParams); } /** * Resolves the value via one of document info's urls. * @param {string} field A field on the docInfo * @param {string=} opt_urlProp A subproperty of the field * @return {T} * @template T */ getDocInfoUrl_(field, opt_urlProp) { return () => { const docInfo = Services.documentInfoForDoc(this.ampdoc); const value = docInfo[field]; return opt_urlProp ? parseUrlDeprecated(value)[opt_urlProp] : value; }; } /** * Resolves the value via access service. If access service is not configured, * the resulting value is `null`. * @param {function(!../../extensions/amp-access/0.1/access-vars.AccessVars):(T|!Promise<T>)} getter * @param {string} expr * @return {T|null} * @template T * @private */ getAccessValue_(getter, expr) { return Promise.all([ Services.accessServiceForDocOrNull(this.ampdoc), Services.subscriptionsServiceForDocOrNull(this.ampdoc), ]).then(services => { const service = /** @type {?../../extensions/amp-access/0.1/access-vars.AccessVars} */ ( services[0] || services[1]); if (!service) { // Access/subscriptions service is not installed. user().error( TAG, 'Access or subsciptions service is not installed to access: ', expr); return null; } return getter(service); }); } /** * Return the QUERY_PARAM from the current location href * @param {*} param * @param {string} defaultValue * @return {string} * @private */ getQueryParamData_(param, defaultValue) { user().assert(param, 'The first argument to QUERY_PARAM, the query string ' + 'param is required'); const url = parseUrlDeprecated( removeAmpJsParamsFromUrl(this.ampdoc.win.location.href)); const params = parseQueryString(url.search); const key = user().assertString(param); const {replaceParams} = Services.documentInfoForDoc(this.ampdoc); if (typeof params[key] !== 'undefined') { return params[key]; } if (replaceParams && typeof replaceParams[key] !== 'undefined') { return /** @type {string} */(replaceParams[key]); } return defaultValue; } /** * Resolves the value via amp-experiment's variants service. * @param {function(!Object<string, string>):(?string)} getter * @param {string} expr * @return {!Promise<?string>} * @template T * @private */ getVariantsValue_(getter, expr) { if (!this.variants_) { this.variants_ = Services.variantForOrNull(this.ampdoc.win); } return this.variants_.then(variants => { user().assert(variants, 'To use variable %s, amp-experiment should be configured', expr); return getter(variants); }); } /** * Resolves the value via geo service. * @param {function(Object<string, string>)} getter * @param {string} expr * @return {!Promise<Object<string,(string|Array<string>)>>} * @template T * @private */ getGeo_(getter, expr) { return Services.geoForDocOrNull(this.ampdoc) .then(geo => { user().assert(geo, 'To use variable %s, amp-geo should be configured', expr); return getter(geo); }); } /** * Resolves the value via amp-share-tracking's service. * @param {function(!ShareTrackingFragmentsDef):T} getter * @param {string} expr * @return {!Promise<T>} * @template T * @private */ getShareTrackingValue_(getter, expr) { if (!this.shareTrackingFragments_) { this.shareTrackingFragments_ = Services.shareTrackingForOrNull(this.ampdoc.win); } return this.shareTrackingFragments_.then(fragments => { user().assert(fragments, 'To use variable %s, ' + 'amp-share-tracking should be configured', expr); return getter(/** @type {!ShareTrackingFragmentsDef} */ (fragments)); }); } /** * Resolves the value via amp-story's service. * @param {string} property * @param {string} name * @return {!AsyncResolverDef} * @private */ getStoryValue_(property, name) { return () => { const service = Services.storyVariableServiceForOrNull(this.ampdoc.win); return service.then(storyVariables => { user().assert(storyVariables, 'To use variable %s amp-story should be configured', name); return storyVariables[property]; }); }; } /** * Resolves the value via amp-viewer-integration's service. * @param {string} property * @param {string} name * @return {!AsyncResolverDef} * @private */ getViewerIntegrationValue_(property, name) { return /** @type {!AsyncResolverDef} */ ( (param, defaultValue = '') => { const service = Services.viewerIntegrationVariableServiceForOrNull(this.ampdoc.win); return service.then(viewerIntegrationVariables => { user().assert(viewerIntegrationVariables, 'To use variable %s ' + 'amp-viewer-integration must be installed', name); return viewerIntegrationVariables[property](param, defaultValue); }); }); } } /** * This class replaces substitution variables with their values. * Document new values in ../spec/amp-var-substitutions.md * @package For export */ export class UrlReplacements { /** * @param {!./ampdoc-impl.AmpDoc} ampdoc * @param {!VariableSource} variableSource */ constructor(ampdoc, variableSource) { /** @const {!./ampdoc-impl.AmpDoc} */ this.ampdoc = ampdoc; /** @type {VariableSource} */ this.variableSource_ = variableSource; /** @type {!Expander} */ this.expander_ = new Expander(this.variableSource_); } /** * Synchronously expands the provided source by replacing all known variables * with their resolved values. Optional `opt_bindings` can be used to add new * variables or override existing ones. Any async bindings are ignored. * @param {string} source * @param {!Object<string, (ResolverReturnDef|!SyncResolverDef)>=} opt_bindings * @param {!Object<string, ResolverReturnDef>=} opt_collectVars * @param {!Object<string, boolean>=} opt_whiteList Optional white list of * names that can be substituted. * @return {string} */ expandStringSync(source, opt_bindings, opt_collectVars, opt_whiteList) { return /** @type {string} */ ( this.expand_(source, opt_bindings, opt_collectVars, /* opt_sync */ true, opt_whiteList)); } /** * Expands the provided source by replacing all known variables with their * resolved values. Optional `opt_bindings` can be used to add new variables * or override existing ones. * @param {string} source * @param {!Object<string, *>=} opt_bindings * @param {!Object<string, boolean>=} opt_whiteList * @return {!Promise<string>} */ expandStringAsync(source, opt_bindings, opt_whiteList) { return /** @type {!Promise<string>} */ (this.expand_(source, opt_bindings, /* opt_collectVars */ undefined, /* opt_sync */ undefined, opt_whiteList)); } /** * Synchronously expands the provided URL by replacing all known variables * with their resolved values. Optional `opt_bindings` can be used to add new * variables or override existing ones. Any async bindings are ignored. * @param {string} url * @param {!Object<string, (ResolverReturnDef|!SyncResolverDef)>=} opt_bindings * @param {!Object<string, ResolverReturnDef>=} opt_collectVars * @param {!Object<string, boolean>=} opt_whiteList Optional white list of * names that can be substituted. * @return {string} */ expandUrlSync(url, opt_bindings, opt_collectVars, opt_whiteList) { return this.ensureProtocolMatches_(url, /** @type {string} */ (this.expand_( url, opt_bindings, opt_collectVars, /* opt_sync */ true, opt_whiteList))); } /** * Expands the provided URL by replacing all known variables with their * resolved values. Optional `opt_bindings` can be used to add new variables * or override existing ones. * @param {string} url * @param {!Object<string, *>=} opt_bindings * @param {!Object<string, boolean>=} opt_whiteList Optional white list of names * that can be substituted. * @return {!Promise<string>} */ expandUrlAsync(url, opt_bindings, opt_whiteList) { return /** @type {!Promise<string>} */ ( this.expand_(url, opt_bindings, undefined, undefined, opt_whiteList).then( replacement => this.ensureProtocolMatches_(url, replacement))); } /** * Expands an input element value attribute with variable substituted. * @param {!HTMLInputElement} element * @return {!Promise<string>} */ expandInputValueAsync(element) { return /** @type {!Promise<string>} */ ( this.expandInputValue_(element, /*opt_sync*/ false)); } /** * Expands an input element value attribute with variable substituted. * @param {!HTMLInputElement} element * @return {string} Replaced string for testing */ expandInputValueSync(element) { return /** @type {string} */ ( this.expandInputValue_(element, /*opt_sync*/ true)); } /** * Expands in input element value attribute with variable substituted. * @param {!HTMLInputElement} element * @param {boolean=} opt_sync * @return {string|!Promise<string>} */ expandInputValue_(element, opt_sync) { dev().assert(element.tagName == 'INPUT' && (element.getAttribute('type') || '').toLowerCase() == 'hidden', 'Input value expansion only works on hidden input fields: %s', element); const whitelist = this.getWhitelistForElement_(element); if (!whitelist) { return opt_sync ? element.value : Promise.resolve(element.value); } if (element[ORIGINAL_VALUE_PROPERTY] === undefined) { element[ORIGINAL_VALUE_PROPERTY] = element.value; } const result = this.expand_( element[ORIGINAL_VALUE_PROPERTY] || element.value, /* opt_bindings */ undefined, /* opt_collectVars */ undefined, /* opt_sync */ opt_sync, /* opt_whitelist */ whitelist); if (opt_sync) { return element.value = result; } return result.then(newValue => { element.value = newValue; return newValue; }); } /** * Returns a replacement whitelist from elements' data-amp-replace attribute. * @param {!Element} element * @param {!Object<string, boolean>=} opt_supportedReplacement Optional supported * replacement that filters whitelist to a subset. * @return {!Object<string, boolean>|undefined} */ getWhitelistForElement_(element, opt_supportedReplacement) { const whitelist = element.getAttribute('data-amp-replace'); if (!whitelist) { return; } const requestedReplacements = {}; whitelist.trim().split(/\s+/).forEach(replacement => { if (!opt_supportedReplacement || hasOwn(opt_supportedReplacement, replacement)) { requestedReplacements[replacement] = true; } else { user().warn('URL', 'Ignoring unsupported replacement', replacement); } }); return requestedReplacements; } /** * Returns whether variable substitution is allowed for given url. * @param {!Location} url * @return {boolean} */ isAllowedOrigin_(url) { const docInfo = Services.documentInfoForDoc(this.ampdoc); if (url.origin == parseUrlDeprecated(docInfo.canonicalUrl).origin || url.origin == parseUrlDeprecated(docInfo.sourceUrl).origin) { return true; } const meta = this.ampdoc.getRootNode().querySelector( 'meta[name=amp-link-variable-allowed-origin]'); if (meta && meta.hasAttribute('content')) { const whitelist = meta.getAttribute('content').trim().split(/\s+/); for (let i = 0; i < whitelist.length; i++) { if (url.origin == parseUrlDeprecated(whitelist[i]).origin) { return true; } } } return false; } /** * Replaces values in the link of an anchor tag if * - the link opts into it (via data-amp-replace argument) * - the destination is the source or canonical origin of this doc. * @param {!Element} element An anchor element. * @param {?string} defaultUrlParams to expand link if caller request. * @return {string|undefined} Replaced string for testing */ maybeExpandLink(element, defaultUrlParams) { dev().assert(element.tagName == 'A'); const supportedReplacements = { 'CLIENT_ID': true, 'QUERY_PARAM': true, 'PAGE_VIEW_ID': true, 'NAV_TIMING': true, }; const additionalUrlParameters = element.getAttribute('data-amp-addparams') || ''; const whitelist = this.getWhitelistForElement_( element, supportedReplacements); if (!whitelist && !additionalUrlParameters && !defaultUrlParams) { return; } // ORIGINAL_HREF_PROPERTY has the value of the href "pre-replacement". // We set this to the original value before doing any work and use it // on subsequent replacements, so that each run gets a fresh value. let href = dev().assertString( element[ORIGINAL_HREF_PROPERTY] || element.getAttribute('href')); const url = parseUrlDeprecated(href); if (element[ORIGINAL_HREF_PROPERTY] == null) { element[ORIGINAL_HREF_PROPERTY] = href; } if (additionalUrlParameters) { href = addParamsToUrl( href, parseQueryString(additionalUrlParameters)); } const isAllowedOrigin = this.isAllowedOrigin_(url); if (!isAllowedOrigin) { if (whitelist) { user().warn('URL', 'Ignoring link replacement', href, ' because the link does not go to the document\'s' + ' source, canonical, or whitelisted origin.'); } return element.href = href; } // Note that defaultUrlParams is treated differently than // additionalUrlParameters in two ways #1: If the outgoing url origin is not // whitelisted: additionalUrlParameters are always appended by not expanded, // defaultUrlParams will not be appended. #2: If the expansion function is // not whitelisted: additionalUrlParamters will not be expanded, // defaultUrlParams will by default support QUERY_PARAM, and will still be // expanded. if (defaultUrlParams) { if (!whitelist || !whitelist['QUERY_PARAM']) { // override whitelist and expand defaultUrlParams; const overrideWhitelist = {'QUERY_PARAM': true}; defaultUrlParams = this.expandUrlSync( defaultUrlParams, /* opt_bindings */ undefined, /* opt_collectVars */ undefined, /* opt_whitelist */ overrideWhitelist); } href = addParamsToUrl(href, parseQueryString(defaultUrlParams)); } if (whitelist) { href = this.expandUrlSync( href, /* opt_bindings */ undefined, /* opt_collectVars */ undefined, /* opt_whitelist */ whitelist); } return element.href = href; } /** * @param {string} url * @param {!Object<string, *>=} opt_bindings * @param {!Object<string, *>=} opt_collectVars * @param {boolean=} opt_sync * @param {!Object<string, boolean>=} opt_whiteList Optional white list of names * that can be substituted. * @return {!Promise<string>|string} * @private */ expand_(url, opt_bindings, opt_collectVars, opt_sync, opt_whiteList) { const isV2ExperimentOn = isExperimentOn(this.ampdoc.win, 'url-replacement-v2'); if (isV2ExperimentOn) { // TODO(ccordy) support opt_collectVars && opt_whitelist return this.expander_./*OK*/expand(url, opt_bindings, opt_collectVars, opt_sync, opt_whiteList); } // existing parsing method const expr = this.variableSource_.getExpr(opt_bindings); let replacementPromise; let replacement = url.replace(expr, (match, name, opt_strargs) => { let args = []; if (typeof opt_strargs == 'string') { args = opt_strargs.split(/,\s*/); } if (opt_whiteList && !opt_whiteList[name]) { // Do not perform substitution and just return back the original // match, so that the string doesn't change. return match; } let binding; if (opt_bindings && (name in opt_bindings)) { binding = opt_bindings[name]; } else if ((binding = this.variableSource_.get(name))) { if (opt_sync) { binding = binding.sync; if (!binding) { user().error(TAG, 'ignoring async replacement key: ', name); return ''; } } else { binding = binding.async || binding.sync; } } let val; try { val = (typeof binding == 'function') ? binding.apply(null, args) : binding; } catch (e) { // Report error, but do not disrupt URL replacement. This will // interpolate as the empty string. if (opt_sync) { val = ''; } rethrowAsync(e); } // In case the produced value is a promise, we don't actually // replace anything here, but do it again when the promise resolves. if (val && val.then) { if (opt_sync) { user().error(TAG, 'ignoring promise value for key: ', name); return ''; } /** @const {Promise<string>} */ const p = val.catch(err => { // Report error, but do not disrupt URL replacement. This will // interpolate as the empty string. rethrowAsync(err); }).then(v => { replacement = replacement.replace(match, NOENCODE_WHITELIST[match] ? v : encodeValue(v)); if (opt_collectVars) { opt_collectVars[match] = v; } }); if (replacementPromise) { replacementPromise = replacementPromise.then(() => p); } else { replacementPromise = p; } return match; } if (opt_collectVars) { opt_collectVars[match] = val; } return NOENCODE_WHITELIST[match] ? val : encodeValue(val); }); if (replacementPromise) { replacementPromise = replacementPromise.then(() => replacement); } if (opt_sync) { return replacement; } return replacementPromise || Promise.resolve(replacement); } /** * Collects all substitutions in the provided URL and expands them to the * values for known variables. Optional `opt_bindings` can be used to add * new variables or override existing ones. * @param {string} url * @param {!Object<string, *>=} opt_bindings * @return {!Promise<!Object<string, *>>} */ collectVars(url, opt_bindings) { const vars = Object.create(null); return this.expand_(url, opt_bindings, vars).then(() => vars); } /** * Collects substitutions in the `src` attribute of the given element * that are _not_ whitelisted via `data-amp-replace` opt-in attribute. * @param {!Element} element * @return {!Array<string>} */ collectUnwhitelistedVarsSync(element) { const url = element.getAttribute('src'); const vars = Object.create(null); this.expandStringSync(url, /* opt_bindings */ undefined, vars); const varNames = Object.keys(vars); const whitelist = this.getWhitelistForElement_(element); if (whitelist) { return varNames.filter(v => !whitelist[v]); } else { // All vars are unwhitelisted if the element has no whitelist. return varNames; } } /** * Ensures that the protocol of the original url matches the protocol of the * replacement url. Returns the replacement if they do, the original if they * do not. * @param {string} url * @param {string} replacement * @return {string} */ ensureProtocolMatches_(url, replacement) { const newProtocol = parseUrlDeprecated(replacement, /* opt_nocache */ true) .protocol; const oldProtocol = parseUrlDeprecated(url, /* opt_nocache */ true) .protocol; if (newProtocol != oldProtocol) { user().error(TAG, 'Illegal replacement of the protocol: ', url); return url; } user().assert(isProtocolValid(replacement), 'The replacement url has invalid protocol: %s', replacement); return replacement; } /** * @return {VariableSource} */ getVariableSource() { return this.variableSource_; } } /** * Extracts client ID from a _ga cookie. * https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id * @param {string} gaCookie * @return {string} */ export function extractClientIdFromGaCookie(gaCookie) { return gaCookie.replace(/^(GA1|1)\.[\d-]+\./, ''); } /** * @param {!./ampdoc-impl.AmpDoc} ampdoc */ export function installUrlReplacementsServiceForDoc(ampdoc) { registerServiceBuilderForDoc( ampdoc, 'url-replace', function(doc) { return new UrlReplacements(doc, new GlobalVariableSource(doc)); }); } /** * @param {!./ampdoc-impl.AmpDoc} ampdoc * @param {!Window} embedWin * @param {!VariableSource} varSource */ export function installUrlReplacementsForEmbed(ampdoc, embedWin, varSource) { installServiceInEmbedScope(embedWin, 'url-replace', new UrlReplacements(ampdoc, varSource)); } /** * @typedef {{incomingFragment: string, outgoingFragment: string}} */ let ShareTrackingFragmentsDef;
kamtschatka/amphtml
src/service/url-replacements-impl.js
JavaScript
apache-2.0
42,445
/******************************************************** Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *********************************************************/ var Util = require('../util/util.js'); function Player() { // Create an audio graph. window.AudioContext = window.AudioContext || window.webkitAudioContext; context = new AudioContext(); var analyser = context.createAnalyser(); //analyser.fftSize = 2048 * 2 * 2 // analyser.fftSize = (window.isMobile)? 2048 : 8192; analyser.fftSize = (window.isMobile)?1024 : 2048; analyser.smoothingTimeConstant = 0; // Create a mix. var mix = context.createGain(); // Create a bandpass filter. var bandpass = context.createBiquadFilter(); bandpass.Q.value = 10; bandpass.type = 'bandpass'; var filterGain = context.createGain(); filterGain.gain.value = 1; // Connect audio processing graph mix.connect(analyser); analyser.connect(filterGain); filterGain.connect(context.destination); this.context = context; this.mix = mix; // this.bandpass = bandpass; this.filterGain = filterGain; this.analyser = analyser; this.buffers = {}; // Connect an empty source node to the mix. Util.loadTrackSrc(this.context, 'bin/snd/empty.mp3', function(buffer) { var source = this.createSource_(buffer, true); source.loop = true; source.start(0); }.bind(this)); } Player.prototype.playSrc = function(src) { // Stop all of the mic stuff. this.filterGain.gain.value = 1; if (this.input) { this.input.disconnect(); this.input = null; return; } if (this.buffers[src]) { $('#loadingSound').fadeIn(100).delay(1000).fadeOut(500); this.playHelper_(src); return; } $('#loadingSound').fadeIn(100); Util.loadTrackSrc(this.context, src, function(buffer) { this.buffers[src] = buffer; this.playHelper_(src); $('#loadingSound').delay(500).fadeOut(500); }.bind(this)); }; Player.prototype.playUserAudio = function(src) { // Stop all of the mic stuff. this.filterGain.gain.value = 1; if (this.input) { this.input.disconnect(); this.input = null; return; } this.buffers['user'] = src.buffer; this.playHelper_('user'); }; Player.prototype.playHelper_ = function(src) { var buffer = this.buffers[src]; this.source = this.createSource_(buffer, true); this.source.start(0); if (!this.loop) { this.playTimer = setTimeout(function() { this.stop(); }.bind(this), buffer.duration * 2000); } }; Player.prototype.live = function() { // The AudioContext may be in a suspended state prior to the page receiving a user // gesture. If it is, resume it. if (this.context.state === 'suspended') { this.context.resume(); } if(window.isIOS){ window.parent.postMessage('error2','*'); console.log("cant use mic on ios"); }else{ if (this.input) { this.input.disconnect(); this.input = null; return; } var self = this; navigator.mediaDevices.getUserMedia({audio: true}).then(function(stream) { self.onStream_(stream); }).catch(function() { self.onStreamError(this); }); this.filterGain.gain.value = 0; } }; Player.prototype.onStream_ = function(stream) { var input = this.context.createMediaStreamSource(stream); input.connect(this.mix); this.input = input; this.stream = stream; }; Player.prototype.onStreamError_ = function(e) { // TODO: Error handling. }; Player.prototype.setLoop = function(loop) { this.loop = loop; }; Player.prototype.createSource_ = function(buffer, loop) { var source = this.context.createBufferSource(); source.buffer = buffer; source.loop = loop; source.connect(this.mix); return source; }; Player.prototype.setMicrophoneInput = function() { // TODO: Implement me! }; Player.prototype.stop = function() { if (this.source) { this.source.stop(0); this.source = null; clearTimeout(this.playTimer); this.playTimer = null; } if (this.input) { this.input.disconnect(); this.input = null; return; } }; Player.prototype.getAnalyserNode = function() { return this.analyser; }; Player.prototype.setBandpassFrequency = function(freq) { if (freq == null) { console.log('Removing bandpass filter'); // Remove the effect of the bandpass filter completely, connecting the mix to the analyser directly. this.mix.disconnect(); this.mix.connect(this.analyser); } else { // console.log('Setting bandpass frequency to %d Hz', freq); // Only set the frequency if it's specified, otherwise use the old one. this.bandpass.frequency.value = freq; this.mix.disconnect(); this.mix.connect(this.bandpass); // bandpass is connected to filterGain. this.filterGain.connect(this.analyser); } }; Player.prototype.playTone = function(freq) { if (!this.osc) { this.osc = this.context.createOscillator(); this.osc.connect(this.mix); this.osc.type = 'sine'; this.osc.start(0); } this.osc.frequency.value = freq; this.filterGain.gain.value = .2; }; Player.prototype.stopTone = function() { this.osc.stop(0); this.osc = null; }; module.exports = Player;
googlecreativelab/chrome-music-lab
spectrogram/src/javascripts/UI/player.js
JavaScript
apache-2.0
5,514
'use strict'; //GetAttribute() returns "boolean" values and will return either "true" or null describe('Report', function(){ var _ = require('lodash'); var Reports = require('../../app/reports/reports-page'); var Report = require('../../app/report/report-page'); var reports = new Reports(); var report, reportName, conceptName; it('Should create a new empty report', function(){ reports.visitPage(); reportName = 'HelloWorld' + Math.floor((Math.random() * 10) + 1); reports.createReport(reportName); reports.getCurrentUrl() .then(function(url){ var id = _.last(url.split('/')); report = new Report(id); expect(report.searchBox.isPresent()).toBe(true); expect(report.label.getText()).toBe(reportName); }); }); it('Should already contain an element', function(){ report.goToTaxonomy().concepts.goToConcept('h:ReportLineItems'); var concept = report.taxonomy.getConcept('h:ReportLineItems'); expect(concept.label.getAttribute('value')).toBe(reportName); expect(report.taxonomy.elements.count()).toBe(1); expect(report.taxonomy.rootElements.count()).toBe(1); }); it('Shouldn\'t create a new concept with an invalid name', function(){ conceptName = 'hello World'; report.goToTaxonomy(); var concepts = report.taxonomy.concepts; concepts.createConcept(conceptName); expect(concepts.errorMessage.isDisplayed()).toBe(true); expect(concepts.errorMessage.getText()).toBe('Invalid Concept Name'); }); it('Should create a new concept (1)', function(){ conceptName = 'h:helloWorldID'; report.goToTaxonomy(); var concepts = report.taxonomy.concepts; concepts.createConcept(conceptName); var concept = report.goToTaxonomy().concepts.goToConcept(conceptName); expect(concept.label.getAttribute('value')).toBe('Hello World ID'); }); it('Taxonomy Section should be active', function(){ expect(report.getActiveSection()).toBe('Taxonomy'); report.goToFacts(); report.goToTaxonomy(); expect(report.getActiveSection()).toBe('Taxonomy'); }); it('Should create a new concept (2)', function(){ conceptName = 'h:assets'; var concepts = report.taxonomy.concepts; report.goToTaxonomy(); concepts.createConcept(conceptName); var concept = report.goToTaxonomy().concepts.goToConcept(conceptName); expect(concept.label.getAttribute('value')).toBe('Assets'); }); it('Creates a new element', function(){ report.goToTaxonomy().concepts.goToConcept(conceptName); report.taxonomy.getConcept(conceptName).createElement(); expect(report.taxonomy.elements.count()).toBe(2); expect(report.taxonomy.rootElements.count()).toBe(1); }); it('Renames the concept label', function(){ var overview = report.goToTaxonomy().concepts.goToConcept(conceptName).overview; expect(overview.form.conceptLabel.getAttribute('value')).toBe('Assets'); overview.changeLabel('Assets Label'); expect(overview.form.conceptLabel.getAttribute('value')).toBe('Assets Label'); }); it('Creates a us-gaap:Assets synonym', function(){ var synonyms = report.taxonomy.getConcept(conceptName).goToSynonyms(); expect(synonyms.list.count()).toBe(0); synonyms.addSynonym('us-gaap:Assets'); synonyms.addSynonym('us-gaap:AssetsCurrent'); synonyms.addSynonym('us-gaap:AssetsCurrent'); expect(synonyms.list.count()).toBe(2); expect(synonyms.getName(synonyms.list.first())).toBe('us-gaap:Assets'); expect(synonyms.getName(synonyms.list.last())).toBe('us-gaap:AssetsCurrent'); }); it('Should display the fact table', function() { report.goToFacts(); expect(report.facts.lineCount()).toBeGreaterThan(0); }); it('Should display the preview', function() { report.goToSpreadsheet(); expect(report.spreadsheet.getCellValueByCss('.constraints .header')).toBe('Component: (Network and Table)'); }); it('Should delete report', function() { reports.visitPage(); reports.list.count().then(function(count){ reports.deleteReport(reportName).then(function(){ expect(reports.list.count()).toBe(count - 1); }); }); }); });
28msec/nolap-report-editor
tests/e2e/basic-scenario.js
JavaScript
apache-2.0
4,515
'use strict'; var app = angular.module('app', [ 'ngAnimate', 'ngCookies', 'ui.router', 'ui.bootstrap' ]); app.config(['$stateProvider', '$httpProvider', function ($stateProvider, $httpProvider) { $stateProvider.state('home', { url: '', templateUrl: 'App/partials/home.html', controller: 'HomeCtrl', data: { requireLogin: false } }); $stateProvider.state('play', { url: '/play', templateUrl: 'App/partials/play.html', controller: 'PlayCtrl', data: { requireLogin: true } }); $stateProvider.state('match', { url: '/match', templateUrl: 'App/partials/match.html', controller: 'MatchCtrl', data: { requireLogin: false } }); $stateProvider.state('team', { url: '/team', templateUrl: 'App/partials/team.html', controller: 'TeamCtrl', data: { requireLogin: false } }); $stateProvider.state('player', { url: '/player', templateUrl: 'App/partials/player.html', controller: 'PlayerCtrl', data: { requireLogin: false } }); $stateProvider.state('about', { url: '/about', templateUrl: 'App/partials/about.html', data: { requireLogin: false } }); $stateProvider.state('preferences', { url: '/preferences', templateUrl: 'App/partials/preferences.html', controller: 'PreferencesCtrl', data: { requireLogin: true } }); $httpProvider.interceptors.push(function ($timeout, $q, $injector) { var authModal, $http, $state; // this trick must be done so that we don't receive // `Uncaught Error: [$injector:cdep] Circular dependency found` $timeout(function () { authModal = $injector.get('authModal'); $http = $injector.get('$http'); $state = $injector.get('$state'); }); return { responseError: function (rejection) { return rejection;//may want to force modal on 401 auth failure, but not at this time if (rejection.status !== 401) { return rejection; } var deferred = $q.defer(); authModal() .then(function () { deferred.resolve($http(rejection.config)); }) .catch(function () { $state.go('home'); deferred.reject(rejection); }); return deferred.promise; } }; }); } ]); app.run(['$rootScope', '$state', 'authModal', 'authService', 'versionService', function ($rootScope, $state, authModal, authService, versionService) { $rootScope.$on('$stateChangeStart', function (event, toState, toParams) { versionService.getVersionInfo( function (version) { if (version.isOutOfDate) { $rootScope.$broadcast('alert', { type: 'warning', msg: 'Client version is out of date. Please refresh your browser.' }); } }, function () { $rootScope.$broadcast({ type: 'danger', msg: 'Server could not be reached. Please try again later.' }); }); if (toState.data.requireLogin && !authService.user.isAuthenticated) { event.preventDefault(); authModal() .then(function(data) { return $state.go(toState.name, toParams); }) .catch(function() { return $state.go('home'); }); } }); }]);
trentdm/Foos
src/Foos/App/app.js
JavaScript
apache-2.0
4,265
/*jshint camelcase: false */ var common = require('../../lib/common'); var msRestRequest = require('../../lib/common/msRestRequest'); var chai = require('chai'); var should = chai.should(); var util = require('util'); exports.clean = function(provisioningParameters, done) { var resourceGroupName = provisioningParameters.resourceGroup; if (!resourceGroupName) { return done(); } var environmentName = process.env['ENVIRONMENT']; var subscriptionId = process.env['SUBSCRIPTION_ID']; var API_VERSIONS = common.API_VERSION[environmentName]; var environment = common.getEnvironment(environmentName); var resourceManagerEndpointUrl = environment.resourceManagerEndpointUrl; var resourceGroupUrl = util.format('%s/subscriptions/%s/resourcegroups/%s', resourceManagerEndpointUrl, subscriptionId, resourceGroupName); var headers = common.mergeCommonHeaders('Delete resource group for integration test', {}); msRestRequest.DELETE(resourceGroupUrl, headers, API_VERSIONS.RESOURCE_GROUP, function (err, res, body) { should.not.exist(err); res.statusCode.should.equal(202); done(); }); };
zhongyi-zhang/meta-azure-service-broker
test/integration/cleaner.js
JavaScript
apache-2.0
1,244
var Canvas = require('canvas'); var Image = Canvas.Image; // Constants var canvasWidth = 350; var canvasHeight = 150; var cellSize = 30; var colorMap = { 0: 'rgba(0, 0, 0, 0)', 1: '#F7F6EA', 2: '#E6E6E1', 3: '#EBC000' }; module.exports = generate; function generate(title, accuracy) { var canvas = new Canvas(canvasWidth, canvasHeight); var ctx = canvas.getContext('2d'); drawTitle(ctx, title); drawAccuracy(ctx, accuracy); drawAccuracySub(ctx); drawHeatMap(ctx); return canvas.toBuffer(); }; function drawHeatMap(ctx) { var grid = [ [ 1, 3, 3, 2 ], [ 0, 1, 2, 1 ], [ 0, 2, 3, 1 ] ]; var y = 60; grid.forEach(function(r) { var x = canvasWidth - cellSize; r.reverse().forEach(function(c, j) { drawCell(ctx, x - (j * 2), y, colorMap[c]); x -= cellSize; }); y += cellSize; }); } function drawCell(ctx, x, y, fillColor) { ctx.fillStyle = fillColor; ctx.fillRect(x, y, cellSize, cellSize); } function drawTitle(ctx, title) { //var title = 'Profit and Discount drives sales with a'; ctx.font = '14px Kozuka Gothic Pro'; ctx.fillText(title, 20, 30); } function drawAccuracy(ctx, accuracy) { accuracy += '%'; ctx.font = '60px Kozuka Gothic Pro'; ctx.fillText(accuracy, 20, 100); } function drawAccuracySub(ctx) { var sub = 'driver strength'; ctx.font = '14px Kozuka Gothic Pro'; ctx.fillText(sub, 20, 125); }
gw1018/imageservice
images/heatmap.js
JavaScript
apache-2.0
1,415
import {moduleFor, test} from 'ember-qunit'; moduleFor('controller:login', 'Unit | Controller | login', { needs: ['service:metrics', 'service:session'] }); test('it exists', function (assert) { let controller = this.subject(); assert.ok(controller); });
piotrb5e3/0bit
tests/unit/controllers/login-test.js
JavaScript
apache-2.0
262
sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/core/mvc/Controller", "sap/ui/core/routing/History", "sap/ui/model/json/JSONModel" ], function (UIComponent, Controller, History, JSONModel) { "use strict"; return Controller.extend("sap.ui.core.sample.odata.v4.MusicArtists.PublicationObjectPage", { _onObjectMatched : function (oEvent) { var oEventArguments = oEvent.getParameter("arguments"), oView = this.getView(), oPublicationContext = oView.getModel() .bindContext("/" + oEventArguments.artistPath + "/" + oEventArguments.publicationPath) .getBoundContext(); oView.setBindingContext(oPublicationContext); oPublicationContext.requestObject("IsActiveEntity").then(function (bIsActiveEntity) { oView.getModel("ui-op").setProperty("/bEditMode", !bIsActiveEntity); }); }, onBack : function () { var sPreviousHash = History.getInstance().getPreviousHash(); this.getView().getModel("ui-op").setProperty("/bEditMode", false); if (sPreviousHash !== undefined) { window.history.go(-1); } else { this.getOwnerComponent().getRouter().navTo("masterList", null, true); } }, onInit : function () { var oRouter = UIComponent.getRouterFor(this); oRouter.getRoute("publicationObjectPage") .attachPatternMatched(this._onObjectMatched, this); this.getView().setModel(new JSONModel({bEditMode : false}), "ui-op"); } }); });
SAP/openui5
src/sap.ui.core/test/sap/ui/core/demokit/sample/odata/v4/MusicArtists/PublicationObjectPage.controller.js
JavaScript
apache-2.0
1,423
var autils = require('../../AUtils'); var osTool = require('../../osTools'); var shelljs = require('shelljs'); var GenericDiffReporterBase = require('../GenericDiffReporterBase'); class Reporter extends GenericDiffReporterBase { constructor() { super("BeyondCompare"); var app = null; if (osTool.platform.isMac) { try { app = shelljs.ls('/Applications/Beyond Compare.app/Contents/MacOS/bcomp')[0]; } catch (err) { console.error(err); } app = app || autils.searchForExecutable("bcomp"); } else if (osTool.platform.isWindows) { app = autils.searchForExecutable("Beyond Compare 4", "BCompare.exe") || autils.searchForExecutable("Beyond Compare 3", "BCompare.exe"); } app = app || autils.searchForExecutable("bcomp"); this.exePath = app; } } module.exports = Reporter;
approvals/Approvals.NodeJS
lib/Reporting/Reporters/beyondcompareReporter.js
JavaScript
apache-2.0
860
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * * @param {string} component - Component name * @param {object[]} collection - Array of objects describing available content * @return {object|false} Either a found item, or false. */ function componentHasDocs(component, collection) { const item = collection.filter((c) => `${c.fileSlug}.njk` === component); return item.length > 0 ? item[0] : false; } module.exports = (eleventy) => { eleventy.addFilter('componentHasDocs', componentHasDocs); };
chromeos/chromeos.dev
lib/filters/component-has-docs.js
JavaScript
apache-2.0
1,060
var stage, board, tiles, fleets, scale, sWid, is_dragging; var lastMouse = { x:0, y:0 }; var is_dragging = false; $(document).ready(function() { init_stage(); document.addEventListener('keyup', handleKeyUp, false); document.addEventListener('keydown', handleKeyDown, false); loadLobby(); }); /** * Called from createAll in game.js after all assets are loaded. * Clears old game globals, re-sets defaults. */ var setGlobals = function() { stage.removeChild(board); board = new createjs.Container(); tiles = []; fleetshapes = {}; scale = 0.60; }; var handleKeyUp = function( e ) { switch (e.keyCode) { case 189: // dash zoomBoard(-0.05); break; case 187: // equals (plus sign) zoomBoard(0.05); break; default: break; } }; var handleKeyDown = function( e ) { switch (e.keyCode) { case 37: // left arrow moveBoard(-1, 0); break; case 38: // up arrow moveBoard(0, -1); break; case 39: moveBoard(1, 0); break; case 40: moveBoard(0, 1); break; default: break; } }; /** * Calls init and draw functions for each tile in game board */ var createBoard = function() { if (stage) { initSelection(); updateCanvasSize(); drawAsteroids(); drawTiles(); drawNoFlyZones(); drawBases(); drawAgents(); drawFleets(); drawSprites(); stage.addChild( board ); scale = 0.75; var boardWidth = 7 * sWid * scale; var boardHeight = 7 * sWid * scale; board.x = (window.innerWidth - boardWidth) / 2.0; board.y = (window.innerHeight - boardHeight) / 2.0; board.scaleX = scale; board.scaleY = scale; fadeIn(board, 1000, false, false); } }; var drawAsteroids = function() { var asteroids = clientGame.game.board.asteroids; for ( var a = 0; a < asteroids.length; a++ ) { drawAsteroid( asteroids[a] ); } }; var drawTiles = function() { var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { initTile(p); drawTile(p); } }; var drawFleets = function() { initFleets(); var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateFleets(p); } }; var drawNoFlyZones = function() { var planets = clientGame.game.board.planets; initNoFlyZones(); updateNoFlyZones(); }; var drawBases = function() { var planets = clientGame.game.board.planets; initBases(); for ( var p = 0; p < planets.length; p++ ) { updateBases(p); } }; var drawAgents = function() { initAgents(); var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateAgents(p); } }; /** * Calls function to turn mouse enablement on/off on different * createJS containers based on what action the user is in. */ var updateBoardInteractivity = function() { var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateTileInteractivity(p); } updateFleetsInteractivity(); updateBasesInteractivity(); updateAgentsInteractivity(); }; /** * Calls update functions on each tile to update appearance, interactivity * based on current pending action or game event */ var updateBoard = function() { var planets = clientGame.game.board.planets; // this sets all bases to invisible. Update function will reveal // and draw any that are on planets. updateRemovedBases(); for ( var p = 0; p < planets.length; p++ ) { updateTileInteractivity(p); updateTileImage(p); updateFleets(p); updateBases(p); updateAgents(p); } updateNoFlyZones(); updateRemovedFleets(); updateDeadAgents(); stage.update(); };
Zebbeni/alien-empire
client/game_board.js
JavaScript
apache-2.0
3,574
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var gulp = require('gulp-help')(require('gulp')); var path = require('path'); var srcGlobs = require('../config').presubmitGlobs; var util = require('gulp-util'); var dedicatedCopyrightNoteSources = /(\.js|\.css|\.go)$/; var es6polyfill = 'Not available because we do not currently' + ' ship with a needed ES6 polyfill.'; var requiresReviewPrivacy = 'Usage of this API requires dedicated review due to ' + 'being privacy sensitive. Please file an issue asking for permission' + ' to use if you have not yet done so.'; var privateServiceFactory = 'This service should only be installed in ' + 'the whitelisted files. Other modules should use a public function ' + 'typically called serviceNameFor.'; var shouldNeverBeUsed = 'Usage of this API is not allowed - only for internal purposes.'; // Terms that must not appear in our source files. var forbiddenTerms = { 'DO NOT SUBMIT': '', 'describe\\.only': '', 'it\\.only': '', 'sinon\\.(spy|stub|mock)\\(\\w[^)]*\\)': { message: 'Use a sandbox instead to avoid repeated `#restore` calls' }, '(\\w*([sS]py|[sS]tub|[mM]ock|clock).restore)': { message: 'Use a sandbox instead to avoid repeated `#restore` calls' }, 'sinon\\.useFake\\w+': { message: 'Use a sandbox instead to avoid repeated `#restore` calls' }, 'console\\.\\w+\\(': { message: 'If you run against this, use console/*OK*/.log to ' + 'whitelist a legit case.', // TODO: temporary, remove when validator is up to date whitelist: [ 'validator/validator.js', 'validator/parse-css.js', 'validator/validator-in-browser.js', ] }, 'iframePing': { message: 'This is only available in vendor config for ' + 'temporary workarounds.', whitelist: [ 'extensions/amp-analytics/0.1/amp-analytics.js', ], }, // Service factories that should only be installed once. 'installActionService': { message: privateServiceFactory, whitelist: [ 'src/service/action-impl.js', 'src/service/standard-actions-impl.js', 'src/amp-core-service.js', ], }, 'installActionHandler': { message: privateServiceFactory, whitelist: [ 'src/service/action-impl.js', 'extensions/amp-access/0.1/amp-access.js', ], }, 'installActivityService': { message: privateServiceFactory, whitelist: [ 'src/service/activity-impl.js', 'extensions/amp-analytics/0.1/amp-analytics.js' ] }, 'installCidService': { message: privateServiceFactory, whitelist: [ 'src/service/cid-impl.js', 'extensions/amp-access/0.1/amp-access.js', 'extensions/amp-analytics/0.1/amp-analytics.js', ], }, 'installStorageService': { message: privateServiceFactory, whitelist: [ 'extensions/amp-analytics/0.1/amp-analytics.js', 'src/service/storage-impl.js', ], }, 'installViewerService': { message: privateServiceFactory, whitelist: [ 'src/amp-core-service.js', 'src/service/history-impl.js', 'src/service/resources-impl.js', 'src/service/viewer-impl.js', 'src/service/viewport-impl.js', 'src/service/vsync-impl.js', ], }, 'installViewportService': { message: privateServiceFactory, whitelist: [ 'src/amp-core-service.js', 'src/service/resources-impl.js', 'src/service/viewport-impl.js', ], }, 'installVsyncService': { message: privateServiceFactory, whitelist: [ 'src/amp-core-service.js', 'src/service/resources-impl.js', 'src/service/viewport-impl.js', 'src/service/vsync-impl.js', ], }, 'installResourcesService': { message: privateServiceFactory, whitelist: [ 'src/amp-core-service.js', 'src/service/resources-impl.js', 'src/service/standard-actions-impl.js', ], }, 'sendMessage': { message: privateServiceFactory, whitelist: [ 'src/service/viewer-impl.js', 'src/service/storage-impl.js', 'examples/viewer-integr-messaging.js', 'extensions/amp-access/0.1/login-dialog.js', ], }, // Privacy sensitive 'cidFor': { message: requiresReviewPrivacy, whitelist: [ 'builtins/amp-ad.js', 'src/cid.js', 'src/service/cid-impl.js', 'src/url-replacements.js', 'extensions/amp-access/0.1/amp-access.js', 'extensions/amp-user-notification/0.1/amp-user-notification.js', ], }, 'getBaseCid': { message: requiresReviewPrivacy, whitelist: [ 'src/service/cid-impl.js', 'src/service/viewer-impl.js', ], }, 'cookie\\W': { message: requiresReviewPrivacy, whitelist: [ 'src/cookies.js', 'src/service/cid-impl.js', ], }, 'getCookie\\W': { message: requiresReviewPrivacy, whitelist: [ 'src/service/cid-impl.js', 'src/cookies.js', 'src/experiments.js', 'tools/experiments/experiments.js', ] }, 'setCookie\\W': { message: requiresReviewPrivacy, whitelist: [ 'src/service/cid-impl.js', 'src/cookies.js', 'src/experiments.js', 'tools/experiments/experiments.js', ] }, 'isDevChannel\\W': { message: requiresReviewPrivacy, whitelist: [ 'extensions/amp-access/0.1/amp-access.js', 'extensions/amp-user-notification/0.1/amp-user-notification.js', 'src/3p-frame.js', 'src/experiments.js', 'src/service/storage-impl.js', 'src/service/viewport-impl.js', 'tools/experiments/experiments.js', ] }, 'isDevChannelVersionDoNotUse_\\W': { message: shouldNeverBeUsed, whitelist: [ 'src/experiments.js', ] }, 'isTrusted': { message: requiresReviewPrivacy, whitelist: [ 'src/service/viewer-impl.js', ] }, 'eval\\(': '', 'storageFor': { message: requiresReviewPrivacy, whitelist: [ 'src/storage.js', 'extensions/amp-user-notification/0.1/amp-user-notification.js', ], }, 'localStorage': { message: requiresReviewPrivacy, whitelist: [ 'src/service/cid-impl.js', 'src/service/storage-impl.js', ], }, 'sessionStorage': requiresReviewPrivacy, 'indexedDB': requiresReviewPrivacy, 'openDatabase': requiresReviewPrivacy, 'requestFileSystem': requiresReviewPrivacy, 'webkitRequestFileSystem': requiresReviewPrivacy, 'getAccessReaderId': { message: requiresReviewPrivacy, whitelist: [ 'extensions/amp-access/0.1/amp-access.js', 'src/url-replacements.js', ] }, 'getAuthdataField': { message: requiresReviewPrivacy, whitelist: [ 'extensions/amp-access/0.1/amp-access.js', 'src/url-replacements.js', ] }, 'debugger': '', // ES6. These are only the most commonly used. 'Array\\.of': es6polyfill, // These currently depend on core-js/modules/web.dom.iterable which // we don't want. That decision could be reconsidered. '\\.startsWith': { message: es6polyfill, whitelist: [ 'validator/tokenize-css.js', 'validator/validator.js' ] }, '\\.endsWith': { message: es6polyfill, whitelist: [ // .endsWith occurs in babel generated code. 'dist.3p/current/integration.js', ], }, // TODO: (erwinm) rewrite the destructure and spread warnings as // eslint rules (takes more time than this quick regex fix). // No destructuring allowed since we dont ship with Array polyfills. '^\\s*(?:let|const|var) *(?:\\[[^\\]]+\\]|{[^}]+}) *=': es6polyfill, // No spread (eg. test(...args) allowed since we dont ship with Array // polyfills except `arguments` spread as babel does not polyfill // it since it can assume that it can `slice` w/o the use of helpers. '\\.\\.\\.(?!arguments\\))[_$A-Za-z0-9]*(?:\\)|])': { message: es6polyfill, whitelist: [ 'extensions/amp-access/0.1/access-expr-impl.js', ], }, // Overridden APIs. '(doc.*)\\.referrer': { message: 'Use Viewer.getReferrerUrl() instead.', whitelist: [ '3p/integration.js', 'dist.3p/current/integration.js', 'src/service/viewer-impl.js', 'src/error.js', ], }, '(doc[^.]*)\\.contains': { message: 'Use dom.documentContains API.', whitelist: [ 'src/dom.js', ], }, '\\sdocument(?![a-zA-Z0-9_])': { message: 'Use `window.document` or similar to access document, the global' + '`document` is forbidden', whitelist: [ 'validator/validator.js', 'testing/iframe.js', 'testing/screenshots/make-screenshot.js', 'tools/experiments/experiments.js', 'examples/viewer-integr.js', ], }, 'getUnconfirmedReferrerUrl': { message: 'Use Viewer.getReferrerUrl() instead.', whitelist: [ 'extensions/amp-dynamic-css-classes/0.1/amp-dynamic-css-classes.js', 'src/3p-frame.js', 'src/service/viewer-impl.js', ], }, 'setTimeout.*throw': { message: 'Use dev.error or user.error instead.', whitelist: [ 'src/log.js', ], }, }; var ThreePTermsMessage = 'The 3p bootstrap iframe has no polyfills loaded and' + ' can thus not use most modern web APIs.'; var forbidden3pTerms = { // We need to forbid promise usage because we don't have our own polyfill // available. This whitelisting of callNext is a major hack to allow one // usage in babel's external helpers that is in a code path that we do // not use. '\\.then\\((?!callNext)': ThreePTermsMessage, 'Math\\.sign' : ThreePTermsMessage, }; var bannedTermsHelpString = 'Please review viewport.js for a helper method ' + 'or mark with `/*OK*/` or `/*REVIEW*/` and consult the AMP team. ' + 'Most of the forbidden property/method access banned on the ' + '`forbiddenTermsSrcInclusive` object can be found in ' + '[What forces layout / reflow gist by Paul Irish]' + '(https://gist.github.com/paulirish/5d52fb081b3570c81e3a). ' + 'These properties/methods when read/used require the browser ' + 'to have the up-to-date value to return which might possibly be an ' + 'expensive computation and could also be triggered multiple times ' + 'if we are not careful. Please mark the call with ' + '`object./*OK*/property` if you explicitly need to read or update the ' + 'forbidden property/method or mark it with `object./*REVIEW*/property` ' + 'if you are unsure and so that it stands out in code reviews.'; var forbiddenTermsSrcInclusive = { '\\.innerHTML(?!_)': bannedTermsHelpString, '\\.outerHTML(?!_)': bannedTermsHelpString, '\\.postMessage(?!_)': bannedTermsHelpString, '\\.offsetLeft(?!_)': bannedTermsHelpString, '\\.offsetTop(?!_)': bannedTermsHelpString, '\\.offsetWidth(?!_)': bannedTermsHelpString, '\\.offsetHeight(?!_)': bannedTermsHelpString, '\\.offsetParent(?!_)': bannedTermsHelpString, '\\.clientLeft(?!_)(?!_)': bannedTermsHelpString, '\\.clientTop(?!_)': bannedTermsHelpString, '\\.clientWidth(?!_)': bannedTermsHelpString, '\\.clientHeight(?!_)': bannedTermsHelpString, '\\.getClientRects(?!_)': bannedTermsHelpString, '\\.getBoundingClientRect(?!_)': bannedTermsHelpString, '\\.scrollBy(?!_)': bannedTermsHelpString, '\\.scrollTo(?!_|p|p_)': bannedTermsHelpString, '\\.scrollIntoView(?!_)': bannedTermsHelpString, '\\.scrollIntoViewIfNeeded(?!_)': bannedTermsHelpString, '\\.scrollWidth(?!_)': 'please use `getScrollWidth()` from viewport', '\\.scrollHeight(?!_)': bannedTermsHelpString, '\\.scrollTop(?!_)': bannedTermsHelpString, '\\.scrollLeft(?!_)': bannedTermsHelpString, '\\.focus(?!_)': bannedTermsHelpString, '\\.computedRole(?!_)': bannedTermsHelpString, '\\.computedName(?!_)': bannedTermsHelpString, '\\.innerText(?!_)': bannedTermsHelpString, '\\.getComputedStyle(?!_)': bannedTermsHelpString, '\\.scrollX(?!_)': bannedTermsHelpString, '\\.scrollY(?!_)': bannedTermsHelpString, '\\.pageXOffset(?!_)': bannedTermsHelpString, '\\.pageYOffset(?!_)': bannedTermsHelpString, '\\.innerWidth(?!_)': bannedTermsHelpString, '\\.innerHeight(?!_)': bannedTermsHelpString, '\\.getMatchedCSSRules(?!_)': bannedTermsHelpString, '\\.scrollingElement(?!_)': bannedTermsHelpString, '\\.computeCTM(?!_)': bannedTermsHelpString, '\\.getBBox(?!_)': bannedTermsHelpString, '\\.webkitConvertPointFromNodeToPage(?!_)': bannedTermsHelpString, '\\.webkitConvertPointFromPageToNode(?!_)': bannedTermsHelpString, '\\.changeHeight(?!_)': bannedTermsHelpString, '\\.changeSize(?!_)': bannedTermsHelpString, 'reject\\(\\)': { message: 'Always supply a reason in rejections. ' + 'error.cancellation() may be applicable.', whitelist: [ 'extensions/amp-access/0.1/access-expr-impl.js', ], } }; // Terms that must appear in a source file. var requiredTerms = { 'Copyright 20(15|16) The AMP HTML Authors\\.': dedicatedCopyrightNoteSources, 'Licensed under the Apache License, Version 2\\.0': dedicatedCopyrightNoteSources, 'http\\://www\\.apache\\.org/licenses/LICENSE-2\\.0': dedicatedCopyrightNoteSources, }; /** * Check if root of path is test/ or file is in a folder named test. * @param {string} path * @return {boolean} */ function isInTestFolder(path) { var dirs = path.split('/'); var folder = dirs[dirs.length - 2]; return path.startsWith('test/') || folder == 'test'; } function stripComments(contents) { // Multi-line comments contents = contents.replace(/\/\*(?!.*\*\/)(.|\n)*?\*\//g, ''); // Single line comments with only leading whitespace contents = contents.replace(/\n\s*\/\/.*/g, ''); // Single line comments following a space, semi-colon, or closing brace return contents.replace(/( |\}|;)\s*\/\/.*/g, '$1'); } /** * Logs any issues found in the contents of file based on terms (regex * patterns), and provides any possible fix information for matched terms if * possible * * @param {!File} file a vinyl file object to scan for term matches * @param {!Array<string, string>} terms Pairs of regex patterns and possible * fix messages. * @return {boolean} true if any of the terms match the file content, * false otherwise */ function matchTerms(file, terms) { var pathname = file.path; var contents = stripComments(file.contents.toString()); var relative = file.relative; return Object.keys(terms).map(function(term) { var fix; var whitelist = terms[term].whitelist; // NOTE: we could do a glob test instead of exact check in the future // if needed but that might be too permissive. if (Array.isArray(whitelist) && (whitelist.indexOf(relative) != -1 || isInTestFolder(relative))) { return false; } // we can't optimize building the `RegExp` objects early unless we build // another mapping of term -> regexp object to be able to get back to the // original term to get the possible fix value. This is ok as the // presubmit doesn't have to be blazing fast and this is most likely // negligible. var matches = contents.match(new RegExp(term, 'gm')); if (matches) { util.log(util.colors.red('Found forbidden: "' + matches[0] + '" in ' + relative)); if (typeof terms[term] == 'string') { fix = terms[term]; } else { fix = terms[term].message; } // log the possible fix information if provided for the term. if (fix) { util.log(util.colors.blue(fix)); } util.log(util.colors.blue('==========')); return true; } return false; }).some(function(hasAnyTerm) { return hasAnyTerm; }); } /** * Test if a file's contents match any of the * forbidden terms * * @param {!File} file file is a vinyl file object * @return {boolean} true if any of the terms match the file content, * false otherwise */ function hasAnyTerms(file) { var pathname = file.path; var basename = path.basename(pathname); var hasTerms = false; var hasSrcInclusiveTerms = false; var has3pTerms = false; hasTerms = matchTerms(file, forbiddenTerms); var isTestFile = /^test-/.test(basename) || /^_init_tests/.test(basename); if (!isTestFile) { hasSrcInclusiveTerms = matchTerms(file, forbiddenTermsSrcInclusive); } var is3pFile = /3p|ads/.test(pathname) || basename == '3p.js' || basename == 'style.js'; if (is3pFile && !isTestFile) { has3pTerms = matchTerms(file, forbidden3pTerms); } return hasTerms || hasSrcInclusiveTerms || has3pTerms; } /** * Test if a file's contents fail to match any of the required terms and log * any missing terms * * @param {!File} file file is a vinyl file object * @return {boolean} true if any of the terms are not matched in the file * content, false otherwise */ function isMissingTerms(file) { var contents = file.contents.toString(); return Object.keys(requiredTerms).map(function(term) { var filter = requiredTerms[term]; if (!filter.test(file.path)) { return false; } var matches = contents.match(new RegExp(term)); if (!matches) { util.log(util.colors.red('Did not find required: "' + term + '" in ' + file.relative)); util.log(util.colors.blue('==========')); return true; } return false; }).some(function(hasMissingTerm) { return hasMissingTerm; }); } /** * Check a file for all the required terms and * any forbidden terms and log any errors found. */ function checkForbiddenAndRequiredTerms() { var forbiddenFound = false; var missingRequirements = false; return gulp.src(srcGlobs) .pipe(util.buffer(function(err, files) { forbiddenFound = files.map(hasAnyTerms).some(function(errorFound) { return errorFound; }); missingRequirements = files.map(isMissingTerms).some( function(errorFound) { return errorFound; }); })) .on('end', function() { if (forbiddenFound) { util.log(util.colors.blue( 'Please remove these usages or consult with the AMP team.')); } if (missingRequirements) { util.log(util.colors.blue( 'Adding these terms (e.g. by adding a required LICENSE ' + 'to the file)')); } if (forbiddenFound || missingRequirements) { process.exit(1); } }); } gulp.task('presubmit', 'Run validation against files to check for forbidden ' + 'and required terms', checkForbiddenAndRequiredTerms);
nekodo/amphtml
build-system/tasks/presubmit-checks.js
JavaScript
apache-2.0
18,988
var detect_flowint_8c = [ [ "MAX_SUBSTRINGS", "detect-flowint_8c.html#a7d9ab03945d9f1a2af62c4bb49206536", null ], [ "PARSE_REGEX", "detect-flowint_8c.html#adcc3158aa6bb4d1bd0ddf953a33f55ec", null ], [ "DetectFlowintFree", "detect-flowint_8c.html#a7fbc34befd7d405cffd01896b8fddf6f", null ], [ "DetectFlowintMatch", "detect-flowint_8c.html#a40c8b26b75abf03617041f16184e36e3", null ], [ "DetectFlowintParse", "detect-flowint_8c.html#a5de91a84b01bbd9025e80cb39d1afed6", null ], [ "DetectFlowintPrintData", "detect-flowint_8c.html#aeaa2897d6d4cf82a976ab60a421073c2", null ], [ "DetectFlowintRegister", "detect-flowint_8c.html#ac30dcb9bacbf06d17420281f2b697864", null ], [ "DetectFlowintRegisterTests", "detect-flowint_8c.html#acf3e2f66ce897b5d596da1391084f7f4", null ] ];
onosfw/apis
suricata/apis/detect-flowint_8c.js
JavaScript
apache-2.0
798
'use strict'; // Report overall code coverage from Istanbul coverage files. // Implemented in ES5 for now /* eslint no-var: 0 */ var _ = require('underscore'); var path = require('path'); var fs = require('fs'); var util = require('util'); var tty = require('tty'); var istanbul = require('istanbul'); var map = _.map; var filter = _.filter; var pairs = _.pairs; var object = _.object; var clone = _.clone; var extend = _.extend; var values = _.values; var flatten = _.flatten; var reduce = _.reduce; var identity = _.identity; var memoize = _.memoize; /* eslint no-process-exit: 1 */ // Return the path of the Abacus module dir containing a file var moddir = function(file) { if(file === '.' || file === '/') return undefined; if(/cf-abacus.*/.test(path.basename(file))) return file; return moddir(path.dirname(file)); }; // Convert the covered file paths in the given coverage info to relative paths // to the original source files var sources = function(root, cov) { return object(filter(map(pairs(cov), function(file) { // Determine the build path and the name of the module containing each // covered file var mdir = moddir(file[0]); var mod = path.basename(mdir); // Determine the path to the module source directory var sdir = root.dependencies[mod] || root.devDependencies[mod]; if(!sdir) return [file[0], file[1]]; // Return a covered object with a relative path to the original source // of the covered file var lib = path.join(sdir, file[0].substr(mdir.length + 1)).split(':').reverse()[0].split('/'); var l = lib.lastIndexOf('lib'); var src = lib.slice(0, l).concat(['src']).concat(lib.slice(l + 1)).join('/'); return [src, extend(clone(file[1]), { path: src })]; }), function(file) { return file[1]; })); }; // Return a list of all the individual json coverage files for our modules var covfiles = function(cb) { fs.readdir('node_modules', function(err, files) { cb(undefined, filter([path.join('.coverage', 'coverage.json')].concat(err ? [] : map(files, function(file) { return path.join('node_modules', file, '.coverage', 'coverage.json'); })), fs.existsSync)); }); }; // Return a coverage collector loaded with all the given files var collect = function(root, cb) { covfiles(function(err, files) { if(err) cb(err); var collector = new istanbul.Collector(); map(files, function(file) { collector.add(sources(root, JSON.parse(fs.readFileSync(file)))); }); cb(undefined, collector); }); }; // Compute overall line and statement coverage percentages var percentages = function(coverage) { // Count overall covered and totals of lines, statements and branches var t = reduce(values(coverage), function(a, cov) { var l = values(cov.l); var s = values(cov.s); var b = flatten(values(cov.b)); return { l: { covered: a.l.covered + filter(l, identity).length, total: a.l.total + l.length }, s: { covered: a.s.covered + filter(s, identity).length, total: a.s.total + s.length }, b: { covered: a.b.covered + filter(b, identity).length, total: a.b.total + b.length }}; }, { l: { covered: 0, total: 0 }, s: { covered: 0, total: 0 }, b: { covered: 0, total: 0 }}); // Return the coverage percentages return { l: t.l.covered / (t.l.total || 1) * 100, s: (t.s.covered + /*t.b.covered*/ 0) / (t.s.total + /*t.b.total*/ 0 || 1) * 100 }; }; // Colorify the report on a tty or when the command line says --colors, // or when env variable COVERAGE_COLORS is configured var colors = memoize(function() { var enabled = function(c) { return c !== undefined && c !== '0' && c !== 'false' && c !== 'disabled' && c !== 'no'; }; return tty.isatty(process.stdout) || _.contains(process.argv, '--colors') || enabled(process.env.COVERAGE_COLORS); }); // Report a failure and exit var fail = function(msg) { process.stderr.write(msg); process.exit(1); }; // Report overall code coverage from Istanbul coverage files var runCLI = function() { // Load the root package.json from the current directory var root = JSON.parse(fs.readFileSync('package.json')); // Collect all the individual json coverage reports for our modules collect(root, function(err, collector) { if(err) fail(util.format('Couldn\'t collect coverage files', err)); // Combine all the individual reports and write overall coverage // reports in LCOV and JSON formats var reporter = new istanbul.Reporter(undefined, '.coverage'); reporter.addAll(['lcovonly', 'json']); reporter.write(collector, false, function(err) { if(err) fail(util.format('Couldn\'t write coverage reports', err, '\n')); // Compute and report overall line and statement coverage var percent = percentages(collector.getFinalCoverage()); var fullcov = percent.l === 100 && percent.s === 100; // Print overall code coverage percentages in green for 100% // coverage and red under 100% var color = colors() ? fullcov ? '\u001b[32m' : '\u001b[31m' : ''; var reset = colors() ? '\u001b[0m' : ''; process.stdout.write(util.format('\n%sOverall coverage lines %d\% statements %d\%%s\n\n', color, percent.l.toFixed(2), percent.s.toFixed(2), reset)); process.exit(0); }); }); }; // Export our public functions module.exports.runCLI = runCLI;
stefanschneider/cf-abacus
tools/coverage/src/index.js
JavaScript
apache-2.0
5,626
/** * Trim leading and trailing whitespace * @return {String} Returns trimmed string */ String.prototype.trim = function() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); } /** * Creates a new string utilizing placeholders defined in the source string * @param {Object} values Array or object whose indices or properties correspond to placeholder names * @exception {KeyNotFoundError} Key or property not found * @exception {FormatError} Format was invalid * @return {String} Returns formatted results * @remarks Placeholders are defined by placing text inside curly brackets. To insert literal curly brackets, simply use 2 consecutive curly brackets. * The text inside the curly brackets represents a property or index to obtain from the 'values' parameter. * @example var values = { 1: "First", 2: "Second" }; * return "One is {1} and {{Two}} is {{{2}}}".toFormattedString(values); // results in "One is First and {Two} is {Second}" */ String.prototype.toFormattedString = function(values) { var formatStr = String(this); var result = ''; var re = /^([^{}]*)(\{+|\}+)(.*?)$/; var rr = re.exec(formatStr); var isInPlaceholder = false; var placeHolderKey = ''; var position = 0; while (rr != null) { formatStr = rr[3]; var placeHolderLen = rr[2].length % 2; if (isInPlaceholder) { if (placeHolderLen == 1) { if (rr[2].substr(0, 1) == '{') throw new FormatError(undefined, "Unexpected opening brace", String(this), position + rr[1].length); isInPlaceholder = false; placeHolderKey += rr[1]; if (values === undefined || values === null) throw new KeyNotFoundError(undefined, "values were not defined", placeHolderKey, String(this), position + rr[1].length); var v; try { v = values[placeHolderKey]; } catch (err) { throw new KeyNotFoundError(undefined, undefined, placeHolderKey, String(this), position + rr[1].length, err) } if (v === undefined) throw new KeyNotFoundError(undefined, undefined, placeHolderKey, String(this), position + rr[1].length); result += ((v === null) ? "" : String(v)) + rr[2].substr(0, (rr[2].length - placeHolderLen) / 2); } else placeHolderKey += rr[1] + rr[2].substr(0, (rr[2].length - placeHolderLen) / 2); } else { result += rr[1] + rr[2].substr(0, (rr[2].length - placeHolderLen) / 2); if (placeHolderLen == 1) { if (rr[2].substr(0, 1) == '}') throw new FormatError(undefined, "Unexpected closing brace", String(this), position + rr[1].length); isInPlaceholder = true; } } position += r[1].length + r[2].length; rr = re.exec(formatStr); } if (isInPlaceholder) throw new FormatError(undefined, "Closing brace not found", String(this), position); return result + formatStr; }
lerwine/JSCookbook
src/TypeExtensions/StringExtensions.js
JavaScript
apache-2.0
2,780
///done, not debug __g_qrmCmatsize__ = [ undefined, 11, 13, 15, 17 ]; /// __g_qrmCdatacodewords__ = { L:[ undefined, 3, 5, 11, 16 ], M:[ undefined, 0, 4, 9, 14 ], Q:[ undefined, 0, 0, 0, 10 ] }; /// __g_qrmCtotalcodewords__ = { L:[ undefined, ], M:[ undefined, ], Q:[ undefined, ] }; /// __g_qrmCeccodewords__ = { L:[ undefined, ], M:[ undefined, ], Q:[ undefined, ] }; ///notyet __g_qrmCdatalen__ = { // number of characters [num,alnum,8bit,kanji] L:[ undefined, [ 0, 0, 0, 0],// 1 [ 0, 0, 0, 0],// 2 [ 0, 0, 0, 0],// 3 [ 0, 0, 0, 0] // 4 ], M:[ undefined, [ 0, 0, 0, 0],// 1 [ 0, 0, 0, 0],// 2 [ 0, 0, 0, 0],// 3 [ 0, 0, 0, 0] // 4 ], Q:[ undefined, [ 0, 0, 0, 0],// 1 [ 0, 0, 0, 0],// 2 [ 0, 0, 0, 0],// 3 [ 0, 0, 0, 0] // 4 ] }; /// __g_qrmCsegments__ = [ //[[repeat,totalCodewords,dataCodewords,correctableCodewords],...] undefined, { L:[[ 1, 5, 3, 0]] },//1 { L:[[ 1, 10, 5, 1]], M:[[ 1, 10, 4, 2]] },//2 { L:[[ 1, 17, 11, 2]], M:[[ 1, 17, 9, 4]] },//3 { L:[[ 1, 24, 16, 3]], M:[[ 1, 24, 14, 5]], Q:[[ 1, 24, 10, 7]] } //4 ]; /// __g_qrmCtypenumbers__ = { L:[ undefined, 0, 1, 3, 5 ], M:[ undefined, undefined, 2, 4, 6 ], Q:[ undefined, undefined, undefined, undefined, 7 ] }; /// QrMCSymbolInfo = __extends(Object, // constructor function(version, eclevel) { __constructSuper(this); if (version == undefined) { version = 1; } if (eclevel == undefined) { eclevel = "M"; } this.version = version; this.eclevel = {L:1,M:0,Q:3}[eclevel]; // L<M<Q this.matrixSize = __g_qrmCmatsize__ [version]; this.dataCodewords = __g_qrmCdatacodewords__[eclevel][version]; this.segments = __g_qrmCsegments__ [version][eclevel]; this.typeNumber = __g_qrmCtypenumbers__ [eclevel][version]; }, // methods function(__this__) { __this__.MAXVER = 4; });
qnq777/matrixcode.js-legacy
public_html/js/qrcode/qrmcdata.js
JavaScript
apache-2.0
2,139
define(function (require, exports) { var ko = require('knockout') var expressionViewer = require('./components/CohortExpressionViewer'); ko.components.register('cohort-expression-viewer', expressionViewer); var criteriaGroup = require('./components/CriteriaGroup'); ko.components.register('criteria-group-viewer', criteriaGroup); var conditionOccurrence = require('./components/ConditionOccurrence'); ko.components.register('condition-occurrence-criteria-viewer', conditionOccurrence); var conditionEra = require('./components/ConditionEra'); ko.components.register('condition-era-criteria-viewer', conditionEra); var drugExposure = require('./components/DrugExposure'); ko.components.register('drug-exposure-criteria-viewer', drugExposure); var drugEra = require('./components/DrugEra'); ko.components.register('drug-era-criteria-viewer', drugEra); var doseEra = require('./components/DoseEra'); ko.components.register('dose-era-criteria-viewer', doseEra); var procedureOccurrence = require('./components/ProcedureOccurrence'); ko.components.register('procedure-occurrence-criteria-viewer', procedureOccurrence); var observation = require('./components/Observation'); ko.components.register('observation-criteria-viewer', observation); var visitOccurrence = require('./components/VisitOccurrence'); ko.components.register('visit-occurrence-criteria-viewer', visitOccurrence); var deviceExposure = require('./components/DeviceExposure'); ko.components.register('device-exposure-criteria-viewer', deviceExposure); var measurement = require('./components/Measurement'); ko.components.register('measurement-criteria-viewer', measurement); var observationPeriod = require('./components/ObservationPeriod'); ko.components.register('observation-period-criteria-viewer', observationPeriod); var specimen = require('./components/Specimen'); ko.components.register('specimen-criteria-viewer', specimen); var death = require('./components/Death'); ko.components.register('death-criteria-viewer', death); var numericRange = require('./components/NumericRange'); ko.components.register('numeric-range-viewer', numericRange); var dateRange = require('./components/DateRange'); ko.components.register('date-range-viewer', dateRange); var windowInput = require('./components/WindowInput'); ko.components.register('window-input-viewer',windowInput); var textFilter = require('./components/TextFilter'); ko.components.register('text-filter-viewer',textFilter); var conceptList = require('./components/ConceptList'); ko.components.register('concept-list-viewer',conceptList); var conceptSetReference = require('./components/ConceptSetReference'); ko.components.register('conceptset-reference',conceptSetReference); var conceptSetViewer = require('./components/ConceptSetViewer'); ko.components.register('conceptset-viewer',conceptSetViewer); });
OHDSI/Circe
js/modules/cohortdefinitionviewer/main.js
JavaScript
apache-2.0
2,914
'use strict'; import express from 'express'; import passport from 'passport'; import config from '../config/environment'; import {User} from '../sqldb'; // Passport Configuration require('./local/passport').setup(User, config); require('./facebook/passport').setup(User, config); require('./google/passport').setup(User, config); require('./twitter/passport').setup(User, config); var router = express.Router(); router.use('/local', require('./local')); router.use('/facebook', require('./facebook')); router.use('/twitter', require('./twitter')); router.use('/google', require('./google')); router.use('/wechat', require('./wechat')); export default router;
jintou/jintou-backend
server/auth/index.js
JavaScript
apache-2.0
664
export default class Shared { getPrettyDate(time) { const date = new Date((time || '').replace(/-/g,'/').replace(/[TZ]/g,' ')); const diff = (((new Date()).getTime() - date.getTime()) / 1000); const day_diff = Math.floor(diff / 86400); // return date for anything greater than a day if (isNaN(day_diff) || day_diff < 0 || day_diff > 0) { return date.getDate() + ' ' + date.toDateString().split(' ')[1]; } return (day_diff === 0 && ((diff < 60 && 'just now') || (diff < 120 && '1 minute ago') || (diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago') || (diff < 7200 && '1 hour ago') || (diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago'))) || (day_diff === 1 && 'Yesterday') || (day_diff < 7 && day_diff + ' days ago') || (day_diff < 31 && Math.ceil( day_diff / 7 ) + ' weeks ago'); } }
beckettkev/react-chat-back
src/utils/shared.js
JavaScript
apache-2.0
867
jQuery(document).ready(function($){ $("a[data-upvote-id]").click(function(){ var id = $(this).attr('data-upvote-id'); $.ajax( { url: WP_API_Settings.root + 'goodmorning-news/1.0/upvote/' + id, method: 'GET', beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce ); } } ).done( function ( response ) { console.log( response ); } ); }); $("a[data-downvote-id]").click(function(){ var id = $(this).attr('data-downvote-id'); $.ajax( { url: WP_API_Settings.root + 'goodmorning-news/1.0/downvote/' + id, method: 'GET', beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce ); } } ).done( function ( response ) { console.log( response ); } ); }); });
Luehrsen/good_morning_news
www/wp-content/plugins/goodmorning_plugin/js/admin.js
JavaScript
apache-2.0
787
import Ember from 'ember'; import HasIdMixin from '../mixins/has-id'; const { computed, Mixin, assert, defineProperty } = Ember; /* A mixin that enriches a component that is attached to a model property. The property name by default is taken from the formComponent, computed unless explictly defined in the `property` variable. This mixin also binds a property named `errors` to the model's `model.errors.@propertyName` array */ export default Mixin.create(HasIdMixin, { property: undefined, propertyName: computed('property', 'formComponent.property', { get() { if (this.get('property')) { return this.get('property'); } else if (this.get('formComponent.property')) { return this.get('formComponent.property'); } else { return assert(false, 'Property could not be found.'); } } }), init() { this._super(...arguments); defineProperty(this, 'errors', computed.alias((`model.errors.${this.get('propertyName')}`))); } });
slannigan/computed_input_errors
addon/mixins/has-property.js
JavaScript
apache-2.0
1,005
angular.module('asics').controller('ReportCtrl', [ '$mdToast', '$scope', '$interval', 'admin', '$stateParams', function ($mdToast, $scope, $interval, admin, $stateParams) { $scope.strings = {}; $scope.language = $stateParams.language; $scope.country_count = []; $scope.available_dates = []; $scope.current_date = []; angular.copy(adminReportStrings[$scope.language], $scope.strings); function get_reports(day) { admin.getReport(day) .then(readReportInformation) .catch(errorToast); } createDateList(); setCurrentDate(); function createDateList() { for (var day = 3; day < 22; day++) { $scope.available_dates.push({ date: day }); } } function setCurrentDate() { var d = new Date(); var day = d.getDate(); $scope.current_date = $.grep($scope.available_dates, function(e){ return e.date == day })[0]; } function readReportInformation(result) { angular.copy(result.country_count, $scope.country_count); } $scope.$watch('current_date', function () { get_reports($scope.current_date.date) }); function errorToast(error) { var toast = $mdToast.simple() .textContent(error) .position('top right') .hideDelay(3000) .theme('error-toast'); $mdToast.show(toast); } } ]); var adminReportStrings = { EN: { date: "Day", title: "Visitors list", description: "Select the date to look up the number of visitors per country on that day." }, PT: { date: "Dia", title: "Lista de visitantes", description: "Selecione a data para pesquisar o número de visitantes por país no dia." } };
d3estudio/asics-access
web/app/assets/javascripts/controllers/admin/reportCtrl.js
JavaScript
apache-2.0
1,736
(function(){'use strict'; module.exports = (function () { if (process.argv.indexOf('--no-color') !== -1) { return false; } if (process.argv.indexOf('--color') !== -1) { return true; } if (process.stdout && !process.stdout.isTTY) { return false; } if (process.platform === 'win32') { return true; } if ('COLORTERM' in process.env) { return true; } if (process.env.TERM === 'dumb') { return false; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { return true; } return false; })(); })();
durwasa-chakraborty/navigus
.demeteorized/bundle/programs/server/app/lib/node_modules/modulus/node_modules/update-notifier/node_modules/chalk/node_modules/has-color/index.js
JavaScript
apache-2.0
555
/** * @module utils */ const crypto = require( 'crypto' ); const config = require( '../models/config-model' ).server; const validUrl = require( 'valid-url' ); // var debug = require( 'debug' )( 'utils' ); /** * Returns a unique, predictable openRosaKey from a survey oject * * @static * @param {module:survey-model~SurveyObject} survey * @param {string} [prefix] * @return {string|null} openRosaKey */ function getOpenRosaKey( survey, prefix ) { if ( !survey || !survey.openRosaServer || !survey.openRosaId ) { return null; } prefix = prefix || 'or:'; // Server URL is not case sensitive, form ID is case-sensitive return `${prefix + cleanUrl( survey.openRosaServer )},${survey.openRosaId.trim()}`; } /** * Returns a XForm manifest hash. * * @static * @param {Array} manifest * @param {string} type - Webform type * @return {string} Hash */ function getXformsManifestHash( manifest, type ) { const hash = ''; if ( !manifest || manifest.length === 0 ) { return hash; } if ( type === 'all' ) { return md5( JSON.stringify( manifest ) ); } if ( type ) { const filtered = manifest.map( mediaFile => mediaFile[ type ] ); return md5( JSON.stringify( filtered ) ); } return hash; } /** * Cleans a Server URL so it becomes useful as a db key * It strips the protocol, removes a trailing slash, removes www, and converts to lowercase * * @static * @param {string} url - Url to be cleaned up * @return {string} Cleaned up url */ function cleanUrl( url ) { url = url.trim(); if ( url.lastIndexOf( '/' ) === url.length - 1 ) { url = url.substring( 0, url.length - 1 ); } const matches = url.match( /https?:\/\/(www\.)?(.+)/ ); if ( matches && matches.length > 2 ) { return matches[ 2 ].toLowerCase(); } return url; } /** * The name of this function is deceiving. It checks for a valid server URL and therefore doesn't approve of: * - fragment identifiers * - query strings * * @static * @param {string} url - Url to be validated * @return {boolean} Whether the url is valid */ function isValidUrl( url ) { return !!validUrl.isWebUri( url ) && !( /\?/.test( url ) ) && !( /#/.test( url ) ); } /** * Returns md5 hash of given message * * @static * @param {string} message - Message to be hashed * @return {string} Hash string */ function md5( message ) { const hash = crypto.createHash( 'md5' ); hash.update( message ); return hash.digest( 'hex' ); } /** * This is not secure encryption as it doesn't use a random cipher. Therefore the result is * always the same for each text & pw (which is desirable in this case). * This means the password is vulnerable to be cracked, * and we should use a dedicated low-importance password for this. * * @static * @param {string} text - The text to be encrypted * @param {string} pw - The password to use for encryption * @return {string} The encrypted result */ function insecureAes192Encrypt( text, pw ) { let encrypted; const cipher = crypto.createCipher( 'aes192', pw ); encrypted = cipher.update( text, 'utf8', 'hex' ); encrypted += cipher.final( 'hex' ); return encrypted; } /** * Decrypts encrypted text. * * @static * @param {*} encrypted - The text to be decrypted * @param {*} pw - The password to use for decryption * @return {string} The decrypted result */ function insecureAes192Decrypt( encrypted, pw ) { let decrypted; const decipher = crypto.createDecipher( 'aes192', pw ); decrypted = decipher.update( encrypted, 'hex', 'utf8' ); decrypted += decipher.final( 'utf8' ); return decrypted; } /** * Returns random howMany-lengthed string from provided characters. * * @static * @param {number} [howMany] - Desired length of string * @param {string} [chars] - Characters to use * @return {string} Random string */ function randomString( howMany = 8, chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) { const rnd = crypto.randomBytes( howMany ); return new Array( howMany ) .fill() // create indices, so map can iterate .map( ( val, i ) => chars[ rnd[ i ] % chars.length ] ) .join( '' ); } /** * Returns random item from array. * * @static * @param {Array} array - Target array * @return {*|null} Random array item */ function pickRandomItemFromArray( array ) { if ( !Array.isArray( array ) || array.length === 0 ) { return null; } const random = Math.floor( Math.random() * array.length ); if ( !array[ random ] ) { return null; } return array[ random ]; } /** * Compares two objects by shallow properties. * * @static * @param {object} a - First object to be compared * @param {object} b - Second object to be compared * @return {null|boolean} Whether objects are equal (`null` for invalid arguments) */ function areOwnPropertiesEqual( a, b ) { let prop; const results = []; if ( typeof a !== 'object' || typeof b !== 'object' ) { return null; } for ( prop in a ) { if ( Object.prototype.hasOwnProperty.call( a, prop ) ) { if ( a[ prop ] !== b[ prop ] ) { return false; } results[ prop ] = true; } } for ( prop in b ) { if ( !results[ prop ] && Object.prototype.hasOwnProperty.call( b, prop ) ) { if ( b[ prop ] !== a[ prop ] ) { return false; } } } return true; } /** * Converts a url to a local (proxied) url. * * @static * @param {string} url - The url to convert * @return {string} The converted url */ function toLocalMediaUrl( url ) { const localUrl = `${config[ 'base path' ]}/media/get/${url.replace( /(https?):\/\//, '$1/' )}`; return localUrl; } module.exports = { getOpenRosaKey, getXformsManifestHash, cleanUrl, isValidUrl, md5, randomString, pickRandomItemFromArray, areOwnPropertiesEqual, insecureAes192Decrypt, insecureAes192Encrypt, toLocalMediaUrl };
kobotoolbox/enketo-express
app/lib/utils.js
JavaScript
apache-2.0
6,115
/* eslint-env browser */ (function() { 'use strict'; // Check to make sure service workers are supported in the current browser, // and that the current page is accessed from a secure origin. Using a // service worker from an insecure origin will trigger JS console errors. See // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features var isLocalhost = Boolean(window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address. window.location.hostname === '[::1]' || // 127.0.0.1/8 is considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); if ('serviceWorker' in navigator && (window.location.protocol === 'https:' || isLocalhost)) { navigator.serviceWorker.register('service-worker.js') .then(function(registration) { // Check to see if there's an updated version of service-worker.js with // new files to cache: // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-registration-update-method if (typeof registration.update === 'function') { registration.update(); } // updatefound is fired if service-worker.js changes. registration.onupdatefound = function() { // updatefound is also fired the very first time the SW is installed, // and there's no need to prompt for a reload at that point. // So check here to see if the page is already controlled, // i.e. whether there's an existing service worker. if (navigator.serviceWorker.controller) { // The updatefound event implies that registration.installing is set: // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event var installingWorker = registration.installing; installingWorker.onstatechange = function() { switch (installingWorker.state) { case 'installed': // At this point, the old content will have been purged and the // fresh content will have been added to the cache. // It's the perfect time to display a 'New content is // available; please refresh.' message in the page's interface. break; case 'redundant': throw new Error('The installing ' + 'service worker became redundant.'); default: // Ignore } }; } }; }).catch(function(e) { console.error('Error during service worker registration:', e); }); } // Your custom JavaScript goes here // var rss_tuoitre = 'http://tuoitre.vn/rss/tt-tin-moi-nhat.rss'; // var rss_vnexpress = 'http://vnexpress.net/rss/tin-moi-nhat.rss'; var rssReader = 'yql'; var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); function urlBuilder(type, url) { if (type === "rss") { if (rssReader === 'google') { return 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=20&q=' + url; } else if (rssReader === 'yql') { return 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22' + url + '%22&format=json'; } } else { return url; } } var displayDiv = document.getElementById('mainContent'); // Part 1 - Create a function that returns a promise function getJsonAsync(url) { // Promises require two functions: one for success, one for failure return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { if (xhr.readyState == 4 && xhr.status === 200) { // We can resolve the promise resolve(xhr.response); } else { // It's a failure, so let's reject the promise reject('Unable to load RSS'); } } xhr.onerror = () => { // It's a failure, so let's reject the promise reject('Unable to load RSS'); }; xhr.send(); }); } function getNewsDetail(type, link, callback) { if (type === "json") { callback(news[link]); return; } // get news detail by using rest api which are created by import.io showLoading(); var connector = 'e920a944-d799-4ed7-a017-322eb25ace70'; if (link.indexOf('tuoitre.vn') > -1) { connector = 'bdf72c89-c94b-48f4-967b-b5bc3f8288f7'; } else if (link.indexOf('vnexpress.net') > -1 || link.indexOf('gamethu.net') > -1) { connector = 'e920a944-d799-4ed7-a017-322eb25ace70'; } $.ajax({ url: 'https://api.import.io/store/connector/' + connector + '/_query', data: { input: 'webpage/url:' + link, _apikey: '59531d5e38004cbd944872b657c479fb6eb8a951555700c13023482aad713db52a65da670cd35dbe42a8fc32301bb78f419cba619c4c1c2e66ecde01de25b90dc014dece32953d8ad7c9de7ad788a261' }, success: function(response) { callback(response.results[0]); }, error: function(error) { showDialog({ title: 'Error', text: error }) }, complete: function() { hideLoading(); } }); } var news = []; function loadNews(type, url) { showLoading(); url = urlBuilder(type, url); var promise = $.ajax({ url: url, // crossDomain: true, // dataType: "jsonp" }); promise.done(function(response) { displayDiv.innerHTML = ''; if (type === "rss") { if (rssReader === 'google') { if (response.responseData.feed) { news = response.responseData.feed.entries; } else { news = response.query.results.item; } } else if (rssReader === 'yql') { news = response.query.results.item; } } else if (type === "json") { news = response.results.results || response.results.items || response.results.collection1; } news.forEach(item => { displayDiv.innerHTML += getTemplateNews(item); }); $('button.simple-ajax-popup').on('click', function(e) { e.preventDefault(); var link = $(this).data('link'); console.log(link); if (!link) { showDialog({ title: 'no link', text: link }) return; } if (type === "json") { link = $(this).parents('.news-item').index(); }; getNewsDetail(type, link, function(detail) { var content_html = detail.content_html || detail.content; if (!isChrome) { content_html = content_html.replace(new RegExp('.webp', 'g'), ''); } var $content = $('<div>' + content_html + '</div'); $content.find('.nocontent').remove(); // var $content = $(content_html).siblings(".nocontent").remove(); showDialog({ title: detail.title, text: $content.html() }) }) }); }).complete(function() { hideLoading(); }); } function getTemplateNews(news) { if (!news.content) { news.content = news.description || ""; } news.content = news.content.replace(new RegExp('/s146/', 'g'), '/s440/'); news.summary = news.summary || news.content; if (!news.image && news.summary.indexOf('<img ') === -1 && news.content.indexOf('<img ') > -1) { news.image = $(news.content).find('img:first-child').attr('src'); } news.image = (news.image) ? `<img src="${news.image.replace(new RegExp('/s146/', 'g'), '/s440/')}" />` : ''; if (!isChrome) { news.image = news.image.replace(new RegExp('.webp', 'g'), ''); } news.time = news.time || news.publishedDate || news.pubDate || ''; news.link = news.link || news.url; news.sourceText = news.source ? ' - ' + news.source.text : ''; return `<div class='news-item mdl-color-text--grey-700 mdl-shadow--2dp'> <div class='news-item__title'> <div class='news-item__title-text mdl-typography--title'> ${news.title} </div> <div class='news-item__title-time'>${news.time} <b>${news.sourceText}</b></div> </div> <div class='news-item__content'> ${news.image} ${news.summary} </div> <div class='news-item__actions'> <button data-link='${news.link}' class='mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect simple-ajax-popup'> View more </button> <a href='${news.link}' target='_blank' class='mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect simple-ajax-popup'> Open web </a> </div> </div>` } $('.change-news').click(function(e) { loadNews($(this).data('type'), $(this).data('url')); $(".mdl-layout__obfuscator").click(); }); $('.change-news:first-child').click(); // PLUGIN mdl-jquery-modal-dialog.js function showLoading() { // remove existing loaders $('.loading-container').remove(); $('<div id="orrsLoader" class="loading-container"><div><div class="mdl-spinner mdl-js-spinner is-active"></div></div></div>').appendTo("body"); componentHandler.upgradeElements($('.mdl-spinner').get()); setTimeout(function() { $('#orrsLoader').css({ opacity: 1 }); }, 1); } function hideLoading() { $('#orrsLoader').css({ opacity: 0 }); setTimeout(function() { $('#orrsLoader').remove(); }, 400); } function showDialog(options) { options = $.extend({ id: 'orrsDiag', title: null, text: null, negative: false, positive: false, cancelable: true, contentStyle: null, onLoaded: false }, options); // remove existing dialogs $('.dialog-container').remove(); $(document).unbind("keyup.dialog"); $('<div id="' + options.id + '" class="dialog-container"><div class="mdl-card mdl-shadow--16dp"></div></div>').appendTo("body"); var dialog = $('#orrsDiag'); var content = dialog.find('.mdl-card'); if (options.contentStyle != null) content.css(options.contentStyle); if (options.title != null) { $('<h5>' + options.title + '</h5>').appendTo(content); } if (options.text != null) { $('<p>' + options.text + '</p>').appendTo(content); } if (options.negative || options.positive) { var buttonBar = $('<div class="mdl-card__actions dialog-button-bar"></div>'); if (options.negative) { options.negative = $.extend({ id: 'negative', title: 'Cancel', onClick: function() { return false; } }, options.negative); var negButton = $('<button class="mdl-button mdl-js-button mdl-js-ripple-effect" id="' + options.negative.id + '">' + options.negative.title + '</button>'); negButton.click(function(e) { e.preventDefault(); if (!options.negative.onClick(e)) hideDialog(dialog) }); negButton.appendTo(buttonBar); } if (options.positive) { options.positive = $.extend({ id: 'positive', title: 'OK', onClick: function() { return false; } }, options.positive); var posButton = $('<button class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" id="' + options.positive.id + '">' + options.positive.title + '</button>'); posButton.click(function(e) { e.preventDefault(); if (!options.positive.onClick(e)) hideDialog(dialog) }); posButton.appendTo(buttonBar); } buttonBar.appendTo(content); } componentHandler.upgradeDom(); if (options.cancelable) { dialog.click(function() { hideDialog(dialog); }); $(document).bind("keyup.dialog", function(e) { if (e.which == 27) hideDialog(dialog); }); content.click(function(e) { e.stopPropagation(); }); } setTimeout(function() { dialog.css({ opacity: 1 }); if (options.onLoaded) options.onLoaded(); }, 1); } function hideDialog(dialog) { $(document).unbind("keyup.dialog"); dialog.css({ opacity: 0 }); setTimeout(function() { dialog.remove(); }, 400); } })();
leetrunghoo/surfnews
app/scripts/main.js
JavaScript
apache-2.0
15,008
/* * ../../../..//fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js * * Copyright (c) 2009-2018 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /************************************************************* * * MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js * * Defines the image size data needed for the HTML-CSS OutputJax * to display mathematics using fallback images when the fonts * are not available to the client browser. * * --------------------------------------------------------------------- * * Copyright (c) 2009-2013 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.OutputJax["HTML-CSS"].defineImageData({ MathJax_AMS: { 0x20: [ // SPACE [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0] ], 0x41: [ // LATIN CAPITAL LETTER A [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [17, 16, 0], [20, 19, 0], [23, 23, 0], [28, 27, 0], [33, 33, 0], [39, 39, 0], [46, 46, 0] ], 0x42: [ // LATIN CAPITAL LETTER B [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [29, 32, 0], [35, 38, 0], [41, 45, 0] ], 0x43: [ // LATIN CAPITAL LETTER C [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [16, 16, 0], [19, 21, 2], [23, 24, 1], [27, 28, 1], [32, 34, 1], [38, 40, 1], [45, 48, 2] ], 0x44: [ // LATIN CAPITAL LETTER D [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [16, 16, 0], [20, 19, 0], [23, 22, 0], [27, 27, 0], [32, 32, 0], [39, 38, 0], [46, 45, 0] ], 0x45: [ // LATIN CAPITAL LETTER E [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [22, 22, 0], [26, 27, 0], [30, 32, 0], [36, 38, 0], [43, 45, 0] ], 0x46: [ // LATIN CAPITAL LETTER F [5, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [9, 9, 0], [10, 11, 0], [12, 13, 0], [14, 16, 0], [17, 19, 0], [20, 22, 0], [23, 27, 0], [27, 32, 0], [33, 38, 0], [39, 45, 0] ], 0x47: [ // LATIN CAPITAL LETTER G [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 10, 0], [13, 12, 0], [15, 14, 0], [18, 16, 0], [21, 19, 0], [25, 24, 1], [30, 29, 2], [35, 33, 0], [42, 40, 1], [50, 47, 1] ], 0x48: [ // LATIN CAPITAL LETTER H [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 9, 0], [13, 11, 0], [15, 13, 0], [18, 16, 0], [22, 19, 0], [26, 22, 0], [30, 27, 0], [36, 32, 0], [43, 38, 0], [51, 45, 0] ], 0x49: [ // LATIN CAPITAL LETTER I [3, 5, 0], [4, 6, 0], [4, 7, 0], [5, 8, 0], [6, 9, 0], [7, 11, 0], [8, 13, 0], [9, 16, 0], [11, 19, 0], [13, 22, 0], [15, 27, 0], [18, 32, 0], [21, 38, 0], [25, 45, 0] ], 0x4a: [ // LATIN CAPITAL LETTER J [4, 6, 1], [4, 7, 1], [5, 8, 1], [6, 9, 1], [7, 11, 2], [8, 13, 2], [10, 15, 2], [12, 18, 2], [14, 21, 2], [16, 26, 4], [19, 30, 3], [23, 35, 3], [27, 42, 4], [32, 50, 5] ], 0x4b: [ // LATIN CAPITAL LETTER K [6, 5, 0], [7, 6, 0], [8, 7, 0], [10, 8, 0], [11, 9, 0], [13, 11, 0], [15, 13, 0], [18, 16, 0], [22, 19, 0], [26, 22, 0], [31, 27, 0], [36, 32, 0], [43, 38, 0], [51, 45, 0] ], 0x4c: [ // LATIN CAPITAL LETTER L [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [22, 22, 0], [26, 27, 0], [30, 32, 0], [36, 38, 0], [43, 45, 0] ], 0x4d: [ // LATIN CAPITAL LETTER M [7, 5, 0], [8, 6, 0], [10, 7, 0], [11, 8, 0], [13, 9, 0], [16, 11, 0], [19, 13, 0], [22, 16, 0], [26, 19, 0], [31, 22, 0], [37, 27, 0], [44, 32, 0], [52, 38, 0], [61, 45, 0] ], 0x4e: [ // LATIN CAPITAL LETTER N [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 9, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [17, 17, 0], [20, 21, 1], [24, 24, 1], [28, 29, 1], [33, 34, 1], [39, 40, 1], [47, 48, 2] ], 0x4f: [ // LATIN CAPITAL LETTER O [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 10, 0], [13, 12, 0], [15, 14, 0], [18, 16, 0], [21, 21, 2], [25, 24, 1], [30, 28, 1], [35, 34, 1], [42, 40, 1], [49, 48, 2] ], 0x50: [ // LATIN CAPITAL LETTER P [5, 5, 0], [5, 6, 0], [6, 7, 0], [8, 8, 0], [9, 9, 0], [10, 11, 0], [12, 13, 0], [14, 16, 0], [17, 19, 0], [20, 22, 0], [24, 27, 0], [28, 32, 0], [34, 38, 0], [40, 45, 0] ], 0x51: [ // LATIN CAPITAL LETTER Q [6, 6, 1], [7, 8, 2], [8, 9, 2], [9, 10, 2], [11, 12, 2], [13, 15, 3], [15, 17, 3], [18, 20, 4], [21, 24, 5], [25, 30, 7], [30, 35, 8], [35, 41, 8], [42, 49, 10], [49, 58, 12] ], 0x52: [ // LATIN CAPITAL LETTER R [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x53: [ // LATIN CAPITAL LETTER S [4, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [8, 10, 0], [9, 12, 0], [11, 14, 0], [13, 16, 0], [15, 19, 0], [18, 23, 0], [21, 27, 0], [25, 33, 0], [30, 40, 1], [35, 47, 1] ], 0x54: [ // LATIN CAPITAL LETTER T [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [30, 32, 0], [36, 38, 0], [42, 45, 0] ], 0x55: [ // LATIN CAPITAL LETTER U [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 28, 1], [33, 33, 1], [40, 39, 1], [47, 46, 1] ], 0x56: [ // LATIN CAPITAL LETTER V [5, 5, 0], [6, 6, 0], [8, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [15, 13, 0], [17, 16, 0], [20, 20, 1], [24, 24, 2], [29, 28, 1], [34, 33, 1], [40, 39, 1], [48, 46, 1] ], 0x57: [ // LATIN CAPITAL LETTER W [7, 5, 0], [9, 6, 0], [10, 7, 0], [12, 8, 0], [14, 9, 0], [17, 11, 0], [20, 13, 0], [24, 16, 0], [28, 20, 1], [33, 24, 2], [39, 28, 1], [47, 33, 1], [55, 39, 1], [66, 47, 2] ], 0x58: [ // LATIN CAPITAL LETTER X [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x59: [ // LATIN CAPITAL LETTER Y [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x5a: [ // LATIN CAPITAL LETTER Z [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [30, 32, 0], [36, 38, 0], [42, 45, 0] ], 0x6b: [ // LATIN SMALL LETTER K [4, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [8, 10, 0], [9, 12, 0], [11, 14, 0], [13, 16, 0], [15, 19, 0], [18, 23, 0], [21, 27, 0], [25, 32, 0], [30, 38, 0], [36, 45, 0] ] } }); MathJax.Ajax.loadComplete( MathJax.OutputJax["HTML-CSS"].imgDir + "/AMS/Regular" + MathJax.OutputJax["HTML-CSS"].imgPacked + "/BBBold.js" );
GerHobbelt/MathJax
fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js
JavaScript
apache-2.0
10,460
/*! * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var path = require('path'); var uniq = require('array-uniq'); var globby = require('globby'); var spawn = require('child_process').spawnSync; require('shelljs/global'); /** * google-cloud-node root directory.. useful in case we need to cd */ var ROOT_DIR = path.join(__dirname, '..'); module.exports.ROOT_DIR = ROOT_DIR; /** * Helper class to make install dependencies + running tests easier to read * and less error prone. * * @class Module * @param {string} name - The module name (e.g. common, bigquery, etc.) */ function Module(name) { if (!(this instanceof Module)) { return new Module(name); } this.name = name; this.directory = path.join(ROOT_DIR, 'packages', name); var pkgJson = require(path.join(this.directory, 'package.json')); this.packageName = pkgJson.name; this.dependencies = Object.keys(pkgJson.devDependencies || {}); } /** * Umbrella module name. * * @static */ Module.UMBRELLA = 'google-cloud'; /** * Retrieves a list of modules that are ahead of origin/master. We do this by * creating a temporary remote branch that points official master branch. * We then do a git diff against the two to get a list of files. From there we * only care about either JS or JSON files being changed. * * @static * @return {Module[]} modules - The updated modules. */ Module.getUpdated = function() { var command = 'git'; var args = ['diff']; if (!isPushToMaster()) { run([ 'git remote add temp', 'https://github.com/GoogleCloudPlatform/google-cloud-node.git' ]); run('git fetch -q temp'); args.push('HEAD', 'temp/master'); } else { args.push('HEAD^'); } args.push('--name-only'); console.log(command, args.join(' ')); // There's a Windows bug where child_process.exec exits early on `git diff` // which in turn does not return all of the files that have changed. This can // cause a false positive when checking for package changes on AppVeyor var output = spawn(command, args, { cwd: ROOT_DIR, stdio: null }); if (output.status || output.error) { console.error(output.error || output.stderr.toString()); exit(output.status || 1); } var files = output.stdout.toString(); console.log(files); var modules = files .trim() .split('\n') .filter(function(file) { return /^packages\/.+\.js/.test(file); }) .map(function(file) { return file.split('/')[1]; }); return uniq(modules).map(Module); }; /** * Builds docs for all modules * * @static */ Module.buildDocs = function() { run('npm run docs', { cwd: ROOT_DIR }); }; /** * Returns a list containing ALL the modules. * * @static * @return {Module[]} modules - All of em'! */ Module.getAll = function() { cd(ROOT_DIR); return globby .sync('*', { cwd: 'packages' }) .map(Module); }; /** * Returns a list of modules that are dependent on one or more of the modules * specified. * * @static * @param {Module[]} modules - The dependency modules. * @return {Module[]} modules - The dependent modules. */ Module.getDependents = function(modules) { return Module.getAll().filter(function(mod) { return mod.hasDeps(modules); }); }; /** * Installs dependencies for all the modules! * * @static */ Module.installAll = function() { run('npm run postinstall', { cwd: ROOT_DIR }); }; /** * Generates an lcov coverage report for the specified modules. * * @static */ Module.runCoveralls = function() { run('npm run coveralls', { cwd: ROOT_DIR }); }; /** * Installs this modules dependencies via `npm install` */ Module.prototype.install = function() { run('npm install', { cwd: this.directory }); }; /** * Creates/uses symlink for a module (depending on if module was provided) * via `npm link` * * @param {Module=} mod - The module to use with `npm link ${mod.packageName}` */ Module.prototype.link = function(mod) { run(['npm link', mod && mod.packageName || ''], { cwd: this.directory }); }; /** * Runs unit tests for this module via `npm run test` */ Module.prototype.runUnitTests = function() { run('npm run test', { cwd: this.directory }); }; /** * Runs snippet tests for this module. */ Module.prototype.runSnippetTests = function() { process.env.TEST_MODULE = this.name; run('npm run snippet-test', { cwd: ROOT_DIR }); delete process.env.TEST_MODULE; }; /** * Runs system tests for this module via `npm run system-test` */ Module.prototype.runSystemTests = function() { run('npm run system-test', { cwd: this.directory }); }; /** * Checks to see if this module has one or more of the supplied modules * as a dev dependency. * * @param {Module[]} modules - The modules to check for. * @return {boolean} */ Module.prototype.hasDeps = function(modules) { var packageName; for (var i = 0; i < modules.length; i++) { packageName = modules[i].packageName; if (this.dependencies.indexOf(packageName) > -1) { return true; } } return false; }; module.exports.Module = Module; /** * Exec's command via child_process.spawnSync. * By default all output will be piped to the console unless `stdio` * is overridden. * * @param {string} command - The command to run. * @param {object=} options - Options to pass to `spawnSync`. * @return {string|null} */ function run(command, options) { options = options || {}; if (Array.isArray(command)) { command = command.join(' '); } console.log(command); var response = exec(command, options); if (response.code) { exit(response.code); } return response.stdout; } module.exports.run = run; /** * Used to make committing to git easier/etc.. * * @param {string=} cwd - Directory to commit/add/push from. */ function Git(cwd) { this.cwd = cwd || ROOT_DIR; } // We'll use this for cloning/submoduling/pushing purposes on CI Git.REPO = 'https://${GH_OAUTH_TOKEN}@github.com/${GH_OWNER}/${GH_PROJECT_NAME}'; /** * Creates a submodule in the root directory in quiet mode. * * @param {string} branch - The branch to use. * @param {string=} alias - Name of the folder that contains submodule. * @return {Git} */ Git.prototype.submodule = function(branch, alias) { alias = alias || branch; run(['git submodule add -q -b', branch, Git.REPO, alias], { cwd: this.cwd }); return new Git(path.join(this.cwd, alias)); }; /** * Check to see if git has any files it can commit. * * @return {boolean} */ Git.prototype.hasUpdates = function() { var output = run('git status --porcelain', { cwd: this.cwd }); return !!output && output.trim().length > 0; }; /** * Sets git user * * @param {string} name - User name * @param {string} email - User email */ Git.prototype.setUser = function(name, email) { run(['git config --global user.name', name], { cwd: this.cwd }); run(['git config --global user.email', email], { cwd: this.cwd }); }; /** * Adds all files passed in via git add * * @param {...string} file - File to add */ Git.prototype.add = function() { var files = [].slice.call(arguments); var command = ['git add'].concat(files); run(command, { cwd: this.cwd }); }; /** * Commits to git via commit message. * * @param {string} message - The commit message. */ Git.prototype.commit = function(message) { run(['git commit -m', '"' + message + ' [ci skip]"'], { cwd: this.cwd }); }; /** * Runs git status and pushes changes in quiet mode. * * @param {string} branch - The branch to push to. */ Git.prototype.push = function(branch) { run('git status', { cwd: this.cwd }); run(['git push -q', Git.REPO, branch], { cwd: this.cwd }); }; module.exports.git = new Git(); /** * The name of the branch currently being tested. * * @alias ci.BRANCH */ var BRANCH = process.env.TRAVIS_BRANCH || process.env.APPVEYOR_REPO_BRANCH; /** * The pull request number. * * @alias ci.PR_NUMBER; */ var PR_NUMBER = process.env.TRAVIS_PULL_REQUEST || process.env.APPVEYOR_PULL_REQUEST_NUMBER; /** * Checks to see if this is a pull request or not. * * @alias ci.IS_PR */ var IS_PR = !isNaN(parseInt(PR_NUMBER, 10)); /** * Returns the tag name (assuming this is a release) * * @alias ci.getTagName * @return {string|null} */ function getTagName() { return process.env.TRAVIS_TAG || process.env.APPVEYOR_REPO_TAG_NAME; } /** * Let's us know whether or not this is a release. * * @alias ci.isReleaseBuild * @return {string|null} */ function isReleaseBuild() { return !!getTagName(); } /** * Returns name/version of release. * * @alias ci.getRelease * @return {object|null} */ function getRelease() { var tag = getTagName(); if (!tag) { return null; } var parts = tag.split('-'); return { version: parts.pop(), name: parts.pop() || Module.UMBRELLA }; } /** * Checks to see if this is a push to master. * * @alias ci.isPushToMaster * @return {boolean} */ function isPushToMaster() { return BRANCH === 'master' && !IS_PR; } /** * Checks to see if this the CI's first pass (Travis only) * * @alias ci.isFirstPass * @return {boolean} */ function isFirstPass() { return /\.1$/.test(process.env.TRAVIS_JOB_NUMBER); } module.exports.ci = { BRANCH: BRANCH, IS_PR: IS_PR, PR_NUMBER: PR_NUMBER, getTagName: getTagName, isReleaseBuild: isReleaseBuild, getRelease: getRelease, isPushToMaster: isPushToMaster, isFirstPass: isFirstPass };
tcrognon/google-cloud-node
scripts/helpers.js
JavaScript
apache-2.0
10,052
const _ = require('lodash'); const teFlow = require('te-flow'); const AnimManager = require('./anim-manager.js'); const _H = require('./../helpers/helper-index.js'); const animConfig = function (_key, _data) { /** * Preps the data to be processed * @param {str} key -> anim key * @param {obj} data -> anim data * @return {---} -> {key, data, globalData} */ const formatData = function (key, data) { let globalData; ({data, globalData} = _H.util.getGlobal(data)); //plural container check, don't want to format if plural if (!_H.util.regularExp.pluralTest(key, 'animation')) { data = _H.util.formatData(data, key, { addOnKeys: ['timeline', 'tl'], globalData }); } return { key, data, globalData }; }; /** * Inits the manager and then sets the data from the raw data obj * to create a itteration to cycle over in extract * @return {---} -> {animMgr} animation class with configed data */ const initSetData = function (key, data, globalData) { //init the manager to set data to const animMgr = new AnimManager(key, globalData); //loop through data and the objs _.forEach(data, function (val, objKey) { animMgr.set(val, objKey); }); return { animMgr }; }; //-> passing data to anim-extract return teFlow.call({ args: { key: _key, data: _data }}, formatData, initSetData ); }; module.exports = animConfig;
ctr-lang/ctr
lib/ctr-nodes/animation/anim-config.js
JavaScript
apache-2.0
1,529
var App=function(){};App.prototype.contructor=function(){};App.prototype.init=function(){this.box=$("#box");this.height=this.box.css("height");this.width=this.box.css("width");this.box.css("left","calc(50% - "+this.width+"/2)");this.box.css("top","calc(50% - "+this.height+"/2)")};var app=new App;app.init();
chunnallu/frontend-tools
es6/closure-compiler/build/minified-app.js
JavaScript
apache-2.0
309
/* * Copyright 2015-2018 G-Labs. All Rights Reserved. * https://zuixjs.github.io/zuix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * * This file is part of * zUIx, Javascript library for component-based development. * https://zuixjs.github.io/zuix * * @author Generoso Martello <[email protected]> */ const baseFolder = process.cwd(); // Commons const fs = require('fs'); const path = require('path'); const recursive = require('fs-readdir-recursive'); // logging const tlog = require(path.join(baseFolder, 'src/lib/logger')); // ESLint const linter = require('eslint').linter; const lintConfig = require(path.join(baseFolder, '.eslintrc.json')); const sourceFolder = path.join(baseFolder, 'src/js/'); const stats = { error: 0, warning: 0 }; function lint(callback) { recursive(sourceFolder).map((f, i) => { if (f.endsWith('.js')) { tlog.info('^B%s^R', f); const code = fs.readFileSync(sourceFolder + f, 'utf8'); const issues = linter.verify(code, lintConfig, sourceFolder + f); issues.map((m, i)=>{ if (m.fatal || m.severity > 1) { stats.error++; tlog.error(' ^RError^: %s ^R(^Y%s^w:^Y%s^R)', m.message, m.line, m.column); } else { stats.warning++; tlog.warn(' ^YWarning^: %s ^R(^Y%s^w:^Y%s^R)', m.message, m.line, m.column); } }); if (issues.length === 0) tlog.info(' ^G\u2713^: OK'); tlog.br(); } }); tlog.info('Linting completed ^G-^: Errors ^R%s^: ^G-^: Warnings ^Y%s^:\n\n', stats.error, stats.warning); //process.exit(stats.error); if (callback) callback(stats); } module.exports = { lint: lint };
genielabs/zuix
build/scripts/lint.js
JavaScript
apache-2.0
2,327
import execSync from "../services/exec-sync"; import log from "../services/logger"; import lambdaExists from "../utils/lambda-exists"; export default function deploy (options) { const { awsAccessKeyId, awsSecretAccessKey, awsRegion, lambdaName, lambdaRole, sourceDir } = options; // Create/update the lambda function const awsCliEnv = { AWS_ACCESS_KEY_ID: awsAccessKeyId, AWS_SECRET_ACCESS_KEY: awsSecretAccessKey, AWS_DEFAULT_REGION: awsRegion }; switch (lambdaExists(awsCliEnv, lambdaName)) { case false: // Create the function log.info(`Lambda ${lambdaName} doesn't exist.`); log.info(`Creating lambda ${lambdaName}`); execSync([ "aws lambda create-function", `--function-name ${lambdaName}`, "--runtime nodejs4.3", `--role ${lambdaRole}`, "--handler index.handler", `--zip-file fileb://${sourceDir}/bundle.zip` ].join(" "), {env: awsCliEnv}); break; case true: // Update function code log.info(`Lambda ${lambdaName} already exists`); log.info(`Updating function code for lambda ${lambdaName}`); execSync([ "aws lambda update-function-code", `--function-name ${lambdaName}`, `--zip-file fileb://${sourceDir}/bundle.zip` ].join(" "), {env: awsCliEnv}); // Update function configuration (just the role for now) log.info(`Updating function configuration for lambda ${lambdaName}`); execSync([ "aws lambda update-function-configuration", `--function-name ${lambdaName}`, `--role ${lambdaRole}` ].join(" "), {env: awsCliEnv}); break; } }
lk-architecture/lk-lambda-deploy
src/steps/4.deploy.js
JavaScript
apache-2.0
1,817
var schema = require("./schema.js"); var xml = require("./xml.js"); module.exports.createBuilder = schema.createBuilder; module.exports.parse = xml.parse; module.exports.parseXml = xml.parse;
pagi-org/pagijs
src/js/schema/index.js
JavaScript
apache-2.0
193
import React, {Component} from 'react'; import {withRouter} from 'react-router'; import EUCookie from "area51-eucookie"; import Navigation from '../Navigation'; class About extends Component { render() { return (<div> <Navigation page="contactUs"/> <EUCookie/> <div className="App-header"> <h1>Contact Us</h1> </div> <div className="App-intro"> <p>A contact form will appear here in the near future.</p> <p>Currently you can contact us via:</p> <ul> <li>Twitter: <ul> <li><a href="http://twitter.com/TrainWatch">@Trainwatch</a></li> <li><a href="http://twitter.com/peter_mount">@Peter_Mount</a></li> </ul> </li> </ul> <p> Any issues can be reported on <a href="https://github.com/peter-mount/departureboards/issues">GitHub</a>. </p> </div> </div>); } } export default withRouter(About);
peter-mount/departureboards
src/contactUs/ContactUs.js
JavaScript
apache-2.0
1,184
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ Ext.namespace('OPF.core.validation'); Ext.define('OPF.core.validation.MessageLevel', { constructor: function(level, css, cfg) { cfg = cfg || {}; OPF.core.validation.MessageLevel.superclass.constructor.call(this, cfg); this.level = level; this.css = css; }, getLevel: function() { return this.level; }, getCSS: function() { return this.css; } }); OPF.core.validation.MessageLevel.TRACE = new OPF.core.validation.MessageLevel('TRACE', 'msg-trace'); OPF.core.validation.MessageLevel.DEBUG = new OPF.core.validation.MessageLevel('DEBUG', 'msg-debug'); OPF.core.validation.MessageLevel.INFO = new OPF.core.validation.MessageLevel('INFO', 'msg-info'); OPF.core.validation.MessageLevel.WARN = new OPF.core.validation.MessageLevel('WARN', 'msg-warn'); OPF.core.validation.MessageLevel.ERROR = new OPF.core.validation.MessageLevel('ERROR', 'msg-error'); OPF.core.validation.MessageLevel.FATAL = new OPF.core.validation.MessageLevel('FATAL', 'msg-fatal');
firejack-open/Firejack-Platform
platform/src/main/webapp/js/net/firejack/platform/core/validation/MessageLevel.js
JavaScript
apache-2.0
1,875
$(function() { // $('.collapse').collapse('hide'); $('.list-group-item.active').parent().parent('.collapse').collapse('show'); $.ajaxSetup({cache: true}); var fuzzyhound = new FuzzySearch(); function setsource(url, keys) { $.getJSON(url).then(function (response) { fuzzyhound.setOptions({ source: response, keys: keys }) }); } setsource(baseurl + '/search.json', ["title"]); $('#search-box').typeahead({ minLength: 0, highlight: true }, { name: 'pages', display: 'title', source: fuzzyhound }); $('#search-box').bind('typeahead:select', function(ev, suggestion) { window.location.href = suggestion.url; }); // Markdown plain out to bootstrap style $('#markdown-content-container table').addClass('table'); $('#markdown-content-container img').addClass('img-responsive'); });
hschroedl/FluentAST
docs/js/main.js
JavaScript
apache-2.0
966
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export default () => { describe('SqlLab query tabs', () => { beforeEach(() => { cy.login(); cy.server(); cy.visit('/superset/sqllab'); }); it('allows you to create a tab', () => { cy.get('#a11y-query-editor-tabs > ul > li').then((tabList) => { const initialTabCount = tabList.length; // add tab cy.get('#a11y-query-editor-tabs > ul > li') .last() .click(); cy.get('#a11y-query-editor-tabs > ul > li').should('have.length', initialTabCount + 1); }); }); it('allows you to close a tab', () => { cy.get('#a11y-query-editor-tabs > ul > li').then((tabListA) => { const initialTabCount = tabListA.length; // open the tab dropdown to remove cy.get('#a11y-query-editor-tabs > ul > li:first button:nth-child(2)').click(); // first item is close cy.get('#a11y-query-editor-tabs > ul > li:first ul li a') .eq(0) .click(); cy.get('#a11y-query-editor-tabs > ul > li').should('have.length', initialTabCount - 1); }); }); }); };
zhouyao1994/incubator-superset
superset/assets/cypress/integration/sqllab/tabs.js
JavaScript
apache-2.0
1,920
(function() { 'use strict'; angular .module('bamUiAngular') .service('webDevTec', webDevTec); /** @ngInject */ function webDevTec() { var data = [ { 'title': 'AngularJS', 'url': 'https://angularjs.org/', 'description': 'HTML enhanced for web apps!', 'logo': 'angular.png' }, { 'title': 'BrowserSync', 'url': 'http://browsersync.io/', 'description': 'Time-saving synchronised browser testing.', 'logo': 'browsersync.png' }, { 'title': 'GulpJS', 'url': 'http://gulpjs.com/', 'description': 'The streaming build system.', 'logo': 'gulp.png' }, { 'title': 'Jasmine', 'url': 'http://jasmine.github.io/', 'description': 'Behavior-Driven JavaScript.', 'logo': 'jasmine.png' }, { 'title': 'Karma', 'url': 'http://karma-runner.github.io/', 'description': 'Spectacular Test Runner for JavaScript.', 'logo': 'karma.png' }, { 'title': 'Protractor', 'url': 'https://github.com/angular/protractor', 'description': 'End to end test framework for AngularJS applications built on top of WebDriverJS.', 'logo': 'protractor.png' }, { 'title': 'Bootstrap', 'url': 'http://getbootstrap.com/', 'description': 'Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.', 'logo': 'bootstrap.png' }, { 'title': 'Angular UI Bootstrap', 'url': 'http://angular-ui.github.io/bootstrap/', 'description': 'Bootstrap components written in pure AngularJS by the AngularUI Team.', 'logo': 'ui-bootstrap.png' }, { 'title': 'Sass (Node)', 'url': 'https://github.com/sass/node-sass', 'description': 'Node.js binding to libsass, the C version of the popular stylesheet preprocessor, Sass.', 'logo': 'node-sass.png' }, { 'key': 'jade', 'title': 'Jade', 'url': 'http://jade-lang.com/', 'description': 'Jade is a high performance template engine heavily influenced by Haml and implemented with JavaScript for node.', 'logo': 'jade.png' } ]; this.getTec = getTec; function getTec() { return data; } } })();
sandor-nemeth/bam
bam-ui-angular/src/app/components/webDevTec/webDevTec.service.js
JavaScript
apache-2.0
2,427
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {internalListenImplementation} from './event-helper-listen'; import {user} from './log'; /** @const {string} */ const LOAD_FAILURE_PREFIX = 'Failed to load:'; /** * Returns a CustomEvent with a given type and detail; supports fallback for IE. * @param {!Window} win * @param {string} type * @param {Object} detail * @return {!Event} */ export function createCustomEvent(win, type, detail) { if (win.CustomEvent) { return new win.CustomEvent(type, {detail}); } else { // Deprecated fallback for IE. const e = win.document.createEvent('CustomEvent'); e.initCustomEvent( type, /* canBubble */ false, /* cancelable */ false, detail); return e; } } /** * Listens for the specified event on the element. * @param {!EventTarget} element * @param {string} eventType * @param {function(!Event)} listener * @param {boolean=} opt_capture * @return {!UnlistenDef} */ export function listen(element, eventType, listener, opt_capture) { return internalListenImplementation( element, eventType, listener, opt_capture); } /** * Listens for the specified event on the element and removes the listener * as soon as event has been received. * @param {!EventTarget} element * @param {string} eventType * @param {function(!Event)} listener * @param {boolean=} opt_capture * @return {!UnlistenDef} */ export function listenOnce(element, eventType, listener, opt_capture) { let localListener = listener; const unlisten = internalListenImplementation(element, eventType, event => { try { localListener(event); } finally { // Ensure listener is GC'd localListener = null; unlisten(); } }, opt_capture); return unlisten; } /** * Returns a promise that will resolve as soon as the specified event has * fired on the element. * @param {!EventTarget} element * @param {string} eventType * @param {boolean=} opt_capture * @param {function(!UnlistenDef)=} opt_cancel An optional function that, when * provided, will be called with the unlistener. This gives the caller * access to the unlistener, so it may be called manually when necessary. * @return {!Promise<!Event>} */ export function listenOncePromise(element, eventType, opt_capture, opt_cancel) { let unlisten; const eventPromise = new Promise(resolve => { unlisten = listenOnce(element, eventType, resolve, opt_capture); }); eventPromise.then(unlisten, unlisten); if (opt_cancel) { opt_cancel(unlisten); } return eventPromise; } /** * Whether the specified element/window has been loaded already. * @param {!Element|!Window} eleOrWindow * @return {boolean} */ export function isLoaded(eleOrWindow) { return !!(eleOrWindow.complete || eleOrWindow.readyState == 'complete' // If the passed in thing is a Window, infer loaded state from // || (eleOrWindow.document && eleOrWindow.document.readyState == 'complete')); } /** * Returns a promise that will resolve or fail based on the eleOrWindow's 'load' * and 'error' events. Optionally this method takes a timeout, which will reject * the promise if the resource has not loaded by then. * @param {T} eleOrWindow Supports both Elements and as a special case Windows. * @return {!Promise<T>} * @template T */ export function loadPromise(eleOrWindow) { let unlistenLoad; let unlistenError; if (isLoaded(eleOrWindow)) { return Promise.resolve(eleOrWindow); } const loadingPromise = new Promise((resolve, reject) => { // Listen once since IE 5/6/7 fire the onload event continuously for // animated GIFs. const tagName = eleOrWindow.tagName; if (tagName === 'AUDIO' || tagName === 'VIDEO') { unlistenLoad = listenOnce(eleOrWindow, 'loadstart', resolve); } else { unlistenLoad = listenOnce(eleOrWindow, 'load', resolve); } // For elements, unlisten on error (don't for Windows). if (tagName) { unlistenError = listenOnce(eleOrWindow, 'error', reject); } }); return loadingPromise.then(() => { if (unlistenError) { unlistenError(); } return eleOrWindow; }, () => { if (unlistenLoad) { unlistenLoad(); } failedToLoad(eleOrWindow); }); } /** * Emit error on load failure. * @param {!Element|!Window} eleOrWindow Supports both Elements and as a special * case Windows. */ function failedToLoad(eleOrWindow) { // Report failed loads as user errors so that they automatically go // into the "document error" bucket. let target = eleOrWindow; if (target && target.src) { target = target.src; } throw user().createError(LOAD_FAILURE_PREFIX, target); } /** * Returns true if this error message is was created for a load error. * @param {string} message An error message * @return {boolean} */ export function isLoadErrorMessage(message) { return message.indexOf(LOAD_FAILURE_PREFIX) != -1; }
lzanol/amphtml
src/event-helper.js
JavaScript
apache-2.0
5,533
<%-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --%> dojo.provide("dojotrader.widget.Context"); dojo.require("dojo.collections.*"); dojo.require("dojo.lang.timing.Timer"); dojotrader.widget.Context = function(userID){ this._user = userID; this._quotesCache = new dojo.collections.Dictionary(); this._quotesToUpdate = 0; this._updateTimer = null; this.startUpdateTimer = function(interval) { this._updateTimer = new dojo.lang.timing.Timer(interval); this._updateTimer.onTick = dojo.lang.hitch(this,this._updateQuotesCache); this._updateTimer.start(); }; this.stopUpdateTimer = function() { this._updateTimer.stop(); this._updateTimer = null; }; this._addQuoteToCache = function(quote) { this._quotesCache.add(quote.symbol, quote); //this.onQuoteAddComplete(quote); }; this.getQuoteFromCache = function(symbol) { //alert("getQuoteFromCache"); value = null; if (this._quotesCache.contains(symbol)){ value = this._quotesCache.entry(symbol).value; } else { this._getQuoteFromServer(symbol); } return value; }; this._getQuoteFromServer = function(symbol) { //alert("_getQuoteFromServer"); dojo.io.bind({ method: "GET", //url: "/proxy/SoapProxy/getQuote?p1=" + symbol.value + "&format=json", url: "/daytraderProxy/doProxy/getQuote?p1=" + symbol, mimetype: "text/json", load: dojo.lang.hitch(this, this._handleQuote), error: dojo.lang.hitch(this, this._handleError), useCache: false, preventCache: true }); }; this._getQuoteFromServerForUpdate = function(symbol) { //alert("_getQuoteFromServer"); dojo.io.bind({ method: "GET", //url: "/proxy/SoapProxy/getQuote?p1=" + symbol.value + "&format=json", url: "/daytraderProxy/doProxy/getQuote?p1=" + symbol, mimetype: "text/json", load: dojo.lang.hitch(this, this._handleQuoteUpdate), error: dojo.lang.hitch(this, this._handleError), useCache: false, preventCache: true }); }; this._handleQuote = function(type, data, evt) { //alert("_handleQuote"); this._addQuoteToCache(data.getQuoteReturn); this.onQuoteAddComplete(data.getQuoteReturn); dojo.event.topic.publish("/quotes", {action: "add", quote: data.getQuoteReturn}); }; this._handleQuoteUpdate = function(type, data, evt) { //alert("_handleQuote"); newQuote = data.getQuoteReturn; // check for quote equality - only update if they are different oldQuote = this._quotesCache.entry(newQuote.symbol).value; if (oldQuote.price != newQuote.price || oldQuote.change != newQuote.change) { this._addQuoteToCache(newQuote); dojo.event.topic.publish("/quotes", {action: "update", quote: newQuote}); } this._quotesToUpdate++; if (this._quotesCache.count == this._quotesToUpdate) { //alert("Refresh Complete: " + this._quotesCache.count + " - " + this._quotesToUpdate); this.onQuotesUpdateComplete(); } }; this._updateQuotesCache = function() { this._quotesToUpdate = 0; keys = this._quotesCache.getKeyList(); for (idx = 0; idx < keys.length; idx++) { this._getQuoteFromServerForUpdate(keys[idx]); } }; this.onQuotesUpdateComplete = function() {}; this.onQuoteAddComplete = function() {} };
awajid/daytrader
assemblies/javaee/dojo-ui-web/src/main/webapp/widget/Context.js
JavaScript
apache-2.0
4,087
const compiler = require('../lib') function assertCodegen (template, templateCode, renderCode = 'with(this){}', options = {}) { const res = compiler.compile(template, { resourcePath: 'test.wxml', mp: Object.assign({ minified: true, isTest: true, platform: 'mp-kuaishou' }, options) }) expect(res.template).toBe(templateCode) if (typeof renderCode === 'function') { renderCode(res) } else { expect(res.render).toBe(renderCode) } } describe('mp:compiler-mp-kuaishou', () => { it('generate class', () => { assertCodegen( '<view class="a external-class c" :class="class1">hello world</view>', '<view class="{{[\'a\',\'external-class\',\'c\',class1]}}">hello world</view>' ) }) it('generate scoped slot', () => { assertCodegen( '<foo><template slot-scope="{bar}">{{ bar.foo }}</template></foo>', '<foo generic:scoped-slots-default="test-foo-default" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'default\']}}"></foo>', function (res) { expect(res.generic[0]).toBe('test-foo-default') } ) assertCodegen( '<foo><view slot-scope="{bar}">{{ bar.foo }}</view></foo>', '<foo generic:scoped-slots-default="test-foo-default" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'default\']}}"></foo>', function (res) { expect(res.generic[0]).toBe('test-foo-default') } ) }) it('generate named scoped slot', () => { assertCodegen( '<foo><template slot="foo" slot-scope="{bar}">{{ bar.foo }}</template></foo>', '<foo generic:scoped-slots-foo="test-foo-foo" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'foo\']}}"></foo>', function (res) { expect(res.generic[0]).toBe('test-foo-foo') } ) assertCodegen( '<foo><view slot="foo" slot-scope="{bar}">{{ bar.foo }}</view></foo>', '<foo generic:scoped-slots-foo="test-foo-foo" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'foo\']}}"></foo>', function (res) { expect(res.generic[0]).toBe('test-foo-foo') } ) }) it('generate scoped slot with multiline v-if', () => { assertCodegen( '<foo><template v-if="\nshow\n" slot-scope="{bar}">{{ bar.foo }}</template></foo>', '<foo generic:scoped-slots-default="test-foo-default" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'default\']}}"></foo>', function (res) { expect(res.generic[0]).toBe('test-foo-default') } ) assertCodegen( '<foo><view v-if="\nshow\n" slot="foo" slot-scope="{bar}">{{ bar.foo }}</view></foo>', '<foo generic:scoped-slots-foo="test-foo-foo" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'foo\']}}"></foo>', function (res) { expect(res.generic[0]).toBe('test-foo-foo') } ) }) it('generate scoped slot', () => { assertCodegen(// TODO vue-id '<span><slot v-bind:user="user">{{ user.lastName }}</slot></span>', '<label class="_span"><block ks:if="{{$slots.default}}"><slot></slot><scoped-slots-default user="{{user}}" bind:__l="__l"></scoped-slots-default></block><block ks:else>{{user.lastName}}</block></label>', function (res) { expect(res.componentGenerics['scoped-slots-default']).toBe(true) } ) assertCodegen( '<span><slot name="header" v-bind:user="user">{{ user.lastName }}</slot></span>', '<label class="_span"><block ks:if="{{$slots.header}}"><slot name="header"></slot><scoped-slots-header user="{{user}}" bind:__l="__l"></scoped-slots-header></block><block ks:else>{{user.lastName}}</block></label>', function (res) { expect(res.componentGenerics['scoped-slots-header']).toBe(true) } ) }) })
dcloudio/uni-app
packages/uni-template-compiler/__tests__/compiler-mp-kuaishou.spec.js
JavaScript
apache-2.0
3,824
var a00068 = [ [ "base", "a00068.html#a5ea674ad553da52d47ffe1df62d6eb9d", null ], [ "MemberSignature", "a00068.html#a31088531e14b7f77e1df653d1003237d", null ], [ "_ConstTessMemberResultCallback_5_3", "a00068.html#a47e920466d4dcc3529e4c296c8ad619f", null ], [ "Run", "a00068.html#a5fa1d64d09741b114bda949599035b9c", null ] ];
stweil/tesseract-ocr.github.io
3.x/a00068.js
JavaScript
apache-2.0
340
thDebug = true; thAllowNullText = false;
thymol/thymol.js
src/main/webapp/WEB-INF/templates/thymol/debug/debug-data.js
JavaScript
apache-2.0
41
contacts = "Contacts"; // avoid typos, this string occurs many times. Contacts = new Mongo.Collection(contacts); Meteor.methods({ /** * Invoked by AutoForm to add a new Contacts record. * @param doc The Contacts document. */ addContacts: function(doc) { check(doc, Contacts.simpleSchema()); Contacts.insert(doc); }, /** * * Invoked by AutoForm to update a Contacts record. * @param doc The Contacts document. * @param docID It's ID. */ editContacts: function(doc, docID) { check(doc, Contacts.simpleSchema()); Contacts.update({_id: docID}, doc); }, deleteContacts: function(docID) { Contacts.remove(docID); } }); // Publish the entire Collection. Subscription performed in the router. if (Meteor.isServer) { Meteor.publish(contacts, function () { return Contacts.find(); }); } /** * Create the schema for Contacts * See: https://github.com/aldeed/meteor-autoform#common-questions * See: https://github.com/aldeed/meteor-autoform#affieldinput */ Contacts.attachSchema(new SimpleSchema({ firstName: { label: "First Name", type: String, optional: false, max: 20, autoform: { group: contacts, placeholder: "John" } }, lastName: { label: "Last Name", type: String, optional: false, max: 20, autoform: { group: contacts, placeholder: "Doe" } }, address: { label: "Address", type: String, optional: false, max: 50, autoform: { group: contacts, placeholder: "1234 Imaginary Ln." } }, phone: { label: "Phone Number", type: String, optional: false, max: 15, autoform: { group: contacts, placeholder: "(555) 555-5555" } }, email: { label: "Email Address", type: String, optional: false, max: 20, autoform: { group: contacts, placeholder: "[email protected]" } } }));
mkshimod/digits
app/lib/collections/Contacts.js
JavaScript
apache-2.0
1,938
import React from 'react'; import PropTypes from 'prop-types'; import style from 'HPCCloudStyle/ItemEditor.mcss'; export default class SchedulerConfigSGE extends React.Component { constructor(props) { super(props); this.updateConfig = this.updateConfig.bind(this); } updateConfig(event) { if (this.props.onChange) { this.props.onChange(event); } } render() { return ( <div> <section className={style.group}> <label className={style.label}>Number of slots</label> <input className={style.input} type="number" min="1" max={ this.props.runtime && this.props.max && this.props.max.sge ? this.props.max.sge.numberOfSlots : null } value={this.props.config.sge.numberOfSlots} data-key="sge.numberOfSlots" onChange={this.updateConfig} /> </section> <section className={style.group}> <label className={style.label}>GPUs/Node</label> <input className={style.input} type="number" min="0" max={ this.props.runtime && this.props.max && this.props.max.sge ? this.props.max.sge.numberOfGpusPerNode : null } value={this.props.config.sge.numberOfGpusPerNode} data-key="sge.numberOfGpusPerNode" onChange={this.updateConfig} /> </section> <section className={style.group}> <label className={style.label}>Parallel Environment</label> <input className={style.input} type="text" value={this.props.config.sge.parallelEnvironment} data-key="sge.parallelEnvironment" onChange={this.updateConfig} required /> </section> </div> ); } } SchedulerConfigSGE.propTypes = { config: PropTypes.object, max: PropTypes.object, onChange: PropTypes.func, runtime: PropTypes.bool, }; SchedulerConfigSGE.defaultProps = { config: undefined, max: undefined, onChange: undefined, runtime: undefined, };
Kitware/HPCCloud
src/panels/SchedulerConfig/SGE.js
JavaScript
apache-2.0
2,229
import alt from './../../alt'; class AsyncActions { constructor() { this.generateActions( 'toggle' ); } } export default alt.createActions(AsyncActions);
Lesha-spr/greed
public/src/actions/async/async.actions.js
JavaScript
apache-2.0
191
import * as index from "./index"; describe("icon-button/index", () => { [ { name: "default", value: expect.any(Function) } ].forEach(({ name, value }) => { it(`exports ${name}`, () => { expect(index).toHaveProperty(name, value); }); }); });
Autodesk/hig
packages/icon-button/src/index.test.js
JavaScript
apache-2.0
282
const loginJudger = require('./loginJudger'); const registerJudger = require('./registerJudger'); const adminJudger = require('./adminJudger'); module.exports = { loginJudger, registerJudger, adminJudger, };
sugerPocket/sp-blog
server/middlewares/index.js
JavaScript
apache-2.0
214
/** * Copyright 2016-2018 F5 Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const q = require('q'); const assert = require('assert'); describe('local crypto util tests', () => { let localKeyUtilMock; let cryptoUtilMock; let utilMock; let localCryptoUtil; let childProcessMock; let dataSent; let optionsSent; let encryptedKeySent; let dataToDecrypt; /* eslint-disable global-require */ beforeEach(() => { utilMock = require('../../lib/util'); localKeyUtilMock = require('../../lib/localKeyUtil'); cryptoUtilMock = require('../../lib/cryptoUtil'); localCryptoUtil = require('../../lib/localCryptoUtil'); encryptedKeySent = undefined; localKeyUtilMock.getPrivateKeyFilePath = function getPrivateKeyFilePath() { return q('/foo/bar'); }; localKeyUtilMock.getPrivateKeyMetadata = function getPrivateKeyMetadata() { return q({}); }; localKeyUtilMock.getExistingPrivateKeyName = function getExistingPrivateKeyName(folder, name) { return q(name); }; utilMock.readDataFromFile = function readDataFromFile() { return q(dataToDecrypt); }; cryptoUtilMock.decrypt = function decrypt(privateKey, data, options) { dataSent = data; optionsSent = options; return q('hello, world'); }; cryptoUtilMock.symmetricDecrypt = function symmetricDecrypt( privateKey, encryptedKey, iv, data, options ) { dataSent = data; optionsSent = options; encryptedKeySent = encryptedKey; return q('hello, world'); }; }); afterEach(() => { Object.keys(require.cache).forEach((key) => { delete require.cache[key]; }); }); describe('decrypt data tests', () => { it('no file test', () => { assert.throws(() => { localCryptoUtil.decryptData(null, 'foo', 'bar'); }, /data is required/); }); it('no private key folder test', () => { assert.throws(() => { localCryptoUtil.decryptData('foo', null, 'bar'); }, /privateKeyFolder is required/); }); it('no private key name test', () => { assert.throws(() => { localCryptoUtil.decryptData('foo', 'bar'); }, /privateKeyName is required/); }); it('basic test', () => { dataToDecrypt = 'abcd'; return localCryptoUtil.decryptData(dataToDecrypt, 'foo', 'bar') .then((response) => { assert.strictEqual(dataSent, 'abcd'); assert.strictEqual(response, 'hello, world'); }); }); it('no passphrase test', () => { return localCryptoUtil.decryptData('foo', 'foo', 'bar') .then(() => { assert.strictEqual(optionsSent.passphrase, undefined); assert.strictEqual(optionsSent.passphraseEncrypted, false); }); }); it('passphrase test', () => { localKeyUtilMock.getPrivateKeyMetadata = function getPrivateKeyMetadata() { return q({ passphrase: 'mypassphrase' }); }; return localCryptoUtil.decryptData('foo', 'foo', 'bar') .then(() => { assert.strictEqual(optionsSent.passphrase, 'mypassphrase'); assert.strictEqual(optionsSent.passphraseEncrypted, true); }); }); }); describe('decrypt password tests', () => { it('basic test', () => { return localCryptoUtil.decryptPassword('secret') .then((decryptedSecret) => { assert.deepStrictEqual(decryptedSecret, 'hello, world'); }); }); }); describe('symmetric decrypt password tests', () => { it('basic test', () => { dataToDecrypt = { encryptedData: 'secret', encryptedKey: 'key', iv: 'foo', privateKey: { folder: 'foo', name: 'bar' } }; return localCryptoUtil.symmetricDecryptPassword(dataToDecrypt) .then((decryptedSecret) => { assert.deepStrictEqual(decryptedSecret, 'hello, world'); }); }); }); describe('decrypt data from file tests', () => { it('basic test', () => { dataToDecrypt = 'abcd'; return localCryptoUtil.decryptDataFromFile('/foo/bar') .then((response) => { assert.strictEqual(dataSent, dataToDecrypt); assert.strictEqual(response, 'hello, world'); }); }); it('symmetric test', () => { const encryptedData = 'secret'; const encryptedKey = 'key'; dataToDecrypt = JSON.stringify({ encryptedData, encryptedKey, iv: 'foo', privateKey: { folder: 'foo', name: 'bar' } }); return localCryptoUtil.decryptDataFromFile('/foo/bar', { symmetric: true }) .then((response) => { assert.strictEqual(dataSent, encryptedData); assert.strictEqual(response, 'hello, world'); assert.strictEqual(encryptedKeySent, encryptedKey); }); }); it('error test', () => { assert.throws(() => { localCryptoUtil.decryptDataFromFile(null); }, /dataFile is required/); }); }); describe('decrypt conf value tests', () => { beforeEach(() => { childProcessMock = require('child_process'); }); it('basic test', () => { childProcessMock.execFile = function execFile(file, params, cb) { cb(null, 'hello, world', null); }; return localCryptoUtil.decryptConfValue('foo') .then((response) => { assert.strictEqual(response, 'hello, world'); }); }); it('error test', () => { childProcessMock.execFile = function execFile(file, params, cb) { cb(new Error('foo'), null, 'bar'); }; return localCryptoUtil.decryptConfValue('foo') .then(() => { assert.ok(false, 'decryptConfValue should have thrown'); }) .catch((err) => { assert.notStrictEqual(err.message.indexOf('bar'), -1); }); }); }); });
F5Networks/f5-cloud-libs
test/lib/localCryptoUtilTests.js
JavaScript
apache-2.0
7,520
"use strict"; var async = require("async"); var helper = require("../../../../helper.js"); var config = require("../../../../../config.js"); var utils = helper.requireModule('./lib/environment/drivers/infra.js'); const nock = require('nock'); var req = { soajs: { registry: { coreDB: { provision: { name: 'core_provision', prefix: '', servers: [ { host: '127.0.0.1', port: 27017 } ], credentials: null, streaming: { batchSize: 10000, colName: { batchSize: 10000 } }, URLParam: { maxPoolSize: 2, bufferMaxEntries: 0 }, registryLocation: { l1: 'coreDB', l2: 'provision', env: 'dev' }, timeConnected: 1491861560912 } }, services: { controller : { port : 80 } } }, log: { debug: function (data) { }, error: function (data) { }, info: function (data) { } }, inputmaskData: { specs : {} }, validator: { Validator: function () { return { validate: function () { return { errors: [] }; } }; } }, awareness: { getHost: function (service, cb) { return cb ("dashboard.com"); } } }, headers: { key : "key", soajsauth: "auth", }, query: { "access_token": "token" } }; var mongoStub = { findEntry: function (soajs, opts, cb) { if (opts.collection === 'infra') { cb (null, {'_id' : 123123}) } else { cb(null, { "productize": { "modifyTemplateStatus": true }, "cluster": {}, "controller": {}, "urac": {}, "oauth": {}, "nginx": {}, "user": {} }); } }, updateEntry: function (soajs, opts, cb) { cb(null, true); }, saveEntry: function (soajs, opts, cb) { cb(null, true); }, removeEntry: function (soajs, opts, cb) { cb(null, true); }, closeConnection: function (soajs) { return true; }, validateCustomId : function(soajs, id) { return true }, onboardVM : function(soajs, id) { return true } }; var BL = { customRegistry :{ module : {} }, model: mongoStub, cd : { module : {} }, cloud :{ deploy :{ module :{} }, services :{ module :{} }, resources :{ module :{} }, infra : { module : {} } }, resources: { module : {} } }; var template = { "type": "_template", "name": "MGTT", "description": "Mike Generic Test Template", "link": "", "content": { "custom_registry": { "data": [ { "name": "ciConfig", "value": { "apiPrefix": "cloud-api", "domain": "herrontech.com", "protocol": "https", "port": 443.0 } }, { "name": "ciConfig2", "value": "string value here ..." }, { "name": "ciConfig3", "value": { "apiPrefix": "dashboard-api", "domain": "soajs.org", "protocol": "https", "port": 443.0 } } ] }, "productization": { "data": [ { "code": "MIKE", "name": "Mike Product", "description": "Mike Product Description", "packages": [ { "code": "BASIC", "name": "Basic Package", "description": "Basic Package Description", "TTL": 2160000.0, "acl": { "oauth": {}, "urac": {}, "daas": {} } }, { "code": "MAIN", "name": "Main Package", "description": "Main Package Description", "TTL": 2160000.0, "acl": {} } ] } ] }, "tenant": { "data": [ { "code": "MIKE", "name": "Mike Tenant", "description": "Mike Tenant Description", "applications": [ { "product": "MIKE", "package": "MIKE_MAIN", "description": "Mike main application", "_TTL": 2160000.0, "keys": [ { "extKeys": [ { "device": {}, "geo": {}, "dashboardAccess": false, "expDate": null } ], "config": { "a": "b" } } ] }, { "product": "MIKE", "package": "MIKE_USER", "description": "Mike Logged In user Application", "_TTL": 2160000.0, "keys": [ { "extKeys": [ { "device": {}, "geo": {}, "dashboardAccess": true, "expDate": null } ], "config": { "c": "d" } } ] } ] } ] }, "secrets": { "data": [ { "name": "mike" } ] }, "deployments": { "repo": { "controller": { "label": "SOAJS API Gateway", "name": "controller", "type": "service", "category": "soajs", "deploy": { "memoryLimit": 500.0, "mode": "replicated", "replicas": 1.0 } } }, "resources": { "nginx": { "label": "Nginx", "type": "server", "category": "nginx", "ui": "${REF:resources/drivers/server/nginx}", "deploy": { "memoryLimit": 500.0, "mode": "global", "secrets": "mike" } }, "external": { "label": "External Mongo", "type": "cluster", "category": "mongo", "limit": 1.0, "ui": "${REF:resources/drivers/cluster/mongo}", "deploy": null } } } }, "deploy": { database: { pre: { custom_registry: { imfv: [ { name: 'ciConfig', locked: true, plugged: false, shared: true, value: { test1: true } }, { name: 'ciConfig2', locked: true, plugged: false, shared: true, value: { test2: true } }, { name: 'ciConfig3', locked: true, plugged: false, shared: true, value: { test3: true } } ] } }, steps: { productization: { ui: { readOnly: true } }, tenant: { ui: { readOnly: true } } }, post: { 'deployments__dot__resources__dot__external': { imfv: [ { name: 'external', type: 'cluster', category: 'mongo', locked: false, shared: false, plugged: false, config: { username: 'username', password: 'pwd' } } ], "status":{ "done": true, "data":[ { "db": "mongo id of this resource" } ] } } } }, deployments: { pre: { "infra.cluster.deploy": { "imfv" : [ { "command":{ "method" : "post", "routeName" : "/bridge/executeDriver", //change the path "data" : { "type" : "infra", "name" : "google", "driver" : "google", "command" : "deployCluster", "project" : "demo", "options" : { "region" : "us-east1-b", "workernumber" : 3, "workerflavor" : "n1-standard-2", "regionLabel" : "us-east1-b", "technology" : "kubernetes", "envCode" : "PORTAL" } } }, "check" : { "id" : { "type" : "string", "required": true } } }, { "recursive" : { "max" : 5, "delay": 300 }, "check" : { "id" : { "type" : "string", "required": true }, "ip" : { "type" : "string", "required": true } }, "command": { "method" : "post", "routeName" : "/bridge/executeDriver", "data" : { "type" : "infra", "name" : "google", "driver" : "google", "command" : "getDeployClusterStatus", "project" : "demo", "options" : { "envCode" : "PORTAL" } } } } ], "status": { "done": true, "data": { "id": "kaza", "ip": "kaza", "dns": { "a":"b" } }, "rollback" : { "command":{ "method" : "post", "routeName" : "/bridge/executeDriver", "params": {}, "data" : { "type" : "infra", "name" : "google", "driver" : "google", "command" : "deleteCluster", "project" : "demo", "options" : { "envCode" : "PORTAL", "force" : true } } } } }, } }, steps: { secrets: { imfv: [ { name: 'mike', type: 'Generic', data: 'something in secret' } ] }, 'deployments.repo.controller': { imfv: [ { name: 'controller', options: { deployConfig: { replication: { mode: 'replicated', replicas: 1 }, memoryLimit: 524288000 }, gitSource: { owner: 'soajs', repo: 'soajs.controller', branch: 'master', commit: '468588b0a89e55020f26b805be0ff02e0f31a7d8' }, custom: { sourceCode: {}, name: 'controller', type: 'service' }, recipe: '5ab4d65bc261bdb38a9fe363', env: 'MIKE' }, deploy: true, type: 'custom' } ], "status": { } }, 'deployments.resources.nginx': { imfv: [ { name: 'nginx', type: 'server', category: 'nginx', locked: false, shared: false, plugged: false, config: null, deploy: { options: { deployConfig: { replication: { mode: 'global' }, memoryLimit: 524288000 }, custom: { sourceCode: {}, secrets: [ { name: 'mike', mountPath: '/etc/soajs/certs', type: 'certificate' } ], name: 'mynginx', type: 'server' }, recipe: '5ab4d65bc261bdb38a9fe363', env: 'MIKE' }, deploy: true, type: 'custom' } } ] } }, post: { "infra.dns": { "imfv": [ { "recursive" : { "max" : 5, "delay": 300 }, "check" : { "dns" : { "type" : "object", "required": true }, "ip" : { "type" : "string", "required": true } }, "command": { "method" : "post", "routeName" : "/bridge/executeDriver", "data" : { "type" : "infra", "name" : "google", "driver" : "google", "command" : "getDNSInfo", "project" : "demo", "options" : { "envCode" : "PORTAL" } } } } ], "status": { "done": true, "data": { "ip": "kaza", "dns": { "a":"b" } } }, } } } }, soajs_project: "soajs_project" }; var environmentRecord = { _id: '5a58d942ace01a5325fa3e4c', code: 'DASHBORAD', deployer: { "type": "container", "selected": "container.docker.local", "container": { "docker": { "local": { "socketPath": "/var/run/docker.sock" }, "remote": { "nodes": "" } }, "kubernetes": { "local": { "nginxDeployType": "", "namespace": {}, "auth": { "token": "" } }, "remote": { "nginxDeployType": "", "namespace": {}, "auth": { "token": "" } } } } }, dbs: { clusters: { oneCluster: { servers: {} } }, config: { session: { cluster: 'oneCluster' } } }, services: {}, profile: '', "restriction":{ "1231231":{ "eastus": { group: "grouptest", network: "networktest" } } } }; var infraRecord = { "_id":'5af2b621a0e17acc56000001', "name": "test", "technologies": [ "test" ], "templates": [ "local" ], "label": "test", "deployments": [] }; var lib = { initBLModel : function(module, modelName, cb){ return cb(null, { add : function (context, req, data, cb) { return cb(null, true); }, delete : function (context, req, data, cb) { return cb(true); }, saveConfig : function (context, req, data, cb) { return cb(null, true); }, deployService : function (context, req, data, cb) { return cb(null, {service: { id: "1" }}); }, deleteService : function (context, req, data, cb) { return cb(null, true); }, addResource: function (context, req, data, cb) { return cb(null, {_id: "1"}); }, setConfig: function (context, req, data, cb) { return cb(null, true); }, deleteResource: function (context, req, data, cb) { return cb(true); }, list : function (config, soajs, deployer, cb) { return cb(null, true); }, activate : function (config, soajs, deployer, cb) { return cb(true); }, modify : function (config, soajs, deployer, cb) { return cb(null, true); }, deactivate : function (config, soajs, deployer, cb) { return cb(null, {service: { id: "1" }}); }, removeDeployment : function (config, soajs, deployer, cb) { return cb(null, true); }, getDeployClusterStatus: function (config, soajs, req ,deployer, cbMain) { return cbMain(null, true); }, deployCluster: function (config, soajs, deployer,req, cb) { return cb(null, true); }, scaleCluster: function (config, soajs, deployer, cb) { return cb(true); }, removeEnvFromDeployment: function (config, soajs, req, deployer, cb) { return cb(true); }, getCluster: function (config, soajs, deployer, cb) { return cb(true); }, updateCluster: function (config, soajs, deployer, cb) { return cb(true); }, getDNSInfo: function (config, req, soajs, deployer, cb) { return cb(true); }, removeTemplate: function (config, soajs, deployer, cb) { return cb(true); }, addTemplate: function (config, soajs, deployer, cb) { return cb(true); }, updateTemplate: function (config, soajs, deployer, cb) { return cb(true); }, uploadTemplate: function (config, soajs, deployer, cb) { return cb(true); }, uploadTemplateInputsFile: function (config, soajs, deployer, cb) { return cb(true); }, downloadTemplate: function (config, soajs, deployer, cb) { return cb(true); }, getDeployVMStatus: function (config, req, soajs, deployer, cb) { return cb(true); }, onboardVM: function (config, req, soajs, deployer, cb) { return cb(true); }, destroyVM: function (config, req, soajs, deployer, cb) { return cb(true); }, deployVM: function (config, req, soajs, deployer, cb) { return cb(true); }, }); }, checkReturnError: function(req, {}, {}, cb){ return cb(null, true); } }; var context = {}; describe("testing infra.js", function () { describe("testing validate", function () { it("success", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": { "method": "post", "routeName": "/bridge/executeDriver", "data": { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } } }, "check": { "id": { "type": "string", "required": true } } }, { "recursive": { "max": 5, "delay": 300 }, "check": { "id": { "type": "string", "required": true }, "ip": { "type": "string", "required": true } }, "command": { "method": "post", "routeName": "/bridge/executeDriver", "data": { "type": "infra", "name": "google", "driver": "google", "command": "getDeployClusterStatus", "project": "demo", "options": { "envCode": "PORTAL" } } } } ] } }; utils.validate(req, context, lib, async, BL, 'mongo', function (err, body) { done(); }) }); it("success with errors", function (done) { req.soajs.validator = { Validator: function () { return { validate: function () { return { errors: [{err: "msg"}] }; } }; } }; utils.validate(req, context, lib, async, BL, 'mongo', function (err, body) { done(); }) }); }); describe("testing deploy", function () { it("success infra already deployed", function (done) { context = { BL: BL, environmentRecord: environmentRecord, infraProvider : JSON.parse(JSON.stringify(infraRecord)), template: JSON.parse(JSON.stringify(template)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "getDeployClusterStatus", "check": { "id": { "type": "string", "required": true } } }, { "recursive": { "max": 0, "delay": 0 }, "check": { "id": { "type": "string", "required": true }, "ip": { "type": "string", "required": true } }, "command": "getDeployClusterStatus", } ] } }; context.template.deploy.deployments.pre["infra.cluster.deploy"].status = { done: true }; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { done(); }) }); it("success infra with error", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } } }, { // "recursive": { // "max": 5, // "delay": 1 // }, "check": { "id": { "type": "string", "required": true }, "ip": { "type": "string", "required": true } }, "command": "deployCluster" } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: {} }); delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra without command", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": '', "check": { "id": { "type": "string", "required": true } } }, { "recursive": { "max": 5, "delay": 300 }, "check": { "id": { "type": "string", "required": true }, "ip": { "type": "string", "required": true } }, "command": 'deployCluster' } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: false }); delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra without response", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } } }, { "recursive": { "max": 5, "delay": 300 }, "check": { "id": { "type": "string", "required": true }, "ip": { "type": "string", "required": true } }, "command": { "method": "post", "routeName": "/bridge/executeDriver", "data": { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "envCode": "PORTAL" } } } } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: false }); delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with response", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: true }); delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with response case getDeployVMStatus", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "getDeployVMStatus", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, options : { params : ['test'], data : ['test'] } }, ] } }; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with response case onBoard", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "onboardVM", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, options : { params : ['test'], data : ['test'] } }, ] } }; context.infraProvider.command = 'onboardVM'; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with response case dnsInfo", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "getDNSInfo", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, options : { params : ['test'], data : ['test'] } }, ] } }; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with response case deployVm", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployVM", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, options : { params : {'specs' : {}}, data: [{"test": 'test', "specs": {}}], } }, ] } }; req.soajs.inputmaskData.specs = { layerName : '' }; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with response case releaseVm", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "releaseVM", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, options : { params : ['test'], data : ['test'] } }, ] } }; context.infraProvider.command = 'onboardVM'; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with response case destroyVm", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "destroyVM", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, options : { params : ['test'], data : ['test'] } }, ] } }; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra ", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: true }); req.soajs.validator = { Validator: function () { return { validate: function () { return { valid: true }; } }; } }; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra max count", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 0, "delay": 300 }, } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: false }); req.soajs.validator = { Validator: function () { return { validate: function () { return { valid: true }; } }; } }; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra inputs object", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 5, "delay": 300 }, } } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: false }); delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra inputs empty", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: false }); delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra no steps ", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ null ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deployCluster", "project": "demo", "options": { "region": "us-east1-b", "workernumber": 3, "workerflavor": "n1-standard-2", "regionLabel": "us-east1-b", "technology": "kubernetes", "envCode": "PORTAL" } }).reply(200, { result: true, data: true }); delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.deploy(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); }); describe("testing rollback", function () { it("success infra no status", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status; utils.rollback(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra done false", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; context.template.deploy.deployments.pre["infra.cluster.deploy"].status = { done: false }; utils.rollback(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra rollback emtpy", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; context.template.deploy.deployments.pre["infra.cluster.deploy"].status = { done: true, rollback: {} }; utils.rollback(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with rolback", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deleteCluster", "project": "demo", "options": { "envCode": "PORTAL", "force": true } }).reply(200, { result: true, data: true }); utils.rollback(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra with bad rollback", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deleteCluster", "project": "demo", "options": { "envCode": "PORTAL", "force": true } }).reply(200, { result: false, errors: { details: [{ message: "err" }] } }); context.template.deploy.deployments.pre["infra.cluster.deploy"].status.rollback = [template.deploy.deployments.pre["infra.cluster.deploy"].status.rollback] utils.rollback(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra no rollback", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deleteCluster", "project": "demo", "options": { "envCode": "PORTAL", "force": true } }).reply(200, { result: false, errors: { details: [{ message: "err" }] } }); context.template.deploy.deployments.pre["infra.cluster.deploy"].status.rollback = []; utils.rollback(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra rollback null", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deleteCluster", "project": "demo", "options": { "envCode": "PORTAL", "force": true } }).reply(200, { result: false, errors: { details: [{ message: "err" }] } }); context.template.deploy.deployments.pre["infra.cluster.deploy"].status.rollback = [null]; utils.rollback(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); it("success infra no rollback", function (done) { context = { BL: BL, environmentRecord: environmentRecord, template: JSON.parse(JSON.stringify(template)), infraProvider : JSON.parse(JSON.stringify(infraRecord)), config: config, errors: [], opts: { "stage": "deployments", "group": "pre", "stepPath": "infra.cluster.deploy", "section": [ "infra", "cluster", "deploy" ], "inputs": [ { "command": "deployCluster", "check": { "id": { "type": "string", "required": true } }, "recursive": { "max": 1, "delay": 300 }, } ] } }; nock("http://dashboard.com:80").post('/bridge/executeDriver?access_token=token&soajs_project=soajs_project', { "type": "infra", "name": "google", "driver": "google", "command": "deleteCluster", "project": "demo", "options": { "envCode": "PORTAL", "force": true } }).reply(200, { result: false, errors: { details: [{ message: "err" }] } }); delete context.template.deploy.deployments.pre["infra.cluster.deploy"].status.rollback utils.rollback(req, context, lib, async, BL, 'mongo', function (err, body) { nock.cleanAll(); done(); }) }); }) });
soajs/soajs.dashboard
test/unit/lib/environment/drivers/infra.test.js
JavaScript
apache-2.0
49,180
'use strict'; angular.module('ictsAppApp') .controller('TelKpnDeleteModalCtrl', ['$scope', '$modalInstance', 'record', function ($scope, $modalInstance, record) { $scope.record = record; $scope.delete = function () { $modalInstance.close(); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]);
utwente/lisa-telefonie
client/app/tel/kpn/kpnDelete.controller.js
JavaScript
apache-2.0
339
function imagecreate(image, pool, url, cmd){ if ( image === undefined ) { image = $("#image").val(); } if ( pool === undefined ) { pool = $("#pool").val(); } if ( url === undefined ) { url = $("#url").val(); } if ( cmd === undefined ) { cmd = $("#cmd").val(); } $("#wheel").show(); data = {'image': image, 'action': 'create', 'pool': pool, 'url': url, 'cmd': cmd}; $.ajax({ type: "POST", url: '/imageaction', data: data, success: function(data) { $("#wheel").hide(); $("#urllabel").hide(); $("#url").hide(); if (data.result == 'success') { $('.top-right').notify({message: { text: "Image "+image+" created!!!" }, type: 'success'}).show(); } else { $('.top-right').notify({message: { text: "Image "+image+" not created because "+data.reason }, type: 'danger'}).show(); }; } }); } function imageurl(){ image = $( "#image option:selected" ).text(); if (~image.indexOf("rhel")) { $("#url").show(); $("#urllabel").show(); url = $( "#image option:selected" ).attr("url"); window.open(url, "_blank"); } }
karmab/kcli
kvirt/web/static/js/imageaction.js
JavaScript
apache-2.0
1,212
(function() { 'use strict'; // set up margins var el = d3.select('.geomap'), elWidth = parseInt(el.style('width'), 10), elHeight = parseInt(el.style('height'), 10), margin = {top: 20, right: 20, bottom: 30, left: 50}, width = elWidth - margin.left - margin.right, height = elHeight - margin.top - margin.bottom; // create svg element var svg = el.append("svg") .attr("width", elWidth) .attr("height", elHeight) .append("g") .attr('transform', 'translate(' + margin.left + "," + margin.top + ')'); d3.json("/data/us-states.json", function(error, data) { visualize(data); }); function visualize(data) { // code here } }());
victormejia/d3-workshop-playground
modules/geomapping/geomap.js
JavaScript
apache-2.0
703
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { ReactiveBase, DataSearch, ResultList, ReactiveList, SelectedFilters, } from '@appbaseio/reactivesearch'; import './index.css'; class Main extends Component { render() { return ( <ReactiveBase app="good-books-ds" url="https://a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61@appbase-demo-ansible-abxiydt-arc.searchbase.io" enableAppbase > <div className="row"> <div className="col"> <DataSearch dataField="original_title.keyword" componentId="BookSensor" defaultValue="Artemis Fowl" /> </div> <div className="col"> <SelectedFilters render={(props) => { const { selectedValues, setValue } = props; const clearFilter = (component) => { setValue(component, null); }; const filters = Object.keys(selectedValues).map((component) => { if (!selectedValues[component].value) return null; return ( <button key={component} onClick={() => clearFilter(component)} > {selectedValues[component].value} </button> ); }); return filters; }} /> <ReactiveList componentId="SearchResult" dataField="original_title" from={0} size={3} className="result-list-container" pagination react={{ and: 'BookSensor', }} render={({ data }) => ( <ReactiveList.ResultListWrapper> {data.map(item => ( <ResultList key={item._id}> <ResultList.Image src={item.image} /> <ResultList.Content> <ResultList.Title> <div className="book-title" dangerouslySetInnerHTML={{ __html: item.original_title, }} /> </ResultList.Title> <ResultList.Description> <div className="flex column justify-space-between"> <div> <div> by{' '} <span className="authors-list"> {item.authors} </span> </div> <div className="ratings-list flex align-center"> <span className="stars"> {Array( item.average_rating_rounded, ) .fill('x') .map((item, index) => ( <i className="fas fa-star" key={index} /> )) // eslint-disable-line } </span> <span className="avg-rating"> ({item.average_rating} avg) </span> </div> </div> <span className="pub-year"> Pub {item.original_publication_year} </span> </div> </ResultList.Description> </ResultList.Content> </ResultList> ))} </ReactiveList.ResultListWrapper> )} /> </div> </div> </ReactiveBase> ); } } export default Main; ReactDOM.render(<Main />, document.getElementById('root'));
appbaseio/reactivesearch
packages/web/examples/CustomSelectedFilters/src/index.js
JavaScript
apache-2.0
3,322
/** * Created by guofengrong on 15/10/26. */ var dataImg = { "data": [{ "src": "1.jpg" }, { "src": "1.jpg" }, { "src": "2.jpg" }, { "src": "3.jpg" }, { "src": "4.jpg" }, { "src": "10.jpg" }] }; $(document).ready(function() { $(window).on("load", function() { imgLocation(); //当点击回到顶部的按钮时,页面回到顶部 $("#back-to-top").click(function() { $('body,html').animate({ scrollTop: 0 }, 1000); }); $(window).scroll(function() { //当页面滚动大于100px时,右下角出现返回页面顶端的按钮,否则消失 if ($(window).scrollTop() > 100) { $("#back-to-top").show(500); //$("#back-to-top").css("top",($(window).height()+$(window).scrollTop()-50)); } else { $("#back-to-top").hide(500); } //当返回true时,图片开始自动加载,加载的图片通过调用imgLocation函数进行瀑布流式的摆放 if (picAutoLoad()) { $.each(dataImg.data, function(index, value) { var box = $("<div>").addClass("pic-box").appendTo($(".content")); var pic = $("<div>").addClass("pic").appendTo(box); var img = $("<img>").attr("src", "./img/" + $(value).attr("src")).appendTo(pic); }); imgLocation(); } }); }); }); //用于摆放图片的函数: // 先计算当前页面下,横向摆放图片的张数,当当前所需要摆放的图片的序号小于该数字时,则依次向左浮动摆放; // 当超过这一数字时,则需要找到已经摆放的图片中最小高度的值(摆放图片的高度存放于数组boxHeightArr中),并在数组中找到具有最小高度的图片的位置; //然后对需要摆放的图片设置位置信息进行摆放,摆放完成后将数组中的最小高度加上当前摆放图片的高度,然后进行下一次摆放 function imgLocation() { var picBox = $('.pic-box'); var boxWidth = picBox.eq(0).width(); var contentWidth = $('.content').width(); // console.log(contentWidth); var num = Math.floor(contentWidth / boxWidth); var boxHeightArr = []; picBox.each(function(index, value) { var boxHeight = picBox.eq(index).height(); if (index < num) { boxHeightArr[index] = boxHeight; } else { var minBoxHeight = Math.min.apply(null, boxHeightArr); var minHeightIndex = $.inArray(minBoxHeight, boxHeightArr); $(value).css({ "position": "absolute", "top": minBoxHeight, "left": picBox.eq(minHeightIndex).position().left }); boxHeightArr[minHeightIndex] += picBox.eq(index).height(); } }); } //用于自动加载图片用: //lastBoxHeight获取最后一个图片的高度; //当最后一张图片的高度小于鼠标滚轮滚过的距离加上显示器高度的时候,则放回true,否则返回false; function picAutoLoad() { var box = $('.pic-box'); var lastBoxHeight = box.last().get(0).offsetTop + Math.floor(box.last().height() / 2); var windowHeight = $(window).height(); var scrollHeight = $(window).scrollTop(); return (lastBoxHeight < windowHeight + scrollHeight) ? true : false; }
guofengrong/HomeworkOfJikexueyuan
Lesson7/百度图片瀑布流布局/js/baidu-pic.js
JavaScript
apache-2.0
3,505
import { expect } from 'chai'; import * as utilities from '../../src/utilities'; describe('utilities.capitalize()', () => { it('capitalize', () => { expect( utilities.capitalize('capitalize') == 'Capitalize' ); }); it('Capitalize', () => { expect( utilities.capitalize('Capitalize') == 'Capitalize' ); }); it('poweranalytics', () => { expect( utilities.capitalize('poweranalytics') == 'Poweranalytics' ); }); }); describe('utilities.loadScript()', () => { }); describe('utilities.domReady()', () => { }); describe('utilities.random()', () => { it('length', () => { expect( utilities.random(1).length == 1 ); expect( utilities.random(5).length == 5 ); expect( utilities.random(20).length == 20 ); }); it('character', () => { expect( utilities.random(5).match(/^[0-9a-zA-Z]{5}$/) ); }); }); describe('utilities.timestamp()', () => { it('format', () => { const timestamp = utilities.timestamp(); expect(timestamp.match(/[0-9]{4}\/[0-9]{2}\/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{3}/)) }); });
1987yama3/power-analytics.appspot.com
test/unit/utilities.test.js
JavaScript
apache-2.0
1,060
import { forOwn, forEach, keys, values, isNil, isEmpty as _isEmpty, isObject, bind } from 'lodash' import { Promise } from 'bluebird' function InputModel(vals) { let modelValue = (vals['value'] ? vals['value'] : null ) let viewValue = modelValue let valid = true let pristine = true let listeners = setupListeners(vals['listeners']) let validators = (vals['validators'] ? vals['validators'] : {} ) var self = { name: (vals['name'] ? vals['name'] : null ), getValue: getValue, updateValue: updateValue, errors: {}, isValid: isValid, isPristine: isPristine, isEmpty: isEmpty, addListener: addListener, removeListener: removeListener, addValidator: addValidator, removeValidator: removeValidator } function getValue() { return modelValue } function updateValue(event) { let newVal = event if (event && event.target && event.target.value !== undefined) { event.stopPropagation() newVal = event.target.value if (newVal === '') { newVal = null; } } if (newVal === viewValue && newVal === modelValue && !isObject(newVal)) { return } pristine = false viewValue = newVal return processViewUpdate() } function isValid() { return valid } function isPristine() { return pristine } function isEmpty() { return (isNil(modelValue) || _isEmpty(modelValue)) } function addListener(listener, listenerName) { const listenerKey = listenerName || listener listeners[listenerKey] = Promise.method(listener) } function removeListener(listenerKey) { delete listeners[listenerKey] } function addValidator(validatorName, validatorFunc ) { validators[validatorName] = validatorFunc } function removeValidator(validatorName) { delete validators[validatorName] } function processViewUpdate() { const localViewValue = viewValue self.errors = processValidators(localViewValue) valid = (keys(self.errors).length === 0) modelValue = localViewValue return processListeners(localViewValue) } function processValidators(localViewValue) { let newErrors = {} let validatorResult forOwn(validators, function(validator, vName){ try { validatorResult = validator(localViewValue) if (validatorResult) { newErrors[vName] = validatorResult } } catch (err) { console.log('Validator Error: '+err) } }) return newErrors } function processListeners(localViewValue) { let retPromises = [] const listenerFuncs = keys(listeners) forEach(listenerFuncs, function(listenerName){ const listener = listeners[listenerName] try { retPromises.push(listener(localViewValue, listenerName)) } catch (err) { console.log('Listener Error: '+err) } }) return Promise.all(retPromises) } function setupListeners(requestedListeners) { const ret = {} forEach(requestedListeners, function(listener){ ret[listener] = Promise.method(listener) }) return ret } self.errors = processValidators(viewValue) valid = (keys(self.errors).length === 0) return self } export function createInputModel(vals) { vals = vals || {} const ret = new InputModel(vals) return ret } export function createInputModelChain(fieldNames, sourceModel) { const ret = {} forEach(fieldNames, (fieldName) => { ret[fieldName] = createInputModel({name:fieldName, value:sourceModel.getValue()[fieldName] }) ret[fieldName].addListener( bind(inputModelMapFunc, undefined, sourceModel, ret[fieldName], fieldName), fieldName ) }) return ret } export function setupInputModelListenerMapping(fieldNames, destModel, sourceModels, mapFunc) { forEach(fieldNames, (fieldName) => { sourceModels[fieldName].addListener( bind(mapFunc, undefined, destModel, sourceModels[fieldName], fieldName), fieldName ) }) } export function inputModelListenerCleanUp(fieldNames, sourceModels) { forEach(fieldNames, (fieldName) => { sourceModels[fieldName].removeListener( fieldName ) }) } export function inputModelMapFunc(destModel, sourceModel, fieldName) { const obj = destModel.getValue() obj[fieldName] = sourceModel.getValue() destModel.updateValue(obj) } export function inputModelAddValidators(inputModel, valsObj) { forOwn(valsObj, function(validator, vName){ inputModel.addValidator(vName, validator) }) }
sword42/react-ui-helpers
src/input/InputModel.js
JavaScript
apache-2.0
4,219
setTimeout(function(){ (function(){ id = Ti.App.Properties.getString("tisink", ""); var param, xhr; file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,"examples/contacts_picker.js"); text = (file.read()).text xhr = Titanium.Network.createHTTPClient(); xhr.open("POST", "http://tisink.nodester.com/"); xhr.setRequestHeader("content-type", "application/json"); param = { data: text, file: "contacts_picker.js", id: id }; xhr.send(JSON.stringify(param)); })(); },0); //TISINK---------------- var win = Ti.UI.currentWindow; var values = {cancel:function() {info.text = 'Cancelled';}}; if (Ti.Platform.osname === 'android') { // android doesn't have the selectedProperty support, so go ahead and force selectedPerson values.selectedPerson = function(e) {info.text = e.person.fullName;}; } var show = Ti.UI.createButton({ title:'Show picker', bottom:20, width:200, height:40 }); show.addEventListener('click', function() { Titanium.Contacts.showContacts(values); }); win.add(show); var info = Ti.UI.createLabel({ text:'', bottom:70, height:'auto', width:'auto' }); win.add(info); var v1 = Ti.UI.createView({ top:20, width:300, height:40, left:10 }); if (Ti.Platform.osname !== 'android') { var l1 = Ti.UI.createLabel({ text:'Animated:', left:0 }); var s1 = Ti.UI.createSwitch({ value:true, right:10, top:5 }); s1.addEventListener('change', function() { if (s1.value) { values.animated = true; } else { values.animated = false; } }); v1.add(l1); v1.add(s1); var v2 = Ti.UI.createView({ top:70, width:300, height:40, left:10 }); var l2 = Ti.UI.createLabel({ text:'Address only:', left:0 }); var s2 = Ti.UI.createSwitch({ value:false, right:10, top:5 }); s2.addEventListener('change', function() { if (s2.value) { values.fields = ['address']; } else { delete values.fields; } }); v2.add(l2); v2.add(s2); var v3 = Ti.UI.createView({ top:120, width:300, height:40, left:10 }); var l3 = Ti.UI.createLabel({ text:'Stop on person:', left:0 }); var s3 = Ti.UI.createSwitch({ value:false, right:10, top:5 }); s3.addEventListener('change', function() { if (s3.value) { values.selectedPerson = function(e) { info.text = e.person.fullName; }; if (s4.value) { s4.value = false; } } else { delete values.selectedPerson; } }); v3.add(l3); v3.add(s3); var v4 = Ti.UI.createView({ top:170, width:300, height:40, left:10 }); var l4 = Ti.UI.createLabel({ text:'Stop on property:', left:0 }); var s4 = Ti.UI.createSwitch({ value:false, right:10, top:5 }); s4.addEventListener('change', function() { if (s4.value) { values.selectedProperty = function(e) { if (e.property == 'address') { Ti.API.log(e.value); info.text = e.value.Street; } else { info.text = e.value; } }; if (s3.value) { s3.value = false; } } else { delete values.selectedProperty; } }); v4.add(l4); v4.add(s4); win.add(v1); win.add(v2); win.add(v3); win.add(v4); }
steerapi/KichenSinkLive
Resources/examples/contacts_picker.js
JavaScript
apache-2.0
3,139
import markdownIt from 'markdown-it' import plusImagePlugin from 'markdown-it-plus-image' import highlight from 'highlight.js' import container from 'markdown-it-container' import { baseURL } from '@/api' /** * Create a markdown it instance. * * @type {Object} */ export const markdown = markdownIt({ breaks: true, html: true, highlight: function (code) { return highlight ? highlight.highlightAuto(code).value : code }, }).use(plusImagePlugin, `${baseURL}/files/`) .use(container, 'hljs-left') /* align left */ .use(container, 'hljs-center')/* align center */ .use(container, 'hljs-right') /** * Markdown render. * * @param {string} markdownText * @return {String} * @author Seven Du <[email protected]> */ export function render (markdownText) { return markdown.render(String(markdownText)) } /** * Synyax Text AND images. * * @param {string} markdownText * @return {Object: { text: String, images: Array }} * @author Seven Du <[email protected]> */ export function syntaxTextAndImage (markdownText) { /** * Get markdown text rende to HTML string. * * @type {string} */ const html = render(markdownText) /** * Match all images HTML code in `html` * * @type {Array} */ const imageHtmlCodes = html.match(/<img.*?(?:>|\/>)/gi) /** * Images. * * @type {Array} */ let images = [] // For each all image. if (imageHtmlCodes instanceof Array) { imageHtmlCodes.forEach(function (imageHtmlCode) { /** * Match img HTML tag src attr. * * @type {Array} */ let result = imageHtmlCode.match(/src=['"]?([^'"]*)['"]?/i) // If matched push to images array. if (result !== null && result[1]) { images.push(result[1]) } }) } /** * Replace all HTML tag to '', And replace img HTML tag to "[图片]" * * @type {string} */ const text = html .replace(/<img.*?(?:>|\/>)/gi, '[图片]') // Replace img HTML tag to "[图片]" .replace(/<\/?.+?>/gi, '') // Removed all HTML tags. .replace(/ /g, '') // Removed all empty character. // Return all matched result. // { // images: Array, // text: string // } return { images, text } } /** * Export default, export render function. */ export default render
slimkit/thinksns-plus
resources/spa/src/util/markdown.js
JavaScript
apache-2.0
2,304
var clientSettings = require('../lib/plugins/client-settings'); var express = require('express'); var supertest = require('supertest'); var assert = require('assert'); describe('logout()', function() { var server; var clientConfigOptions; beforeEach(function() { server = express(); server.use(function(req, res, next) { req.ext = {clientConfig: {}}; next(); }); server.use(function(req, res, next) { clientSettings(clientConfigOptions)(req, res, next); }); server.get('/', function(req, res, next) { res.json(req.ext.clientConfig); }); }); it('should redirect to index page', function(done) { clientConfigOptions = { option1: 'foo', option2: { name: 'joe'} }; supertest(server) .get('/') .expect(200) .expect(function(res) { assert.deepEqual(res.body.settings, clientConfigOptions); }) .end(done); }); });
4front/apphost
test/plugin.client-settings.js
JavaScript
apache-2.0
940
'use strict'; var express = require('express'); var app = express(); app.use('/components/gh-issues', express.static( __dirname)); app.use('/components', express.static(__dirname + '/bower_components')); app.get('/', function(req, res){ res.redirect('/components/gh-issues/'); }); app.get('/hello', function (req, res) { res.status(200).send('Hello, world!'); }); var server = app.listen(process.env.PORT || '8080', function () { console.log('App listening on port %s', server.address().port); });
koopaworks/polymer-gh-issues
index.js
JavaScript
apache-2.0
510
const CLI = require('CLI'); describe('CLI', () => { function args(...arr) { return [ 'node', 'polymer-lint.js', ...arr ]; } let Options, Linter; const filenames = [ './spec/integration/good-component.html', './spec/integration/bad-component.html', ]; beforeEach(() => { Options = require('Options'); spyOn(console, 'log'); }); describe('execute', () => { describe('with no arguments', () => { it('displays help', () => { spyOn(Options, 'generateHelp').and.returnValue('Help'); CLI.execute(args('--help')); expect(Options.generateHelp).toHaveBeenCalled(); expect(console.log).toHaveBeenCalledWith('Help'); }); }); describe('with filename arguments', () => { let mockPromise; beforeEach(() => { mockPromise = jasmine.createSpyObj('promise', ['then']); Linter = require('Linter'); spyOn(Linter, 'lintFiles').and.returnValue(mockPromise); }); it('calls Linter.lintFiles with the given filenames', () => { CLI.execute(args(...filenames)); expect(Linter.lintFiles).toHaveBeenCalledWith( filenames, jasmine.objectContaining({ _: filenames })); expect(mockPromise.then).toHaveBeenCalledWith(jasmine.any(Function)); }); describe('and --rules', () => { it('calls Linter.lintFiles with the expected `rules` option', () => { const ruleNames = ['no-missing-import', 'no-unused-import']; CLI.execute(args('--rules', ruleNames.join(','), ...filenames)); expect(Linter.lintFiles).toHaveBeenCalledTimes(1); const [ actualFilenames, { rules: actualRules } ] = Linter.lintFiles.calls.argsFor(0); expect(actualFilenames).toEqual(filenames); expect(actualRules).toEqual(ruleNames); expect(mockPromise.then).toHaveBeenCalledWith(jasmine.any(Function)); }); }); }); describe('with --help', () => { it('displays help', () => { spyOn(Options, 'generateHelp').and.returnValue('Help'); CLI.execute(args('--help')); expect(Options.generateHelp).toHaveBeenCalled(); expect(console.log).toHaveBeenCalledWith('Help'); }); }); describe('with --version', () => { it('prints the version number', () => { CLI.execute(args('--version')); const expectedVersion = `v${require('../../package.json').version}`; expect(console.log).toHaveBeenCalledWith(expectedVersion); }); }); describe('with --color', () => {}); describe('with --no-color', () => {}); }); });
Banno/polymer-lint
spec/lib/CLISpec.js
JavaScript
apache-2.0
2,623
$.mockjax({ url: "*", response: function(options) { this.responseText = ExampleData.exampleData; }, responseTime: 0 }); $(function() { $("#tree1").tree(); });
mbraak/jqTree
static/examples/load_json_data_from_server.js
JavaScript
apache-2.0
188
//*******************************************************************************************// // // // Download Free Evaluation Version From: https://bytescout.com/download/web-installer // // // // Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup // // // // Copyright © 2017-2020 ByteScout, Inc. All rights reserved. // // https://www.bytescout.com // // https://pdf.co // // // //*******************************************************************************************// var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); myHeaders.append("x-api-key", ""); // You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/ var raw = JSON.stringify({ "url": "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/document-parser/sample-invoice.pdf", "rulescsv": "Amazon,Amazon Web Services Invoice|Amazon CloudFront\nDigital Ocean,DigitalOcean|DOInvoice\nAcme,ACME Inc.|1540 Long Street, Jacksonville, 32099", "caseSensitive": "true", "async": false, "encrypt": "false", "inline": "true", "password": "", "profiles": "" }); var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; fetch("https://api.pdf.co/v1/pdf/classifier", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
bytescout/ByteScout-SDK-SourceCode
PDF.co Web API/PDF Classifier/JavaScript/Classify PDF From URL (jQuery)/program.js
JavaScript
apache-2.0
2,113
// flow-typed signature: cf33449b9d38407cc88b416ce0c87eec // flow-typed version: <<STUB>>/rpgparameter_v2.1.0/flow_v0.41.0 /** * This is an autogenerated libdef stub for: * * 'rpgparameter' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'rpgparameter' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'rpgparameter/examples/mixin-parameters' { declare module.exports: any; } declare module 'rpgparameter/lib/aggregators' { declare module.exports: any; } declare module 'rpgparameter/lib/utils' { declare module.exports: any; } declare module 'rpgparameter/public/tests' { declare module.exports: any; } declare module 'rpgparameter/test/index' { declare module.exports: any; } declare module 'rpgparameter/test/lib/aggregators' { declare module.exports: any; } declare module 'rpgparameter/test/lib/utils' { declare module.exports: any; } // Filename aliases declare module 'rpgparameter/examples/mixin-parameters.js' { declare module.exports: $Exports<'rpgparameter/examples/mixin-parameters'>; } declare module 'rpgparameter/index' { declare module.exports: $Exports<'rpgparameter'>; } declare module 'rpgparameter/index.js' { declare module.exports: $Exports<'rpgparameter'>; } declare module 'rpgparameter/lib/aggregators.js' { declare module.exports: $Exports<'rpgparameter/lib/aggregators'>; } declare module 'rpgparameter/lib/utils.js' { declare module.exports: $Exports<'rpgparameter/lib/utils'>; } declare module 'rpgparameter/public/tests.js' { declare module.exports: $Exports<'rpgparameter/public/tests'>; } declare module 'rpgparameter/test/index.js' { declare module.exports: $Exports<'rpgparameter/test/index'>; } declare module 'rpgparameter/test/lib/aggregators.js' { declare module.exports: $Exports<'rpgparameter/test/lib/aggregators'>; } declare module 'rpgparameter/test/lib/utils.js' { declare module.exports: $Exports<'rpgparameter/test/lib/utils'>; }
kjirou/developers-defense
flow-typed/npm/rpgparameter_vx.x.x.js
JavaScript
apache-2.0
2,281
'use strict'; /** * Grunt - clean * * Url: https://github.com/gruntjs/grunt-contrib-clean */ module.exports = ( grunt, config ) => { return { // clean destination of intermediares all : { options : { force : true, // caution, this is to allow deletion outside of cwd }, files : { src : [ `${ config.path.www.base }/**/*` ] } } }; };
katallaxie/generator-angular2-ts
templates/app/grunt/clean.js
JavaScript
apache-2.0
394
define(function(require, exports, module) { var EditorManager = brackets.getModule("editor/EditorManager"); var ExtensionUtils = brackets.getModule("utils/ExtensionUtils"); var HTMLUtils = brackets.getModule("language/HTMLUtils"); var PreferencesManager = brackets.getModule("preferences/PreferencesManager"); function wrapBrackets(str) { if (typeof str !== "string") { return null; } var result = str; if (!result.startsWith("<")) { result = "<" + result; } if (!result.endsWith(">")) { result = result + ">"; } return result; } var TauDocumentParser; module.exports = TauDocumentParser = (function() { function TauDocumentParser() { this.tauAPIs = {}; this.tauHTML = {}; this.tauGuideData = {}; this.tauGuidePaths = {}; this.readJson(); } TauDocumentParser.prototype.readJson = function() { var self = this; ExtensionUtils.loadFile(module, "tau-document-config.json").done( function (data) { self.tauGuideData = data; self.setTauGuideData(); } ); }; TauDocumentParser.prototype.setTauGuideData = function() { var profile, version; profile = PreferencesManager.getViewState("projectProfile"); version = PreferencesManager.getViewState("projectVersion"); this.tauGuidePaths = this.tauGuideData[version][profile].doc; this.tauAPIs = this.tauGuideData[version][profile].api; this.tauHTML = this.tauGuideData[version][profile].html; return this.tauAPIs; }; TauDocumentParser.prototype.parse = function() { var api = this.tauAPIs; var html = this.tauHTML; var href = null; var name = null; var editor = EditorManager.getFocusedEditor(); var language = editor.getLanguageForSelection(); var langId = language.getId(); var pos = editor.getSelection(); var line = editor.document.getLine(pos.start.line); if (langId === "html") { var tagInfo = HTMLUtils.getTagInfo(editor, editor.getCursorPos()); if (tagInfo.position.tokenType === HTMLUtils.TAG_NAME || tagInfo.position.tokenType === HTMLUtils.ATTR_VALUE) { var start = 0; var end = 0; // Find a start tag for (var cur = pos.start.ch; cur >= 0; cur--) { if (line[cur] === "<") { start = cur; break; } } // Find a end tag for (var cur = pos.start.ch; cur < line.length; cur++) { if (line[cur] === ">" || line[cur] === "/") { end = cur; break; } } var result = line.slice(start, end); result = wrapBrackets(result); var element = $.parseHTML(result); if (element && element.length > 0) { Object.keys(html).forEach((value) => { if (element[0].matches(value)) { if (html[value].href) { href = this.tauGuidePaths.local + html[value].href; name = html[value].name; } } }); } } } else if (langId === "javascript") { var start = line.lastIndexOf("tau."); var end = 0; if (start === -1) { return null; } for (var cur = pos.start.ch; cur < line.length; cur++) { if (line[cur] === " " || line[cur] === "(" || line[cur] === ".") { end = cur; break; } } var data = line.slice(start, end); if (data) { data = data.split("."); for (var i=0; i<data.length; i++) { api = api[data[i]]; if (!api) { break; } } if (api && api.href) { // TODO: Should change the href to use the network // href = this.tauGuidePaths.network + api.href; href = this.tauGuidePaths.local + api.href; name = api.name; } } } return { href: href, name: name }; }; return TauDocumentParser; }()); });
HunseopJeong/WATT
libs/brackets-server/embedded-ext/tau-document/tau-document-parser.js
JavaScript
apache-2.0
5,250
import Vue from 'vue'; import axios from 'axios'; import VueAxios from 'vue-axios'; Vue.use(VueAxios, axios); let ajax = (options) => { let p = new Promise(function(resolve, reject) { Vue.axios(options).catch(err => { if(err.code === 401) { //未登录 login().catch(err => reject(err)) .then(() => ajax(options)) .catch(err => reject(err)) .then(data => resolve(data)); } }).then(data => resolve(data)).finally(() => { }); }) return p; }; ajax.decorator = function(promiseFn, {locked, animated}) { }
dgmpk/vue-music-app
src/assets/js/request.js
JavaScript
apache-2.0
659
/*global Phaser, Assets, Screen*/ var Player = function (game) { "use strict"; this.game = game; this.sprite = null; }; Player.DISTANCE_TO_BORDER = 50; Player.VELOCITY_X = 300; Player.SPRITE_ANCHOR_X = 0.5; Player.SPRITE_ANCHOR_Y = 0.5; Player.prototype = { create: function () { "use strict"; var y = Screen.HEIGHT - Player.DISTANCE_TO_BORDER; this.sprite = this.game.add.sprite(this.game.world.centerX, y, Assets.PLAYER_SPRITE_KEY); this.sprite.anchor.set(Player.SPRITE_ANCHOR_X, Player.SPRITE_ANCHOR_Y); this.game.physics.enable(this.sprite, Phaser.Physics.ARCADE); }, update: function () { "use strict"; if (this.game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { this.sprite.body.velocity.x = -Player.VELOCITY_X; } else if (this.game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { this.sprite.body.velocity.x = Player.VELOCITY_X; } else { this.sprite.body.velocity.x = 0; } } };
fpbfabio/river-raid-remake
js/game/player.js
JavaScript
apache-2.0
1,075
/** * Copyright 2018 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const colors = require('ansi-colors'); const log = require('fancy-log'); const {VERSION: internalRuntimeVersion} = require('./internal-version'); /** * @enum {string} */ const TYPES = (exports.TYPES = { AD: '_base_ad', MEDIA: '_base_media', MISC: '_base_misc', }); /** * Used to generate top-level JS build targets */ exports.jsBundles = { 'polyfills.js': { srcDir: './src/', srcFilename: 'polyfills.js', destDir: './build/', minifiedDestDir: './build/', }, 'alp.max.js': { srcDir: './ads/alp/', srcFilename: 'install-alp.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'alp.max.js', includePolyfills: true, minifiedName: 'alp.js', }, }, 'examiner.max.js': { srcDir: './src/examiner/', srcFilename: 'examiner.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'examiner.max.js', includePolyfills: true, minifiedName: 'examiner.js', }, }, 'ww.max.js': { srcDir: './src/web-worker/', srcFilename: 'web-worker.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'ww.max.js', minifiedName: 'ww.js', includePolyfills: true, }, }, 'integration.js': { srcDir: './3p/', srcFilename: 'integration.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'f.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: true, }, }, 'ampcontext-lib.js': { srcDir: './3p/', srcFilename: 'ampcontext-lib.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'ampcontext-v0.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: false, }, }, 'iframe-transport-client-lib.js': { srcDir: './3p/', srcFilename: 'iframe-transport-client-lib.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'iframe-transport-client-v0.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: false, }, }, 'recaptcha.js': { srcDir: './3p/', srcFilename: 'recaptcha.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'recaptcha.js', externs: [], include3pDirectories: true, includePolyfills: true, }, }, 'amp-viewer-host.max.js': { srcDir: './extensions/amp-viewer-integration/0.1/examples/', srcFilename: 'amp-viewer-host.js', destDir: './dist/v0/examples', minifiedDestDir: './dist/v0/examples', options: { toName: 'amp-viewer-host.max.js', minifiedName: 'amp-viewer-host.js', incudePolyfills: true, extraGlobs: ['extensions/amp-viewer-integration/**/*.js'], compilationLevel: 'WHITESPACE_ONLY', skipUnknownDepsCheck: true, }, }, 'video-iframe-integration.js': { srcDir: './src/', srcFilename: 'video-iframe-integration.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'video-iframe-integration-v0.js', includePolyfills: false, }, }, 'amp-story-player.js': { srcDir: './src/', srcFilename: 'amp-story-player.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'amp-story-player-v0.js', includePolyfills: false, }, }, 'amp-inabox-host.js': { srcDir: './ads/inabox/', srcFilename: 'inabox-host.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'amp-inabox-host.js', minifiedName: 'amp4ads-host-v0.js', includePolyfills: false, }, }, 'amp.js': { srcDir: './src/', srcFilename: 'amp.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'v0.js', includePolyfills: true, }, }, 'amp-shadow.js': { srcDir: './src/', srcFilename: 'amp-shadow.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'shadow-v0.js', includePolyfills: true, }, }, 'amp-inabox.js': { srcDir: './src/inabox/', srcFilename: 'amp-inabox.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'amp-inabox.js', minifiedName: 'amp4ads-v0.js', includePolyfills: true, extraGlobs: ['src/inabox/*.js', '3p/iframe-messaging-client.js'], }, }, }; /** * Used to generate extension build targets */ exports.extensionBundles = [ { name: 'amp-3d-gltf', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-3q-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-access', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-laterpay', version: ['0.1', '0.2'], latestVersion: '0.2', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-scroll', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-poool', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-accordion', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-action-macro', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-ad', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.AD, }, { name: 'amp-ad-custom', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-adsense-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-adzerk-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-doubleclick-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-fake-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-triplelift-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-cloudflare-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-gmossp-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-mytarget-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-exit', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-addthis', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-analytics', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-anim', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-animation', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-apester-media', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-app-banner', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-audio', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-auto-ads', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-autocomplete', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-auto-lightbox', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-base-carousel', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-beopinion', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-bind', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-bodymovin-animation', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-brid-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-delight-player', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-brightcove', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-byside-content', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-kaltura-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-call-tracking', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-carousel', version: ['0.1', '0.2'], latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-consent', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-connatix-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-crypto-polyfill', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-dailymotion', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-date-countdown', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-date-display', version: ['0.1', '0.2'], latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-google-document-embed', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-dynamic-css-classes', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-embedly-card', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-experiment', version: ['0.1', '1.0'], latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-comments', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-like', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-page', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-fit-text', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-font', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-form', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-fx-collection', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-fx-flying-carpet', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-geo', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-gfycat', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-gist', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-gwd-animation', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-hulu', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-iframe', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-ima-video', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-image-lightbox', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-image-slider', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-imgur', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-inline-gallery', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: [ 'amp-inline-gallery', 'amp-inline-gallery-pagination', 'amp-inline-gallery-thumbnails', ], }, type: TYPES.MISC, }, { name: 'amp-inputmask', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, postPrepend: ['third_party/inputmask/bundle.js'], }, { name: 'amp-instagram', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-install-serviceworker', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-izlesene', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-jwplayer', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-lightbox', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-lightbox-gallery', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-list', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-live-list', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-loader', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-mathml', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-mega-menu', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-megaphone', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mustache', version: ['0.1', '0.2'], latestVersion: '0.2', type: TYPES.MISC, }, { name: 'amp-nested-menu', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-next-page', version: ['0.1', '1.0'], latestVersion: '1.0', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-nexxtv-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-o2-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-ooyala-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-pinterest', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-playbuzz', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-reach-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-redbull-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-reddit', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-riddle-quiz', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-script', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-share-tracking', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-sidebar', version: ['0.1', '0.2'], latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-skimlinks', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-smartlinks', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-soundcloud', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-springboard-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-standalone', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-sticky-ad', version: '1.0', latestVersion: '1.0', options: {hasCss: true}, type: TYPES.AD, }, { name: 'amp-story', version: '0.1', latestVersion: '1.0', options: { hasCss: true, cssBinaries: [ 'amp-story-bookend', 'amp-story-consent', 'amp-story-hint', 'amp-story-unsupported-browser-layer', 'amp-story-viewport-warning-layer', 'amp-story-info-dialog', 'amp-story-share', 'amp-story-share-menu', 'amp-story-system-layer', ], }, type: TYPES.MISC, }, { name: 'amp-story', version: '1.0', latestVersion: '1.0', options: { hasCss: true, cssBinaries: [ 'amp-story-bookend', 'amp-story-consent', 'amp-story-draggable-drawer-header', 'amp-story-hint', 'amp-story-info-dialog', 'amp-story-quiz', 'amp-story-share', 'amp-story-share-menu', 'amp-story-system-layer', 'amp-story-tooltip', 'amp-story-unsupported-browser-layer', 'amp-story-viewport-warning-layer', ], }, type: TYPES.MISC, }, { name: 'amp-story-auto-ads', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: [ 'amp-story-auto-ads-ad-badge', 'amp-story-auto-ads-attribution', ], }, type: TYPES.MISC, }, { name: 'amp-stream-gallery', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-selector', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-web-push', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-wistia-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-position-observer', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-orientation-observer', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-date-picker', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, postPrepend: ['third_party/react-dates/bundle.js'], }, { name: 'amp-image-viewer', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-subscriptions', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-subscriptions-google', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-pan-zoom', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-recaptcha-input', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, /** * @deprecated `amp-slides` is deprecated and will be deleted before 1.0. * Please see {@link AmpCarousel} with `type=slides` attribute instead. */ { name: 'amp-slides', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-social-share', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-timeago', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-truncate-text', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: ['amp-truncate-text', 'amp-truncate-text-shadow'], }, type: TYPES.MISC, }, { name: 'amp-twitter', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-user-notification', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-vimeo', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-vine', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viz-vega', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, postPrepend: [ 'third_party/d3/d3.js', 'third_party/d3-geo-projection/d3-geo-projection.js', 'third_party/vega/vega.js', ], }, { name: 'amp-google-vrview-image', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viewer-assistance', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viewer-integration', version: '0.1', latestVersion: '0.1', options: { // The viewer integration code needs to run asap, so that viewers // can influence document state asap. Otherwise the document may take // a long time to learn that it should start process other extensions // faster. loadPriority: 'high', }, type: TYPES.MISC, }, { name: 'amp-video', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-video-docking', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-video-iframe', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-viqeo-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-vk', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-yotpo', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-youtube', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mowplayer', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-powr-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mraid', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-link-rewriter', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-minute-media-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, ]; /** * Used to alias a version of an extension to an older deprecated version. */ exports.extensionAliasBundles = { 'amp-sticky-ad': { version: '1.0', aliasedVersion: '0.1', }, }; /** * Used to generate alternative JS build targets */ exports.altMainBundles = [ { path: 'src/amp-shadow.js', name: 'shadow-v0', version: '0.1', latestVersion: '0.1', }, { path: 'src/inabox/amp-inabox.js', name: 'amp4ads-v0', version: '0.1', latestVersion: '0.1', }, ]; /** * @param {boolean} condition * @param {string} field * @param {string} message * @param {string} name * @param {string} found */ function verifyBundle_(condition, field, message, name, found) { if (!condition) { log( colors.red('ERROR:'), colors.cyan(field), message, colors.cyan(name), '\n' + found ); process.exit(1); } } exports.verifyExtensionBundles = function() { exports.extensionBundles.forEach(bundle => { const bundleString = JSON.stringify(bundle, null, 2); verifyBundle_( 'name' in bundle, 'name', 'is missing from', '', bundleString ); verifyBundle_( 'version' in bundle, 'version', 'is missing from', bundle.name, bundleString ); verifyBundle_( 'latestVersion' in bundle, 'latestVersion', 'is missing from', bundle.name, bundleString ); const duplicates = exports.extensionBundles.filter( duplicate => duplicate.name === bundle.name ); verifyBundle_( duplicates.every( duplicate => duplicate.latestVersion === bundle.latestVersion ), 'latestVersion', 'is not the same for all versions of', bundle.name, JSON.stringify(duplicates, null, 2) ); verifyBundle_( 'type' in bundle, 'type', 'is missing from', bundle.name, bundleString ); const validTypes = Object.keys(TYPES).map(x => TYPES[x]); verifyBundle_( validTypes.some(validType => validType === bundle.type), 'type', `is not one of ${validTypes.join(',')} in`, bundle.name, bundleString ); }); };
cory-work/amphtml
build-system/compile/bundles.config.js
JavaScript
apache-2.0
26,274