commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
73dbeed557071dbbb1c48caa2d1df2f075158ea1
Put fonts with the CSS
setup/webpack.config.js
setup/webpack.config.js
var path = require('path'); var webpack = require('webpack'); var Mix = require('laravel-mix').config; var plugins = require('laravel-mix').plugins; /* |-------------------------------------------------------------------------- | Mix Initialization |-------------------------------------------------------------------------- | | As our first step, we'll require the project's Laravel Mix file | and record the user's requested compilation and build steps. | Once those steps have been recorded, we may get to work. | */ Mix.finalize(); /* |-------------------------------------------------------------------------- | Webpack Context |-------------------------------------------------------------------------- | | This prop will determine the appropriate context, when running Webpack. | Since you have the option of publishing this webpack.config.js file | to your project root, we will dynamically set the path for you. | */ module.exports.context = Mix.contextPath(); /* |-------------------------------------------------------------------------- | Webpack Entry |-------------------------------------------------------------------------- | | We'll first specify the entry point for Webpack. By default, we'll | assume a single bundled file, but you may call Mix.extract() | to make a separate bundle specifically for vendor libraries. | */ module.exports.entry = Mix.entry(); if (Mix.js.vendor) { module.exports.entry.vendor = Mix.js.vendor; } /* |-------------------------------------------------------------------------- | Webpack Output |-------------------------------------------------------------------------- | | Webpack naturally requires us to specify our desired output path and | file name. We'll simply echo what you passed to with Mix.js(). | Note that, for Mix.version(), we'll properly hash the file. | */ module.exports.output = Mix.output(); /* |-------------------------------------------------------------------------- | Rules |-------------------------------------------------------------------------- | | Webpack rules allow us to register any number of loaders and options. | Out of the box, we'll provide a handful to get you up and running | as quickly as possible, though feel free to add to this list. | */ module.exports.module = { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { js: 'babel-loader' + Mix.babelConfig() }, postcss: [ require('autoprefixer') ] } }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader' + Mix.babelConfig() }, { test: /\.(png|jpg|gif)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } }, { test: /\.(woff2?|ttf|eot|svg)$/, loader: 'file-loader', options: { name: path.relative(__dirname, './fonts/[name].[ext]?[hash]') } } ] }; if (Mix.sass) { module.exports.module.rules.push({ test: /\.s[ac]ss$/, loader: plugins.ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: [ 'css-loader', 'postcss-loader', 'resolve-url-loader', 'sass-loader?sourceMap' ] }) }); } if (Mix.less) { module.exports.module.rules.push({ test: /\.less$/, loader: plugins.ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: ['css-loader', 'postcss-loader', 'less-loader'] }) }); } /* |-------------------------------------------------------------------------- | Resolve |-------------------------------------------------------------------------- | | Here, we may set any options/aliases that affect Webpack's resolving | of modules. To begin, we will provide the necessary Vue alias to | load the Vue common library. You may delete this, if needed. | */ module.exports.resolve = { extensions: ['*', '.js', '.jsx', '.vue'], alias: { 'vue$': 'vue/dist/vue.common.js' } }; /* |-------------------------------------------------------------------------- | Stats |-------------------------------------------------------------------------- | | By default, Webpack spits a lot of information out to the terminal, | each you time you compile. Let's keep things a bit more minimal | and hide a few of those bits and pieces. Adjust as you wish. | */ module.exports.stats = { hash: false, version: false, timings: false, children: false }; module.exports.performance = { hints: false}; /* |-------------------------------------------------------------------------- | Devtool |-------------------------------------------------------------------------- | | Sourcemaps allow us to access our original source code within the | browser, even if we're serving a bundled script or stylesheet. | You may activate sourcemaps, by adding Mix.sourceMaps(). | */ module.exports.devtool = Mix.sourcemaps; /* |-------------------------------------------------------------------------- | Webpack Dev Server Configuration |-------------------------------------------------------------------------- | | If you want to use that flashy hot module replacement feature, then | we've got you covered. Here, we'll set some basic initial config | for the Node server. You very likely won't want to edit this. | */ module.exports.devServer = { historyApiFallback: true, noInfo: true }; /* |-------------------------------------------------------------------------- | Plugins |-------------------------------------------------------------------------- | | Lastly, we'll register a number of plugins to extend and configure | Webpack. To get you started, we've included a handful of useful | extensions, for versioning, OS notifications, and much more. | */ module.exports.plugins = []; if (Mix.notifications) { module.exports.plugins.push( new plugins.WebpackNotifierPlugin({ title: 'Laravel Mix', alwaysNotify: true, contentImage: 'node_modules/laravel-mix/icons/laravel.png' }) ); } module.exports.plugins.push( function() { this.plugin('done', stats => Mix.manifest.write(stats)); } ); module.exports.plugins.push( new webpack.LoaderOptionsPlugin({ minimize: Mix.inProduction, options: { postcss: [ require('autoprefixer') ], context: __dirname, output: { path: './' } } }) ); if (Mix.versioning.enabled) { Mix.versioning.record(); module.exports.plugins.push( new plugins.WebpackOnBuildPlugin(() => { Mix.versioning.prune(Mix.publicPath); }) ); } if (Mix.combine || Mix.minify) { module.exports.plugins.push( new plugins.WebpackOnBuildPlugin(() => { Mix.concatenateAll().minifyAll(); }) ); } if (Mix.copy) { Mix.copy.forEach(copy => { module.exports.plugins.push( new plugins.CopyWebpackPlugin([copy]) ); }); } if (Mix.js.vendor) { module.exports.plugins.push( new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'] }) ); } if (Mix.cssPreprocessor) { module.exports.plugins.push( new plugins.ExtractTextPlugin({ filename: Mix.cssOutput() }) ); } if (Mix.inProduction) { module.exports.plugins = module.exports.plugins.concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false } }) ]); }
JavaScript
0
@@ -3149,30 +3149,38 @@ ath. -relative(__dirname, +parse(Mix.cssOutput()).dir + ' -. /fon @@ -3202,17 +3202,16 @@ ?%5Bhash%5D' -) %0A
8fafbd61d89c1b1638a228a23d77ea6d46fe854c
Remove parsing
Application/RecruitmentManagementSystem.App/Scripts/questions/controllers/questions.controller.js
Application/RecruitmentManagementSystem.App/Scripts/questions/controllers/questions.controller.js
(function(app) { "use strict"; app.controller("QuestionsController", [ "$http", "fileService", "notifierService", "questionConstants", "$scope", function($http, fileService, notifierService, constants, $scope) { var vm = this; vm.constants = constants; vm.allDocuments = []; vm.categories = []; var defaultChoices = [ { text: "", isValid: false }, { text: "", isValid: false } ]; vm.choices = angular.copy(defaultChoices); vm.create = function() { vm.form.submitted = true; var model = { text: vm.text, questionType: vm.questionType, choices: parseInt(vm.questionType, 10) === vm.constants.questionType.descriptive ? [] : vm.choices, notes: vm.notes, answer: vm.answer, categoryId: vm.categoryId, files: [], __RequestVerificationToken: angular.element(":input:hidden[name*='RequestVerificationToken']").val() }; if (vm.allDocuments && vm.allDocuments.length) { model.files = vm.allDocuments; } if (vm.form.$valid) { fileService.postMultipartForm({ url: "/Question/Create", data: model }).progress(function(evt) { console.log("percent: " + parseInt(100.0 * evt.loaded / evt.total)); }).success(function(data) { location.href = "/Question"; }).error(function(response) { notifierService.notifyError(response); }); } }; vm.update = function() { vm.form.submitted = true; }; vm.addNewChoice = function() { vm.choices.push({ text: "", isValid: false }); }; vm.discardChoice = function(index) { vm.choices.splice(index, 1); }; vm.find = function() { var id = location.pathname.replace("/Question/Edit/", ""); $http.get("/Question/Details/" + id).success(function(data) { vm.question = data; }); }; vm.findCategories = function() { $http.get("/QuestionCategory/").success(function(data) { vm.categories = data; }); }; vm.addDocument = function(files) { angular.forEach(files, function(file) { if (file) { vm.allDocuments.push(file); } }); } vm.discardDocument = function(index) { vm.allDocuments.splice(index, 1); } // Watchers $scope.$watch(function() { return vm.questionType; }, function(newVal, oldVal) { if (newVal !== oldVal) { vm.choices = angular.copy(defaultChoices); } }); } ]); })(angular.module("questions"));
JavaScript
0.000013
@@ -286,24 +286,37 @@ constants;%0A + %0A @@ -759,16 +759,129 @@ = true;%0A + console.log(vm.questionType);%0A console.log(vm.constants.questionType.descriptive); %0A @@ -1018,25 +1018,16 @@ hoices: -parseInt( vm.quest @@ -1037,13 +1037,8 @@ Type -, 10) === @@ -2990,24 +2990,25 @@ t = function + (files) %7B%0A @@ -3192,32 +3192,33 @@ );%0A %7D +; %0A%0A vm @@ -3309,32 +3309,33 @@ );%0A %7D +; %0A%0A //
323badd3ed9a8ce7db54f139acfb49d46918a0c1
Fix Challenge View (#1540)
CTFd/plugins/dynamic_challenges/assets/view.js
CTFd/plugins/dynamic_challenges/assets/view.js
CTFd._internal.challenge.data = undefined CTFd._internal.challenge.renderer = CTFd.lib.markdown(); CTFd._internal.challenge.preRender = function () { } CTFd._internal.challenge.render = function (markdown) { return CTFd._internal.challenge.renderer.render(markdown) } CTFd._internal.challenge.postRender = function () { } CTFd._internal.challenge.submit = function (preview) { var challenge_id = parseInt(CTFd.lib.$('#challenge-id').val()) var submission = CTFd.lib.$('#submission-input').val() var body = { 'challenge_id': challenge_id, 'submission': submission, } var params = {} if (preview) { params['preview'] = true } return CTFd.api.post_challenge_attempt(params, body).then(function (response) { if (response.status === 429) { // User was ratelimited but process response return response } if (response.status === 403) { // User is not logged in or CTF is paused. return response } return response }) };
JavaScript
0
@@ -483,26 +483,25 @@ lib.$('# -submission +challenge -input')
8645c2e9e086271a3c677873f771a7dfcf1fbcfd
Read from cookie
src/javascript/config.js
src/javascript/config.js
/* * Configuration values needed in js codes * * NOTE: * Please use the following command to avoid accidentally committing personal changes * git update-index --assume-unchanged src/javascript/config.js * */ function getAppId() { return localStorage.getItem('config.app_id') ? localStorage.getItem('config.app_id') : /staging\.binary\.com/i.test(window.location.hostname) ? '1098' : '1'; } function getSocketURL() { var server_url = localStorage.getItem('config.server_url'), loginid = $.cookie('loginid'), isReal = loginid && !/^VRT/.test(loginid), realToGreenPercent = 90, virtualToBluePercent = 90, randomPercent = Math.random() * 100; if(!server_url) server_url = (/staging\.binary\.com/i.test(window.location.hostname) ? 'www2' : (isReal ? (randomPercent < realToGreenPercent ? 'green' : 'blue' ) : (randomPercent < virtualToBluePercent ? 'blue' : 'green')) ) + '.binaryws.com'; return 'wss://' + server_url + '/websockets/v3'; }
JavaScript
0
@@ -497,25 +497,51 @@ er_url') -, +; %0A - +if(!server_url) %7B%0A var loginid @@ -572,16 +572,20 @@ + isReal = @@ -627,21 +627,21 @@ -realT + t oGreenPe @@ -650,51 +650,41 @@ ent - = -90,%0A virtualToBluePercent = 90,%0A +%7B'real': 100, 'other': 0%7D,%0A @@ -726,50 +726,311 @@ 100 -;%0A if(!server_url) server_url =%0A +,%0A percentValues = $.cookie('connection_setup');%0A if(percentValues && percentValues.indexOf(',') %3E 0) %7B%0A var percents = percentValues.split(',');%0A toGreenPercent.real = +percents%5B0%5D;%0A toGreenPercent.other = +percents%5B1%5D;%0A %7D%0A server_url = (/s @@ -1105,16 +1105,20 @@ + (isReal @@ -1140,13 +1140,9 @@ t %3C -realT +t oGre @@ -1150,17 +1150,21 @@ nPercent - +.real ? 'gre @@ -1179,13 +1179,16 @@ lue' - ) :%0A + @@ -1226,51 +1226,54 @@ t %3C -virtualToBluePercent ? 'blue' : 'green'))%0A +toGreenPercent.other ? 'green' : 'blue'))%0A @@ -1297,16 +1297,22 @@ s.com';%0A + %7D%0A retu
2d27b42b8161dc715f9649d42d670b1a63d39e67
Add chainable add() method
public/assets/wee/script/chain/wee.chain.dom.js
public/assets/wee/script/chain/wee.chain.dom.js
(function(W, U) { 'use strict'; var $ = W._win[WeeAlias]; W.$chain({ addClass: function(value) { W.$addClass(this, value); return this; }, after: function(source, remove) { W.$after(this, source, remove); return this; }, append: function(source) { W.$append(this, source); return this; }, appendTo: function(target) { W.$append(target, this); return this; }, attr: function(key, value) { var resp = W.$attr(this, key, value); return value !== U ? this : resp; }, before: function(source, remove) { W.$before(this, source, remove); return this; }, children: function(filter) { return $(W.$children(this, filter)); }, clone: function() { return $(W.$clone(this)); }, closest: function(filter) { return $(W.$closest(this, filter)); }, contains: function(descendant) { return W.$contains(this, descendant); }, contents: function() { return $(W.$contents(this)); }, css: function(a, b) { var r = W.$css(this, a, b); return b || W.$isObject(a) ? this : r; }, data: function(key, value) { var resp = W.$data(this, key, value); return value !== U ? this : resp; }, empty: function() { W.$empty(this); return this; }, eq: function(index) { return $(W.$eq(this, index)); }, filter: function(filter) { return $(W.$filter(this, filter)); }, find: function(filter) { return $(W.$find(this, filter)); }, first: function() { return this.eq(0); }, hasClass: function(value) { return W.$hasClass(this, value); }, height: function(value) { var r = W.$height(this, value); return value === U || value === true ? r : this; }, hide: function() { W.$hide(this); return this; }, html: function(value) { var r = W.$html(this, value); return value !== U ? this : r; }, index: function() { return W.$index(this); }, insertAfter: function(source) { W.$insertAfter(this, source); return this; }, insertBefore: function(source) { W.$insertBefore(this, source); return this; }, is: function(filter) { return W.$is(this, filter); }, last: function() { return $(W.$last(this)); }, next: function(filter) { return $(W.$next(this, filter)); }, not: function(filter) { return $(W.$not(this, filter)); }, offset: function(value) { return W.$offset(this, value); }, parent: function() { return $(W.$parent(this)); }, parents: function(filter) { return $(W.$parents(this, filter)); }, position: function() { return W.$position(this); }, prepend: function(source) { W.$prepend(this, source); return this; }, prependTo: function(target) { W.$prepend(target, this.reverse()); return this; }, prev: function(filter) { return $(W.$prev(this, filter)); }, prop: function(key, value) { var r = W.$prop(this, key, value); return value !== U ? this : r; }, remove: function() { W.$remove(this); return this; }, removeAttr: function(key) { W.$removeAttr(this, key); return this; }, removeClass: function(value) { W.$removeClass(this, value); return this; }, replaceWith: function(source) { return W.$replaceWith(this, source); }, scrollLeft: function(value) { var r = W.$scrollLeft(this, value); return value === U || value === true ? r : this; }, scrollTop: function(value) { var r = W.$scrollTop(this, value); return value === U || value === true ? r : this; }, serialize: function() { return W.$serializeForm(this); }, show: function() { W.$show(this); return this; }, siblings: function(filter) { return $(W.$siblings(this, filter)); }, slice: function(start, end) { return $(W.$slice(this, start, end)); }, text: function(value) { var r = W.$text(this, value); return value !== U ? this : r; }, toggle: function() { W.$toggle(this); return this; }, toggleClass: function(val, toggle) { W.$toggleClass(this, val, toggle); return this; }, val: function(value) { var r = W.$val(this, value); return value !== U ? this : r; }, width: function(value) { var r = W.$width(this, value); return value === U || value === true ? r : this; }, wrap: function(html) { W.$wrap(this, html); return this; }, wrapInner: function(html) { W.$wrapInner(this, html); return this; } }); })(Wee, undefined);
JavaScript
0.000001
@@ -1,8 +1,31 @@ +/* global WeeAlias */%0A%0A (functio @@ -90,16 +90,189 @@ chain(%7B%0A +%09%09add: function(source) %7B%0A%09%09%09var orig = %5B%5D,%0A%09%09%09%09i = 0;%0A%0A%09%09%09for (; i %3C this.length; i++) %7B%0A%09%09%09%09orig.push(this%5Bi%5D);%0A%09%09%09%7D%0A%0A%09%09%09return $(W.$merge(orig, W.$(source), true));%0A%09%09%7D,%0A %09%09addCla
4f6d21199cdba5d70df3f0e78d81cde680879de1
Remove unused variable
libsquoosh/src/worker_pool.js
libsquoosh/src/worker_pool.js
import { Worker, parentPort } from 'worker_threads'; import { TransformStream } from 'web-streams-polyfill'; function uuid() { return Array.from({ length: 16 }, () => Math.floor(Math.random() * 256).toString(16), ).join(''); } function jobPromise(worker, msg) { return new Promise((resolve, reject) => { const id = uuid(); worker.postMessage({ msg, id }); worker.on('message', function f({ error, result, id: rid }) { if (rid !== id) { return; } if (error) { reject(error); return; } worker.off('message', f); resolve(result); }); }); } export default class WorkerPool { constructor(numWorkers, workerFile) { this.numWorkers = numWorkers; this.jobQueue = new TransformStream(); this.workerQueue = new TransformStream(); const writer = this.workerQueue.writable.getWriter(); for (let i = 0; i < numWorkers; i++) { writer.write(new Worker(workerFile)); } writer.releaseLock(); this.done = this._readLoop(); } async _readLoop() { const reader = this.jobQueue.readable.getReader(); while (true) { const { value, done } = await reader.read(); if (done) { await this._terminateAll(); return; } const { msg, resolve, reject } = value; const worker = await this._nextWorker(); jobPromise(worker, msg) .then((result) => resolve(result)) .catch((reason) => reject(reason)) .finally(() => { // Return the worker to the pool const writer = this.workerQueue.writable.getWriter(); writer.write(worker); writer.releaseLock(); }); } } async _nextWorker() { const reader = this.workerQueue.readable.getReader(); const { value, done } = await reader.read(); reader.releaseLock(); return value; } async _terminateAll() { for (let n = 0; n < this.numWorkers; n++) { const worker = await this._nextWorker(); worker.terminate(); } this.workerQueue.writable.close(); } async join() { this.jobQueue.writable.getWriter().close(); await this.done; } dispatchJob(msg) { return new Promise((resolve, reject) => { const writer = this.jobQueue.writable.getWriter(); writer.write({ msg, resolve, reject }); writer.releaseLock(); }); } static useThisThreadAsWorker(cb) { parentPort.on('message', async (data) => { const { msg, id } = data; try { const result = await cb(msg); parentPort.postMessage({ result, id }); } catch (e) { parentPort.postMessage({ error: e.message, id }); } }); } }
JavaScript
0.000015
@@ -1780,38 +1780,32 @@ const %7B value -, done %7D = await reade
a4c175ef207c97f84eca6c022b8d609973800512
use dialog skin in example
examples/example.js
examples/example.js
var View = require('../src/index.js'); var view = new View({skin: 'preview', position: 'mc', serviceName: 'SatisMeter'}); view.on('submit', function() { console.log('submit', view.rating, view.feedback); }); view.on('dismiss', function() { console.log('dismiss'); }); view.show(); // expose view for experiments window.view = view;
JavaScript
0
@@ -64,15 +64,14 @@ n: ' -preview +dialog ', p
ff3fb2e72ec9a0706c307135e1f30cc1389c0587
Add _gh_pages folder in ignores.
build/change-version.js
build/change-version.js
#!/usr/bin/env node /*! * Script to update version number references in the project. * Copyright 2017-2019 The Bootstrap Authors * Copyright 2017-2019 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ 'use strict' const fs = require('fs') const path = require('path') const sh = require('shelljs') sh.config.fatal = true // Blame TC39... https://github.com/benjamingr/RegExp.escape/issues/37 function regExpQuote(string) { return string.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&') } function regExpQuoteReplacement(string) { return string.replace(/[$]/g, '$$') } const DRY_RUN = false function walkAsync(directory, excludedDirectories, fileCallback, errback) { if (excludedDirectories.has(path.parse(directory).base)) { return } fs.readdir(directory, (err, names) => { if (err) { errback(err) return } names.forEach(name => { const filepath = path.join(directory, name) fs.lstat(filepath, (err, stats) => { if (err) { process.nextTick(errback, err) return } if (stats.isDirectory()) { process.nextTick(walkAsync, filepath, excludedDirectories, fileCallback, errback) } else if (stats.isFile()) { process.nextTick(fileCallback, filepath) } }) }) }) } function replaceRecursively(directory, excludedDirectories, allowedExtensions, original, replacement) { original = new RegExp(regExpQuote(original), 'g') replacement = regExpQuoteReplacement(replacement) const updateFile = DRY_RUN ? filepath => { if (allowedExtensions.has(path.parse(filepath).ext)) { console.log(`FILE: ${filepath}`) } else { console.log(`EXCLUDED:${filepath}`) } } : filepath => { if (allowedExtensions.has(path.parse(filepath).ext)) { sh.sed('-i', original, replacement, filepath) } } walkAsync(directory, excludedDirectories, updateFile, err => { console.error('ERROR while traversing directory!:') console.error(err) process.exit(1) }) } function main(args) { if (args.length !== 2) { console.error('USAGE: change-version old_version new_version') console.error('Got arguments:', args) process.exit(1) } const oldVersion = args[0] const newVersion = args[1] const EXCLUDED_DIRS = new Set([ '.git', 'node_modules', 'vendor' ]) const INCLUDED_EXTENSIONS = new Set([ // This extension whitelist is how we avoid modifying binary files '', '.css', '.html', '.js', '.json', '.md', '.scss', '.txt', '.yml' ]) replaceRecursively('.', EXCLUDED_DIRS, INCLUDED_EXTENSIONS, oldVersion, newVersion) } main(process.argv.slice(2))
JavaScript
0.000042
@@ -2379,24 +2379,41 @@ '.git',%0A + '_gh_pages',%0A 'node_mo
e115c1fa950a9b145ef3bac12f7a67c65e86a984
Remove jquery and rails-ujs requires from backend.js
backend/app/assets/javascripts/spree/backend.js
backend/app/assets/javascripts/spree/backend.js
//= require solidus_admin/bind-polyfill //= require handlebars //= require jquery //= require rails-ujs //= require jquery.sticky-kit.min //= require solidus_admin/select2 //= require solidus_admin/underscore //= require solidus_admin/backbone //= require solidus_admin/backbone-nested-models //= require solidus_admin/popover //= require solidus_admin/bootstrap //= require solidus_admin/flatpickr/flatpickr //= require prism //= require spree //= require spree/backend/namespaces //= require spree/backend/translation //= require spree/backend/backbone-overrides //= require spree/backend/format_money // //= require spree/backend/templates //= require spree/backend/models //= require spree/backend/collections //= require spree/backend/views // //= require spree/backend/addresses //= require spree/backend/adjustments //= require spree/backend/admin //= require spree/backend/calculator //= require spree/backend/checkouts/edit //= require spree/backend/components/number_with_currency //= require spree/backend/components/tabs //= require spree/backend/components/tooltips //= require spree/backend/components/editable_table //= require spree/backend/components/sortable_table //= require spree/backend/datepicker //= require spree/backend/flash //= require spree/backend/gateway //= require spree/backend/handlebars_extensions //= require spree/backend/images/index //= require spree/backend/images/upload //= require spree/backend/locale_selection //= require spree/backend/navigation //= require spree/backend/option_type_autocomplete //= require spree/backend/option_value_picker //= require spree/backend/orders //= require spree/backend/payments/edit //= require spree/backend/payments/new //= require spree/backend/product_picker //= require spree/backend/progress //= require spree/backend/promotions //= require spree/backend/promotions/activation //= require spree/backend/returns/return_item_selection //= require spree/backend/routes //= require spree/backend/shipments //= require spree/backend/spree-select2 //= require spree/backend/stock_management //= require spree/backend/store_credits //= require spree/backend/style_guide //= require spree/backend/taxon_autocomplete //= require spree/backend/taxonomy //= require spree/backend/taxons //= require spree/backend/user_picker //= require spree/backend/variant_autocomplete //= require spree/backend/zone
JavaScript
0.000034
@@ -60,49 +60,8 @@ ars%0A -//= require jquery%0A//= require rails-ujs%0A //=
caf91e7932a1892febe6d778b06fdb5860b0b914
Add back import that isn't strictly required
packages/ddp-client/client/client.js
packages/ddp-client/client/client.js
export { DDP, LivedataTest } from '../common/namespace'; if (false) { import './stream_client_sockjs'; } // Initialize the default server connection and put it on Meteor.connection import './client_convenience';
JavaScript
0
@@ -102,16 +102,57 @@ js';%0A%7D%0A%0A +import '../common/livedata_connection';%0A%0A // Initi
d9927217d414d9b615a20020a79fed65de95d149
Update demo
demo/javascripts/application.js
demo/javascripts/application.js
$(document).ready(function() { $('#slides').superslides({ slide_easing: 'easeInOutCubic', slide_speed: 800, pagination: true }); });
JavaScript
0.000001
@@ -126,16 +126,38 @@ ination: + true,%0A hashchange: true%0A
d44367961f763e009497a928143d594b04f01d39
Add error reporting to all calls.
examples/example.js
examples/example.js
/* * This file is part of noddycouch released under the MIT license. * See the NOTICE for more information. */ var sys = require("sys"), fs = require("fs"), couchdb =require("../couchdb"); s = new couchdb.Server() s.info({ success: function(b) { sys.puts("server info:" + b.version) } }); s.uuids({ success: function(b) { sys.puts("uuid:" + b.uuids[0]) } }); s.all_dbs({ success: function(b) { sys.puts("all_dbs:" + b) } }); s.create_db("testdb") var db = new couchdb.Database("http://127.0.0.1:5984/testdb"); db.info({ responseEncoding: "binary", success: function(b) { sys.puts("db info:" + b) } }); db.saveDoc({}, { success: function(doc) { sys.puts("empty doc saved:" + doc.id); }, error: function(error) { sys.puts("error:" + error) } }); var doc = { "test": "essai" } db.saveDoc(doc, { success: function(doc) { sys.puts("doc saved: (" + doc.id + "," + doc.rev +")"); db.openDoc(doc.id, { success: function(doc1) { sys.puts("test = " + doc1.test); sys.puts("rev: " + doc.rev + " == " + doc1._rev); } }) } }); db.allDocs({ success: function(docs) { sys.puts("all docs total rows:" + docs.total_rows ) } }) db.saveDoc({}, { success: function(res) { var res = res; sys.puts("doc saved: (" + res.id + "," + res.rev +")"); var docid = res.id; db.putAttachment(res.id, "test content", "test", { success: function(res1) { db.fetchAttachment(docid, "test", { success: function(content) { sys.puts("fetched attachment :" + content) } }); } }); } }); db.saveDoc({}, { success: function(res) { var res = res; sys.puts("notice doc saved: (" + res.id + "," + res.rev +")"); var docid = res.id; db.fputAttachment(res.id, "./NOTICE", "NOTICE", { success: function(res1) { db.fetchAttachment(docid, "NOTICE", { success: function(content) { sys.puts("fetched NOTICE :" + content) } }); } }); } });
JavaScript
0
@@ -194,25 +194,129 @@ chdb%22);%0A - %0A +%0Afunction reportError(label) %7B%0A return function(error) %7B%0A sys.puts(%22ERROR: %22 + label + %22: %22 + error);%0A %7D%0A%7D%0A%0A %0As = new @@ -409,24 +409,61 @@ version)%0A %7D +,%0A error: reportError(%22server info%22) %0A%7D);%0A%0As.uuid @@ -525,24 +525,55 @@ uids%5B0%5D)%0A %7D +,%0A error: reportError(%22uuids%22) %0A%7D);%0A%0As.all_ @@ -631,24 +631,57 @@ s:%22 + b)%0A %7D +,%0A error: reportError(%22all_dbs%22) %0A%7D);%0A%0As.crea @@ -854,24 +854,58 @@ o:%22 + b)%0A %7D +,%0A error: reportError(%22db info%22)%0A %0A%7D);%0A%0A%0Adb.sa @@ -1009,60 +1009,39 @@ or: -function(error) %7B%0A sys.puts(%22error:%22 + error)%0A %7D +reportError(%22saving empty doc%22) %0A %0A @@ -1350,24 +1350,111 @@ %7D -%0A %7D)%0A %0A %7D +,%0A error: reportError(%22opening test doc%22)%0A %7D)%0A %0A %7D,%0A error: reportError(%22saving test doc%22) %0A%7D); @@ -1565,16 +1565,61 @@ %0A %7D +,%0A error: reportError(%22retrieving all docs%22) %0A%7D)%0A%0A%0Adb @@ -1979,17 +1979,16 @@ tachment - :%22 + con @@ -2008,40 +2008,228 @@ %7D -%0A %7D);%0A %7D%0A %7D);%0A %7D +,%0A error: reportError(%22fetching hardcoded attachment%22)%0A %7D);%0A %7D,%0A error: reportError(%22putting hardcoded attachment%22)%0A %7D);%0A %7D,%0A error: reportError(%22saving empty doc for hardcoded attachment%22) %0A%7D); @@ -2235,32 +2235,47 @@ ;%0A%0A%0Adb.saveDoc(%7B +%22for%22: %22NOTICE%22 %7D, %7B%0A success: @@ -2327,14 +2327,14 @@ ts(%22 -notice +NOTICE doc @@ -2484,32 +2484,74 @@ unction(res1) %7B%0A + sys.puts(%22NOTICE file attached%22);%0A db.fetch @@ -2685,40 +2685,214 @@ %7D -%0A %7D);%0A %7D%0A %7D);%0A %7D +,%0A error: reportError(%22fetching file attachment%22)%0A %7D);%0A %7D,%0A error: reportError(%22putting file attachment%22)%0A %7D);%0A %7D,%0A error: reportError(%22saving empty doc for file attachment%22) %0A%7D); +%0A
6fe13a87ba349ccbfc091f57ee9c20225671219c
Fix sending test metadata
packages/ddp-server/stream_server.js
packages/ddp-server/stream_server.js
// By default, we use the permessage-deflate extension with default // configuration. If $SERVER_WEBSOCKET_COMPRESSION is set, then it must be valid // JSON. If it represents a falsey value, then we do not use permessage-deflate // at all; otherwise, the JSON value is used as an argument to deflate's // configure method; see // https://github.com/faye/permessage-deflate-node/blob/master/README.md // // (We do this in an _.once instead of at startup, because we don't want to // crash the tool during isopacket load if your JSON doesn't parse. This is only // a problem because the tool has to load the DDP server code just in order to // be a DDP client; see https://github.com/meteor/meteor/issues/3452 .) var websocketExtensions = _.once(function () { var extensions = []; var websocketCompressionConfig = process.env.SERVER_WEBSOCKET_COMPRESSION ? JSON.parse(process.env.SERVER_WEBSOCKET_COMPRESSION) : {}; if (websocketCompressionConfig) { extensions.push(Npm.require('permessage-deflate').configure( websocketCompressionConfig )); } return extensions; }); var pathPrefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ""; StreamServer = function () { var self = this; self.registration_callbacks = []; self.open_sockets = []; // Because we are installing directly onto WebApp.httpServer instead of using // WebApp.app, we have to process the path prefix ourselves. self.prefix = pathPrefix + '/sockjs'; RoutePolicy.declare(self.prefix + '/', 'network'); // set up sockjs var sockjs = Npm.require('sockjs'); var serverOptions = { prefix: self.prefix, log: function() {}, // this is the default, but we code it explicitly because we depend // on it in stream_client:HEARTBEAT_TIMEOUT heartbeat_delay: 45000, // The default disconnect_delay is 5 seconds, but if the server ends up CPU // bound for that much time, SockJS might not notice that the user has // reconnected because the timer (of disconnect_delay ms) can fire before // SockJS processes the new connection. Eventually we'll fix this by not // combining CPU-heavy processing with SockJS termination (eg a proxy which // converts to Unix sockets) but for now, raise the delay. disconnect_delay: 60 * 1000, // Set the USE_JSESSIONID environment variable to enable setting the // JSESSIONID cookie. This is useful for setting up proxies with // session affinity. jsessionid: !!process.env.USE_JSESSIONID }; // If you know your server environment (eg, proxies) will prevent websockets // from ever working, set $DISABLE_WEBSOCKETS and SockJS clients (ie, // browsers) will not waste time attempting to use them. // (Your server will still have a /websocket endpoint.) if (process.env.DISABLE_WEBSOCKETS) { serverOptions.websocket = false; } else { serverOptions.faye_server_options = { extensions: websocketExtensions() }; } self.server = sockjs.createServer(serverOptions); // Install the sockjs handlers, but we want to keep around our own particular // request handler that adjusts idle timeouts while we have an outstanding // request. This compensates for the fact that sockjs removes all listeners // for "request" to add its own. WebApp.httpServer.removeListener( 'request', WebApp._timeoutAdjustmentRequestCallback); self.server.installHandlers(WebApp.httpServer); WebApp.httpServer.addListener( 'request', WebApp._timeoutAdjustmentRequestCallback); // Support the /websocket endpoint self._redirectWebsocketEndpoint(); self.server.on('connection', function (socket) { // sockjs sometimes passes us null instead of a socket object // so we need to guard against that. see: // https://github.com/sockjs/sockjs-node/issues/121 // https://github.com/meteor/meteor/issues/10468 if (!socket) return; // We want to make sure that if a client connects to us and does the initial // Websocket handshake but never gets to the DDP handshake, that we // eventually kill the socket. Once the DDP handshake happens, DDP // heartbeating will work. And before the Websocket handshake, the timeouts // we set at the server level in webapp_server.js will work. But // faye-websocket calls setTimeout(0) on any socket it takes over, so there // is an "in between" state where this doesn't happen. We work around this // by explicitly setting the socket timeout to a relatively large time here, // and setting it back to zero when we set up the heartbeat in // livedata_server.js. socket.setWebsocketTimeout = function (timeout) { if ((socket.protocol === 'websocket' || socket.protocol === 'websocket-raw') && socket._session.recv) { socket._session.recv.connection.setTimeout(timeout); } }; socket.setWebsocketTimeout(45 * 1000); socket.send = function (data) { socket.write(data); }; socket.on('close', function () { self.open_sockets = _.without(self.open_sockets, socket); }); self.open_sockets.push(socket); // only to send a message after connection on tests, useful for // socket-stream-client/server-tests.js if (process.env.TEST_METADATA) { socket.send(JSON.stringify({ testMessageOnConnect: true })); } // call all our callbacks when we get a new socket. they will do the // work of setting up handlers and such for specific messages. _.each(self.registration_callbacks, function (callback) { callback(socket); }); }); }; Object.assign(StreamServer.prototype, { // call my callback when a new socket connects. // also call it for all current connections. register: function (callback) { var self = this; self.registration_callbacks.push(callback); _.each(self.all_sockets(), function (socket) { callback(socket); }); }, // get a list of all sockets all_sockets: function () { var self = this; return _.values(self.open_sockets); }, // Redirect /websocket to /sockjs/websocket in order to not expose // sockjs to clients that want to use raw websockets _redirectWebsocketEndpoint: function() { var self = this; // Unfortunately we can't use a connect middleware here since // sockjs installs itself prior to all existing listeners // (meaning prior to any connect middlewares) so we need to take // an approach similar to overshadowListeners in // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee ['request', 'upgrade'].forEach((event) => { var httpServer = WebApp.httpServer; var oldHttpServerListeners = httpServer.listeners(event).slice(0); httpServer.removeAllListeners(event); // request and upgrade have different arguments passed but // we only care about the first one which is always request var newListener = function(request /*, moreArguments */) { // Store arguments for use within the closure below var args = arguments; // TODO replace with url package var url = Npm.require('url'); // Rewrite /websocket and /websocket/ urls to /sockjs/websocket while // preserving query string. var parsedUrl = url.parse(request.url); if (parsedUrl.pathname === pathPrefix + '/websocket' || parsedUrl.pathname === pathPrefix + '/websocket/') { parsedUrl.pathname = self.prefix + '/websocket'; request.url = url.format(parsedUrl); } _.each(oldHttpServerListeners, function(oldListener) { oldListener.apply(httpServer, args); }); }; httpServer.addListener(event, newListener); }); } });
JavaScript
0
@@ -5253,16 +5253,54 @@ METADATA + && process.env.TEST_METADATA !== %22%7B%7D%22 ) %7B%0A
43d316347f41775fe145637672e1e14c4e5e2cb9
allow db connection to be configured by environment (overwriting config.test.json)
model/db.js
model/db.js
"use strict"; const { Pool } = require("pg"); var config = require("../config.js"); var should = require("should"); var sqldebug = require("debug")("OSMBC:model:sql"); const pgConfigValues = config.getValue("postgres", { mustexist: true }); const logTime = config.getValue("postgresLogStatements", { default: 1000 }); should.exist(pgConfigValues.username); should.exist(pgConfigValues.database); should.exist(pgConfigValues.password); should.exist(pgConfigValues.server); should.exist(pgConfigValues.port); var logger = require("../config.js").logger; if (pgConfigValues.connectstr && pgConfigValues.connectStr !== "") { logger.error("Database connectstr is deprecated, please remove from config"); process.exit(1); } // create a config to configure both pooling behavior // and client options // note: all config is optional and the environment variables // will be read if the config is not present var pgConfig = { user: pgConfigValues.username, database: pgConfigValues.database, password: pgConfigValues.password, host: pgConfigValues.server, port: pgConfigValues.port, max: 10, connectionTimeoutMillis: 1000, idleTimeoutMillis: 1000 }; // this initializes a connection pool // it will keep idle connections open for 30 seconds // and set a limit of maximum 10 idle clients let pool = null; function getPool() { if (pool) return pool; pool = new Pool(pgConfig); pool.on("error", function(err, client) { console.error("There is an error in PG Pool / Problem with database"); console.error(err); console.error("-------- client ----------------------"); console.error(client); process.exit(1); }); return pool; } let deep = 0; // export the query method for passing queries to the pool module.exports.query = function (text, values, callback) { if (typeof values === "function") { callback = values; values = undefined; } should.exist(callback); should(typeof callback).eql("function"); var startTime = new Date().getTime(); sqldebug("SQL: start %s", text); function handleResult(err, result) { deep = deep - 1; var endTime = new Date().getTime(); if (endTime - startTime > logTime) { logger.info("SQL: >>>>>>>>>> [" + (endTime - startTime) / 1000 + "] \n" + text + "\n"); if (values) logger.info("SQL: VALUES " + JSON.stringify(values)); logger.info("SQL: <<<<<<<<<< (" + deep + ")"); } if (err) { if (err.message.indexOf("connect ECONNREFUSED") >= 0) { err.message = "\nError connecting to PSQL, is database started ? \n" + err.message; } sqldebug("SQL: [" + (endTime - startTime) / 1000 + "]( Result: ERROR)" + text); return callback(err); } sqldebug("SQL: [" + (endTime - startTime) / 1000 + "](" + ((result.rows) ? result.rows.length : 0) + " rows)" + text); return callback(null, result); } deep = deep + 1; if (values === undefined) { getPool().query(text, handleResult); } else { getPool().query(text, values, handleResult); } }; module.exports.getPool = getPool;
JavaScript
0
@@ -1168,16 +1168,355 @@ 000%0A%7D;%0A%0A +// overwrite with environment%0Aif (process.env.POSTGRES_HOST) pgConfig.host = process.env.POSTGRES_HOST;%0Aif (process.env.POSTGRES_USER) pgConfig.user = process.env.POSTGRES_USER;%0Aif (process.env.POSTGRES_PORT) pgConfig.port = process.env.POSTGRES_PORT;%0Aif (process.env.POSTGRES_PASSWORD) pgConfig.password = process.env.POSTGRES_PASSWORD;%0A%0A // this
c9f64ec5fc2b0c7cd21781d519a8ed08c0c46f32
Update plugin.js
base/static/ckeditor/plugins/pbckcode/plugin.js
base/static/ckeditor/plugins/pbckcode/plugin.js
// needed js files var js = { ace : "ace.js", aceExtWhitespace : "ext-whitespace.js", pbSyntaxHighlighter : CKEDITOR.plugins.getPath('pbckcode') + "dialogs/PBSyntaxHighlighter.js" }; var commandName = 'pbckcode'; /** * Plugin definition */ CKEDITOR.plugins.add('pbckcode', { icons : 'pbckcode', lang : ['fr', 'en'], init : function (editor) { var plugin = this; // if there is no user settings // create an empty object if (editor.config.pbckcode === undefined) { editor.config.pbckcode = {}; } // default settings object var DEFAULT_SETTINGS = { cls : '', modes : [ ['HTML', 'html'], ['CSS', 'css'], ['PHP', 'php'], ['JS', 'javascript'] ], theme : 'textmate', tab_size : 4, js : "//cdn.jsdelivr.net//ace/1.1.4/noconflict///" }; // merge user settings with default settings editor.settings = CKEDITOR.tools.extend(DEFAULT_SETTINGS, editor.config.pbckcode, true); editor.settings.js = normalizeJsUrl(editor.settings.js); // load CSS for the dialog editor.on('instanceReady', function () { CKEDITOR.document.appendStyleSheet(plugin.path + "dialogs/style.css"); }); // add the button in the toolbar editor.ui.addButton('pbckcode', { label : editor.lang.pbckcode.addCode, command : commandName, toolbar : 'pbckcode' }); // link the button to the command editor.addCommand(commandName, new CKEDITOR.dialogCommand('pbckcodeDialog', { allowedContent : 'pre[*]{*}(*)' }) ); // disable the button while the required js files are not loaded editor.getCommand(commandName).disable(); // add the plugin dialog element to the plugin CKEDITOR.dialog.add('pbckcodeDialog', plugin.path + 'dialogs/pbckcode.js'); // add the context menu if (editor.contextMenu) { editor.addMenuGroup('pbckcodeGroup'); editor.addMenuItem('pbckcodeItem', { label : editor.lang.pbckcode.editCode, icon : plugin.path + "icons/pbckcode.png", command : commandName, group : 'pbckcodeGroup' }); editor.contextMenu.addListener(function (element) { if (element.getAscendant('pre', true)) { return {pbckcodeItem : CKEDITOR.TRISTATE_OFF}; } }); } var scripts = [ getScriptUrl(editor.settings.js, js.ace), js.pbSyntaxHighlighter ]; // Load the required js files // enable the button when loaded CKEDITOR.scriptLoader.load(scripts, function () { editor.getCommand(commandName).enable(); // need ace to be loaded CKEDITOR.scriptLoader.load([ getScriptUrl(editor.settings.js, js.aceExtWhitespace) ]); }); } }); function normalizeJsUrl(js) { return js.concat("/") .replace(new RegExp('([^:]\/)\/+', 'g'), '$1'); } function getScriptUrl(prefix, scriptName) { return prefix + scriptName; }
JavaScript
0.000001
@@ -952,49 +952,29 @@ : %22/ -/cdn.jsdelivr.net//ace/1.1.4/noconflict// +static/js/ace/src-min /%22%0A @@ -1134,32 +1134,34 @@ true);%0A +// editor.settings.
64e58d5ec230a379483719657773f899af49e802
Add max zip compression
scripts/bower-version.js
scripts/bower-version.js
var path = require('path'); var fs = require('fs'); var JSZip = require('jszip'); var glob = require('glob'); var zip = new JSZip(); var root = path.join(__dirname, '..'); var build = path.join(root, 'build'); var bowerJson = require(path.join(root, 'bower.json')); var npmJson = require(path.join(root, 'package.json')); bowerJson.version = npmJson.version; zip.file('bower.json', JSON.stringify(bowerJson, null, 2)); glob.sync('*', {nodir: true, cwd: build}).forEach(function (file) { zip.file(file, fs.readFileSync(path.join(build, file), 'utf-8')); }); fs.writeFileSync(path.join(root, 'build.zip'), zip.generate({type: 'nodebuffer'}));
JavaScript
0.000001
@@ -641,13 +641,69 @@ ebuffer' +, compression: 'DEFLATE', compressionOptions: %7Blevel: 9%7D %7D));%0A
97d20d349e12b03ccfa6077b99a1d0c7b041a3d8
Make options an optional argument to Ember.Handlebars.getPath
packages/ember-handlebars/lib/ext.js
packages/ember-handlebars/lib/ext.js
// ========================================================================== // Project: Ember Handlebar Views // Copyright: ©2011 Strobe Inc. and contributors. // License: Licensed under MIT license (see license.js) // ========================================================================== /*globals Handlebars */ require("ember-views/system/render_buffer"); /** @namespace @name Handlebars @private */ /** @namespace @name Handlebars.helpers @description Helpers for Handlebars templates */ /** @class Prepares the Handlebars templating library for use inside Ember's view system. The Ember.Handlebars object is the standard Handlebars library, extended to use Ember's get() method instead of direct property access, which allows computed properties to be used inside templates. To use Ember.Handlebars, call Ember.Handlebars.compile(). This will return a function that you can call multiple times, with a context object as the first parameter: var template = Ember.Handlebars.compile("my {{cool}} template"); var result = template({ cool: "awesome" }); console.log(result); // prints "my awesome template" Note that you won't usually need to use Ember.Handlebars yourself. Instead, use Ember.View, which takes care of integration into the view layer for you. */ Ember.Handlebars = Ember.create(Handlebars); Ember.Handlebars.helpers = Ember.create(Handlebars.helpers); /** Override the the opcode compiler and JavaScript compiler for Handlebars. */ Ember.Handlebars.Compiler = function() {}; Ember.Handlebars.Compiler.prototype = Ember.create(Handlebars.Compiler.prototype); Ember.Handlebars.Compiler.prototype.compiler = Ember.Handlebars.Compiler; Ember.Handlebars.JavaScriptCompiler = function() {}; Ember.Handlebars.JavaScriptCompiler.prototype = Ember.create(Handlebars.JavaScriptCompiler.prototype); Ember.Handlebars.JavaScriptCompiler.prototype.compiler = Ember.Handlebars.JavaScriptCompiler; Ember.Handlebars.JavaScriptCompiler.prototype.namespace = "Ember.Handlebars"; Ember.Handlebars.JavaScriptCompiler.prototype.initializeBuffer = function() { return "''"; }; /** Override the default buffer for Ember Handlebars. By default, Handlebars creates an empty String at the beginning of each invocation and appends to it. Ember's Handlebars overrides this to append to a single shared buffer. @private */ Ember.Handlebars.JavaScriptCompiler.prototype.appendToBuffer = function(string) { return "data.buffer.push("+string+");"; }; /** Rewrite simple mustaches from {{foo}} to {{bind "foo"}}. This means that all simple mustaches in Ember's Handlebars will also set up an observer to keep the DOM up to date when the underlying property changes. @private */ Ember.Handlebars.Compiler.prototype.mustache = function(mustache) { if (mustache.params.length || mustache.hash) { return Handlebars.Compiler.prototype.mustache.call(this, mustache); } else { var id = new Handlebars.AST.IdNode(['_triageMustache']); // Update the mustache node to include a hash value indicating whether the original node // was escaped. This will allow us to properly escape values when the underlying value // changes and we need to re-render the value. if(mustache.escaped) { mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]); mustache.hash.pairs.push(["escaped", new Handlebars.AST.StringNode("true")]); } mustache = new Handlebars.AST.MustacheNode([id].concat([mustache.id]), mustache.hash, !mustache.escaped); return Handlebars.Compiler.prototype.mustache.call(this, mustache); } }; /** Used for precompilation of Ember Handlebars templates. This will not be used during normal app execution. @param {String} string The template to precompile */ Ember.Handlebars.precompile = function(string) { var ast = Handlebars.parse(string); var options = { data: true, stringParams: true }; var environment = new Ember.Handlebars.Compiler().compile(ast, options); return new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); }; /** The entry point for Ember Handlebars. This replaces the default Handlebars.compile and turns on template-local data and String parameters. @param {String} string The template to compile */ Ember.Handlebars.compile = function(string) { var ast = Handlebars.parse(string); var options = { data: true, stringParams: true }; var environment = new Ember.Handlebars.Compiler().compile(ast, options); var templateSpec = new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); return Handlebars.template(templateSpec); }; /** If a path starts with a reserved keyword, returns the root that should be used. @private */ var normalizePath = Ember.Handlebars.normalizePath = function(root, path, data) { var keywords = (data && data.keywords) || {}, keyword, isKeyword; // Get the first segment of the path. For example, if the // path is "foo.bar.baz", returns "foo". keyword = path.split('.', 1)[0]; // Test to see if the first path is a keyword that has been // passed along in the view's data hash. If so, we will treat // that object as the new root. if (keywords.hasOwnProperty(keyword)) { // Look up the value in the template's data hash. root = keywords[keyword]; isKeyword = true; // Handle cases where the entire path is the reserved // word. In that case, return the object itself. if (path === keyword) { path = ''; } else { // Strip the keyword from the path and look up // the remainder from the newly found root. path = path.substr(keyword.length); } } return { root: root, path: path, isKeyword: isKeyword }; }; /** Lookup both on root and on window. If the path starts with a keyword, the corresponding object will be looked up in the template's data hash and used to resolve the path. @param {Object} root The object to look up the property on @param {String} path The path to be lookedup @param {Object} options The template's option hash */ Ember.Handlebars.getPath = function(root, path, options) { var data = options.data, normalizedPath = normalizePath(root, path, data), value; // In cases where the path begins with a keyword, change the // root to the value represented by that keyword, and ensure // the path is relative to it. root = normalizedPath.root; path = normalizedPath.path; // TODO: Remove this `false` when the `getPath` globals support is removed value = Ember.getPath(root, path, false); if (value === undefined && root !== window && Ember.isGlobalPath(path)) { value = Ember.getPath(window, path); } return value; }; /** Registers a helper in Handlebars that will be called if no property with the given name can be found on the current context object, and no helper with that name is registered. This throws an exception with a more helpful error message so the user can track down where the problem is happening. @name Handlebars.helpers.helperMissing @param {String} path @param {Hash} options */ Ember.Handlebars.registerHelper('helperMissing', function(path, options) { var error, view = ""; error = "%@ Handlebars error: Could not find property '%@' on object %@."; if (options.data){ view = options.data.view; } throw new Ember.Error(Ember.String.fmt(error, [view, path, this])); });
JavaScript
0.000173
@@ -6220,16 +6220,27 @@ r data = + options && options
f96503cba3066c802927f26296cf40ab3e4b5fe9
declare data variable
hinclude.js
hinclude.js
/* hinclude.js -- HTML Includes (version 0.9) Copyright (c) 2005-2011 Mark Nottingham <mnot@mnot.net> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ See http://www.mnot.net/javascript/hinclude/ for documentation. TODO: - check navigator property to see if browser will handle this without javascript ------------------------------------------------------------------------------ */ var hinclude = { set_content_async: function (element, req) { if (req.readyState == 4) { if (req.status == 200 | req.status == 304) { element.innerHTML = req.responseText; } element.className = "include_" + req.status; } }, buffer: new Array(), set_content_buffered: function (element, req) { if (req.readyState == 4) { hinclude.buffer.push(new Array(element, req)); hinclude.outstanding--; if (hinclude.outstanding == 0) { hinclude.show_buffered_content(); } } }, show_buffered_content: function () { while (hinclude.buffer.length > 0) { var include = hinclude.buffer.pop(); if (include[1].status == 200 | include[1].status == 304) { include[0].innerHTML = include[1].responseText; } include[0].className = "include_" + include[1].status; } }, outstanding: 0, run: function () { var mode = this.get_meta("include_mode", "buffered"); var callback = function(element, req) {}; var includes = document.getElementsByTagName("hx:include"); if (includes.length == 0) { // remove ns for IE includes = document.getElementsByTagName("include"); } if (mode == "async") { callback = this.set_content_async; } else if (mode == "buffered") { callback = this.set_content_buffered; var timeout = this.get_meta("include_timeout", 2.5) * 1000; setTimeout("hinclude.show_buffered_content()", timeout); } for (var i=0; i < includes.length; i++) { this.include(includes[i], includes[i].getAttribute("src"), callback); } }, include: function (element, url, incl_cb) { var scheme = url.substring(0,url.indexOf(":")); if (scheme.toLowerCase() == "data") { // just text/plain for now data = unescape(url.substring(url.indexOf(",") + 1, url.length)); element.innerHTML = data; } else { var req = false; if(window.XMLHttpRequest) { try { req = new XMLHttpRequest(); } catch(e) { req = false; } } else if (window.ActiveXObject) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; } } if (req) { this.outstanding++; req.onreadystatechange = function() { incl_cb(element, req); }; try { req.open("GET", url, true); req.send(""); } catch (e) { this.outstanding--; alert("Include error: " + url + " (" + e + ")"); } } } }, get_meta: function (name, value_default) { var metas = document.getElementsByTagName("meta"); for (var m=0; m < metas.length; m++) { var meta_name = metas[m].getAttribute("name"); if (meta_name == name) { return metas[m].getAttribute("content"); } } return value_default; }, /* * (c)2006 Dean Edwards/Matthias Miller/John Resig * Special thanks to Dan Webb's domready.js Prototype extension * and Simon Willison's addLoadEvent * * For more info, see: * http://dean.edwards.name/weblog/2006/06/again/ * * Thrown together by Jesse Skinner (http://www.thefutureoftheweb.com/) * * * To use: call addDOMLoadEvent one or more times with functions, ie: * * function something() { * // do something * } * addDOMLoadEvent(something); * * addDOMLoadEvent(function() { * // do other stuff * }); */ addDOMLoadEvent: function(func) { if (!window.__load_events) { var init = function () { // quit if this function has already been called if (arguments.callee.done) return; // flag this function so we don't do the same thing twice arguments.callee.done = true; // kill the timer if (window.__load_timer) { clearInterval(window.__load_timer); window.__load_timer = null; } // execute each function in the stack in the order they were added for (var i=0;i < window.__load_events.length;i++) { window.__load_events[i](); } window.__load_events = null; // clean up the __ie_onload event /*@cc_on @*/ /*@if (@_win32) document.getElementById("__ie_onload").onreadystatechange = ""; /*@end @*/ }; // for Mozilla/Opera9 if (document.addEventListener) { document.addEventListener("DOMContentLoaded", init, false); } // for Internet Explorer /*@cc_on @*/ /*@if (@_win32) document.write( "<scr" + "ipt id=__ie_onload defer src=javascript:void(0)><\/scr" + "ipt>" ); var script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") { init(); // call the onload handler } }; /*@end @*/ // for Safari if (/WebKit/i.test(navigator.userAgent)) { // sniff window.__load_timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) { init(); // call the onload handler } }, 10); } // for other browsers window.onload = init; // create event function stack window.__load_events = []; } // add function to event stack window.__load_events.push(func); } }; hinclude.addDOMLoadEvent(function() { hinclude.run(); });
JavaScript
0.000456
@@ -3231,16 +3231,20 @@ w%0A +var data = u
718c0e810c98fd5fb8de40c70724563fac6cd670
Solve the 1st and 2nd sub-issue of the 6th koan
koans/AboutArrays.js
koans/AboutArrays.js
describe("About Arrays", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should create arrays", function() { var emptyArray = []; expect(typeof(emptyArray)).toBe(FILL_ME_IN); //A mistake? - http://javascript.crockford.com/remedial.html expect(emptyArray.length).toBe(FILL_ME_IN); var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]]; expect(multiTypeArray[0]).toBe(FILL_ME_IN); expect(multiTypeArray[2]).toBe(FILL_ME_IN); expect(multiTypeArray[3]()).toBe(FILL_ME_IN); expect(multiTypeArray[4].value1).toBe(FILL_ME_IN); expect(multiTypeArray[4]["value2"]).toBe(FILL_ME_IN); expect(multiTypeArray[5][0]).toBe(FILL_ME_IN); }); it("should understand array literals", function () { var array = []; expect(array).toEqual([]); array[0] = 1; expect(array).toEqual([1]); array[1] = 2; expect(array).toEqual([1, FILL_ME_IN]); array.push(3); expect(array).toEqual(FILL_ME_IN); }); it("should understand array length", function () { var fourNumberArray = [1, 2, 3, 4]; expect(fourNumberArray.length).toBe(FILL_ME_IN); fourNumberArray.push(5, 6); expect(fourNumberArray.length).toBe(FILL_ME_IN); var tenEmptyElementArray = new Array(10); expect(tenEmptyElementArray.length).toBe(FILL_ME_IN); tenEmptyElementArray.length = 5; expect(tenEmptyElementArray.length).toBe(FILL_ME_IN); }); it("should slice arrays", function () { var array = ["peanut", "butter", "and", "jelly"]; expect(array.slice(0, 1)).toEqual(FILL_ME_IN); expect(array.slice(0, 2)).toEqual(FILL_ME_IN); expect(array.slice(2, 2)).toEqual(FILL_ME_IN); expect(array.slice(2, 20)).toEqual(FILL_ME_IN); expect(array.slice(3, 0)).toEqual(FILL_ME_IN); expect(array.slice(3, 100)).toEqual(FILL_ME_IN); expect(array.slice(5, 1)).toEqual(FILL_ME_IN); }); it("should know array references", function () { var array = [ "zero", "one", "two", "three", "four", "five" ]; function passedByReference(refArray) { refArray[1] = "changed in function"; } passedByReference(array); expect(array[1]).toBe(FILL_ME_IN); var assignedArray = array; assignedArray[5] = "changed in assignedArray"; expect(array[5]).toBe(FILL_ME_IN); var copyOfArray = array.slice(); copyOfArray[3] = "changed in copyOfArray"; expect(array[3]).toBe(FILL_ME_IN); }); it("should push and pop", function () { var array = [1, 2]; array.push(3); expect(array).toEqual(FILL_ME_IN); var poppedValue = array.pop(); expect(poppedValue).toBe(FILL_ME_IN); expect(array).toEqual(FILL_ME_IN); }); it("should know about shifting arrays", function () { var array = [1, 2]; array.unshift(3); expect(array).toEqual(FILL_ME_IN); var shiftedValue = array.shift(); expect(shiftedValue).toEqual(FILL_ME_IN); expect(array).toEqual(FILL_ME_IN); }); });
JavaScript
0.998855
@@ -209,26 +209,24 @@ )).toBe( -FILL_ME_IN +'object' ); //A m @@ -312,34 +312,25 @@ ength).toBe( -FILL_ME_IN +0 );%0A%0A var @@ -451,34 +451,25 @@ ay%5B0%5D).toBe( -FILL_ME_IN +0 );%0A expec
a2d0bd210bafcb49c3894c33d90462a12e7b46ae
correct typo in error message and include path
modified.js
modified.js
var _ = require('lodash-node/modern'); module.exports = function lastModifiedPlugin(schema, options) { /* jshint eqnull:true */ options = _.merge({ optionKey: 'modified', date: { path: 'modified.date', options: {} }, by: { path: 'modified.by', ref: undefined, options: {} } }, options || {}); var paths = Object.keys(schema.paths).filter(function (path) { var schemaType = schema.path(path); return schemaType.options && schemaType.options[options.optionKey]; }); // If no fields are flagged with the optionKey, monitor all fields if (paths.length === 0) { paths.push(undefined); } schema.path(options.date.path, _.defaults({ type: Date }, options.date.options)); if (options.by.path) { if (options.by.options.required === true) { options.by.options.required = function requiredCheck(val) { return !this.isNew && this.isModified(options.date.path); }; } schema.path(options.by.path, _.defaults( options.by.ref ? {type: schema.constructor.Types.ObjectId, ref: options.by.ref} : {type: String}, options.by.options) ); } schema.pre('validate', function lastModifiedSave(next) { // check if at least one indicated field has been modified if (!this.isNew && paths.some(this.isModified, this)) { if (options.by.options.required && !this.isModified(options.by.path)) { this.invalidate(options.by.path, 'must be updated with document modifcation'); } else { this.set(options.date.path, Date.now()); } } return next(); }); };
JavaScript
0.000003
@@ -1469,16 +1469,23 @@ .path, ' +%7BPATH%7D must be @@ -1492,20 +1492,19 @@ updated -with +for documen @@ -1510,16 +1510,17 @@ nt modif +i cation')
df1a8e981737a7d1fc5799469e061c0ea8718f8a
Fix legacy getInputValue behaviour
imports/modules/get-input-value.js
imports/modules/get-input-value.js
import ReactDOM from 'react-dom'; export const getInputValue = (component) => { let el = ReactDOM.findDOMNode(component); if (el.tagName == "input") return el.value; else return el.getElementsByTagName("input")[0].value; };
JavaScript
0
@@ -134,16 +134,30 @@ .tagName +.toLowerCase() == %22inp
5cb604d88fbb00aad6bd705af0bbcac10b6c2de1
add method for resonding to updates
shared/src/model/api.js
shared/src/model/api.js
import { observable, computed, action } from 'mobx'; import { readonly } from 'core-decorators'; export default class ModelApi { @readonly requestsInProgress = observable.map(); @readonly requestCounts = observable({ read: 0, create: 0, update: 0, delete: 0, modify: 0, }); @observable errors = {}; @computed get isPending() { return this.requestsInProgress.size > 0; } @computed get isDeleted() { return this.requestCounts.delete > 0; } @computed get isPendingInitialFetch() { return this.isPending && !this.hasBeenFetched; } @computed get isFetchInProgress() { return Boolean(this.requestsInProgress.get('read')); } @computed get hasBeenFetched() { return Boolean( this.requestCounts.read > 0 ); } @computed get isFetchedOrFetching() { return Boolean(this.isFetchInProgress || this.hasBeenFetched); } @computed get hasErrors() { return Boolean(Object.keys(this.errors || {}).length); } @action reset() { Object.keys(this.requestCounts).forEach(k => this.requestCounts[k] = 0); } }
JavaScript
0
@@ -674,24 +674,232 @@ read'));%0A %7D +%0A %0A @computed get isWriteInProgress() %7B%0A return Boolean(%0A this.requestsInProgress.get('put') %7C%7C%0A this.requestsInProgress.get('post') %7C%7C%0A this.requestsInProgress.get('patch')%0A );%0A %7D %0A%0A @compute
ecbceeb9ca463626834a44b8bb7807711460065e
Add node shebang to single JS builds (#915)
scripts/build-webpack.js
scripts/build-webpack.js
#!/usr/bin/env node /* eslint-disable */ const webpack = require('webpack'); const path = require('path'); const util = require('util'); const fs = require('fs'); const version = require('../package.json').version; const basedir = path.join(__dirname, '../'); const babelRc = JSON.parse(fs.readFileSync(path.join(basedir, '.babelrc'), 'utf8')); // // Modern build // const compiler = webpack({ // devtool: 'inline-source-map', entry: [path.join(basedir, 'src/cli/index.js')], module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel', }, { test: /\.json$/, loader: 'json', }], }, output: { filename: `yarn-${version}.js`, path: path.join(basedir, 'dist'), }, target: 'node', }); compiler.run((err, stats) => { const {fileDependencies} = stats.compilation; const filenames = fileDependencies.map(x => x.replace(basedir, '')); console.log(util.inspect(filenames, {maxArrayLength: null})); }); // // Legacy build // const compilerLegacy = webpack({ // devtool: 'inline-source-map', entry: [path.join(basedir, 'src/cli/index.js')], module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: babelRc.env['pre-node5'], }, { test: /\.json$/, loader: 'json', }], }, output: { filename: `yarn-legacy-${version}.js`, path: path.join(basedir, 'dist'), }, target: 'node', }); compilerLegacy.run((err, stats) => { // do nothing, but keep here for debugging... });
JavaScript
0
@@ -639,32 +639,141 @@ ',%0A %7D%5D,%0A %7D,%0A + plugins: %5B%0A new webpack.BannerPlugin(%7B%0A banner: %22#!/usr/bin/env node%22,%0A raw: true%0A %7D)%0A %5D,%0A output: %7B%0A @@ -1440,16 +1440,125 @@ %5D,%0A %7D,%0A + plugins: %5B%0A new webpack.BannerPlugin(%7B%0A banner: %22#!/usr/bin/env node%22,%0A raw: true%0A %7D)%0A %5D,%0A output
23c343ffe630d7c071c6581364f0b8329fd2536c
Update temporary list of tainted domains
core/interceptor.js
core/interceptor.js
/** * Interceptor * Belongs to Decentraleyes. * * @author Thomas Rientjes * @since 2016-04-06 * @license MPL 2.0 * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; /** * Interceptor */ var interceptor = {}; /** * Public Methods */ interceptor.handleRequest = function (requestDetails, tabIdentifier, tab) { let validCandidate, tabDomain, targetDetails, targetPath; validCandidate = requestAnalyzer.isValidCandidate(requestDetails, tab); if (!validCandidate) { return { 'cancel': false }; } tabDomain = helpers.extractDomainFromUrl(tab.url, true); if (tabDomain === null) { tabDomain = Address.EXAMPLE; } // Temporary list of undetectable tainted domains. let undetectableTaintedDomains = { '10fastfingers.com': true, 'blog.datawrapper.de': true, 'bundleofholding.com': true, 'cdnjs.com': true, 'dropbox.com': true, 'glowing-bear.org': true, 'minigames.mail.ru': true, 'miniquadtestbench.com': true, 'openweathermap.org': true, 'qwertee.com': true, 'report-uri.io': true, 'scotthelme.co.uk': true, 'securityheaders.io': true, 'stefansundin.github.io': true, 'udacity.com': true, 'yadi.sk': true, 'yourvotematters.co.uk': true }; if (undetectableTaintedDomains[tabDomain] || (/yandex\./).test(tabDomain)) { if (tabDomain !== 'yandex.ru') { return interceptor._handleMissingCandidate(requestDetails.url); } } targetDetails = requestAnalyzer.getLocalTarget(requestDetails); targetPath = targetDetails.path; if (!targetPath) { return interceptor._handleMissingCandidate(requestDetails.url); } if (!files[targetPath]) { return interceptor._handleMissingCandidate(requestDetails.url); } stateManager.requests[requestDetails.requestId] = { tabIdentifier, targetDetails }; return { 'redirectUrl': chrome.extension.getURL(targetPath) }; }; /** * Private Methods */ interceptor._handleMissingCandidate = function (requestUrl) { if (interceptor.blockMissing === true) { return { 'cancel': true }; } let requestUrlSegments = new URL(requestUrl); if (requestUrlSegments.protocol === Address.HTTP) { requestUrlSegments.protocol = Address.HTTPS; requestUrl = requestUrlSegments.toString(); return { 'redirectUrl': requestUrl }; } else { return { 'cancel': false }; } }; interceptor._handleStorageChanged = function (changes) { if (Setting.BLOCK_MISSING in changes) { interceptor.blockMissing = changes.blockMissing.newValue; } }; /** * Initializations */ interceptor.amountInjected = 0; interceptor.blockMissing = false; chrome.storage.local.get([Setting.AMOUNT_INJECTED, Setting.BLOCK_MISSING], function (items) { interceptor.amountInjected = items.amountInjected || 0; interceptor.blockMissing = items.blockMissing || false; }); /** * Event Handlers */ chrome.storage.onChanged.addListener(interceptor._handleStorageChanged);
JavaScript
0
@@ -1229,32 +1229,59 @@ nch.com': true,%0A + 'nhm.ac.uk': true,%0A 'openwea
8bc01267d3ba0467c5ea814fdd90a9221d88fe06
fix robert baratheon for single player games
server/game/cards/characters/01/robertbaratheon.js
server/game/cards/characters/01/robertbaratheon.js
const _ = require('underscore'); const DrawCard = require('../../../drawcard.js'); class RobertBaratheon extends DrawCard { constructor(owner, cardData) { super(owner, cardData); this.registerEvents(['onCardPlayed', 'onCardLeftPlay', 'onCardKneeled', 'onCardStood']); } calculateStrength() { var otherPlayer = this.game.getOtherPlayer(this.controller); var cardsInPlay = []; if(!otherPlayer) { cardsInPlay = this.controller.cardsInPlay; } else { cardsInPlay = this.controller.cardsInPlay.union(otherPlayer.cardsInPlay.value()); } this.strengthModifier = _.reduce(cardsInPlay, (counter, card) => { if(card.getType() !== 'character' || !card.kneeled) { return counter; } return counter + 1; }, 0); } play(player) { super.play(player); this.calculateStrength(); } onCardPlayed(event) { this.calculateStrength(); } onCardLeftPlay(event) { this.calculateStrength(); } onCardKneeled(event, player, card) { if(card.getType() !== 'character') { return; } this.calculateStrength(); } onCardStood(event, player, card) { if(card.getType() !== 'character') { return; } this.calculateStrength(); } } RobertBaratheon.code = '01048'; module.exports = RobertBaratheon;
JavaScript
0
@@ -497,16 +497,24 @@ dsInPlay +.value() ;%0A
4a3e6248659cbd131db134fd5696f98b5cc1ea14
add test for #176
test/unit/io/save.js
test/unit/io/save.js
import {p5} from '../../lib'; import {testDownload} from './test-download'; describe('IO/save', function() { this.timeout(1000 * 5); it('save()', function(done) { testDownload('untitled', 'svg', function(p) { p.save(); }, done); }); it('save(Graphics)', function(done) { testDownload('untitled', 'svg', function(p) { p.save(p._defaultGraphics); }, done); }); it('save(<svg>)', function(done) { testDownload('untitled', 'svg', function(p) { p.save(p._renderer.svg); }, done); }); it('canvas\'s save should still work', function(done) { new p5(function(p) { p.setup = function() { var _saveCanvas = p5.prototype.saveCanvas; p5.prototype.saveCanvas = function() { p5.prototype.saveCanvas = _saveCanvas; done(); }; p.save('canvas-save.png'); }; }); }); });
JavaScript
0.000002
@@ -3,16 +3,24 @@ port %7Bp5 +, assert %7D from ' @@ -136,24 +136,752 @@ 1000 * 5);%0A%0A + // See https://github.com/zenozeng/p5.js-svg/issues/176%0A it('should generate valid svg output', async function() %7B%0A const dataURL = await new Promise((resolve) =%3E %7B%0A new p5((p) =%3E %7B%0A p.setup = function () %7B%0A p.createCanvas(600, 600, p.SVG);%0A p.downloadFile = function(dataURL) %7B%0A resolve(dataURL)%0A %7D%0A %7D%0A%0A p.draw = function() %7B%0A p.rect(0, 0, 100, 100);%0A p.line(30, 20, 85, 75);%0A p.save();%0A p.noLoop();%0A %7D%0A %7D)%0A %7D);%0A assert.equal(dataURL.indexOf('#'), -1);%0A %7D)%0A%0A it('save
125765b7e173fc4a227df96c931bc38bd5fc894d
Add changelings to the character creation section
public/scripts/app/views/CharacterCreateView.js
public/scripts/app/views/CharacterCreateView.js
// Category View // ============= // Includes file dependencies define([ "jquery", "backbone", "text!../templates/character-create-view.html", "text!../templates/werewolf-create-view.html" ], function( $, Backbone, character_create_view_html , werewolf_create_view_html ) { // Extends Backbone.View var View = Backbone.View.extend( { // The View Constructor initialize: function() { _.bindAll(this, "scroll_back_after_page_change"); }, scroll_back_after_page_change: function() { var self = this; $(document).one("pagechange", function() { var top = _.parseInt(self.backToTop); $.mobile.silentScroll(top); }); }, // Renders all of the Category models on the UI render: function() { if ("Werewolf" == this.model.get("type")) { this.template = _.template(werewolf_create_view_html)({ "character": this.model } ); } else { this.template = _.template(character_create_view_html)({ "character": this.model } ); } // Renders the view's template inside of the current listview element this.$el.find("div[role='main']").html(this.template); this.$el.enhanceWithin(); // Maintains chainability return this; } } ); // Returns the View class return View; } );
JavaScript
0
@@ -984,32 +984,221 @@ this.model %7D );%0A + %7D else if (%22ChangelingBetaSlice%22 == this.model.get(%22type%22)) %7B%0A this.template = _.template(changelinge_beta_slice_create_view_html)(%7B %22character%22: this.model %7D );%0A %7D el
46ac947e9b681b494dba5f541a6c47e09582cda0
Refactor auth config checks in another test (#3698)
services/github/github-api-provider.integration.js
services/github/github-api-provider.integration.js
'use strict' const { expect } = require('chai') const serverSecrets = require('../../lib/server-secrets') const GithubApiProvider = require('./github-api-provider') describe('Github API provider', function() { const baseUrl = process.env.GITHUB_URL || 'https://api.github.com' const reserveFraction = 0.333 let token before(function() { token = serverSecrets.gh_token if (!token) { throw Error('The integration tests require a gh_token to be set') } }) let githubApiProvider context('without token pool', function() { before(function() { githubApiProvider = new GithubApiProvider({ baseUrl, withPooling: false, globalToken: token, reserveFraction, }) }) it('should be able to run 10 requests', async function() { this.timeout('20s') for (let i = 0; i < 10; ++i) { await githubApiProvider.requestAsPromise( require('request'), '/repos/rust-lang/rust', {} ) } }) }) context('with token pool', function() { let githubApiProvider before(function() { githubApiProvider = new GithubApiProvider({ baseUrl, withPooling: true, reserveFraction, }) githubApiProvider.addToken(token) }) const headers = [] async function performOneRequest() { const { res } = await githubApiProvider.requestAsPromise( require('request'), '/repos/rust-lang/rust', {} ) expect(res.statusCode).to.equal(200) headers.push(res.headers) } before('should be able to run 10 requests', async function() { this.timeout('20s') for (let i = 0; i < 10; ++i) { await performOneRequest() } }) it('should decrement the limit remaining with each request', function() { for (let i = 1; i < headers.length; ++i) { const current = headers[i] const previous = headers[i - 1] expect(+current['x-ratelimit-remaining']).to.be.lessThan( +previous['x-ratelimit-remaining'] ) } }) it('should update the token with the final limit remaining and reset time', function() { const lastHeaders = headers.slice(-1)[0] const reserve = reserveFraction * +lastHeaders['x-ratelimit-limit'] const usesRemaining = +lastHeaders['x-ratelimit-remaining'] - reserve const nextReset = +lastHeaders['x-ratelimit-reset'] const tokens = [] githubApiProvider.standardTokens.forEach(t => { tokens.push(t) }) // Confidence check. expect(tokens).to.have.lengthOf(1) const [token] = tokens expect(token.usesRemaining).to.equal(usesRemaining) expect(token.nextReset).to.equal(nextReset) }) }) })
JavaScript
0
@@ -52,58 +52,49 @@ nst -serverSecrets = require('../../lib/server-secrets' +config = require('config').util.toObject( )%0Aco @@ -348,21 +348,22 @@ n = -serverSecrets +config.private .gh_
232b99a37efd765ad93041d168e5a7daa98a5ee5
Move help result up if shows
app/cmd/commandsCatalog.js
app/cmd/commandsCatalog.js
app.run(function() { "use strict"; var dispatcher = app.get('dispatcher'); dispatcher.commands({ 'help': function() { return new app.models.HelpResult(); }, 'clear': function() { app.controller('cmdController').clear(); }, 'em': function() { var cfg = app.get('cmdConfig'); cfg.emphasizeBytes = !cfg.emphasizeBytes; } }); // TODO: Make as function dispatcher.command({ canHandle: function(input) { return app.get('expression').canParse(input); }, handle: function(input) { return app.get('expression').parse(input); } }); });
JavaScript
0
@@ -125,32 +125,224 @@ ': function() %7B%0A + var helpResult = document.querySelector('.result .help');%0A if(helpResult != null) %7B%0A moveHelpResultUp(helpResult);%0A return;%0A %7D%0A retu @@ -870,12 +870,334 @@ %7D);%0A +%0A function moveHelpResultUp(helpResult) %7B%0A var container = helpResult.parentNode.parentNode;%0A if(container.parentNode.firstChild != container) %7B%0A%0A var out = container.parentNode;%0A out.removeChild(container);%0A out.insertBefore(container, out.firstChild);%0A %7D%0A%0A %7D%0A%0A %7D);%0A
e840e711329c6a59e593669bc4fd1e2cac5210eb
Fix HoundCI issues
scripts/merge-configs.js
scripts/merge-configs.js
/* global hexo */ var merge = require('./merge'); /** * Merge configs in _data/next.yml into hexo.theme.config. * Note: configs in _data/next.yml will override configs in hexo.theme.config. */ hexo.on('generateBefore', function () { if (hexo.locals.get) { var data = hexo.locals.get('data'); if ( data && data.next ) { if ( data.next.override ) hexo.theme.config = data.next else merge(hexo.theme.config, data.next) } } });
JavaScript
0
@@ -358,16 +358,18 @@ erride ) + %7B %0A @@ -402,19 +402,24 @@ next +; %0A + %7D else + %7B %0A @@ -458,16 +458,25 @@ ta.next) +;%0A %7D %0A %7D%0A
644f3820d6cdfc1af40a6051b3d7bb5dadcb9234
Fix broccoli pipeline
Brocfile.js
Brocfile.js
var concat = require('broccoli-sourcemap-concat'); var Funnel = require('broccoli-funnel'); var mergeTrees = require('broccoli-merge-trees'); var compileES6Modules = require('broccoli-es6modules'); var transpileES6 = require('broccoli-babel-transpiler'); var jshintTree = require('broccoli-jshint'); var replace = require('broccoli-string-replace'); var gitVersion = require('git-repo-version'); var jscs = require('broccoli-jscs'); // extract version from git // note: remove leading `v` (since by default our tags use a `v` prefix) var version = gitVersion().replace(/^v/, ''); var packages = [ { name: 'orbit', include: [/orbit.js/, /(orbit\/.+.js)/] }, { name: 'orbit-common', include: [/orbit-common.js/, /(orbit\-common\/.+.js)/], exclude: [/orbit-common\/local-storage-source.js/, /orbit-common\/jsonapi-serializer.js/, /orbit-common\/jsonapi-source.js/] }, { name: 'orbit-common-local-storage', include: [/orbit-common\/local-storage-source.js/] }, { name: 'orbit-common-jsonapi', include: [/orbit-common\/jsonapi-serializer.js/, /orbit-common\/jsonapi-source.js/] } ]; var loader = new Funnel('bower_components', { srcDir: 'loader', files: ['loader.js'], destDir: '/assets/' }); var globalizedLoader = new Funnel('build-support', { srcDir: '/', files: ['globalized-loader.js'], destDir: '/assets/' }); var generatedPackageConfig = new Funnel('build-support', { srcDir: '/', destDir: '/', files: ['bower.json', 'package.json'] }); generatedPackageConfig = replace(generatedPackageConfig, { files: ['bower.json', 'package.json'], pattern: { match: /VERSION_PLACEHOLDER/, replacement: function() { return version; } } }); var tests = new Funnel('test', { srcDir: '/tests', include: [/.js$/], destDir: '/tests' }); var buildExtras = new Funnel('build-support', { srcDir: '/', destDir: '/', files: ['README.md', 'LICENSE'] }); var lib = {}; var main = {}; var globalized = {}; packages.forEach(function(package) { lib[package.name] = new Funnel('lib', { srcDir: '/', include: package.include, exclude: package.exclude || [], destDir: '/' }); main[package.name] = mergeTrees([ lib[package.name] ]); main[package.name] = jscs(main[package.name], { esnext: true, enabled: true }); main[package.name] = new compileES6Modules(main[package.name]); main[package.name] = new transpileES6(main[package.name]); main[package.name] = concat(main[package.name], { inputFiles: ['**/*.js'], outputFile: '/' + package.name + '.amd.js' }); var support = new Funnel('build-support', { srcDir: '/', files: ['iife-start.js', 'globalize-' + package.name + '.js', 'iife-stop.js'], destDir: '/' }); var loaderTree = (package.name === 'orbit' ? loader : globalizedLoader); var loaderFile = (package.name === 'orbit' ? 'loader.js' : 'globalized-loader.js'); globalized[package.name] = concat(mergeTrees([loaderTree, main[package.name], support]), { inputFiles: ['iife-start.js', 'assets/' + loaderFile, package.name + '.amd.js', 'globalize-' + package.name + '.js', 'iife-stop.js'], outputFile: '/' + package.name + '.js' }); }); var allLib = mergeTrees(Object.keys(lib).map(function(package) { return lib[package]; })); var allMain = mergeTrees(Object.keys(main).map(function(package) { return main[package]; })); var allGlobalized = mergeTrees(Object.keys(globalized).map(function(package) { return globalized[package]; })); var jshintLib = jshintTree(allLib); var jshintTest = jshintTree(tests); var jscsLib = jscs(allLib, {esnext: true, enabled: true}); var jscsTest = jscs(tests, {esnext: true, enabled: true}); var mainWithTests = mergeTrees([allLib, tests, jshintLib, jshintTest, jscsLib, jscsTest]); mainWithTests = new compileES6Modules(mainWithTests); mainWithTests = new transpileES6(mainWithTests); mainWithTests = concat(mainWithTests, { inputFiles: ['**/*.js'], outputFile: '/assets/tests.amd.js' }); var vendor = concat('bower_components', { inputFiles: [ 'jquery/dist/jquery.js', 'rsvp/rsvp.js'], outputFile: '/assets/vendor.js' }); var qunit = new Funnel('bower_components', { srcDir: '/qunit/qunit', files: ['qunit.js', 'qunit.css'], destDir: '/assets' }); var testSupport = concat('test', { inputFiles: ['../test/test-support/sinon.js', '../test/test-support/test-shims.js', '../test/test-support/test-loader.js'], outputFile: '/assets/test-support.js' }); var testIndex = new Funnel('test', { srcDir: '/', files: ['index.html'], destDir: '/tests' }); module.exports = mergeTrees([loader, globalizedLoader, allMain, allGlobalized, mainWithTests, vendor, qunit, testSupport, testIndex, generatedPackageConfig, buildExtras]);
JavaScript
0.000012
@@ -2319,100 +2319,8 @@ %5D);%0A - main%5Bpackage.name%5D = jscs(main%5Bpackage.name%5D, %7B%0A esnext: true,%0A enabled: true%0A %7D);%0A ma
eb13e5563928ea6ea754801cf9e9dccb38413dd3
make loadGraph execute in update_state() instead of input
browser/plugins/load_graph_on_trigger.plugin.js
browser/plugins/load_graph_on_trigger.plugin.js
(function() { var LoadGraphOnTrigger = E2.plugins.load_graph_on_trigger = function(core, node) { Plugin.apply(this, arguments) this.desc = 'Loads and plays the Vizor file (replacing the current one) on trigger' this.input_slots = [{ name: 'trigger', dt: core.datatypes.BOOL, desc: 'When trigger is true, the URL will be loaded in the player', def: null }, { name: 'url', dt: core.datatypes.TEXT, desc: 'Relative URL to published Vizor file, eg. /fthr/moon', def: null }] this.output_slots = [] } LoadGraphOnTrigger.prototype.update_input = function(slot, data) { Plugin.prototype.update_input.apply(this, arguments) if (slot.name === 'trigger' && data && this.inputValues.url) { var givenUrlParts = this.inputValues.url.split('/') var graphPath = '/' + givenUrlParts.splice(-2, 2).join('/') console.log('loading', graphPath) // in the editor if (E2.app && E2.app.navigateToPublishedGraph) return E2.app.navigateToPublishedGraph(graphPath) // in the player var graphUrl = '/data/graph' + graphPath + '.min.json' E2.app.player.load_from_url(graphUrl, function() { E2.app.player.play() }) } } })()
JavaScript
0
@@ -85,14 +85,8 @@ core -, node ) %7B%0A @@ -543,138 +543,130 @@ type -.update_input = function(slot, data) %7B%0A%09Plugin.prototype.update_input.apply(this, arguments)%0A%0A%09if (slot.name === 'trigger' && data + = Object.create(Plugin.prototype)%0A%0ALoadGraphOnTrigger.prototype.update_state = function() %7B%0A%09if (this.inputValues.trigger && @@ -810,45 +810,8 @@ ')%0A%0A -%09%09console.log('loading', graphPath)%0A%0A %09%09// @@ -1090,15 +1090,14 @@ %09%7D)%0A%09%7D%0A%7D -%09 %0A%0A%7D)()
9fb2108118183e90f03f8b2d96a5919a59a186d2
Remove amount limit TODO, handled with documentation.
app/index.js
app/index.js
/** * Created by sbardian on 5/16/17. */ import React from 'react'; import PropTypes from 'prop-types'; import openTriviaAPI from 'opentriviaapi'; import QuestionWrapper from './components/QuestionWrapper'; export default class OpenTrivia extends React.Component { constructor(props) { super(props); this.state = { loading: true, results: [{}], token: null, index: 0, } this.nextQuestion = this.nextQuestion.bind(this); this.prevQuestion = this.prevQuestion.bind(this); this.getToken = this.getToken.bind(this); } // Moves forward to the next question nextQuestion() { console.log('NEXT'); let i = this.state.index; if (i < (this.props.amount - 1)) { i++; } this.setState({ index: i }); } // Moves backwards to the previous question prevQuestion() { console.log('PREV'); let i = this.state.index; if (i > 0) { i--; } this.setState({ index: i }); } getToken() { if (this.props.getToken && !this.state.token) { return openTriviaAPI.getToken() .then(data => data.token); } return this.state.token; } componentWillMount() { this.getToken() .then((token) => { this.setState({token}); return openTriviaAPI.getQuestions({token, ...this.props}); }) .then((data) => { this.setState({ results: data.results, loading: false, }); }); } render() { return this.state.loading === true ? <div><h1>Loading Question. . .</h1></div> : <div> <h4>{(this.state.index + 1)} / {this.props.amount}</h4> <div> <button onClick={this.nextQuestion}>Next</button> </div> <div> <button onClick={this.prevQuestion}>Prev</button> </div> <QuestionWrapper question={this.state.results[this.state.index]}/> </div> } } // TODO: API only takes between 1-50 for amount, need to have a limit. OpenTrivia.propTypes = { amount: PropTypes.number, category: PropTypes.number, difficulty: PropTypes.string, type: PropTypes.string, encode: PropTypes.string, getToken: PropTypes.bool, }; OpenTrivia.defaultProps = { amount: 1, results: [{}], };
JavaScript
0
@@ -1977,80 +1977,8 @@ %0A%7D%0A%0A -// TODO: API only takes between 1-50 for amount, need to have a limit. %0A Open
f5d241b5d5782d46aba15ee6c7735ab5560ecf1a
Add bcrypt-nodejs and Promise to package.json, fix minor require statements
app/collections/invites.js
app/collections/invites.js
var db = require('../config'); var Invite = require('../models/invitee'); var Invites = new db.Collection(); Invites.model = Invite; module.exports = Invites;
JavaScript
0
@@ -62,17 +62,16 @@ s/invite -e ');%0A%0Avar
a13f42871e276981f8b11d97dac0fe1c29041689
update search call
lambdas/api/index.js
lambdas/api/index.js
'use strict' const zlib = require('zlib') const Api = require('sat-api-lib') const util = require('lambda-proxy-utils') const get = require('lodash.get') const es = require('../../lib/es') module.exports.handler = function (event, context, cb) { console.log(`API handler: ${JSON.stringify(event)}`) const resources = event.resource.split('/') switch (resources[0]) { case 'api': console.log('/api') cb() break case 'collections': console.log('/collections') cb() break case 'search': console.log('/search') break } const method = event.httpMethod const payload = { query: {}, headers: event.headers } if (method === 'POST' && event.body) { payload.query = JSON.parse(event.body); } else if (method === 'GET' && event.queryStringParameters) { payload.query = event.queryStringParameters; } es.client().then((esClient) => { const s = new Api.search(payload, esClient); //const encoding = get(req, 'headers.Accept-Encoding', null); s['search'](function (err, resp) { if (err) { console.log(err); const res = new util.Response({ cors: true, statusCode: 400 }); return cb(null, res.send({ details: err.message })); } const res = new util.Response({ cors: true, statusCode: 200 }); return cb(null, res.send(resp)); }); }) }
JavaScript
0
@@ -42,17 +42,17 @@ )%0Aconst -A +a pi = req @@ -932,16 +932,21 @@ st s +earch = new -A +a pi.s @@ -1051,18 +1051,20 @@ s -%5B' +earch. search -'%5D (fun
6e942fd6e3f2d3d90dfee4aa34bcbb7b501081ad
Fix filtering on discussion
app/coffeescripts/views/DiscussionTopic/DiscussionToolbarView.js
app/coffeescripts/views/DiscussionTopic/DiscussionToolbarView.js
// // Copyright (C) 2012 - present Instructure, Inc. // // This file is part of Canvas. // // Canvas is free software: you can redistribute it and/or modify it under // the terms of the GNU Affero General Public License as published by the Free // Software Foundation, version 3 of the License. // // Canvas is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR // A PARTICULAR PURPOSE. See the GNU Affero General Public License for more // details. // // You should have received a copy of the GNU Affero General Public License along // with this program. If not, see <http://www.gnu.org/licenses/>. import {View} from 'Backbone' import _ from 'underscore' import 'jqueryui/button' // # // requires a MaterializedDiscussionTopic model export default class DiscussionToolbarView extends View { constructor(...args) { super(...args) this.clearInputs = this.clearInputs.bind(this) } static initClass() { this.prototype.els = { '#discussion-search': '$searchInput', '#onlyUnread': '$unread', '#showDeleted': '$deleted', '.disableWhileFiltering': '$disableWhileFiltering' } this.prototype.events = { 'keyup #discussion-search': 'filterBySearch', 'change #onlyUnread': 'toggleUnread', 'change #showDeleted': 'toggleDeleted', 'click #collapseAll': 'collapseAll', 'click #expandAll': 'expandAll' } this.prototype.filter = this.prototype.afterRender this.prototype.filterBySearch = _.debounce(function() { let value = this.$searchInput.val() if (value === '') { value = null } this.model.set('query', value) return this.maybeDisableFields() }, 250) } initialize() { super.initialize(...arguments) return this.model.on('change', this.clearInputs) } afterRender() { this.$unread.button() return this.$deleted.button() } clearInputs() { if (this.model.hasFilter()) return this.$searchInput.val('') this.$unread.prop('checked', false) this.$unread.button('refresh') return this.maybeDisableFields() } toggleUnread() { // setTimeout so the ui can update the button before the rest // do expensive stuff return setTimeout(() => { this.model.set('unread', this.$unread.prop('checked')) return this.maybeDisableFields() }, 50) } toggleDeleted() { return this.trigger('showDeleted', this.$deleted.prop('checked')) } collapseAll() { this.model.set('collapsed', true) return this.trigger('collapseAll') } expandAll() { this.model.set('collapsed', false) return this.trigger('expandAll') } maybeDisableFields() { return this.$disableWhileFiltering.attr('disabled', this.model.hasFilter()) } } DiscussionToolbarView.initClass()
JavaScript
0.000002
@@ -1859,16 +1859,22 @@ change', + () =%3E this.cl @@ -1882,16 +1882,18 @@ arInputs +() )%0A %7D%0A%0A
0c1bdc76016ae210fe4da824387f9813621d43c6
add tocco-util transform plugin
build/webpack.config.js
build/webpack.config.js
import path from 'path' import webpack from 'webpack' import HtmlWebpackPlugin from 'html-webpack-plugin' import config from '../config' import _debug from 'debug' import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin' import LodashModuleReplacementPlugin from 'lodash-webpack-plugin' const debug = _debug('app:webpack:config') const paths = config.utils_paths const {__DEV__, __PROD__, __STANDALONE__, __TEST__, __PACKAGE__} = config.globals const packageDir = `packages/${__PACKAGE__}` const absolutePackagePath = paths.client(`${packageDir}/`) const outputDir = absolutePackagePath + '/dist' debug('Create configuration.') const webpackConfig = { name: 'client', target: 'web', devtool: __PROD__ ? 'source-map' : 'eval', resolve: { modules: [ path.resolve(paths.client(), packageDir, 'src'), 'node_modules', path.resolve(paths.client(), 'node_modules') ], alias: { 'ReactDOM': `${__dirname}/../node_modules/react-dom/index.js`, 'React': `${__dirname}/../node_modules/react/react.js` }, extensions: ['.js', '.jsx', '.json'] }, performance: { hints: __PROD__ ? 'warning' : false }, module: {} } if (!__TEST__) { webpackConfig.externals = { 'react': 'React', 'React': 'React', 'react-dom': 'ReactDOM', 'ReactDOM': 'ReactDOM' } } // ------------------------------------ // Entry Points // ------------------------------------ const APP_ENTRY_PATH = paths.client(`${packageDir}/src/main.js`) webpackConfig.entry = { app: __DEV__ ? [APP_ENTRY_PATH, `webpack-hot-middleware/client?path=/__webpack_hmr`] : [APP_ENTRY_PATH] } // ------------------------------------ // Bundle Output // ------------------------------------ webpackConfig.output = { filename: 'index.js', path: outputDir, libraryTarget: 'umd', publicPath: '' } // ------------------------------------ // Plugins // ------------------------------------ webpackConfig.plugins = [ new webpack.DefinePlugin(config.globals) ] if (__DEV__) { webpackConfig.plugins.push( new HtmlWebpackPlugin({ template: paths.client('server/index.html'), hash: false, filename: 'index.html', inject: 'body', minify: { collapseWhitespace: true } }) ) } if (__STANDALONE__) { webpackConfig.plugins.push( new HtmlWebpackPlugin({ template: paths.client('server/standalone.html'), hash: false, filename: 'index.html', inject: 'body', minify: { collapseWhitespace: true } }) ) } if (__DEV__) { debug('Enable plugin for case-sensitive path check') webpackConfig.plugins.push(new CaseSensitivePathsPlugin()) debug('Enable plugins for live development (HMR, NoErrors).') webpackConfig.plugins.push( new webpack.HotModuleReplacementPlugin() ) } else if (__PROD__) { webpackConfig.plugins.push( new webpack.LoaderOptionsPlugin({ minimize: true, debug: false }), new LodashModuleReplacementPlugin(), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, screw_ie8: true, conditionals: true, unused: true, comparisons: true, sequences: true, dead_code: true, evaluate: true, if_return: true, join_vars: true }, output: { comments: false } }) ) } const testPlugins = [] // see: https://github.com/karma-runner/karma-sauce-launcher/issues/95 if (!process || !process.env || !process.env.DISABLE_ISTANBUL_COVERAGE) { debug('Enable instanbul test plugin.') testPlugins.push(['istanbul', { 'exclude': [ '**/dev/**', '**/*/*.spec.js', '**/tocco-ui/**/example.js', '**/tocco-ui/dist' ] }]) } webpackConfig.module.rules = [ { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader', options: { cacheDirectory: true, plugins: [ ['transform-imports', { 'tocco-ui': { 'transform': 'tocco-ui/src/${member}', // eslint-disable-line no-template-curly-in-string 'preventFullImport': true } }], 'transform-runtime', 'transform-flow-strip-types' ], presets: [ ['es2015', { 'modules': false }], 'react', 'stage-0' ], env: { production: { plugins: [ 'transform-react-remove-prop-types', 'transform-react-constant-elements' ] }, development: { plugins: ['flow-react-proptypes'], presets: [ 'react-hmre' ] }, test: { plugins: testPlugins } } } } ] if (__DEV__) { // Run linting but only show errors as warning webpackConfig.module.rules.push( { test: /\.jsx?$/, enforce: 'pre', use: ['eslint-loader'] } ) webpackConfig.plugins.push( new webpack.LoaderOptionsPlugin({ options: { eslint: { emitWarning: true } } }) ) } webpackConfig.module.rules.push( { test: /\.css$/, use: 'style-loader!css-loader' }, { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] } ) // File loaders /* eslint-disable */ webpackConfig.module.rules.push( { test: /\.woff(\?.*)?$/, use: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' }, { test: /\.woff2(\?.*)?$/, use: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' }, { test: /\.otf(\?.*)?$/, use: 'file-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' }, { test: /\.ttf(\?.*)?$/, use: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' }, { test: /\.eot(\?.*)?$/, use: 'file-loader?prefix=fonts/&name=[path][name].[ext]' }, { test: /\.svg(\?.*)?$/, use: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' }, { test: /\.(png|jpg)$/, use: 'file-loader?limit=8192' } ) /* eslint-enable */ export default webpackConfig
JavaScript
0
@@ -4240,24 +4240,205 @@ port': true%0A + %7D,%0A 'tocco-util': %7B%0A 'transform': 'tocco-util/src/$%7Bmember%7D', // eslint-disable-line no-template-curly-in-string%0A 'preventFullImport': true%0A %7D%0A
861fb75b3975111a6ea85d268327f86330a9c165
Update ddb_query.js
javascript/example_code/dynamodb/ddb_query.js
javascript/example_code/dynamodb/ddb_query.js
/* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ This file 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. ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html */ // Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create DynamoDB service object var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); var params = { ExpressionAttributeValues: { ':s': {N: '2'}, ':e' : {N: '09'}, ':topic' : {S: 'PHRASE'} }, KeyConditionExpression: 'Season = :s and Episode > :e', ProjectionExpression: 'Episode, Title, Subtitle', FilterExpression: 'contains (Subtitle, :topic)', TableName: 'EPISODES_TABLE' }; ddb.query(params, function(err, data) { if (err) { console.log("Error", err); } else { //console.log("Success", data.Items); data.Items.forEach(function(element, index, array) { console.log(element.Title.S + " (" + element.Subtitle.S + ")"); }); } });
JavaScript
0
@@ -1,9 +1,6 @@ / -*%0A +/ Cop @@ -77,26 +77,12 @@ ed.%0A -%0A This file is l +// L icen @@ -105,428 +105,80 @@ ache - License, Version 2.0 (the %22License%22).%0A You may not use this file except in compliance with the License. A copy of%0A the License is located at%0A%0A http://aws.amazon.com/apache2.0/%0A%0A This file is distributed on an %22AS IS%22 BASIS, WITHOUT WARRANTIES OR%0A CONDITIONS OF ANY KIND, either express or implied. See the License for the%0A specific language governing permissions and limitations under the License.%0A %0A +-2.0 License on an %22AS IS%22 BASIS, WITHOUT WARRANTIES OF ANY KIND. %0A%0A// ABO @@ -272,18 +272,18 @@ opic at%0A - +// https:/ @@ -378,12 +378,8 @@ tml%0A -*/%0A%0A // L
cb7e7372335b9f90fa23b513098548b7e4b2a6f1
fix protractor to load correct routes
spec/javascripts/e2e/affordability_page_spec.js
spec/javascripts/e2e/affordability_page_spec.js
describe('E2E: affordability calculator page', function() { var ptor; beforeEach(function() { browser.get('#/affordability'); ptor = protractor.getInstance(); }); it('should load the affordability calculator page', function() { var ele = by.css('h2'); expect(ptor.isElementPresent(ele)).toBe(true); }); });
JavaScript
0
@@ -114,9 +114,27 @@ et(' -# +mortgage_calculator /aff @@ -284,17 +284,17 @@ y.css('h -2 +1 ');%0A
0af06a1ea4d4d32b4c67d2c942b63228da6a96e3
rename relayout method
window.js
window.js
import { arr, obj } from "lively.lang"; import { pt, Color, Rectangle } from "lively.graphics"; import { show, morph, Morph, GridLayout } from "./index.js"; import { connect } from "lively.bindings"; export default class Window extends Morph { constructor(props = {}) { super({ fill: Color.lightGray, borderRadius: 7, dropShadow: true, borderColor: Color.gray, borderWidth: 1, clipMode: "hidden", resizable: true, ...obj.dissoc(props, ["title", "targetMorph"]), }); this.submorphs = this.controls(this.resizable) if (props.targetMorph) this.targetMorph = props.targetMorph; this.layout = new GridLayout({grid: [[this.titleLabel()], [this.targetMorph]], autoAssign: false, compensateOrigin: true}), this.layout.row(0).col(0).group.align = "center"; this.layout.row(0).fixed = 25; this.title = props.title || this.name || ""; this.resetPropertyCache(); this.positionResizer(); connect(this, "extent", this, "positionResizer"); } get isWindow() { return true } get targetMorph() { return arr.withoutAll(this.submorphs, this.controls())[0]; } set targetMorph(morph) { var ctrls = this.controls(); arr.withoutAll(this.submorphs, ctrls).forEach(ea => ea.remove()); if (morph) this.addMorph(morph, ctrls[0]); } targetMorphBounds() { return new Rectangle(0, 25, this.width, this.height - 25); } resetPropertyCache() { // For remembering the position and extents of the window states this.propertyCache = {nonMinizedBounds: null, nonMaximizedBounds: null, minimizedBounds: null}; } positionResizer() { this.resizer().bottomRight = this.innerBounds().bottomRight(); } controls() { return this.buttons() .concat(this.titleLabel()) .concat(this.resizable ? this.resizer() : []); } buttons() { let defaultStyle = { type: "ellipse", extent: pt(13,13), borderWith: 1, onHoverIn() { this.submorphs[0].visible = true; }, onHoverOut() { this.submorphs[0].visible = false; } } return [ this.getSubmorphNamed("close") || { ...defaultStyle, name: "close", center: pt(15,13), borderColor: Color.darkRed, fill: Color.rgb(255,96,82), onMouseDown: (evt) => { this.close(); }, submorphs: [{ fill: Color.black.withA(0), scale: 0.7, visible: false, styleClasses: ["morph", "fa", "fa-times"], center: pt(5.5, 5), opacity: 0.5 }] }, this.getSubmorphNamed("minimize") || { ...defaultStyle, center: pt(35,13), name: "minimize", borderColor: Color.brown, fill: Color.rgb(255,190,6), onMouseDown: (evt) => { this.toggleMinimize(); }, submorphs: [{ fill: Color.black.withA(0), scale: 0.7, visible: false, styleClasses: ["morph", "fa", "fa-minus"], center: pt(5.5,5), opacity: 0.5 }] }, this.resizable ? (this.getSubmorphNamed("maximize") || { ...defaultStyle, name: "maximize", center: pt(55,13), borderColor: Color.darkGreen, fill: Color.green, onMouseDown: (evt) => { this.toggleMaximize(); }, submorphs: [{ fill: Color.black.withA(0), scale: 0.7, visible: false, styleClasses: ["morph", "fa", "fa-plus"], center: pt(5.5,5), opacity: 0.5 }] }) : undefined ] } titleLabel() { return this.getSubmorphNamed("titleLabel") || { type: "label", name: "titleLabel", fill: Color.transparent, fontColor: Color.darkGray, reactsToPointer: false, textString: "" }; } resizer() { const win = this; return this.getSubmorphNamed("resizer") || { name: "resizer", nativeCursor: "nwse-resize", extent: pt(20,20), fill: Color.transparent, bottomRight: this.extent, onDrag(evt) { win.resizeBy(evt.state.dragDelta); this.bottomRight = win.extent; } }; } get title() { return this.titleLabel().textString; } set title(title) { this.titleLabel().textString = title; } toggleMinimize() { var cache = this.propertyCache, bounds = this.bounds(), duration = 200, easing = "cubic-bezier(0.19, 1, 0.22, 1)"; if (this.minimized) { cache.minimizedBounds = bounds; this.animate({bounds: cache.nonMinizedBounds || bounds, duration, easing}); } else { cache.nonMinizedBounds = bounds; cache.minimizedBounds = cache.minimizedBounds || bounds.withExtent(pt(this.width, 25)); this.animate({bounds: cache.minimizedBounds, duration, easing}); } this.minimized = !this.minimized; this.resizer().visible = !this.minimized; } toggleMaximize() { var cache = this.propertyCache, easing = "cubic-bezier(0.19, 1, 0.22, 1)", duration = 200; if (this.maximized) { this.animate({bounds: cache.nonMaximizedBounds, duration, easing}); this.resizer().bottomRight = this.extent; this.maximized = false; } else { cache.nonMaximizedBounds = this.bounds(); this.animate({bounds: this.world().visibleBounds().insetBy(5), duration, easing}); this.resizer().visible = true; this.maximized = true; this.minimized = false; } } close() { this.remove() } onMouseDown(evt) { this.activate(); this.styleClasses = ["morph"]; } focus() { var w = this.world(), t = this.targetMorph; if (!w || !t) return; if (w.focusedMorph && (w.focusedMorph === t || t.isAncestorOf(w.focusedMorph))) return; t.focus(); } isActive() { var w = this.world(); return w ? arr.last(w.getWindows()) === this : false; } activate() { if (this.isActive()) { this.focus(); return this; } if (!this.world()) { this.openInWorldNearHand() } else this.bringToFront(); var w = this.world() || this.env.world; arr.without(w.getWindows(), this).forEach(ea => ea.deactivate()); this.focus(); return this; } deactivate() {} }
JavaScript
0.000001
@@ -570,16 +570,17 @@ sizable) +; %0A %0A @@ -1055,31 +1055,32 @@ this. -positionResizer +relayoutControls ();%0A @@ -1110,31 +1110,32 @@ this, %22 -positionResizer +relayoutControls %22);%0A %7D%0A @@ -1738,23 +1738,24 @@ %0A%0A -positionResizer +relayoutControls () %7B
1a05c4f97bff618339bb5eb42d796cdcc23c15e9
remove race condition where song could possibly be downloaded twice
backends/gmusic.js
backends/gmusic.js
var config; var creds = require(process.env.HOME + '/.googlePlayCreds.json'); var PlayMusic = require('playmusic'); var mkdirp = require('mkdirp'); var https = require('https'); var send = require('send'); var url = require('url'); var fs = require('fs'); var gmusicBackend = {}; var gmusicDownload = function(startUrl, songID, callback, errCallback) { var doDownload = function(streamUrl) { console.log('downloading song ' + songID); var filePath = config.songCachePath + '/gmusic/' + songID + '.mp3'; var songFd = fs.openSync(filePath, 'w'); var req = https.request(streamUrl, function(res) { res.on('data', function(chunk) { fs.writeSync(songFd, chunk, 0, chunk.length, null); }); res.on('end', function() { if(res.statusCode === 302) { // redirect console.log('redirected. retrying with new URL'); fs.closeSync(songFd); fs.unlinkSync(config.songCachePath + '/gmusic/' + songID + '.mp3'); gmusicDownload(res.headers.location, songID, callback, errCallback); } else if(res.statusCode === 200) { console.log('download finished ' + songID); fs.closeSync(songFd); if(callback) callback(); } else { console.log('ERROR: unknown status code ' + res.statusCode); fs.closeSync(songFd); fs.unlinkSync(config.songCachePath + '/gmusic/' + songID + '.mp3'); if(errCallback) errCallback('error while pre-caching ' + songID); } }); }); req.on('error', function(e) { console.log('error ' + e + ' while fetching! reconnecting in 5s...'); setTimeout(function() { gmusicBackend.init(function() { console.log('error while fetching! now reconnected to gmusic'); gmusicBackend.pm.getStreamUrl(songID, function(streamUrl) { gmusicDownload(streamUrl, songID, callback, errCallback); }); }); }, 5000); }); req.end(); }; if(startUrl) { doDownload(startUrl); } else { gmusicBackend.pm.getStreamUrl(songID, function(streamUrl) { doDownload(streamUrl); }); } }; // cache songID to disk. // on success: callback must be called // on failure: errCallback must be called with error message gmusicBackend.prepareSong = function(songID, callback, errCallback) { var filePath = config.songCachePath + '/gmusic/' + songID + '.mp3'; if(fs.existsSync(filePath)) { // song was found from cache if(callback) callback(); return; } else { // song had to be downloaded gmusicDownload(null, songID, callback, errCallback); } }; // search for music from the backend // on success: callback must be called with a list of song objects // on failure: errCallback must be called with error message gmusicBackend.search = function(terms, callback, errCallback) { gmusicBackend.pm.search(terms, config.searchResultCnt + 1, function(data) { var songs = []; if(data.entries) { songs = data.entries.sort(function(a, b) { return a.score < b.score; // sort by score }).filter(function(entry) { return entry.type === '1'; // songs only, no albums/artists }); for(var i = 0; i < songs.length; i++) { songs[i] = { artist: songs[i].track.artist, title: songs[i].track.title, album: songs[i].track.album, duration: songs[i].track.durationMillis, id: songs[i].track.nid, backend: 'gmusic' }; } } callback(songs); }, function(err) { errCallback('error while searching gmusic: ' + err); }); }; // called when partyplay is started to initialize the backend // do any necessary initialization here gmusicBackend.init = function(_config, callback) { config = _config; gmusicBackend.pm = new PlayMusic(); mkdirp(config.songCachePath + '/gmusic'); gmusicBackend.pm.init(creds, callback); }; // expressjs middleware for requesting music data // must support ranges in the req, and send the data to res gmusicBackend.middleware = function(req, res, next) { send(req, url.parse(req.url).pathname, { dotfiles: 'allow', root: config.songCachePath + '/gmusic' }).pipe(res); }; module.exports = gmusicBackend;
JavaScript
0
@@ -2499,24 +2499,47 @@ ;%0A %7D%0A%7D;%0A%0A +var pendingSongs = %7B%7D;%0A // cache son @@ -2794,16 +2794,105 @@ .mp3';%0A%0A + // song is already downloading%0A if(pendingSongs%5BsongID%5D) %7B%0A return;%0A %7D%0A%0A if(f @@ -3077,58 +3077,255 @@ -gmusicDownload(null, songID, callback, errCallback +pendingSongs%5BsongID%5D = true;%0A gmusicDownload(null, songID, function() %7B%0A delete(pendingSongs%5BsongID%5D);%0A callback();%0A %7D, function() %7B%0A delete(pendingSongs%5BsongID%5D);%0A errCallback();%0A %7D );%0A
307546fcdf9cdd1520e47833e3623904f214ae0b
Change wef type "function" -> "object"
test/wef.coreTest.js
test/wef.coreTest.js
/*! * wef.core tests * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ module("core"); test("namespace", function() { notEqual(wef, undefined, "is wef namespace defined?"); notEqual(typeof wef, "function", "is wef a function?"); }); test("public properties", function() { equal(typeof wef.version, "string", "wef().version"); });
JavaScript
0
@@ -178,28 +178,25 @@ ned?%22);%0A -notE +e qual(typeof @@ -201,24 +201,22 @@ f wef, %22 -function +object %22, %22is w @@ -219,25 +219,24 @@ is wef a - function +n object ?%22);%0A%7D);
d4ee091f5c4c3893996a2d36b01d3573f4af8df2
Update index.js
webpack/gitbook/gitbook-plugin-modal/index.js
webpack/gitbook/gitbook-plugin-modal/index.js
var className = 'gitbook-plugin-modal'; require(['gitbook'], function (gitbook) { gitbook.events.bind('page.change', function () { // 配置项 var cfg = gitbook.state.config.pluginsConfig.modal || {}; var html = cfg.html; var closeable = cfg.closeable; var excludeUrls = cfg.excludeUrls || []; var shouldClose = false; var $modal; var $bookBody = window.document.getElementsByClassName('book-body')[0]; function closeModal() { if ($modal) { $modal.remove(); $modal = null; } shouldClose = true; } function showModal(content, closeable) { if ($bookBody.getElementsByClassName('gitbook-plugin-modal').length > 0) { $bookBody.getElementsByClassName('gitbook-plugin-modal')[0].style.display = 'none'; return; } $modal = window.document.createElement('div'); $modal.style.left = $bookBody.offsetLeft + 'px'; $modal.style.width = $bookBody.clientWidth + 'px'; $modal.className = className; $modal.innerHTML = '<div class="gitbook-plugin-modal-content">' + content + '</div>'; $bookBody.appendChild($modal); if (closeable) { $modal.onclick = closeModal; } } function checkModal() { if (shouldClose) { return; } // URL 检查 for (var i = 0; i < excludeUrls.length; i++) { var exReg = new RegExp(excludeUrls[i], 'g'); if (exReg.test(decodeURI(window.location.href))) { return; } } showModal(html, closeable); } // 事件监听检查 $bookBody.addEventListener('scroll', checkModal); var $bodyInner = window.document.getElementsByClassName('body-inner')[0]; $bodyInner.addEventListener('scroll', checkModal); window.document.getElementById('book-search-input').getElementsByTagName('input')[0].addEventListener('input', closeModal); }); });
JavaScript
0.000002
@@ -1563,24 +1563,26 @@ %E4%BA%8B%E4%BB%B6%E7%9B%91%E5%90%AC%E6%A3%80%E6%9F%A5%0A +// $bookBody.ad @@ -1701,16 +1701,18 @@ 0%5D;%0A +// $bodyInn
d76d04f2244ccaf7a347750972e2ee8f6d8d80e7
Fix path for resolving embed.hbs
src/js/bundle-webpack.js
src/js/bundle-webpack.js
var sprintf = require('sprintf'); var gutil = require('gulp-util'); var extend = require('object-extend'); var gulpWebpack = require('webpack-stream'); var WebpackDevServer = require("webpack-dev-server"); var HtmlWebpackPlugin = require('html-webpack-plugin') var gulp = require('gulp'); var src = gulp.src; var dest = gulp.dest; var webpack = require('webpack'), path = require('path'); var parseArgs = require('minimist'); var options = parseArgs(process.argv, {default: { hot: false }}); /* * Bundle a component * * entryPoint - the entry point for the bundle * outputFileName - file name for produced bundle * destPath - destination path for produced bundle, * relative to the root directory of the project * being built * pageDefs - options to pass on into the template * for each index.html entry point to be * generated. must be either an array (or null, * if no index.html:s need to be generated) * watch - start webpack-dev-server with hot reloading * setting this true will cause this to block * babelPaths - paths for which .js and .jsx files should be * run through babel-loader. this options is at * least needed for backwards compatiblity for some time */ function bundle( entryPoint, outputFileName, destPath, pageDefs, watch, assetContext, babelPaths, callback) { var config = { resolve: { modulesDirectories: ['node_modules'], }, module: { loaders: getLoaders(babelPaths) }, resolveLoader: { root: [path.resolve(__dirname, '../node_modules')], }, output: { filename: outputFileName, path: process.cwd() + "/" + destPath, publicPath: '/' + assetContext }, entry: entryPoint, plugins: htmlWebpackPluginsFromPageDefs(pageDefs, watch), // enabling watch here seems to fix a weird problem where // the bundle would seemingly randomly be built incorrectly // when using the webpack-dev-server, resulting in TypeError // for embed-decorator in the browser console watch: watch }; if (watch) { devServerBundle(config, destPath); return; } plainBundle(config, callback); } // // Private functions // ----------------- // /* * Create HtmlWebpack plugin entries * based on given page defs */ function htmlWebpackPluginsFromPageDefs(pageDefs, watch) { var arr; if (Array.isArray(pageDefs)) { arr = pageDefs; } else { return []; } return arr.map(item => { if (!item.path) { item.path = ''; } var config = { template: require.resolve('lucify-component-builder/src/www/embed.hbs'), inject: false, filename: path.join(item.path, 'index.html'), // this enables a script tag for automatic refresh // https://webpack.github.io/docs/webpack-dev-server.html#automatic-refresh devServer: watch }; var fullConfig = extend(config, item); return new HtmlWebpackPlugin(fullConfig); }); } /* * Start webpack dev server for given webpack configuration */ function devServerBundle(config, destPath) { config.output.publicPath = '/'; if (options.hot) { // Experimental setup for hot module replacement // enable via --hot option // // This seems to work correctly, but we get a message that // some modules could not be updated, as they would need a // full reload. I suspect this is related to the use of higher-order // components. // // https://medium.com/@dan_abramov/the-death-of-react-hot-loader-765fa791d7c4#.wrqoafdic // https://gaearon.github.io/react-hot-loader/getstarted/ // https://webpack.github.io/docs/hot-module-replacement-with-webpack.html config.entry = [config.entry, 'webpack/hot/only-dev-server']; config.plugins.push(new webpack.HotModuleReplacementPlugin()); } var compiler = webpack(config); new WebpackDevServer(compiler, { contentBase: destPath, noInfo: false, hot: options.hot, colors: true }).listen(3000, "localhost", function(err) { if(err) { throw new gutil.PluginError("webpack-dev-server", err); } // keep the server alive or continue? // callback(); }); } /* * Create distribution for given webpack configuration */ function plainBundle(config, callback) { webpack(config, function(err, stats) { if (err) { gutil.log("[webpack]", err); process.exit(1); } gutil.log("[webpack]", stats.toString({chunks: false})); callback(); }); } /* * Get the webpack loaders object for the webpack configuration */ function getLoaders(babelPaths) { if (!babelPaths) { babelPaths = []; } return [ { test: /\.(js|jsx)$/, loader: 'babel', //loaders: ['react-hot', 'babel-loader'], include: [ process.cwd() + '/src', process.cwd() + '/temp', ].concat(babelPaths), query: { presets: [ // https://github.com/babel/babel-loader/issues/166 require.resolve('babel-preset-es2015'), require.resolve('babel-preset-stage-0'), require.resolve('babel-preset-react') ] } }, { test: /\.css$/, loaders: [ 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]', 'postcss-loader' ] }, { test: /\.svg$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml' }, { test: /\.scss$/, loaders: ["style", "css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]", "sass"] }, { test: /\.(jpeg|jpg|gif|png|json)$/, loaders: ["file-loader?name=[name]-[hash:12].[ext]"] }, { test: /\.hbs$/, loader: "handlebars" } ]; } module.exports = bundle;
JavaScript
0.000002
@@ -2836,36 +2836,10 @@ ve(' -lucify-component-builder/src +.. /www
e4b2e9f53ca4ebb78e506e6a2258998f3a105a77
Use break instead of return
js/app/modules/supplementaryArticlesModule.js
js/app/modules/supplementaryArticlesModule.js
// Copyright 2016 Endless Mobile, Inc. /* exported SupplementaryArticlesModule */ const Gettext = imports.gettext; const GObject = imports.gi.GObject; const Lang = imports.lang; const Actions = imports.app.actions; const Config = imports.app.config; const Dispatcher = imports.app.dispatcher; const Module = imports.app.interfaces.module; const CardContainer = imports.app.modules.cardContainer; let _ = Gettext.dgettext.bind(null, Config.GETTEXT_PACKAGE); /** * Class: SupplementaryArticlesModule * A module that displays all unread articles as cards in an arrangement. If no * unread articles are available it will show read articles with the same criteria. * * Slots: * arrangement * card-type */ const SupplementaryArticlesModule = new Lang.Class({ Name: 'SupplementaryArticlesModule', GTypeName: 'EknSupplementaryArticlesModule', Extends: CardContainer.CardContainer, Implements: [ Module.Module ], Properties: { 'factory': GObject.ParamSpec.override('factory', Module.Module), 'factory-name': GObject.ParamSpec.override('factory-name', Module.Module), /** * Property: same-set * * Whether to show articles from the same set or from different sets. */ 'same-set': GObject.ParamSpec.boolean('same-set', 'Show articles from same set', 'Whether to show articles in the same set', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, true), }, _init: function (props={}) { props.title = _("Other news"); this.parent(props); let dispatcher = Dispatcher.get_default(); dispatcher.register((payload) => { switch(payload.action_type) { case Actions.CLEAR_SUPPLEMENTARY_ARTICLES: if (payload.same_set !== this.same_set) break; this.arrangement.clear(); break; case Actions.APPEND_SUPPLEMENTARY_ARTICLES: if (payload.same_set !== this.same_set) return; // If we asked for unread articles and didn't get any // try now asking for _read_ articles with the same // criteria if (payload.need_unread && payload.models.length === 0) { dispatcher.dispatch({ action_type: Actions.NEED_MORE_SUPPLEMENTARY_ARTICLES, same_set: this.same_set, set_tags: payload.set_tags, need_unread: false, }); } payload.models.forEach(this.arrangement.add_model, this.arrangement); break; } }); }, // Module override get_slot_names: function () { return ['arrangement']; }, });
JavaScript
0.000001
@@ -2091,22 +2091,21 @@ +b re -turn +ak ;%0A%0A
4756ece5d684c3388e0473c7da7f90dd5ca9f495
update CardViewModel dependency #515
arches/app/media/js/views/components/resource-report-abstract.js
arches/app/media/js/views/components/resource-report-abstract.js
define([ 'arches', 'jquery', 'underscore', 'knockout', 'report-templates', 'models/report', 'models/graph', 'viewmodels/card', ], function(arches, $, _, ko, reportLookup, ReportModel, GraphModel, CardViewModel) { var ResourceReportAbstract = function(params) { var self = this; this.loading = ko.observable(true); this.version = arches.version; this.resourceid = ko.unwrap(params.resourceid); this.summary = Boolean(params.summary); this.configForm = params.configForm; this.configType = params.configType; this.template = ko.observable(); this.report = ko.observable(); this.initialize = function() { var url; if (params.report) { if (!params.report.report_json && params.report.attributes.resourceid) { url = arches.urls.api_bulk_disambiguated_resource_instance + `?resource_ids=${params.report.attributes.resourceid}`; $.getJSON(url, function(resp) { params.report.report_json = resp[params.report.attributes.resourceid]; self.template(reportLookup[params.report.templateId()]); self.report(params.report); self.loading(false); }); } else { this.template(reportLookup[params.report.templateId()]); this.report(params.report); self.loading(false); } } else if (self.resourceid) { url = arches.urls.api_resource_report(self.resourceid); self.fetchResourceData(url).then(function(responseJson) { var template = responseJson.template; self.template(template); if (template.preload_resource_data) { self.preloadResourceData(responseJson); } else { self.report({ 'template': responseJson.template, 'report_json': responseJson.report_json, }); } self.loading(false); }); } }; this.fetchResourceData = function(url) { return window.fetch(url).then(function(response){ if (response.ok) { return response.json(); } else { throw new Error(arches.translations.reNetworkReponseError); } }); }; this.preloadResourceData = function(responseJson) { var graphModel = new GraphModel({ data: responseJson.graph, datatypes: responseJson.datatypes, }); var graph = { graphModel: graphModel, cards: responseJson.cards, graph: responseJson.graph, datatypes: responseJson.datatypes, cardwidgets: responseJson.cardwidgets }; responseJson.cards = _.filter(graph.cards, function(card) { var nodegroup = _.find(graph.graph.nodegroups, function(group) { return group.nodegroupid === card.nodegroup_id; }); return !nodegroup || !nodegroup.parentnodegroup_id; }).map(function(card) { return new CardViewModel({ card: card, graphModel: graph.graphModel, resourceId: self.resourceid, displayname: responseJson.displayname, cards: graph.cards, tiles: responseJson.tiles, cardwidgets: graph.cardwidgets }); }); var report = new ReportModel(_.extend(responseJson, { resourceid: self.resourceid, graphModel: graph.graphModel, graph: graph.graph, datatypes: graph.datatypes })); report['hideEmptyNodes'] = responseJson.hide_empty_nodes; report['report_json'] = responseJson.report_json; self.report(report); }; if (ko.unwrap(this.template)?.preload_resource_data) { require(['viewmodels/card'], function(cardViewModel) { CardViewModel = cardViewModel; self.initialize(); }); } else { self.initialize(); } }; ko.components.register('resource-report-abstract', { viewModel: ResourceReportAbstract, template: { require: 'text!templates/views/components/resource-report-abstract.htm' } }); return ResourceReportAbstract; });
JavaScript
0
@@ -240,17 +240,16 @@ el) %7B - %0A var @@ -4470,55 +4470,22 @@ if ( -ko.unwrap(this.template)?.preload_resource_data +!CardViewModel ) %7B%0A @@ -4600,16 +4600,33 @@ Model; %0A + %0A @@ -4669,33 +4669,32 @@ %7D);%0A %7D - %0A else %7B%0A @@ -4734,17 +4734,16 @@ %7D%0A -%0A %7D;%0A @@ -4939,24 +4939,24 @@ ' %7D%0A %7D);%0A - return R @@ -4978,12 +4978,17 @@ stract;%0A + %0A %7D);%0A
8ad80b54e5f0cd6814c4eb847717e89c8db351f5
Remove copy of require-router
app/index.js
app/index.js
var fs = require('fs'); var util = require('util'); var path = require('path'); var Base = require('../lib/base'); var ThoraxGenerator = module.exports = function (args, options, config) { Base.apply(this, arguments); this.prompts.push({ type: 'confirm', name: 'newDirectory', message: 'Would you like to generate the app in a new directory?', default: false }); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); }; util.inherits(ThoraxGenerator, Base); ThoraxGenerator.prototype._name = 'application'; ThoraxGenerator.prototype.askFor = Base.prototype._askFor; ThoraxGenerator.prototype.directory = function () { if (!this.newDirectory) { return; } this._checkAndCreateDirectory(this._.dasherize(this.name), this.async()); }; ThoraxGenerator.prototype._checkAndCreateDirectory = function (directory, cb) { var prompts = [{ type: 'input', name: 'directoryName', message: 'Directory already exists, enter a new name:' }]; if (!directory) { prompts[0].message = 'A directory name is required'; return this.prompt(prompts, function (props) { this._checkAndCreateDirectory(props.directoryName, cb); }.bind(this)); } fs.exists(path.join(this.destinationRoot(), directory), function (exists) { // If the directory doesn't already exist, create a new directory and set // the base destination path here if (!exists) { this.mkdir(directory); this.destinationRoot(directory); this.newDirectory = false; return cb(); } return this.prompt(prompts, function (props) { this._checkAndCreateDirectory(props.directoryName, cb); }.bind(this)); }.bind(this)); }; ThoraxGenerator.prototype.app = function () { this.template('_bower.json', 'bower.json'); this.template('_package.json', 'package.json'); // Using the destinationRoot function seem to break the directory copy helper // this.directory('seed', '.'); this.copy('seed/README.md', 'README.md'); this.copy('seed/routes.json', 'routes.json'); this.copy('seed/Gruntfile.js', 'Gruntfile.js'); this.mkdir('public'); this.mkdir('public/img'); this.copy('seed/public/img/glyphicons-halflings.png', 'public/img/glyphicons-halflings.png'); this.copy('seed/public/img/glyphicons-halflings-white.png', 'public/img/glyphicons-halflings-white.png'); this.mkdir('stylesheets'); this.copy('seed/stylesheets/base.css', 'stylesheets/base.css'); this.mkdir('tasks'); this.copy('seed/tasks/ensure-installed.js', 'tasks/ensure-installed.js'); this.mkdir('tasks/tools'); this.copy('seed/tasks/tools/_require-router.js', 'tasks/tools/_require-router.js'); this.mkdir('js'); this.mkdir('js/templates'); this.mkdir('js/templates/helpers'); this.mkdir('js/views'); this.mkdir('js/models'); this.mkdir('js/routers'); this.mkdir('js/collections'); this.template('_root.handlebars', 'js/templates/root.handlebars'); this.template('_root.js', 'js/views/root.handlebars'); }; ThoraxGenerator.prototype.scripts = function () { this.template('_base.js', 'js/base.js'); this.template('_init.js', 'js/init.js'); this.template('_view.js', 'js/view.js'); this.template('_collection-view.js', 'js/collection-view.js'); this.template('_layout-view.js', 'js/layout-view.js'); this.template('_model.js', 'js/model.js'); this.template('_collection.js', 'js/collection.js'); this.template('_index.html', 'public/index.html'); }; ThoraxGenerator.prototype.projectFiles = function () { this.copy('jshintrc', '.jshintrc'); this.copy('editorconfig', '.editorconfig'); this.copy('bowerrc', '.bowerrc'); };
JavaScript
0
@@ -2623,94 +2623,8 @@ s'); -%0A this.copy('seed/tasks/tools/_require-router.js', 'tasks/tools/_require-router.js'); %0A%0A
b791f99fa13421e684b7b5de51cc2858c95d6433
update gulpfile
gulpfile.js
gulpfile.js
var gulp = require('gulp'), ossup = require('gulp-oss-up'), newer = require('gulp-newer'), useref = require('gulp-useref'), clean = require('gulp-clean'), exec = require('child_process').exec, runSequence = require('run-sequence'), rev = require('gulp-rev'), revReplace = require('gulp-rev-replace'), replace = require('gulp-replace'), filter = require('gulp-filter'), through = require('through2'), fs = require('fs'), manifest = {} // cdn options var cdn_host = process.env.CDN_HOST // aliyun options var aliyunOptions = { 'accessKeyId': process.env.ACCESS_KEY_ID, 'accessKeySecret': process.env.ACCESS_KEY_SECRET, 'bucket': process.env.BUCKET } // clean gulp.task('clean', () => { return gulp.src(['dist']) .pipe(clean()) }) // build gulp.task('build', () => { var imgFilter = filter('public/images/**/*', {restore: true}); var fontFilter = filter('public/fonts/**/*', {restore: true}); var jsFilter = filter('public/javascripts/doc-*.js', {restore: true}); var cssFilter = filter('public/stylesheets/doc-*.css', {restore: true}); var htmlFilter = filter('public/**/*.html', {restore: true}); return gulp.src('public/**') .pipe(htmlFilter) .pipe(useref({searchPath: 'public'})) .pipe(gulp.dest('public')) .pipe(replace(/src="(\.\.\/)*images/g, 'src="/images')) .pipe(htmlFilter.restore) .pipe(imgFilter) .pipe(rev()) .pipe(imgFilter.restore) .pipe(fontFilter) .pipe(rev()) .pipe(fontFilter.restore) .pipe(cssFilter) .pipe(rev()) .pipe(cssFilter.restore) .pipe(jsFilter) .pipe(rev()) .pipe(jsFilter.restore) .pipe(revReplace({ canonicalUris: true, prefix: cdn_host })) .pipe(gulp.dest('dist')) }) // upload files to aliyun gulp.task('oss-before', () => { var content = fs.readFileSync('./manifest.json', {flag: 'a+'}).toString() manifest = JSON.parse(content || '{}'); return gulp }) gulp.task('oss-css', () => { var cssOptions = cloneObj(aliyunOptions) cssOptions.objectDir = 'stylesheets' return gulp.src('dist/stylesheets/doc-*.css') .pipe(checkManifest('stylesheets')) .pipe(ossup(cssOptions)) .pipe(gulp.dest('dist-bak/stylesheets/')) }) gulp.task('oss-js', () => { var jsOptions = cloneObj(aliyunOptions) jsOptions.objectDir = 'javascripts' return gulp.src('dist/javascripts/doc-*.js') .pipe(checkManifest('javascripts')) .pipe(ossup(jsOptions)) .pipe(gulp.dest('dist-bak/javascripts/')) }) gulp.task('oss-img', () => { var imgOptions = cloneObj(aliyunOptions) imgOptions.objectDir = 'images' return gulp.src('dist/images/**/*') .pipe(checkManifest('images')) .pipe(ossup(imgOptions)) .pipe(gulp.dest('dist-bak/images/')) }) gulp.task('oss-font', () => { var fontOptions = cloneObj(aliyunOptions) fontOptions.objectDir = 'fonts' return gulp.src('dist/fonts/**/*') .pipe(checkManifest('fonts')) .pipe(ossup(fontOptions)) .pipe(gulp.dest('dist-bak/fonts/')) }) gulp.task("oss-after", () => { fs.writeFileSync('manifest.json', JSON.stringify(manifest)) return gulp.src([ 'dist/images', 'dist/fonts', 'dist/javascripts', 'dist/stylesheets']) .pipe(clean()) }) gulp.on('stop', () => { process.exit(0) }) // utils var cloneObj = (obj) => JSON.parse(JSON.stringify(obj)) var checkManifest = (type) => { return through.obj((chunk, enc, cb) => { manifest[type] || (manifest[type] = []) if (manifest[type].indexOf(chunk.path) > -1) { cb(null, null) } else { manifest[type].push(chunk.path) cb(null, chunk) } }) } gulp.task('default', (cb) => { runSequence( 'clean', 'build', 'oss-before', ['oss-js', 'oss-css', 'oss-font', 'oss-img'], 'oss-after', cb ); });
JavaScript
0.000001
@@ -1802,26 +1802,29 @@ p.task(' -oss-before +init-manifest ', () =%3E @@ -3033,19 +3033,25 @@ ask( -%22oss-after%22 +'update-manifest' , () @@ -3118,16 +3118,67 @@ ifest))%0A + return gulp%0A%7D)%0A%0Agulp.task('clean-assets', () =%3E %7B %0A retur @@ -3210,17 +3210,16 @@ images', - %0A ' @@ -3226,25 +3226,24 @@ dist/fonts', - %0A 'dist @@ -3256,17 +3256,16 @@ cripts', - %0A ' @@ -3732,21 +3732,139 @@ %7B%0A -runSequence(%0A +console.log(process.env.NODE_ENV)%0A %0A var tasks = %5B%5D%0A switch (process.env.NODE_ENV) %7B%0A case 'production':%0A tasks = %5B%0A @@ -3876,16 +3876,20 @@ n',%0A + + 'build', @@ -3897,22 +3897,33 @@ + -'oss-before',%0A + 'init-manifest',%0A @@ -3976,32 +3976,192 @@ -'oss-after',%0A cb%0A ); + 'update-manifest',%0A 'clean-assets',%0A cb%0A %5D%0A break%0A default:%0A tasks = %5B%0A 'clean',%0A 'build'%0A %5D%0A %7D%0A runSequence.apply(this, tasks) %0A%7D);
2ef8a0fbe60e486d9beabc3fe32207a3c6fd2e78
Add make directorya and clone runTest test case
test/run.js
test/run.js
/* global describe it beforeEach */ 'use strict' const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const requireInject = require('require-inject') const sinon = require('sinon') const sinonChai = require('sinon-chai') require('sinon-as-promised') chai.use(chaiAsPromised) chai.use(sinonChai) const expect = chai.expect describe('runTests', function () { let logger let util let stubs beforeEach(function () { logger = { debug: sinon.spy(), info: sinon.spy() } util = { exists: sinon.stub(), exec: sinon.stub() } stubs = {} stubs[require.resolve('../lib/logging')] = {logger} stubs[require.resolve('../lib/util')] = util }) it('pulls changes if version directory exists', function () { util.exists.resolves() util.exec.resolves() const runTests = requireInject('../lib/run', stubs).runTests return expect(runTests('some dir', 'some version')) .to.eventually.be.fulfilled.then(function () { expect(util.exec).to.have.been.calledWith( 'git pull', {cwd: 'some dir/some version'}) }) }) })
JavaScript
0
@@ -416,16 +416,126 @@ et stubs +%0A const defaultCommandOutput = %7B%0A command: 'command',%0A stdout: 'stdout',%0A stderr: 'stderr'%0A %7D %0A%0A befo @@ -678,16 +678,43 @@ exec: + sinon.stub(),%0A mkdir: sinon.s @@ -961,24 +961,44 @@ ec.resolves( +defaultCommandOutput )%0A const @@ -1213,16 +1213,16 @@ edWith(%0A - @@ -1280,12 +1280,558 @@ %7D)%0A %7D) +%0A%0A it('makes directory and clones if version directory does not exist', function () %7B%0A util.exists.rejects()%0A util.mkdir.resolves()%0A util.exec.resolves(defaultCommandOutput)%0A const runTests = requireInject('../lib/run', stubs).runTests%0A%0A return expect(runTests('some dir', 'some version'))%0A .to.eventually.be.fulfilled.then(function () %7B%0A expect(util.mkdir).to.have.been.calledWith('some dir/some version')%0A expect(util.exec).to.have.been.calledWith(%0A 'git clone . some dir/some version')%0A %7D)%0A %7D) %0A%7D)%0A
91a5b111f0f2afe83d3f209e9d39fb03ffe9af03
fix typo in conditional
app/index.js
app/index.js
'use strict'; var util = require('util'), path = require('path'), yeoman = require('yeoman-generator'); function ExpressSimpleGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.argument('appname', { desc: 'create an express-app with name [appname]', type: Boolean, required: false, defaults: path.basename(process.cwd()) }); this.on('end', function () { this.installDependencies({skipInstall: options['skip-install']}); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(ExpressSimpleGenerator, yeoman.generators.Base); ExpressSimpleGenerator.prototype.askFor = function () { var cb = this.async(), root = this; console.log('express-simple comes with bootstrap and jquery'); var prompts = [ { type: 'list', name: 'expressVersion', message: 'Select the express version you want', default: '3.x', choices: ['3.x', '4.x'] }, { type: 'confirm', name: 'mvc', message: 'Do you want an mvc express app', default: true }, { type: 'list', name: 'cssPreprocessor', message: 'Select the css preprocessor you would like to use', default: 'less', choices: ['less', 'sass', 'stylus'], }, { type: 'list', name: 'viewEngine', message: 'Select view engine you would like to use', default: 'jade', choices: ['jade', 'handlebars', 'ejs'] }, { type: 'list', name: 'buildTool', message: 'Select the build tool you want to use for this project', default: 'grunt', choices: ['grunt', 'gulp'] }, { type: 'list', name: 'buildToolLanguage', message: 'Select the language you want to use for the build tool', default: 'javascript', choices: ['javascript', 'coffeescript'] } ]; var answersCallback = (function (answers) { this.options.mvc = answers.mvc; this.expressVersion = answers.expressVersion; this.cssPreprocessor = answers.cssPreprocessor; this.cssExt = this.cssPreprocessor === 'stylus' ? 'styl' : (this.cssPreprocessor === 'sass' ? 'scss' : this.cssPreprocessor); this.viewEngine = answers.viewEngine === 'handlebars' ? 'hbs' : answers.viewEngine; this.buildTool = answers.buildTool; this.buildToolLanguage = answers.buildToolLanguage === 'javascript' ? 'js' : 'coffee'; cb(); }).bind(this); this.prompt(prompts, answersCallback); }; ExpressSimpleGenerator.prototype.basicSetup = function () { this.mkdir('public'); this.mkdir('public/' + this.cssPreprocessor); this.mkdir('public/vendor'); this.mkdir('public/img'); this.mkdir('public/css'); this.mkdir('public/js'); this.template('styles.css', 'public/' + this.cssPreprocessor + '/styles.' + this.cssExt); this.copy('main.js', 'public/js/main.js'); }; ExpressSimpleGenerator.prototype.viewsSetup = function () { this.sourceRoot(path.join(__dirname, 'templates/views')); ['layout', 'index', '404'].forEach(function (file) { this.template(file + '.html', 'views/' + file + '.' + this.viewEngine); }, this); }; ExpressSimpleGenerator.prototype.setupApp = function () { var prefix = 'templates/' + (this.expressVersion === '3.x' ? '' : 'express4/'); if (this.options.mvc) { this.sourceRoot(path.join(__dirname, prefix + 'mvc')); this.directory('.', '.'); } else { this.sourceRoot(path.join(__dirname, prefix + 'basic')); this.directory('.', '.'); } }; ExpressSimpleGenerator.prototype.changeDir = function () { this.sourceRoot(path.join(__dirname, 'templates', 'common')); }; ExpressSimpleGenerator.prototype.writePackageJSONFile = function () { this.template('.package.json', 'package.json'); }; ExpressSimpleGenerator.prototype.writeBowerJSONFile = function () { this.template('.bower.json', 'bower.json'); }; ExpressSimpleGenerator.prototype.projectfiles = function () { ['.bowerrc', '.editorconfig', '.gitignore', '.jshintrc'].forEach(function (file) { this.copy(file === '.gitignore' ? 'gitignore' : file, file); }, this); }; // working on using either gulp or grunt as the development and build tool // there's a lot of work to be done ExpressSimpleGenerator.prototype.writeBuildFile = function () { this.sourceRoot(path.join(__dirname, 'templates/' + this.buildTool + 'files')); if (this.buildToolLanguage === 'grunt') { this.template('Gruntfile.' + this.buildToolLanguage, 'Gruntfile.' + this.buildToolLanguage); } else { if (this.buildToolLanguage === 'coffee') { this.template('_gulpfile.js', 'gulpfile.js'); } this.template('gulpfile.' + this.buildToolLanguage, 'gulpfile.' + this.buildToolLanguage); } }; module.exports = ExpressSimpleGenerator;
JavaScript
0.000338
@@ -4317,32 +4317,135 @@ = function () %7B%0A + var buildFile = (this.buildTool === 'grunt' ? 'Gruntfile.' : 'gulpfile.') + this.buildToolLanguage;%0A%0A this.sourceRoo @@ -4527,32 +4527,24 @@ is.buildTool -Language === 'grunt' @@ -4569,83 +4569,27 @@ ate( -'Gruntfile.' + this.buildToolLanguage, 'Gruntfile.' + this.buildToolLanguag +buildFile, buildFil e);%0A @@ -4726,81 +4726,27 @@ ate( -'gulpfile.' + this.buildToolLanguage, 'gulpfile.' + this.buildToolLanguag +buildFile, buildFil e);%0A
358725bee3a450edb2a8137020f83ccc9610ea91
Add onRemove handler to pad outline
src/js/directives/pad.js
src/js/directives/pad.js
'use strict'; /** * @ngdoc function * @name Teem.controller:ChatCtrl * @description * # Chat Ctrl * Show Pad for a given project */ angular.module('Teem') .directive('pad', function() { return { scope: true, link: function($scope, elem, attrs) { $scope.editingDefault = attrs.editingDefault; }, controller: [ 'SessionSvc', '$rootScope', '$scope', '$route', '$location', '$timeout', 'SharedState', 'needWidget', '$element', function(SessionSvc, $rootScope, $scope, $route, $location, $timeout, SharedState, needWidget, $element) { var buttons = ['text_fields', 'format_bold', 'format_italic', 'format_strikethrough', 'format_align_left', 'format_align_center', 'format_align_right', 'format_list_bulleted', 'format_list_numbered']; var annotationMap = { 'text_fields': 'paragraph/header=h3', 'format_bold': 'style/fontWeight=bold', 'format_italic': 'style/fontStyle=italic', 'format_strikethrough': 'style/textDecoration=line-through', 'format_align_left': 'paragraph/textAlign=left', 'format_align_center': 'paragraph/textAlign=center', 'format_align_right': 'paragraph/textAlign=right', 'format_list_bulleted': 'paragraph/listStyleType=unordered', 'format_list_numbered': 'paragraph/listStyleType=decimal' }; var annotations = {}; $scope.padWidgets = { 'need': needWidget.getWidget($scope), 'img': { onInit: function(parentElement, state) { $scope.project.attachments[state].file.getUrl().then(url => { parentElement.innerHTML='<img src="'+url+'">'; }); }, onChangeState: function(parentElement, before, state) { $scope.project.attachments[state].file.getUrl().then(url => { parentElement.innerHTML='<img src="'+url+'">'; }); } } }; $scope.padAnnotations = { 'paragraph/header': { onAdd: function() { $scope.pad.outline = this.editor.getAnnotationSet('paragraph/header'); $timeout(); }, onChange: function() { $scope.pad.outline = this.editor.getAnnotationSet('paragraph/header'); $timeout(); } }, 'link': { onEvent: function(range, event) { if (event.type === 'click') { event.stopPropagation(); $scope.linkModal.open(range); } } } }; function updateAllButtons() { for (let btn of buttons) { let [key, val] = annotationMap[btn].split('='); $scope.buttons[btn] = (annotations && annotations[key] === val); } $timeout(); } function disableAllButtons() { $scope.buttons = {}; buttons.forEach(btn => $scope.buttons[btn] = false); $timeout(); } $scope.padCreate = function(editor) { $scope.linkModal = { add: function() { event.stopPropagation(); let range = editor.getSelection(); if (range.text) { editor.setAnnotation('link', ''); } $scope.linkModal.open(range); }, open: function(range) { let annotation = editor.getAnnotationInRange(range, 'link'); $scope.linkModal.range = range; $scope.linkModal.annotation = annotation; console.log(range); let clientRect = range.node.nextSibling ? range.node.nextSibling.getBoundingClientRect() : range.node.parentElement.getBoundingClientRect(); document.getElementById('link-modal').style.top = clientRect.top + 25 + 'px'; document.getElementById('link-modal').style.left = clientRect.left + 'px'; $scope.linkModal.text = range.text; $scope.linkModal.link = annotation ? annotation.value : ''; $scope.linkModal.show = true; let emptyInput = !range.text ? 'text': 'link'; let autofocus = document.querySelector('#link-modal [ng-model="linkModal.' + emptyInput + '"]'); $timeout(() => autofocus && autofocus.focus()); }, change: function() { let range = editor.setText($scope.linkModal.range, $scope.linkModal.text); editor.setAnnotationInRange(range, 'link', $scope.linkModal.link); $scope.linkModal.show = false; $scope.linkModal.edit = false; }, clear: function() { editor.clearAnnotationInRange($scope.linkModal.range, 'link'); $scope.linkModal.show = false; $scope.linkModal.edit = false; } }; disableAllButtons(); editor.onSelectionChanged(function(range) { annotations = range.annotations; updateAllButtons(); }); }; $scope.padReady = function(editor) { // FIXME // SwellRT editor is created with .wave-editor-off // Should use .wave-editor-on when SwellRT editor callback is available // https://github.com/P2Pvalue/swellrt/issues/84 var editorElement = angular.element($element.find('.swellrt-editor').children()[0]); editorElement.on('focus', updateAllButtons); editorElement.on('blur', disableAllButtons); $scope.pad.outline = editor.getAnnotationSet('paragraph/header'); $scope.annotate = function(btn) { let [key, val] = annotationMap[btn].split('='); let currentVal = annotations[key]; if (currentVal === val) { val = null; } annotations[key] = val; editor.setAnnotation(key, val); editorElement.focus(); }; $scope.clearFormat = function() { editor.clearAnnotation('style'); editorElement.focus(); }; $scope.widget = function(type) { if (type === 'need') { needWidget.add(editor, $scope); } if (type === 'img') { if (arguments[1] === undefined) { // First step $scope.pad.selectingFile = true; $timeout(() => $scope.pad.selectingFile = false); } else { // Second step $scope.pad.selectingFile = false; var id = $scope.project.addAttachment(arguments[1]); editor.addWidget('img', id); } } }; $scope.editOn = function () { if (editorElement.attr('class') === 'wave-editor-on') { $scope.pad.editing = true; SessionSvc.showSaving = true; SharedState.turnOn('hiddenTabs'); $timeout(); } }; $scope.editOff = function () { if (editorElement.attr('class') === 'wave-editor-on') { $scope.pad.editing = $scope.editingDefault; SessionSvc.showSaving = false; SharedState.turnOff('hiddenTabs'); $timeout(); } }; if ($scope.editingDefault && $scope.project.isParticipant()) { $scope.pad.editing = true; } }; $scope.$watchCollection(function() { return SessionSvc.status; }, function(current) { $scope.pad.saving = !current.sync; }); }], templateUrl: 'pad.html' }; });
JavaScript
0
@@ -2470,32 +2470,201 @@ $timeout();%0A + %7D,%0A onRemove: function() %7B%0A $scope.pad.outline = this.editor.getAnnotationSet('paragraph/header');%0A $timeout();%0A %7D%0A
790cfb574ec43610cacbb6c32af6dcb358458250
change in browser
app/controllers/browser.js
app/controllers/browser.js
var args = arguments[0] || {}; var image = args.image; var video = args.video; if (video) { if (video.length < 18) { $.header.title.text = video; $.show.setUrl(video); } else { var x = video.substring(6, 21); $.header.title.text = x; $.show.setUrl(video); } } else { $.header.title.text = image; $.show.setHtml('<html><body> <img src=image /> </body></html>'); } $.show.addEventListener('load', function(e) { $.header.title.text = $.show.evalJS("document.title"); });
JavaScript
0.000001
@@ -208,9 +208,9 @@ ing( -6 +7 , 21
7417d3008779f126aa7ebcb41cbaaeeaace076d6
test escape
js/book.js
js/book.js
var number = 1; document.onkeydown = checkKey; //Buttons $(document).ready(function () { if(number == 1) { number++; getData(); } }); function animalNoise(text) { var hasGorilla = text.includes("Gorilla"); var hasTiger = text.includes("Tiger"); var hasPeacock = text.includes("Peacock"); var hasFlamingo = text.includes("Flamingo"); var hasGiraffe = text.includes("Giraffe"); var hasPolarBear = text.includes("Polar"); var hasBird = text.includes("Birds"); var hasElephant=text.includes("Elephants"); var hasCamel=text.includes("Camels"); var hasAnimals=text.includes("animals"); if(hasGorilla == true) { document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='../audio/Gorilla.mp3' type='audio/mpeg'></audio>"; } else if(hasTiger == true) { document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='../audio/Tiger.mp3' type='audio/mpeg'></audio>"; } else if(hasPeacock == true) { document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='../audio/Peacock.mp3' type='audio/mpeg'></audio>"; } else if(hasFlamingo == true) { document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='http://www.wildlifelands.com/wxs/flamingo.mp3' type='audio/mpeg'></audio>"; } else if(hasGiraffe == true) { document.getElementById('audio').innerHTML = "<audio id ='audiotag' controls autoplay><source src='../audio/Giraffe.mp3' type='audio/mpeg'></audio>"; } else if(hasPolarBear == true) { document.getElementById('audio').innerHTML = "<audio id ='audiotag' controls autoplay><source src='../audio/PolarBear.mp3' type='audio/mpeg'></audio>"; } else if(hasBird == true) { document.getElementById('audio').innerHTML = "<audio id ='audiotag' controls autoplay><source src='../audio/Parrot.mp3' type='audio/mpeg'></audio>"; } else if(hasElephant == true) { document.getElementById('audio').innerHTML = "<audio id ='audiotag' controls autoplay><source src='../audio/Elephant.mp3' type='audio/mpeg'></audio>"; } else if(hasCamel == true) { document.getElementById('audio').innerHTML = "<audio id ='audiotag' controls autoplay><source src='../audio/Camel.mp3' type='audio/mpeg'></audio>"; } else if(hasAnimals == true) { document.getElementById('audio').innerHTML = "<audio id ='audiotag' controls autoplay><source src='../audio/Zoo.mp3' type='audio/mpeg'></audio>"; } } function getData() { $.ajax({ dataType: "html", url: "http://tarheelreader.org/2015/03/30/at-the-zoo-10/" + number, crossDomain: true, error: function(xhr, textStatus, error){ console.log(xhr.statusText); console.log(textStatus); console.log(error); }, success: function(data) { if(number <= 12) { console.log("SUCCESS"); if(number == 2 || number == 12) { initial(); document.getElementById('enddiv').innerHTML= ""; } if(number == 2) { $("#imgcaption").addClass("bold"); } else { $("#imgcaption").removeClass("bold"); } //Reset audio document.getElementById('audio').innerHTML = ""; //Get and set tarheel reader content var text = getTRContent(data); //Add animal noises animalNoise(text); } else { //If last page then get rid of content and replace with the end clearPage(); $("#openbook").addClass("hidden"); document.getElementById('enddiv').innerHTML= "The End"; } } }) } function initial() { //Get rid of open book button and add back and next $("#openbook").addClass("hidden"); $("#image").removeClass("hidden"); } function getTRContent(data) { var imgurl = $(data).find('img.thr-pic').attr("src"); imgurl = "http://tarheelreader.org/" + imgurl; document.getElementById('img').src=imgurl; var text = $(data).find('p.thr-caption').text(); document.getElementById('imgcaption').innerHTML=text; return(text); } function clearPage() { //Add open button and hide next and back $("#openbook").removeClass("hidden"); $("#image").addClass("hidden"); } function checkKey(e) { e = e || window.event; if (e.keyCode == '38') { // up arrow document.getElementById('audiotag').currentTime=0; document.getElementById('audiotag').play(); } else if (e.keyCode == '40') { // down arrow var audio = document.getElementById('audiotag'); if(audio.paused) { audio.play(); } else { audio.pause(); } } else if (e.keyCode == '37') { // left arrow if(number > 2) { number--; getData(); } } else if (e.keyCode == '39' || e.keyCode == '32') { // right arrow if(number <= 12) { number++; getData(); } else { window.location.replace("../html/game.html"); } } } function right() { if(number <= 12) { number++; getData(); } else { window.location.replace("../html/game.html"); } } function left() { if(number > 2) { number--; getData(); } }
JavaScript
0.000003
@@ -4725,16 +4725,37 @@ == '32' + %7C%7C e.keyCode == '27' ) %7B%0A
fc141c05b526bc883b8db5dbe8619743f610abea
Fix dropping of images in image responses when a response exists
src/js/image-response.js
src/js/image-response.js
import Dropzone from 'react-dropzone'; import uuid from 'node-uuid'; import * as uploader from './uploader.js'; import {authorize} from './auth.js'; import LoginGate from './login-gate.js'; import storage from './storage.js'; import cond from 'lodash/fp/cond'; const style = { width: '100%', height: 200, borderWidth: 2, borderColor: '#666', borderStyle: 'dashed', borderRadius: 5, }; const activeStyle = { borderStyle: 'solid', backgroundColor: '#eee' }; const rejectStyle = { borderStyle: 'solid', backgroundColor: '#ffdddd' }; const ImageResponse = React.createClass({ getInitialState: function () { return { uploadedImageUrl: this.props.response }; }, componentDidMount: async function () { this.props.allowSaving(); this.props.addBeforeSaveHook(() => this.beforeSaveHook()); }, onDrop: async function ([file]) { if (this.state.isUploading) {return;} console.log('dropped', file); if (file && file.name) { this.setState({currentFile: file}); } }, async beforeSaveHook() { const file = this.state.currentFile if (file) { this.props.setSaveStatusMessage('Uploading...'); this.setState({isUploading: true}); const user = await authorize(); const ref = storage.child(`${user.uid}|${uuid.v4()}`); const uploadTask = ref.put(file); // Perform the image upload return new Promise((resolve, reject) => { uploadTask.on('state_changed', () => {}, error => { reject(error); }, () => { resolve(uploadTask.snapshot.downloadURL); }) }); } else { window.alert('Please choose a picture first'); } }, render: function () { let image; if (this.props.response) { image = ( <img className="pure-img" style={{maxHeight: '100%'}} src={this.props.response} /> ) } else if (this.state.currentFile) { image = ( <img className="pure-img" style={{maxHeight: '100%'}} src={this.state.currentFile.preview} /> ); } else { image = ( <div className="image-upload-message" style={{padding: '0 1.5em', textAlign: 'center'}}> Drag and drop a picture here or click/tap here to pick one </div> ); } let uploadedImage = this.state.uploadedImageUrl ? (<img src={this.state.uploadedImageUrl} />) : ''; return ( <div> <LoginGate> <Dropzone className="image-upload-dropzone" onDrop={this.onDrop} style={style} activeStyle={activeStyle} rejectStyle={rejectStyle} multiple={false}> {image} </Dropzone> </LoginGate> </div> ) } }); export default ImageResponse;
JavaScript
0.000086
@@ -793,22 +793,16 @@ aveHook( -() =%3E this.bef @@ -812,18 +812,69 @@ SaveHook -( ) +;%0A this.props.addAfterSaveHook(this.afterSaveHook );%0A %7D,%0A @@ -1736,16 +1736,116 @@ %7D%0A %7D,%0A + afterSaveHook(savePromise) %7B%0A savePromise.then(() =%3E this.setState(%7BcurrentFile: null%7D));%0A %7D,%0A render @@ -1888,29 +1888,32 @@ f (this. -props.respons +state.currentFil e) %7B%0A @@ -1997,30 +1997,41 @@ c=%7Bthis. -props.response +state.currentFile.preview %7D /%3E%0A @@ -2034,16 +2034,17 @@ %0A ) +; %0A %7D e @@ -2056,32 +2056,29 @@ f (this. -state.currentFil +props.respons e) %7B%0A @@ -2166,33 +2166,22 @@ his. -state.currentFile.preview +props.response %7D /%3E @@ -2180,33 +2180,32 @@ onse%7D /%3E%0A ) -; %0A %7D else %7B%0A
c1f10e6db36cecaeac086a43d4ba84804a82688f
add phpunit to gulp
gulpfile.js
gulpfile.js
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Sass | file for our application, as well as publishing vendor resources. | */ elixir(function(mix) { mix.sass('app.scss'); });
JavaScript
0.000001
@@ -466,18 +466,16 @@ (mix) %7B%0A - mix.sa @@ -488,14 +488,30 @@ p.scss') +%0A .phpUnit() ;%0A%7D);%0A
47f77c5c942cb2b645a12ba32e7f7bb4ae7f0da1
modify searchIndex class method
src/js/inverted-index.js
src/js/inverted-index.js
/* Inverted index class */ class InvertedIndex { /** * @constructor */ constructor() { this.indexMap = {}; } /** * createIndex * create an index map of an array of object * @param {Object} jsonContent an array of objects * @return {Object} */ createIndex(jsonContent) { if (!(this.isValidJson(jsonContent))) { return "invaid json"; } jsonContent.forEach((currentDocument, docId) => { let wordsInDocument = `${currentDocument.title} ${currentDocument.text}`; let currentDocumentTokens = this.getCleanTokens(wordsInDocument); this.indexBot(currentDocumentTokens, docId) }); } /** * getIndex * @return {Object} indexMap */ getIndex() { return this.indexMap; } /** * searchIndex * @param {String} terms string of terms to search for * @return {Object} An array of the search terms index */ searchIndex(terms) { let searchTermTokens = this.getCleanTokens(terms); let foundInDocuments = []; searchTermTokens.forEach((word) => { if (this.search(word)) { foundInDocuments.push(this.search(word)); } }) return foundInDocuments; } /* Helper methods */ /** * isValidJson * Check if all items in an array is a JSON valid. * @param {Object} jsonArray Array of JSON objects * @return {Boolean} */ isValidJson(jsonArray) { if (typeof jsonArray !== "object" || jsonArray.length === 0) { return false } try { jsonArray.forEach((currentBook) => { if (!(currentBook.hasOwnProperty("title") && currentBook.hasOwnProperty("text"))) { return false; } }); return true; } catch (err) { return false } } /** * getCleanTokens * sanitizes and splits a string * @param {String} string string to sanitize and tokenize * @return {Object} An array of clean splitted string */ getCleanTokens(string) { let invalidCharaters = /[^a-z0-9\s]/gi; return string.replace(invalidCharaters, " ") .toLowerCase() .split(" ") .filter((word) => { return Boolean(word); }); } /** * indexBot * maps an arrays their it docs index * @param {Object} tokens An array of words */ indexBot(tokens, docId) { tokens.forEach((token) => { if (token in this.indexMap) { if (this.indexMap[token].indexOf(docId) === -1) { this.indexMap[token].push(docId); } } else { this.indexMap[token] = [docId]; } }); } /** * search * returns an array containing document id in which a search term exist * @param {String} searchTerm A single search term string * @return {Object} An array containing index of a search term */ search(searchTerm) { let indexDatabase = this.indexMap; if (indexDatabase.hasOwnProperty(searchTerm)) { return indexDatabase[searchTerm]; } else { return false; } } }
JavaScript
0
@@ -1,9 +1,8 @@ -%0A /* Inver @@ -635,17 +635,16 @@ docId)%0A -%0A %7D);%0A @@ -985,29 +985,25 @@ let -foundInDocuments = %5B%5D +searchResult = %7B%7D ;%0A%0A @@ -1085,30 +1085,29 @@ -foundInDocuments.push( +searchResult%5Bword%5D = this @@ -1119,17 +1119,16 @@ ch(word) -) ;%0A @@ -1151,24 +1151,69 @@ urn -foundInDocuments +Object.keys(searchResult).length === 0 ? false : searchResult ;%0A @@ -3016,8 +3016,500 @@ %7D%0A %7D%0A%7D%0A +%0Alet books = %5B%0A %7B%0A %22title%22: %22Alice in Wonderland%22,%0A %22text%22: %22Alice falls into a rabbit hole and enters a world full of imagination.%22%0A %7D,%0A%0A %7B%0A %22title%22: %22The Lord of the Rings: The Fellowship of the Ring.%22,%0A %22text%22: %22An unusual alliance of man, elf, dwarf, wizard and hobbit seek to destroy a powerful ring.%22%0A %7D%0A%5D%0A%0Alet myInvertedIndex = new InvertedIndex();%0AmyInvertedIndex.createIndex(books);%0AmyInvertedIndex.getIndex();%0Aconsole.log(myInvertedIndex.searchIndex(%22sfdd .alice%22))%0A
47eca745ea7f0d60a62f4b9f2eb8c8f7909a035d
TEST bower
app/index.js
app/index.js
(function () { 'use strict'; var util = require('util'), path = require('path'), slug = require('slug'), fs = require('fs'), yeoman = require('yeoman-generator'), chalk = require('chalk'); var ScaffoldGenerator = module.exports = function ScaffoldGenerator(args, options) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(ScaffoldGenerator, yeoman.generators.Base); ScaffoldGenerator.prototype.init = function init () { var cb = this.async(); this.log(chalk.cyan('\t \t ___ __ __ _ _ ')); this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |')); this.log(chalk.cyan('\t \t \\__ \\/ _/ _` | _| _/ _ \\ / _` |')); this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_|')); this.log('\n'); this.log(chalk.cyan('\t \t [ Welcome to Scaffold Generator ] \n \n')); this.log(chalk.green('I will guide you to generate your best workflow. Come with me... \n \n')); cb(); }; ScaffoldGenerator.prototype.askFor = function askFor () { var cb = this.async(), prompts = [{ name: 'projectName', message: 'What is the name of your project?', validate: function(input) { var done = this.async(); if (input.trim() === '') { done('You need to provide a name for your project'); return; } done(true); } }, { name: 'projectDescription', message: 'What is the description?', validate: function(input) { var done = this.async(); if (input.trim() === '') { done('You need to provide a description'); return; } done(true); } }, { name: 'projectMember', message: 'Which members involved in the project?', validate: function(input) { var done = this.async(); if (input.trim() === '') { done('You need to provide which members'); return; } done(true); } }, { type: 'list', name: 'projectType', message: 'What kind of project?', choices: ['Web Only', 'Mobile Only', 'Responsive', 'Wordpress'], default: 0 }]; this.prompt(prompts, function (props) { for(var item in props) { this[item] = props[item]; } cb(); }.bind(this)); }; ScaffoldGenerator.prototype.getScaffoldCore = function getScaffoldCore () { var cb = this.async(); this.log(chalk.green('\n \n Downloading core of scaffold')); this.tarball('https://github.com/marcosmoura/scaffold/archive/v2.zip', '.', cb); }; ScaffoldGenerator.prototype.processPackage = function processPackage () { var cb = this.async(), pkgPath = path.join(this.env.cwd, 'package.json'), pkg = JSON.parse(this.readFileAsString(pkgPath)); pkg.projectName = this.projectName; pkg.name = slug(this.projectName.toLowerCase()); pkg.description = this.projectDescription; pkg.developers = this.projectMember; var dev = this.projectMember.split(','), devList = []; for(var member in dev) { devList.push({ 'name': dev[member].trim() }); } pkg.author = devList; fs.unlink(pkgPath); this.write(pkgPath, JSON.stringify(pkg, null, 2)); cb(); }; ScaffoldGenerator.prototype.processGruntFile = function processGruntFile () { var cb = this.async(); //var tasksPath = path.join(this.env.cwd, 'grunt/options'); if (this.projectType === 'Mobile Only') { this.log(chalk.green('\n \n Downloading mobile version')); this.tarball('https://github.com/marcosmoura/scaffold-mobile/archive/master.zip', 'dev/', cb); } else if (this.projectType === 'Web Only') { this.log(chalk.green('\n \n Downloading web version')); this.tarball('https://github.com/marcosmoura/scaffold-web/archive/master.zip', 'dev/', cb); } else if (this.projectType === 'Responsive') { this.log(chalk.green('\n \n Downloading responsive version')); this.tarball('https://github.com/marcosmoura/scaffold-mobile/archive/master.zip', 'dev/', cb); } }; ScaffoldGenerator.prototype.copyBower = function copyBower () { var cb = this.async(); this.dest.copy('dev/bower.json', 'bower.json'); this.spawnCommand('grunt', ['bower']); }; ScaffoldGenerator.prototype.garbageRemoval = function garbageRemoval () { var cb = this.async(), devPath = path.join(this.env.cwd, 'dev'); fs.unlink(path.join(devPath, 'LICENSE')); fs.unlink(path.join(devPath, 'README.md')); cb(); }; })();
JavaScript
0.000001
@@ -5278,56 +5278,8 @@ n'); -%0A%0A this.spawnCommand('grunt', %5B'bower'%5D); %0A
cf229ff0071fb24029f27683dc62462717f73ca6
Correcting the spelling of the GSIM groups query
src/js/sparql/queries.js
src/js/sparql/queries.js
//TODO we might need to filter on the language, but for now english seems to be //the only language available /** * Builds the query that retrieve the GSBPM overlook */ const GSBPMDescription = () => ` PREFIX gsbpm: <http://rdf.unece.org/models/gsbpm#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> select ?phase ?phaseLabel ?subprocess ?subprocessLabel ?phaseCode ?subprocessCode where { ?phase a gsbpm:Phase ; skos:narrower ?subprocess ; OPTIONAL { ?phase skos:prefLabel ?phaseLabel } OPTIONAL { ?subprocess skos:prefLabel ?subprocessLabel } OPTIONAL { ?phase skos:notation ?phaseCode } OPTIONAL { ?subprocess skos:notation ?subprocessCode } } ` const services = () => ` PREFIX cspa:<http://rdf.unece.org/models/cspa#> PREFIX gsbpm: <http://rdf.unece.org/models/gsbpm#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> SELECT distinct ?service ?label WHERE { ?service a cspa:package . ?service cspa:label ?label } ` const serviceDetails = service => ` PREFIX cspa:<http://rdf.unece.org/models/cspa#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> SELECT ?label WHERE { <${service}> cspa:label ?label } ` //TODO investigate, we shouldn't need DISTINCT, should we ? const serviceSubprocesses = service => ` PREFIX cspa:<http://rdf.unece.org/models/cspa#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> SELECT DISTINCT ?sub ?label WHERE { <${service}> cspa:hasPackageDefinition ?definition . ?definition cspa:aimsAt ?function . ?function cspa:gsbpmSubProcess ?sub . ?sub skos:prefLabel ?label } ` /* Retrieve all GSBPM subprocesses */ const subprocesses = () => ` PREFIX gsbpm: <http://rdf.unece.org/models/gsbpm#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> SELECT ?sub ?label ?code WHERE { ?sub a gsbpm:SubProcess ; skos:prefLabel ?label ; skos:notation ?code } ORDER BY ?code ` const serviceInputs = service => ` PREFIX cspa: <http://rdf.unece.org/models/cspa#> PREFIX gsbpm: <http://rdf.unece.org/models/gsbpm#> PREFIX gsim: <http://rdf.unece.org/models/gsim#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT DISTINCT ?gsimClass ?label ?definition WHERE { <${service}> a cspa:package ; cspa:label ?servicelabel ; cspa:hasPackageDefinition ?pckgDefinition . ?pckgDefinition cspa:definitionHasInput ?input . ?input cspa:gsimInput ?gsimClass . ?gsimClass rdfs:label ?label . ?gsimClass gsim:classDefinition ?definition } ` const serviceOutputs = service => ` PREFIX cspa: <http://rdf.unece.org/models/cspa#> PREFIX gsbpm: <http://rdf.unece.org/models/gsbpm#> PREFIX gsim: <http://rdf.unece.org/models/gsim#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT DISTINCT ?gsimClass ?label ?definition WHERE { <${service}> a cspa:package ; cspa:label ?servicelabel ; cspa:hasPackageDefinition ?pckgDefinition . ?pckgDefinition cspa:definitionHasOutput ?input . ?input cspa:gsimOutput ?gsimClass . ?gsimClass rdfs:label ?label . ?gsimClass gsim:classDefinition ?definition } ` const GSIMgroups = () => ` PREFIX gsim:<http://rdf.unece.org/models/gsim#> PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> SELECT ?group ?label WHERE { ?group rdfs:subClassOf gsim:GSIMObject . ?group rdfs:label ?label } ` /* Retrieve all GSIM classes */ const GSIMClasses = () => ` PREFIX gsim: <http://rdf.unece.org/models/gsim#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> SELECT ?GSIMClass ?label ?definition WHERE { ?GSIMClass rdfs:subClassOf gsim:Concepts ; gsim:classDefinition ?definition ; rdfs:label ?label } ` const gsimInputServices = gsimClass => ` PREFIX cspa: <http://rdf.unece.org/models/cspa#> PREFIX gsbpm: <http://rdf.unece.org/models/gsbpm#> PREFIX gsim: <http://rdf.unece.org/models/gsim#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT DISTINCT ?service ?label WHERE { ?service a cspa:package ; cspa:label ?label ; cspa:hasPackageDefinition ?pckgDefinition . ?pckgDefinition cspa:definitionHasInput ?input . ?input cspa:gsimInput <${gsimClass}> } ` const serviceBySubProcess = (subprocess) => ` PREFIX gsbpm: <http://rdf.unece.org/models/gsbpm#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX cspa:<http://rdf.unece.org/models/cspa#> SELECT ?service ?label WHERE { ?function cspa:gsbpmSubProcess <${subprocess}> . ?definition cspa:aimsAt ?function . ?service cspa:hasPackageDefinition ?definition . ?service cspa:label ?label } ` export default { GSBPMDescription, services, serviceDetails, serviceSubprocesses, serviceInputs, serviceOutputs, gsimInputServices, subprocesses, GSIMClasses, serviceBySubProcess, GSIMGroups }
JavaScript
0.999993
@@ -3273,17 +3273,17 @@ nst GSIM -g +G roups =
c7bf0c5c03a5c7716a39a0f2f5a11681eedbac7f
Fix prototype used for selector matcher function
src/js/utils/elements.js
src/js/utils/elements.js
// ========================================================================== // Element utils // ========================================================================== import is from './is'; import { extend } from './objects'; // Wrap an element export function wrap(elements, wrapper) { // Convert `elements` to an array, if necessary. const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the // first element (see `child` below). Array.from(targets) .reverse() .forEach((element, index) => { const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling. const parent = element.parentNode; const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current // parent). child.appendChild(element); // If the element had a sibling, insert the wrapper before // the sibling to maintain the HTML structure; otherwise, just // append it to the parent. if (sibling) { parent.insertBefore(child, sibling); } else { parent.appendChild(child); } }); } // Set attributes export function setAttributes(element, attributes) { if (!is.element(element) || is.empty(attributes)) { return; } // Assume null and undefined attributes should be left out, // Setting them would otherwise convert them to "null" and "undefined" Object.entries(attributes) .filter(([, value]) => !is.nullOrUndefined(value)) .forEach(([key, value]) => element.setAttribute(key, value)); } // Create a DocumentFragment export function createElement(type, attributes, text) { // Create a new <element> const element = document.createElement(type); // Set all passed attributes if (is.object(attributes)) { setAttributes(element, attributes); } // Add text node if (is.string(text)) { element.innerText = text; } // Return built element return element; } // Inaert an element after another export function insertAfter(element, target) { if (!is.element(element) || !is.element(target)) { return; } target.parentNode.insertBefore(element, target.nextSibling); } // Insert a DocumentFragment export function insertElement(type, parent, attributes, text) { if (!is.element(parent)) { return; } parent.appendChild(createElement(type, attributes, text)); } // Remove element(s) export function removeElement(element) { if (is.nodeList(element) || is.array(element)) { Array.from(element).forEach(removeElement); return; } if (!is.element(element) || !is.element(element.parentNode)) { return; } element.parentNode.removeChild(element); } // Remove all child elements export function emptyElement(element) { if (!is.element(element)) { return; } let { length } = element.childNodes; while (length > 0) { element.removeChild(element.lastChild); length -= 1; } } // Replace element export function replaceElement(newChild, oldChild) { if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) { return null; } oldChild.parentNode.replaceChild(newChild, oldChild); return newChild; } // Get an attribute object from a string selector export function getAttributesFromSelector(sel, existingAttributes) { // For example: // '.test' to { class: 'test' } // '#test' to { id: 'test' } // '[data-test="test"]' to { 'data-test': 'test' } if (!is.string(sel) || is.empty(sel)) { return {}; } const attributes = {}; const existing = extend({}, existingAttributes); sel.split(',').forEach(s => { // Remove whitespace const selector = s.trim(); const className = selector.replace('.', ''); const stripped = selector.replace(/[[\]]/g, ''); // Get the parts and value const parts = stripped.split('='); const [key] = parts; const value = parts.length > 1 ? parts[1].replace(/["']/g, '') : ''; // Get the first character const start = selector.charAt(0); switch (start) { case '.': // Add to existing classname if (is.string(existing.class)) { attributes.class = `${existing.class} ${className}`; } else { attributes.class = className; } break; case '#': // ID selector attributes.id = selector.replace('#', ''); break; case '[': // Attribute selector attributes[key] = value; break; default: break; } }); return extend(existing, attributes); } // Toggle hidden export function toggleHidden(element, hidden) { if (!is.element(element)) { return; } let hide = hidden; if (!is.boolean(hide)) { hide = !element.hidden; } // eslint-disable-next-line no-param-reassign element.hidden = hide; } // Mirror Element.classList.toggle, with IE compatibility for "force" argument export function toggleClass(element, className, force) { if (is.nodeList(element)) { return Array.from(element).map(e => toggleClass(e, className, force)); } if (is.element(element)) { let method = 'toggle'; if (typeof force !== 'undefined') { method = force ? 'add' : 'remove'; } element.classList[method](className); return element.classList.contains(className); } return false; } // Has class name export function hasClass(element, className) { return is.element(element) && element.classList.contains(className); } // Element matches selector export function matches(element, selector) { const prototype = { Element }; function match() { return Array.from(document.querySelectorAll(selector)).includes(this); } const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match; return method.call(element, selector); } // Find all elements export function getElements(selector) { return this.elements.container.querySelectorAll(selector); } // Find a single element export function getElement(selector) { return this.elements.container.querySelector(selector); } // Set focus and tab focus class export function setFocus(element = null, tabFocus = false) { if (!is.element(element)) { return; } // Set regular focus element.focus({ preventScroll: true }); // If we want to mimic keyboard focus via tab if (tabFocus) { toggleClass(element, this.config.classNames.tabFocus); } }
JavaScript
0
@@ -6170,18 +6170,16 @@ pe = - %7B Element %7D;%0A @@ -6174,18 +6174,26 @@ Element - %7D +.prototype ;%0A%0A f
340ac1cb72287947d0840b1234b2b0804df0f3c0
Change base_url to _plugins/crate-admin
app/index.js
app/index.js
require.config({ baseUrl: '/_plugin/ca', paths: { // Libraries backbone: 'bower_components/backbone/backbone', bootstrap: 'bower_components/bootstrap/dist/js/bootstrap', jquery: 'bower_components/jquery/dist/jquery', text: 'bower_components/requirejs-text/text', underscore: 'bower_components/underscore/underscore', spin: 'bower_components/ladda-bootstrap/dist/spin', ladda: 'bower_components/ladda-bootstrap/dist/ladda', // App app: 'js/app', base: 'js/base', Overview: 'js/overview', SQL: 'js/sql', Status: 'js/status', Console: 'js/console' }, shim: { backbone: { deps: ['underscore', 'jquery'], exports: "Backbone" }, bootstrap: { deps: ['jquery'] }, underscore: { exports: '_' } } }); define([ 'jquery', 'app'], function ($, app) { // Treat the jQuery ready function as the entry point to the application. // Inside this function, kick-off all initialization, everything up to this // point should be definitions. $(function () { app.start(); }); });
JavaScript
0.000001
@@ -34,17 +34,26 @@ plugin/c -a +rate-admin ',%0A%0A
49628112767a120ea9a72379c223b96f000bc076
change json util
src/jsonUtil/jsonUtil.js
src/jsonUtil/jsonUtil.js
angular.module('cgGrid.jsonUtil', ['cgGrid.lodash']) .factory('JsonUtil', function (_) { function getKeys(json){ return _.keys(json); } function getHeaders(size,type){ return _.range(size) .map(function(){ return type }) } function transformJsonArray(jsonArray) { var gridData = _.map(jsonArray, function (obj, index) { return { id: ++index, data: _.values(obj) } }); var keys=getKeys(jsonArray[0]); var transformedData={ headings:keys.join(','), filters:getHeaders(keys.length,'#text_filter').join(','), sortings:getHeaders(keys.length,'str').join(','), data:{rows:gridData} }; return transformedData; } return { jsonToArray: transformJsonArray } });
JavaScript
0.00404
@@ -46,18 +46,16 @@ dash'%5D)%0A - .facto @@ -85,25 +85,24 @@ (_) %7B%0A%0A -%09 function get @@ -111,24 +111,25 @@ ys(json) + %7B%0A + -%09%09 + return _ @@ -145,24 +145,23 @@ n);%0A -%09 %7D%0A +%0A -%09 function @@ -181,22 +181,24 @@ ize, + type) + %7B%0A%0A + -%09%09 + retu @@ -218,18 +218,20 @@ ze)%0A + -%09%09 + .map(fun @@ -239,19 +239,24 @@ tion + () + %7B%0A + -%09%09%09 + retu @@ -271,34 +271,24 @@ -%09%09%7D)%0A%0A -%09 %7D +)%0A %0A -%09%0A +%7D %0A%0A%0A - @@ -331,30 +331,24 @@ y) %7B%0A%0A - - var gridData @@ -391,24 +391,16 @@ ndex) %7B%0A - @@ -407,17 +407,16 @@ return %7B - id: ++in @@ -443,17 +443,16 @@ obj) - %7D%0A @@ -451,25 +451,13 @@ - - %7D);%0A%0A - @@ -466,17 +466,19 @@ var keys -= + = getKeys( @@ -492,22 +492,16 @@ ay%5B0%5D);%0A - va @@ -517,17 +517,19 @@ rmedData -= + = %7B%0A @@ -530,21 +530,16 @@ - %09 headings @@ -539,16 +539,17 @@ eadings: + keys.joi @@ -568,21 +568,16 @@ - - %09 filters: getH @@ -572,16 +572,17 @@ filters: + getHeade @@ -596,16 +596,17 @@ .length, + '#text_f @@ -632,21 +632,16 @@ - -%09 sortings @@ -641,16 +641,17 @@ ortings: + getHeade @@ -665,16 +665,17 @@ .length, + 'str').j @@ -696,24 +696,21 @@ - - %09 data: + %7Brows: + grid @@ -715,22 +715,16 @@ idData%7D%0A - %7D; @@ -726,30 +726,24 @@ %7D;%0A - - return trans @@ -754,20 +754,16 @@ edData;%0A - %7D%0A%0A @@ -765,28 +765,24 @@ %7D%0A%0A - - return %7B jsonToA @@ -773,17 +773,16 @@ return %7B - jsonToAr @@ -808,14 +808,12 @@ rray - %7D%0A - %7D); +%0A
ab0a8e590c9bfe55a70f5196003910b9d4db51b2
add isCreator
scripts/services/task.js
scripts/services/task.js
'use strict'; app.factory('Task', function(FURL, $firebase, Auth) { var ref = new Firebase(FURL); var tasks = $firebase(ref.child('task')).$asArray(); var user = Auth.user; var Task = { all: tasks, getTask: function(taskId) { return $firebase(ref.child('tasks').child(taskId)); }, createTask: function(task) { task.datetime = Firebase.ServerValue.TIMESTAMP; return tasks.$add(task); }, editTask: function(task) { var t = this.getTask(task.$id); return t.$update({title: task.title, description: task.description, total: task.total}); }, cancelTask: function(taskId) { var t = this.getTask(taskId); return t.$update({status: "cancelled"}); }, }; });
JavaScript
0.000259
@@ -690,16 +690,118 @@ ;%0A%09%09%7D,%0A%0A +%09%09isCreator: function(task) %7B%09%09%09%0A%09%09%09return (user && user.provider && user.uid === task.poster);%0A%09%09%7D,%0A%0A %09%7D;%0A%0A%0A%7D)
e11d932d7aa6e612cb406c911c19e4c65871edf1
update copyright dates from daily grunt work
js/VerticalAquaRadioButtonGroup.js
js/VerticalAquaRadioButtonGroup.js
// Copyright 2020, University of Colorado Boulder /** * VerticalAquaRadioButtonGroup is a convenience class for creating a vertical AquaRadioButtonGroup. * * @author Chris Malley (PixelZoom, Inc.) */ define( require => { 'use strict'; // modules const AquaRadioButtonGroup = require( 'SUN/AquaRadioButtonGroup' ); const merge = require( 'PHET_CORE/merge' ); const sun = require( 'SUN/sun' ); class VerticalAquaRadioButtonGroup extends AquaRadioButtonGroup { /** * @param {Property} property * @param {Object[]} items - see AquaRadioButtonGroup * @param {Object} [options] */ constructor( property, items, options ) { assert && assert( !options || options.orientation === undefined, 'VerticalAquaRadioButtonGroup sets orientation' ); super( property, items, merge( { orientation: 'vertical' }, options ) ); } } return sun.register( 'VerticalAquaRadioButtonGroup', VerticalAquaRadioButtonGroup ); } );
JavaScript
0
@@ -6,16 +6,21 @@ pyright +2013- 2020, Un
77b40a38e5e314b80509a8752d923db4dd771de3
Adding the into keyword
scripts/shBrushCSharp.js
scripts/shBrushCSharp.js
;(function() { // CommonJS SyntaxHighlighter = SyntaxHighlighter || (typeof require !== 'undefined'? require('shCore').SyntaxHighlighter : null); function Brush() { var keywords = 'abstract as base bool break byte case catch char checked class const ' + 'continue decimal default delegate do double else enum event explicit volatile ' + 'extern false finally fixed float for foreach get goto if implicit in int ' + 'interface internal is lock long namespace new null object operator out ' + 'override params private protected public readonly ref return sbyte sealed set ' + 'short sizeof stackalloc static string struct switch this throw true try ' + 'typeof uint ulong unchecked unsafe ushort using virtual void while var ' + 'from group by select'; function fixComments(match, regexInfo) { var css = (match[0].indexOf("///") == 0) ? 'color1' : 'comments' ; return [new SyntaxHighlighter.Match(match[0], match.index, css)]; } this.regexList = [ { regex: SyntaxHighlighter.regexLib.singleLineCComments, func : fixComments }, // one line comments { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments { regex: /@"(?:[^"]|"")*"/g, css: 'string' }, // @-quoted strings { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings { regex: /^\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // c# keyword { regex: /\bpartial(?=\s+(?:class|interface|struct)\b)/g, css: 'keyword' }, // contextual keyword: 'partial' { regex: /\byield(?=\s+(?:return|break)\b)/g, css: 'keyword' } // contextual keyword: 'yield' ]; this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); }; Brush.prototype = new SyntaxHighlighter.Highlighter(); Brush.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.brushes.CSharp = Brush; // CommonJS typeof(exports) != 'undefined' ? exports.Brush = Brush : null; })();
JavaScript
0.999889
@@ -784,16 +784,21 @@ roup by +into select'; @@ -2214,9 +2214,8 @@ ;%0A%7D)();%0A -%0A
a5f3b0165c918f78d0a7f06d2e8e5e4cde9c86d5
Fix a typo in test helper. (#13161)
testing/test-helper.js
testing/test-helper.js
/** * Copyright 2016 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 {poll} from './iframe'; import {xhrServiceForTesting} from '../src/service/xhr-impl'; import { getService, getServiceForDoc, registerServiceBuilder, registerServiceBuilderForDoc, resetServiceForTesting, } from '../src/service'; import {WindowInterface} from '../src/window-interface'; export function stubService(sandbox, win, serviceId, method) { // Register if not already registered. registerServiceBuilder(win, serviceId, function() { return { [method]: () => {}, }; }); const service = getService(win, serviceId); return sandbox.stub(service, method); } export function stubServiceForDoc(sandbox, ampdoc, serviceId, method) { // Register if not already registered. registerServiceBuilderForDoc(ampdoc, serviceId, function() { return { [method]: () => {}, }; }); const service = getServiceForDoc(ampdoc, serviceId); return sandbox.stub(service, method); } export function mockServiceForDoc(sandbox, ampdoc, serviceId, methods) { resetServiceForTesting(ampdoc.win, 'viewer'); const impl = {}; methods.forEach(method => { impl[method] = () => {}; }); registerServiceBuilderForDoc(ampdoc, serviceId, () => impl); const mock = {}; methods.forEach(method => { mock[method] = sandbox.stub(impl, method); }); return mock; } export function mockWindowInterface(sandbox) { const methods = Object.getOwnPropertyNames(WindowInterface) .filter(p => typeof WindowInterface[p] === 'function'); const mock = {}; methods.forEach(method => { mock[method] = sandbox.stub(WindowInterface, method); }); return mock; } /** * Resolves a promise when a spy has been called a configurable number of times. * @param {!Object} spy * @param {number=} opt_callCount * @return {!Promise} */ export function whenCalled(spy, opt_callCount = 1) { return poll(`Spy was called ${opt_callCount} times`, () => spy.callCount === opt_callCount); } /** * Asserts that the given element is only visible to screen readers. * @param {!Element} node */ export function assertScreenReaderElement(element) { expect(element).to.exist; expect(element.classList.contains('i-amphtml-screen-reader')).to.be.true; const win = element.ownerDocument.defaultView; const computedStyle = win.getComputedStyle(element); expect(computedStyle.getPropertyValue('position')).to.equal('fixed'); expect(computedStyle.getPropertyValue('top')).to.equal('0px'); expect(computedStyle.getPropertyValue('left')).to.equal('0px'); expect(computedStyle.getPropertyValue('width')).to.equal('4px'); expect(computedStyle.getPropertyValue('height')).to.equal('4px'); expect(computedStyle.getPropertyValue('opacity')).to.equal('0'); expect(computedStyle.getPropertyValue('overflow')).to.equal('hidden'); expect(computedStyle.getPropertyValue('border')).to.contain('none'); expect(computedStyle.getPropertyValue('margin')).to.equal('0px'); expect(computedStyle.getPropertyValue('padding')).to.equal('0px'); expect(computedStyle.getPropertyValue('display')).to.equal('block'); expect(computedStyle.getPropertyValue('visibility')).to.equal('visible'); } ///////////////// // Request Bank // A server side temporary request storage which is useful for testing // browser sent HTTP requests. ///////////////// /** @const {string} */ const REQUEST_URL = '//localhost:9876/amp4test/request-bank/'; /** * Append user agent to request-bank deposit/withdraw IDs to avoid * cross-browser race conditions when testing in Saucelabs. * @const {string} */ const userAgent = encodeURIComponent(window.navigator.userAgent); export function depositRequestUrl(id) { return `${REQUEST_URL}deposit/${id}-${userAgent}`; } export function withdrawRequest(win, id) { const url = `${REQUEST_URL}withdraw/${id}-${userAgent}`; return xhrServiceForTesting(win).fetchJson(url, { method: 'GET', ampCors: false, credentials: 'omit', }).then(res => res.json()); }
JavaScript
0.999534
@@ -1664,16 +1664,17 @@ in, -'viewer' +serviceId );%0A
0bee7fc7398a1c4958b8e14a4f0f1b239c6dd7f3
Remove unneeded line
test/tdd.js
test/tdd.js
var assert = require('assert'), factorial = require('../index'); suite('Test', function (){ setup(function (){ // Create any objects that we might need }); suite('#factorial()', function (){ test('equals 1 for sets of zero length', function (){ assert.equal(1, factorial(0)); }); test('equals 1 for sets of length one', function (){ assert.equal(1, factorial(1)); }); test('equals 2 for sets of length two', function (){ assert.equal(2, factorial(2)); }); test('equals 6 for sets of length three', function (){ assert.equal(6, factorial(3)); }); }); });
JavaScript
0.001768
@@ -63,17 +63,16 @@ dex');%0A%0A -%0A suite('T
3d00f81e6760dd3f740bbd34392ce5b3ca1f6008
Refactor benchmark
benchmark/index.js
benchmark/index.js
'use strict'; var Retext, retext, keywords, source, sourceSmall, sourceMedium, tiny, small, medium, wordCount, sentenceCount, paragraphCount; Retext = require('retext'); keywords = require('..'); /* First paragraph on term extraction from Wikipedia: * http://en.wikipedia.org/wiki/Terminology_extraction */ source = 'Terminology mining, term extraction, term recognition, or ' + 'glossary extraction, is a subtask of information extraction. ' + 'The goal of terminology extraction is to automatically extract ' + 'relevant terms from a given corpus.\n\n'; /* Test data */ sourceSmall = Array(11).join(source); sourceMedium = Array(11).join(sourceSmall); retext = new Retext().use(keywords); tiny = retext.parse(source); small = retext.parse(sourceSmall); medium = retext.parse(sourceMedium); wordCount = sentenceCount = paragraphCount = 0; tiny.visitType(tiny.WORD_NODE, function () { wordCount++; }); tiny.visitType(tiny.SENTENCE_NODE, function () { sentenceCount++; }); tiny.visitType(tiny.PARAGRAPH_NODE, function () { paragraphCount++; }); if (wordCount !== 30) { console.error('Word count should be 300!'); } if (sentenceCount !== 2) { console.error('Sentence count should be 300!'); } if (paragraphCount !== 1) { console.error('Paragraph count should be 300!'); } /* Benchmarks */ suite('Finding keywords in English', function () { bench('small (10 paragraphs, 20 sentences, 300 words)', function () { small.keywords(); }); bench('medium (100 paragraphs, 200 sentences, 3000 words)', function () { medium.keywords(); }); }); /* Benchmarks */ suite('Finding keyphrases in English', function () { bench('small (10 paragraphs, 20 sentences, 300 words)', function () { small.keyphrases(); }); bench('medium (100 paragraphs, 200 sentences, 3000 words)', function () { medium.keyphrases(); }); });
JavaScript
0
@@ -12,146 +12,58 @@ ';%0A%0A -var Retext, retext, keywords, source,%0A sourceSmall, sourceMedium,%0A tiny, small, medium +/**%0A * Dependencies.%0A */%0A%0Avar Retext ,%0A +key word -Count, sentenceCount, paragraphCount +s ;%0A%0AR @@ -118,16 +118,36 @@ .');%0A%0A/* +*%0A * Fixtures.%0A *%0A * First p @@ -192,16 +192,21 @@ edia:%0A * +%0A * http:// @@ -258,16 +258,65 @@ */%0A +%0Avar source,%0A sourceSmall,%0A sourceMedium;%0A%0A source = 'Te @@ -311,16 +311,20 @@ source = +%0A 'Termin @@ -573,24 +573,8 @@ ';%0A%0A -/* Test data */%0A sour @@ -652,16 +652,49 @@ mall);%0A%0A +/**%0A * Retext.%0A */%0A%0Avar retext;%0A%0A retext = @@ -727,269 +727,119 @@ );%0A%0A -tiny = retext.parse(source);%0Asmall = retext.parse(sourceSmall);%0Amedium = retext.parse(sourceMedium);%0A%0AwordCount = sentenceCount = paragraphCount = 0;%0A%0Atiny.visitType(tiny.WORD_NODE, function () %7B%0A wordCount++;%0A%7D);%0A%0Atiny.visitType(tiny.SENTENCE_NODE, +/**%0A * Benchmarks.%0A */%0A%0Asuite('A big section (10 paragraphs)', function () %7B%0A var tree;%0A%0A before( function () @@ -834,26 +834,29 @@ function - ( +next ) %7B%0A sentence @@ -851,370 +851,136 @@ -sentenceCount++;%0A%7D);%0A%0Atiny.visitType(tiny.PARAGRAPH_NODE, function () %7B%0A paragraphCount++;%0A%7D);%0A%0Aif (wordCount !== 30) %7B%0A console.error('Word count should be 300!');%0A%7D%0A%0Aif (sentenceCount !== 2) %7B%0A console.error('Sentence count should be 300!');%0A%7D%0A%0Aif (paragraphCount !== 1) %7B%0A console.error('Paragraph count should be 300!');%0A%7D%0A%0A/* Benchmarks */%0Asuite + retext.parse(sourceSmall, function (err, node) %7B%0A tree = node;%0A next();%0A %7D);%0A %7D);%0A%0A bench ('Fi @@ -993,27 +993,16 @@ keywords - in English ', funct @@ -1018,174 +1018,67 @@ -bench('small (10 paragraphs, 20 sentences, 300 words)', function () %7B%0A small.keywords();%0A %7D);%0A%0A bench('medium (100 paragraphs, 200 sentences, 3000 words) + tree.keywords();%0A %7D);%0A%0A bench('Finding keyphrases ', f @@ -1102,22 +1102,22 @@ -medium.keyword +tree.keyphrase s(); @@ -1134,135 +1134,256 @@ );%0A%0A -/* Benchmarks */%0Asuite('Finding keyphrases in English', function () %7B%0A bench('small (10 paragraphs, 20 sentences, 300 +suite('A big article (100 paragraphs)', function () %7B%0A var tree;%0A%0A before(function(next) %7B%0A retext.parse(sourceMedium, function (err, node) %7B%0A tree = node;%0A next();%0A %7D);%0A %7D);%0A%0A bench('Finding key words -) ', f @@ -1407,23 +1407,20 @@ -small.keyphrase +tree.keyword s(); @@ -1444,58 +1444,26 @@ ch(' -medium (100 paragraphs, 200 sentences, 3000 words) +Finding keyphrases ', f @@ -1487,14 +1487,12 @@ -medium +tree .key
c3eb6982ba519a93304dce4b5666e5b009adb586
Set correct moduleName and run this.askFor()
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var shell = require('shelljs'); var npmName = require('npm-name'); var yeoman = require('yeoman-generator'); var SimpleNodePackageGenerator = module.exports = function SimpleNodePackageGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'], bower: false }); }); this.pkg = require('../package.json'); this.cli = false; this.name = this.user.git.name; this.email = this.user.git.email; this.website = shell.exec('git config --get user.website', { silent: true }).output.trim(); this.githubUsername = void 0; this.user.github.username(function(err, username){ this.githubUsername = username; }.bind(this)); }; util.inherits(SimpleNodePackageGenerator, yeoman.generators.Base); SimpleNodePackageGenerator.prototype.prompting = function prompting() { var done = this.async(); var prompts = [{ name: 'github', message: 'What is your GitHub username?', when: function(){ return this.githubUsername; } }, { name: 'moduleName', message: 'What is the name of your module?', default: path.basename(process.cwd()) }, { type: 'confirm', name: 'pkgName', message: 'The name above already exists on npm, choose another?', default: true, when: function(answers) { var done = this.async(); npmName(answers.moduleName, function (err, available) { if (!available) { done(true); } done(false); }); } }]; this.prompt(prompts, function(props) { this.githubUsername = props.github || this.githubUsername; if (props.pkgName) { return this.askForName(); } this.moduleName = props.moduleName; done(); }.bind(this)); }; SimpleNodePackageGenerator.prototype.askFor = function askFor() { var done = this.async(); var prompts = [ { name: 'description', message: 'Please provide a short description for the project' }, { type: 'confirm', name: 'cli', message: 'Will this module include a CLI?', default: true }, { type: 'confirm', name: 'git', message: 'Do you want to init this project as a Git repo and create initial commit', default: true } ]; this.prompt(prompts, function(props) { this.description = props.description; this.cli = props.cli; this.git = props.git; done(); }.bind(this)); }; SimpleNodePackageGenerator.prototype.info = function info() { if(!this.website) { this.website = this.githubUsername ? 'https://github.com/' + this.githubUsername : 'https://github.com/'; this.log('\n\nCouldn\'t find your website in git config under \'user.website\''); this.log('Defaulting to Github url: ' + this.website); } }; SimpleNodePackageGenerator.prototype.project = function project(){ this.template('readme.md', 'readme.md'); this.template('license', 'license'); this.template('_package.json', 'package.json'); this.template('editorconfig', '.editorconfig'); this.template('gitignore', '.gitignore'); this.template('jshintrc', '.jshintrc'); this.template('travis.yml', '.travis.yml'); }; SimpleNodePackageGenerator.prototype.app = function app(){ this.template('index.js', 'index.js'); this.template('test.js', 'test.js'); if(this.cli){ this.template('cli.js', 'cli.js'); } };
JavaScript
0.000001
@@ -1748,24 +1748,65 @@ ubUsername;%0A + this.moduleName = props.moduleName;%0A%0A if (prop @@ -1842,20 +1842,16 @@ s.askFor -Name ();%0A @@ -1857,49 +1857,8 @@ %7D%0A%0A - this.moduleName = props.moduleName;%0A%0A
63e79a0504a3e511722e8980b2eabd3e9a5c55e7
Add header and footer to app layout
src/layouts/app/index.js
src/layouts/app/index.js
// External Deps import React from 'react'; import Radium from 'radium'; import { GatewayProvider, GatewayDest } from 'react-gateway'; // Theme import { grey } from 'theme/variables'; // Sub-layouts import TopLeftSection from 'layouts/topLeftSection'; import TopRightSection from 'layouts/topRightSection'; import BottomSection from 'layouts/bottomSection'; // layout constants const APP_WIDTH = 1400; const APP_HEIGHT = 800; const APP_PADDING = 40; const TOP_BOTTOM_DIVIDER_HEIGHT = 3; const TOP_HEIGHT = Math.ceil(APP_HEIGHT * 0.64) - (TOP_BOTTOM_DIVIDER_HEIGHT * 2); const BOTTOM_HEIGHT = APP_HEIGHT - TOP_HEIGHT - (TOP_BOTTOM_DIVIDER_HEIGHT * 2); const INSTRUMENT_SEPERATOR_WIDTH = 1; const TOP_LEFT_WIDTH = Math.ceil(APP_WIDTH * 0.23) - INSTRUMENT_SEPERATOR_WIDTH; const TOP_RIGHT_WIDTH = APP_WIDTH - TOP_LEFT_WIDTH ; const TOP_HORIZONTAL_SEPERATOR_HEIGHT = TOP_HEIGHT - 10; @Radium class AppLayout extends React.Component { shouldComponentUpdate() { return false; } render() { const styles = { wrapper: { position: 'relative', width: '100%', height: '100%', minWidth: APP_WIDTH + APP_PADDING, minHeight: APP_HEIGHT + APP_PADDING }, appWrapper: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, margin: 'auto', width: APP_WIDTH, height: APP_HEIGHT, display: 'flex', flexDirection: 'column' }, topBottomDivider: { width: APP_WIDTH, height: TOP_BOTTOM_DIVIDER_HEIGHT, backgroundColor: grey }, topHorizontalDivider: { width: INSTRUMENT_SEPERATOR_WIDTH, height: TOP_HORIZONTAL_SEPERATOR_HEIGHT, backgroundColor: grey }, topWrapper: { width: APP_WIDTH, height: TOP_HEIGHT, display: 'flex', flexDirection: 'row', alignItems: 'center' }, bottomWrapper: { width: APP_WIDTH, height: BOTTOM_HEIGHT } }; return ( <GatewayProvider> <div style={styles.wrapper}> <GatewayDest name="knobOverlay" /> <div style={styles.wrapper}> <div style={styles.appWrapper}> <div style={styles.topBottomDivider}></div> <div style={styles.topWrapper}> <TopLeftSection width={TOP_LEFT_WIDTH} height={TOP_HEIGHT} /> <div style={styles.topHorizontalDivider}></div> <TopRightSection width={TOP_RIGHT_WIDTH} height={TOP_HEIGHT} seperatorWidth={INSTRUMENT_SEPERATOR_WIDTH} /> <div style={styles.topHorizontalDivider}></div> </div> <div style={styles.topBottomDivider}></div> <div style={styles.bottomWrapper}> <BottomSection width={APP_WIDTH} height={BOTTOM_HEIGHT} topLeftWidth={TOP_LEFT_WIDTH} /> </div> </div> </div> </div> </GatewayProvider> ); } } export default AppLayout;
JavaScript
0
@@ -447,16 +447,69 @@ = 40;%0A%0A +const HEADER_HEIGHT = 50;%0Aconst FOOTER_HEIGHT = 50;%0A%0A const TO @@ -1222,27 +1222,147 @@ EIGHT + -APP_PADDING +HEADER_HEIGHT + FOOTER_HEIGHT + APP_PADDING,%0A display: 'flex',%0A flexDirection: 'column',%0A alignItems: 'center' %0A %7D @@ -1370,19 +1370,22 @@ %0A%0A -app +header Wrapper: @@ -1399,99 +1399,410 @@ -position: 'absolute',%0A top: 0, left: 0, right: 0, bottom: 0,%0A margin: 'auto', +width: APP_WIDTH, height: HEADER_HEIGHT,%0A display: 'flex',%0A flexDirection: 'row',%0A alignItems: 'center',%0A justifyContent: 'space-between'%0A %7D,%0A%0A footerWrapper: %7B%0A width: APP_WIDTH, height: FOOTER_HEIGHT,%0A display: 'flex',%0A flexDirection: 'row',%0A alignItems: 'center',%0A justifyContent: 'space-between'%0A %7D,%0A%0A appWrapper: %7B %0A @@ -2589,32 +2589,85 @@ tyles.wrapper%7D%3E%0A + %3Cdiv style=%7Bstyles.headerWrapper%7D%3E%3C/div%3E%0A %3Cdiv @@ -3426,32 +3426,85 @@ %3C/div%3E%0A + %3Cdiv style=%7Bstyles.footerWrapper%7D%3E%3C/div%3E%0A %3C/div%3E
046ce954fde98d9cf393156af2b01871cb0c788e
Fix gulp watch to call sass instead of css
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp') , browserify = require('browserify') , bump = require('gulp-bump') , connect = require('gulp-connect') , eslint = require('gulp-eslint') , insert = require('gulp-insert') , rename = require('gulp-rename') , rimraf = require('gulp-rimraf') , sass = require('gulp-sass') , transform = require('vinyl-transform') , uglify = require('gulp-uglify') , zip = require('gulp-zip'); var version = '/* perfect-scrollbar v' + require('./package').version + ' */\n'; gulp.task('lint', function () { return gulp.src(['./src/**/*.js', './gulpfile.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task('clean:js', function () { return gulp.src('./dist/js/*.js', {read: false}) .pipe(rimraf()); }); gulp.task('clean:js:min', function () { return gulp.src('./dist/js/min/*.js', {read: false}) .pipe(rimraf()); }); function browserified() { return transform(function (filename) { var b = browserify(filename); return b.bundle(); }); } gulp.task('js', ['clean:js'], function () { return gulp.src('./src/js/adaptor/*.js') .pipe(browserified()) .pipe(insert.prepend(version)) .pipe(rename(function (path) { if (path.basename === 'global') { path.basename = 'perfect-scrollbar'; } else { path.basename = 'perfect-scrollbar.' + path.basename; } })) .pipe(gulp.dest('./dist/js')) .pipe(connect.reload()); }); gulp.task('js:min', ['clean:js:min'], function () { return gulp.src('./src/js/adaptor/*.js') .pipe(browserified()) .pipe(uglify()) .pipe(insert.prepend(version)) .pipe(rename(function (path) { if (path.basename === 'global') { path.basename = 'perfect-scrollbar.min'; } else { path.basename = 'perfect-scrollbar.' + path.basename + '.min'; } })) .pipe(gulp.dest('./dist/js/min')); }); gulp.task('clean:css', function () { return gulp.src('./dist/css/perfect-scrollbar.css', {read: false}) .pipe(rimraf()); }); gulp.task('clean:css:min', function () { return gulp.src('./dist/css/perfect-scrollbar.min.css', {read: false}) .pipe(rimraf()); }); gulp.task('sass', ['clean:css'], function () { return gulp.src('./src/css/main.scss') .pipe(sass()) .pipe(insert.prepend(version)) .pipe(rename('perfect-scrollbar.css')) .pipe(gulp.dest('./dist/css')) .pipe(connect.reload()); }); gulp.task('sass:min', ['clean:css:min'], function () { return gulp.src('./src/css/main.scss') .pipe(sass({outputStyle: 'compressed'})) .pipe(insert.prepend(version)) .pipe(rename('perfect-scrollbar.min.css')) .pipe(gulp.dest('./dist/css')); }); function bumpType() { if (gulp.env.major) { return 'major'; } else if (gulp.env.minor) { return 'minor'; } else { return 'patch'; } } gulp.task('bump', function () { gulp.src('./*.json') .pipe(bump({type: bumpType()})) .pipe(gulp.dest('./')); }); gulp.task('release', ['bump', 'build']); gulp.task('build', ['js', 'js:min', 'sass', 'sass:min']); gulp.task('connect', ['build'], function () { connect.server({ root: __dirname, livereload: true }); }); gulp.task('watch', function () { gulp.watch(['src/js/**/*'], ['js']); gulp.watch(['src/css/**/*'], ['css']); }); gulp.task('serve', ['connect', 'watch']); gulp.task('compress', function () { return gulp.src('./dist/**') .pipe(zip('perfect-scrollbar.zip')) .pipe(gulp.dest('./dist')); }); gulp.task('default', ['lint', 'build']);
JavaScript
0
@@ -3318,17 +3318,18 @@ /*'%5D, %5B' -c +sa ss'%5D);%0A%7D
234c911e423785b2a0c6f32ea9d5cd9b2fabcb8a
Remove obsolete server hash
src/leo-export-inject.js
src/leo-export-inject.js
di.require(["$tooltip"], function(tooltip){ window.postMessage({ type: 'LeoDict', payload: { wordsCount: CONFIG.pages.userdict3.count_words, serverHash: CONFIG_GLOBAL.serverHash } }, '*'); window.addEventListener("message", function(event) { // We only accept messages from ourselves if (event.source != window) return; if (event.data.type && (event.data.type == "LeoExportExtension.ShowTooltip")) { tooltip.show($("#leo-export-extension-btn"), {content:event.data.payload.message,position:"bottom",styleClass:event.data.payload.style}); } if (event.data.type && (event.data.type == "LeoExportExtension.AddDropdownHideHandler")) { LEO.ui.BodyClickHider .removeItem(".leo-export-extension-menu-container") .addItem(".leo-export-extension-menu-container", function() { $(".leo-export-extension-menu-container").hide(); } ); } }, false); });
JavaScript
0.000005
@@ -139,46 +139,8 @@ ords -, serverHash: CONFIG_GLOBAL.serverHash %7D %7D
ca7a21bab4295e62aa0196bb605deaf00145adb5
Add tests and fix raw not being a string (#5)
lib/smtp.js
lib/smtp.js
'use strict'; var uuid = require('node-uuid'); var MailParser = require("mailparser").MailParser; var SMTPServer = require('smtp-server').SMTPServer; function SmtpServer(port, logger, storage) { this.port = port; this.storage = storage; this.logger = logger; var onData = function onData(stream, session, callback) { var mailparser = new MailParser({ }); var message = { id: uuid.v4(), body: { plain: '', html: '' }, raw: [] }; stream.pipe(mailparser); stream.on('data', function(chunk) { message.raw.push(chunk); }); mailparser.on('end', function(mail_object) { message.timestamp = mail_object.date.toISOString(); message.body.plain = mail_object.text; message.body.html = mail_object.html; message.subject = mail_object.subject; if (mail_object.headers['message-id']) { message.id = mail_object.headers['message-id'].replace(/[^a-zA-Z1-9-/]/g, '_'); } ['to','from','bcc','cc'].forEach(function(field) { if (!mail_object[field]) { return; } message[field] = mail_object[field].map(function(elm) { if (!elm.name) { return elm.address; } return elm.name + " <" + elm.address + ">"; }); }); if (message.from) { message.from = message.from[0]; } message.subject = mail_object.subject; storage.store(message); callback(); }); }; this.server = new SMTPServer({ disabledCommands: ['AUTH'], logger: logger, onMailFrom: function(address, session, callback) { return callback(); }, onAuth: function(auth, session, callback) { return callback(); }, // onAuth: onAuth.bind(this), //onRcptTo: onRcptTo.bind(this) onData: onData }); this.server.on('error', function(err) { console.log('Error %s', err.message); }); }; SmtpServer.prototype.run = function() { this.server.listen(this.port); }; module.exports = SmtpServer;
JavaScript
0
@@ -537,16 +537,27 @@ sh(chunk +.toString() );%0A %7D @@ -1864,16 +1864,18 @@ unction( +cb ) %7B%0A th @@ -1900,16 +1900,20 @@ his.port +, cb );%0A%7D;%0A%0Am
7cea2050b11abb0eaf6492fabd93fc5a254c187f
Update to React instead of react.
app/index.js
app/index.js
/** * Created by sbardian on 5/16/17. */ import react from 'react'; class openTrivia extends react.Component { constructor (props) { super(props); this.state = { test: 'test', } } componentWillReceiveProps (newProps) { // When component gets props } componentWillUnmount () { // When component mounts } render () { return ( <div> <div>This is a state ${this.state.test}</div> <div>This is a props ${this.props.test}</div> </div> ) } } openTrivia.propTypes = { // set default props the component will expect }; openTrivia.defaultProps = { // set value of default props test: 'test', }; export default openTrivia;
JavaScript
0
@@ -44,21 +44,25 @@ %0Aimport -r +%7B R eact + %7D from 'r @@ -94,17 +94,17 @@ extends -r +R eact.Com
772d24f0b88fde27d586eaa0300f90c6708ab1e2
update build scripts
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const { series, parallel } = gulp; const glob = require('glob'); const shell = cmd => require('child_process').execSync(cmd, { stdio: [0, 1, 2] }); const del = require('del'); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); const $ = require('gulp-load-plugins')(); const browserify = require('browserify'); const tsify = require('tsify'); const minify = require('gulp-uglify/composer')(require('uglify-es'), console); const Server = require('karma').Server; const pkg = require('./package.json'); const config = { browsers: ['Chrome', 'Firefox'].concat((os => { switch (os) { case 'Windows_NT': return ['Edge']; case 'Darwin': return []; default: return []; } })(require('os').type())), ts: { dist: { src: [ '*.ts' ], dest: 'dist' }, test: { src: [ '*.ts', 'src/**/*.ts', 'test/**/*.ts' ], dest: 'dist' } }, site: { js: './gh-pages/assets/js/lib', }, banner: [ `/*! ${pkg.name} v${pkg.version} ${pkg.repository.url} | (c) 2016, ${pkg.author} | ${pkg.license} License */`, '' ].join('\n'), module: ` (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof module === 'object' && module.exports) { module.exports = factory(); } else { //root.returnExports = factory(); } }(typeof self !== 'undefined' ? self : this, function () { return require('${pkg.name}'); })); `, clean: [ 'dist', 'gh-pages/assets/*/**/lib', ] }; function compile(src) { let done = true; const b = browserify(Object.values(src).map(p => glob.sync(p)), { cache: {}, packageCache: {}, }) .require(`./index.ts`, { expose: pkg.name }) .plugin(tsify, { global: true, ...require('./tsconfig.json').compilerOptions }) .on('update', () => void bundle()); return bundle(); function bundle() { console.time('bundle'); return b .bundle() .on("error", err => done = console.log(err + '')) .pipe(source(`${pkg.name}.js`)) .pipe(buffer()) .once('finish', () => console.timeEnd('bundle')) .once("finish", () => done || process.exit(1)) .pipe($.footer(config.module)); } } gulp.task('ts:dev', () => gulp.watch(config.ts.test.src, { ignoreInitial: false }, () => compile(config.ts.test.src) .pipe($.rename({ extname: '.test.js' })) .pipe(gulp.dest(config.ts.test.dest)))); gulp.task('ts:test', () => compile(config.ts.test.src) .pipe($.rename({ extname: '.test.js' })) .pipe(gulp.dest(config.ts.test.dest))); gulp.task('ts:dist', () => compile(config.ts.dist.src) .pipe($.unassert()) .pipe($.header(config.banner)) .pipe(gulp.dest(config.ts.dist.dest)) .pipe(gulp.dest(config.site.js)) .pipe($.rename({ extname: '.min.js' })) .pipe(minify({ output: { comments: /^!/ } })) .pipe(gulp.dest(config.ts.dist.dest))); gulp.task('ts:view', () => gulp.watch(config.ts.dist.src, { ignoreInitial: false }, () => compile(config.ts.dist.src) .pipe($.unassert()) .pipe($.header(config.banner)) .pipe(gulp.dest(config.site.js)))); gulp.task('karma:dev', done => new Server({ configFile: __dirname + '/karma.conf.js', browsers: config.browsers, preprocessors: { 'dist/*.js': ['espower'] }, }, done).start()); gulp.task('karma:test', done => new Server({ configFile: __dirname + '/karma.conf.js', browsers: config.browsers, preprocessors: { 'dist/*.js': ['coverage', 'espower'] }, reporters: ['dots', 'coverage'], concurrency: 1, singleRun: true }, done).start()); gulp.task('karma:ci', done => new Server({ configFile: __dirname + '/karma.conf.js', browsers: config.browsers, preprocessors: { 'dist/*.js': ['coverage', 'espower'] }, reporters: ['dots', 'coverage', 'coveralls'], concurrency: 1, singleRun: true }, done).start()); gulp.task('clean', () => del(config.clean)); gulp.task('install', done => { shell('npm i --no-shrinkwrap'); done(); }); gulp.task('update', done => { shell('bundle update'); shell('ncu -ua'); shell('npm i -DE typescript@next --no-shrinkwrap'); shell('npm i --no-shrinkwrap'); done(); }); gulp.task('dev', series( 'clean', parallel( 'ts:dev', 'karma:dev', ))); gulp.task('test', series( 'clean', series( 'ts:test', 'karma:test', 'ts:dist', ))); gulp.task('dist', series( 'clean', series( 'ts:dist', ))); gulp.task('view', series( 'clean', () => shell([ 'concurrently', '"gulp dev"', '"gulp ts:view"', '"bundle exec jekyll serve -s ./gh-pages -d ./gh-pages/_site --incremental"' ].join(' ')), )); gulp.task('ci', series( 'clean', series( 'ts:test', 'karma:ci', 'karma:ci', 'karma:ci', 'dist', )));
JavaScript
0.000003
@@ -1935,47 +1935,8 @@ s %7D) -%0A .on('update', () =%3E void bundle()) ;%0A
b3c5edabc74b8ef220e7fce917b2dd1655886466
Add gulp gh-deploy
gulpfile.js
gulpfile.js
var src = ['src/**', 'sw/**']; var deployDir = 'docs'; var gulp = require('gulp'); var clean = require('gulp-clean'); var concat = require('gulp-concat'); var jshint = require('gulp-jshint'); var uglify = require('gulp-uglify'); var babel = require('gulp-babel'); var inject = require('gulp-inject'); var minifyHtml = require('gulp-minify-html'); var minifyCss = require('gulp-clean-css'); var browserSync = require('browser-sync'); var injectVersion = require('gulp-inject-version'); gulp.task('default', ['lint']); gulp.task('build', ['build-html', 'build-sw']); gulp.task('clean', function () { return gulp.src(deployDir) .pipe(clean()); }); gulp.task('lint', function () { var filesToLint = src.map(path => path + '/*.js'); filesToLint.push('gulpfile.js'); return gulp.src(filesToLint) .pipe(jshint({ eqeqeq: true, esversion: 6, eqnull: true })) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); gulp.task('build-js', ['clean'], function () { return gulp.src(['./src/**/*.js', './sw/install.js']) .pipe(injectVersion()) .pipe(babel({ presets: ['es2015'] })) .pipe(concat('all.min.js')) .pipe(uglify()) .pipe(gulp.dest(deployDir)); }); gulp.task('build-css', ['clean'], function () { return gulp.src('src/**/*.css') .pipe(minifyCss()) .pipe(gulp.dest(deployDir)); }); gulp.task('build-extension', ['clean'], function () { return gulp.src(['src/manifest.json', 'src/icon.png']) .pipe(gulp.dest(deployDir)); }); gulp.task('build-html', ['build-js', 'build-css', 'build-extension'], function () { // Inject references of every JS and CSS file in the deploy directory (excluding sw.js) into index.html. var target = gulp.src('src/index.html'); var sources = gulp.src(['!' + deployDir + '/sw.js', deployDir + '/*.{js,css}',], { read: false }); return target.pipe(inject(sources, { ignorePath: deployDir, addRootSlash: false })) .pipe(injectVersion()) .pipe(minifyHtml()) .pipe(gulp.dest(deployDir)); }); gulp.task('build-sw', ['clean'], function () { return gulp.src('./sw/sw.js') .pipe(injectVersion()) .pipe(babel({ presets: ['es2015'] })) .pipe(uglify()) .pipe(gulp.dest(deployDir)); }); gulp.task('serve', function () { browserSync({ server: { baseDir: './src/' }, notify: false }); gulp.watch(['./src/*'], browserSync.reload); });
JavaScript
0.000001
@@ -53,20 +53,21 @@ ';%0A%0Avar -gulp +babel = requi @@ -74,16 +74,65 @@ re('gulp +-babel');%0Avar browserSync = require('browser-sync ');%0Avar @@ -203,22 +203,21 @@ ');%0Avar -jshint +debug = requi @@ -229,22 +229,21 @@ ulp- -jshint +debug ');%0Avar ugli @@ -238,22 +238,23 @@ ');%0Avar -uglify +ghPages = requi @@ -266,22 +266,52 @@ ulp- -uglify +gh-pages');%0Avar gulp = require('gulp ');%0Avar babe @@ -302,29 +302,30 @@ gulp');%0Avar -babel +inject = require(' @@ -321,37 +321,38 @@ = require('gulp- -babel +inject ');%0Avar inject = @@ -341,32 +341,39 @@ ct');%0Avar inject +Version = require('gulp @@ -383,26 +383,30 @@ ject -');%0Avar minifyHtml +-version');%0Avar jshint = r @@ -422,19 +422,14 @@ ulp- -minify-html +jshint ');%0A @@ -471,35 +471,34 @@ -css');%0Avar -browserSync +minifyHtml = require(' @@ -501,41 +501,38 @@ re(' -browser-sync');%0Avar injectVersion +gulp-minify-html');%0Avar uglify = r @@ -540,38 +540,30 @@ quire('gulp- -inject-version +uglify ');%0A%0Agulp.ta @@ -1056,32 +1056,242 @@ ('fail'));%0A%7D);%0A%0A +gulp.task('gh-deploy', %5B'build'%5D, () =%3E %7B%0A return gulp.src('./docs/**/*')%0A .pipe(debug('hello'))%0A .pipe(ghPages(%7B%0A remote: %22origin%22,%0A branch: %22gh-pages%22%0A %7D));%0A%7D);%0A%0A gulp.task('build
855ac6a804a3eeffb06182532d9f2599b49f77ae
remove unused acceleration, causing errors in android browsers
app/js/ui.js
app/js/ui.js
module.exports = ColorUI; var round = Math.round; var abs = Math.abs; /** * Class to calculate the color if the screen * based on the movement of the phone * * Also draws the color the given DOM element * * @param {Object} opts options */ function ColorUI(opts) { this.dom = opts.dom || document.body; // acceleration this.ax = 0; this.ay = 0; this.az = 0; this.aa = 0; this.ab = 0; this.ag = 0; } /** * Handles the DeviceMotionEvent and uses * the acceleration values to calc the accelation * on each axis and with the rotation data the other. * * @param {DeviceMotionEvent} e */ ColorUI.prototype.handleMotionEvent = function handleEvent(e) { var acc = e.accelerationIncludingGravity; var rr = e.rotationRate; this.ax = round(abs(acc.x * 1)); this.ay = round(abs(acc.y * 1)); this.az = round(abs(acc.z * 1)); if(rr !== null) { this.aa = round(rr.alpha); this.ab = round(rr.beta); this.ag = round(rr.gamma); } }; /** * Draws the screen background and font color * based on the acceleration values * * The background color is tuned to look nice. * the conf color is the inversed color of the * background color, so a high contrast should be visible */ ColorUI.prototype.draw = function draw() { var color = this.makeColor(this.aa, this.ab, this.ag); this.dom.style.backgroundColor = '#' + (color[0].toString(16)).substr(1) + (color[1].toString(16)).substr(1) + (color[2].toString(16)).substr(1); this.dom.style.color = '#'+ ((512 -color[0]).toString(16)).substr(1) + ((512 -color[1]).toString(16)).substr(1) + ((512 -color[2]).toString(16)).substr(1); }; /** * Create a color based on the acceleration alpha/beta/gamme * values and returns a array of integers for RGB * * @param {Number} a acceleration alpha * @param {Number} b acceleration beta * @param {Number} g acceleration gamma * @return {Array} if ints [r, g, b] */ ColorUI.prototype.makeColor = function makeColor(a, b, g) { var red = abs(a*100) % 255; var green = abs(b*100) % 255; var blue = abs(g*100) % 255; var bright = 60; return [ (0|(1<<8) + red + (256 - red) * bright / 100), (0|(1<<8) + green + (256 - green) * bright / 100), (0|(1<<8) + blue + (256 - blue) * bright / 100) ]; };
JavaScript
0
@@ -329,53 +329,8 @@ ion%0A - this.ax = 0;%0A this.ay = 0;%0A this.az = 0;%0A th @@ -636,178 +636,28 @@ var -acc = e.accelerationIncludingGravity;%0A var rr = e.rotationRate;%0A this.ax = round(abs(acc.x * 1));%0A this.ay = round(abs(acc.y * 1));%0A this.az = round(abs(acc.z * 1));%0A +rr = e.rotationRate; %0A i
88c245a922bd5944375c28087b04fd28ee02d250
Complete AboutHigherOrderFunctions
koans/AboutHigherOrderFunctions.js
koans/AboutHigherOrderFunctions.js
var _; //globals /* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/ "Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux." */ describe("About Higher Order Functions", function () { it("should use filter to return array items that meet a criteria", function () { var numbers = [1,2,3]; var odd = _(numbers).filter(function (x) { return x % 2 !== 0 }); expect(odd).toEqual(FILL_ME_IN); expect(odd.length).toBe(FILL_ME_IN); expect(numbers.length).toBe(FILL_ME_IN); }); it("should use 'map' to transform each element", function () { var numbers = [1, 2, 3]; var numbersPlus1 = _(numbers).map(function(x) { return x + 1 }); expect(numbersPlus1).toEqual(FILL_ME_IN); expect(numbers).toEqual(FILL_ME_IN); }); it("should use 'reduce' to update the same result on each iteration", function () { var numbers = [1, 2, 3]; var reduction = _(numbers).reduce( function(memo, x) { //note: memo is the result from last call, and x is the current number return memo + x; }, /* initial */ 0 ); expect(reduction).toBe(FILL_ME_IN); expect(numbers).toEqual(FILL_ME_IN); }); it("should use 'forEach' for simple iteration", function () { var numbers = [1,2,3]; var msg = ""; var isEven = function (item) { msg += (item % 2) === 0; }; _(numbers).forEach(isEven); expect(msg).toEqual(FILL_ME_IN); expect(numbers).toEqual(FILL_ME_IN); }); it("should use 'all' to test whether all items pass condition", function () { var onlyEven = [2,4,6]; var mixedBag = [2,4,5,6]; var isEven = function(x) { return x % 2 === 0 }; expect(_(onlyEven).all(isEven)).toBe(FILL_ME_IN); expect(_(mixedBag).all(isEven)).toBe(FILL_ME_IN); }); it("should use 'any' to test if any items passes condition" , function () { var onlyEven = [2,4,6]; var mixedBag = [2,4,5,6]; var isEven = function(x) { return x % 2 === 0 }; expect(_(onlyEven).any(isEven)).toBe(FILL_ME_IN); expect(_(mixedBag).any(isEven)).toBe(FILL_ME_IN); }); it("should use range to generate an array", function() { expect(_.range(3)).toEqual(FILL_ME_IN); expect(_.range(1, 4)).toEqual(FILL_ME_IN); expect(_.range(0, -4, -1)).toEqual(FILL_ME_IN); }); it("should use flatten to make nested arrays easy to work with", function() { expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual(FILL_ME_IN); }); it("should use chain() ... .value() to use multiple higher order functions", function() { var result = _([ [0, 1], 2 ]).chain() .flatten() .map(function(x) { return x+1 } ) .reduce(function (sum, x) { return sum + x }) .value(); expect(result).toEqual(FILL_ME_IN); }); });
JavaScript
0
@@ -673,34 +673,29 @@ dd).toEqual( -FILL_ME_IN +%5B1,3%5D );%0A expec @@ -709,34 +709,25 @@ ength).toBe( -FILL_ME_IN +2 );%0A expec @@ -745,34 +745,25 @@ ength).toBe( -FILL_ME_IN +3 );%0A %7D);%0A @@ -961,34 +961,33 @@ s1).toEqual( -FILL_ME_IN +%5B2, 3, 4%5D );%0A expec @@ -1001,34 +1001,33 @@ rs).toEqual( -FILL_ME_IN +%5B1, 2, 3%5D );%0A %7D);%0A @@ -1379,34 +1379,25 @@ ction).toBe( -FILL_ME_IN +6 );%0A expec @@ -1411,34 +1411,33 @@ rs).toEqual( -FILL_ME_IN +%5B1, 2, 3%5D );%0A %7D);%0A @@ -1678,34 +1678,40 @@ sg).toEqual( -FILL_ME_IN +%22falsetruefalse%22 );%0A expec @@ -1725,34 +1725,33 @@ rs).toEqual( -FILL_ME_IN +%5B1, 2, 3%5D );%0A %7D);%0A @@ -1982,34 +1982,28 @@ Even)).toBe( -FILL_ME_IN +true );%0A expec @@ -2030,34 +2030,29 @@ Even)).toBe( -FILL_ME_IN +false );%0A %7D);%0A @@ -2281,34 +2281,28 @@ Even)).toBe( -FILL_ME_IN +true );%0A expec @@ -2333,26 +2333,20 @@ )).toBe( -FILL_ME_IN +true );%0A %7D); @@ -2433,34 +2433,33 @@ 3)).toEqual( -FILL_ME_IN +%5B0, 1, 2%5D );%0A expec @@ -2479,34 +2479,33 @@ 4)).toEqual( -FILL_ME_IN +%5B1, 2, 3%5D );%0A expec @@ -2530,34 +2530,39 @@ 1)).toEqual( -FILL_ME_IN +%5B0, -1, -2, -3%5D );%0A %7D);%0A%0A @@ -2687,34 +2687,36 @@ ()).toEqual( -FILL_ME_IN +%5B1, 2, 3, 4%5D );%0A %7D);%0A%0A @@ -3064,18 +3064,9 @@ ual( -FILL_ME_IN +6 );%0A
8938c85783ad946dc284b882b9cc8f76e007f6c2
Remove unnecessary trailing slash
gulpfile.js
gulpfile.js
/* Copyright (c) 2016, salesforce.com, inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; // This gulpfile makes use of new JavaScript features. // Babel handles this without us having to do anything. It just works. // You can read more about the new JavaScript features here: // https://babeljs.io/docs/learn-es2015/ const path = require('path'); const fs = require('fs'); const gulp = require('gulp'); const del = require('del'); const runSequence = require('run-sequence'); const browserSync = require('browser-sync'); const gulpLoadPlugins = require('gulp-load-plugins'); const $ = gulpLoadPlugins(); gulp.task('assets', () => gulp .src([ 'node_modules/@salesforce-ux/design-system/assets/**/*.{woff,woff2,txt,jpg,png,gif,svg,md}', 'assets/**/*.{woff,woff2,txt,jpg,png,gif,svg,md}' ]) .pipe(gulp.dest('dist/assets')) ); gulp.task('favicon', () => gulp .src([ 'app/favicon*.*' ], { base: 'app' }) .pipe(gulp.dest('dist')) ); // Get data from the corresponding filename // e.g. inject data/foo.json into foo.html const getData = (file) => { const dataPath = path.resolve('./app/views/data/' + path.basename(file.path, '.html') + '.json') let data = {}; try { data = JSON.parse(fs.readFileSync(dataPath, 'utf8')); } catch(e) { // Don't fail if the JSON is badly formed or the file doesn't exist } finally { return data; } }; gulp.task('views', () => gulp .src([ 'app/views/**/*.html', '!app/views/**/_*.html' ], { base: 'app/views' }) .pipe($.data(getData)) .pipe($.nunjucks.compile()) .pipe(gulp.dest('dist/')) ); gulp.task('scripts', () => gulp .src([ 'app/scripts/**/*.js' ], { base: 'app' }) .pipe(gulp.dest('dist/')) ); gulp.task('styles', () => gulp .src('app/styles/*.scss') .pipe($.plumber()) .pipe($.sourcemaps.init()) .pipe($.sass.sync({ precision: 10 }).on('error', $.sass.logError)) .pipe($.autoprefixer({ browsers: ['last 2 versions'], remove: false })) .pipe($.minifyCss({ advanced: false })) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest('dist/styles')) .pipe(browserSync.stream({ match: '**/*.css' })) ); // Static Server (development) gulp.task('default', ['build'], () => { browserSync({ notify: false, server: 'dist', online: true }); gulp.watch('app/styles/*.scss', ['styles']); gulp.watch([ 'app/views/**/*.html', 'app/views/data/*.json' ], ['views']); gulp.watch('assets/**/*.{woff,woff2,txt,jpg,png,gif,svg,md}', ['assets']); gulp.watch('app/scripts/**/*.js', ['scripts']); gulp.watch([ 'dist/**/*.html', 'dist/scripts/**/*.js', // Note: we're not watching icons and fonts changes, // as they're slowing down the task 'dist/assets/*.{woff,woff2,txt,jpg,png,gif,svg,md}', 'dist/assets/styles/*.css' ]).on('change', browserSync.reload); }); gulp.task('clean', () => del(['dist'], { dot: true })); gulp.task('build', callback => { runSequence( 'clean', 'assets', 'views', 'styles', 'scripts', 'favicon', callback); });
JavaScript
0.00005
@@ -3012,33 +3012,32 @@ (gulp.dest('dist -/ '))%0A);%0A%0Agulp.tas
86d030a6604d2bd1a067bb89fbf1fc41a535da09
deploy pushes to origin
gulpfile.js
gulpfile.js
var fs = require('fs-extra'); var git = require('gulp-git'); var gulp = require('gulp'); var mocha = require('gulp-mocha'); var rename = require('gulp-rename'); var template = require('gulp-template'); var yaml = require('js-yaml'); var resource = require('./src/resource'); var helpers = require('./src/helpers'); /** * Paths */ var test = 'test/**/*'; /** * Environment */ var languages = { js: { repo: 'Asana/node-asana-gen', destPath: '/lib', resourceBaseName: function(resource) { return helpers.plural(resource); } } }; var paths = { dist: function(lang) { return 'dist/' + lang; }, repo: function(lang) { return 'dist/repos/' + lang; }, repoDest: function(lang) { return paths.repo(lang) + paths.repoDestRelative(lang); }, repoDestRelative: function(lang) { return languages[lang].destPath; } }; /** * High-level tasks */ // Build all languages gulp.task('build', ['test'].concat(Object.keys(languages).map(function(lang) { return 'build-' + lang; }))); // Deploy languages gulp.task('deploy', ['build'].concat(Object.keys(languages).map(function(lang) { return 'deploy-' + lang; }))); /** * Generate deploy rules for each language */ Object.keys(languages).forEach(function(lang) { gulp.task('deploy-' + lang, function(cb) { var dest = paths.repoDest(lang); var repoRoot = paths.repo(lang); fs.removeSync(repoRoot); git.clone( 'git@github.com:' + languages[lang].repo, {args: repoRoot + ' --depth=1'}, function(err) { if (err) throw err; fs.mkdirpSync(dest); fs.copy(paths.dist(lang), dest, function(err) { if (err) throw err; git.add({cwd: repoRoot, args: paths.repoDestRelative(lang)}, function(err) { if (err) throw err; // TODO: add current version to commit message git.commit({cwd: repoRoot, args: '-m "Deploy from asana-api-meta"'}, function(err) { if (err) throw err; cb(); }); }); }); }); }); }); /** * Generate build rules for each resource in each language. */ var resourceNames = resource.names(); Object.keys(languages).forEach(function(lang) { function taskName(resourceName) { return 'build-' + lang + '-' + resourceName; } resourceNames.forEach(function(resourceName) { gulp.task(taskName(resourceName), function() { return gulp.src('src/templates/' + lang + '/resource.*.template') .pipe(template(resource.load(resourceName), { imports: helpers, variable: 'resource' })) .pipe(rename(function(path) { path.extname = /^.*([.].*?)$/.exec(path.basename)[1]; path.basename = languages[lang].resourceBaseName(resourceName); })) .pipe(gulp.dest(paths.dist(lang))); }); }); gulp.task('build-' + lang, ['clean-' + lang].concat(resourceNames.map(taskName))); }); Object.keys(languages).forEach(function(lang) { gulp.task('clean-' + lang, function() { fs.removeSync(paths.dist(lang)); }); }); /** * Tests the code with mocha. */ gulp.task('test', function(callback) { gulp.src(test) .pipe(mocha({ reporter: process.env.TRAVIS ? 'spec' : 'nyan' })); });
JavaScript
0
@@ -1980,11 +1980,137 @@ -cb( +git.push('origin', 'master', %7Bcwd: repoRoot%7D, function(err) %7B%0A if (err) throw err;%0A cb();%0A %7D );%0A
d02a45fd80d79acab163c0757358e52ec10220a0
Use spaces, not tabs
inherits.js
inherits.js
define([], function () { /** * sub should prototypally inherit from base * @param sub {function} Subclass constructor * @param base {function} Base class constructor */ function inherits (sub, base) { var Fn = function(){}; Fn.prototype = base.prototype; sub.prototype = new Fn(); sub.prototype.constructor = sub; } /** * sub should parasitically inherit from base * that is, we should pluck values from base.prototype onto sub.prototype */ inherits.parasitically = function (sub, base) { var baseKeys = inherits.keys(base.prototype), baseKeysLength = baseKeys.length, methodName; for (var i=0; i < baseKeysLength; i++) { methodName = baseKeys[i]; if ( ! sub.prototype[methodName]) { sub.prototype[methodName] = base.prototype[methodName]; } } }; /** * Object.keys shim */ inherits.keys = Object.keys || (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"), DontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], DontEnumsLength = DontEnums.length; return function (o) { if (typeof o != "object" && typeof o != "function" || o === null) throw new TypeError("Object.keys called on a non-object"); var result = []; for (var name in o) { if (hasOwnProperty.call(o, name)) result.push(name); } if (hasDontEnumBug) { for (var i = 0; i < DontEnumsLength; i++) { if (hasOwnProperty.call(o, DontEnums[i])) result.push(DontEnums[i]); } } return result; }; })(); return inherits; });
JavaScript
0.000145
@@ -20,22 +20,28 @@ () %7B%0A%0A%0A -%09/**%0A%09 + /**%0A * sub s @@ -77,17 +77,20 @@ om base%0A -%09 + * @para @@ -127,17 +127,20 @@ tructor%0A -%09 + * @para @@ -180,22 +180,28 @@ tructor%0A -%09 */%0A%09 + */%0A function @@ -228,10 +228,16 @@ ) %7B%0A -%09%09 + var @@ -373,19 +373,28 @@ ub;%0A -%09%7D%0A%0A%0A%09/**%0A%09 + %7D%0A%0A%0A /**%0A * s @@ -435,17 +435,20 @@ om base%0A -%09 + * that @@ -517,14 +517,20 @@ ype%0A -%09 */%0A%09 + */%0A inhe @@ -932,15 +932,21 @@ %7D%0A -%09 + %7D;%0A%0A%0A -%09 + /**%0A @@ -2129,9 +2129,12 @@ );%0A%0A -%09 + retu
6a249faf0ff9f0441ba9c78c9e465bccaf8dd0e9
Enable <blink>ing.
js/init.js
js/init.js
Reveal.addEventListener("ready", function() { var codes = document.querySelectorAll("code.javascript"); Array.prototype.forEach.call(codes, function (block) { hljs.highlightBlock(block); }); }); // Full list of configuration options available at: // https://github.com/hakimel/reveal.js#configuration Reveal.initialize({ controls: true, progress: true, history: true, center: true, transition: 'none', // none/fade/slide/convex/concave/zoom // Optional reveal.js plugins dependencies: [{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/zoom-js/zoom.js', async: true }, { src: 'plugin/notes/notes.js', async: true }] });
JavaScript
0
@@ -39,16 +39,94 @@ ion() %7B%0A + var Ap = Array.prototype;%0A var each = Ap.forEach;%0A var slice = Ap.slice;%0A%0A var co @@ -177,34 +177,24 @@ ript -%22);%0A Array.prototype.forE +,code.xml%22);%0A e ach. @@ -220,24 +220,48 @@ n (block) %7B%0A + console.log(block);%0A hljs.hig @@ -285,16 +285,397 @@ );%0A %7D); +%0A%0A var blinkers = slice.call(document.querySelectorAll(%22.blink%22));%0A if (blinkers.length %3E 0) %7B%0A var visible = true;%0A function setVisibility(blinker) %7B%0A blinker.style.visibility = visible ? %22visible%22 : %22hidden%22;%0A %7D%0A%0A function go() %7B%0A blinkers.forEach(setVisibility);%0A setTimeout(go, visible ? 1000 : 500);%0A visible = ! visible;%0A %7D%0A%0A go();%0A %7D %0A%7D);%0A%0A//
df84958b71dea608b45d6881dd2fe5c0ab0c0d95
Create index on database
app/serve.js
app/serve.js
"use strict"; /*eslint no-console: 0*/ const express = require("express"); const router = require("./http/router"); const logging = require("morgan"); const mongodb = require("mongodb"); const odm = require("./odm"); const server = express(); const config = require("./config"); const credentials = { username: "admin", password: config.password }; if (config.debug) { console.log("Debug mode active"); server.use(logging("dev")); } mongodb.connect(config.db_url, function(error, db) { if (error) { console.log(error); } else { const collection = db.collection("shortlinks"); const shortlinks = odm(collection); router(server, credentials, shortlinks); server.listen(config.port, () => { console.log("Server listening on port " + config.port + "…"); }); } });
JavaScript
0.000001
@@ -507,84 +507,25 @@ _url -, function(error, db) %7B%0A if (error) %7B%0A console.log(error);%0A %7D else +).then((db) =%3E %7B%0A - co @@ -572,18 +572,16 @@ ks%22);%0A - - const sh @@ -608,19 +608,16 @@ ction);%0A -%0A router @@ -651,19 +651,91 @@ links);%0A -%0A +return collection.createIndex(%7Btoken:1%7D, %7Bunique:true%7D);%0A%7D).then(() =%3E %7B%0A server @@ -763,18 +763,16 @@ () =%3E %7B%0A - cons @@ -833,19 +833,57 @@ %22);%0A - %7D);%0A - %7D +%7D).catch((error) =%3E %7B%0A console.log(error); %0A%7D);
36f5152ec326dfb7564e427334bbc95182eb76e1
Fix login JS files not being output to right dir
gulpfile.js
gulpfile.js
var browserify = require('browserify'); var watchify = require('watchify'); var source = require('vinyl-source-stream'); var gulp = require('gulp'); var uglify = require('gulp-uglify'); var streamify = require('gulp-streamify'); var gutil = require('gulp-util'); var pump = require('pump'); function react_browserify(infile, outfile, debug) { outfile = (outfile === undefined) ? infile : outfile; debug = (debug === undefined) ? false : debug; var b = browserify('client-js/'+infile+'.jsx', {transform: 'babelify', debug:true}); b = watchify(b); function bundlefn(cb) { pump([ b.bundle(), source(outfile+'.js'), debug ? gutil.noop() : streamify(uglify()), gulp.dest('static/js') ], cb); } b.on('update', bundlefn); b.on('log', gutil.log); return bundlefn; } gulp.task('build-login', react_browserify('login')); gulp.task('build-inventory', react_browserify('inventory')); gulp.task('build-users', react_browserify('users')); gulp.task('build-nav', react_browserify('CommonNav', 'navbar')); gulp.task('build', ['build-login', 'build-inventory', 'build-users', 'build-nav']);
JavaScript
0
@@ -327,16 +327,24 @@ outfile, + outdir, debug) @@ -401,16 +401,74 @@ utfile;%0A + outdir = (outdir === undefined) ? 'static/js' : outdir;%0A debug @@ -774,27 +774,22 @@ lp.dest( -'static/js' +outdir )%0A %5D, @@ -925,16 +925,38 @@ ('login' +, 'login', 'public/js' ));%0Agulp
e1d52da28d6c57156228ab958eb005981e96041c
fix lint issues
docs/src/components/AppFrame.js
docs/src/components/AppFrame.js
// @flow import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import compose from 'recompose/compose' import { withStyles } from 'material-ui/styles' import Typography from 'material-ui/Typography' import AppBar from 'material-ui/AppBar' import Toolbar from 'material-ui/Toolbar' import IconButton from 'material-ui/IconButton' import withWidth, { isWidthUp } from 'material-ui/utils/withWidth' import MenuIcon from 'material-ui-icons/Menu' import LightbulbOutline from 'material-ui-icons/LightbulbOutline' import Github from 'docs/src/components/Github' import AppDrawer from 'docs/src/components/AppDrawer' function getTitle(routes) { for (let i = routes.length - 1; i >= 0; i -= 1) { if (routes[i].hasOwnProperty('title')) { return routes[i].title } } return null } const styles = theme => ({ '@global': { html: { boxSizing: 'border-box', }, '*, *:before, *:after': { boxSizing: 'inherit', }, body: { margin: 0, background: theme.palette.background.default, color: theme.palette.text.primary, lineHeight: '1.2', overflowX: 'hidden', WebkitFontSmoothing: 'antialiased', // Antialiasing. MozOsxFontSmoothing: 'grayscale', // Antialiasing. }, }, root: { display: 'flex', alignItems: 'stretch', minHeight: '100vh', width: '100%', }, grow: { flex: '1 1 auto', }, title: { marginLeft: 24, flex: '0 1 auto', }, appBar: { transition: theme.transitions.create('width'), }, appBarHome: { backgroundColor: 'transparent', boxShadow: 'none', }, [theme.breakpoints.up('lg')]: { drawer: { width: '250px', }, appBarShift: { width: '100%', }, navIconHide: { display: 'none', }, }, }) class AppFrame extends Component { state = { drawerOpen: false, } handleDrawerClose = () => { this.setState({ drawerOpen: false }) } handleDrawerToggle = () => { this.setState({ drawerOpen: !this.state.drawerOpen }) } handleToggleShade = () => { this.props.dispatch({ type: 'TOGGLE_THEME_SHADE' }) } render() { const { children, routes, width } = this.props const classes = this.props.classes const title = getTitle(routes) // let drawerDocked = isWidthUp('lg', width) const navIconClassName = '' let appBarClassName = classes.appBar if (title === null) { // home route, don't shift app bar or dock drawer // drawerDocked = false // appBarClassName += ` ${classes.appBarHome}` } else { // navIconClassName += ` ${classes.navIconHide}` appBarClassName += ` ${classes.appBarShift}` } return ( <div className={classes.root}> <AppBar className={appBarClassName}> <Toolbar> <IconButton color="contrast" aria-label="open drawer" onClick={this.handleDrawerToggle} className={navIconClassName} > <MenuIcon /> </IconButton> {title !== null && ( <Typography className={classes.title} type="title" color="inherit" noWrap > {title} </Typography> )} <div className={classes.grow} /> <IconButton title="Toggle light/dark theme" color="contrast" aria-label="change theme" onClick={this.handleToggleShade} > <LightbulbOutline /> </IconButton> <IconButton component="a" title="GitHub" color="contrast" href="https://github.com/sghall/react-compound-slider" > <Github /> </IconButton> </Toolbar> </AppBar> <AppDrawer className={classes.drawer} routes={routes} onRequestClose={this.handleDrawerClose} open={this.state.drawerOpen} /> {children} </div> ) } } AppFrame.propTypes = { children: PropTypes.node.isRequired, classes: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, routes: PropTypes.array.isRequired, width: PropTypes.string.isRequired, } export default compose( withStyles(styles, { name: 'AppFrame', }), withWidth(), connect(), )(AppFrame)
JavaScript
0.000002
@@ -403,23 +403,8 @@ idth -, %7B isWidthUp %7D fro @@ -2199,23 +2199,16 @@ , routes -, width %7D = thi @@ -4343,46 +4343,8 @@ ed,%0A - width: PropTypes.string.isRequired,%0A %7D%0A%0Ae
eee1532fc9b575b7e9eb4b8af4eeb5f812d6e4eb
Fix whitespace nits in lib/util.js.
lib/util.js
lib/util.js
;(function() { 'use strict'; /** Load Node.js modules */ var fs = require('fs'), path = require('path'); /** Load other modules */ var _ = require('lodash/lodash.js'); /** Used to indicate if running in Windows */ var isWindows = process.platform == 'win32'; /*--------------------------------------------------------------------------*/ /** * The path separator. * * @memberOf util.path * @type string */ var sep = path.sep || (isWindows ? '\\' : '/'); /** * The escaped path separator used for inclusion in RegExp strings. * * @memberOf util.path * @type string */ var sepEscaped = sep.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); /** Used to determine if a path is prefixed with a drive letter, dot, or slash */ var rePrefixed = RegExp('^(?:' + (isWindows ? '[a-zA-Z]:|' : '') + '\\.?)' + sepEscaped); /*--------------------------------------------------------------------------*/ /** * Makes the given `dirname` directory, without throwing errors for existing * directories and making parent directories as needed. * * @memberOf util.fs * @param {string} dirname The path of the directory. * @param {number|string} [mode='0777'] The permission mode. */ function mkdirpSync(dirname, mode) { // ensure relative paths are prefixed with `./` if (!rePrefixed.test(dirname)) { dirname = '.' + sep + dirname; } dirname.split(sep).reduce(function(currPath, segment) { currPath += sep + segment; try { currPath = fs.realpathSync(currPath); } catch(e) { fs.mkdirSync(currPath, mode); } return currPath; }); } /** * Removes files or directories and their contents recursively. * * @memberOf util.fs * @param {string} pathname The path of the file or directory. */ function rmrfSync(pathname) { // safety first, limit to modifying lodash-cli if (pathname.indexOf(path.dirname(__dirname) + sep) != 0) { return; } try { pathname = fs.realpathSync(pathname); } catch(e) { return; } if (!fs.statSync(pathname).isDirectory()) { fs.unlinkSync(pathname); return; } fs.readdirSync(pathname).forEach(function(identifier) { var currPath = path.join(pathname, identifier); if (fs.statSync(currPath).isDirectory()) { rmrfSync(currPath); } else { fs.unlinkSync(currPath); } }); fs.rmdirSync(pathname); } /*--------------------------------------------------------------------------*/ /** * The utility object. * * @type Object */ var util = { /** * The file system object. * * @memberOf util * @type Object */ 'fs': _.defaults(_.cloneDeep(fs), { 'existsSync': fs.existsSync || path.existsSync, 'mkdirpSync': mkdirpSync, 'rmrfSync': rmrfSync }), /** * The path object. * * @memberOf util * @type Object */ 'path': _.defaults(_.cloneDeep(path), { 'sep': sep, 'sepEscaped': sepEscaped }) }; /*--------------------------------------------------------------------------*/ // export module.exports = util; }());
JavaScript
0.000338
@@ -2639,28 +2639,30 @@ til = %7B%0A%0A + /**%0A + * The fi @@ -2671,32 +2671,33 @@ system object.%0A + *%0A * @mem @@ -2682,32 +2682,33 @@ ect.%0A *%0A + * @memberOf util @@ -2704,32 +2704,33 @@ mberOf util%0A + * @type Object%0A @@ -2720,32 +2720,33 @@ * @type Object%0A + */%0A 'fs': @@ -2901,20 +2901,22 @@ %7D),%0A%0A + /**%0A + * Th @@ -2926,24 +2926,25 @@ ath object.%0A + *%0A * @@ -2937,24 +2937,25 @@ %0A *%0A + * @memberOf @@ -2959,24 +2959,25 @@ Of util%0A + * @type Obje @@ -2975,24 +2975,25 @@ type Object%0A + */%0A '
e0cc42236e3d080a515fd6266a3668ab417484bc
remove excess property
app/state.js
app/state.js
import * as EDITOR_MODE from './constants/editorModes'; import * as NODE_CATEGORY from './constants/nodeCategory'; import * as PIN_DIRECTION from './constants/pinDirection'; import * as PIN_TYPE from './constants/pinType'; import { PROPERTY_TYPE, PROPERTY_DEFAULT_VALUE } from './constants/property'; const initialState = { project: { meta: { name: 'Awesome project', author: 'Amperka team', }, patches: { 1: { id: 1, name: 'Skynet', }, }, nodes: { 1: { id: 1, typeId: 4, label: 'Blue LED', patchId: 1, position: { x: 320, y: 120, }, props: { brightness: 0.67, }, }, 2: { id: 2, typeId: 1, patchId: 1, position: { x: 360, y: 300, }, }, 3: { id: 3, typeId: 3, label: 'My potentiometer with a knob', patchId: 1, position: { x: 160, y: 90, }, }, 4: { id: 4, typeId: 2, patchId: 1, position: { x: 170, y: 380, }, }, 5: { id: 5, typeId: 5, patchId: 1, position: { x: 100, y: 185, }, }, }, pins: { 1: { id: 1, nodeId: 1, key: 'brightness', }, 2: { id: 2, nodeId: 2, key: 'in', }, 3: { id: 3, nodeId: 2, key: 'out', }, 4: { id: 4, nodeId: 3, key: 'out', }, 5: { id: 5, nodeId: 4, key: 'in', }, 6: { id: 6, nodeId: 4, key: 'ifFalse', }, 7: { id: 7, nodeId: 4, key: 'ifTrue', }, 8: { id: 8, nodeId: 4, key: 'out', }, 9: { id: 9, nodeId: 5, key: 'value', }, }, links: { 1: { id: 1, pins: [4, 1], }, 2: { id: 2, pins: [4, 6], }, }, }, editor: { currentPatchId: 1, mode: EDITOR_MODE.EDITING, dragging: null, selection: [], linkingPin: null, selectedNodeType: 1, }, nodeTypes: { 1: { id: 1, label: 'Not', category: NODE_CATEGORY.FUNCTIONAL, pins: { in: { key: 'in', type: PIN_TYPE.BOOL, direction: PIN_DIRECTION.INPUT, }, out: { key: 'out', type: PIN_TYPE.BOOL, direction: PIN_DIRECTION.OUTPUT, }, }, }, 2: { id: 2, label: 'Either', category: NODE_CATEGORY.FUNCTIONAL, pins: { in: { key: 'in', type: PIN_TYPE.BOOL, direction: PIN_DIRECTION.INPUT, label: 'IN', }, ifTrue: { key: 'ifTrue', type: PIN_TYPE.BOOL, direction: PIN_DIRECTION.INPUT, label: 'T', }, ifFalse: { key: 'ifFalse', type: PIN_TYPE.BOOL, direction: PIN_DIRECTION.INPUT, label: 'F', }, out: { key: 'out', type: PIN_TYPE.BOOL, direction: PIN_DIRECTION.OUTPUT, }, }, }, 3: { id: 3, label: 'Pot', category: NODE_CATEGORY.HARDWARE, pins: { out: { key: 'out', type: PIN_TYPE.NUMBER, direction: PIN_DIRECTION.OUTPUT, }, }, }, 4: { id: 4, label: 'LED', category: NODE_CATEGORY.HARDWARE, pins: { brightness: { key: 'brightness', type: PIN_TYPE.NUMBER, direction: PIN_DIRECTION.INPUT, }, }, }, 5: { id: 5, label: 'Servo', category: NODE_CATEGORY.HARDWARE, pins: { value: { key: 'value', type: PIN_TYPE.NUMBER, direction: PIN_DIRECTION.INPUT, }, }, }, 6: { id: 6, label: 'Constant:Bool', category: NODE_CATEGORY.CONFIGURATION, pins: { value: { key: 'value', type: PIN_TYPE.BOOL, direction: PIN_DIRECTION.OUTPUT, }, }, properties: { value: { key: 'value', label: 'Value', type: PROPERTY_TYPE.BOOL, defaultValue: PROPERTY_DEFAULT_VALUE.BOOL, }, }, }, 7: { id: 7, label: 'Constant:Number', category: NODE_CATEGORY.CONFIGURATION, pins: { value: { key: 'value', type: PIN_TYPE.NUMBER, direction: PIN_DIRECTION.OUTPUT, }, }, properties: { value: { key: 'value', label: 'Value', type: PROPERTY_TYPE.NUMBER, defaultValue: PROPERTY_DEFAULT_VALUE.NUMBER, }, }, }, 8: { id: 8, label: 'Constant:String', category: NODE_CATEGORY.CONFIGURATION, pins: { value: { key: 'value', type: PIN_TYPE.STRING, direction: PIN_DIRECTION.OUTPUT, }, }, properties: { value: { key: 'value', label: 'Value', type: PROPERTY_TYPE.STRING, defaultValue: PROPERTY_DEFAULT_VALUE.STRING, }, }, }, 9: { id: 9, label: 'IMU', category: NODE_CATEGORY.HARDWARE, pins: { yaw: { key: 'yaw', type: PIN_TYPE.NUMBER, direction: PIN_DIRECTION.OUTPUT, label: 'YAW', }, pitch: { key: 'pitch', type: PIN_TYPE.NUMBER, direction: PIN_DIRECTION.OUTPUT, label: 'PIT', }, roll: { key: 'roll', type: PIN_TYPE.NUMBER, direction: PIN_DIRECTION.OUTPUT, label: 'ROL', }, }, }, }, errors: [], }; export default initialState;
JavaScript
0.000032
@@ -668,64 +668,8 @@ %7D,%0A - props: %7B%0A brightness: 0.67,%0A %7D,%0A
0d520042572e4eb82036d12495cee1f996a5554f
use inherits or instances do not pass instanceof check
lib/util.js
lib/util.js
'use strict'; exports = module.exports = {}; // dependencies // exports.once = require('once'); exports.type = require('utils-type'); exports.clone = require('lodash.clone'); exports.merge = require('lodash.merge'); exports.inherits = require('inherits'); exports.asyncDone = require('async-done'); // assorted util // exports.mapFrom = function (argv, args, pos) { var index = -1; var length = args.length; while (++pos < length) { argv[++index] = args[pos]; } }; exports.classFactory = function (SuperTor) { function createClass (mixin) { mixin = mixin || {}; var Tor = exports.type(mixin.create).function || function Tor (props) { if (!(this instanceof Tor)) { return new Tor(props); } SuperTor.call(this, props); }; delete mixin.create; Tor.super_ = SuperTor; exports.merge(Tor.prototype, SuperTor.prototype, mixin); Tor.create = function (a, b) { return new Tor(a, b); }; Tor.createClass = exports.classFactory(Tor); return Tor; } return createClass; };
JavaScript
0
@@ -807,20 +807,29 @@ -Tor.super_ = +exports.inherits(Tor, Sup @@ -833,16 +833,17 @@ SuperTor +) ;%0A ex
31fc956cccf19945954b60575b06a2ea31837201
Change to work with Express 4. Pipeline stack moved from application object to the application._route object
lib/util.js
lib/util.js
'use strict'; var fs = require('fs'); var path = require('path'); var touch = require('touch'); var connect = require('connect'); exports.touchFile = function touchFile(path) { touch.sync(path); } exports.makeServerTaskName = function makeServerTaskName(serverName, kind) { return 'express_' + serverName + '_' + kind; } exports.rearrangeMiddleware = function rearrangeMiddleware(server) { server.stack = (server.stack || []).sortBy(function(mw) { return mw.handle.middlewarePriority || 99; }); } exports.watchModule = function watchModule(watcher) { // hijack each module extension handler, and watch the file function injectWatcher(handler) { return function(module, filename) { fs.watchFile(filename, watcher); handler(module, filename); }; } for (var ext in require.extensions) { var handler = require.extensions[ext]; require.extensions[ext] = injectWatcher(handler); } } exports.assignMiddlewaresPriority = function assignMiddlewaresPriority(main, statics, additionals) { var staticsPlaceholderIndex = -1; // find the `staticsPlaceholder` index from the group of middlewares injected by grunt config additionals.each(function(mw, index) { if (mw.name === 'staticsPlaceholder') { staticsPlaceholderIndex = index; } }); var globalStaticsPlaceholderIndex = main.findIndex(function(mw) { return mw.handle.name === 'staticsPlaceholder'; }); var middlewarePlaceholderIndex = main.findIndex(function(mw) { return mw.handle.name === 'middlewarePlaceholder'; }); var mainStackPriorities = [1, 3, 5]; var dynamicStack = []; var markers = []; if (globalStaticsPlaceholderIndex === -1) { if (staticsPlaceholderIndex !== -1) { [].splice.apply(additionals, [staticsPlaceholder, 0].concat(statics)); dynamicStack.push(additionals.map(function(mw) { mw.middlewarePriority = 2; })); } else { dynamicStack.push(statics.concat(additionals).map(function(mw) { mw.middlewarePriority = 2; })); } if (middlewarePlaceholderIndex !== -1) { markers = [middlewarePlaceholderIndex]; } else { markers = [main.length - 1]; } } else { var temp; if (globalStaticsPlaceholderIndex < middlewarePlaceholderIndex) { temp = [statics, additionals]; markers = [globalStaticsPlaceholderIndex, middlewarePlaceholderIndex]; } else if (middlewarePlaceholderIndex !== -1) { temp = [additionals, statics]; markers = [middlewarePlaceholderIndex, globalStaticsPlaceholderIndex]; } else { temp = [statics, additionals]; markers = [globalStaticsPlaceholderIndex, main.length - 1]; } dynamicStack.push(temp[0].map(function(mw) { mw.middlewarePriority = 2; })); dynamicStack.push(temp[1].map(function(mw) { mw.middlewarePriority = 4; })); } var i = 0; var j = 0; while (j < markers.length) { while (i < markers[j]) { main[i++].handle.middlewarePriority = mainStackPriorities[j]; } j++; } } exports.runServer = function runServer(grunt, options) { options = Object.merge({ port: 3000, // hostname: 'localhost', bases: null, // string|array of each static folders server: null, showStack: false // (optional) filepath that points to a module that exportss a 'server' object that provides // 1. a 'listen' function act like http.Server.listen (which connect.listen does) // 2. a 'use' function act like connect.use }, options); var middlewares = options.middleware || []; var statics = []; if (options.bases) { // wrap each path in connect.static middleware options.bases.each(function(b) { statics.push(connect.static(b)); }); } var server; if (options.server) { try { server = require(path.resolve(options.server)); if (typeof server.listen !== 'function') { grunt.fatal('Server should provide a function called "listen" that acts as http.Server.listen'); } if (typeof server.use !== 'function') { grunt.fatal('Server should provide a function called "use" that acts as connect.use'); } } catch (e) { var errorMessage = options.showStack ? '\n' + e.stack : e; grunt.fatal('Server ["' + options.server + '"] - ' + errorMessage); } if(server.stack) { this.assignMiddlewaresPriority(server.stack, statics, middlewares); } middlewares.concat(statics).each(function(mw) { server.use(mw); }) } else { server = connect.apply(null, statics.concat(middlewares)); } if (options.livereload && options.insertConnectLivereload !== false) { var lr = require('connect-livereload')({ port: options.livereload }); lr.middlewarePriority = -1; server.use(lr); } this.rearrangeMiddleware(server); // console.log(server.stack) if (options.hostname === '*') { delete options.hostname; } // Start server. (function startServer (port) { // grunt.config.set( var args = [port, function() { server.emit('startListening', this); grunt.log.writeln('Web server started on port:' + port + (options.hostname ? ', hostname: ' + options.hostname : ', no hostname specified') + ' [pid: ' + process.pid + ']'); } ]; // always default hostname to 'localhost' would prevent access using IP address if (options.hostname) { args.splice(1, 0, options.hostname); } server.listen.apply(server, args) .on('error', function(err) { if (err.code === 'EADDRINUSE') { grunt.log.writeln('Port ' + port + ' in use'); startServer(++port); } else { grunt.fatal(err); } }); })(options.port); return server; }
JavaScript
0
@@ -383,19 +383,24 @@ leware(s -erv +tackHold er) %7B%0A @@ -400,19 +400,24 @@ r) %7B%0A s -erv +tackHold er.stack @@ -421,19 +421,24 @@ ack = (s -erv +tackHold er.stack @@ -4348,15 +4348,84 @@ -if(serv +var stackHolder = server._router ? server._router : server;%0A if(stackHold er.s @@ -4470,19 +4470,24 @@ iority(s -erv +tackHold er.stack @@ -4920,19 +4920,24 @@ leware(s -erv +tackHold er);%0A / @@ -4951,19 +4951,24 @@ le.log(s -erv +tackHold er.stack
e24984bb2d2768ac24c61f17e4ff8c70c08df85f
Add http protocol to request util.
lib/util.js
lib/util.js
"use strict"; function log(...args) { const now = new Date().toLocaleString("en-US", { month: "short", day: "2-digit", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }); console.log(now, ...args); // eslint-disable-line no-console } const urlParse = require("url").parse; const https = require("https"); const querystring = require("querystring"); const EventEmitter = require("events"); const HttpsProxyAgent = require("https-proxy-agent"); function request({ url = "", method = "GET", headers = {}, body = null, qs = {} } = {}, callback) { const ee = new EventEmitter(); const reqUrl = urlParse(url); const host = reqUrl.hostname; const port = reqUrl.port || 443; let path = reqUrl.path; if (method === "GET" && Object.keys(qs).length) { path += `?${querystring.stringify(qs)}`; } if (body) { headers["Content-Type"] = "application/json"; headers["Content-Length"] = JSON.stringify(body).length; } const requestOptions = { host, port, path, method, headers }; function requestResponse(res) { ee.emit("response"); res.setEncoding("utf8"); let rawData = ""; res.on("data", chunk => { ee.emit("data", chunk); rawData += chunk; }); res.on("end", () => callback(null, res, rawData)); } if (process.env.https_proxy) { requestOptions.agent = new HttpsProxyAgent(process.env.https_proxy); } const req = https.request(requestOptions, requestResponse); req.on("error", err => callback(err)); if (body) { req.write(JSON.stringify(body)); } req.end(); return ee; } exports.log = log; exports.request = request;
JavaScript
0
@@ -378,24 +378,54 @@ e(%22https%22);%0A +const http = require(%22http%22);%0A const querys @@ -740,16 +740,66 @@ e(url);%0A + const isHttps = reqUrl.protocol === %22https:%22;%0A cons @@ -860,11 +860,28 @@ %7C%7C -443 +(isHttps ? 443 : 80) ;%0A%0A @@ -1582,20 +1582,30 @@ %7D%0A%0A -if ( +const proxy = process. @@ -1619,16 +1619,58 @@ ps_proxy + %7C%7C process.env.http_proxy;%0A%0A if (proxy ) %7B%0A @@ -1723,46 +1723,135 @@ (pro -cess.env.https_proxy);%0A %7D%0A const +xy);%0A %7D%0A%0A let req;%0A%0A if (isHttps) %7B%0A req = https.request(requestOptions, requestResponse);%0A %7D else %7B%0A req @@ -1849,33 +1849,32 @@ req = http -s .request(request @@ -1899,16 +1899,22 @@ sponse); +%0A %7D %0A%0A re
32309fd06dac3bd8dbf5d6836f73cbd6009c5b1e
set new release branch for v2
gulpfile.js
gulpfile.js
/* eslint-disable no-unused-vars */ // npm run release -- --addition,subtraction const { series } = require('gulp'); const fs = require('fs'); const { join } = require('path'); const { spawn } = require('child_process'); const { PublishCommand } = require('@lerna/publish'); const git = require('simple-git/promise')(__dirname); const sync = require('./scripts/preversion/sync.js'); const stableBranch = 'master'; const releaseBranch = 'release'; const ignored = ['.git', '.log', 'node_modules', 'packages', '.md', 'package-lock', '.vscode', 'demos', 'live-examples', '.cache', 'archive']; const packagesDirectory = join(__dirname, '/packages/'); let packagesDirNamesToRelease = []; let fullRelease = false; const readDirPromise = (directory) => { return new Promise((resolve, reject) => { fs.readdir(directory, (err, files) => { if (err) { return reject(err); } resolve(files); }); }); }; const validateReleasePackages = async () => { packagesDirNamesToRelease = process.argv[3].replace('--', '').split(','); if (packagesDirNamesToRelease.includes('all')) { fullRelease = true; return; } const areNamesValidType = packagesDirNamesToRelease.every((name) => (typeof name === 'string') && name.length > 0); if (!areNamesValidType) { throw new Error(`Invalid packages names: ${JSON.stringify(packagesDirNamesToRelease)}`); } const areNamesExisting = packagesDirNamesToRelease.every((pkgName) => fs.existsSync(join(packagesDirectory, pkgName))); if (!areNamesExisting) { throw new Error(`Non-existent packages names: ${JSON.stringify(packagesDirNamesToRelease)}`); } }; const checkout = async (branchName) => { await git.checkout(branchName); }; const checkoutRelease = async () => { await checkout(releaseBranch); await git.pull(); }; const checkoutMaster = async () => { await checkout(stableBranch); process.exitCode = 0; }; const syncAllContentsExceptPackages = async () => { const rootContents = await readDirPromise(__dirname); const itemToSync = rootContents.filter((element) => !ignored.some((igElement) => element.includes(igElement))); itemToSync.push('.gitignore'); for (const item of itemToSync) { console.log(`checking out ${item}`); await git.raw(['checkout', stableBranch, item]); } }; const syncPackagesToRelease = async () => { if (fullRelease) { console.log('Checking out all packages for full release'); await git.raw(['checkout', stableBranch, 'packages/']); return; } for (const packageName of packagesDirNamesToRelease) { console.log(`checking out ${packageName}`); await git.raw(['checkout', stableBranch, `packages/${packageName}`]); } }; const bootstrap = () => { return new Promise((resolve, reject) => { const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm'; const child = spawn(npmCommand, ['run', 'bootstrap'], { stdio: 'inherit' }); child.on('error', reject); child.on('exit', (code) => { if (code === 1) { reject(); } resolve(); }); }); }; const versionSync = async () => { await sync(git, false); }; const addCommit = async (message) => { await git.add('.'); await git.commit(message, undefined, { '--no-verify': null }); }; const commitIsolatedPackages = async () => { await addCommit('Release package/s isolated'); }; const publish = async () => { const command = new PublishCommand({}); await command.runner; }; // exports.release = series( // validateReleasePackages, // checkoutRelease, // syncAllContentsExceptPackages, // syncPackagesToRelease, // bootstrap, // versionSync, // commitIsolatedPackages, // publish, // checkoutMaster // ); // stopped publish and checkoutMaster to allow for dist-tags exports.release = series( validateReleasePackages, checkoutRelease, syncAllContentsExceptPackages, syncPackagesToRelease, bootstrap, versionSync, commitIsolatedPackages );
JavaScript
0
@@ -438,16 +438,19 @@ 'release +-V2 ';%0Aconst
95d095ef76184679e176aa8c25d460a09124285a
Improve parsing data
src/main/webapp/parse.js
src/main/webapp/parse.js
// Copyright 2020 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. /** * parse.js * * MediaWiki API Demos * Demo of `Parse` module: Parse content of a page * * MIT License */ function sendData() { var url; const type = document.getElementById("type").innerText ?? ""; try { url = "https://en.wikibooks.org/w/api.php?" + new URLSearchParams({ origin: "*", action: "parse", page: `Cookbook:${document.getElementById("input-text").value}`, format: "json", prop: "text", }); } catch(error) { console.log(error); } fetch(url) .then(response => response.json()) .then((jsonData) => { const container = document.getElementById("data-container"); container.innerHTML = jsonData.parse.text['*']; try { const ingrHTML = document.getElementsByTagName("ul").item(0).children; const list = document.getElementsByClassName("mw-parser-output")[0]; const descriptionHTML = list.getElementsByTagName("p")[1]; const title = jsonData.parse.title.replace("Cookbook:", "").toLowerCase(); const description = descriptionHTML.textContent; const ingredients = Array.from(ingrHTML).map(el => el.innerText); // Create JSON String for Meal object. // By default id of object is 0, before putting object to Datastore // id is initialized. data = JSON.stringify( { id: 0, title: title, description: description, type: type, ingredients: ingredients }); return fetch("/import", { method: 'POST', body: data, headers: { 'Content-type': 'application/json' } }); } catch (error) { console.log(error); } }); }
JavaScript
0.001906
@@ -735,52 +735,148 @@ -const type = document.getElementById(%22type%22) +//%C2%A0Get%C2%A0type%C2%A0of%C2%A0meal.%0A%C2%A0%C2%A0%C2%A0%C2%A0var%C2%A0typeSelector%C2%A0=%C2%A0document.getElementById(%22type%22);%0A%C2%A0%C2%A0%C2%A0%C2%A0var%C2%A0type%C2%A0=%C2%A0typeSelector.options%5BtypeSelector.selectedIndex%5D .inn @@ -885,12 +885,12 @@ Text - ?? +%C2%A0??%C2%A0 %22%22;%0A @@ -1673,152 +1673,231 @@ nst -descriptionHTML = list.getElementsByTagName(%22p%22)%5B1%5D;%0A const title = jsonData.parse.title.replace(%22Cookbook:%22, %22%22).toLowerCase();%0A +ingredients = Array.from(ingrHTML).map(el =%3E el.innerText);%0A const descriptionHTML = list.getElementsByTagName(%22p%22)%5B1%5D;%0A var description = %22%22;%0A if (descriptionHTML != null) %7B%0A @@ -1900,37 +1900,32 @@ -const description = d @@ -1950,16 +1950,22 @@ tContent + ?? %22%22 ;%0A @@ -1978,71 +1978,98 @@ -const ingredients = Array.from(ingrHTML).map(el =%3E el.innerText +%7D%0A const title = jsonData.parse.title.replace(%22Cookbook:%22, %22%22).toLowerCase( );%0A
c8e902ee3ba4aff984a85a75b8cb716b9c9ea74b
Fix gulpfile case-sensitive src build commands
gulpfile.js
gulpfile.js
(function () { 'use strict'; // Initialize variables var gulp = require('gulp'); var del = require('del'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); // Initialize Panda Libraries var panda = [ // Panda 'src/Panda.js', // Base packages 'src/Panda/*.js', // Debug package 'src/Panda/Debug/*.js', // Environment package 'src/Panda/Env/*.js', // Events package 'src/Panda/Events/*.js', // Helpers package 'src/Panda/Helpers/*.js', // Http package 'src/Panda/Http/*.js', 'src/Panda/Http/Jar/*.js', // Main files 'src/Init.js' ]; var version = '1.3.0'; // Set default gulp task gulp.task('default', ['build']); // Compress files task gulp.task('build', ['minify']); // Minify files gulp.task('minify', ['concat', 'concat-with-jq'], function () { return gulp.src(['./dist/*.js']) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('./dist/')); }); // Concat source files gulp.task('concat', function () { // Clean files del('./dist/*'); // build without jQuery return gulp.src(panda) .pipe(concat('panda-' + version + '.js')) .pipe(gulp.dest('./dist/')); }); // Concat source files gulp.task('concat-with-jq', function () { // Clean files del('./dist/*'); // build with jQuery return gulp.src(['src/jquery/jquery-2.2.4.js'].concat(panda)) .pipe(concat('panda-' + version + '.jq.js')) .pipe(gulp.dest('./dist/')); }); }());
JavaScript
0.000074
@@ -369,25 +369,25 @@ 'src/ -P +p anda/*.js',%0A @@ -429,15 +429,15 @@ src/ -P +p anda/ -D +d ebug @@ -489,23 +489,23 @@ 'src/ -P +p anda/ -E +e nv/*.js' @@ -550,15 +550,15 @@ src/ -P +p anda/ -E +e vent @@ -607,23 +607,23 @@ 'src/ -P +p anda/ -H +h elpers/* @@ -662,31 +662,31 @@ 'src/ -P +p anda/ -H +h ttp/*.js',%0A @@ -701,15 +701,15 @@ src/ -P +p anda/ -H +h ttp/ @@ -1654,20 +1654,9 @@ ery/ -jquery-2.2.4 +* .js'
66f9886bc169c7c1d53fe2b2c6569a8277642408
Set port=undefined by default
lib/util.js
lib/util.js
const parseurl = require('parseurl'); const zlib = require('zlib'); const request = require('request'); const urlParse = require('url').parse; const { PassThrough } = require('stream'); exports.isFunction = fn => typeof fn === 'function'; exports.noop = () => {}; const getCharset = (headers) => { if (/charset=([^\s]+)/.test(headers['content-type'])) { return RegExp.$1; } return 'utf8'; }; exports.getCharset = getCharset; exports.isText = (headers) => { const type = headers['content-type']; return !type || /(javascript|css|html|json|xml)|text\//i.test(type); }; const HOST_RE = /^([^:]+):(\d+)$/; const parseArguments = (args) => { if (!args.length || !args[0]) { return {}; } const options = args[0]; if (HOST_RE.test(options)) { return { host: RegExp.$1, port: RegExp.$2, }; } if (typeof options === 'string') { return { host: options, port: args[1] > 0 ? args[1] : null, }; } if (!(options.port > 0)) { delete options.port; if (HOST_RE.test(options)) { options.host = RegExp.$1; options.port = RegExp.$2; } } if (typeof options.host !== 'string') { delete options.host; } return options; }; exports.parseArguments = parseArguments; const getValueFromHeaders = (headers, name) => { name = headers[name]; return name ? decodeURIComponent(name) : ''; }; exports.getValueFromHeaders = getValueFromHeaders; exports.getCustomHost = (headers, options) => { const host = getValueFromHeaders(headers, options.LOCAL_HOST_HEADER); return parseArguments([host]); }; const getRuleValue = (headers, options) => { const value = headers[options.RULE_VALUE_HEADER]; if (!value) { return; } return decodeURIComponent(value); }; exports.getRuleValue = getRuleValue; exports.request = (ctx, opts) => { opts = opts || {}; const req = ctx.req; const options = parseurl(req); options.followRedirect = req.followRedirect || false; options.headers = req.headers || {}; options.method = req.method; options.body = req; delete options.protocol; if (opts.host || options.port > 0) { const uri = options.uri = urlParse(ctx.fullUrl); if (opts.host) { uri.hostname = opts.host; delete opts.hostname; } if (opts.port > 0) { uri.port = opts.port; } } else { options.uri = urlParse(ctx.fullUrl); } if (req.body !== undefined) { delete req.headers['content-encoding']; options.body = req.body; } options.encoding = null; const transform = new PassThrough(); return new Promise((resolve, reject) => { delete options.headers['content-length']; delete options.headers['transfer-encoding']; const res = request(options); res.pipe(transform); res.on('error', reject); res.on('response', ({ statusCode, headers }) => { res.on('error', err => transform.emit('error', err)); transform.statusCode = statusCode; transform.headers = headers; resolve(transform); }); }); }; const unzipBody = (headers, body, callback) => { let unzip; let encoding = headers['content-encoding']; if (body && typeof encoding === 'string') { encoding = encoding.trim().toLowerCase(); if (encoding === 'gzip') { unzip = zlib.gunzip.bind(zlib); } else if (encoding === 'gzip') { unzip = zlib.inflate.bind(zlib); } } if (!unzip) { return callback(null, body); } unzip(body, (err, data) => { if (err) { return zlib.inflateRaw(body, callback); } callback(null, data); }); }; exports.getStreamBuffer = (stream) => { return new Promise((resolve, reject) => { let buffer; stream.on('data', (data) => { buffer = buffer ? Buffer.concat([buffer, data]) : data; }); stream.on('end', () => { unzipBody(stream.headers, buffer, (err, data) => { if (err) { reject(err); } else { resolve(data || null); } }); }); stream.on('error', reject); }); }; exports.setupContext = (ctx, options) => { ctx.options = options; ctx.reqOptions = parseurl(ctx.req); const fullUrl = getValueFromHeaders(ctx.headers, options.FULL_URL_HEADER); ctx.fullUrl = fullUrl; }; exports.responseRules = (ctx) => { if (!ctx.body && (ctx.rules || ctx.values)) { ctx.body = { rules: Array.isArray(ctx.rules) ? ctx.rules.join('\n') : `${ctx.rules}`, values: ctx.values, }; } };
JavaScript
0.000019
@@ -934,20 +934,25 @@ gs%5B1%5D : -null +undefined ,%0A %7D;
b3f4d67a7c9ea2d05db6fbf69639af351b23d3f2
update 'instances destroy' command
lib/cast-client/commands/instances/destroy.js
lib/cast-client/commands/instances/destroy.js
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick 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. */ var sys = require('sys'); var fs = require('fs'); var path = require('path'); var sprintf = require('sprintf').sprintf; var async = require('async'); var term = require('terminal'); var http = require('util/http'); var misc = require('util/misc'); var clientUtils = require('util/client'); var config = { shortDescription: 'Destroy an instance', longDescription: 'Destroy an instance and all of its data and services.', requiredArguments: [ ['name', 'The name of the instance to be destroyed'] ], optionalArguments: [], usesGlobalOptions: ['debug', 'remote'] }; function DestroyDeclinedError() { this.message = 'User declined to destroy instance'; } sys.inherits(DestroyDeclinedError, Error); function handleCommand(args, parser, callback) { var instanceName = args.name; async.series([ function(callback) { var promptStr = 'Are you sure you want to destroy \'' + instanceName + '\'?'; term.prompt(promptStr, ['y', 'n'], 'n', null, function(resp) { if (resp !== 'y') { callback(new DestroyDeclinedError()); return; } else { callback(); return; } }); }, function(callback) { var remotePath = sprintf('/instances/%s/', instanceName); http.getApiResponse(remotePath, 'DELETE', { 'remote': args.remote, 'apiVersion': '1.0', 'parseJson': true, 'expectedStatusCodes': [200]}, function(err, response) { if (err) { callback(err); return; } callback(); }); } ], function(err) { var successMessage = null; if (err) { if (err instanceof DestroyDeclinedError) { err = null; successMessage = 'Ok, destroy operation canceled'; } } else { successMessage = sprintf('Instance "%s" destroyed.', instanceName); } callback(err, successMessage); }); } exports.config = config; exports.handleCommand = handleCommand;
JavaScript
0.000001
@@ -1631,17 +1631,16 @@ back) %7B%0A -%0A va @@ -2075,57 +2075,25 @@ ttp. -getApiResponse(remotePath, 'DELETE', %7B 'r +executeR emote -': +Job( args @@ -2104,382 +2104,39 @@ ote, -%0A 'apiVersion': '1.0',%0A 'parseJson': true,%0A 'expectedStatusCodes': %5B200%5D%7D,%0A function(err, response) %7B%0A if (err) %7B%0A callback(err);%0A return;%0A %7D%0A%0A callback();%0A %7D + remotePath, 'DELETE', callback );%0A
d676e87d43a915201448730a5e5f652ae87498f2
add leveldown classic build task
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var coffee = require('gulp-coffee'); var shell = require('gulp-shell'); var zip = require('gulp-zip'); var concat = require('gulp-concat'); var del = require('del'); var nwVersion = '0.8.6'; var paths = { scripts: ['backend/*.coffee'], scriptsJS: ['backend/*.js'], all: ["backend/**/*.js", "client/public/**", "app.html", "package.json", "node_modules/**"], leveldown: 'node_modules/pouchdb/node_modules/leveldown' }; gulp.task('clean', function(cb) { del(paths.scriptsJS, cb); }); gulp.task('scripts', ['clean'], function() { return gulp.src(paths.scripts) .pipe(coffee({bare: true})) .pipe(gulp.dest('backend')); }); gulp.task('watch', function() { gulp.watch(paths.scripts, ['scripts']); }); gulp.task('leveldown', shell.task([ 'cd ' + paths.leveldown + ' && nw-gyp configure --target=' + nwVersion, 'cd ' + paths.leveldown + ' && nw-gyp build' ])); gulp.task('builder', ['scripts', 'leveldown'], function() { var NwBuilder = require('node-webkit-builder'); var nw = new NwBuilder({ files: paths.all, version: nwVersion, platforms: ['linux64'] }); nw.build().then(function () { console.log('Cozy Data Proxy was successfully built.'); }).catch(function (error) { console.log('An error occured whild building Cozy Data Proxy.'); console.log(error); }); }); gulp.task('default', ['watch']);
JavaScript
0.000001
@@ -911,24 +911,125 @@ uild'%0A%5D));%0A%0A +gulp.task('leveldown-classic', shell.task(%5B%0A 'rm -rf ./node_modules/pouchdb',%0A 'npm install'%0A%5D));%0A%0A gulp.task('b
8250aaef5e6597dd0e84d3da7bff0d5cc54c9ddf
Fix jshint gulp src files
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var react = require('gulp-react'); var jshint = require('gulp-jshint'); var jsFiles = [ 'app/**/*.js', 'test/**/*.js', 'buildprod.js', 'env.js', 'gulpfile.js', 'webpack.config.js', 'server.js', 'webpack.config.prod.js' ]; gulp.task('jshint', function(cb) { var stream = gulp.src(jsFiles) .pipe(react()) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); if (process.env.CI) { stream = stream.pipe(jshint.reporter('fail')); } stream.on('end', cb); }); gulp.task('jshint-watch', ['jshint'], function(cb){ gulp.watch(jsFiles, ['jshint']); cb(); console.log('Watching files for changes...'); }); gulp.task('default', ['jshint']);
JavaScript
0.000002
@@ -152,112 +152,9 @@ %0A ' -buildprod.js',%0A 'env.js',%0A 'gulpfile.js',%0A 'webpack.config.js',%0A 'server.js',%0A 'webpack.config.prod +* .js'
20073b42d97078d9a0dc525e2751c18ce77c0dba
Fix typo in gulpfile.js
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var concat = require('gulp-concat'); var env = process.env.NODE_ENV ? 'prod' : 'dev'; ////////////////// // Source Files // ////////////////// var source = {}; source.js = {}; source.js.vendor = {}; source.js.src = {}; source.css = {}; source.css.vendor = {}; source.css.src = {}; source.js.vendor.dev = [ "public/lib/angular/angular.js", "public/lib/ui-router/release/angular-ui-router.js", "public/lib/angular-animate/angular-animate.js", "public/lib/angular-aria/angular-aria.js", "public/lib/angular-material/angular-material.js", ]; source.js.vendor.prod = [ "public/lib/angular/angular.min.js", "public/lib/ui-router/release/angular-ui-router.min.js", "public/lib/angular-animate/angular-animate.min.js", "public/lib/angular-aria/angular-aria.min.js", "public/lib/angular-material/angular-material.min.js", ]; source.css.vendor.dev= [ "public/lib/angular-material/angular-material.css", ]; source.css.vendor.prod= [ "public/lib/angular-material/angular-material.min.css", ]; source.js.src= [ "public/js/app.js", ]; source.css.src= [ "public/styles/style.css", ]; gulp.task('default', function() { console.log('Compiling files...'); gulp.src(source.js.vendor[env]) .pipe(concat('vendor.js')) .pipe(gulp.dest('public/dist/')); gulp.src(source.js.src) .pipe(concat('main.js')) .pipe(gulp.dest('public/dist/')); gulp.src(source.js.vendor[env]) .pipe(concat('vendor.css')) .pipe(gulp.dest('public/dist/')); gulp.src(source.css.src) .pipe(concat('main.css')) .pipe(gulp.dest('public/dist/')); console.log('Finished compiling files.'); });
JavaScript
0.997618
@@ -1417,33 +1417,34 @@ gulp.src(source. -j +cs s.vendor%5Benv%5D)%0A
ba4f5b10033930864fa37e00fdf6724be60535f1
Switch to ES5 style import
gulpfile.js
gulpfile.js
'use strict'; const path = require('path'); const gulp = require('gulp'); const eslint = require('gulp-eslint'); const excludeGitignore = require('gulp-exclude-gitignore'); const mocha = require('gulp-mocha'); const plumber = require('gulp-plumber'); const babel = require('gulp-babel'); const del = require('del'); import run from "gulp-run-command"; // Initialize the babel transpiler so ES2015 files gets compiled // when they're loaded require('babel-core/register'); gulp.task('static', () => gulp.src('**/*.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()) ); gulp.task('watch', () => { gulp.watch(['lib/**/*.js', 'test/**'], ['test']); }); gulp.task('test-coverage', [run('npm i nyc')]) gulp.task('test', ['test-coverage']) gulp.task('babel', ['clean'], () => gulp.src('lib/**/*.js') .pipe(babel()) .pipe(gulp.dest('dist')) ); gulp.task('clean', () => del('dist')); gulp.task('prepublish', ['babel']); gulp.task('default', ['static', 'test']);
JavaScript
0
@@ -314,25 +314,29 @@ ');%0A -impor +cons t run -from %22 += require(' gulp @@ -351,10 +351,18 @@ mand -%22; +').default %0A%0A//
4d2d0c37dd5ec638d9e1167051584cbba4d3097b
Remove window thing
js/main.js
js/main.js
(function () { 'use strict'; var diskStyles = { backgroundColor : 'white', borderColor : 'black' }; var diskOptions = { opacity : false, running : true, width : 400 }; function Disk(radius, xy) { var disk = document.createElement('div'); disk.className = 'disk'; disk.style.width = (radius * 2) + 'px'; disk.style.height = (radius * 2) + 'px'; disk.style.left = (xy[0] === radius ? 0 : (xy[0] - radius)) + 'px'; disk.style.top = (xy[1] === radius ? 0 : (xy[1] - radius)) + 'px'; return disk; } function polar2cart(radius, angle) { return [ radius * Math.cos(angle), radius * Math.sin(angle) ]; } function run() { var edgeContainer = document.getElementById('container'), centeringElem = document.createElement('div'); centeringElem.className = 'center'; var duration = 2.0, fps = 20, ndisks_per_cycle = 8, speed = 0.05; var circle1 = Disk(0.65 * diskOptions.width, [0.65 * diskOptions.width, 0.65 * diskOptions.width]), circle2 = Disk(0.42 * diskOptions.width, [0.42 * diskOptions.width, 0.42 * diskOptions.width]); circle2.appendChild(centeringElem); circle1.appendChild(circle2); edgeContainer.appendChild(circle1); function make_frame(t) { var delay_between_disks = 1.0 * duration / 2 / ndisks_per_cycle, total_number_of_disks = parseInt(ndisks_per_cycle / speed, 10), start = 1.0 / speed; centeringElem.innerHTML = ''; for (var i = 0; i < total_number_of_disks; i++) { var angle = (Math.PI / ndisks_per_cycle) * (total_number_of_disks - i - 1), radius = Math.max(0, 0.05 * (t + start - delay_between_disks * (total_number_of_disks - i - 1))); var cartCoords = polar2cart(radius, angle); cartCoords[0] = (cartCoords[0] + 0.5) * diskOptions.width; cartCoords[1] = (cartCoords[1] + 0.5) * diskOptions.width; var color = ((1.0 * i / ndisks_per_cycle) % 1.0), circle = Disk(0.3 * diskOptions.width, cartCoords); circle.style.borderColor = diskStyles.borderColor; circle.style.backgroundColor = diskStyles.backgroundColor; circle.style.opacity = diskOptions.opacity ? color : 1; centeringElem.appendChild(circle); } } var t = 0, frameRate = duration * fps; window.setInterval(function () { if (!diskOptions.running) return; var frame = t / fps; if (t === frameRate) { t = 0; } make_frame(frame); t++; }, frameRate); } function configureToggles() { var toggles = document.getElementsByTagName('input'); toggles.opacity.addEventListener('change', function() { diskOptions.opacity = this.checked; }); toggles.inverse.addEventListener('change', function() { var temp = diskStyles.backgroundColor; diskStyles.backgroundColor = diskStyles.borderColor; diskStyles.borderColor = temp; }); toggles.running.addEventListener('change', function() { diskOptions.running = this.checked; }); toggles.width.addEventListener('change', function() { diskOptions.width = this.value; }); toggles.colorbg.addEventListener('change', function() { diskStyles.backgroundColor = this.value; }); toggles.colorborder.addEventListener('change', function() { diskStyles.borderColor = this.value; }); } window.diskOptions = diskOptions; configureToggles(); run(); })();
JavaScript
0
@@ -3255,44 +3255,8 @@ %09%7D%0A%0A -%09window.diskOptions = diskOptions;%0A%0A %09con
75b1d6bdb1f2d3db292e5733c34dd5a69fc74e52
Fix Gulp watch mode for local development
gulpfile.js
gulpfile.js
/* eslint-env node */ const eslint = require('gulp-eslint'); const gulp = require('gulp'); const gutil = require('gulp-util'); const jest = require('gulp-jest').default; const rimraf = require('rimraf'); const runSequence = require('run-sequence'); const watch = require('gulp-watch'); const webpack = require('webpack'); const webpackConfig = require('./webpack.config.js'); const webpackProductionConfig = require('./webpack.production.config.js'); const DIST_DIRECTORY = 'dist'; // Clean all release artifacts gulp.task('clean', function(done) { rimraf(`${__dirname}/${DIST_DIRECTORY}`, done); }); gulp.task('lint', function() { return gulp.src(['**/*.js', `!${DIST_DIRECTORY}/**`, '!node_modules/**', '!coverage/**']) // eslint() attaches the lint output to the "eslint" property // of the file object so it can be used by other modules. .pipe(eslint()) // eslint.format() outputs the lint results to the console. // Alternatively use eslint.formatEach() (see Docs). .pipe(eslint.format()) // To have the process exit with an error code (1) on // lint error, return the stream and pipe to failAfterError last. .pipe(eslint.failAfterError()); }); gulp.task('test', function () { process.env.NODE_ENV = 'test'; return gulp.src('app/js/__tests__').pipe(jest(Object.assign({}, { config: { transformIgnorePatterns: [ '<rootDir>/dist/', '<rootDir>/node_modules/', ], transform: { '^.+\\.jsx?$': 'babel-jest', }, verbose: true, automock: false, }, }))); }); function webpackLog(stats) { gutil.log('[webpack]', stats.toString({ chunks: false, // Limit chunk information output; it's slow and not too useful colors: true, modules: false, })); } gulp.task('webpack', function(done) { return webpack( webpackConfig, function(err, stats) { if (err) throw new gutil.PluginError('webpack', err); webpackLog(stats); done(); } ); }); gulp.task('webpack:production', function(done) { return webpack( webpackProductionConfig, function(err, stats) { if (err) throw new gutil.PluginError('webpack', err); webpackLog(stats); done(); } ); }); gulp.task('webpack:watch', function(done) { let firstRun = true; return webpack(Object.assign({}, {watch: true}, webpackConfig), function(err, stats) { if (err) throw new gutil.PluginError('webpack', err); webpackLog(stats); // Call Gulp's `done` callback only once per watch. Calling it more than once is an error. if (firstRun) { firstRun = false; done(); } }); }); // Watch and re-compile / re-lint when in development. // eslint-disable-next-line no-unused-vars gulp.task('watch', function(done) { watch('app/**/*.js', function() { gulp.start('lint'); gulp.start('test'); }); watch('__tests__/**/*.js', function() { gulp.start('lint'); gulp.start('test'); }); gulp.start(['lint', 'test', 'webpack:watch']); }); gulp.task('release', function(done) { runSequence( 'clean', 'lint', 'test', 'webpack:production', function() { done(); } ); }); gulp.task('default', function(done) { runSequence('lint', 'webpack', done); });
JavaScript
0
@@ -2303,16 +2303,80 @@ webpack( +%0A webpackConfig.map(function (platformConfig) %7B%0A return Object.a @@ -2404,23 +2404,36 @@ e%7D, -webpackConfig), +platformConfig);%0A %7D),%0A fun @@ -2452,24 +2452,26 @@ tats) %7B%0A + + if (err) thr @@ -2512,24 +2512,26 @@ , err);%0A + webpackLog(s @@ -2538,16 +2538,18 @@ tats);%0A%0A + // C @@ -2635,24 +2635,26 @@ error.%0A + + if (firstRun @@ -2653,24 +2653,26 @@ firstRun) %7B%0A + firstR @@ -2685,32 +2685,34 @@ alse;%0A + done();%0A %7D%0A %7D);%0A @@ -2699,24 +2699,32 @@ done();%0A + %7D%0A %7D%0A %7D);%0A%7D);%0A @@ -2715,17 +2715,16 @@ %7D%0A -%7D );%0A%7D);%0A%0A