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
0f7e304fb5e9878c1f1bf2d1be74bd25178e48d0
add function for getting obs values corresponding z score
js/solGS/normalDistribution.js
js/solGS/normalDistribution.js
/** * given an array of arrays dataset ([[A, 1], [B, 2], [C, 4], [D, 1]]), it standardizes dependent variable values (calculates z-scores), calculates probabilties and returns an array of js objects of the form [{x: xvalue, y: yvalue, z: z-score , p: probability}, ....] * uses methods from statistics/simple_statistics js library * Isaak Y Tecle <iyt2@cornell.edu> **/ var solGS = solGS || function solGS () {}; solGS.normalDistribution = function () {}; solGS.normalDistribution.prototype.getNormalDistData = function (xy) { var yValues = this.getYValues(xy); var mean = ss.mean(yValues); var std = ss.standard_deviation(yValues); var normalDistData = []; for (var i=0; i < xy.length; i++) { var x = xy[i][0]; var y = xy[i][1]; var z = ss.z_score(y, mean, std); var p = ss.cumulative_std_normal_probability(z); if (y > mean) { p = 1 - p; } normalDistData.push({'x': x, 'y': y, 'z': z, 'p': p}); } return normalDistData; } solGS.normalDistribution.prototype.getPValues = function (normalData) { var p = []; for (var i=0; i < normalData.length; i++) { var pV = normalData[i].p; p.push(pV); } return p; } solGS.normalDistribution.prototype.getXValues = function (xy) { var xv = []; for (var i=0; i < xy.length; i++) { var x = xy[i][0]; x = x.replace(/^\s+|\s+$/g, ''); x = Number(x); xv.push(x); } return xv; } solGS.normalDistribution.prototype.getYValues = function (xy) { var yv = []; for (var i=0; i < xy.length; i++) { var y = xy[i][1]; y = Number(y); yv.push(y); } return yv; } solGS.normalDistribution.prototype.getYValuesZScores = function (normalData) { var yz = []; for (var i=0; i < normalData.length; i++) { var y = normalData[i].y; var z = normalData[i].z; yz.push([y, z]); } return yz; } solGS.normalDistribution.prototype.getZScoresP = function (normalData) { var zp = []; for (var i=0; i < normalData.length; i++) { var zV = normalData[i].z; var pV = normalData[i].p; zp.push([zV, pV]); } return zp; } solGS.normalDistribution.prototype.getYValuesP = function (normalData) { var yp = []; for (var i=0; i < normalData.length; i++) { var x = normalData[i].y; var y = normalData[i].p; yp.push([x, y]); } return yp; }
JavaScript
0.000002
@@ -2469,16 +2469,382 @@ yp;%0A%7D%0A%0A%0A +solGS.normalDistribution.prototype.getObsValueZScore = function (obsValuesZScores, zScore) %7B%0A%0A%09var obsValue;%0A%09for (var i=0; i %3C obsValuesZScores.length; i++) %7B%0A%09 %0A%09 var j = obsValuesZScores%5Bi%5D;%0A%09 if (d3.format('.1f')(obsValuesZScores%5Bi%5D%5B1%5D) == d3.format('.1f')(zScore)) %7B%09%09%0A%09%09obsValue = obsValuesZScores%5Bi%5D%5B0%5D;%0A%09 %7D%0A%09%7D%0A %0A return %5BobsValue, zScore%5D;%0A%7D%0A%0A%0A %0A%0A
cbeb63f5e7b1cfea5f09a8eba5932a682df9b535
remove versionName from content button
app/components/Product/ContentActionButtons/ContentActionButtons.js
app/components/Product/ContentActionButtons/ContentActionButtons.js
import React, { PropTypes } from 'react'; import StripeCheckout from 'react-stripe-checkout'; import './ContentActionButtons.css'; import StateStore from '../../../stores/StateStore'; import ProductStore from '../../../stores/ProductStore'; import ProductActions from '../../../actions/ProductActions'; import StoreService from '../../../services/StoreService'; import StateService from '../../../services/StateService'; import InstallerService from '../../../services/InstallerService'; import InstallerStore from '../../../stores/InstallerStore'; import StoreStore from '../../../stores/StoreStore'; import ContentText from '../../Text/ContentText'; import mui from 'material-ui'; var ThemeManager = new mui.Styles.ThemeManager(); var RaisedButton = mui.RaisedButton; var LinearProgress = mui.LinearProgress; var Dialog = mui.Dialog; export default class ContentActionButtons extends React.Component { constructor(props) { super(props); this.state = { isBusy: false, isUpgrading: false, buttonState: ProductStore.getPrimaryCallToAction( this.props.content.id ), currentPackageStatus: InstallerStore.getPackageStatus( StoreStore.getReleaseVersionId( this.props.content.id ) ) } } _onChange() { this.setState({ currentPackageStatus: InstallerStore.getPackageStatus( StoreStore.getReleaseVersionId( this.props.content.id ) ), buttonState: ProductStore.getPrimaryCallToAction( this.props.content.id ), }); } componentDidMount() { this.changeListener = this._onChange.bind(this); InstallerStore.addChangeListener(this.changeListener); StateStore.addChangeListener(this.changeListener); ProductStore.addChangeListener(this.changeListener); StoreStore.addChangeListener(this.changeListener); } componentWillUnmount() { InstallerStore.removeChangeListener(this.changeListener); StateStore.removeChangeListener(this.changeListener); ProductStore.removeChangeListener(this.changeListener); StoreStore.removeChangeListener(this.changeListener); } static childContextTypes = { muiTheme: React.PropTypes.object } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } showActionButton () { const buttonStyle = { width: this.props.width + "px", display: "inline-block", left: 0 } if( ProductStore.isUpgradeAvailable(this.props.content.id) && this.state.buttonState!='upgrading') { buttonStyle.height = this.props.buttonHeight*0.7 + "px"; } else { buttonStyle.height = this.props.buttonHeight + "px"; } let buttonText = ''; switch(this.state.buttonState) { case 'play': buttonText = 'Play'; break; case 'download': case 'upgrading': buttonText = 'Download'; break; case 'buy': buttonText = 'Buy'; return ( <StripeCheckout name='Kimochi' description={ProductStore.product.name} amount={this.props.content.price * 100} currency='USD' token={this.doCurrentProductAction.bind(this)} stripeKey='pk_live_Lbn1yTs8LH12jPfx8myHzE6K'> <RaisedButton disabled={this.state.isBusy} secondary={true} style={buttonStyle}> <span className="ContentActionButtons-actionText">{buttonText}</span><br /> <span className="ContentActionButtons-versionText">{ versionName }</span> </RaisedButton> </StripeCheckout> ); break; case 'free': buttonText = 'Add to library'; break; default: break; } return ( <RaisedButton disabled={this.state.isBusy} onClick={ ()=>{ this.doCurrentProductAction()} } secondary={true} style={buttonStyle}> <span className="ContentActionButtons-actionText">{ buttonText }</span><br /> </RaisedButton> ); } doCurrentProductAction(token) { switch(this.state.buttonState) { case 'play': StateService.openLatestPackageExecutable(ProductStore.product.id, this.props.content.id, StoreStore.getReleaseVersionId( this.props.content.id )); amplitude.logEvent('playButtonClick', { id: ProductStore.product.id, name: ProductStore.product.name }); break; case 'download': case 'upgrading': this.downloadVersion(ProductStore.product.id, this.props.content.id, StoreStore.getReleaseVersionId( this.props.content.id )); break; case 'buy': StoreService.purchase(this.props.content.id, 'stripe', token); break; case 'free': StoreService.purchase(this.props.content.id, 'free', ''); break; default: break; } } downloadVersion( productId, contentId, versionId ) { this.setState({ isBusy: true }); InstallerService.downloadDependenciesAndPackage(productId, contentId, versionId, ()=> { this.setState({ isBusy: false }); amplitude.logEvent('downloadSuccess', { id: ProductStore.product.id, name: ProductStore.product.name, }) }); amplitude.logEvent('downloadButtonClick', { id: ProductStore.product.id, name: ProductStore.product.name }); } showUpdateButton() { if( ProductStore.isUpgradeAvailable(this.props.content.id) && this.state.buttonState!='upgrading') { const buttonStyle = { width: this.props.width + "px", height: this.props.buttonHeight * 0.3 + "px" } return ( <RaisedButton primary={true} label={"Upgrade"} style={buttonStyle} onClick={ ()=>{ ProductActions.upgradeContent( this.props.content.id ); this.downloadVersion(ProductStore.product.id, this.props.content.id, StoreStore.getReleaseVersionId( this.props.content.id ) ); } } /> ); } } render() { return( <div className="ContentActionButtons-container"> { this.showActionButton() } { this.showUpdateButton() } </div> ); } }
JavaScript
0.000001
@@ -2354,16 +2354,18 @@ %0A %7D%0A%0A + if( Pr @@ -2459,24 +2459,26 @@ ing') %7B%0A + buttonStyle. @@ -2524,16 +2524,18 @@ %22px%22;%0A + + %7D else %7B @@ -2535,16 +2535,18 @@ else %7B%0A + butt @@ -2594,16 +2594,18 @@ + %22px%22;%0A + %7D%0A%0A @@ -3373,96 +3373,8 @@ /%3E%0A - %3Cspan className=%22ContentActionButtons-versionText%22%3E%7B versionName %7D%3C/span%3E%0A
0d802fbd88fe5dd443599afe6f57e6e410010b75
add lastServiceVersions
app/src/controller/modules/other/modules/modules.js
app/src/controller/modules/other/modules/modules.js
import twitter from './twitter/twitter'; export default { twitter, };
JavaScript
0
@@ -33,16 +33,93 @@ witter'; +%0Aimport lastServiceVersions from './lastServiceVersions/lastServiceVersions'; %0A%0Aexport @@ -140,11 +140,34 @@ witter,%0A + lastServiceVersions,%0A %7D;%0A
35aaae71990d8ff1c4dd7440631013bbeb109879
clean up XML parser unit test
parsers/parserXML/popcorn.parserXML.unit.js
parsers/parserXML/popcorn.parserXML.unit.js
test("Popcorn 0.1 XML Parser Plugin", function () { var expects = 7, count = 0, timeOut = 0, interval, poppercorn = Popcorn( "#video" ); function plus() { if ( ++count === expects ) { start(); // clean up added events after tests clearInterval( interval ); } } expect(expects); stop( 10000 ); Popcorn.plugin("parserTest1", { start: function ( event, options ) { ok( options.item2 === "item2", "parserTest1 has data directly from manifest" ); plus(); ok( options.item3 === "item3", "parserTest1 has cascading data from manifest" ); plus(); }, end: function ( event, options ) {} }); Popcorn.plugin("parserTest2", { start: function ( event, options ) { ok( options.text === "item4", "parserTest2 has text data" ); plus(); ok( options.item1 === "item1", "parserTest2 has cascading data from parent" ); plus(); }, end: function ( event, options ) {} }); Popcorn.plugin("parserTest3", { start: function ( event, options ) { ok( options.item1 === "item1", "parserTest3 has cascading data from parent" ); plus(); ok( options.item2 === "item2", "parserTest3 has data directly from manifest" ); plus(); ok( options.item3 === "item3", "parserTest3 has cascading data from manifest" ); plus(); }, end: function ( event, options ) {} }); poppercorn.parseXML("data/unit.XML"); // interval used to wait for data to be parsed interval = setInterval( function() { poppercorn.currentTime(5).play().currentTime(6); }, 2000); });
JavaScript
0
@@ -1487,86 +1487,9 @@ XML%22 -);%0A%0A // interval used to wait for data to be parsed%0A interval = setInterval( +, fun @@ -1531,47 +1531,19 @@ e(5) -.play().currentTime(6);%0A %7D, 2000 +;%0A %7D ); -%0A %0A%7D);%0A +%0A
355e2cf831502571fec1a58dbe672784d17e6fd5
Use new taxon slug generator in admin panel
Resources/private/js/sylius-taxon-slug.js
Resources/private/js/sylius-taxon-slug.js
/* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ (function ($) { 'use strict'; $.fn.extend({ taxonSlugGenerator: function () { var timeout; $('[name*="sylius_taxon[translations]"][name*="[name]"]').on('input', function() { clearTimeout(timeout); var element = $(this); timeout = setTimeout(function() { updateSlug(element); }, 1000); }); $('.toggle-taxon-slug-modification').on('click', function(e) { e.preventDefault(); toggleSlugModification($(this), $(this).siblings('input')); }); function updateSlug(element) { var slugInput = element.parents('.content').find('[name*="[slug]"]'); var loadableParent = slugInput.parents('.field.loadable'); if ('readonly' == slugInput.attr('readonly')) { return; } loadableParent.addClass('loading'); var data; if ('' != slugInput.attr('data-parent') && undefined != slugInput.attr('data-parent')) { data = { name: element.val(), parentId: slugInput.attr('data-parent') }; } else if ($('#sylius_taxon_parent').length > 0 && $('#sylius_taxon_parent').is(':visible') && '' != $('#sylius_taxon_parent').val()) { data = { name: element.val(), parentId: $('#sylius_taxon_parent').val() }; } else { data = { name: element.val() }; } $.ajax({ type: "GET", url: slugInput.attr('data-url'), data: data, dataType: "json", accept: "application/json", success: function(data) { slugInput.val(data.slug); if (slugInput.parents('.field').hasClass('error')) { slugInput.parents('.field').removeClass('error'); slugInput.parents('.field').find('.sylius-validation-error').remove(); } loadableParent.removeClass('loading'); } }); } function toggleSlugModification(button, slugInput) { if (slugInput.attr('readonly')) { slugInput.removeAttr('readonly'); button.html('<i class="unlock icon"></i>'); } else { slugInput.attr('readonly', 'readonly'); button.html('<i class="lock icon"></i>'); } } } }); })(jQuery);
JavaScript
0
@@ -1378,32 +1378,89 @@ : element.val(), + locale: element.closest('%5Bdata-locale%5D').data('locale'), parentId: slugI @@ -1688,16 +1688,73 @@ t.val(), + locale: element.closest('%5Bdata-locale%5D').data('locale'), parentI @@ -1860,24 +1860,81 @@ lement.val() +, locale: element.closest('%5Bdata-locale%5D').data('locale') %7D;%0A
1a067a9635585cbb96c80040b2941e92868b07df
Use cache dir based on file location
browscap.js
browscap.js
"use strict"; module.exports = function Browscap (cacheDir) { if (typeof cacheDir === 'undefined') { cacheDir = './sources/'; } this.cacheDir = cacheDir; /** * parses the given user agent to get the information about the browser * * if no user agent is given, it uses {@see \BrowscapPHP\Helper\Support} to get it * * @param userAgent the user agent string */ this.getBrowser = function(userAgent) { var Ini = require('./parser'); var Quoter = require('./helper/quoter'); var quoter = new Quoter(); var GetPattern = require('./helper/pattern'); var BrowscapCache = require('browscap-js-cache'); var cache = new BrowscapCache(this.cacheDir); var GetData = require('./helper/data'); var patternHelper = new GetPattern(cache); var dataHelper = new GetData(cache, quoter); var parser = new Ini(patternHelper, dataHelper); return parser.getBrowser(userAgent); }; };
JavaScript
0.000001
@@ -112,18 +112,29 @@ heDir = +__dirname + ' -. /sources
004e3ca14bca9dd46eb80fec3073378334297d47
Fix indentation
SQLite3JS/js/SQLite3.js
SQLite3JS/js/SQLite3.js
(function () { "use strict"; var Statement, Database; // Alternative typeof implementation yielding more meaningful results, // see http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/ function type(obj) { var typeString; typeString = Object.prototype.toString.call(obj); return typeString.substring(8, typeString.length - 1).toLowerCase(); } function throwSQLiteError(message, comException) { var error = new Error(message); error.resultCode = comException.number & 0xffff; throw error; } Statement = WinJS.Class.define(function (db, sql, args) { try { this.statement = db.connection.prepare(sql); } catch (comException) { throwSQLiteError('Error preparing an SQLite statement.', comException); } if (args) { this.bind(args); } }, { bind: function (args) { var index, resultCode; args.forEach(function (arg, i) { index = i + 1; switch (type(arg)) { case 'number': if (arg % 1 === 0) { resultCode = this.statement.bindInt(index, arg); } else { resultCode = this.statement.bindDouble(index, arg); } break; case 'string': resultCode = this.statement.bindText(index, arg); break; case 'null': resultCode = this.statement.bindNull(index); break; default: throw new Error("Unsupported argument type: " + type(arg)); } if (resultCode !== SQLite3.ResultCode.ok) { throw new Error("Error " + resultCode + " when binding argument to SQL query."); } }, this); }, run: function () { this.statement.step(); }, all: function () { var result = []; this.each(function (row) { result.push(row); }); return result; }, each: function (callback) { var row, i, len, name; while (this.statement.step() === SQLite3.ResultCode.row) { row = {}; for (i = 0, len = this.statement.columnCount() ; i < len; i += 1) { name = this.statement.columnName(i); switch (this.statement.columnType(i)) { case SQLite3.Datatype.integer: row[name] = this.statement.columnInt(i); break; case SQLite3.Datatype.float: row[name] = this.statement.columnDouble(i); break; case SQLite3.Datatype.text: row[name] = this.statement.columnText(i); break; case SQLite3.Datatype["null"]: row[name] = null; break; } } callback(row); } }, close: function () { this.statement.close(); } }); Database = WinJS.Class.define(function (dbPath) { try { this.connection = SQLite3.Database(dbPath); } catch (comException) { throwSQLiteError('Error creating an SQLite database connection.', comException); } }, { run: function (sql, args) { var statement = new Statement(this, sql, args); statement.run(); statement.close(); }, all: function (sql, args) { var rows, statement = new Statement(this, sql, args); rows = statement.all(); statement.close(); return rows; }, each: function (sql, args, callback) { if (!callback && type(args) === 'function') { callback = args; args = null; } var statement = new Statement(this, sql, args); statement.each(callback); statement.close(); }, close: function () { this.connection.close(); } }); WinJS.Namespace.define('SQLite3JS', { Database: Database }); }());
JavaScript
0.017244
@@ -3712,21 +3712,25 @@ ;%0A %7D%0A + %7D);%0A%0A + WinJS.Na @@ -3759,16 +3759,18 @@ 3JS', %7B%0A + Databa @@ -3782,16 +3782,18 @@ atabase%0A + %7D);%0A%0A%7D()
8f9e3b62c695a0dc7db34853e94b74f951bcb3da
modify JShint errors
src/Game.js
src/Game.js
function Game() { 'use strict'; this.scores = []; //store [[ro11-1, roll-2, bonus]] this.frameScores = []; //store [ro11-1, roll-2] this.STRIKE_PINS = 10; this.roll = 1; this.frame = 1; this.finish = false; this.thirdRoll = false; } Game.prototype.passScore = function(user_input){ var pins = Number(user_input) if( this.frameScores.length === 0 ){ this.frameScores.push(pins) this.scores.push(this.frameScores) } else { this.frameScores.push(pins) this.scores[ this.frame - 1 ] = this.frameScores } }; Game.prototype.passStrikeSecondRollScore = function(){ this.frameScores.push(0) this.scores[ this.frame - 1 ] = this.frameScores } Game.prototype.increaseRoll = function(){ this.roll ++ }; Game.prototype.changeRoll = function(){ if( this.roll === 1 ){ this.increaseRoll() } else { this.roll = 1 } }; Game.prototype.increaseFrame = function(){ if( this.frame < 10 && this.frameScores.length === 2 ){ return this.frame ++ } }; Game.prototype.clearFrameScores = function(){ if( this.frameScores.length === 2 ){ return this.frameScores = [] } }; Game.prototype.isGameFinish = function(){ if( this.roll === 2 && this.thirdRoll === false ){ return true } else if( this.roll === 3 ){ return true } else { return false } };
JavaScript
0
@@ -1059,39 +1059,32 @@ .length === 2 )%7B - return this.frameScore
0b7f4704869d800392f9bf618fb12a82f6e3b526
add tweaking to slow scenarios
test/managers/purchasing/delivery-order/index.js
test/managers/purchasing/delivery-order/index.js
describe("BASIC CRUD SCENARIOS", function() { require("./basic"); }); // describe("CREATE SCENARIOS", function() { // require("./create"); // });
JavaScript
0
@@ -39,16 +39,38 @@ ion() %7B%0A + this.slow(10000);%0A requ
a7da36d8376de9f2eccac11f9e3db35618ecf44a
Switch from arrays to Sets
source/index.js
source/index.js
import normalizeEvents from './tools/normalizeEvents'; import normalizeListener from './tools/normalizeListener'; export default function stereo () { let listeners = {}; let emitter = { on(events, listener) { // Normalize arguments. events = normalizeEvents(events); listener = normalizeListener(listener); // Register the listener. for (let event of events) { let register = listeners[event]; if (!register) listeners[event] = [listener]; else if (!register.includes(listener)) { register.push(listener); } } }, once(events, listener) { events = normalizeEvents(events); listener = normalizeListener(listener); function listenerWrapper (...args) { emitter.off(events, listenerWrapper); listener(...args); } emitter.on(events, listenerWrapper); }, off(events, listener) { // Normalize arguments. events = normalizeEvents(events); // If no listener is specified, unregister all listeners. if (listener == null) for (let event of events) { delete listeners[event]; } // Otherwise unregister the given listener. else { listener = normalizeListener(listener); for (let event of events) { let register = listeners[event]; let index = register.indexOf(listener); if (index !== -1) register.splice(index, 1); } } }, emit(events, ...args) { // Normalize arguments. events = normalizeEvents(events); // Dispatch listeners. for (let event of events) { let register = listeners[event]; if (register) for (let listener of register) { listener(...args); } } } }; return emitter; }
JavaScript
0.000001
@@ -478,16 +478,24 @@ vent%5D = +new Set( %5Blistene @@ -496,16 +496,17 @@ istener%5D +) ;%0A @@ -530,15 +530,10 @@ ter. -include +ha s(li @@ -540,28 +540,16 @@ stener)) - %7B%0A registe @@ -554,12 +554,11 @@ ter. -push +add (lis @@ -565,26 +565,16 @@ tener);%0A - %7D%0A %7D%0A @@ -1241,25 +1241,24 @@ (listener);%0A -%0A for @@ -1296,142 +1296,39 @@ l -et register = listeners%5Bevent%5D;%0A let index = register.indexOf(listener);%0A if (index !== -1) register.splice(index, 1 +isteners%5Bevent%5D.delete(listener );%0A
73c252f8677f7fb44aa0397128658cc11711ebc3
Add error objects to index exports
source/index.js
source/index.js
/** * lazy-linked-lists * Lazy and infinite linked lists for JavaScript. * * source/index.js * * Top level index. */ export { LT, GT, EQ } from './ord'; export { emptyList, list, listRange, listRangeBy, listAppend, cons, head, last, tail, init, length, isList, isEmpty, fromArrayToList, fromListToArray, fromListToString, fromStringToList, concat, index, filter, map, reverse, sort, sortBy, take, drop, takeWhile, dropWhile, listInf, listInfBy, iterate, repeat, replicate, cycle } from './lib';
JavaScript
0.000001
@@ -571,8 +571,72 @@ ./lib';%0A +%0Aexport %7B%0A EmptyListError,%0A OutOfRangeError%0A%7D from './error';%0A
b96918609d701187bcfa68bb1a983da8a3c025f1
return error message when not proceeding
source/index.js
source/index.js
import 'babel-polyfill'; import shell from 'shelljs'; import readline from 'readline-sync'; function precommit(config = {}) { let branches = config.branches || []; let command = shell.exec('git rev-parse --abbrev-ref HEAD', { silent: true }); if (!command.code) { let currentBranch = command.output.trim(); let allowed = !branches.includes(currentBranch); if (!allowed) { return readline.keyInYN('You are not supposed to commit in this ' + 'branch. Proceed?'); } } return true; } exports['pre-commit'] = precommit;
JavaScript
0.000002
@@ -423,22 +423,29 @@ -return +let proceed = readlin @@ -458,29 +458,19 @@ nYN( -'You are not supposed +%60Attempting to @@ -483,14 +483,16 @@ in -this ' +branch %60 %0A @@ -510,15 +510,27 @@ + -'b +%60%22$%7BcurrentB ranch +%7D%22 . Pr @@ -539,12 +539,125 @@ eed? -' +%60 );%0A + if (!proceed) %7B%0A return %60Aborting commit in branch %22$%7BcurrentBranch%7D%22%60;%0A %7D%0A
35511124f4a825a21a1385269198839ca3fc2e2e
Correct up-conversion but it fails when the JS scripts come before the network event (on startup on open page)
resources/JavaScriptEventHandler.js
resources/JavaScriptEventHandler.js
// See Purple/license.txt for Google BSD license // Copyright 2011 Google, Inc. johnjbarton@johnjbarton.com define(['../browser/remoteByWebInspector', '../resources/Resources', '../resources/JavaScriptResource'], function (remoteByWebInspector, Resources, JavaScriptResource) { var thePurple = window.purple; var Assembly = thePurple.Assembly; var jsEventHandler = new thePurple.PurplePart('jsEventHandler'); //--------------------------------------------------------------------------------------------- // jsEventHandler.startDebugger = function() { this.remote.Debugger.enable(); }; jsEventHandler.stopDebugger = function() { this.remote.Debugger.disable(); }; jsEventHandler.getOrCreateJavaScriptResource = function(url, isContentScript) { var resource = Resources.get(url); if (!resource) { resource = new JavaScriptResource(url, isContentScript); Resources.append(url, resource); } else if ( ! (resource instanceof JavaScriptResource) ) { // we have a network resource which we just discovered is a JavaScriptResource Object.keys(JavaScriptResource.prototype).forEach(function(key) { resource[key] = JavaScriptResource.prototype[key]; }); } return resource; }; // Implement Remote.events jsEventHandler.responseHandlers = { Debugger: { breakpointResolved: function(breakpointId, location) { console.log("JavaScriptEventHandler", arguments); }, paused: function(details) { console.log("JavaScriptEventHandler", arguments); }, resumed: function() { console.log("JavaScriptEventHandler", arguments); }, scriptFailedToParse: function(data, errorLine, errorMessage, firstLine, url) { console.log("JavaScriptEventHandler", arguments); }, scriptParsed: function(endColumn, endLine, isContentScript, scriptId, startColumn, startLine, url) { var res = jsEventHandler.getOrCreateJavaScriptResource(url, isContentScript); res.appendScript(scriptId, startLine, startColumn, endLine, endColumn); } }, Timeline: { eventRecorded: function(record) { console.log("JavaScriptEventHandler", arguments); }, started: function() { console.log("JavaScriptEventHandler", arguments); }, stopped: function() { console.log("JavaScriptEventHandler", arguments); }, }, }; //--------------------------------------------------------------------------------------------- // Implement PurplePart jsEventHandler.connect = function(channel) { this.remote = remoteByWebInspector.create('resourceCreationRemote', this.responseHandlers); this.remote.connect(channel); this.logger = channel.recv.bind(channel); Resources.connect(this.logger); this.startDebugger(); }; jsEventHandler.disconnect = function(channel) { this.stopDebugger(); this.remote.disconnect(channel); Resources.disconnect(this.logger); }; thePurple.registerPart(jsEventHandler); return jsEventHandler; });
JavaScript
0
@@ -982,17 +982,16 @@ if ( ! -( resource @@ -1025,10 +1025,8 @@ rce) - ) %7B%0D%0A @@ -1121,81 +1121,112 @@ -Object.keys(JavaScriptResource.prototype).forEach(function(key) %7B +var tmp = Object.create(resource);%0D%0A JavaScriptResource.apply(tmp, %5Burl, isContentScript%5D); %0D%0A re @@ -1225,70 +1225,58 @@ - r +R esource -%5Bkey%5D = JavaScriptResource.prototype%5Bkey%5D;%0D%0A %7D) +s.replace(url, tmp);%0D%0A resource = tmp ;%0D%0A
92bbb59b2f06c45cd2a5cc12c04e19cb58012e0d
Fix key-handling bug with completions.
resources/public/js/codemirrorVM.js
resources/public/js/codemirrorVM.js
/* * This file is part of gorilla-repl. Copyright (C) 2014, Jony Hudson. * * gorilla-repl is licenced to you under the MIT licence. See the file LICENCE.txt for full details. */ // This is a viewmodel and KO binding for the codemirror code editor. You should apply the codemirror binding // to a textarea, and bind it to a viewmodel made with makeCodeMirrorViewmodel. // // The viewmodel raises events when something that might warrant external action happens. For instance, if the focus // is entering or leaving the editor, or if a segment should be deleted. The editor must be given an id, and it will // include this id in the events it raises. var codemirrorVM = function (id, initialContents, contentType) { var self = {}; self.id = id; self.contentType = contentType; self.contents = ko.observable(initialContents); // ** Public methods for manipulating this editor ** // asks the editor to redraw itself. Needed when its size has changed. self.reflow = function () { self.codeMirror.refresh(); }; self.blur = function () { // this doesn't seem to be built in to the editor self.codeMirror.getInputField().blur(); }; self.complete = function (completionFunc) { CodeMirror.showHint(self.codeMirror, completionFunc); }; // These can be called to position the CodeMirror cursor appropriately. They are used when the cell is receiving // focus from another cell. self.positionCursorAtContentStart = function () { self.codeMirror.focus(); self.codeMirror.setCursor(0, 0); self.codeMirror.focus(); }; self.positionCursorAtContentEnd = function () { self.codeMirror.focus(); // TODO: Bit of a fudge doing this here! self.reflow(); // position the cursor past the end of the content self.codeMirror.setCursor(self.codeMirror.lineCount(), 0); self.codeMirror.focus(); }; self.positionCursorAtContentStartOfLastLine = function () { self.codeMirror.focus(); self.codeMirror.setCursor(self.codeMirror.lineCount() - 1, 0); self.codeMirror.focus(); }; // ** Internal methods - should only be called by our CodeMirror instance. ** // These will be called by the CodeMirror component, and will notify the application that something of note has // happened. Cursor movement and segment deletion generate "command" events, which will be handled by the command // processor (which will then delegate to the worksheet). Segment clicks are not sent as commands as it doesn't // really make sense. self.notifyMoveCursorBack = function () { eventBus.trigger("command:worksheet:leaveBack") }; self.notifyMoveCursorForward = function () { eventBus.trigger("command:worksheet:leaveForward") }; self.notifyBackspaceOnEmpty = function () { eventBus.trigger("command:worksheet:delete") }; self.notifyClicked = function () { eventBus.trigger("worksheet:segment-clicked", {id: self.id}) }; return self; }; ko.bindingHandlers.codemirror = { init: function (element, valueAccessor, allBindingsAccessor, viewModel) { // we define a custom CodeMirror keymap, which takes a few steps. // First we need to define a CodeMirror command that does nothing // (according to the CodeMirror docs, one should be able set a key-binding as 'false' and have it do nothing // but I can't seem to get that to work. CodeMirror.commands['doNothing'] = function () {}; // then patch the Mac default keymap to get rid of the emacsy binding, which interfere with our shortcuts CodeMirror.keyMap['macDefault'].fallthrough = "basic"; // and then create our custom map, which will fall through to the (patched) default. Shift+Enter is stopped // from doing anything. CodeMirror.keyMap["gorilla"] = {'Shift-Enter': "doNothing", fallthrough: "default"}; var cm = CodeMirror.fromTextArea(element, { lineNumbers: false, matchBrackets: true, autoCloseBrackets: true, lineWrapping: true, keyMap: 'gorilla', mode: valueAccessor().contentType, onKeyEvent: function (editor, event) { // only check on cursor key keydowns // we stop() the cursor events, as we don't want them reaching the worksheet. We explicity // generate events when the cursor should leave the segment. if (event.type === 'keydown') { // up var curs; if (event.keyCode === 38) { // get the current cursor position curs = editor.getCursor(); // check for first line if (curs.line === 0) valueAccessor().notifyMoveCursorBack(); event.stop(); } // left if (event.keyCode === 37) { // get the current cursor position curs = editor.getCursor(); // check for first line, start position if (curs.line === 0 && curs.ch === 0) valueAccessor().notifyMoveCursorBack(); event.stop(); } // down if (event.keyCode === 40) { // get the current cursor position curs = editor.getCursor(); // check for last line if (curs.line === (editor.lineCount() - 1)) valueAccessor().notifyMoveCursorForward(); event.stop(); } // right if (event.keyCode === 39) { // get the current cursor position curs = editor.getCursor(); // check for last line, last position if (curs.line === (editor.lineCount() - 1)) { if (curs.ch === editor.getLine(curs.line).length) valueAccessor().notifyMoveCursorForward(); } event.stop(); } // delete on an empty editor if (event.keyCode === 8) { if (editor.getValue() === "") valueAccessor().notifyBackspaceOnEmpty(); } } } }); // this function is called back by codemirror when ever the contents changes. // It keeps the model in sync with the code. cm.on('change', function (editor) { var value = valueAccessor(); value.contents(editor.getValue()); }); cm.on('mousedown', function () { valueAccessor().notifyClicked(); }); // store the editor object on the viewmodel valueAccessor().codeMirror = cm; // set the initial content cm.setValue(ko.utils.unwrapObservable(valueAccessor().contents)); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { var cm = valueAccessor().codeMirror; var value = ko.utils.unwrapObservable(valueAccessor().contents); // KO will trigger this update function whenever the model changes, even if that change // is because the editor itself has just updated the model. This messes with the cursor // position, so we check here whether the value really has changed before we interfere // with the editor. if (value !== cm.getValue()) cm.setValue(value); } };
JavaScript
0
@@ -4969,28 +4969,207 @@ -if (curs.line === 0) +// TODO: I'm not sure whether the completionActive state is part of the public API%0A if ((curs.line === 0) && !editor.state.completionActive)%0A val @@ -5993,32 +5993,33 @@ if +( (curs.line === ( @@ -6042,16 +6042,83 @@ () - 1)) + && !editor.state.completionActive)%0A valueAc
20026c1937cfb6ffd230abe0cdd28b13b59341fd
remove unused cls reference
replacement/replacement.js
replacement/replacement.js
"use strict"; log('running replacement.js'); var Ping = { ping: function () { log('ping: ' + this.name); }, } var Pong = { pong: function () { log('pong'); } } function PingPong () { var cls, method; for (var ii = 0; ii < arguments.length; ii++) { cls = arguments[ii]; this[cls] = Object.create(window[cls]); for (method in window[cls]) { this[method] = window[cls][method]; } } this.init = function (name) { this.name = name; }; this.pingpong = function () { this.ping(); this.pong(); }; } var pingPong = new PingPong('Ping', 'Pong'); pingPong.init('p1'); pingPong.ping(); pingPong.pong(); log(typeof pingPong.ping); pingPong.pingpong(); var pingPong2 = new PingPong('Ping', 'Pong'); pingPong2.init('p2'); pingPong2.pingpong(); pingPong.pingpong();
JavaScript
0
@@ -317,56 +317,8 @@ i%5D;%0A - this%5Bcls%5D = Object.create(window%5Bcls%5D);%0A
270ea8031d1315ae1f73329137600ddd8afb3d9b
add response object parsing
source/popup.js
source/popup.js
document.addEventListener('DOMContentLoaded', function () { urlFetcher.getUrl() }) var urlFetcher = { getUrl: function(){ chrome.tabs.query({currentWindow: true, active: true}, function(tabs){ var url = tabs[0].url var apiUrl = urlFetcher.prepareUrl(url) commentGenerator.getComments(apiUrl) }) }, prepareUrl: function(url) { var videoId = urlFetcher.extractVideoId(url) var urlString = 'https://gdata.youtube.com/feeds/api/videos/' + videoId + '/comments?v=2&alt=json' return urlString }, extractVideoId: function(url) { var regex = /v=(.*)/ var matchArray = regex.exec(url) return matchArray[1] } } var commentGenerator = { getComments: function(url) { $('body').append(url) $.ajax({ type: 'GET', dataType:"json", url: url, success: function(response){ // call parser code here } }) } }
JavaScript
0.000002
@@ -504,16 +504,31 @@ alt=json +&max-results=50 '%0A re @@ -735,34 +735,8 @@ ) %7B%0A - $('body').append(url)%0A @@ -838,59 +838,702 @@ onse -)%7B%0A// call parser code here %0A %7D +Object) %7B%0A commentParser.init(responseObject) %0A %7D%0A %7D)%0A %7D%0A%7D%0A%0Avar commentParser = %7B%0A init: function(responseObject) %7B%0A var parsedArray = commentParser.extractComments(responseObject)%0A $('body').append(parsedArray%5B0%5D.commentContent)%0A %7D,%0A extractComments: function(responseObject) %7B%0A var commentArray = responseObject.feed.entry%0A var parsedComments = %5B%5D%0A for (var i = 0;i%3CcommentArray.length;i++)%7B%0A var comment = commentArray%5Bi%5D.content.$t%0A var authorLink = %22http://www.youtube.com/profile_redirector/%22 + commentArray%5Bi%5D.yt$googlePlusUserId.$t%0A parsedComments.push(%7BcommentContent:comment,authorUrl:authorLink%7D) %0A %7D -) %0A -%7D%0A + return parsedComments%0A %7D%0A +%7D
5600fdb454498263c9cba055eeea2ca3b7d3bf73
Improve the O.UA.canU2F check
source/ua/UA.js
source/ua/UA.js
/*global navigator, document, window */ /** Module: UA The UA module contains information about the platform on which the application is running. */ const ua = navigator.userAgent.toLowerCase(); const other = [ 'other', '0' ]; const platform = /windows phone/.test( ua ) ? 'winphone' : /ip(?:ad|hone|od)/.test( ua ) ? 'ios' : ( /android|webos/.exec( ua ) || /mac|win|linux/.exec( navigator.platform.toLowerCase() ) || other )[0]; const browser = ( /firefox|edge|msie/.exec( ua ) || /chrome|safari/.exec( ua ) || other )[0]; const version = parseFloat(( /(?:; rv:|edge\/|version\/|firefox\/|msie\s|os )(\d+(?:[._]\d+)?)/ .exec( ua ) || /chrome\/(\d+\.\d+)/.exec( ua ) || other )[1].replace( '_', '.' ) ); const prefix = { firefox: '-moz-', msie: '-ms-', }[ browser ] || '-webkit-'; /** Namespace: O.UA The O.UA namespace contains information about which browser and platform the application is currently running on, and which CSS properties are supported. */ export default { /** Property: O.UA.platform Type: String The operating system being run: "mac", "win", "linux", "android", "ios", "webos" or "other. */ platform, /** Property: O.UA.isMac Type: Boolean True if running on a mac. */ isMac: platform === 'mac', /** Property: O.UA.isWin Type: Boolean True if running on windows. */ isWin: platform === 'win', /** Property: O.UA.isLinux Type: Boolean True if running on linux. */ isLinux: platform === 'linux', /** Property: O.UA.isIOS Type: Boolean True if running on iOS. */ isIOS: platform === 'ios', /** Property: O.UA.isWKWebView Type: Boolean True if running on WKWebView in iOS. */ isWKWebView: platform === 'ios' && !!window.indexedDB, /** Property: O.UA.isAndroid Type: Boolean True if running on Android. */ isAndroid: platform === 'android', /** Property: O.UA.isWinPhone Type: Boolean True if running on Windows Phone. */ isWinPhone: platform === 'winphone', /** Property: O.UA.browser Type: String The browser being run. "chrome", "firefox", "msie", "edge" or "safari". */ browser, /** Property: O.UA.version Type: Number The browser version being run. This is a float, and includes the first minor revision as well as the major revision. For example, if the user is running Opera 12.5, this will be `12.5`, not just `12`. */ version, /** Property: O.UA.chrome Type: Number If running Chrome, this will be the version number running. Otherwise 0. Other browsers like Opera may report as Chrome; the version number should correspond to the build of Chromium whence they came. */ chrome: browser === 'chrome' ? version : 0, /** Property: O.UA.safari Type: Number If running Safari, this will be the version number running. Otherwise 0. */ safari: browser === 'safari' ? version : 0, /** Property: O.UA.firefox Type: Number If running Firefox, this will be the version number running. Otherwise 0. */ firefox: browser === 'firefox' ? version : 0, /** Property: O.UA.edge Type: Number If running Edge, this will be the version number running. Otherwise 0. */ edge: browser === 'edge' ? version : 0, /** Property: O.UA.msie Type: Number If running Internet Explorer, this will be the version number running. Otherwise 0. */ msie: browser === 'msie' ? version : 0, /** Property: O.UA.operaMini Type: Number If running Opera Mini, this will be the version number running. Otherwise 0. */ operaMini: window.operamini ? version : 0, /** Property: O.UA.cssPrefix Type: String The CSS prefix to use for this browser. */ cssPrefix: prefix, /** Property: O.UA.canTouch Type: Boolean Does the browser support touch events? */ canTouch: 'ontouchstart' in document.documentElement, /** Property: O.UA.canU2F Type: Boolean Does the browser support U2F? */ // TODO: Find a way of detecting this rather than hardcoding // For now, referencing http://caniuse.com/#feat=u2f canU2F: browser === 'chrome' && version >= 41, };
JavaScript
0.000002
@@ -4483,32 +4483,41 @@ oes the browser +probably support U2F?%0A @@ -4531,122 +4531,218 @@ // -TODO: Find a way of detecting this rather than hardcoding%0A // For now, referencing http://caniuse.com/#feat=u2f +See http://caniuse.com/#feat=u2f%0A // Chrome 41+ supports it but exposes no obvious global; Firefox has it%0A // disabled by default but if enabled by security.webauth.u2f exposes a%0A // global called U2F. %0A @@ -4749,16 +4749,18 @@ canU2F: + ( browser @@ -4789,13 +4789,31 @@ on %3E= 41 + ) %7C%7C !!window.U2F ,%0A%7D;%0A
ad72cce06ec3d480cd62cdd79567e64266cfb268
Add class StopFlashFrame + Add StopFlashTab::newTab() + Add frameId var
background.js
background.js
/** * StopFlash * * https://github.com/JWhile/StopFlash * * background.js */ function StopFlashBackground() { this.tabs = []; // :Array<StopFlashTab> } function StopFlashTab() { this.frames = []; } /* function BackgroundFlashData(id) { this.id = id; // :int this.data = null; // :Object this.popupPort = null; // :chrome.runtime.Port this.contentPorts = []; // :Array<chrome.runtime.Port> } // function setData(Object data):void BackgroundFlashData.prototype.setData = function(data) { this.data = data; this.sendToPopup(); }; // function setPopup(chrome.runtime.Port popupPort):void BackgroundFlashData.prototype.setPopup = function(popupPort) { this.popupPort = popupPort; var self = this; this.popupPort.onDisconnect.addListener(function() { self.popupPort = null; }); this.sendToPopup(); }; // function setContentScript(chrome.runtime.Port contentPort):void BackgroundFlashData.prototype.setContentScript = function(contentPort) { this.contentPorts.push(contentPort); var self = this; contentPort.onDisconnect.addListener(function() { var index = self.contentPorts.indexOf(contentPort); if(index >= 0) { self.contentPorts.splice(index, 1); } }); contentPort.postMessage({'stopflashWhitelist': whitelist}); }; // function sendToPopup():void BackgroundFlashData.prototype.sendToPopup = function() { if(this.popupPort != null) { this.popupPort.postMessage({'stopflashData': this.data}); } }; // function sendToContent(Object data):void BackgroundFlashData.prototype.sendToContent = function(data) { for(var i = 0; i < this.contentPorts.length; ++i) { this.contentPorts[i].postMessage(data); } }; // function clear():void BackgroundFlashData.prototype.clear = function() { this.data = null; if(this.popupPort != null) { this.popupPort.disconnect(); } this.popupPort = null; if(this.contentPort != null) { this.contentPort.disconnect(); } this.contentPort = null; }; var flashData = []; // :Array<BackgroundFlashData> var whitelist = []; // :Array<String> // function getFlashData(int id):BackgroundFlashData var getFlashData = function(id) { for(var i = 0; i < flashData.length; ++i) { if(flashData[i].id === id) { return flashData[i]; } } return null; }; chrome.runtime.onConnect.addListener(function(port) { if(port.name === 'stopflashContentScript' && port.sender.tab != null) { var data = null; port.onMessage.addListener(function(rep) { if(rep['stopflashInit']) { data = getFlashData(port.sender.tab.id); if(data != null) { if(rep['stopflashIsMainFrame']) { data.clear(); } } else { data = new BackgroundFlashData(port.sender.tab.id); flashData.push(data); } data.setContentScript(port); } if(rep['stopflashHaveChange']) { data.data = null; data.sendToContent({'stopflashDataUpdate'}); } if(rep['stopflashDataUpdate'] && rep['stopflashData']) { data.setData(rep.stopflashData); } }); } else if(port.name === 'stopflashPopup') { var data = null; port.onMessage.addListener(function(rep) { if(rep['stopflashInit']) { data = getFlashData(rep['stopflashInit']); if(data != null) { data.setPopup(port); } } if(rep['stopflashBlock']) { data.sendToContent({'stopflashBlock': rep['stopflashBlock']}); } if(rep['stopflashUnblock']) { data.sendToContent({'stopflashUnblock': rep['stopflashUnblock']}); } }); } }); */
JavaScript
0.000001
@@ -77,16 +77,34 @@ js%0A */%0A%0A +var frameId = 0;%0A%0A function @@ -222,16 +222,281 @@ es = %5B%5D; + // :Array%3CStopFlashFrame%3E%0A%7D%0A// function newTab():StopFlashFrame%0AStopFlashTab.prototype.newTab = function()%0A%7B%0A var frame = new StopFlashFrame(++frameId);%0A%0A this.frames.push(frame);%0A%0A return frame;%0A%7D;%0A%0Afunction StopFlashFrame(id)%0A%7B%0A this.id = id; // :int %0A%7D%0A%0A/*%0Af
f48b1e1889a9110b1e650c7f8b33e4807163c9f5
Fix typo with calendar desc for specific teams
calendar.js
calendar.js
const https = require('follow-redirects').https const fs = require('fs'); const util = require('util'); const readline = require('readline'); const stream = require('stream'); const url = "https://www.google.com/calendar/ical/hockeyligan.sverige@gmail.com/public/basic.ics"; let icalData = false; let lastFetch = false; const download = function(url, cb) { let fetch = true; if (icalData) { const now = new Date().getTime() / 1000; const diff = now - 3600; if (diff < lastFetch ) { fetch = false; }; }; if (!fetch) { cb(null); } else { const request = https.get(url, function(response) { let bufferData = []; response.on( 'data', ( chunk ) => { bufferData.push( chunk ); }); response.on('end', () => { icalData = Buffer.concat( bufferData ); lastFetch = new Date().getTime() / 1000; cb(null); }); }).on('error', function(err) { if (cb) { cb(err); return false; } }); }; }; const calendar = (f,cb) => { const filter = [].concat(f); const re_array = []; const newline = "\r\n"; let return_object = `BEGIN:VCALENDAR${ newline }PRODID:-//Google Inc//Google Calendar//EN${ newline }VERSION:2.0${ newline }CALSCALE:GREGORIAN${ newline }X-WR-TIMEZONE:Europe/Stockholm${ newline }`; let calendarName = 'SHL'; let calendarDesc = 'Spelschema för SHL'; filter.forEach(function(team) { if (team === "BIF") { re_array.push("Brynäs IF"); } else if ( team === "DIF" ) { re_array.push("Djurgården"); } else if ( team === "FHC" ) { re_array.push("Frölunda HC"); } else if ( team === "FBK" ) { re_array.push("Färjestad BK"); } else if ( team === "HV71" ) { re_array.push("HV71"); } else if ( team === "KHK" ) { re_array.push("Karlskrona HK"); } else if ( team === "LIF" ) { re_array.push("Leksands IF"); } else if ( team === "LHC" ) { re_array.push("Linköping HC"); } else if ( team === "LHF" ) { re_array.push("Luleå Hockey"); } else if ( team === "MIF" ) { re_array.push("Malmö Redhawks"); } else if ( team === "RBK" ) { re_array.push("Rögle BK"); } else if ( team === "SAIK" ) { re_array.push("Skellefteå AIK"); } else if ( team === "VLH" ) { re_array.push("Växjö Lakers"); } else if ( team === "ÖRE" ) { re_array.push("Örebro Hockey"); }; }); if( filter.length === 1 ){ calendarName = re_array[ 0 ]; calendarDesc = `Spelshechema för ${ re_array[ 0 ] }`; } return_object = `${ return_object }X-WR-CALNAME:${ calendarName }${ newline }`; return_object = `${ return_object }X-WR-CALDESC:${ calendarDesc }${ newline }`; const global_re = re_array.join("|"); download(url, (err) => { if (err) { cb(err); return false; } let readStream = new stream.PassThrough(); readStream.end( icalData ); const lineReader = readline.createInterface({ input: readStream }); let in_event = false; let event_data = []; let print_event = false; lineReader.on('line', (line) => { if (line.match("^BEGIN:VEVENT")) { in_event = true; event_data = []; } if (in_event) { event_data.push(line); } if (line.match("^END:VEVENT")) { print_event = false; in_event = false; event_data.forEach(function(entry) { re = /^SUMMARY/; if (entry.match(re) && entry.match(global_re)) { print_event = true; }; }); if (print_event) { event_data.forEach(function(entry) { return_object += entry + newline; }); }; }; }); lineReader.on('close', () => { return_object = `${ return_object }END:VCALENDAR`; cb(null, return_object); }); lineReader.on('error', ( error ) => { cb(error); }); }); }; module.exports = calendar;
JavaScript
0.000002
@@ -2831,18 +2831,16 @@ = %60Spels -he chema f%C3%B6
ea7301385497917ddfaa5278c03ec0904ee8b2d0
Create class StopFlashTab
background.js
background.js
/** * StopFlash * * https://github.com/JWhile/StopFlash * * background.js */ function StopFlashBackground() { this.tabs = []; } /* function BackgroundFlashData(id) { this.id = id; // :int this.data = null; // :Object this.popupPort = null; // :chrome.runtime.Port this.contentPorts = []; // :Array<chrome.runtime.Port> } // function setData(Object data):void BackgroundFlashData.prototype.setData = function(data) { this.data = data; this.sendToPopup(); }; // function setPopup(chrome.runtime.Port popupPort):void BackgroundFlashData.prototype.setPopup = function(popupPort) { this.popupPort = popupPort; var self = this; this.popupPort.onDisconnect.addListener(function() { self.popupPort = null; }); this.sendToPopup(); }; // function setContentScript(chrome.runtime.Port contentPort):void BackgroundFlashData.prototype.setContentScript = function(contentPort) { this.contentPorts.push(contentPort); var self = this; contentPort.onDisconnect.addListener(function() { var index = self.contentPorts.indexOf(contentPort); if(index >= 0) { self.contentPorts.splice(index, 1); } }); contentPort.postMessage({'stopflashWhitelist': whitelist}); }; // function sendToPopup():void BackgroundFlashData.prototype.sendToPopup = function() { if(this.popupPort != null) { this.popupPort.postMessage({'stopflashData': this.data}); } }; // function sendToContent(Object data):void BackgroundFlashData.prototype.sendToContent = function(data) { for(var i = 0; i < this.contentPorts.length; ++i) { this.contentPorts[i].postMessage(data); } }; // function clear():void BackgroundFlashData.prototype.clear = function() { this.data = null; if(this.popupPort != null) { this.popupPort.disconnect(); } this.popupPort = null; if(this.contentPort != null) { this.contentPort.disconnect(); } this.contentPort = null; }; var flashData = []; // :Array<BackgroundFlashData> var whitelist = []; // :Array<String> // function getFlashData(int id):BackgroundFlashData var getFlashData = function(id) { for(var i = 0; i < flashData.length; ++i) { if(flashData[i].id === id) { return flashData[i]; } } return null; }; chrome.runtime.onConnect.addListener(function(port) { if(port.name === 'stopflashContentScript' && port.sender.tab != null) { var data = null; port.onMessage.addListener(function(rep) { if(rep['stopflashInit']) { data = getFlashData(port.sender.tab.id); if(data != null) { if(rep['stopflashIsMainFrame']) { data.clear(); } } else { data = new BackgroundFlashData(port.sender.tab.id); flashData.push(data); } data.setContentScript(port); } if(rep['stopflashHaveChange']) { data.data = null; data.sendToContent({'stopflashDataUpdate'}); } if(rep['stopflashDataUpdate'] && rep['stopflashData']) { data.setData(rep.stopflashData); } }); } else if(port.name === 'stopflashPopup') { var data = null; port.onMessage.addListener(function(rep) { if(rep['stopflashInit']) { data = getFlashData(rep['stopflashInit']); if(data != null) { data.setPopup(port); } } if(rep['stopflashBlock']) { data.sendToContent({'stopflashBlock': rep['stopflashBlock']}); } if(rep['stopflashUnblock']) { data.sendToContent({'stopflashUnblock': rep['stopflashUnblock']}); } }); } }); */
JavaScript
0.000001
@@ -129,16 +129,91 @@ bs = %5B%5D; + // :Array%3CStopFlashTab%3E%0A%7D%0A%0Afunction StopFlashTab()%0A%7B%0A this.frames = %5B%5D; %0A%7D%0A%0A/*%0Af
d37f331fbcb2f5e3b300b9b4f4e1050a865072cf
replace deprecated getSelected with query, add null check for exiting chrome
background.js
background.js
var hkgcacheUrl = "https://plasticnofd.xyz/#/"; var isValidUrl = false; var type, message, page; // listener // Note that the tab's URL may not be set at the time onActivated event fired chrome.tabs.onActivated.addListener(UpdateShowStatus); chrome.tabs.onUpdated.addListener(UpdateShowStatus); // process the new url on extension icon clicked chrome.extension.onRequest.addListener( function(request, sender) { chrome.tabs.getSelected(null,function(tab) { var givenUrl = request.url; var clipboardText = request.clipboardText; // always check the tab url first if(IsDomainHKGForum(tab.url)){ var newUrl = GetHKGCacheUrlFromUrl(tab.url); console.log("newUrl=" + newUrl); chrome.runtime.sendMessage({action: "redirect", url: newUrl}); } // work with any given url else if (typeof givenUrl != "undefined" && null != givenUrl) { if(IsDomainHKGForum(givenUrl)){ var newUrl = GetHKGCacheUrlFromUrl(givenUrl); console.log("newUrl=" + givenUrl); chrome.runtime.sendMessage({action: "redirect", url: newUrl}); } else { console.log("clearUrlField"); chrome.runtime.sendMessage({action: "clearUrlField"}); } } // work with the clipboard value else if (typeof clipboardText != "undefined" && null != clipboardText) { console.log("clipboardText=" + clipboardText); if(!IsDomainHKGForum(clipboardText)) { console.log("clearUrlField"); chrome.runtime.sendMessage({action: "clearUrlField"}); } } else { console.log("Unexpected error"); } }); } ) // update extension show status function UpdateShowStatus(activeInfo) { chrome.tabs.getSelected(null,function(tab) { chrome.pageAction.show(tab.id); }); }; // reset value to default function Init() { // so any error page will redirect to /BW/1 type = "BW"; message = ""; page = "1"; } // get the corrsponding HKGCache url from current url function GetHKGCacheUrlFromUrl(url) { Init(); AnalyseHKGDataFromUrl(url); // topic if (message == "") { return (hkgcacheUrl + "topics/" + type.toUpperCase() + "/" + page); } // post else { return (hkgcacheUrl + "post/" + message + "/" + page); } } // check if the url is a valid HKG url function IsDomainHKGForum(url) { if(typeof url == "undefined" || null == url) url = window.location.href; var regex = /(m[0-9]+|forum[0-9]+)\.hkgolden\.com/; var match = url.match(regex); // confirm to be hkg forum if(typeof match != "undefined" && null != match) { return true; } return false; } // prepare the data for generating the url // assumed that url is valid and domain is checked function AnalyseHKGDataFromUrl(url) { var content = url.split(".com"); if (typeof content != "undefined") { var data = content[1].split(/[\?\&]+/); if(typeof data != "undefined" && null != data) { data.forEach(AnalyseHKGData); } } } // for each type of data function AnalyseHKGData(element, index, array) { var content = element.split("="); if (typeof content != "undefined" && content.length == 2) { switch(content[0]) { case "type": type = content[1]; break; case "message": message = content[1]; break; case "page": page = content[1]; break; } //console.log("set " + content[0] + " to " + content[1]); } } // contextMenus // Set up context menu at install time. chrome.runtime.onInstalled.addListener(function() { console.log("onInstall"); var context = ["page", "link"] var title = "View with HKGCache"; chrome.contextMenus.create({title: title, contexts: context}); }); chrome.contextMenus.onClicked.addListener(function(info) { if (info.linkUrl) { console.log("linkUrl=" + info.linkUrl); url = info.linkUrl; if(IsDomainHKGForum(url)){ chrome.tabs.create({url: GetHKGCacheUrlFromUrl(url), active: true}); } } // try page else { console.log("pageUrl=" + info.pageUrl); url = info.pageUrl; if(IsDomainHKGForum(url)){ chrome.tabs.getSelected(null, function(tab) { console.log("redirecting to " + url); chrome.tabs.update(tab.id, {url: GetHKGCacheUrlFromUrl(url)}); }); } } });
JavaScript
0
@@ -2080,32 +2080,65 @@ me.tabs. -getSelected(null +query(%7B%22active%22: true, %22lastFocusedWindow%22: true%7D ,functio @@ -2134,37 +2134,141 @@ ue%7D,function(tab +s ) %7B%0D%0A + if (typeof tabs != %22undefined%22 && null != tabs) %7B%0D%0A if (tabs.length %3E 0) %7B%0D%0A chrome.p @@ -2289,15 +2289,45 @@ (tab +s%5B0%5D .id);%0D%0A + %7D%0D%0A %7D%0D%0A
dd8142eba176f7c262e07949045a4650cdc82ee0
Make sure default state is properly set.
background.js
background.js
function reflowListener(windowId, start, stop, stack) { OhNoReflow.reflow({ windowId, start, stop, stack }); } const OhNoReflow = { reflowLog: [], _enabled: false, set enabled(val) { if (val) { browser.reflows.onUninterruptableReflow.addListener(reflowListener); } else { browser.reflows.onUninterruptableReflow.removeListener(reflowListener); } this._enabled = val; this.saveState(); return this._enabled; }, get enabled() { return this._enabled; }, _threshold: 1.0, set threshold(val) { if (!isNaN(val)) { this._threshold = val; this.saveState(); } return this._threshold; }, get threshold() { return this._threshold; }, sound: false, ignoreNative: true, saveState() { let state = { enabled: this.enabled, threshold: this.threshold, sound: this.sound, ignoreNative: this.ignoreNative, }; browser.storage.local.set({ state }); }, init(state, signatureStuff) { browser.runtime.onMessage.addListener(this.messageListener.bind(this)); browser.commands.onCommand.addListener(this.commandListener.bind(this)); this.threshold = parseFloat(state.threshold, 10); if (state.enabled) { this.toggle(true); } this.sound = !!state.sound; if (state.ignoreNative !== undefined) { this.ignoreNative = !!state.ignoreNative; } this.sigData = []; this.loadSigData(signatureStuff); }, commandListener(command) { switch (command) { case "Toggle": { this.toggle(!this.enabled); break; } case "DumpReport": { this.dumpReport(); break; } } }, messageListener(msg, sender, sendReply) { switch(msg.name) { case "get-reflows": { sendReply(this.reflowLog); break; } case "get-signature-data": { sendReply(this.sigData); break; } case "reset": { this.reset(); break; } case "get-state": { sendReply({ enabled: this.enabled, threshold: this.threshold, sound: this.sound, ignoreNative: this.ignoreNative, }); break; } case "toggle": { this.toggle(msg.enabled); break; } case "threshold": { this.threshold = msg.threshold; break; } case "sound": { this.sound = msg.enabled; break; } case "ignoreNative": { this.ignoreNative = msg.enabled; break; } case "dumpReport": { this.dumpReport(); break; } } }, reflow(reflowData) { if (this.ignoreNative && !reflowData.stack) { return; } let totalTime = (reflowData.stop - reflowData.start).toFixed(2); if (totalTime >= this.threshold) { this.reflowLog.push(reflowData); if (this.sound) { this.playSound(); } this.updateBadge(); } }, reset() { this.reflowLog = []; this.updateBadge(); }, toggle(enabled) { if (this.enabled != enabled) { this.enabled = enabled; let iconSuffix = this.enabled ? "on" : "off"; let path = `icons/toolbar_${iconSuffix}.png`; browser.browserAction.setIcon({ path }); this.updateBadge(); } }, dumpReport() { browser.tabs.create({ url: "/content/report.html", }); }, _playTimer: null, _soundObj: new Audio("/sounds/sonar-sweep.mp3"), playSound() { if (this._playTimer) { clearTimeout(this._playTimer); } this._playTimer = setTimeout(() => { this._soundObj.play(); this._playTimer = null; }, 500); }, updateBadge() { let text = this.enabled ? this.reflowLog.length.toString() : ""; browser.browserAction.setBadgeText({ text }); }, loadSigData(signatureStuff) { this.sigData = []; for (let sigEntry of signatureStuff.data) { let bugs = sigEntry.bugs; let signatures = sigEntry.signatures; this.sigData.push({ bugs, signatures }); } }, } browser.storage.local.get("state").then(result => { window.fetch("docs/signatures.json").then((response) => { response.json().then((sigs) => { OhNoReflow.init(result.state, sigs); }); }); });
JavaScript
0
@@ -113,16 +113,119 @@ %7D);%0A%7D%0A%0A +const DEFAULT_STATE = %7B%0A enabled: true,%0A threshold: %221.0%22,%0A sound: false,%0A ignoreNative: true,%0A%7D;%0A%0A const Oh @@ -4369,24 +4369,41 @@ result.state + %7C%7C DEFAULT_STATE , sigs);%0A
a0b049a5f396eb9498bd1a8ea8bdb79f64321b97
Save the players array correctly when saving game stats
server/repositories/gameRepository.js
server/repositories/gameRepository.js
const mongoskin = require('mongoskin'); const logger = require('../log.js'); class GameRepository { save(game, callback) { var db = mongoskin.db('mongodb://127.0.0.1:27017/throneteki'); if(!game.id) { db.collection('games').insert(game, function(err, result) { if(err) { logger.info(err.message); callback(err); return; } callback(undefined, result.ops[0]._id); }); } else { db.collection('games').update({ _id: mongoskin.helper.toObjectID(game.id) }, { '$set': { startedAt: game.startedAt, players: game.playersAndSpectators, winner: game.winner, winReason: game.winReason, finishedAt: game.finishedAt } }); } } } module.exports = GameRepository;
JavaScript
0.000001
@@ -742,21 +742,8 @@ yers -AndSpectators ,%0A
40743d988e0ab90d9e54f304a65a5f436db13dbd
Add test for untested empty string branch.
server/test/unit/logger/loggerSpec.js
server/test/unit/logger/loggerSpec.js
'use strict'; var chai = require('chai'), expect = chai.expect, sinon = require('sinon'), sinonChai = require('sinon-chai'), logger = require('../../../logger'); chai.use(sinonChai); describe('logger', function () { describe('infoStream', function () { var infoStream = logger.infoStream, messageWithInnerLinebreaks = '\nany message containing \n \n line breaks'; beforeEach(function () { logger.info = sinon.stub(); }); it('should remove any new line characters at the end', function () { var message = messageWithInnerLinebreaks + '\n\n\n'; infoStream.write(message); expect(logger.info).to.have.been.calledOnce; expect(logger.info).to.have.been.calledWith(messageWithInnerLinebreaks); }); it('should not remove new line characters in the message string if not at the end', function () { infoStream.write(messageWithInnerLinebreaks); expect(logger.info).to.have.been.calledOnce; expect(logger.info).to.have.been.calledWith(messageWithInnerLinebreaks); }); it('should stop removing characters when none are left anymore', function () { infoStream.write('\n'); expect(logger.info).to.have.been.calledOnce; expect(logger.info).to.have.been.calledWith(''); }); }); });
JavaScript
0
@@ -1139,32 +1139,279 @@ );%0A %7D);%0A%0A + it('should return without errors if the message is empty', function () %7B%0A infoStream.write('');%0A%0A expect(logger.info).to.have.been.calledOnce;%0A expect(logger.info).to.have.been.calledWith('');%0A %7D);%0A%0A it('shou
c1b4756ccaf67ba51d253ef02989017b990e30be
Define the view contexts for the unified dashboard.
assets/js/googlesitekit/widgets/default-contexts.js
assets/js/googlesitekit/widgets/default-contexts.js
/** * Widgets API default contexts * * Site Kit by Google, Copyright 2021 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. */ export const CONTEXT_DASHBOARD = 'dashboard'; export const CONTEXT_PAGE_DASHBOARD = 'pageDashboard'; export const CONTEXT_MODULE_SEARCH_CONSOLE = 'moduleSearchConsole'; export const CONTEXT_MODULE_ANALYTICS = 'moduleAnalytics'; export const CONTEXT_MODULE_ADSENSE = 'moduleAdsense'; export default { CONTEXT_DASHBOARD, CONTEXT_PAGE_DASHBOARD, CONTEXT_MODULE_SEARCH_CONSOLE, CONTEXT_MODULE_ANALYTICS, CONTEXT_MODULE_ADSENSE, };
JavaScript
0.000002
@@ -645,16 +645,101 @@ e.%0A */%0A%0A +/**%0A * Internal dependencies%0A */%0Aimport %7B isFeatureEnabled %7D from '../../features';%0A%0A export c @@ -1160,11 +1160,642 @@ DSENSE,%0A +%09...( isFeatureEnabled( 'unifiedDashboard' )%0A%09%09? %7B%0A%09%09%09%09// Main dashboard%0A%09%09%09%09CONTEXT_MAIN_DASHBOARD_TRAFFIC: 'mainDashboardTraffic',%0A%09%09%09%09CONTEXT_MAIN_DASHBOARD_CONTENT: 'mainDashboardContent',%0A%09%09%09%09CONTEXT_MAIN_DASHBOARD_SPEED: 'mainDashboardSpeed',%0A%09%09%09%09CONTEXT_MAIN_DASHBOARD_MONETIZATION:%0A%09%09%09%09%09'mainDashboardMonetization',%0A%09%09%09%09// Entity dashboard%0A%09%09%09%09CONTEXT_ENTITY_DASHBOARD_TRAFFIC: 'entityDashboardTraffic',%0A%09%09%09%09CONTEXT_ENTITY_DASHBOARD_CONTENT: 'entityDashboardContent',%0A%09%09%09%09CONTEXT_ENTITY_DASHBOARD_SPEED: 'entityDashboardSpeed',%0A%09%09%09%09CONTEXT_ENTITY_DASHBOARD_MONETIZATION:%0A%09%09%09%09%09'entityDashboardMonetization',%0A%09%09 %7D%0A%09%09: %7B%7D ),%0A %7D;%0A
cb04d931a6666910cc549e71f1b5f5afd6a5aebd
Properly encode UTF-8
src/Util.js
src/Util.js
var Util = { // '19:00' formatTime: function(date) { return date.toTimeString().substring(0, 5); }, // 'Wed Jul 28' formatDate: function(date) { return date.toDateString().substring(0, 10); }, trimLine: function(str) { return str.substring(0, 30); }, // 'Wed Jul 28 19:00' getMessageDateTime: function(message) { var date = new Date(+message.internalDate); return Util.formatDate(date) + ', ' + Util.formatTime(date); }, getMessageHeader: function(message, headerName) { var headers = message.payload.headers; for (var i = 0; i < headers.length; i++) { if (headers[i].name === headerName) { return headers[i].value; } } return ''; }, getMessageFromHeader: function(message) { var from = this.getMessageHeader(message, 'From'); var bracketIndex = from.indexOf('<'); // If the only thing in the from header is '<email>', keep it. if (bracketIndex > 0) { return from.substring(0, bracketIndex).trim(); } else { return from; } }, getMessageSubjectHeader: function(message) { return this.getMessageHeader(message, 'Subject') || '(no subject)'; }, // Decodes html text from html entities and tags // Credit: https://gist.github.com/CatTail/4174511 decodeHTML: function(str) { if (!str) return ''; return str.replace(/<[^>]*>/g, "").replace(/&#(\d+);/g, function(match, dec) { return String.fromCharCode(dec); }); }, // Decodes base64 // Credit: http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html base64keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789-_=", decode64: function(input, maxlength) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; maxlength = maxlength ? (maxlength * 4 + 2) / 3 : input.length; maxlength = maxlength < input.length ? maxlength : input.length; do { enc1 = this.base64keyStr.indexOf(input.charAt(i++)); enc2 = this.base64keyStr.indexOf(input.charAt(i++)); enc3 = this.base64keyStr.indexOf(input.charAt(i++)); enc4 = this.base64keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < maxlength); return output; }, /* Recursively grabs the first text part of multipart messages * Prefers plaintext over html. */ getMessageBody: function(message) { var body = null; if ('payload' in message) { if (!message.loaded) { return Util.decodeHTML(message.snippet || ''); } body = Util.getMessageBody(message.payload); if (!body || !body.data) { return ''; } var limit = Pebble.getActiveWatchInfo().platform == 'aplite' ? 768 : 0; body.data = Util.decode64(body.data, limit); return body.html ? Util.decodeHTML(body.data) : body.data; } else if (message.mimeType.substring(0, 4) == 'text' && message.body.data) { return { html: message.mimeType.slice(-4) == 'html', data: message.body.data }; } else if (message.mimeType.substring(0, 9) == 'multipart') { for (var i = 0; i < message.parts.length; i++) { var part = Util.getMessageBody(message.parts[i]); if (part && !part.html) { return part; } else if (part && part.html && !body) { body = part; } } } return body; }, getFriendlyLabelName: function(label) { if (label.type === 'system') { var match = /^CATEGORY_(.*)$/.exec(label.id); if (match) { return Util.capitalize(match[1]); } else { return Util.capitalize(label.name); } } return label.name; }, capitalize: function(str) { if (str) { return str[0].toUpperCase() + str.substring(1).toLowerCase(); } return ''; }, plural: function(number, text) { return number != 1 ? (text || 's') : ''; }, systemLabelSortComparator: function(a, b) { var priorities = { UNREAD: 1, STARRED: 2, IMPORTANT: 3, INBOX: 4, SPAM: 5, TRASH: 6 }; return (priorities[a.label.id] || 9) - (priorities[b.label.id] || 9); } }; module.exports = Util;
JavaScript
0.999999
@@ -2684,21 +2684,88 @@ -return +/* Make the string proper UTF-8 */%0A return decodeURIComponent(escape( output +)) ;%0A
1e64df6dbb57254e3f6e5ae8266496d3372ba5a8
remove async from lambda function definition
lambdas/rematching/index.js
lambdas/rematching/index.js
const { rematchAllQuestionsOfAType, rematchIndividualQuestion } = require('./rematch') exports.handler = async (event, context, callback) => { const { uid, type } = event function finishRematching() { const response = { statusCode: 200, body: JSON.stringify(`uid: ${uid}, type: ${type}`), headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, }; callback(null, JSON.stringify(response)) } if (uid) { rematchIndividualQuestion(uid, type, finishRematching) } else { rematchAllQuestionsOfAType(type, finishRematching) } };
JavaScript
0.000016
@@ -103,14 +103,8 @@ er = - async (ev
479c4b36136efce2a807122b29b88174b9b3fee8
Use push from props instead of router
src/components/Navigation/components/Navigation.js
src/components/Navigation/components/Navigation.js
import React from 'react'; import { withRouter } from 'react-router'; import InfinityMenu from 'react-infinity-menu'; import './Navigation.scss'; export class Navigation extends React.Component { constructor (props) { super(props); this.onNodeMouseClick = this.onNodeMouseClick.bind(this); this.onLeafMouseClick = this.onLeafMouseClick.bind(this); this.toggleNavigationVisibility = this.toggleNavigationVisibility.bind(this); this.state = { tree: [] }; } componentWillMount () { this.props.fetchNavigation(); } componentWillReceiveProps (nextProps) { const { items } = nextProps; this.setState({ tree: items }); } componentDidUpdate () { if (this.props.TOSPath.length === 0) { this.props.setNavigationVisibility(true); } } toggleNavigationVisibility () { const currentVisibility = this.props.is_open; this.props.setNavigationVisibility(!currentVisibility); } onNodeMouseClick (event, tree, node, level, keyPath) { this.setState({ tree: tree }); } onLeafMouseClick (event, leaf) { this.props.router.push(`/view-tos/${leaf.id}`); this.toggleNavigationVisibility(); } render () { let navigationTitle = 'Navigaatio'; if (!this.props.is_open && this.props.TOSPath.length) { navigationTitle = this.props.TOSPath.map((section, index) => { return <div key={index}>{section}</div>; }); } return ( <div className='container-fluid'> <div className='navigation-menu'> <button className='btn btn-default btn-sm pull-right' onClick={this.toggleNavigationVisibility}> <span className={'fa ' + (this.props.is_open ? 'fa-minus' : 'fa-plus')} aria-hidden='true' /> </button> {!this.props.is_open && <div className='nav-path-list' onClick={this.toggleNavigationVisibility}>{navigationTitle}</div> } {this.props.is_open && <InfinityMenu tree={this.state.tree} onNodeMouseClick={this.onNodeMouseClick} onLeafMouseClick={this.onLeafMouseClick} /> } </div> </div> ); } } Navigation.propTypes = { TOSPath: React.PropTypes.array.isRequired, fetchNavigation: React.PropTypes.func.isRequired, is_open: React.PropTypes.bool.isRequired, items: React.PropTypes.array.isRequired, router: React.PropTypes.object.isRequired, setNavigationVisibility: React.PropTypes.func.isRequired }; export default withRouter(Navigation);
JavaScript
0
@@ -24,51 +24,8 @@ t';%0A -import %7B withRouter %7D from 'react-router';%0A impo @@ -1071,15 +1071,8 @@ ops. -router. push @@ -2391,14 +2391,12 @@ ,%0A -router +push : Re @@ -2413,14 +2413,12 @@ pes. -object +func .isR @@ -2508,19 +2508,8 @@ ult -withRouter( Navi @@ -2514,11 +2514,10 @@ vigation -) ;%0A
d63a7b245f2abd43ef0af5d39604f89189f48300
Remove button setting
site/js/whileaway.js
site/js/whileaway.js
/*****************************************************************************/ /* Main JS for whileaway */ /*****************************************************************************/ // Form UI fixes $('#keyword').change(function() { option_val = $('#keyword > option:selected').text(); $('#keyword-span').html(option_val); $('#keyword').width($('#keyword-span').width()); }); $('#keyword').change(); $('#date').change(function() { option_val = $('#date > option:selected').text(); $('#date-span').html(option_val); $('#date').width($('#date-span').width()); }); $('#date').change(); function inputWidth() { $('#number-span').html($('#number').val()); $('#number').css('width', $('#number-span').width()); } inputWidth(); $('#number').bind('keyup input paste', inputWidth); window.onresize = function() { $('#keyword').change(); $('#date').change(); inputWidth(); } // Fetching and displaying stories getNews(); // onchange of input fields, call getNews() $('#number').bind('keyup input paste', function(){getNews();}); $('#date').change(function(){getNews();}); $('#keyword').change(function(){getNews();}); function getNews(){ amount = $('#number').val(); scope = $('#date option:selected').val(); keyword = $('#keyword option:selected').val(); if (keyword == 'news') { keyword = ''; }; try { validate(amount, scope, keyword); } catch (e) { alert(e); return; } // make asynchronous request getNewsFromAPI(amount, scope, keyword); } function handleNews(news){ $('#form button').html('Go'); str = '<ol>'; $.each(news, function(index, story) { headline = story[0]; link = story[1]; date = story[2]; // summary = story[3]; // str += '<li>' + headline + ' (<a href="' + link + '">more…</a>, ' + date.f('d MMM yyyy HH:mm') + ')</li>'; str += '<li><a href="' + link + '">' + headline + '</a></li>'; }); str += '</ol>'; $('#headlines').html(str); } function validate(amount, scope, keyword) { scopes = ['days', 'weeks', 'months']; if (scopes.indexOf(scope) < 0) { throw 'Invalid scope'; } if (isNaN(amount)) { throw 'Invalid amount'; } $.trim(keyword); }
JavaScript
0.000103
@@ -1565,40 +1565,8 @@ s)%7B%0A -%09$('#form button').html('Go');%0A%0A %09str
f84972b7c25d6fc95f4e21ce08fbe66fdb39ef33
Fix module export
templates/Gjs/module.js
templates/Gjs/module.js
imports.gi.versions.<%= name %> = '<%= version %>' export default imports.gi.<%= name %>
JavaScript
0
@@ -48,22 +48,24 @@ %25%3E'%0A -export default +module.exports = imp
99ceffeaad638905df64a5c3a135fd8a8ce4644d
test fix
test/dft-complex.js
test/dft-complex.js
'use strict'; var lib = require('../lib'), expect = require('chai').expect; describe('DFT 1024', function () { var i, inpReal, inpImag, res, len = 1024, add = function (a, b) { return a + b; }; before(function () { inpReal = []; inpImag = []; for (i = 0; i < len; i++) { inpReal.push(0); inpImag.push(0); } }); it('zero', function (done) { res = lib.dftComplex(inpReal, inpImag); expect(res[0]).to.be.an('array'); expect(res[1]).to.be.an('array'); expect(res[0].reduce(add, 0)).to.be.equal(0); expect(res[1].reduce(add, 0)).to.be.equal(0); done(); }); it('DC = 1', function (done) { inpReal[0] = 1; res = lib.dftComplex(inpReal, inpImag); expect(res[0].reduce(add, 0)).to.be.equal(len); expect(res[1].reduce(add, 0)).to.be.equal(0); done(); }); it('random 8', function (done) { inpReal = [ 0.27984, 0.57953, 0.46401, 0.35479, 0.57387, 0.83437, 0.51631, 0.86183 ]; res = lib.dftComplex(inpReal, inpImag); expect(res[0]).to.be.eql([ 4.46455, -0.11569766978475315, -0.12661000000000014, -0.4723623302152477, -0.7964899999999999, -0.4723623302152478, -0.1266100000000027, -0.11569766978474949 ]); expect(res[1]).to.be.eql([ 0, 0.5910305144504069, -0.19728000000000023, 0.4864305144504075, -6.768867788247251e-16, -0.4864305144504081, 0.19727999999999957, -0.5910305144504059 ]); done(); }); });
JavaScript
0.000001
@@ -467,39 +467,32 @@ res = lib.dft -Complex (inpReal, inpIma @@ -786,39 +786,32 @@ res = lib.dft -Complex (inpReal, inpIma @@ -1211,15 +1211,8 @@ .dft -Complex (inp
31dcfaacafaf8276475a7abd036773ddb7a473bc
Order tag names
cmd/tags.js
cmd/tags.js
exports.run = async function (Elga, msg, args) { if (!args[0]) { Elga.db.all('SELECT * FROM tags') .then(res => { msg.edit({ embed: { title: `Tags (${res.length})`, color: Elga.config.embedColor, description: res.map(tag => tag.tagName).join(', ') } }); }) .catch(err => { Elga.cmdErr(msg, err); }); } const tag = await Elga.db.get('SELECT * FROM tags WHERE TagName = ?', args[1] || args[0]); if (['create', 'edit'].includes(args[0]) && tag) { return msg.edit(`Tag \`${args[1]}\` already exists${tag.tagContent.length < 750 ? ` with contents:\n${Elga.codeblock(tag.tagContent)}` : '.'}`); } if (['delete', 'remove'].includes(args[0]) && !tag) { return msg.edit(`No tag found with name \`${args[0]}\`.`); } if (args[0] === 'remove' || args[0] === 'delete') { Elga.db.run('DELETE FROM tags WHERE TagName = ?', args[1]) .then(() => { msg.edit(`Tag \`${args[1]}\` successfully deleted.`); }) .catch(err => { return Elga.cmdErr(msg, err); }); } else if (args[0] === 'create' || args[0] === 'add') { Elga.db.run('INSERT INTO tags (TagName, TagContent) VALUES (?, ?)', args[1], args.slice(2).join(' ')) .then(() => { msg.channel.send({ embed: { color: Elga.config.embedColor, title: `${args[1]} created successfully.`, description: `*${args.slice(2).join(' ')}*` } }); }) .catch(err => { return Elga.cmdErr(msg, err); }); } else if (args[0] === 'edit') { Elga.db.run('UPDATE tags SET TagContent = ? WHERE TagName = ?', args.slice(2).join(' '), args[1]) .then(() => { msg.channel.send({ embed: { color: Elga.config.embedColor, title: `${args[1]} updated successfully.`, description: `*${args.slice(2).join(' ')}*` } }); }) .catch(err => { Elga.cmdErr(msg, err); }); } else { if (['jpg', 'png', 'peg', 'gif', 'ebp'].includes(tag.tagContent.slice(-3, tag.tagContent.length)) && (msg.channel.type === 'dm' || msg.channel.permissionsFor(Elga.user.id).has('EMBED_LINKS'))) { msg.edit({ embed: { // I would send this raw, but that would mean deleting the old message and sending a new one color: Elga.config.embedColor, // because you can't edit old messages to have images image: { url: tag.tagContent } } }); } else { msg.edit(tag.tagContent); } } }; exports.props = { name : 'tags', usage : '{command} [tag name | add | remove | edit | nothing] [tag name] [(new) contents]', aliases : ['tag'], description : 'TBD' };
JavaScript
0.000001
@@ -101,16 +101,37 @@ ROM tags + ORDER BY TagName ASC ')%0A @@ -478,24 +478,40 @@ %7D);%0A + return;%0A %7D%0A%0A c
f3d02945223e2bd166bc0465f58ac82ba62dddbe
support startPropagation
base-event.js
base-event.js
var Delegator = require('dom-delegator') module.exports = BaseEvent function BaseEvent(lambda) { return EventHandler; function EventHandler(fn, data, opts) { var handler = { fn: fn, data: data || {}, opts: opts || {}, handleEvent: handleEvent } if (fn && fn.type === 'dom-delegator-handle') { return Delegator.transformHandle(fn, handleLambda.bind(handler)) } return handler; } function handleLambda(ev, broadcast) { return lambda.call(this, ev, broadcast) } function handleEvent(ev) { var self = this lambda.call(self, ev, broadcast) function broadcast(value) { if (typeof self.fn === 'function') { self.fn(value) } else { self.fn.write(value) } } } }
JavaScript
0
@@ -560,109 +560,331 @@ -return lambda.call(this, ev, broadcast)%0A %7D%0A%0A function handleEvent(ev) %7B%0A var self = this +if (this.opts.startPropagation && ev.startPropagation) %7B%0A ev.startPropagation();%0A %7D%0A%0A return lambda.call(this, ev, broadcast)%0A %7D%0A%0A function handleEvent(ev) %7B%0A var self = this%0A%0A if (self.opts.startPropagation && ev.startPropagation) %7B%0A ev.startPropagation()%0A %7D%0A %0A
33236ef9ee7f42ac24996ab08b24b20ae11383a0
Add Base documentation
src/base.js
src/base.js
udefine(['eventmap', 'mixedice', 'gameboard/input', './group', './world'], function(EventMap, mixedice, Input, Group, World) { 'use strict'; var objectIndex = 0; var prependMax = 10000; var numToIdString = function(num) { var stringNum = num + ''; if (num >= prependMax) { return stringNum; } else { var prependLength = (prependMax + '').length - stringNum.length; for (var i = 0; i < prependLength; i++) { stringNum = '0' + stringNum; } return stringNum; } }; var Base = function(type, descriptor) { var self = this; mixedice([this, Base.prototype], new EventMap()); type = type || 'Base'; this.type = type; this.name = this.type + '-' + Date.now(); var currentObject = numToIdString(++objectIndex); Object.defineProperty(this, 'id', { get: function() { return this.type + '-' + currentObject; }, enumerable: true }); this.descriptor = descriptor; this.children = new Group(); this.queue = []; this.parent = null; this.input = Input; this.world = World; this.trigger('constructed'); }; Base.prototype.call = Base.prototype.reset = function() { this.apply(arguments); }; Base.prototype.apply = function(args) { // TODO: Reflect if function check should be enforced here if (this.descriptor) { this.descriptor.apply(this, args); this.trigger('execute'); // TODO: Impose an order in the queue, such as: // (Game) -> Scene -> GameObject -> Behavior -> Model this.queue.forEach(function(q) { q && q(); }); this.queue = []; } }; Base.prototype.log = function() { if (console && console.log) { var argArray = [].slice.call(arguments); argArray.unshift(':'); argArray.unshift(this.name); argArray.unshift(this.type); return console.log.apply(console, argArray); } }; Base.extend = function(target, type, descriptor) { var base = new Base(type, descriptor); mixedice(target, base); }; return Base; });
JavaScript
0
@@ -588,16 +588,65 @@ this;%0A%0A + // Mix in an %60EventMap%60 instance into %60Base%60%0A mixe @@ -785,24 +785,71 @@ ate.now();%0A%0A + // Count up %60objectIndex%60 and stringify it%0A var curr @@ -887,24 +887,116 @@ ectIndex);%0A%0A + // The %60id%60 property is read-only and returns the type and the stringified object index%0A Object.d @@ -1132,24 +1132,51 @@ ue%0A %7D);%0A%0A + // Save the descriptor%0A this.des @@ -1206,109 +1206,407 @@ -this.children = new Group();%0A%0A this.queue = %5B%5D;%0A%0A this.parent = null;%0A%0A this.input = Input;%0A +// Create a new group for all children elements%0A this.children = new Group();%0A%0A // Add a queue: All addable elements will be pushed into the queue first and called after everything else in%0A // the %60descriptor%60 has been called%0A this.queue = %5B%5D;%0A%0A this.parent = null;%0A%0A // %60Input%60 should be available in instances derived from %60Base%60%0A this.input = Input;%0A%0A // As should %60World%60 %0A @@ -1627,16 +1627,37 @@ World;%0A%0A + // Emit an event%0A this @@ -1743,24 +1743,75 @@ unction() %7B%0A + // Call %60Base#apply%60 with the arguments object%0A this.app @@ -1963,16 +1963,162 @@ ptor) %7B%0A + // If args is not an array or array-like, provide an empty one%0A args = args %7C%7C %5B%5D;%0A%0A // Call the %60descriptor%60 property with %60args%60 %0A t @@ -2151,16 +2151,49 @@ args);%0A + %0A // Trigger an event%0A th @@ -2330,16 +2330,56 @@ %3E Model%0A + %0A // TODO: Implement z-order%0A th @@ -2437,16 +2437,48 @@ %7D);%0A + %0A // Reset the queue%0A th @@ -2618,24 +2618,83 @@ rguments);%0A%0A + // Log with %60console.log%60: Prepend the type and name%0A argArr @@ -2840,24 +2840,79 @@ %7D%0A %7D;%0A%0A + // Shorthand function to derive from the Base object%0A Base.exten
161dd218e7ddc0115700aa14d3e6be8ce62642c9
Simplify disabling logic for georef modal
lib/assets/javascripts/cartodb/common/dialogs/georeference/georeference_model.js
lib/assets/javascripts/cartodb/common/dialogs/georeference/georeference_model.js
var Backbone = require('backbone'); var _ = require('underscore'); var cdb = require('cartodb.js'); var LonLatColumnsModel = require('./lon_lat_columns/lon_lat_columns_model'); var CityNamesModel = require('./city_names/city_names_model'); var AdminRegionsModel = require('./admin_regions/admin_regions_model'); var PostalCodesModel = require('./postal_codes/postal_codes_model'); var IpAddressesModel = require('./ip_addresses/ip_addresses_model'); var StreetAddressesModel = require('./street_addresses/street_addresses_model'); var GeocodeStuff = require('./geocode_stuff'); var UserGeocodingModel = require('./user_geocoding_model'); /** * View model for merge datasets view. */ module.exports = cdb.core.Model.extend({ _EXCLUDED_COLUMN_NAMES: ['cartodb_id', 'the_geom', 'updated_at', 'created_at', 'cartodb_georef_status'], _ALLOWED_COLUMN_TYPES: ['string', 'number', 'boolean', 'date'], defaults: { options: undefined // Collection, created with model }, initialize: function(attrs) { if (!attrs.table) throw new Error('table is required'); if (!attrs.user) throw new Error('user is required'); this._initOptions(); }, changedSelectedTab: function(newTab) { this.get('options').chain() .without(newTab).each(this._deselect); }, createView: function() { return this._selectedTabModel().createView(); }, canContinue: function() { return this._selectedTabModel().get('canContinue'); }, continue: function() { if (this.canContinue()) { this._selectedTabModel().continue(); } }, canGoBack: function() { return this._selectedTabModel().get('canGoBack'); }, goBack: function() { if (this.canGoBack()) { this._selectedTabModel().goBack(); } }, updateAvailableGeometriesFetchData: function() { this._selectedTabModel().updateAvailableGeometriesFetchData(this.get('table').get('id')); location = m.get('location'); var d = { kind: m.kind }; var location = this.get('location'); m.set('availableGeometriesFetchData', { kind: m.kind, }); }, _selectedTabModel: function() { return this.get('options').find(this._isSelected); }, _columnsNames: function() { // Maintained old logic, so for some reason the column types filter is not applied for the places where the column names are usd return _.chain(this.get('table').get('schema')) .filter(this._isAllowedColumnName, this) .map(this._columnName) .value(); }, _filteredColumns: function() { var table = this.get('table'); // original_schema may be set if not in SQL view (see where attr is set in the table model) // maintained from code to not break behavior when implementing this new modal return _.chain(table.get('original_schema') || table.get('schema')) .filter(this._isAllowedColumnName, this) .filter(this._isAllowedColumnType, this) .map(this._inverColumnRawValues) .value(); }, _inverColumnRawValues: function(rawColumn) { // The cdb.forms.CustomTextCombo expects the data to be in order of [type, name], so need to translate the raw schema var type = rawColumn[1]; var name = rawColumn[0]; return [type, name]; }, _isAllowedColumnName: function(rawColumn) { return !_.contains(this._EXCLUDED_COLUMN_NAMES, this._columnName(rawColumn)); }, _isAllowedColumnType: function(rawColumn) { return _.contains(this._ALLOWED_COLUMN_TYPES, this._columnType(rawColumn)); }, _columnName: function(rawColumn) { return rawColumn[0]; }, _columnType: function(rawColumn) { return rawColumn[1]; }, _isSelected: function(m) { return m.get('selected'); }, _deselect: function(m) { m.set('selected', false); }, _initOptions: function() { var geocodeStuff = new GeocodeStuff(this.get('table').get('id')); var columnsNames = this._columnsNames(); var columns = this._filteredColumns(); this.set('options', new Backbone.Collection([ new LonLatColumnsModel({ geocodeStuff: geocodeStuff, columnsNames: columnsNames, selected: true }), new CityNamesModel({ geocodeStuff: geocodeStuff, columnsNames: columnsNames, columns: columns }), new AdminRegionsModel({ geocodeStuff: geocodeStuff, columnsNames: columnsNames, columns: columns }), new PostalCodesModel({ geocodeStuff: geocodeStuff, columnsNames: columnsNames, columns: columns }), new IpAddressesModel({ geocodeStuff: geocodeStuff, columnsNames: columnsNames, columns: columns }), new StreetAddressesModel({ geocodeStuff: geocodeStuff, columns: columns, isGoogleMapsUser: this._isGoogleMapsUser(), userGeocoding: this._userGeocoding(), estimation: new cdb.admin.Geocodings.Estimation({ id: this.get('table').getUnquotedName() }) }) ]) ); window.s=this.get('options').last(); if (this.get('user').featureEnabled('georef_disabled')) { this._disableGeorefTabs(); } else { this._maybeDisabledStreetAddresses(); } }, _disableGeorefTabs: function() { _.each(this._georefTabs(), this._disableTab.bind(this, "You don't have this option available in this version")); }, _georefTabs: function() { // exclude 1st tab (LonLat), since it should not be affected by this feature flag return this.get('options').rest(); }, _maybeDisabledStreetAddresses: function() { // Credits are only used for users that use non-google geocoding (i.e. the default use-case) if (!this._isGoogleMapsUser()) { var userGeocoding = this._userGeocoding(); if (!userGeocoding.hasQuota()) { this._disableTab('Your geocoding quota is not defined, please contact us at support@cartodb.com', this._streetAddrTabModel()); } else if (userGeocoding.hasReachedMonthlyQuota()) { this._disableTab("You've reached the available street address credits for your account this month", this._streetAddrTabModel()); } } }, _userGeocoding: function() { return new UserGeocodingModel(this.get('user').get('geocoding')); }, _isGoogleMapsUser: function() { return this.get('user').featureEnabled('google_maps'); }, _streetAddrTabModel: function() { return this.get('options').find(function(m) { return m instanceof StreetAddressesModel; }); }, _disableTab: function(msg, tabModel) { tabModel.set('disabled', msg); } });
JavaScript
0.000002
@@ -5851,17 +5851,16 @@ if ( -! userGeoc @@ -5891,148 +5891,8 @@ -this._disableTab('Your geocoding quota is not defined, please contact us at support@cartodb.com', this._streetAddrTabModel());%0A %7D else if ( @@ -5925,32 +5925,34 @@ nthlyQuota()) %7B%0A + this._di @@ -6068,24 +6068,184 @@ abModel());%0A + %7D%0A %7D else %7B%0A this._disableTab('Your geocoding quota is not defined, please contact us at support@cartodb.com', this._streetAddrTabModel());%0A %7D%0A
728d0fcd3b2644ea0272fe1bdda1f9a8693c881c
Fix #7
src/card.js
src/card.js
(function (window, document, Card, angular, undefined) { 'use strict'; angular .module('gavruk.card', []) .controller('CardCtrl', function ($scope) {}) .directive('card', function ($compile) { return { restrict: 'A', scope: { cardContainer: '@', // required width: '@', placeholders: '=', options: '=', messages: '=', }, controller: 'CardCtrl', link: function (scope, element, attributes, cardCtrl) { var defaultPlaceholders = { number: '•••• •••• •••• ••••', name: 'Full Name', expiry: '••/••', cvc: '•••' }; var defaultMessages = { validDate: 'valid\nthru', monthYear: 'month/year', }; var defaultOptions = { debug: false, formatting: true }; var placeholders = angular.extend(defaultPlaceholders, scope.placeholders); var messages = angular.extend(defaultMessages, scope.messages); var options = angular.extend(defaultOptions, scope.options); var opts = { form: 'form[name=' + attributes.name + ']', // a selector or jQuery object for the container // where you want the card to appear container: scope.cardContainer, // *required* formSelectors: {}, width: scope.width || 350, // Strings for translation - optional messages: { validDate: messages.validDate, monthYear: messages.monthYear }, // Default placeholders for rendered fields - options placeholders: { number: placeholders.number, name: placeholders.name, expiry: placeholders.expiry, cvc: placeholders.cvc }, formatting: options.formatting, // optional - default true debug: options.debug // if true, will log helpful messages for setting up Card }; if (cardCtrl.numberInput && cardCtrl.numberInput.length > 0) { opts.formSelectors.numberInput = 'input[name="' + cardCtrl.numberInput[0].name + '"]'; } if (cardCtrl.expiryInput && cardCtrl.expiryInput.length > 0) { opts.formSelectors.expiryInput = 'input[name="' + cardCtrl.expiryInput[0].name + '"]'; } if (cardCtrl.cvcInput && cardCtrl.cvcInput.length > 0) { opts.formSelectors.cvcInput = 'input[name="' + cardCtrl.cvcInput[0].name + '"]'; } if (cardCtrl.nameInput && cardCtrl.nameInput.length > 0) { opts.formSelectors.nameInput = 'input[name="' + cardCtrl.nameInput[0].name + '"]'; } new Card(opts); } }; }) .directive('cardNumber', function ($compile) { return { restrict: 'A', scope: { ngModel: '=' }, require: [ '^card', 'ngModel' ], link: function (scope, element, attributes, ctrls) { var cardCtrl = ctrls[0]; cardCtrl.numberInput = element; scope.$watch('ngModel', function (newVal, oldVal) { if (!oldVal && !newVal) { return; } if (oldVal === newVal && !newVal) { return; } var evt = document.createEvent('HTMLEvents'); evt.initEvent('keyup', false, true); element[0].dispatchEvent(evt); }); } }; }) .directive('cardName', function ($compile) { return { restrict: 'A', scope: { ngModel: '=' }, require: [ '^card', 'ngModel' ], link: function (scope, element, attributes, ctrls) { var cardCtrl = ctrls[0]; cardCtrl.nameInput = element; scope.$watch('ngModel', function (newVal, oldVal) { if (!oldVal && !newVal) { return; } if (oldVal === newVal && !newVal) { return; } var evt = document.createEvent('HTMLEvents'); evt.initEvent('keyup', false, true); element[0].dispatchEvent(evt); }); } }; }) .directive('cardExpiry', function ($compile) { return { restrict: 'A', scope: { ngModel: '=' }, require: [ '^card', 'ngModel' ], link: function (scope, element, attributes, ctrls) { var cardCtrl = ctrls[0]; cardCtrl.expiryInput = element; scope.$watch('ngModel', function (newVal, oldVal) { if (!oldVal && !newVal) { return; } if (oldVal === newVal && !newVal) { return; } var evt = document.createEvent('HTMLEvents'); evt.initEvent('keyup', false, true); element[0].dispatchEvent(evt); }); } }; }) .directive('cardCvc', function ($compile) { return { restrict: 'A', scope: { ngModel: '=' }, require: [ '^card', 'ngModel' ], link: function (scope, element, attributes, ctrls) { var cardCtrl = ctrls[0]; cardCtrl.cvcInput = element; scope.$watch('ngModel', function (newVal, oldVal) { if (!oldVal && !newVal) { return; } if (oldVal === newVal && !newVal) { return; } var evt = document.createEvent('HTMLEvents'); evt.initEvent('keyup', false, true); element[0].dispatchEvent(evt); }); } }; }); })(window, window.document, window.Card, window.angular);
JavaScript
0.000001
@@ -1119,20 +1119,16 @@ form: ' -form %5Bname='
7ae6b81b173b1cab9194371232d155b3e6ffb15a
fix specs
lib/assets/test/spec/cartodb/common/dialogs/change_lock/change_lock_view.spec.js
lib/assets/test/spec/cartodb/common/dialogs/change_lock/change_lock_view.spec.js
var cdb = require('cartodb.js-v3'); var $ = require('jquery-cdb-v3'); var ViewModel = require('../../../../../../javascripts/cartodb/common/dialogs/change_lock/change_lock_view_model'); var ChangeLockDialog = require('../../../../../../javascripts/cartodb/common/dialogs/change_lock/change_lock_view'); var sharedTestsForASetOfItems = function(opts) { beforeEach(function() { this.selectedItems = [ new cdb.core.Model({ name: '1st', locked: opts.lockedInitially }), new cdb.core.Model({ name: '2nd', locked: opts.lockedInitially }) ]; this.viewModel = new ViewModel({ items: this.selectedItems, contentType: 'datasets' }); this.view = new ChangeLockDialog({ model: this.viewModel }); this.view.render(); }); it('should have no leaks', function() { expect(this.view).toHaveNoLeaks(); }); it('should render a title with "' + opts.lockOrUnlockStr + '" + count of items to delete', function() { expect(this.innerHTML()).toContain(opts.lockOrUnlockStr.toLowerCase() + ' 2 datasets'); }); it('should render the lock description', function() { expect(this.innerHTML()).toContain(opts.lockOrUnlockStr + 'ing'); }); it('should have a default template if none is given', function() { expect(this.view.options.template).toEqual(jasmine.any(Function)); }); describe('when "OK, ' + opts.lockOrUnlockStr + '" button is clicked', function() { beforeEach(function() { spyOn(this.view, 'close').and.callThrough(); this.selectedItems.forEach(function(model) { var dfd = $.Deferred(); spyOn(model, 'save').and.returnValue(dfd.promise()); }); this.view.$('.js-ok').click(); }); it('should render processing message', function() { expect(this.innerHTML()).toContain(opts.lockOrUnlockStr + 'ing datasets'); }); describe('when change finishes successfully', function() { beforeEach(function() { this.viewModel.set('state', 'ProcessItemsDone'); }); it('should close the dialog', function() { expect(this.view.close).toHaveBeenCalled(); }); }); describe('when changing lock state fails', function() { beforeEach(function() { this.viewModel.set('state', 'ProcessItemsFail'); }); it('should render error', function() { expect(this.view.close).not.toHaveBeenCalled(); }); }); }); }; describe('common/dialogs/change_lock/change_lock_view', function() { describe('given a set of unlocked items', function() { sharedTestsForASetOfItems({ lockedInitially: false, lockOrUnlockStr: 'Lock' }); it('should indicate that lock is a negative action in styles', function() { expect(this.innerHTML()).toContain('--negative'); expect(this.innerHTML()).not.toContain('--positive'); }); }); describe('given a set of locked items', function() { sharedTestsForASetOfItems({ lockedInitially: true, lockOrUnlockStr: 'Unlock' }); it('should indicate that unlock is a positive action in styles', function() { expect(this.innerHTML()).toContain('--positive'); expect(this.innerHTML()).not.toContain('--negative'); }); describe('when given the template for opening item on dashboard', function() { beforeEach(function() { this.view.clean(); // previous created view this.view = new ChangeLockDialog({ model: this.viewModel, isOwner: true, ownerName: "cartodb", template: cdb.templates.getTemplate('common/dialogs/change_lock/templates/unlock_to_editor') }); this.view.render(); }); it('should render fine', function() { expect(this.innerHTML()).toContain('is locked'); expect(this.innerHTML()).toContain('That means you need to unlock it'); }); }); describe('when given the template for opening item from other user on dashboard', function() { beforeEach(function() { this.view.clean(); // previous created view this.view = new ChangeLockDialog({ model: this.viewModel, isOwner: false, ownerName: "cartodb", template: cdb.templates.getTemplate('common/dialogs/change_lock/templates/unlock_to_editor') }); this.view.render(); }); it('should render fine', function() { expect(this.innerHTML()).toContain('was locked by cartodb'); expect(this.innerHTML()).toContain('That means you need to unlock it'); }); }); }); afterEach(function() { if (this.view) { this.view.clean(); } }); });
JavaScript
0.000001
@@ -2766,32 +2766,29 @@ oContain('-- -negative +alert ');%0A ex @@ -3197,24 +3197,21 @@ tain('-- -negative +alert ');%0A
a21a53609871db61875a69ea49c5712dc7aa8d85
Use compile-client API from command line
bin/jade.js
bin/jade.js
#!/usr/bin/env node /** * Module dependencies. */ var fs = require('fs') , program = require('commander') , path = require('path') , basename = path.basename , dirname = path.dirname , resolve = path.resolve , exists = fs.existsSync || path.existsSync , join = path.join , monocle = require('monocle')() , mkdirp = require('mkdirp') , jade = require('../'); // jade options var options = {}; // options program .version(require('../package.json').version) .usage('[options] [dir|file ...]') .option('-O, --obj <str>', 'javascript options object') .option('-o, --out <dir>', 'output the compiled html to <dir>') .option('-p, --path <path>', 'filename used to resolve includes') .option('-P, --pretty', 'compile pretty html output') .option('-c, --client', 'compile function for client-side runtime.js') .option('-D, --no-debug', 'compile without debugging (smaller functions)') .option('-w, --watch', 'watch files for changes and automatically re-render') program.on('--help', function(){ console.log(' Examples:'); console.log(''); console.log(' # translate jade the templates dir'); console.log(' $ jade templates'); console.log(''); console.log(' # create {foo,bar}.html'); console.log(' $ jade {foo,bar}.jade'); console.log(''); console.log(' # jade over stdio'); console.log(' $ jade < my.jade > my.html'); console.log(''); console.log(' # jade over stdio'); console.log(' $ echo "h1 Jade!" | jade'); console.log(''); console.log(' # foo, bar dirs rendering to /tmp'); console.log(' $ jade foo bar --out /tmp '); console.log(''); }); program.parse(process.argv); // options given, parse them if (program.obj) { if (exists(program.obj)) { options = JSON.parse(fs.readFileSync(program.obj)); } else { options = eval('(' + program.obj + ')'); } } // --filename if (program.path) options.filename = program.path; // --no-debug options.compileDebug = program.debug; // --client options.client = program.client; // --pretty options.pretty = program.pretty; // --watch options.watch = program.watch; // left-over args are file paths var files = program.args; // compile files if (files.length) { console.log(); files.forEach(renderFile); if (options.watch) { monocle.watchFiles({ files: files, listener: function(file) { renderFile(file.absolutePath); } }); } process.on('exit', function () { console.log(); }); // stdio } else { stdin(); } /** * Compile from stdin. */ function stdin() { var buf = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', function(chunk){ buf += chunk; }); process.stdin.on('end', function(){ var fn = jade.compile(buf, options); var output = options.client ? fn.toString() : fn(options); process.stdout.write(output); }).resume(); } /** * Process the given path, compiling the jade files found. * Always walk the subdirectories. */ function renderFile(path) { var re = /\.jade$/; fs.lstat(path, function(err, stat) { if (err) throw err; // Found jade file if (stat.isFile() && re.test(path)) { fs.readFile(path, 'utf8', function(err, str){ if (err) throw err; options.filename = path; var fn = jade.compile(str, options); var extname = options.client ? '.js' : '.html'; path = path.replace(re, extname); if (program.out) path = join(program.out, basename(path)); var dir = resolve(dirname(path)); mkdirp(dir, 0755, function(err){ if (err) throw err; try { var output = options.client ? fn.toString() : fn(options); fs.writeFile(path, output, function(err){ if (err) throw err; console.log(' \033[90mrendered \033[36m%s\033[0m', path); }); } catch (e) { if (options.watch) { console.error(e.stack || e.message || e); } else { throw e } } }); }); // Found directory } else if (stat.isDirectory()) { fs.readdir(path, function(err, files) { if (err) throw err; files.map(function(filename) { return path + '/' + filename; }).forEach(renderFile); }); } }); }
JavaScript
0.000001
@@ -2731,34 +2731,78 @@ tion()%7B%0A var -fn +output;%0A if (options.client) %7B%0A output = jade.compile( @@ -2800,16 +2800,22 @@ .compile +Client (buf, op @@ -2830,69 +2830,78 @@ -var output = options.client%0A ? fn.toString()%0A : +%7D else %7B%0A var fn = jade.compile(buf, options);%0A var output = fn( @@ -2906,24 +2906,30 @@ n(options);%0A + %7D%0A process. @@ -3370,32 +3370,84 @@ var fn = + options.client ? jade.compileClient(str, options) : jade.compile(st @@ -3796,52 +3796,13 @@ ient -%0A ? fn.toString()%0A + ? fn : f
ef17a7472b83f6c52034dcd69f0ffa537031e3f5
create if directive
src/core.js
src/core.js
"use strict"; (function(window) { function Moon(opts) { var _el = opts.el; var _data = opts.data; var _methods = opts.methods; var directives = {}; this.$el = document.getElementById(_el); this.dom = {type: this.$el.nodeName, children: [], node: this.$el}; // Change state when $data is changed Object.defineProperty(this, '$data', { get: function() { return _data; }, set: function(value) { _data = value; this.build(this.dom.children); } }); // Utility: Raw Attributes -> Key Value Pairs var extractAttrs = function(node) { var attrs = {}; if(!node.attributes) return attrs; var rawAttrs = node.attributes; for(var i = 0; i < rawAttrs.length; i++) { attrs[rawAttrs[i].name] = rawAttrs[i].value } return attrs; } // Utility: Compile a template and return html var compileTemplate = function(template, data) { var code = template, re = /{{([.]?\w+)}}/gi; code.replace(re, function(match, p) { code = code.replace(match, "` + data." + p + " + `"); }); var compile = new Function("data", "var out = `" + code + "`; return out"); return compile(data); } // Utility: Create Elements Recursively For all Children this.recursiveChildren = function(children) { var recursiveChildrenArr = []; for(var i = 0; i < children.length; i++) { var child = children[i]; recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child)); } return recursiveChildrenArr; } // Utility: Create Virtual DOM Instance this.createVirtualDOM = function(node) { var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node); this.dom = vdom; } // Build the DOM with $data this.build = function(children) { for(var i = 0; i < children.length; i++) { var el = children[i]; if(el.type === "#text") { el.node.textContent = compileTemplate(el.val, this.$data); } else { for(var prop in el.props) { var propVal = el.props[prop]; var directive = directives[prop]; if(directive) { directive(el.node, propVal); } el.node.setAttribute(prop, compileTemplate(propVal, this.$data)); } } this.build(el.children); } } // Create Virtual DOM Object from Params this.createElement = function(type, children, val, props, node) { return {type: type, children: children, val: val, props: props, node: node}; } // Set any value in $data this.set = function(key, val) { this.$data[key] = val; this.build(this.dom.children); } // Get any value in $data this.get = function(key) { return this.$data[key]; } // Make AJAX GET/POST requests this.ajax = function(method, url, params, cb) { var xmlHttp = new XMLHttpRequest(); method = method.toUpperCase(); if(typeof params === "function") { cb = params; } var urlParams = "?"; if(method === "POST") { http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); for(var param in params) { urlParams += param + "=" + params[param] + "&"; } } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) cb(JSON.parse(xmlHttp.responseText)); } xmlHttp.open(method, url, true); xmlHttp.send(method === "POST" ? urlParams : null); } // Call a method defined in _methods this.method = function(method) { _methods[method](); } // Directive Initialization this.directive = function(name, action) { directives["m-" + name] = action; this.build(this.dom.children); } // Default Directives // Initialize this.createVirtualDOM(this.$el); this.build(this.dom.children); } window.Moon = Moon; window.$ = function(el) { el = document.querySelectorAll(el); return el.length === 1 ? el[0] : el; } })(window);
JavaScript
0.002029
@@ -4546,16 +4546,86 @@ rectives +%0A directives%5B%22m-if%22%5D = function(el, val) %7B%0A %0A %7D %0A%0A
e02f96afb5d14e95bb96d152a7fe30d0f44a6099
Test whether that the AI places the piece in the most optimal location to prevent or win
spec/TTTSpec.js
spec/TTTSpec.js
describe("Create board", function() { it("has 3 rows and 3 columns", function() { var board = new Board(); var new_board = board.newBoard(); var matchBoard = [[1,2,3], [4,5,6], [7,8,9]] expect(new_board[0]).toMatch(matchBoard[0]); expect(new_board[1]).toMatch(matchBoard[1]); expect(new_board[2]).toMatch(matchBoard[2]); }); it("initializes current state", function() { var board = new Board(); expect(board.state).toEqual([]); }); }); describe("Render state", function() { it("after each turn", function() { var board = new Board(); board.state = [[1,2,3], [4,5,6], [7,8,9]] var matchBoard = [['o','x','o'], [4,5,6], [7,8,9]] expect(board.currentState([1,2,3])).toEqual(matchBoard); }); it("continus from previous", function() { countPlace = 0 var board = new Board(); board.state = [[1,2,3], [4,5,6], [7,8,9]] var matchBoard = [['o','x','o'], [4,'x',6], [7,8,9]] expect(board.currentState([1,2,3,5])).toEqual(matchBoard); }); }); describe("Play game", function() { it("decides who goes first", function() { var game = new PlayGame(); var play_game = game.firstMove(); var fp = '' if(counter % 2 == 0) { var fp = "Human"; } else { var fp = "Computer"; } expect(firstPlayer).toMatch(fp) }); it("player places piece", function() { var game = new PlayGame(); game.placePiece(1); expect(game.piecesPlayed).toEqual([1]); }); it('calls board to render current board state', function() { var game = new PlayGame(); counter = 2; game.placePiece(1); game.placePiece(1); game.placePiece(2); pieces = game.piecesPlayed expect(pieces).toEqual([1,2]); expect(counter).toEqual(4); }); it("takes turn playing pieces", function() { counter = 1; game = new PlayGame(); game.move() expect(counter).toEqual(2) }); }); describe('Game result', function() { it('determines if computer won',function() { var game_result = new GameResult(); var play_game = new PlayGame(); play_game.computerPieces = [1,4,7]; result = game_result.checkHands(play_game.computerPieces); expect(result).toEqual('Would you like to play again?'); }); it('determines if they tied', function() { var game_result = new GameResult(); var play_game = new PlayGame(); play_game.computerPieces = [1,7,5,6]; counter = 11; result = game_result.checkHands(play_game.computerPieces); expect(result).toEqual('Would you like to play again?'); }); }); describe('AI moves', function() { xit('places at the best spot', function() { }); });
JavaScript
0.000115
@@ -2749,32 +2749,785 @@ again?');%0A %7D);%0A +describe(%22AI places piece%22, function() %7B%0A it('prevents Player to win', function() %7B%0A var play_game = new PlayGame();%0A%0A play_game.playerPieces = %5B1,3%5D;%0A play_game.computerPieces = %5B5%5D;%0A%0A board.state%5B1%5D%5B1%5D = 'x';%0A board.state%5B0%5D%5B0%5D = 'o';%0A board.state%5B0%5D%5B2%5D = 'o';%0A play_game.move();%0A%0A expect(play_game.computerPieces).toEqual(%5B5,2%5D);%0A %7D);%0A it('players the most to win', function() %7B%0A var play_game = new PlayGame();%0A%0A play_game.playerPieces = %5B1,3,9%5D;%0A play_game.computerPieces = %5B5,2%5D;%0A%0A board.state%5B1%5D%5B1%5D = 'x';%0A board.state%5B0%5D%5B1%5D = 'x';%0A%0A board.state%5B0%5D%5B0%5D = 'o';%0A board.state%5B0%5D%5B2%5D = 'o';%0A board.state%5B2%5D%5B2%5D = 'o';%0A play_game.move();%0A%0A expect(play_game.computerPieces).toEqual(%5B8,5,2%5D);%0A %7D);%0A %7D);%0A%0Adescribe('A
65a423d26c25ee6915d0299ce5b08a242cd65559
Move comment
themes/custom/mgapcdev/scripts/build/main.min.js
themes/custom/mgapcdev/scripts/build/main.min.js
jQuery(document).ready(function ($) { // Taken from Medium article @(https://medium.com/@mariusc23/hide-header-on-scroll-down-show-on-scroll-up-67bbaae9a78c#.yd0v5h41r) // Hide Header on on scroll down var didScroll; var lastScrollTop = 0; var delta = 5; $nav = $('nav#block-mgapcdev-mainnavigation'); var navbarHeight = $nav.outerHeight(); // on scroll, let the interval function know the user has scrolled $(window).scroll(function (event) { didScroll = true; }); // run hasScrolled() and reset didScroll status setInterval(function () { if (didScroll) { hasScrolled(); didScroll = false; } }, 250); function hasScrolled() { var st = $(this).scrollTop(); if (Math.abs(lastScrollTop - st) <= delta) { return; } // If they scrolled down and are past the navbar, add class .nav-up. // This is necessary so you never see what is "behind" the navbar. if (st > lastScrollTop && st > navbarHeight) { // Scroll Down $nav.removeClass('nav-down').addClass('nav-up'); } else { // Scroll Up if (st + $(window).height() < $(document).height()) { $nav.removeClass('nav-up').addClass('nav-down'); } } lastScrollTop = st; } $('.nav-burger').click(function () { $('.navbar-nav').toggleClass('closed'); }); // Android emote -------------------------------------------------------------------------------- // Get id of random image function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } var id = getRandomInt(1, 42); // <-- needs to be changed on a regular basis, until better solution is found. $('.android-emote').html('<img onload="this.style.opacity=' + 1 + ';" src="/giffy/droid-' + id + '.gif" >').css('opacity', '1'); $('.android-emote img').load(function () { $('.android-emote').addClass('fade-background-svg'); }); var clientId = drupalSettings.mgapcdev.github.clientId; var clientSecret = drupalSettings.mgapcdev.github.clientSecret; // Initalize github widget @(https://github.com/caseyscarborough/github-activity) GitHubActivity.feed({ username: "MGApcDev", selector: "#github-widget", limit: 6, clientId: clientId, clientSecret: clientSecret, }); });
JavaScript
0
@@ -1916,16 +1916,103 @@ %7D);%0A %0A + %0A // Initalize github widget @(https://github.com/caseyscarborough/github-activity)%0A var cl @@ -2134,92 +2134,8 @@ %0A %0A - // Initalize github widget @(https://github.com/caseyscarborough/github-activity)%0A Gi
06aa8fb3a874998180c8090c0c0a5e51aa53bb8a
Remove debugger statement from plugin.
plugins/sample_and_hold_modulator.plugin.js
plugins/sample_and_hold_modulator.plugin.js
E2.plugins["sample_and_hold_modulator"] = function(core, node) { var self = this; this.desc = 'Emits the input value when \'sample\' is true and emits the last sampled value otherwise. Emits zero by default.'; this.input_slots = [ { name: 'sample', dt: core.datatypes.BOOL, desc: 'Sending true to this slot updated the output value to match the input value, false inhibits input sampling.', def: 'True' }, { name: 'value', dt: core.datatypes.FLOAT, desc: 'The input value.', def: 0 } ]; this.output_slots = [ { name: 'value', dt: core.datatypes.FLOAT, desc: 'The output value.', def: 0 } ]; this.state = { value: 0.0 }; this.reset = function() { self.has_updated = false; self.updated = true; self.last_state = true; }; this.update_input = function(slot, data) { if(slot.index === 0) self.sample = data; else self.buffer = data; }; this.update_state = function(delta_t) { if(self.sample) self.state.value = self.buffer; else if(self.has_updated) self.updated = false; if(!self.sample && self.last_state) { self.last_state = self.sample; self.has_updated = false; } }; this.update_output = function(slot) { self.has_updated = true; return self.state.value; }; this.state_changed = function(ui) { if(!ui) { debugger; self.state.value = 0.0; self.buffer = 0.0; self.sample = true; } }; };
JavaScript
0
@@ -1288,21 +1288,8 @@ %09%09%7B%0A -%09%09%09debugger;%0A %09%09%09s
9598f6484e9b05a3010c1648b20c94c745e4efa0
add another test case
test/Validation.test.js
test/Validation.test.js
var should = require("should"); var webpack = require("../lib/webpack"); var WebpackOptionsValidationError = require("../lib/WebpackOptionsValidationError"); describe("Validation", function() { var testCases = [{ name: "undefined configuration", config: undefined, message: [ " - configuration should be an object." ] }, { name: "null configuration", config: null, message: [ " - configuration should be an object." ] }, { name: "empty configuration", config: {}, message: [ " - configuration misses the property 'entry'.", " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " The entry point(s) of the compilation." ] }, { name: "empty entry string", config: { entry: "" }, message: [ " - configuration.entry should be one of these:", " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " The entry point(s) of the compilation.", " Details:", " * configuration.entry should be an object.", " * configuration.entry should not be empty.", " * configuration.entry should be an array:", " [non-empty string]" ] }, { name: "invalid instanceof", config: { entry: "a", module: { wrappedContextRegExp: 1337 } }, message: [ " - configuration.module.wrappedContextRegExp should be an instance of RegExp.", ] }, { name: "multiple errors", config: { entry: [/a/], output: { filename: /a/ } }, message: [ " - configuration.entry should be one of these:", " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " The entry point(s) of the compilation.", " Details:", " * configuration.entry should be an object.", " * configuration.entry should be a string.", " * configuration.entry[0] should be a string.", " - configuration.output.filename should be a string." ] }, { name: "multiple configurations", config: [{ entry: [/a/], }, { entry: "a", output: { filename: /a/ } }], message: [ " - configuration[0].entry should be one of these:", " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " The entry point(s) of the compilation.", " Details:", " * configuration[0].entry should be an object.", " * configuration[0].entry should be a string.", " * configuration[0].entry[0] should be a string.", " - configuration[1].output.filename should be a string." ] }, { name: "deep error", config: { entry: "a", module: { rules: [{ oneOf: [{ test: "a", paser: { amd: false } }] }] } }, message: [ " - configuration.module.rules[0].oneOf[0] has an unknown property 'paser'. These properties are valid:", " object { enforce?, exclude?, include?, issuer?, loader?, loaders?, oneOf?, options?, parser?, query?, resource?, resourceQuery?, rules?, test?, use? }" ] }, { name: "additional key on root", config: { entry: "a", postcss: function() {} }, message: [ " - configuration has an unknown property 'postcss'. These properties are valid:", " object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, " + "loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, " + "recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }", " For typos: please correct them.", " For loader options: webpack 2 no longer allows custom properties in configuration.", " Loaders should be updated to allow passing options via loader options in module.rules.", " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:", " plugins: [", " new webpack.LoaderOptionsPlugin({", " // test: /\\.xxx$/, // may apply this only for some modules", " options: {", " postcss: ...", " }", " })", " ]" ] }]; testCases.forEach(function(testCase) { it("should fail validation for " + testCase.name, function() { try { webpack(testCase.config); } catch(e) { if(!(e instanceof WebpackOptionsValidationError)) throw e; e.message.should.startWith("Invalid configuration object."); e.message.split("\n").slice(1).should.be.eql(testCase.message); return; } throw new Error("Validation didn't fail"); }) }); });
JavaScript
0.000089
@@ -4160,16 +4160,352 @@ %5D%22%0A%09%09%5D%0A +%09%7D, %7B%0A%09%09name: %22enum%22,%0A%09%09config: %7B%0A%09%09%09entry: %22a%22,%0A%09%09%09devtool: true%0A%09%09%7D,%0A%09%09message: %5B%0A%09%09%09%22 - configuration.devtool should be one of these:%22,%0A%09%09%09%22 string %7C false%22,%0A%09%09%09%22 A developer tool to enhance debugging.%22,%0A%09%09%09%22 Details:%22,%0A%09%09%09%22 * configuration.devtool should be a string.%22,%0A%09%09%09%22 * configuration.devtool should be false%22%0A%09%09%5D%0A %09%7D%5D;%0A%09te
1648244fe6d0b1e9c357db98ac9c25d2018b5db3
Use consistent style
src/data.js
src/data.js
import { isFunction, isArray, toStr, toFloat, toDate, toArr, sortByTime, sortByNumberSeries, isDate, isNumber } from "./helpers"; let formatSeriesData = function (data, keyType) { let r = [], j, keyFunc; if (keyType === "number") { keyFunc = toFloat; } else if (keyType === "datetime") { keyFunc = toDate; } else { keyFunc = toStr; } if (keyType === "bubble") { for (j = 0; j < data.length; j++) { r.push([toFloat(data[j][0]), toFloat(data[j][1]), toFloat(data[j][2])]); } } else { for (j = 0; j < data.length; j++) { r.push([keyFunc(data[j][0]), toFloat(data[j][1])]); } } if (keyType === "datetime") { r.sort(sortByTime); } else if (keyType === "number") { r.sort(sortByNumberSeries); } return r; }; function detectXType(series, noDatetime, options) { if (dataEmpty(series)) { if ((options.xmin || options.xmax) && (!options.xmin || isDate(options.xmin)) && (!options.xmax || isDate(options.xmax))) { return "datetime"; } else { return "number"; } } else if (detectXTypeWithFunction(series, isNumber)) { return "number"; } else if (!noDatetime && detectXTypeWithFunction(series, isDate)) { return "datetime"; } else { return "string"; } } function detectXTypeWithFunction(series, func) { let i, j, data; for (i = 0; i < series.length; i++) { data = toArr(series[i].data); for (j = 0; j < data.length; j++) { if (!func(data[j][0])) { return false; } } } return true; } // creates a shallow copy of each element of the array // elements are expected to be objects function copySeries(series) { let newSeries = [], i, j; for (i = 0; i < series.length; i++) { let copy = {}; for (j in series[i]) { if (series[i].hasOwnProperty(j)) { copy[j] = series[i][j]; } } newSeries.push(copy); } return newSeries; } function processSeries(chart, keyType, noDatetime) { let i; let opts = chart.options; let series = chart.rawData; // see if one series or multiple chart.singleSeriesFormat = (!isArray(series) || typeof series[0] !== "object" || isArray(series[0])); if (chart.singleSeriesFormat) { series = [{name: opts.label, data: series}]; } // convert to array // must come before dataEmpty check series = copySeries(series); for (i = 0; i < series.length; i++) { series[i].data = toArr(series[i].data); } chart.xtype = keyType ? keyType : (opts.discrete ? "string" : detectXType(series, noDatetime, opts)); // right format for (i = 0; i < series.length; i++) { series[i].data = formatSeriesData(series[i].data, chart.xtype); } return series; } function processSimple(chart) { let perfectData = toArr(chart.rawData), i; for (i = 0; i < perfectData.length; i++) { perfectData[i] = [toStr(perfectData[i][0]), toFloat(perfectData[i][1])]; } return perfectData; } function dataEmpty(data, chartType) { if (chartType === "PieChart" || chartType === "GeoChart" || chartType === "Timeline") { return data.length === 0; } else { for (let i = 0; i < data.length; i++) { if (data[i].data.length > 0) { return false; } } return true; } } export { dataEmpty, processSeries, processSimple };
JavaScript
0.000005
@@ -124,19 +124,24 @@ pers%22;%0A%0A -let +function formatS @@ -153,20 +153,8 @@ Data - = function (dat
63dbe4705d5b7c962b74f0e64156b0124b89739c
make the check for URL stricter (#30695)
site/docs/4.4/assets/js/src/search.js
site/docs/4.4/assets/js/src/search.js
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ (function () { 'use strict' if (!window.docsearch) { return } var inputElement = document.getElementById('search-input') var siteDocsVersion = inputElement.getAttribute('data-docs-version') function getOrigin() { var location = window.location var origin = location.origin if (!origin) { var port = location.port ? ':' + location.port : '' origin = location.protocol + '//' + location.hostname + port } return origin } window.docsearch({ apiKey: '5990ad008512000bba2cf951ccf0332f', indexName: 'bootstrap', inputSelector: '#search-input', algoliaOptions: { facetFilters: ['version:' + siteDocsVersion] }, transformData: function (hits) { return hits.map(function (hit) { var currentUrl = getOrigin() var liveUrl = 'https://getbootstrap.com' // When in production, return the result as is, // otherwise remove our url from it. // eslint-disable-next-line no-negated-condition hit.url = currentUrl.indexOf(liveUrl) !== -1 ? hit.url : hit.url.replace(liveUrl, '') // Prevent jumping to first header if (hit.anchor === 'content') { hit.url = hit.url.replace(/#content$/, '') hit.anchor = null } return hit }) }, // Set debug to `true` if you want to inspect the dropdown debug: false }) }())
JavaScript
0
@@ -971,16 +971,17 @@ trap.com +/ '%0A%0A @@ -987,17 +987,73 @@ -// When i +hit.url = currentUrl.lastIndexOf(liveUrl, 0) === 0%0A // O n pr @@ -1085,17 +1085,16 @@ lt as is -, %0A @@ -1098,174 +1098,168 @@ -// otherwise remove our url from it.%0A // eslint-disable-next-line no-negated-condition%0A hit.url = currentUrl.indexOf(liveUrl) !== -1%0A ? hit.url + ? hit.url%0A // On development or Netlify, replace %60hit.url%60 with a trailing slash,%0A // so that the result link is relative to the server root %0A @@ -1293,16 +1293,17 @@ veUrl, ' +/ ')%0A%0A
8a6d3b4c89d8b1a5257c6fa447af11500b898d5e
fix test adapter
lib/Adapters/TestAdapter.js
lib/Adapters/TestAdapter.js
var Q = require('q'); var _ = require('underscore'); var config = require('../../common/Configuration'); var BaseTestAdapter=require('./BaseAdapter.js').BaseTestAdapter; var StreamInfo=require('./BaseAdapter.js').StreamInfo; var util=require('util'); var m3u8Parser = require('./../manifest/promise-m3u8'); var networkClient = require('./../NetworkClientFactory').getNetworkClient(); var url=require('url'); var logger = require('../../common/logger').getLogger("TestAdapter"); const simulateStreams = config.get('simulateStreams'); const preserveOriginalHLS = config.get('preserveOriginalHLS'); const overrideOldRecordedHLS = config.get('overrideOldRecordedHLS'); const runDurationInMinutes = preserveOriginalHLS.runDurationInMinutes; var singletonInstance = Symbol(); var singletonEnforcer = Symbol(); class TestAdapter extends BaseTestAdapter { constructor(enforcer) { super(); if (enforcer !== singletonEnforcer) { throw "Cannot construct singleton"; } if (preserveOriginalHLS.enable) { this.setRunEndTimer(); } } static get instance() { if (!this[singletonInstance]) { this[singletonInstance] = new TestAdapter(singletonEnforcer); } return this[singletonInstance]; } } TestAdapter.prototype.setRunEndTimer = function() { var durationMillisec = 60000 * runDurationInMinutes; var that = this; setTimeout((function(duration) { return () => { logger.info('recording ended (duration: %s minutes). LiveController will exit gracefully.', duration/60000); that.gracefullyExit(0); } })(durationMillisec), durationMillisec); } function TestStreamInfo(entryId,flavors) { StreamInfo.call(this,entryId, _.keys(flavors).join(",")); this.flavors=flavors; } util.inherits(TestStreamInfo,StreamInfo); TestStreamInfo.prototype.getAllFlavors = function() { var _this=this; var flavorsObjArray=[]; _.each(this.flavors,function(flavor,key) { var streamUrl = flavor.url; if (simulateStreams.useNginx) { streamUrl = "http://localhost:2000/entry/" + _this.entryId + "/origin/" + flavor.url.slice(7); } flavorsObjArray.push( { name : key, resolution: flavor.streamItem.attributes.attributes.resolution, codecs: flavor.streamItem.attributes.attributes.codecs, bandwidth: flavor.streamItem.attributes.attributes.bandwidth, liveURL : streamUrl, entryId : _this.entryId }); }); return Q.resolve(flavorsObjArray); }; Number.prototype.pad = function(size) { var s = String(this); while (s.length < (size || 2)) {s = "0" + s;} return s; } TestAdapter.prototype.getLiveEntries=function() { var _this=this; if (this.cache) { return Q.resolve(this.cache); } return networkClient.read(simulateStreams.wowzaUrl) .then(function(content) { return m3u8Parser.parseM3U8(content.body, {'verbatim': true}).then(function (m3u8) { var result = []; let extension = overrideOldRecordedHLS === true || (!simulateStreams.firstIndex) ? 1: simulateStreams.firstIndex; let path = simulateStreams.path ? simulateStreams.path : simulateStreams.entryId; for (let i = 0; i < simulateStreams.count; i++) { var flavors={}; _.each(m3u8.items.StreamItem,function(streamItem,i) { var chunkListUrl = url.resolve(simulateStreams.wowzaUrl, streamItem.properties.uri); flavors[i+1]= { streamItem: streamItem, url: chunkListUrl } }); result.push({ "entryId": util.format('%s-%d',path, extension), "flavorParamsIds": _.keys(flavors).join(","), "serverType": 0, "playWindow": simulateStreams.playWindow, getStreamInfo: function () { return new TestStreamInfo(this.entryId, flavors); } }); } _this.cache = result; return Q.resolve(result); }); }); } module.exports = { TestAdapter : TestAdapter, instance : TestAdapter.instance };
JavaScript
0
@@ -3144,24 +3144,95 @@ esult = %5B%5D;%0A + for (let i = 0; i %3C simulateStreams.count; i++) %7B%0A%0A @@ -3361,24 +3361,28 @@ + let path = s @@ -3407,92 +3407,76 @@ h ? -simulateStreams.path : simulateStreams.entryId;%0A for (let i = 0; i %3C +util.format('%25s-%25d',simulateStreams.path, extension) : util.format( simu @@ -3483,37 +3483,37 @@ lateStreams. -count; i++) %7B +entryId,i+1); %0A%0A @@ -4004,44 +4004,12 @@ d%22: -util.format('%25s-%25d',path, extension) +path ,%0A
5e503a4c78d261de4326f89b14dca16467c19781
Remove stray newline
gulpfile.babel.js
gulpfile.babel.js
import babel from 'gulp-babel'; import concat from 'gulp-concat'; import cssnano from 'gulp-cssnano'; import del from 'del'; import eslint from 'gulp-eslint'; import fs from 'fs'; import gulp from 'gulp'; import gulpif from 'gulp-if'; import handlebars from 'gulp-compile-handlebars'; import nested from 'postcss-nested' import postcss from 'gulp-postcss'; import rename from 'gulp-rename'; import rev from 'gulp-rev'; import stylelint from 'stylelint'; import uglify from 'gulp-uglify'; import watch from 'gulp-watch'; import yargs from 'yargs'; const IS_PRODUCTION = !!(yargs.argv.prod); // true if --prod flag is used gulp.task('clean-css', () => { return del([ './assets/*.css' ]); }); gulp.task('clean-js', () => { return del([ './assets/*.js' ]); }); gulp.task('lint-js', () => { return gulp.src(['./src/js/**/*.js', '!./src/js/vendor/**/*.js']) .pipe(eslint()) .pipe(eslint.format()); }); gulp.task('scripts', ['clean-js', 'lint-js'], () => { return gulp.src('./src/js/**/*.js') .pipe(babel()) .pipe(concat('script.min.js')) .pipe(gulpif(IS_PRODUCTION, uglify())) // Only minify when in production .pipe(gulp.dest('./assets')); }); gulp.task('styles', ['clean-css'], () => { return gulp.src('./src/css/*.css') .pipe(postcss([ nested, stylelint, ])) .on('error', function (error) { console.log(error); }) .pipe(rename({ suffix: '.min', })) .pipe(gulpif(IS_PRODUCTION, cssnano())) // Only minify when in production .pipe(gulp.dest('./assets')); }); gulp.task('rev', ['scripts', 'styles'], () => { return gulp.src(['./assets/style.min.css', './assets/script.min.js']) .pipe(rev()) .pipe(gulp.dest('./assets')) .pipe(rev.manifest()) .pipe(gulp.dest('./assets')) }); gulp.task('index', ['rev'], () => { let manifest = JSON.parse(fs.readFileSync('./assets/rev-manifest.json', 'utf8')); return gulp.src('./src/index.hbs') .pipe(handlebars(manifest)) .pipe(rename({ extname: '.html', })) .pipe(gulp.dest('.')); }); gulp.task('watch', ['default'], () => { watch('./src/js/**/*.js', () => { gulp.start('scripts'); }); watch('./src/css/style.css', () => { gulp.start('styles'); }); }); gulp.task('default', ['scripts', 'styles', 'index']);
JavaScript
0.000008
@@ -2173,17 +2173,16 @@ %7D))%0A -%0A
cba5ba15380f389640540d3f79526a15c42b1e90
Remove static constants from Complex
lib/Complex.js
lib/Complex.js
import validateArgs from './utils/validateArgs.js'; import typecheck from './utils/typecheck.js'; export default class Complex { constructor(real, imaginary) { validateArgs(arguments, 1, 2, 'Must supply a real, and optionally an imaginary, argument to Complex()'); imaginary = imaginary || 0; this.real = real; this.imaginary = imaginary; } add(other) { validateArgs(arguments, 1, 1, 'Must supply 1 parameter to add()'); if (typecheck.isNumber(other)) { return new Complex(this.real + other, this.imaginary); } return new Complex(this.real + other.real, this.imaginary + other.imaginary); } multiply(other) { validateArgs(arguments, 1, 1, 'Must supply 1 parameter to multiply()'); if (typecheck.isNumber(other)) { return new Complex(this.real * other, this.imaginary * other); } return new Complex( this.real * other.real - this.imaginary * other.imaginary, this.real * other.imaginary + this.imaginary * other.real ); } conjugate() { return new Complex(this.real, -this.imaginary); } toString() { if (this.imaginary === 0) return `${this.real}`; let imaginaryString; if (this.imaginary === 1) { imaginaryString = 'i'; } else if (this.imaginary === -1) { imaginaryString = '-i'; } else { imaginaryString = `${this.imaginary}i`; } if (this.real === 0) return imaginaryString; const sign = (this.imaginary < 0) ? '' : '+'; return this.real + sign + imaginaryString; } inspect() { return this.toString(); } format(options) { let realValue = this.real; let imaginaryValue = this.imaginary; if (options && options.decimalPlaces != null) { const roundingMagnitude = Math.pow(10, options.decimalPlaces); realValue = Math.round(realValue * roundingMagnitude) / roundingMagnitude; imaginaryValue = Math.round(imaginaryValue * roundingMagnitude) / roundingMagnitude; } const objectToFormat = new Complex(realValue, imaginaryValue); return objectToFormat.toString(); } negate() { return new Complex(-this.real, -this.imaginary); } magnitude() { return Math.sqrt(this.real * this.real + this.imaginary * this.imaginary); } phase() { // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2 return Math.atan2(this.imaginary, this.real); } subtract(other) { validateArgs(arguments, 1, 1, 'Must supply 1 parameter to subtract()'); if (typecheck.isNumber(other)) { return new Complex(this.real - other, this.imaginary); } return new Complex(this.real - other.real, this.imaginary - other.imaginary); } eql(other) { if (!(other instanceof Complex)) return false; return this.real === other.real && this.imaginary === other.imaginary; } equal(other) { return this.eql(other); } equals(other) { return this.eql(other); } closeTo(other) { return Math.abs(this.real - other.real) < 0.0001 && Math.abs(this.imaginary - other.imaginary) < 0.0001; } /* jshint ignore:start */ /* WARNING: Static constants are not supported by Safari yet (version 14.0.3) */ static ONE = new Complex(1, 0); static ZERO = new Complex(0, 0); static SQRT2 = new Complex(Math.SQRT2, 0); static SQRT1_2 = new Complex(Math.SQRT1_2, 0); /* jshint ignore:end */ }
JavaScript
0.000006
@@ -3080,307 +3080,7 @@ %7D%0A%0A - /* jshint ignore:start */%0A /* WARNING: Static constants are not supported by Safari yet (version 14.0.3) */%0A static ONE = new Complex(1, 0);%0A static ZERO = new Complex(0, 0);%0A static SQRT2 = new Complex(Math.SQRT2, 0);%0A static SQRT1_2 = new Complex(Math.SQRT1_2, 0);%0A /* jshint ignore:end */%0A %0A%7D%0A
dff2e9a991ef939ba11d8a6f153d9201ae868da2
Update main.js
crud/WebContent/main.js
crud/WebContent/main.js
function showBatchWork(keyword){ window.clearInterval(inter); $("#main").load("remote/batch.jsp",{"tb":"room","keyword":keyword}); } function doBatchWork(frm){ window.clearInterval(inter); var data=$(frm).serialize(); $("#main").load("remote/batch.jsp#"+Math.random(),data); return false; } function viewroom(roomid){ window.clearInterval(inter); $("#main").load("view.jsp",{"tb":"room","id":roomid},reformatview); } function dbid(evt){ var data=$(evt.target).parent().parent().attr("id"); return parseInt(data); } function view(rowid){ var tbname=$("#tbname").val(); $("#main").load("view.jsp",{"tb":tbname,"id":rowid},reformatview); //window.open("view.jsp?tb="+tbname+"&id="+rowid); } function edit(rowid){ var tbname=$("#tbname").val(); $("#main").load("add.jsp",{"tb":tbname,"id":rowid},reformatform); } function del(rowid){ var ans=confirm('确定删除编号'+rowid); var tbname=$("#tbname").val(); if(ans){ $.post("del.jsp",{"tbname":tbname,"id":rowid},new function(){ window.setTimeout("mainLoad('"+tbname+"')",1000); }); } } function addButton(main){ //$("#main tr :last-child").css("background","#eeeeee"); $("#main tr").append("<td>"+ "<span class='glyphicon glyphicon-eye-open'></span>"+ "<span class='glyphicon glyphicon-edit'></span>" +"<span class='glyphicon glyphicon-trash' ></span></td>"); $(".glyphicon-eye-open").bind("click",function(evt){ view(dbid(evt)); }); $(".glyphicon-trash").bind("click",function(evt){ del(dbid(evt)); }); $(".glyphicon-edit").bind("click",function(evt){ edit(dbid(evt)); }); } function loadSelect(input){ var input_name=input.attr("name"); var default_value=input.val(); if(input[0].nodeName=="SPAN") //view use span for tag, text() for value default_value=input.text(); var tbname=input_name.substring(0,input_name.length-3); var td=input.parent(); td.load("select.jsp?tbname="+tbname+"&value="+default_value); } function reformatform(){ $("input[name$=_id]").each(function(){ loadSelect($(this)); }); $(".input_date").datepicker(); if(tableName!='config') $("textarea").ckeditor(); } function reformatview(){ $("span[name$=_id]").each(function(){ loadSelect($(this)); }); } function loadReport(){ window.clearInterval(inter); $("#main").load("jsp/report_select.jsp?"+Math.random()); } function mainLoad(tbname,pageNum,keyword){ tableName=tbname; if (typeof(pageNum)=='undefined') pageNum=thepage; if (typeof(keyword)=='undefined') keyword=searchKeyword; thepage=pageNum; searchKeyword=keyword; window.clearInterval(inter); $("#main").load("list.jsp",{"tb":tbname,"pageNum":pageNum,"keyword":keyword},function(text,status,http){ if(status=="success"){ addButton($("#main")); $("#tbname").after("<span id='addrow' class='glyphicon glyphicon-plus'></span>"); $("#addrow").click(function(){ $("#main").load("add.jsp",{tb:tbname},reformatform); }); } }); } function pageUp(tbname,pageNum){ mainLoad(tbname,pageNum-1,searchKeyword); } function pageDown(tbname,pageNum){ mainLoad(tbname,pageNum+1,searchKeyword); } function showReport(frm){ var data=$(frm).serialize(); $("#main").load("jsp/report_select.jsp?"+Math.random(),data); return false; } function submitAdd(tbname){ var data=$("#addForm").serialize(); $.post("add.jsp",data,new function(){ mainLoad(tbname,0,searchKeyword); }); } function submitTable(){ var data=$("#frmAddTable").serialize(); var tbname=$("#tb_name").val(); $.post("addTable.jsp",data,new function(){ window.setTimeout("mainLoad('"+tbname+"',0,'"+searchKeyword+"')",1000); }); } function addTable(){ $("#main").empty(); $("#main").append("<form method=post onSubmit='submitTable()' id='frmAddTable'><table id='tb_adding' class='table table-striped table-hover'></table></form>"); $("#tb_adding").append("<tr><td>表名<input type=text id=tb_name name=tb_name value='tb_'></td><td>中文<input type=text name=tb_title value='信息'></td></tr>"); $("#tb_adding").append("<tr><td>列名</td><td>类型</td><td>中文</td><td><a href=# onclick='addColumn();'><span class='glyphicon glyphicon-plus'></span></a></td></tr>"); $("#frmAddTable").append("<input type=button onclick='submitTable()' value='确定'><input type=reset value='重置'>"); addColumn(); } function addColumn(){ var row="<tr>"; row+="<td><input name=fd_name type=text></td>"; row+="<td><input name=fd_type type=text value='varchar(32)'></td>"; row+="<td><input name=fd_title type=text></td>"; row+="</tr>"; $("#tb_adding").append(row); } function search(keyword){ window.clearTimeout(stid); searchKeyword=keyword; stid=window.setTimeout("mainLoad(tableName,0,'"+keyword+"');",500); } var stid=null; var tableName="room"; var searchKeyword=""; var thepage=0;
JavaScript
0.000001
@@ -4943,16 +4943,34 @@ );%0D%0A%09%7D%0D%0A +%09var inter=null;%0D%0A %09var sti @@ -5041,8 +5041,10 @@ epage=0; +%0D%0A
a2fe1477aef24e5bac7cffdd49e94b6fc6947567
remove console.log on common.js
skeleton/public/javascripts/common.js
skeleton/public/javascripts/common.js
/* config cleidtor */ $.cleditor.defaultOptions.width = '858'; $(function () { var $main = $('#main'); // Show login form $('#loginButton').click(function() { $('#loginLink').hide(); $('#loginForm').fadeIn('fast', function() { setTimeout(function() { $('#username').focus(); }, 300); }); return false; }); // Show new post form $('#newpost').click(function() { $('#main').prepend(Renderer.post({ post: { id: '', title: '', body: '', tag: '', alias: '', createdAt: new Date(), user: user }, action: '/posts', method: 'POST', editable: ' editable', isFeedbacks: typeof isFeedbacks != 'undefined' ? true : false })); edit($('#main').find('.content:eq(0)')); $('#main').find('.content:eq(0) .submit .cancel').attr('disabled', true); return false; }); // Show new user form $('#newuser').click(function() { $('#main').prepend(Renderer.user({ user: { id: '', fullname: '', username: '', icon: '', intro: '', color: '', posts: 0, createdAt: new Date(), user: user }, action: '/users', method: 'POST', editable: ' editable' })); edit($('#main').find('.content:eq(0)')); $('#main').find('.content:eq(0) .submit .cancel').attr('disabled', true); return false; }); // Edit $('.content .action .edit').live('click', function() { edit($(this).parents('.content')); }); // Cancel $('.content .submit .cancel').live('click', function() { var $content = $(this).parents('.content'); $content.find('.editForm').hide(); $content.find('.editForm').get(0).reset(); $content.find('.show').show(); }); // Search by specified words $('#searchForm').submit(function() { var keyword = $('#keyword').val(); if (keyword) { location.href = '/search/' + encodeURIComponent(keyword); } return false; }); // Fixed users navigation when show scrollToTop var $scrollToTop2 = $('#scrollToTop2'); $scrollToTop2.click(scrollToTop); var $usersNav = $('#usersNav'); var usersNavHeight = $usersNav.height() + 48; $(window).scroll(function() { var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; var clientHeight = /*document.body.clientHeight ||*/ document.documentElement.clientHeight; if (scrollTop > usersNavHeight - clientHeight) { console.log('fix!'); if ($usersNav.css('position') != 'fixed') { $usersNav.css('position', 'fixed'); $usersNav.css('top', 'auto'); $usersNav.css('bottom', '0px'); } } else { if ($usersNav.css('position') == 'fixed') { $usersNav.css('position', 'absolute'); $usersNav.css('top', '60px'); $usersNav.css('bottom', 'auto'); } } }); // Show popover to scroll top below topbar $('.topbar').attr('title', '<a href="#" onclick="return scrollToTop();">Scroll<br />to Top</a>'); /* $('.topbar').popover({ //placement: 'below', placement: 'above', trigger: 'manual', html: true }); */ $('.topbar').dblclick(scrollToTop); /* var isPopover; $(window).scroll(function() { if ($('#main .content:eq(1)').length == 0) return false; var popoverBorder = $('#main .content:eq(1)').offset().top - 100; var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; if (scrollTop > popoverBorder && !isPopover) { //$('.topbar').popover('show'); //$scrollToTop2.fadeIn('fast'); //$scrollToTop2.show(); isPopover = true; } else if (scrollTop <= popoverBorder) { //$('.topbar').popover('hide'); //$scrollToTop2.fadeOut('fast'); //$scrollToTop2.hide(); isPopover = false; } }); */ // syntax highlight prettyPrint(); }) function tag(tags) { tags = tags.split(/,\s*/); var html = []; tags.forEach(function(tag) { html.push('<a href="/tag/' + encodeURIComponent(tag) + '">' + tag + '</a>'); }); return html.join(', '); } function onBottom(fn) { $(window).scroll(function() { var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; var scrollHeight = /*document.body.scrollHeight ||*/ document.documentElement.scrollHeight; var clientHeight = /*document.body.clientHeight ||*/ document.documentElement.clientHeight; var remain = scrollHeight - (clientHeight + scrollTop); //if (remain == 0) { if (remain <= 0) { fn(); } }); } // Scroll to top clicked topbar or clicked popover function scrollToTop(e) { $('html, body').animate({ scrollTop: 0 }, 'fast'); return false; } var Renderer = {};
JavaScript
0.000002
@@ -2519,36 +2519,8 @@ ) %7B%0A - console.log('fix!'); %0A
69bc5ecd65d3962b1a1c34b106bbe157483c4b64
Fix typo
lib/Context.js
lib/Context.js
'use strict'; const _ = require('lodash'); const uuid = require('node-uuid'); const arrify = require('arrify'); const defaults = require('defa'); const makeEmitter = require('./events/makeEmitter'); const makeReceiver = require('./events/makeReceiver'); const eventFactories = require('./events/eventFactories'); const eventFormatters = require('./events/eventReducers'); class Context { /** * Represents a context in which an action is executed * @param {Object} [options = {}] * @param {Object} [scope = {}] * @param {String} [parentId = null] Parent ID * @constructor */ constructor(options = {}, scope = {}, parentId = null) { this.created = new Date().getTime(); this.id = uuid.v1(); defaults(options, { cli: false, raw: false, cwd: process.cwd(), verbosity: 0, }, options => ({ format: options.cli && !options.raw })); this.scope = scope; this.options = options; this.parentId = parentId; const r = makeReceiver(this.constructor.eventReducers, this.options); this.receive = r.receiver; this.parser = r.parser; this.emit = makeEmitter(this.constructor.eventFactories, this, this.receive); this.emit.begin(); } /** * Creates a new context based on this one, extending the scope with the given object. * @param {Object} [scope = {}] */ createSubContext(scope = {}) { return this.constructor.createSubContext(this, scope, this.constructor); } /** * Invokes the given function with a new context based on this one, extending the scope with the given object. * @param {Object} scope * @param {Function} fn */ withScope(scope, fn) { return fn(this.createSubContext(scope)); } } /** * Creates a new context based on the given, extending the scope with the given object. * @param {Context} [context] * @param {Object} [scope = {}] * @param {Function} constructor */ Context.createSubContext = (context, scope = {}, constructor = null) => { if (constructor === null) constructor = this.constructor; return new constructor(_.extend({}, context.options), scope, context.id); }; Context.eventFactories = eventFactories; Context.eventReducers = [eventFormatters]; module.exports = Context; /** * Given the BaseContext, return a subclass that implements the given factories and reducers * @param BaseContext * @param {Object} factories * @param {Function|Function[]} reducers * @returns {SubContext} */ module.exports.extend = (BaseContext, factories, reducers) => { const SubContext = class SubContext extends BaseContext { }; SubContext.eventFactories = _.extend.apply(_, [{}, BaseContext.eventFactores].concat(arrify(factories))); SubContext.eventReducers = _.concat(BaseContext.eventReducers, reducers); return SubContext; };
JavaScript
0.999999
@@ -2862,16 +2862,17 @@ ntFactor +i es%5D.conc
fed3445f5cf11911473afc4113797a3861a276b1
make test depend on build (#18)
gulpfile.babel.js
gulpfile.babel.js
var _ = require('lodash'); var gulp = require('gulp'); var sourceFiles = ['index.js', 'metadatafetcher.js']; gulp.task('build', () => { var babel = require('gulp-babel'); gulp.src(sourceFiles) .pipe(babel()) .pipe(gulp.dest('dist')); }); gulp.task('test', () => { var commander = require('commander'); var os = require('os'); var mocha = require('gulp-spawn-mocha'); commander .option('--ci', 'Enable CI specific options') .option('--path <path>', 'Set base output path') .parse(process.argv); var path = commander.path || process.env.WORKSPACE || os.tmpdir(); var options = {}; if (commander.ci) { var testResultPath = path + '/test-results.xml'; options.reporter = 'mocha-junit-reporter'; options.reporterOptions = 'mochaFile=' + testResultPath; process.stdout.write('Test reports will be generated to: ' + testResultPath + '\n'); } options.timeout = '5000'; return gulp.src(['tests/**/*.js'], {read: false}) .pipe(mocha(options)); }); gulp.task('doc', (cb) => { var jsdoc = require('gulp-jsdoc3'); var jsdocConfig = require('./jsdoc.json'); gulp.src(_.union(['README.md'], sourceFiles), { read: false }) .pipe(jsdoc(jsdocConfig, cb)); }); gulp.task('watch', () => { var watch = require('gulp-watch'); watch(sourceFiles, () => { gulp.start('default'); }); }); gulp.task('default', ['build']);
JavaScript
0
@@ -275,16 +275,27 @@ ('test', + %5B'build'%5D, () =%3E %7B
fe7edfee6ca9ee84fc3d4fcbad1411be8a3c30a9
fix cutoff issue in cards without list
card.js
card.js
'use strict'; /** * card tag * * Syntax: * {% card [header] [title=title] [subtitle=] [img=src] [imgalt=alt] [col=12,sm-1,lg-3]%} * Alert string * {% endcard %} */ var marked = require('marked'); var renderer = new marked.Renderer(); /** * level 1-3: title * 4-*: subtitle (muted) */ renderer.heading = function(text, level) { // adjust level level += 2; if(level < 5) { return '<h' + level + ' class="card-title">' + text + '</h' + level + '>'; } return '<h' + level + ' class="card-subtitle mb-2 text-muted">' + text + '</h' + level + '>'; } renderer.list = function(body, ordered) { var type = ordered ? 'ol' : 'ul'; return '</div><' + type + ' class="list-group list-group-flush">\n' + body + '</' + type + '>\n<div class="card-body">'; } renderer.listitem = function(text) { return '<li class="list-group-item">' + text + '</li>'; } renderer.paragraph = function(text){ return '<p class="card-text">' + text + '</p>'; } renderer.br = function() { return ""; } function replaceAll(str, find, replace) { return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace); } module.exports = function(ctx) { return function cardTag(args, content) { var header, subtitle, title, img, imgAlt; var col; var i,j; for(i = 0; i < args.length; i++) { var idx = args[i].indexOf("="); if(idx == -1) { if(args[i] === "col") { col = "col"; } else header = args[i]; continue; } switch(args[i].substring(0, idx).toLowerCase()) { case "col": col = ""; var param = args[i].substring(idx+1).split(","); for(j = 0; j < param.length; j++) { col+=" col-" + param[j]; } if(param.length == 0) { col = "col"; } break; case "title": title = args[i].substring(idx+1); break; case "subtitle": subtitle = args[i].substring(idx+1); break; case "img": img = args[i].substring(idx+1); break; case "imgalt": imgAlt = args[i].substring(idx+1); break; default: header = args[i]; break; } } content = ctx.render.renderSync({text: content, engine: 'markdown'}, { renderer: renderer, breaks: true, smartLists: false }); // clean up some "bad" end-of card rendering if(content.lastIndexOf('<div class="card-body">')) content = content.substring(0, content.length - 34); else content += "</div>"; content = replaceAll(content, "</p><br>", "</p>"); var card = '<div class="card">' + (header?'<div class="card-header">' + header + '</div>':'') + (img?('<img class="card-img-top" src="' + img + '"'+(imgAlt?(' alt="'+imgAlt+'"'):'')+'/>'):'') + '<div class="card-body">'+ (title?'<h4 class="card-title">' + title + '</h4>':'') + (subtitle?'<h6 class="card-subtitle mb-2 text-mited">' + subtitle + '</h6>':'') + content + '</div>'; if(col) { return '<div class="' + col + '">' + card + '</div>'; } else return card; }; };
JavaScript
0
@@ -2266,16 +2266,23 @@ body%22%3E') + !== -1 )%0A%09%09cont
a76f18612a5ae767cf0bb81d846fd297db77927e
Debug noble from env variable DEBUG_NOBLE=true node server.
hardware/index.js
hardware/index.js
var EventEmitter = require('events').EventEmitter; var nobleEmitter = require('./noble-emitter'); // nobleEmitter.debug(); var peripheralUuid = process.env.UUID_PERIPHERAL || "dc76745c6637"; var serviceUuid = process.env.UUID_SERVICE || "2220"; var characteristicUuid = process.env.UUID_CHARACTERISTIC || "2221"; var hardware = module.exports = new EventEmitter(); var e = nobleEmitter.connect(peripheralUuid, serviceUuid, characteristicUuid); e.on('connected', function () { console.log('ble connected'); hardware.emit('connected'); }); e.on('data', function (data) { var value = data.readInt16LE(0); handleButton(value === 0 ? 'a' : 'b'); }); e.on('disconnected', function () { console.log('ble disconnected'); hardware.emit('disconnected'); }); function emitScore (side) { hardware.emit('score', { side: side }); } function emitUndo (side) { hardware.emit('undo', { side: side }); } var undoLimit = 2; var undoTimeout = 300; var timers = {}; var counters = {}; function handleButton (side) { if (counters[side] && counters[side] >= undoLimit) { if (timers[side]) { clearTimeout(timers[side]); timers[side] = null; } counters[side] = 0; emitUndo(side); } else { if (!counters[side]) { counters[side] = 0; } counters[side] += 1; if (!timers[side]) { timers[side] = setTimeout(function () { emitScore(side); timers[side] = null; counters[side] = 0; }, undoTimeout); } } }
JavaScript
0
@@ -96,10 +96,36 @@ ');%0A -// +if (process.env.DEBUG_NOBLE) nob
2138a51cbe13f79a5bd08286faf7fb710f18762b
Add "navigationAction" to NavigationView snippet
snippets/navigationview-properties.js
snippets/navigationview-properties.js
const {Action, CheckBox, NavigationView, Page, Picker, ScrollView, TextView, ui} = require('tabris'); // demonstrates various NavigationView properties const MARGIN = 16; const MARGIN_SMALL = 8; const LABEL_WIDTH = 144; const COLORS = [null, 'red', 'green', 'blue', 'rgba(0, 0, 0, 0.25)']; ui.drawer.enabled = true; let navigationView = new NavigationView({ left: 0, top: 0, right: 0, height: 144, drawerActionVisible: true }).appendTo(ui.contentView); let page = new Page({ title: 'NavigationView', background: '#eeeeee' }).appendTo(navigationView); new TextView({ centerX: 0, centerY: 0, text: 'Page content' }).appendTo(page); new Action({title: 'Search'}).appendTo(navigationView); new Action({ title: 'Share', image: { src: device.platform === 'iOS' ? 'resources/share-black-24dp@3x.png' : 'resources/share-white-24dp@3x.png', scale: 3 } }).appendTo(navigationView); let controls = new ScrollView({ left: 0, right: 0, top: 'prev()', bottom: 0, background: 'white', elevation: 12 }).appendTo(ui.contentView); createCheckBox('Show toolbar', ({value: checked}) => { navigationView.toolbarVisible = checked; topToolbarHeightTextView.text = navigationView.topToolbarHeight; bottomToolbarHeightTextView.text = navigationView.bottomToolbarHeight; }); createCheckBox('Show drawer action', ({value: checked}) => { navigationView.drawerActionVisible = checked; }); createColorPicker('Toolbar color', 'toolbarColor'); createColorPicker('Title text color', 'titleTextColor'); createColorPicker('Action color', 'actionColor'); if (device.platform === 'Android') { createColorPicker('Action text color', 'actionTextColor'); } let topToolbarHeightTextView = createTextView('Toolbar height top', navigationView.topToolbarHeight); let bottomToolbarHeightTextView = createTextView('Toolbar height bottom', navigationView.bottomToolbarHeight); navigationView.on({ topToolbarHeightChanged: ({value}) => topToolbarHeightTextView.text = value, bottomToolbarHeightChanged: ({value}) => bottomToolbarHeightTextView.text = value }); function createCheckBox(text, listener) { return new CheckBox({ left: MARGIN, top: ['prev()', MARGIN_SMALL], right: MARGIN, text: text, checked: true }).on('checkedChanged', listener) .appendTo(controls); } function createColorPicker(text, property) { let initialColor = navigationView.get(property); new TextView({ left: MARGIN, top: ['prev()', MARGIN], width: LABEL_WIDTH, text: text }).appendTo(controls); new Picker({ left: ['prev()', MARGIN], baseline: 'prev()', right: MARGIN, itemCount: COLORS.length, itemText: index => COLORS[index] || initialColor }).on({ select: ({index}) => navigationView.set(property, COLORS[index] || initialColor) }).appendTo(controls); } function createTextView(key, value) { new TextView({ left: MARGIN, top: ['prev()', MARGIN_SMALL], width: LABEL_WIDTH, text: key }).appendTo(controls); return new TextView({ left: ['prev()', MARGIN], baseline: 'prev()', right: 16, height: 48, text: value }).appendTo(controls); }
JavaScript
0.000002
@@ -1400,24 +1400,501 @@ ecked;%0A%7D);%0A%0A +createCheckBox('Custom navigation action', function(%7Bvalue: checked%7D) %7B%0A if (checked) %7B%0A navigationView.navigationAction = new Action(%7B%0A title: 'Settings',%0A image: %7B%0A src: device.platform === 'iOS' ? 'resources/settings-black-24dp@3x.png'%0A : 'resources/settings-white-24dp@3x.png',%0A scale: 3%0A %7D%0A %7D).on('select', () =%3E console.log('navigationAction selected'));%0A %7D else %7B%0A navigationView.navigationAction = null;%0A %7D%0A%7D, false);%0A%0A createColorP @@ -2584,16 +2584,32 @@ listener +, checked = true ) %7B%0A re @@ -2721,20 +2721,23 @@ hecked: -true +checked %0A %7D).on
d0a22020890ee8fe4327bc37a371a3f97b4fcd39
reset WECO alerts when first is encountered
snorkel/app/client/views/weco_view.js
snorkel/app/client/views/weco_view.js
"use strict"; var helpers = require("app/client/views/helpers"); var TimeView = require("app/client/views/time_view"); // runs WECO rules on our time series array and // flags potentials function check_weco(serie, time_bucket) { var start = serie[0].x; var expected = start; var missing_val = 0; var violations = []; var zones = {}; function check_point(zone, pt, ev, max_len, threshold) { if (!zones[zone]) { zones[zone] = { count: 0, arr: [], name: zone }; } if (ev(pt.y)) { zones[zone].count++; } if (threshold <= zones[zone].count) { violations.push({ value: pt.x, type: "zone_" + zone}); } zones[zone].arr.push(pt); while (zones[zone].arr.length > (max_len || 0)) { var old_pt = zones[zone].arr.pop(); if (ev(old_pt.y)) { zones[zone].count--; } } } function eval_a(val) { return Math.abs(val) >= 10; } function eval_b(val) { return Math.abs(val) >= 20; } function eval_c(val) { return Math.abs(val) >= 30; } function eval_d(val) { return Math.abs(val) >= 40; } for (var i = 0; i < serie.length; i++) { var pt = serie[i]; while (expected < pt.x) { expected += time_bucket * 1000; missing_val++; } if (missing_val > 5) { console.log("WARNING! MULTIPLE MISSING VALUES!"); violations.push({value: start, type: "missing" }); } missing_val = 0; start = expected; check_point('a', pt, eval_a, 10, 9); check_point('b', pt, eval_b, 5, 4); check_point('c', pt, eval_c, 3, 2); check_point('d', pt, eval_d, 1, 1); } return _.filter(violations, function(v) { return v.type === "missing" || v.type === "zone_c" || v.type === "zone_d"; }); } var WecoView = TimeView.extend({ prepare: function(data) { this.time_bucket = data.parsed.time_bucket; var ret = TimeView.prototype.prepare(data); _.each(ret, function(serie) { var avg = 0; var std = 0; var m2 = 0; var delta = 0; var n = 0; _.each(serie.data, function(pt) { n += 1; delta = pt.y - avg; avg += delta / n; m2 += delta*(pt.y - avg); }); std = Math.sqrt(m2 / (n-1)); var min, max = 0; _.each(serie.data, function(pt) { pt.y = (pt.y - avg) / std * 10; // check which zone this point falls in min = Math.min(pt.y, min); max = Math.max(pt.y, max); }); serie.data.sort(function(a, b) { return a.x - b.x; }); }); var self = this; var violations = []; _.each(ret, function(serie) { violations = violations.concat(check_weco(serie.data, self.time_bucket)); }); self.violations = violations; return ret; }, getChartOptions: function() { var self = this; var plot_lines = []; _.each([-30, -20, 0, 20, 30], function(p) { plot_lines.push({ value : p, label: { text: p / 10 }, width: 1, color: "#aaa", dashStyle: 'dash' }); }); console.log("VIOLATIONS", self.violations); var options = TimeView.prototype.getChartOptions(); var my_options = {}; my_options.yAxis = { min: -50, max: 50, labels: { enabled: false }, plotLines: plot_lines }; my_options.xAxis = { plotLines: _.map(this.violations, function(v) { return { value: v.value, width: 1, color: "#f00", label: { text: v.type } }; }) }; $.extend(true, options, my_options); return options; } }); SF.trigger("view:add", "weco", { include: helpers.STD_INPUTS .concat(helpers.inputs.TIME_BUCKET) .concat(helpers.inputs.TIME_FIELD), icon: "noun/line.svg" }, WecoView); module.exports = WecoView;
JavaScript
0
@@ -669,24 +669,53 @@ %22 + zone%7D);%0A + zones%5Bzone%5D.count = 0;%0A %7D%0A%0A z @@ -906,16 +906,73 @@ %0A %7D%0A%0A + zones%5Bzone%5D.count = Math.max(zones%5Bzone%5D.count, 0);%0A%0A %7D%0A%0A f
1d8adf224fc6329d09f128918d6c851c08a1465d
Remove describe.only
lib/Card/tests/Card-test.js
lib/Card/tests/Card-test.js
import React from 'react'; import { describe, beforeEach, it } from '@bigtest/mocha'; import { expect } from 'chai'; import { mountWithContext, mount } from '../../../tests/helpers'; import CardInteractor from './interactor'; import Card from '../Card'; const card = new CardInteractor(); const props = { headerStart: 'Header', headerEnd: 'End', body: 'Test Body', }; describe.only('Card', () => { describe('rendering', () => { beforeEach(async () => { await mountWithContext( <Card headerEnd={props.headerEnd} headerStart={props.headerStart} > {props.body} </Card> ); }); it('renders a header', () => { expect(card.isHeaderPresent).to.be.true; }); it('renders headerStart according to prop', () => { expect(card.headerStart).to.equal(props.headerStart); }); it('renders headerEnd according to prop', () => { expect(card.headerStart).to.equal(props.headerStart); }); it('renders a body', () => { expect(card.isBodyPresent).to.be.true; }); it('renders body according to children', () => { expect(card.body).to.equal(props.body); }); it('renders default style', () => { expect(card.rendersDefault).to.be.true; }); describe('when passed a cardStyle of lookupEmpty', () => { beforeEach(async () => { await mount( <Card cardStyle="lookupEmpty" headerStart="Card" > Test </Card> ); }); it('should have the lookupEmpty class', () => { expect(card.rendersLookupEmpty).to.be.true; }); }); describe('when passed a cardStyle of lookupPreview', () => { beforeEach(async () => { await mount( <Card cardStyle="lookupPreview" headerStart="Card" > Test </Card> ); }); it('should have the lookupPreview class', () => { expect(card.rendersLookupPreview).to.be.true; }); }); describe('when passed the bottomMargin0 prop', () => { beforeEach(async () => { await mount( <Card bottomMargin0 cardStyle="lookupPreview" headerStart="Card" > Test </Card> ); }); it('should have the bottomMargin0 class', () => { expect(card.rendersBottomMargin0).to.be.true; }); }); describe('when passed *Class props', () => { beforeEach(async () => { await mount( <Card cardStyle="lookupPreview" headerStart="Card" cardClass="test-card" headerClass="test-header" bodyClass="test-body" > Test </Card> ); }); it('should have the test-card class on the card', () => { expect(card.cardHasTestClass).to.be.true; }); it('should have the test-header class on the header', () => { expect(card.headerHasTestClass).to.be.true; }); it('should have the test-body class on the body', () => { expect(card.bodyHasTestClass).to.be.true; }); }); }); });
JavaScript
0.000001
@@ -384,13 +384,8 @@ ribe -.only ('Ca
f7ea031dac8dedddd9525c42a5c27b34c01f616a
Add ReactTransitionGroup to the build
grunt/config/jsx/jsx.js
grunt/config/jsx/jsx.js
'use strict'; var rootIDs = [ "React" ]; var debug = { rootIDs: rootIDs, configFile: "grunt/config/jsx/debug.json", sourceDir: "src", outputDir: "build/modules" }; var jasmine = { rootIDs: [ "all" ], configFile: debug.configFile, sourceDir: "vendor/jasmine", outputDir: "build/jasmine" }; var test = { rootIDs: rootIDs.concat([ "test/all.js", "**/__tests__/*.js" ]), configFile: "grunt/config/jsx/test.json", sourceDir: "src", outputDir: "build/modules" }; var release = { rootIDs: rootIDs, configFile: "grunt/config/jsx/release.json", sourceDir: "src", outputDir: "build/modules" }; module.exports = { debug: debug, jasmine: jasmine, test: test, release: release };
JavaScript
0
@@ -33,16 +33,42 @@ %22React%22 +,%0A %22ReactTransitionGroup%22 %0A%5D;%0A%0Avar
e9b16bcb75da4428cdec7990569aa45659b98c18
add support for empty activities
packages/node_modules/@ciscospark/react-container-read-receipts/src/selectors.js
packages/node_modules/@ciscospark/react-container-read-receipts/src/selectors.js
import {createSelector} from 'reselect'; import {orderBy} from 'lodash'; const getActivities = (state) => state.conversation.get('activities'); const getParticipants = (state) => state.conversation.get('participants'); const getUsers = (state) => state.users; const getTypingIndicators = (state) => state.indicators.get('typing'); const getSpark = (state, ownProps) => ownProps.sparkInstance || state.spark.get('spark'); const READ_RECEIPTS_SHOWN_LIMIT = 10; const getCurrentUser = createSelector( [getUsers], (users) => users.getIn(['byId', users.get('currentUserId')]) ); const getReadReceipts = createSelector( [getCurrentUser, getActivities, getParticipants, getTypingIndicators], (currentUser, activities, participants, typing) => { const activity = activities.last(); const readParticipants = participants .filter((participant) => participant.get('id') !== currentUser.id && participant.getIn(['roomProperties', 'lastSeenActivityUUID']) === activity.id) .toJS(); const mappedParticipants = readParticipants .map((participant) => { const participantId = participant.id; // Typing events don't give us user IDs, only emails. const isTyping = typing.has(participant.emailAddress); return { displayName: participant.displayName, isTyping, userId: participantId }; }); const sortedParticipants = orderBy(mappedParticipants, 'isTyping', 'desc'); const visibleUsers = sortedParticipants.slice(0, READ_RECEIPTS_SHOWN_LIMIT); const hiddenUsers = sortedParticipants.slice(READ_RECEIPTS_SHOWN_LIMIT); return { hiddenUsers, visibleUsers }; } ); const getReadReceiptsProps = createSelector( [getReadReceipts, getSpark], (readReceipts, sparkInstance) => ({ readReceipts, sparkInstance }) ); export default getReadReceiptsProps;
JavaScript
0.000001
@@ -853,32 +853,59 @@ pant) =%3E%0A + activity && currentUser && participant.get
839c5467645f7f498ad8d1f79df709d605563d8f
e2e testing
tests/e2e/data/data1.js
tests/e2e/data/data1.js
describe('Abe', function() { describe('data', function() { before(function(client, done) { done(); }); after(function(client, done) { client.end(function() { done(); }); }); afterEach(function(client, done) { done(); }); beforeEach(function(client, done) { done(); }); it('Create a autocomplete template post', function(client) { client .useXpath() .url('http://localhost:3003/abe/editor') .click('//*[@id="selectTemplate"]/option[2]') .waitForElementVisible("//div[@data-precontrib-templates='autocomplete']//input[@id='name']", 30000) .setValue("//div[@data-precontrib-templates='autocomplete']//input[@id='name']", 'autocomplete') .click("//button[@type='submit']") .pause(1000) .waitForElementVisible('//*[@id="abeForm"]', 2000) .assert.urlEquals("http://localhost:3003/abe/editor/autocomplete.html", "Clicked URL Matches with URL of the New Window"); }); it('Check input select fields', function(client) { client .useXpath() .url('http://localhost:3003/abe/editor/autocomplete.html') .click('//*[@id="colors.multiple"]/option[2]') .waitForElementVisible('//*[@id="colors"]/div/div/div/div[2]/div/div/div', 1000) .assert.containsText('//*[@id="colors"]/div/div/div/div[2]/div/div/div', 'rouge') .click('//*[@id="colors"]/div/div/div/div[2]/div/div/div/span') .assert.elementNotPresent('//*[@id="colors"]/div/div/div/div[2]/div/div/div') }); it('Check input autocomplete fields', function(client) { client .useXpath() .url('http://localhost:3003/abe/editor/autocomplete.html') .setValue('//*[@id="colors.colors_autocomplete"]', 'rouge') .waitForElementVisible('//*[@id="colors"]/div/div/div/div[3]/div/div[2]/div', 1000) .click('//*[@id="colors"]/div/div/div/div[3]/div/div[2]/div') .waitForElementVisible('//*[@id="colors"]/div/div/div/div[3]/div/div/div', 1000) .assert.containsText('//*[@id="colors"]/div/div/div/div[3]/div/div/div', 'rouge') .click('//*[@id="colors"]/div/div/div/div[3]/div/div/div/span') .assert.elementNotPresent('//*[@id="colors"]/div/div/div/div[3]/div/div/div') }); // it('Abe type data reference json', function(client) { // client // .useXpath() // .url('http://localhost:3003/abe/editor/autocomplete.html') // .waitForElementVisible('//body') // .pause(1000) // .click('//*[@id="abeForm"]/ul/li[2]/a') // .waitForElementVisible('//*[@id="reference"]/div') // .click('//*[@id="reference.single"]/option[2]') // .click('//*[@id="reference.multiple"]/option[3]') // .setValue('//*[@id="reference.autocomplete"]', 'rouge') // .waitForElementVisible('//*[@id="reference"]/div/div/div/div[3]/div[2]', 2000) // .click('//*[@id="reference"]/div/div/div/div[3]/div[2]/div[1]') // .waitForElementVisible('//*[@id="reference"]/div/div/div/div[3]/div/div', 2000); // }); // it('The autocomplete article is deleted in the manager', function(client) { client .useXpath() .url('http://localhost:3003/abe/editor') .waitForElementVisible('//body') .pause(1000) .click("//table[@id='navigation-list']/tbody/tr[1]/td[7]/div/a") .pause(1000) .acceptAlert() .url('http://localhost:3003/abe/editor') .pause(2000) .expect.element("//table[@id='navigation-list']/tbody/tr[1]/td[2]/a").text.to.not.contain('/articles/ftest.html'); }); }); });
JavaScript
0.99933
@@ -564,23 +564,23 @@ rElement -Visible +Present (%22//div%5B @@ -834,39 +834,39 @@ .waitForElement -Visible +Present ('//*%5B@id=%22abeFo @@ -1243,39 +1243,39 @@ .waitForElement -Visible +Present ('//*%5B@id=%22color
a1df669a085a6a843edf72186f7ca280aa80d653
revert doc compiler changes due to crlf issue
comp/csl.js
comp/csl.js
#!/usr/bin/env node let fs = require('fs') let sl = fs.readFileSync('./src/stdlib.js') + '' let exp = /\/\/ (.+)\r*\n+SL\["(.+)"\]/g fs.writeFileSync('./docs/commands.md', `# Commands\n**NOTE:** Anything with "index [number]" refers to the item at that specific index on the stack. "index 0" refers to the top of the stack, "index 1" refers to the second-from-top of stack, etc.\n\n${ sl.match(exp).join`\n`.replace(exp, '- <code>$2</code>: $1') }` )
JavaScript
0
@@ -111,11 +111,8 @@ .+)%5C -r*%5C n+SL
8266f9f8ff83e8d7d944630572fe5462aa50735a
Use isostring for dates
angular/src/scripts/controllers/search.js
angular/src/scripts/controllers/search.js
'use strict'; /** * @ngdoc function * @name angularApp.controller:SearchCtrl * @description * # SearchCtrl * Controller of the angularApp */ angular.module('angularApp') .controller('SearchCtrl', function ($scope, $rootScope) { var vm = $scope; window.searchCtrl = vm; vm.search = { fields: [], inputType: '', params: {}, queries: {} }; vm.$on('model:index-config-loaded', function (evt, modelName, configData) { vm.initSearch(configData.schema.properties); }); vm.initSearch = function (schemaProperties) { vm.search.fields = _.map(schemaProperties, function(value, key) { value.key = key; value.inputType = 'text'; if (value.type === 'string' && value.format === 'date') { value.inputType = 'date'; } else if (value.type === 'number' && value.format === 'uiselect') { value.inputType = 'select'; } return value; }); vm.search.dateRange = {startDate: moment(), endDate: moment()}; } // Reinitialize searchValue if inputType is date vm.$watch('search.searchField', function () { if (!vm.search.searchField) return; if (vm.search.searchField.inputType === 'date') { vm.search.searchValue = [new Date(), new Date()]; } }); vm.getQueryParams = function () { var queryParams = _.reduce(vm.search.params, function (memo, value, key) { var field = _.findWhere(vm.search.fields, {key: key}); if (!field) return memo; if (field.inputType === 'date') { memo[key + '.between'] = _.map(value, function (val) { return val.startDate.toString() + '|' + val.endDate.toString(); }).join('||'); } else if (field.inputType === 'select') { memo[key + '.in'] = value.join(); } else if (field.inputType === 'text') { memo[key + '.like'] = value.join('|'); } return memo; }, {}); if (vm.search.dateRange && vm.search.dateRange.startDate) { var startDate = vm.search.dateRange.startDate.toString(); var endDate = vm.search.dateRange.endDate.toString(); queryParams['created_at.between'] = startDate + '|' + endDate; } return queryParams; } vm.buildSearchQueries = function () { vm.search.queries = _.reduce(vm.search.params, function (memo, value, key) { var field = _.findWhere(vm.search.fields, {key: key}); if (!field) return memo; var queryVal = field.title + ': '; if (field.inputType === 'select') { var vals = _.map(value, function (val) { var item = _.findWhere(field.items, {value: val}) || {}; return item.label; }); queryVal = queryVal + _.uniq(vals); } else if (field.inputType === 'date') { var vals = _.map(value, function (val) { var startDate = new Date(val.startDate).toISOString().slice(0, 10); var endDate = new Date(val.endDate).toISOString().slice(0, 10); if (startDate === endDate) { return startDate; } else { return '(' + startDate + ',' + endDate + ')'; } }); queryVal = queryVal + _.uniq(vals); } else { queryVal = queryVal + _.uniq(value); } memo[key] = queryVal; return memo; }, {}); } vm.addSearchParam = function () { if (!vm.search.searchField || !vm.search.searchValue) { return; } var fieldKey = vm.search.searchField.key; // Check if field exists in params and initialize if not if (!vm.search.params[fieldKey]) { vm.search.params[fieldKey] = []; } vm.search.params[fieldKey].push(vm.search.searchValue); vm.search.searchValue = null; vm.buildSearchQueries(); } vm.clearSearchParams = function () { vm.search.params = {}; vm.search.queries = {}; } vm.removeSearchParam = function (key) { delete vm.search.params[key]; vm.buildSearchQueries(); } vm.doSearch = function () { $rootScope.$broadcast('model:do-search', vm.modelName, vm.getQueryParams()); } if (vm.schema && vm.schema.properties) { vm.initSearch(vm.schema.properties); } });
JavaScript
0.000001
@@ -1639,32 +1639,35 @@ val.startDate.to +ISO String() + '%7C' + @@ -1673,32 +1673,35 @@ + val.endDate.to +ISO String();%0A @@ -2077,24 +2077,27 @@ startDate.to +ISO String();%0A @@ -2148,16 +2148,19 @@ dDate.to +ISO String()
b76027fbff59c969c8ed633284224e2d39a06d00
Add a restart game option.
tic_tac_toe/static/tic_tac_toe/js/tic_tac_toe.js
tic_tac_toe/static/tic_tac_toe/js/tic_tac_toe.js
var Game = function(selector) { var game = { wrapper: $(selector), } game.board = game.wrapper.find('table tbody'); game.scoreboard = game.wrapper.find('.scoreboard'); game.squares = [0,0,0, 0,0,0, 0,0,0]; game.human_mark = 1 /* 1 is human (X), 2 is computer (O), 0 is free */ game.squareDisplayMapping = {0: '', 1: 'X', 2: 'O'} game.squaresDisplayValues = function() { return _.map(game.squares, function(i){ return game.squareDisplayMapping[i]; }); } game.play = function(index, marker) { game.squares[index] = marker; game.render(); game.submit(); } game.disable = function() { $('.scoreboard .computer').addClass('active') $('.scoreboard .human').removeClass('active') } game.enable = function () { $('.scoreboard .human').addClass('active') $('.scoreboard .computer').removeClass('active') } game.endGame = function(winner) { if (!winner) { message = "Tie Game!"; } else if (winner == 2) { message = "Computer Wins!"; } else { message = "You Win!"; } $result = game.scoreboard.find('.result'); game.scoreboard.find('.player').hide(); $result.html(message).show(); } game.submit = function() { game.disable(); var url = "/" + game.squares.join('') + "/"; $.get(url).done(function(data) { // handle data game.squares = data.squares; if (data.is_over) { game.endGame(data.winner); } else { game.enable(); } game.render(); }).fail(function() { alert("I'm sorry. There was an error. I guess you win."); }); } game.template = function(data) { if (!game._template) { game._template = Handlebars.compile($('#table-template').html()) } return game._template(data); } game.render = function() { game.board.html(game.template({squares: game.squaresDisplayValues()})); game.bindClicks(); } game.bindClicks = function() { game.board.find('td').each(function() { $(this).on('click', function() { $square = $(this); // do nothing if they click on already used squares used = $square.hasClass('O') || $square.hasClass('X'); computers_turn = game.scoreboard.find('.computer').hasClass('active'); if (used || computers_turn) { return; } var id = $square.data('id') game.play(id, game.human_mark); }); }); } game.render(); return game } $(function() { window.game = Game('.game'); });
JavaScript
0
@@ -1152,32 +1152,117 @@ in!%22;%0A %7D%0A + message += %22 %3Ca href='#' onclick='game.restart();'%3ETry Again?%3C/a%3E%22;%0A %0A $result @@ -1381,32 +1381,259 @@ .show();%0A %7D%0A%0A + game.restart = function() %7B%0A game.squares = %5B0,0,0, 0,0,0, 0,0,0%5D;%0A game.scoreboard.find('.result').hide();%0A game.scoreboard.find('.player').show();%0A game.render();%0A game.enable();%0A %7D%0A%0A game.submit
1aacb6c10e56c27a76a5924767019af4481408b8
Fix istanbul configuration.
rollup.config.substance.js
rollup.config.substance.js
const nodeResolve = require('rollup-plugin-node-resolve') const commonjs = require('rollup-plugin-commonjs') const DIST = 'dist/' module.exports = function (commandLineArgs) { let target = commandLineArgs.target || 'all' let output = [] if (target === 'browser' || target === 'all') { output.push({ file: DIST + 'substance.js', format: 'umd', name: 'substance', sourcemap: true, sourcemapRoot: __dirname, sourcemapPrefix: 'substance' }) } if (target === 'node' || target === 'all') { output.push({ file: DIST + 'substance.cjs.js', format: 'cjs', sourcemap: true, sourcemapRoot: __dirname, sourcemapPrefix: 'substance' }) } if (target === 'es' || target === 'all') { output.push({ file: DIST + 'substance.es.js', format: 'esm', sourcemap: true, sourcemapRoot: __dirname, sourcemapPrefix: 'substance' }) } if (target === 'coverage') { output.push({ file: 'tmp/substance.cov.js', format: 'umd', name: 'substance', sourcemap: true, sourcemapRoot: __dirname, sourcemapPrefix: 'substance' }) } const config = { input: 'index.es.js', output, plugins: [ nodeResolve(), commonjs({ include: [ 'node_modules/boolbase/**/*', 'node_modules/css-what/**/*', 'node_modules/domelementtype/**/*', 'node_modules/nth-check/**/*' ] }) ] } if (target === 'coverage') { config.istanbul = { include: [ 'dom/*.js', 'model/**/*.js', 'ui/*.js', 'util/*.js' ] } } return config }
JavaScript
0
@@ -102,16 +102,104 @@ monjs')%0A +const istanbul = require('substance-bundler/extensions/rollup/rollup-plugin-istanbul')%0A%0A const DI @@ -1620,24 +1620,44 @@ config. +plugins.push(%0A istanbul = %7B%0A @@ -1652,19 +1652,17 @@ nbul - = +( %7B%0A incl @@ -1653,24 +1653,26 @@ bul(%7B%0A + include: %5B%0A @@ -1662,32 +1662,34 @@ include: %5B%0A + 'dom/*.j @@ -1684,32 +1684,34 @@ 'dom/*.js',%0A + 'model/* @@ -1714,17 +1714,16 @@ el/* -*/* .js',%0A + @@ -1745,16 +1745,18 @@ + + 'util/*. @@ -1769,15 +1769,26 @@ + %5D%0A -%7D + %7D)%0A ) %0A %7D
6d4fc8e5541abdc7625ab9a332e4045c58b1f427
Add more detail to payload title when running inside a beforeEach hook
lib/adapter.js
lib/adapter.js
import path from 'path' import Mocha from 'mocha' import { runInFiberContext, wrapCommands, executeHooksWithArgs } from 'wdio-sync' const INTERFACES = { bdd: ['before', 'beforeEach', 'it', 'after', 'afterEach'], tdd: ['suiteSetup', 'setup', 'test', 'suiteTeardown', 'teardown'], qunit: ['before', 'beforeEach', 'test', 'after', 'afterEach'] } const EVENTS = { 'suite': 'suite:start', 'suite end': 'suite:end', 'test': 'test:start', 'test end': 'test:end', 'hook': 'hook:start', 'hook end': 'hook:end', 'pass': 'test:pass', 'fail': 'test:fail', 'pending': 'test:pending' } const NOOP = function () {} /** * Mocha runner */ class MochaAdapter { constructor (cid, config, specs, capabilities) { this.cid = cid this.capabilities = capabilities this.specs = specs this.config = Object.assign({ mochaOpts: {} }, config) this.runner = {} } async run () { if (typeof this.config.mochaOpts.ui !== 'string' || !INTERFACES[this.config.mochaOpts.ui]) { this.config.mochaOpts.ui = 'bdd' } const mocha = new Mocha(this.config.mochaOpts) mocha.loadFiles() mocha.reporter(NOOP) mocha.fullTrace() this.specs.forEach((spec) => mocha.addFile(spec)) this.requireExternalModules(this.config.mochaOpts.compilers, this.config.mochaOpts.requires) wrapCommands(global.browser, this.config.beforeCommand, this.config.afterCommand) mocha.suite.on('pre-require', () => INTERFACES[this.config.mochaOpts.ui].forEach((fnName) => { runInFiberContext( INTERFACES[this.config.mochaOpts.ui][2], this.config.beforeHook, this.config.afterHook, fnName ) })) await executeHooksWithArgs(this.config.before, [this.capabilities, this.specs]) let result = await new Promise((resolve, reject) => { this.runner = mocha.run(resolve) Object.keys(EVENTS).forEach((e) => this.runner.on(e, this.emit.bind(this, EVENTS[e]))) this.runner.suite.beforeAll(this.wrapHook('beforeSuite')) this.runner.suite.beforeEach(this.wrapHook('beforeTest')) this.runner.suite.afterEach(this.wrapHook('afterTest')) this.runner.suite.afterAll(this.wrapHook('afterSuite')) }) await executeHooksWithArgs(this.config.after, [result, this.capabilities, this.specs]) return result } /** * Hooks which are added as true Mocha hooks need to call done() to notify async */ wrapHook (hookName) { return (done) => executeHooksWithArgs( this.config[hookName], this.prepareMessage(hookName) ).then(() => done()) } prepareMessage (hookName) { const params = { type: hookName } switch (hookName) { case 'beforeSuite': case 'afterSuite': params.payload = this.runner.suite.suites[0] break case 'beforeTest': case 'afterTest': params.payload = this.runner.test break } params.err = this.runner.lastError delete this.runner.lastError return this.formatMessage(params) } formatMessage (params) { let message = { type: params.type } if (params.err) { message.err = { message: params.err.message, stack: params.err.stack, type: params.err.type || params.err.name, expected: params.err.expected, actual: params.err.actual } } if (params.payload) { message.title = params.payload.title message.parent = params.payload.parent ? params.payload.parent.title : null message.pending = params.payload.pending || false message.file = params.payload.file if (params.type.match(/Test/)) { message.passed = (params.payload.state === 'passed') message.duration = params.payload.duration } } return message } requireExternalModules (compilers = [], requires = []) { compilers.concat(requires).forEach((mod) => { mod = mod.split(':') mod = mod[mod.length - 1] if (mod[0] === '.') { mod = path.join(process.cwd(), mod) } this.load(mod) }) } emit (event, payload, err) { // For some reason, Mocha fires a second 'suite:end' event for the root suite, // with no matching 'suite:start', so this can be ignored. if (payload.root) return let message = this.formatMessage({type: event, payload, err}) message.cid = this.cid message.specs = this.specs message.event = event message.runner = {} message.runner[this.cid] = this.capabilities if (err) { this.runner.lastError = err } // When starting a new test, propagate the details to the test runner so that // commands, results, screenshots and hooks can be associated with this test if (event === 'test:start') { this.sendInternal(event, message) } this.send(message) } sendInternal (event, message) { process.emit(event, message) } /** * reset globals to rewire it out in tests */ send (...args) { return process.send.apply(process, args) } load (module) { try { require(module) } catch (e) { throw new Error(`Module ${module} can't get loaded. Are you sure you have installed it?\n` + `Note: if you've installed WebdriverIO globally you need to install ` + `these external modules globally too!`) } } } const _MochaAdapter = MochaAdapter const adapterFactory = {} adapterFactory.run = async function (cid, config, specs, capabilities) { const adapter = new _MochaAdapter(cid, config, specs, capabilities) return await adapter.run() } export default adapterFactory export { MochaAdapter, adapterFactory }
JavaScript
0
@@ -3764,24 +3764,411 @@ .payload) %7B%0A + // Add the current test title to the main title if it adds more value, e.g.%0A // when running inside a beforeEach hook%0A if (params.payload.ctx.currentTest && (params.payload.ctx.currentTest.title !== params.payload.title)) %7B%0A message.title = %60$%7Bparams.payload.title%7D for %22$%7Bparams.payload.ctx.currentTest.title%7D%22%60%0A %7D else %7B%0A @@ -4204,16 +4204,31 @@ d.title%0A + %7D%0A%0A
55c9edf6507bbd356391aee3a7b025cf83f6d5f2
remove spaces in hike_match_test.js
test/hike_match_test.js
test/hike_match_test.js
const chai = require('chai'); const expect = chai.expect; const chaiHttp = require('chai-http'); chai.use(chaiHttp); // const request = chai.request; // const Trail = require(__dirname + '/../models/trail'); const main = require(__dirname + '/test_server'); const origin = 'localhost:4000/api'; const ForecastIo = require('forecastio'); describe('Hike Match test', () => { it('should make a REST API call and return weather data ', (done) => { var forecastIo = new ForecastIo('ce1e9e7c47068378251586a90ecb14cd'); forecastIo.forecast('39.2530', '-118.4210').then((data) => { console.log(typeof data.daily.data[0].precipProbability); expect(data).to.not.eql(null); expect(data.daily.data[0].precipProbability).to.be.an('number'); done(); }); }); });
JavaScript
0.999985
@@ -114,188 +114,8 @@ p);%0A -// const request = chai.request;%0A// const Trail = require(__dirname + '/../models/trail');%0A%0Aconst main = require(__dirname + '/test_server');%0Aconst origin = 'localhost:4000/api';%0A%0A cons
6b1e125eba1bca5d35a58d74d014aad16432c6ea
Fix Typo in comment (#178)
lib/PeerConnectionServer.js
lib/PeerConnectionServer.js
const EventEmitter = require('events').EventEmitter; const LFSR = require('lfsr'); const uuidV4 = require('uuid/v4'); const SemanticSDP = require("semantic-sdp"); const SDPInfo = SemanticSDP.SDPInfo; const Setup = SemanticSDP.Setup; const MediaInfo = SemanticSDP.MediaInfo; const CandidateInfo = SemanticSDP.CandidateInfo; const DTLSInfo = SemanticSDP.DTLSInfo; const ICEInfo = SemanticSDP.ICEInfo; const StreamInfo = SemanticSDP.StreamInfo; const TrackInfo = SemanticSDP.TrackInfo; const SourceGroupInfo = SemanticSDP.SourceGroupInfo; /** * Manager of remoe peer connecion clients */ class PeerConnectionServer { /** * @ignore * @hideconstructor * private constructor */ constructor(endpoint,tm,capabilities) { //Store stuff this.count = 0; this.endpoint = endpoint; this.capabilities = capabilities; this.tm = tm; //The created transports this.transports = new Set(); //Create event emitter this.emitter = new EventEmitter(); //Create our namespace this.ns = tm.namespace("medooze::pc"); //LIsten for creation events this.ns.on("cmd",(cmd)=>{ //Get command nme switch(cmd.name) { case "create" : //Process the sdp var offer = SDPInfo.expand(cmd.data); //Create an DTLS ICE transport in that enpoint const transport = this.endpoint.createTransport(offer); //Set RTP remote properties transport.setRemoteProperties(offer); //Create local SDP info const answer = offer.answer({ dtls : transport.getLocalDTLSInfo(), ice : transport.getLocalICEInfo(), candidates : this.endpoint.getLocalCandidates(), capabilities : this.capabilities }); //Set RTP local properties transport.setLocalProperties(answer); //Get new transport id const id = this.count++; //Create namespace const pcns = this.tm.namespace("medooze::pc::"+id); //LIsten local events transport.on("outgoingtrack",(track,stream)=>{ //Send new event pcns.event("addedtrack",{ streamId: stream ? stream.getId() : "-", track : track.getTrackInfo() }); //Listen for close track track.once("stopped",()=>{ //Send ended event pcns.event("removedtrack",{ streamId: stream ? stream.getId() : "-", trackId : track.getId() }); }); }).on("outgoingstream",(stream)=>{ //For each stream for (const track of stream.getTracks()) { //Send new event pcns.event("addedtrack",{ streamId: stream ? stream.getId() : "-", track : track.getTrackInfo() }); //Listen for close track track.once("stopped",()=>{ //Send ended event pcns.event("removedtrack",{ streamId: stream ? stream.getId() : "-", trackId : track.getId() }); }); } }).on("stopped",()=>{ //Remove from transports this.transports.delete(transport); //Send enven pcns.event("stopped"); //Close ns pcns.close(); }); //Add to transport this.transports.add(transport); //Listen remote events pcns.on("event",(event)=>{ //Get event data const data = event.data; //Depending on the event switch(event.name) { case "addedtrack": { //Get events const streamId = data.streamId; const trackInfo = TrackInfo.expand(data.track); //Get stream let stream = transport.getIncomingStream(streamId); //If we already have it if (!stream) //Create empty one stream = transport.createIncomingStream(new StreamInfo(streamId)); //Create incoming track const track = stream.createTrack(trackInfo); break; } case "removedtrack": { //Get events const streamId = data.streamId; const trackId = data.trackId; //Get stream let stream = transport.getIncomingStream(streamId) //If we already have it if (!stream) return; //Get track const track = stream.getTrack(trackId); //If no track if (!track) return; //Stop track track.stop(); //Id stream has no more tracks if (!stream.getTracks().length) //Stop it too stream.stop(); break; } case "stop": //Stop transport this.transport.stop(); } }); //Done cmd.accept({ id : id, dtls : answer.getDTLS().plain(), ice : answer.getICE().plain(), candidates : this.endpoint.getLocalCandidates(), capabilities : this.capabilities }); /** * New managed transport has been created by a remote peer connection client * * @name transport * @memberof PeerConnectionServer * @kind event * @argument {Transport} transport An initialized transport */ this.emitter.emit("transport",transport); break; defautl: cmd.reject("Command not recognised"); break; } }); //Stop when endpoint stop this.endpoint.once("stopped",this.onendpointstopped=()=>this.stop()); } /** * Add event listener * @param {String} event - Event name * @param {function} listeener - Event listener * @returns {PeerConnectionServer} */ on() { //Delegate event listeners to event emitter this.emitter.on.apply(this.emitter, arguments); //Return object so it can be chained return this; } /** * Add event listener once * @param {String} event - Event name * @param {function} listener - Event listener * @returns {PeerConnectionServer} */ once() { //Delegate event listeners to event emitter this.emitter.once.apply(this.emitter, arguments); //Return object so it can be chained return this; } /** * Remove event listener * @param {String} event - Event name * @param {function} listener - Event listener * @returns {PeerConnectionServer} */ off() { //Delegate event listeners to event emitter this.emitter.removeListener.apply(this.emitter, arguments); //Return object so it can be chained return this; } /** * Stop the peerconnection server, will not stop the transport created by it */ stop() { //Chheck not stopped alrady if (!this.endpoint) //Do nothing return; //Don't listen for stopped event this.endpoint.off("stopped",this.onendpointstopped); //For all transports for (const transport of this.transports) //Stop them transport.stop(); //Close ns this.ns.close(); /** * PeerConnectionServer stopped event * * @name stopped * @memberof PeerConnectionServer * @kind event * @argument {PeerConnectionServer} peerConnectionServer */ this.emitter.emit("stopped",this); //Null this.transports = null; this.emitter = null; this.ns = null; this.endpoint = null; } } module.exports = PeerConnectionServer;
JavaScript
0
@@ -563,16 +563,17 @@ of remo +t e peer c
fb1ae5afa447f106c23336709e413d81c64ccfb6
remove dead code
lib/adduser.js
lib/adduser.js
module.exports = adduser var crypto = require('crypto') function sha (s) { return crypto.createHash("sha1").update(s).digest("hex") } function adduser (username, password, email, cb) { password = ("" + (password || "")).trim() if (!password) return cb(new Error("No password supplied.")) email = ("" + (email || "")).trim() if (!email) return cb(new Error("No email address supplied.")) if (!email.match(/^[^@]+@[^\.]+\.[^\.]+/)) { return cb(new Error("Please use a real email address.")) } var salt = crypto.randomBytes(30).toString('hex') , userobj = { name : username , password : password , email : email , _id : 'org.couchdb.user:'+username , type : "user" , roles : [] , date: new Date().toISOString() } // pluck off any other username/password/token. it needs to be the // same as the user we're becoming now. replace them on error. var pre = { username: this.conf.get('username') , password: this.conf.get('_password') , auth: this.conf.get('_auth') , token: this.conf.get('_token') } this.conf.del('_token') this.conf.del('username') this.conf.del('_auth') this.conf.del('_password') if (this.couchLogin) { this.couchLogin.token = null } cb = done.call(this, cb, pre) var logObj = Object.keys(userobj).map(function (k) { if (k === 'password') return [k, 'XXXXX'] return [k, userobj[k]] }).reduce(function (s, kv) { s[kv[0]] = kv[1] return s }, {}) this.log.verbose("adduser", "before first PUT", logObj) this.request('PUT' , '/-/user/org.couchdb.user:'+encodeURIComponent(username) , userobj , function (error, data, json, response) { // if it worked, then we just created a new user, and all is well. // but if we're updating a current record, then it'll 409 first if (error && !this.conf.get('_auth')) { // must be trying to re-auth on a new machine. // use this info as auth var b = new Buffer(username + ":" + password) this.conf.set('_auth', b.toString("base64")) this.conf.set('username', username) this.conf.set('_password', password) } if (!error || !response || response.statusCode !== 409) { return cb(error, data, json, response) } this.log.verbose("adduser", "update existing user") return this.request('GET' , '/-/user/org.couchdb.user:'+encodeURIComponent(username) + '?write=true' , function (er, data, json, response) { if (er || data.error) { return cb(er, data, json, response) } Object.keys(data).forEach(function (k) { if (!userobj[k] || k === 'roles') { userobj[k] = data[k] } }) this.log.verbose("adduser", "userobj", logObj) this.request('PUT' , '/-/user/org.couchdb.user:'+encodeURIComponent(username) + "/-rev/" + userobj._rev , userobj , cb ) }.bind(this)) }.bind(this)) } function done (cb, pre) { return function (error, data, json, response) { if (!error && (!response || response.statusCode === 201)) { return cb(error, data, json, response) } // there was some kind of error, re-instate previous auth/token/etc. this.conf.set('_token', pre.token) if (this.couchLogin) { this.couchLogin.token = pre.token if (this.couchLogin.tokenSet) { this.couchLogin.tokenSet(pre.token) } } this.conf.set('username', pre.username) this.conf.set('_password', pre.password) this.conf.set('_auth', pre.auth) this.log.verbose("adduser", "back", [error, data, json]) if (!error) { error = new Error( (response && response.statusCode || "") + " "+ "Could not create user\n"+JSON.stringify(data)) } if (response && (response.statusCode === 401 || response.statusCode === 403)) { this.log.warn("adduser", "Incorrect username or password\n" +"You can reset your account by visiting:\n" +"\n" +" https://npmjs.org/forgot\n") } return cb(error) }.bind(this) }
JavaScript
0.999454
@@ -23,121 +23,8 @@ er%0A%0A -var crypto = require('crypto')%0A%0Afunction sha (s) %7B%0A return crypto.createHash(%22sha1%22).update(s).digest(%22hex%22)%0A%7D%0A%0A func @@ -404,60 +404,8 @@ var - salt = crypto.randomBytes(30).toString('hex')%0A , use
1612d26b17584769d26dfd094b8846c451810f69
Add JS test that shows an embarrassing new insight: every function automatically has a fresh prototype object
test/js/FunctionTest.js
test/js/FunctionTest.js
/* Copyright 2015 - 2017 by Jan Dockx 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. */ (function(factory) { "use strict"; var dependencies = ["../_util/describe", "../_util/it", "../_util/expect"]; if (typeof define === "function" && define.amd) { define(dependencies, factory); } else if (typeof exports === "object") { module.exports = factory.apply(undefined, dependencies.map(function(d) {return require(d);})); } }(function(describe, it, expect) { "use strict"; // describe("js", function() { describe("js/Function", function() { describe("#bind()", function() { it("keeps a call of a bound function with another this bound to the bound this", function() { function testF() {return this.property;} // jshint ignore:line var boundThisPropertyValue = "bound this property value"; var boundThis = { property: boundThisPropertyValue }; //noinspection JSUnresolvedFunction var boundF = testF.bind(boundThis); //noinspection JSUnresolvedVariable expect(boundF()).to.equal(boundThisPropertyValue); var otherThisPropertyValue = "other this property value"; var otherThis = { property: otherThisPropertyValue }; //noinspection JSUnresolvedFunction var otherThisResult = boundF.call(otherThis); //noinspection JSUnresolvedVariable expect(otherThisResult).to.equal(boundThisPropertyValue); }); }); }); // }); }));
JavaScript
0.00005
@@ -2002,24 +2002,1688 @@ ;%0A %7D);%0A + describe(%22#prototype%22, function() %7B%0A %5B%0A function simpleF() %7Breturn %22This is a very simple function.%22;%7D,%0A class SimpleClass %7B%7D%0A %5D.forEach(function(f) %7B%0A it(%22exists on function %22 + f, function() %7B%0A function otherSimpleF() %7Breturn %22This is another very simple function.%22;%7D%0A%0A expect(f).to.haveOwnProperty(%22prototype%22);%0A expect(f).to.have.property(%22prototype%22).that.is.an(%22object%22);%0A expect(f).to.have.property(%22prototype%22).instanceOf(Object);%0A //noinspection JSPotentiallyInvalidConstructorUsage%0A expect(f.prototype).to.satisfy(%0A function(simpleFProto) %7Breturn Object.getPrototypeOf(simpleFProto) === Object.prototype;%7D%0A );%0A //noinspection JSPotentiallyInvalidConstructorUsage%0A expect(f).to.have.property(%22prototype%22).that.not.equals(otherSimpleF.prototype);%0A //noinspection JSPotentiallyInvalidConstructorUsage%0A console.log(JSON.stringify(f.prototype));%0A %7D);%0A %7D);%0A %7D);%0A describe(%22new%22, function() %7B%0A %5B%0A function simpleF() %7Breturn %22This is a very simple function.%22;%7D,%0A class SimpleClass %7B%7D%0A %5D.forEach(function(f) %7B%0A it(%22can be used as a constructor %22 + f, function() %7B%0A var result = new f();%0A expect(result).to.be.an(%22object%22);%0A expect(result).to.be.instanceOf(f);%0A expect(Object.getPrototypeOf(result)).to.equal(f.prototype);%0A //noinspection JSPotentiallyInvalidConstructorUsage%0A console.log(JSON.stringify(result));%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A //
61925383887c57328d4c1c1247f4d983784c6301
Fix require
test/js/scripts/game.js
test/js/scripts/game.js
require("./helper.js") const TextMessage = require('hubot/src/message').TextMessage describe('game.js', () => { "use strict" let robot = {} let user = [ {"id": 1, "name": "hoge"}, {"id": 2, "name": "fuga"} ] let adapter = {} shared_context.robot_is_running((ret) => { robot = ret.robot adapter = ret.adapter }); beforeEach(() => { require('../../src/scripts/game.js')(robot) }); })
JavaScript
0.000001
@@ -3,16 +3,17 @@ quire(%22. +. /helper.
f94ecc64d30ab51ffca9542d357ab9ec98a6a8d6
Fix jslint errors in lib/command.js
lib/command.js
lib/command.js
module.exports = function command(request) { return { exec: function exec(command, dir, cb) { if (typeof dir === "function") { cb = dir; dir = ""; } request.post({ uri: "/api/command", json: { command: command, dir: dir } }, function(err, response, body) { if (err) return cb(err); cb(null, body, response); }); } } };
JavaScript
0.000076
@@ -1,8 +1,23 @@ +%22use strict%22;%0A%0A module.e @@ -422,16 +422,29 @@ function + execCallback (err, re @@ -488,23 +488,64 @@ rr) -return cb(err); +%7B%0A return cb(err);%0A %7D%0A %0A @@ -609,17 +609,18 @@ %7D%0A - %7D +; %0A%7D;%0A
b2a66b292b98b9521d0c4a75b4913f4895d73c46
Add PayIns CardWeb tests
test/services/PayIns.js
test/services/PayIns.js
var _ = require('underscore'); var path = require('path'); var expect = require('chai').expect; var helpers = require('../helpers'); describe('PayIns', function() { var john = helpers.data.UserNatural; john.PersonType = 'NATURAL'; var wallet, payIn; before(function(done){ api.Users.create(john, function(){ helpers.getNewPayInCardWeb(api, john, function(data, response){ payIn = data; done(); }); }); }); it('should create the payin', function(){ expect(payIn.Id).not.to.be.undefined; expect(payIn.PaymentType).to.equal('CARD'); }) });
JavaScript
0
@@ -245,16 +245,8 @@ var - wallet, pay @@ -312,32 +312,141 @@ hn, function()%7B%0A + done();%0A %7D);%0A %7D);%0A%0A describe('Card Web', function()%7B%0A before(function(done)%7B%0A help @@ -583,33 +583,81 @@ %7D);%0A +%0A -%7D);%0A%0A + describe('Create Card Web', function()%7B%0A it('shou @@ -674,12 +674,12 @@ the -payi +PayI n', @@ -690,32 +690,40 @@ tion()%7B%0A + expect(payIn.Id) @@ -744,32 +744,40 @@ efined;%0A + expect(payIn.Pay @@ -808,14 +808,892 @@ ');%0A -%7D) + expect(payIn.ExecutionType).to.equal('WEB');%0A %7D);%0A %7D);%0A%0A describe('Get Card Web', function()%7B%0A var getPayIn;%0A before(function(done)%7B%0A api.PayIns.get(payIn.Id, function(data, response)%7B%0A getPayIn = data;%0A done()%0A %7D);%0A %7D);%0A%0A it('should get the PayIn', function()%7B%0A expect(getPayIn.Id).not.to.be.undefined;%0A expect(getPayIn.PaymentType).to.equal('CARD');%0A expect(getPayIn.ExecutionType).to.equal('WEB');%0A expect(getPayIn.Status).to.equal('CREATED');%0A expect(getPayIn.ExecutionDate).to.be.null;%0A expect(getPayIn.RedirectURL).not.to.be.undefined;%0A expect(getPayIn.ReturnURL).not.to.be.undefined;%0A %7D);%0A %7D);%0A %7D); %0A%7D);
b053631ae9ac913e981f2ccc76f2e9669b47c9e2
make sure url and parameters are Uri and QueryString objects
src/http.js
src/http.js
/** * Wrapper for XMLHttpRequest * * @param {String} url * @param {String} method * @param {Object} parameters */ HttpRequest = function (url, method, parameters) { var xhr, httprequest = this, user_agent = 'jsOAuth-HttpRequest/0.1 (+http://www.lemonstudio.co.uk/jsOAuth)', async = true, user = UNDEFINED, password = UNDEFINED; xhr = new XMLHttpRequest(); url = (url != UNDEFINED) ? url : ''; method = (method != UNDEFINED) ? method : HttpRequest.METHOD_GET; httprequest.parameters = new Collection(parameters); /** * set a custom user agent string * * @param {String} string */ httprequest.setUserAgent = function (string) { user_agent = string; }; /** * get the current user agent string */ httprequest.getUserAgent = function () { return user_agent; }; /** * Wrapper for XMLHttpRequest::setRequestHeader * * @param {String} header * @param {String} value */ httprequest.setRequestHeader = function (header, value) { xhr.setRequestHeader(header, value); }; httprequest.setBasicAuthCredentials = function (user, password) { user = user; password = password; }; /** * Open a connection and send the data */ httprequest.send = function () { var data = null, query = this.parameters.toString(); // we only open now so we have greater control over the connection if (method == HttpRequest.METHOD_POST) { data = query; } else { // append the data to the url url += '?' + query; } xhr.open(method, url, async, user, password) httprequest.setRequestHeader('User-Agent', user_agent); // send the data xhr.send(data); }; /** * just a wrapper for XMLHttpRequest::abort() */ httprequest.abort = function (){ xhr.abort() }; }; HttpRequest.METHOD_GET = 'GET'; HttpRequest.METHOD_POST = 'POST'; HttpRequest.METHOD_HEAD = 'HEAD'; HttpRequest.METHOD_PUT = 'PUT'; HttpRequest.METHOD_DELETE = 'DELETE'; HttpRequest.METHOD_OPTIONS = 'OPTIONS'; /** closure compiler "export" method, use quoted syntax */ if (window['HttpRequest'] === UNDEFINED) { // Only give to the world if they want it window['HttpRequest'] = HttpRequest; }
JavaScript
0.000002
@@ -447,45 +447,78 @@ -url = ( +if (!(url instanceof Uri)) %7B%0A url -! = -UNDEFINED) ? url : ''; +new Uri(url);%0A %7D %0A @@ -606,28 +606,72 @@ -httprequest. +if (!(parameters instanceof QueryString)) %7B%0A paramete @@ -683,18 +683,19 @@ new -Collection +QueryString (par @@ -704,16 +704,71 @@ eters);%0A + %7D%0A httprequest.parameters = parameters;%0A @@ -1768,18 +1768,18 @@ ameters. -to +as String()
f722511086d11a8fd4f6b3c16fa341d6d5aadd6e
Fix CommonJS export
src/hunt.js
src/hunt.js
(function(root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(function() { return factory(); }); } else if (typeof exports === 'object') { module.exports = factory; } else { root.hunt = factory(); } })(this, function() { 'use strict'; var huntedElements = [], viewport = window.innerHeight, THROTTLE_INTERVAL = 100; /** * Constructor for element that should be hunted * @constructor Hunted * @param {Node} element * @param {Object} config */ var Hunted = function(element, config) { this.element = element; // instantiate element as not visible this.visible = false; for (var prop in config) { if (config.hasOwnProperty(prop)) { this[prop] = config[prop]; } } }; // by default offset is zero Hunted.prototype.offset = 0; // by default trigger events only once Hunted.prototype.persist = false; // fallback in function to avoid sanity check Hunted.prototype.in = function() {}; // fallback out function to avoid sanity check Hunted.prototype.out = function() {}; /** * Adds one or more elements to the hunted elements array * @method add * @param {Array|Node} elements * @param {Object} options */ var add = function(elements, options) { // sanity check of arguments if (elements instanceof Node === false && typeof elements.length !== 'number' || typeof options !== 'object') { throw new TypeError('Arguments must be an element or a list of them and an object'); } // treat single node as array if (elements instanceof Node === true) { elements = [ elements ]; } var i = 0, len = elements.length; // add elements to general hunted array for (; i < len; i++) { huntedElements.push(new Hunted(elements[i], options)); } // check if recently added elements are visible huntElements(); i = len = null; }; /** * Updates viewport and elements metrics * @method updateMetrics */ var updateMetrics = function() { viewport = window.innerHeight; // check if new elements became visible huntElements(); }; /** * Checks if hunted elements are visible and resets ticking * @method huntElements */ var huntElements = function() { var len = huntedElements.length, hunted, rect; while (len) { --len; hunted = huntedElements[len]; rect = hunted.element.getBoundingClientRect(); /* * trigger (in) event if element comes from a non visible state and the scrolled viewport has * reached the visible range of the element without exceeding it */ if (!hunted.visible && rect.top - hunted.offset < viewport && rect.top >= -(rect.height + hunted.offset)) { hunted.in.apply(hunted.element); hunted.visible = true; } /* * trigger (out) event if element comes from a visible state and it's out of the visible * range its bottom or top limit */ if (hunted.visible && (rect.top - hunted.offset >= viewport || rect.top <= -(rect.height + hunted.offset))) { hunted.out.apply(hunted.element); hunted.visible = false; // when hunting should not persist kick element out if (!hunted.persist) { huntedElements.splice(len, 1); } } } hunted = len = null; }; /** * Prevents overcall during global specified interval * @method throttle * @param {Function} fn * @returns {Function} */ var throttle = function(fn) { var timer = null; return function () { if (timer) { return; } timer = setTimeout(function () { fn.apply(this, arguments); timer = null; }, THROTTLE_INTERVAL); }; }; // on resize update viewport metrics window.addEventListener('resize', throttle(updateMetrics)); // on scroll check for elements position and trigger methods window.addEventListener('scroll', throttle(huntElements)); return add; });
JavaScript
0.000007
@@ -240,16 +240,18 @@ factory +() ;%0A %7D
993d90343ca74982688a9f8ae36130e7f72e3bee
fix indentation
src/i18n.js
src/i18n.js
/* Internationalization module for Game Closure Devkit * * Authors: Jishnu Mohan <jishnu7@gmail.com>, * Vinod CG <vnodecg@gmail.com> * * Copyright: 2014, Hashcube (http://hashcube.com) * */ /* global CACHE, GC */ exports = function (key, params, language) { 'use strict'; var path = 'resources/languages/'; language = language || GC.app.language || 'en'; var localize = function (key, params, language) { var store, string; params = params || []; // if language.json doesn't exists fallback to en_US try { store = JSON.parse(CACHE[path + language + '.json']); } catch (err) { } if (store) { string = store[key]; if (string) { return parser(string, params); } } else if (language !== 'en_US') { return localize(key, params, 'en_US'); } return key; }, pluralize = function (message) { if (!message) { return; } return message.replace(/\[\[[^\]]+\]\]/g, function (match) { var matches = match.replace('[[', '').replace(']]', '').split(','), count = parseInt(matches[0].trim(), 10), is_more = count > 1, word = matches[1].trim(), store; try { store = JSON.parse(CACHE[path + 'plurals_' + language + '.json']); } catch (e) { } if (is_more) { if (store && store[word]) { word = store[word]; } else if (language === 'en') { word += 's'; } } return count + ' ' + word; }); }, parser = function (message, params) { return message.replace(/\$(\d+)/g, function (str, match) { var index = parseInt(match, 10) - 1; return params[index] !== undefined ? params[index] : '$' + match; }); }; return pluralize(localize(key, params, language)); };
JavaScript
0.000358
@@ -320,16 +320,49 @@ guages/' +,%0A localize, pluralize, parser ;%0A%0A lan @@ -409,20 +409,16 @@ en';%0A%0A -var localize @@ -881,17 +881,18 @@ key;%0A %7D -, +;%0A %0A plura @@ -1556,17 +1556,17 @@ %7D);%0A %7D -, +; %0A%0A pars
d5e2a73d99df1ac74d319294edea335b684ae967
Add alt condition back in, rename to specify igorance of shift
src/Keyboard.js
src/Keyboard.js
/* Copyright 2016 OpenMarket Ltd Copyright 2017 New Vector Ltd 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. */ /* a selection of key codes, as used in KeyboardEvent.keyCode */ export const KeyCode = { BACKSPACE: 8, TAB: 9, ENTER: 13, SHIFT: 16, ESCAPE: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, DELETE: 46, KEY_A: 65, KEY_B: 66, KEY_C: 67, KEY_D: 68, KEY_E: 69, KEY_F: 70, KEY_G: 71, KEY_H: 72, KEY_I: 73, KEY_J: 74, KEY_K: 75, KEY_L: 76, KEY_M: 77, KEY_N: 78, KEY_O: 79, KEY_P: 80, KEY_Q: 81, KEY_R: 82, KEY_S: 83, KEY_T: 84, KEY_U: 85, KEY_V: 86, KEY_W: 87, KEY_X: 88, KEY_Y: 89, KEY_Z: 90, }; export function isOnlyCtrlOrCmdKeyEvent(ev) { const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0; if (isMac) { return ev.metaKey && !ev.altKey && !ev.ctrlKey && !ev.shiftKey; } else { return ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey; } } export function isCtrlOrCmdKeyEvent(ev) { const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0; if (isMac) { return ev.metaKey && !ev.ctrlKey; } else { return ev.ctrlKey && !ev.metaKey; } }
JavaScript
0
@@ -1613,16 +1613,20 @@ ction is +Only CtrlOrCm @@ -1618,32 +1618,43 @@ isOnlyCtrlOrCmd +IgnoreShift KeyEvent(ev) %7B%0A @@ -1765,24 +1765,38 @@ v.metaKey && + !ev.altKey && !ev.ctrlKey @@ -1834,24 +1834,38 @@ v.ctrlKey && + !ev.altKey && !ev.metaKey
eb2d16f8a28f5a092a5ddd34d27f5218e4fe5783
Allow options in context clone
lib/context.js
lib/context.js
var _ = require('underscore'), async = require('async'), fs = require('fs'), fu = require('./fileUtil'); function Context(options, config, plugins, mixins, event) { this._package = options.package; this._platform = options.platform; this._plugins = plugins; this.mode = options.mode; this.module = options.module; this.fileConfig = options.fileConfig; this.resource = options.resource; this.config = config; this.mixins = mixins || options.mixins; this.event = event || options.event; } Context.prototype = { fileUtil: fu, clone: function() { var ret = new Context(this, this.config); ret.parent = this; var prototype = Object.keys(Context.prototype); for (var name in this) { if (this.hasOwnProperty(name) && prototype.indexOf(name) === -1) { ret[name] = this[name]; } } return ret; }, fileNamesForModule: function(mode, moduleName, callback) { var context = this.clone(); context.mode = mode; context.module = moduleName && this.config.module(moduleName); this.plugins.outputConfigs(context, function(err, configs) { if (err) { return callback(err); } async.map(configs, function(config, callback) { var fileContext = context.clone(); fileContext.fileConfig = config; fileContext._plugins.fileName(fileContext, function(err, fileName) { config.fileName = fileName; callback(err, config); }); }, callback); }); }, loadResource: function(resource, callback) { if (!callback) { // if only single param, assume as callback and resource from context resource = this.resource; callback = resource; } var fileInfo = {name: resource.hasOwnProperty('sourceFile') ? resource.sourceFile : resource.src}; function loaded(err, data) { if (err) { var json = ''; try { // Output JSON for the resource... but protect ourselves from a failure masking a failure json = '\n\t' + JSON.stringify(resource); } catch(err) { /* NOP */ } callback(new Error('Failed to load resource "' + fileInfo.name + '"' + json + '\n\t' + (err.stack || err))); return; } fileInfo.inputs = data.inputs; fileInfo.noSeparator = data.noSeparator; fileInfo.content = data.data != null ? data.data : data; // Ensure that we dump off the stack _.defer(function() { callback(err, fileInfo); }); } if (typeof resource === 'function') { resource(this, loaded); } else if (resource.src) { // Assume a file page, attempt to load fu.readFile(resource.src, loaded); } else { loaded(undefined, {data: '', noSeparator: true, inputs: resource.dir ? [resource.dir] : []}); } return fileInfo; }, outputFile: function(writer, callback) { var context = this; context.plugins.file(context, function(err) { if (err) { return callback(err); } context.plugins.fileName(context, function(err, fileName) { if (err) { return callback(err); } context.buildPath = (fileName.root ? '' : context.platformPath) + fileName.path + '.' + fileName.extension; context.fileName = context.outdir + '/' + context.buildPath; writer(function(err, data) { data = _.defaults({ fileConfig: context.fileConfig, platform: context.platform, package: context.package, mode: context.mode }, data); if (err) { fs.unlink(context.fileName); } else { context.event.emit('output', data); } context.fileCache = undefined; callback(err, data); }); }); }); }, get plugins() { return this._plugins; }, get package() { return this._package; }, get platform() { return this._platform; }, get platformPath() { return this.platform ? this.platform + '/' : ''; }, get combined() { return this.config.combineModules(this.package); }, get resources() { if (this.parent) { return this.parent.resources; } else { return this._resources; } }, set resources(value) { if (this.parent) { delete this.parent; } this._resources = value; } }; module.exports = Context;
JavaScript
0.000016
@@ -562,32 +562,39 @@ clone: function( +options ) %7B%0A var ret @@ -846,24 +846,192 @@ %7D%0A %7D%0A + if (options) %7B%0A _.extend(ret, options);%0A ret._package = options.package %7C%7C this._package;%0A ret._platform = options.platform %7C%7C this._platform;%0A %7D%0A return r
00159671d2d7eee51237587154bde93817cc09b8
Fix documentation of Info.features() (#148)
src/info.js
src/info.js
import { DateTime } from './datetime'; import { Settings } from './settings'; import { Locale } from './impl/locale'; import { Util } from './impl/util'; /** * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment. */ export class Info { /** * Return whether the specified zone contains a DST. * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. * @return {boolean} */ static hasDST(zone = Settings.defaultZone) { const proto = DateTime.local() .setZone(zone) .set({ month: 12 }); return !zone.universal && proto.offset !== proto.set({ month: 6 }).offset; } /** * Return an array of standalone month names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.outputCalendar='gregory'] - the calendar * @example Info.months()[0] //=> 'January' * @example Info.months('short')[0] //=> 'Jan' * @example Info.months('numeric')[0] //=> '1' * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' * @return {[string]} */ static months( length = 'long', { locale = null, numberingSystem = null, outputCalendar = 'gregory' } = {} ) { return Locale.create(locale, numberingSystem, outputCalendar).months(length); } /** * Return an array of format month names. * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that * changes the string. * See {@link months} * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numbering=null] - the numbering system * @param {string} [opts.outputCalendar='gregory'] - the calendar * @return {[string]} */ static monthsFormat( length = 'long', { locale = null, numberingSystem = null, outputCalendar = 'gregory' } = {} ) { return Locale.create(locale, numberingSystem, outputCalendar).months(length, true); } /** * Return an array of standalone week names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". * @param {object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numbering=null] - the numbering system * @param {string} [opts.outputCalendar='gregory'] - the calendar * @example Info.weekdays()[0] //=> 'Monday' * @example Info.weekdays('short')[0] //=> 'Mon' * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' * @return {[string]} */ static weekdays(length = 'long', { locale = null, numberingSystem = null } = {}) { return Locale.create(locale, numberingSystem, null).weekdays(length); } /** * Return an array of format week names. * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that * changes the string. * See {@link weekdays} * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". * @param {object} opts - options * @param {string} [opts.locale=null] - the locale code * @param {string} [opts.numbering=null] - the numbering system * @param {string} [opts.outputCalendar='gregory'] - the calendar * @return {[string]} */ static weekdaysFormat(length = 'long', { locale = null, numberingSystem = null } = {}) { return Locale.create(locale, numberingSystem, null).weekdays(length, true); } /** * Return an array of meridiems. * @param {object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.meridiems() //=> [ 'AM', 'PM' ] * @example Info.meridiems({ locale: 'de' }) //=> [ 'vorm.', 'nachm.' ] * @return {[string]} */ static meridiems({ locale = null } = {}) { return Locale.create(locale).meridiems(); } /** * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". * @param {object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.eras() //=> [ 'BC', 'AD' ] * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] * @return {[string]} */ static eras(length = 'short', { locale = null } = {}) { return Locale.create(locale, null, 'gregory').eras(length); } /** * Return the set of available features in this environment. * Some features of Luxon are not available in all environments. For example, on older browsers, timezone support is not available. Use this function to figure out if that's the case. * Keys: * * `timezones`: whether this environment supports IANA timezones * * `intlTokens`: whether this environment supports internationalized token-based formatting/parsing * * `intl`: whether this environment supports general internationalization * @example Info.feature() //=> { intl: true, intlTokens: false, timezones: true } * @return {object} */ static features() { let intl = false, intlTokens = false, zones = false; if (Util.hasIntl()) { intl = true; intlTokens = Util.hasFormatToParts(); try { zones = new Intl.DateTimeFormat('en', { timeZone: 'America/New_York' }).resolvedOptions() .timeZone === 'America/New_York'; } catch (e) { zones = false; } } return { intl, intlTokens, zones }; } }
JavaScript
0.000003
@@ -5933,20 +5933,16 @@ * * %60 -time zones%60: @@ -6198,16 +6198,17 @@ .feature +s () //=%3E @@ -6240,20 +6240,16 @@ false, -time zones: t
b3a1fc65e53d4433fee814162b1bef97da68866f
Disable deprecation warning of `crashReported.setExtraParameter()`
lib/common/api/crash-reporter.js
lib/common/api/crash-reporter.js
'use strict' const {spawn} = require('child_process') const os = require('os') const path = require('path') const electron = require('electron') const {app, deprecate} = process.type === 'browser' ? electron : electron.remote const binding = process.atomBinding('crash_reporter') class CrashReporter { start (options) { if (options == null) options = {} this.productName = options.productName != null ? options.productName : app.getName() let { companyName, extra, ignoreSystemCrashHandler, submitURL, uploadToServer } = options if (uploadToServer == null) uploadToServer = options.autoSubmit if (uploadToServer == null) uploadToServer = true if (ignoreSystemCrashHandler == null) ignoreSystemCrashHandler = false if (extra == null) extra = {} if (extra._productName == null) extra._productName = this.getProductName() if (extra._companyName == null) extra._companyName = companyName if (extra._version == null) extra._version = app.getVersion() if (companyName == null) { throw new Error('companyName is a required option to crashReporter.start') } if (submitURL == null) { throw new Error('submitURL is a required option to crashReporter.start') } if (process.platform === 'win32') { const env = { ELECTRON_INTERNAL_CRASH_SERVICE: 1 } const args = [ '--reporter-url=' + submitURL, '--application-name=' + this.getProductName(), '--crashes-directory=' + this.getCrashesDirectory(), '--v=1' ] this._crashServiceProcess = spawn(process.execPath, args, { env: env, detached: true }) } binding.start(this.getProductName(), companyName, submitURL, this.getCrashesDirectory(), uploadToServer, ignoreSystemCrashHandler, extra) } getLastCrashReport () { const reports = this.getUploadedReports() return (reports.length > 0) ? reports[0] : null } getUploadedReports () { return binding.getUploadedReports(this.getCrashesDirectory()) } getCrashesDirectory () { const crashesDir = `${this.getProductName()} Crashes` return path.join(this.getTempDirectory(), crashesDir) } getProductName () { if (this.productName == null) { this.productName = app.getName() } return this.productName } getTempDirectory () { if (this.tempDirectory == null) { try { this.tempDirectory = app.getPath('temp') } catch (error) { this.tempDirectory = os.tmpdir() } } return this.tempDirectory } getUploadToServer () { if (process.type === 'browser') { return binding.getUploadToServer() } else { throw new Error('getUploadToServer can only be called from the main process') } } setUploadToServer (uploadToServer) { if (process.type === 'browser') { return binding.setUploadToServer(uploadToServer) } else { throw new Error('setUploadToServer can only be called from the main process') } } // TODO(2.0) Remove setExtraParameter (key, value) { if (!process.noDeprecations) { deprecate.warn('crashReporter.setExtraParameter', 'crashReporter.addExtraParameter or crashReporter.removeExtraParameter') } binding.setExtraParameter(key, value) } addExtraParameter (key, value) { binding.addExtraParameter(key, value) } removeExtraParameter (key) { binding.removeExtraParameter(key) } getParameters (key, value) { return binding.getParameters() } } module.exports = new CrashReporter()
JavaScript
0
@@ -3091,24 +3091,218 @@ value) %7B%0A + // TODO(alexeykuzmin): Warning disabled since it caused%0A // a couple of Crash Reported tests to time out on Mac. Add it back.%0A // https://github.com/electron/electron/issues/11012%0A%0A // if (!proces @@ -3324,16 +3324,19 @@ s) %7B%0A + // depre @@ -3379,24 +3379,27 @@ ameter',%0A + // 'crashR @@ -3463,24 +3463,27 @@ ameter')%0A + // %7D%0A bindi
c627be39c7b26161ba2b26640b5d820a488dba20
document clientScheduler option
lib/components/client-factory.js
lib/components/client-factory.js
"use strict"; var requestModule = require("request"); /** * @constructor * @param {Object} opts Options for this factory * @param {*=} opts.sdk The Matrix JS SDK require() to use. * @param {string=} opts.url The Client-Server base HTTP URL. This must be set * prior to calling getClientAs(). See configure() to set this after instantiation. * @param {string=} opts.token The application service token to use. This must * be set prior to calling getClientAs(). See configure() to set this after * instantiation. * @param {string=} opts.appServiceUserId The application service's user ID. Must * be set prior to calling getClientAs(). See configure() to set this after * instantiation. */ function ClientFactory(opts) { opts = opts || {}; this._sdk = opts.sdk || require("matrix-js-sdk"); this._clients = { // request_id: { // user_id: Client // } }; this._clientScheduler = opts.clientScheduler; this.configure(opts.url, opts.token, opts.appServiceUserId); } /** * Set a function to be called when logging requests and responses. * @param {Function} func The function to invoke. The first arg is the string to * log. The second arg is a boolean which is 'true' if the log is an error. */ ClientFactory.prototype.setLogFunction = function(func) { if (func) { this._sdk.request(function(opts, callback) { var logPrefix = ( (opts._matrix_opts && opts._matrix_opts._reqId ? "[" + opts._matrix_opts._reqId + "] " : "" ) + opts.method + " " + opts.uri + " " + (opts.qs.user_id ? "(" + opts.qs.user_id + ")" : "(AS)") ); // Request logging func( logPrefix + " Body: " + (opts.body ? JSON.stringify(opts.body).substring(0, 80) : "") ); // Make the request requestModule(opts, function(err, response, body) { // Response logging var httpCode = response ? response.statusCode : null; var responsePrefix = logPrefix + " HTTP " + httpCode; if (err) { func( responsePrefix + " Error: " + JSON.stringify(err), true ); } else if (httpCode >= 300 || httpCode < 200) { func( responsePrefix + " Error: " + JSON.stringify(body), true ); } else { func( // body may be large, so do first 80 chars responsePrefix + " " + JSON.stringify(body).substring(0, 80) ); } // Invoke the callback callback(err, response, body); }); }); } }; /** * Construct a new Matrix JS SDK Client. Calling this twice with the same args * will return the *same* client instance. * @param {?string} userId Required. The user_id to scope the client to. A new * client will be created per user ID. If this is null, a client scoped to the * application service *itself* will be created. * @param {Request=} request Optional. The request ID to additionally scope the * client to. If set, this will create a new client per user ID / request combo. * This factory will dispose the created client instance when the request is * resolved. */ ClientFactory.prototype.getClientAs = function(userId, request) { var reqId = request ? request.getId() : "-"; var userIdKey = userId || "bot"; var self = this; // see if there is an existing match var client = this._getClient(reqId, userIdKey); if (client) { return client; } // create a new client var queryParams = {}; if (userId) { queryParams.user_id = userId; } // force set access_token= so it is used when /register'ing queryParams.access_token = this._token; var clientOpts = { accessToken: this._token, baseUrl: this._url, userId: userId || this._botUserId, // NB: no clobber so we don't set ?user_id=BOT queryParams: queryParams, scheduler: this._clientScheduler }; client = this._sdk.createClient(clientOpts); client._http.opts._reqId = reqId; // FIXME gut wrenching // add a listener for the completion of this request so we can cleanup // the clients we've made if (request) { request.getPromise().finally(function() { delete self._clients[reqId]; }); } // store the new client if (!this._clients[reqId]) { this._clients[reqId] = {}; } this._clients[reqId][userIdKey] = client; return client; }; /** * Configure the factory for generating clients. * @param {string} baseUrl The base URL to create clients with. * @param {string} appServiceToken The AS token to use as the access_token * @param {string} appServiceUserId The AS's user_id */ ClientFactory.prototype.configure = function(baseUrl, appServiceToken, appServiceUserId) { this._url = baseUrl; this._token = appServiceToken; this._botUserId = appServiceUserId; }; ClientFactory.prototype._getClient = function(reqId, userId) { if (this._clients[reqId] && this._clients[reqId][userId]) { return this._clients[reqId][userId]; } return null; }; module.exports = ClientFactory;
JavaScript
0
@@ -689,16 +689,193 @@ iation.%0A + * @param %7BMatrixScheduler%7D opts.clientScheduler Optional. The client scheduler to%0A * use in place of the default event scheduler that schedules events to be sent to%0A * the HS.%0A */%0Afunc
2469c2d856f8beb6c4fd91c06af477bb151ce243
use beforeEach instead of beforeAll, and add afterEach
test/specs/test.spec.js
test/specs/test.spec.js
/* * General specifications GridGallery * 1- creates a grid using elements that will be in different heights and widths * 2- will enable gallery view on click to an element of the grid (dialog) * 3- the dialog will trigger custom events to control data in dialog * 4- nav of items in grid (disable/enable) depending on initialization */ describe('GridGallery', function(){ var x, options = { lightBox: true }; var container; document.body.className = 'grid-gallery__example'; beforeAll(function() { var wrapper = document.createElement('div'); wrapper.className = 'container'; container = document.createElement('div'); container.className = 'grid-gallery'; for (var i = 0; i < 5; i++) { var element = document.createElement('div'); var p = document.createElement('p'); p.textContent = 'lorem nav of items in grid (disable/enable) depending on initialization'; element.className = 'grid-gallery__item grid-gallery__dummy'; element.appendChild(p); container.appendChild(element); } wrapper.appendChild(container); document.body.appendChild(wrapper); x = new GridGallery(container, options); }); describe('GridGallery initialization', function(){ it('Global must have the GridGallery as a property', function() { expect(GridGallery).not.toBeUndefined(); }); it('should manipulate the default options to the created instance', function() { var div = document.createElement('div'); var childs = document.createElement('div'); childs.className = 'grid-gallery__item'; div.appendChild(childs); var y = new GridGallery( div, {}); expect(y.options).toEqual({'lightBox': false}); }); it('should extend the default options and icludes the new one', function() { expect(x.options).toEqual({'lightBox': true}); }); it('should store the container as a property', function() { expect(x.element).toEqual(container); }); it('should have method init', function() { expect(x.init).toBeDefined(); expect(typeof x.init).toBe('function'); }); }); });
JavaScript
0.000001
@@ -495,11 +495,12 @@ fore -All +Each (fun @@ -1184,16 +1184,163 @@ %0A %7D);%0A%0A + afterEach(function()%7B%0A var oldContainer = document.querySelector('.container');%0A oldContainer.parentNode.removeChild(oldContainer);%0A %7D);%0A%0A descri
2041b4e1eb1406488e377aae242fe014850a473b
Revert "Correct HDT escaping."
lib/datasources/HdtDatasource.js
lib/datasources/HdtDatasource.js
/*! @license ©2014 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */ /** An HdtDatasource loads and queries an HDT document in-process. */ var Datasource = require('./Datasource'), fs = require('fs'), hdt = require('hdt'); var escapeSequence = /\\u|\\U/; var escapeSequences = /\\u([a-zA-Z0-9]{4})|\\U([a-zA-Z0-9]{8})/g; var needEscape = /[\u0000-\u0019\u00ff-\uffff]/; var needEscapes = /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u0019\u00ff-\uffff]/g; // Creates a new HdtDatasource function HdtDatasource(options) { if (!(this instanceof HdtDatasource)) return new HdtDatasource(options); Datasource.call(this, options); // Switch to external HDT datasource if the `external` flag is set options = options || {}; if (options.external) return new require('./ExternalHdtDatasource')(options); // Test whether the HDT file exists var hdtFile = (options.file || '').replace(/^file:\/\//, ''); if (!fs.existsSync(hdtFile) || !/\.hdt$/.test(hdtFile)) throw Error('Not an HDT file: ' + hdtFile); // Store requested operations until the HDT document is loaded var pendingCloses = [], pendingSearches = []; this._hdtDocument = { close: function () { pendingCloses.push(arguments); }, search: function () { pendingSearches.push(arguments); } }; // Load the HDT document hdt.fromFile(hdtFile, function (error, hdtDocument) { // Set up an error document if the HDT document could not be opened this._hdtDocument = !error ? hdtDocument : hdtDocument = { close: function (callback) { callback && callback(); }, search: function (s, p, o, op, callback) { callback(error); }, }; // Execute pending operations pendingSearches.forEach(function (args) { hdtDocument.search.apply(hdtDocument, args); }); pendingCloses.forEach(function (args) { hdtDocument.close.apply(hdtDocument, args); }); }, this); } Datasource.extend(HdtDatasource, ['triplePattern', 'limit', 'offset', 'totalCount']); // Writes the results of the query to the given triple stream HdtDatasource.prototype._executeQuery = function (query, tripleStream, metadataCallback) { var subject = needEscape.test(query.subject) ? query.subject.replace(needEscapes, charToCode) : query.subject, predicate = needEscape.test(query.predicate) ? query.predicate.replace(needEscapes, charToCode) : query.predicate, object = needEscape.test(query.object) ? query.object.replace(needEscapes, charToCode) : query.object; // Add unicode escapes to IRIs (TODO: fix this in generation code of HDT library) this._hdtDocument.search(subject, predicate, object, { limit: query.limit, offset: query.offset }, function (error, triples, estimatedTotalCount) { if (error) return tripleStream.emit('error', error); // Ensure the estimated total count is as least as large as the number of triples var tripleCount = triples.length, offset = query.offset || 0; if (tripleCount && estimatedTotalCount < offset + tripleCount) estimatedTotalCount = offset + (tripleCount < query.limit ? tripleCount : 2 * tripleCount); metadataCallback({ totalCount: estimatedTotalCount }); // Add the triples to the stream for (var i = 0; i < tripleCount; i++) { // Remove unicode escapes from IRIs (TODO: fix this in generation code of HDT library) var triple = triples[i]; if (escapeSequence.test(triple.subject)) triple.subject = triple.subject.replace(escapeSequences, codeToChar); if (escapeSequence.test(triple.predicate)) triple.predicate = triple.predicate.replace(escapeSequences, codeToChar); if (escapeSequence.test(triple.object)) triple.object = triple.object.replace(escapeSequences, codeToChar); tripleStream.push(triple); } tripleStream.push(null); }); }; // Converts a unicode escape sequence into a unicode character function codeToChar(match, unicode4, unicode8) { if (unicode4) return String.fromCharCode(parseInt(unicode4, 16)); else { var charCode = parseInt(unicode8, 16); return String.fromCharCode(charCode <= 0xFFFF ? charCode : 0xD800 + ((charCode -= 0x10000) / 0x400), 0xDC00 + (charCode & 0x3FF)); } } // Converts a unicode character into its unicode escape sequence function charToCode(character) { // Replace a single character with its 4-bit unicode escape sequence if (character.length === 1) { character = character.charCodeAt(0).toString(16).toUpperCase(); return '\\u0000'.substr(0, 6 - character.length) + character; } // Replace a surrogate pair with its 8-bit unicode escape sequence else { character = ((character.charCodeAt(0) - 0xD800) * 0x400 + character.charCodeAt(1) + 0x2400).toString(16).toUpperCase(); return '\\U00000000'.substr(0, 10 - character.length) + character; } } // Closes the data source HdtDatasource.prototype.close = function (done) { this._hdtDocument.close(done); }; module.exports = HdtDatasource;
JavaScript
0
@@ -244,238 +244,8 @@ );%0A%0A -var escapeSequence = /%5C%5Cu%7C%5C%5CU/;%0Avar escapeSequences = /%5C%5Cu(%5Ba-zA-Z0-9%5D%7B4%7D)%7C%5C%5CU(%5Ba-zA-Z0-9%5D%7B8%7D)/g;%0Avar needEscape = /%5B%5Cu0000-%5Cu0019%5Cu00ff-%5Cuffff%5D/;%0Avar needEscapes = /%5B%5Cud800-%5Cudbff%5D%5B%5Cudc00-%5Cudfff%5D%7C%5B%5Cu0000-%5Cu0019%5Cu00ff-%5Cuffff%5D/g;%0A%0A // C @@ -1925,502 +1925,105 @@ %7B%0A -var subject = needEscape.test(query.subject) ? query.subject.replace(needEscapes, charToCode) : query.subject,%0A predicate = needEscape.test(query.predicate) ? query.predicate.replace(needEscapes, charToCode) : query.predicate,%0A object = needEscape.test(query.object) ? query.object.replace(needEscapes, charToCode) : query.object;%0A // Add unicode escapes to IRIs (TODO: fix this in generation code of HDT library)%0A this._hdtDocument.search(subject, predicate, object, +this._hdtDocument.search(query.subject, query.predicate, query.object,%0A %7B%C2%A0l @@ -2645,18 +2645,16 @@ nt; i++) - %7B %0A @@ -2658,1647 +2658,80 @@ -// Remove unicode escapes from IRIs (TODO: fix this in generation code of HDT library)%0A var triple = triples%5Bi%5D;%0A if (escapeSequence.test(triple.subject))%0A triple.subject = triple.subject.replace(escapeSequences, codeToChar);%0A if (escapeSequence.test(triple.predicate))%0A triple.predicate = triple.predicate.replace(escapeSequences, codeToChar);%0A if (escapeSequence.test(triple.object))%0A triple.object = triple.object.replace(escapeSequences, codeToChar);%0A tripleStream.push(triple);%0A %7D%0A tripleStream.push(null);%0A %7D);%0A%7D;%0A%0A// Converts a unicode escape sequence into a unicode character%0Afunction codeToChar(match, unicode4, unicode8) %7B%0A if (unicode4)%0A return String.fromCharCode(parseInt(unicode4, 16));%0A else %7B%0A var charCode = parseInt(unicode8, 16);%0A return String.fromCharCode(charCode %3C= 0xFFFF ? charCode :%0A 0xD800 + ((charCode -= 0x10000) / 0x400), 0xDC00 + (charCode & 0x3FF));%0A %7D%0A%7D%0A%0A// Converts a unicode character into its unicode escape sequence%0Afunction charToCode(character) %7B%0A // Replace a single character with its 4-bit unicode escape sequence%0A if (character.length === 1) %7B%0A character = character.charCodeAt(0).toString(16).toUpperCase();%0A return '%5C%5Cu0000'.substr(0, 6 - character.length) + character;%0A %7D%0A // Replace a surrogate pair with its 8-bit unicode escape sequence%0A else %7B%0A character = ((character.charCodeAt(0) - 0xD800) * 0x400 +%0A character.charCodeAt(1) + 0x2400).toString(16).toUpperCase();%0A return '%5C%5CU00000000'.substr(0, 10 - character.length) + character;%0A %7D%0A%7D +tripleStream.push(triples%5Bi%5D);%0A tripleStream.push(null);%0A %7D);%0A%7D; %0A%0A//
afbb650f94f036fce79458ddbc6ba3100bcd8cc8
fix default inclusion of CSS files (closes #2629) (#2701)
nuxt/index.js
nuxt/index.js
const { resolve } = require('path') function pickFirst(...args) { for (const arg of args) { if (arg !== undefined) { return arg } } } module.exports = function nuxtBootstrapVue(moduleOptions = {}) { // Merge moduleOptions with default const options = { ...this.options.bootstrapVue, ...moduleOptions } const bootstrapVueCSS = pickFirst(options.bootstrapVueCSS, options.bootstrapVueCss, options.bvCSS) if (bootstrapVueCSS) { // Add BootstrapVue CSS this.options.css.unshift('bootstrap-vue/dist/bootstrap-vue.css') } const bootstrapCSS = pickFirst(options.bootstrapCSS, options.bootstrapCss, options.css) if (bootstrapCSS) { // Add Bootstrap CSS this.options.css.unshift('bootstrap/dist/css/bootstrap.css') } // Transpile src this.options.build.transpile.push('bootstrap-vue/src') // Register plugin, pasing options to plugin template this.addPlugin({ src: resolve(__dirname, 'plugin.template.js'), fileName: 'bootstrap-vue.js' }) } module.exports.meta = require('../package.json')
JavaScript
0
@@ -358,32 +358,37 @@ CSS = pickFirst( +%0A options.bootstra @@ -391,24 +391,28 @@ strapVueCSS, +%0A options.boo @@ -420,24 +420,28 @@ strapVueCss, +%0A options.bvC @@ -442,16 +442,84 @@ ns.bvCSS +,%0A // Defaults to %60true%60 if no other options provided%0A true%0A )%0A if ( @@ -672,16 +672,21 @@ ckFirst( +%0A options. @@ -698,16 +698,20 @@ trapCSS, +%0A options @@ -724,16 +724,20 @@ trapCss, +%0A options @@ -740,16 +740,84 @@ ions.css +,%0A // Defaults to %60true%60 if no other options provided%0A true%0A )%0A if ( @@ -852,24 +852,48 @@ ootstrap CSS + before BootstrapVue CSS %0A this.op
cb3269524509d1b046aa4e61bdef2d300b347aca
Update error checking
test/test-user-agent.js
test/test-user-agent.js
var test = require('tape'); var path = require('path'); var curli = require(path.join(__dirname, '..')); var server = require(path.join(__dirname, './server.js')).createServer(); var conf = require(path.join(__dirname, '../package.json')); var ua = conf.name + ' / ' + conf.version; server.listen(0, function() { var port = server.address().port; var host = '//localhost:' + port; var href = 'http:' + host + '/'; test('User agent being sent', function(t) { server.on('/', function(req, res) { t.equal(req.headers['user-agent'], ua, 'User agent set to "' + ua + '"'); res.writeHead(200); res.end(); }); curli(href, function(err, headers) { t.ok(!err, 'Shouldn\'t error'); server.close(); t.end(); }); }); });
JavaScript
0.000002
@@ -687,12 +687,14 @@ t. -ok(! +error( err,
627ea6e7175d3ec1fb89e0c896e123ed8bd3ee2b
Make function to eat bookmarks
bookWorm.js
bookWorm.js
$(document).ready(function() { onCreatedChrome() }); function onCreatedChrome() { chrome.tabs.onCreated.addListener(function(tab) { alert("hello"); }); }
JavaScript
0.000028
@@ -43,17 +43,18 @@ Chrome() +; %0A - %7D);%0A%0Afun @@ -139,21 +139,115 @@ -alert(%22hello%22 +chrome.bookmarks.getChildren(%221%22, (bar) =%3E %7B%0A chrome.bookmarks.remove(bar%5Bbar.length - 1%5D.id);%0A %7D );%0A
be3e24072a38dfb8e65ea258e877c134e96cbe89
Fix typo in `Container.destroy`
lib/cloudfiles/container.js
lib/cloudfiles/container.js
/* * container.js: Instance of a single Rackspace Cloudfiles container * * (C) 2010 Nodejitsu Inc. * MIT LICENSE * */ var cloudfiles = require('../cloudfiles'); var Container = exports.Container = function (client, details) { if (!details) { throw new Error("Container must be constructed with at least basic details.") } this.files = []; this.client = client; this._setProperties(details); }; Container.prototype = { addFile: function (file, local, options, callback) { return this.client.addFile(this.name, file, local, options, callback); }, destroy: function (callback) { this.client.destoryContainer(this.name, callback); }, getFiles: function (download, callback) { var self = this; // download can be omitted: (...).getFiles(callback); // In this case first argument will be a function if (typeof download === 'function' && !(download instanceof RegExp)) { callback = download; download = false; } this.client.getFiles(this.name, download, function (err, files) { if (err) { return callback(err); } self.files = files; callback(null, files); }); }, removeFile: function (file, callback) { this.client.destroyFile(this.name, file, callback); }, // Remark: Not fully implemented updateCdn: function (options, callback) { if (!this.cdnEnabled) { callback(new Error('Cannot call updateCdn on a container that is not CDN enabled')); } // TODO: Write the rest of this method }, _setProperties: function (details) { this.name = details.name; this.cdnEnabled = details.cdnEnabled || false; this.cdnUri = details.cdnUri; this.cdnSslUri = details.cdnSslUri; this.ttl = details.ttl; this.logRetention = details.logRetention; this.count = details.count || 0; this.bytes = details.bytes || 0; } };
JavaScript
0
@@ -627,18 +627,18 @@ ent.dest -o r +o yContain
d286adf17beb7f5ba655e1be8d7d8f816dea4612
Update run-multiple.js (#1205)
lib/command/run-multiple.js
lib/command/run-multiple.js
const { getConfig, getTestRoot, fail, deepMerge, } = require('./utils'); const Codecept = require('../codecept'); const Config = require('../config'); const fork = require('child_process').fork; const output = require('../output'); const path = require('path'); const runHook = require('../hooks'); const event = require('../event'); const collection = require('./run-multiple/collection'); const clearString = require('../utils').clearString; const runner = path.join(__dirname, '/../../bin/codecept'); let config; const childOpts = {}; const copyOptions = ['steps', 'reporter', 'verbose', 'config', 'reporter-options', 'grep', 'fgrep', 'debug']; // codeceptjs run:multiple smoke:chrome regression:firefox - will launch smoke run in chrome and regression in firefox // codeceptjs run:multiple smoke:chrome regression - will launch smoke run in chrome and regression in firefox and chrome // codeceptjs run:multiple all - will launch all runs // codeceptjs run:multiple smoke regression' let runId = 1; let subprocessCount = 0; let totalSubprocessCount = 0; let processesDone; module.exports = function (selectedRuns, options) { // registering options globally to use in config process.profile = options.profile; const configFile = options.config; let codecept; const testRoot = getTestRoot(configFile); config = getConfig(configFile); // copy opts to run Object.keys(options) .filter(key => copyOptions.indexOf(key) > -1) .forEach((key) => { childOpts[key] = options[key]; }); if (!config.multiple) { fail('Multiple runs not configured, add "multiple": { /../ } section to config'); } selectedRuns = options.all ? Object.keys(config.multiple) : selectedRuns; if (!selectedRuns.length) { fail('No runs provided. Use --all option to run all configured runs'); } const done = () => event.emit(event.multiple.before, null); runHook(config.bootstrapAll, done, 'multiple.bootstrap'); if (options.config) { // update paths to config path config.tests = path.resolve(testRoot, config.tests); } const childProcessesPromise = new Promise((resolve, reject) => { processesDone = resolve; }); const runsToExecute = []; collection.createRuns(selectedRuns, config).forEach((run) => { const runName = run.getOriginalName() || run.getName(); const runConfig = run.getConfig(); runsToExecute.push(executeRun(runName, runConfig)); }); if (!runsToExecute.length) { fail('Nothing scheduled for execution'); } // Execute all forks totalSubprocessCount = runsToExecute.length; runsToExecute.forEach(runToExecute => runToExecute.call(this)); return childProcessesPromise.then(() => { // fire hook const done = () => event.emit(event.multiple.after, null); runHook(config.teardownAll, done, 'multiple.teardown'); }); }; function executeRun(runName, runConfig) { // clone config let overriddenConfig = Object.assign({}, config); // get configuration const browserConfig = runConfig.browser; const browserName = browserConfig.browser; for (const key in browserConfig) { overriddenConfig.helpers = replaceValue(overriddenConfig.helpers, key, browserConfig[key]); } let outputDir = `${runName}_`; if (browserConfig.outputName) { outputDir += typeof browserConfig.outputName === 'function' ? browserConfig.outputName() : browserConfig.outputName; } else { outputDir += JSON.stringify(browserConfig).replace(/[^\d\w]+/g, '_'); } outputDir += `_${runId}`; outputDir = clearString(outputDir); // tweaking default output directories and for mochawesome overriddenConfig = replaceValue(overriddenConfig, 'output', path.join(config.output, outputDir)); overriddenConfig = replaceValue(overriddenConfig, 'reportDir', path.join(config.output, outputDir)); overriddenConfig = replaceValue(overriddenConfig, 'mochaFile', path.join(config.output, outputDir, `${browserName}_report.xml`)); // override tests configuration if (overriddenConfig.tests) { overriddenConfig.tests = runConfig.tests; } // override grep param and collect all params const params = ['run', '--child', `${runId++}.${runName}:${browserName}`, '--override', JSON.stringify(overriddenConfig), ]; Object.keys(childOpts).forEach((key) => { params.push(`--${key}`); if (childOpts[key] !== true) params.push(childOpts[key]); }); if (runConfig.grep) { params.push('--grep'); params.push(runConfig.grep); } const onProcessEnd = (errorCode) => { if (errorCode !== 0) { process.exitCode = errorCode; } subprocessCount += 1; if (subprocessCount === totalSubprocessCount) { processesDone(); } return errorCode; }; // Return function of fork for later execution return () => fork(runner, params, { stdio: [0, 1, 2, 'ipc'] }) .on('exit', (code) => { return onProcessEnd(code); }) .on('error', (err) => { return onProcessEnd(1); }); } /** * search key in object recursive and replace value in it */ function replaceValue(obj, key, value) { if (!obj) return; if (obj instanceof Array) { for (const i in obj) { replaceValue(obj[i], key, value); } } if (obj[key]) obj[key] = value; if (typeof obj === 'object' && obj !== null) { const children = Object.keys(obj); for (let childIndex = 0; childIndex < children.length; childIndex++) { replaceValue(obj[children[childIndex]], key, value); } } return obj; }
JavaScript
0
@@ -555,16 +555,28 @@ ions = %5B +'override', 'steps',
87511e6783972e30ab3c39a88c45dec1a927dd17
add tests for synchronous generator actions
app/client/src/tests/actions/generator.js
app/client/src/tests/actions/generator.js
import test from 'ava' test('generator actions', async t => { t.pass() })
JavaScript
0
@@ -20,57 +20,608 @@ va'%0A -%0Atest('generator actions', async t =%3E %7B%0A t.pass( +import %7B GeneratorActions %7D from '../../actions'%0Aimport %7B%0A SELECT_TEMPLATE,%0A SET_PAGE_COUNT,%0A SET_PAGE,%0A PREV_PAGE,%0A NEXT_PAGE%0A%7D from '../../constants'%0A%0Aconst %7B%0A selectTemplate,%0A setPageCount,%0A setPage,%0A prevPage,%0A nextPage%0A%7D = GeneratorActions%0A%0Atest('synchronous generator actions', async t =%3E %7B%0A t.deepEqual(selectTemplate(4), %7B type: SELECT_TEMPLATE, templateId: 4 %7D)%0A t.deepEqual(setPageCount(1), %7B type: SET_PAGE_COUNT, pageCount: 1 %7D)%0A t.deepEqual(setPage(2), %7B type: SET_PAGE, page: 2 %7D)%0A t.deepEqual(prevPage(), %7B type: PREV_PAGE %7D)%0A t.deepEqual(nextPage(), %7B type: NEXT_PAGE %7D )%0A%7D)
35728b96409f54f9e697f10a96cfb1f51e8383fd
Fix injectServer/injectDebugger file path for log
src/main.js
src/main.js
import fs from 'fs'; import path from 'path'; import chalk from 'chalk'; import * as injectDebugger from './injectDebugger'; import * as injectServer from './injectServer'; import runServer from './runServer'; const name = 'react-native'; const bundleCode = fs.readFileSync(path.join(__dirname, '../bundle.js'), 'utf-8'); const getModulePath = moduleName => path.join(process.cwd(), 'node_modules', moduleName); const log = (pass, msg) => { const prefix = pass ? chalk.green.bgBlack('PASS') : chalk.red.bgBlack('FAIL'); const color = pass ? chalk.blue : chalk.red; console.log(prefix, color(msg)); }; const getFullPath = filePath => path.resolve(process.cwd(), filePath); const assignSecureOptions = (options, { secure, key, cert, passphrase }) => ({ ...options, ...( secure ? { protocol: 'https', key: key ? getFullPath(key) : null, cert: cert ? getFullPath(cert) : null, passphrase: passphrase || null, } : null ), }); module.exports = argv => { const modulePath = getModulePath(argv.desktop ? 'react-native-desktop' : name); // Revert all injection if (argv.revert) { const passServ = injectServer.revert(modulePath); let msg = 'Revert injection of RemoteDev server from React Native local server'; log(passServ, msg + (!passServ ? `, the file '${injectServer.path}' not found.` : '.')); const passDbg = injectDebugger.revert(modulePath); msg = 'Revert injection of RemoteDev monitor from React Native debugger'; log(passDbg, msg + (!passDbg ? `, the file '${injectDebugger.path}' not found.` : '.')); if (!passServ || !passDbg) return false; return true; } const options = argv.hostname || argv.port ? { secure: argv.secure, hostname: argv.hostname || 'localhost', port: argv.port || 8000, } : null; // Inject server if (argv.injectserver) { const pass = injectServer.inject(modulePath, assignSecureOptions(options, argv)); const msg = 'Inject RemoteDev server into React Native local server'; log(pass, msg + (pass ? '.' : `, the file '${injectServer.path}' not found.`)); if (!pass) return false; } // Inject debugger if (argv.injectdebugger) { const pass = injectDebugger.inject(modulePath, bundleCode, options); const msg = 'Inject RemoteDev monitor into React Native debugger'; log(pass, msg + (pass ? '.' : `, the file '${injectDebugger.path}' not found.`)); if (!pass) return false; } // Run RemoteDev server if (argv.runserver) { return runServer(assignSecureOptions(options || { secure: argv.secure, port: 8000 }, argv)); } return true; };
JavaScript
0
@@ -1319,33 +1319,37 @@ '$%7BinjectServer. -p +fullP ath%7D' not found. @@ -1550,33 +1550,37 @@ %7BinjectDebugger. -p +fullP ath%7D' not found. @@ -2086,17 +2086,21 @@ tServer. -p +fullP ath%7D' no @@ -2404,17 +2404,21 @@ ebugger. -p +fullP ath%7D' no
85b49e2d116037936f702b2765377f72fe338981
Add language name as property to Translation
src/main.js
src/main.js
(function (global) { "use strict"; var languageDialect = (function(lang) { window.location.search.slice(1).split("&").some(function (searchTerm) { if (searchTerm.indexOf("lang=") === 0) { lang = searchTerm.split("=").slice(1).join("="); return true; } }); return lang.toLowerCase(); })(window.navigator.userLanguage || window.navigator.language), language = languageDialect.split("-")[0], Translations = (function() { var scope = "_scope"; function Translations(o) { this[scope] = o; } Translations.prototype.find = function(path) { return path.split(".").reduce(function (obj, key) { return obj ? obj[key] : undefined; }, this[scope]); }; Translations.prototype.translate = function(ele) { if(getLang(ele) === languageDialect) { if(!ele.hasAttribute("data-i18n")) { [].slice.call(ele.querySelectorAll("[lang]:not([lang='" + language + "'])")).forEach(this.translate.bind(this)); } } else if(ele.hasAttribute("data-i18n")) { applyTranslationToElement(ele, this); } else { [].slice.call(ele.querySelectorAll("[data-i18n]")).map(function(match) { if(getLang(match, ele) !== languageDialect) { applyTranslationToElement(match, this); } }); } return ele; }; return Translations; }()); function applyTranslationToElement(ele, obj) { if(ele.hasAttribute("data-i18n")) { applyTranslation(ele, ele.getAttribute("data-i18n"), obj); } } function applyTranslation(ele, path, obj) { var translated = obj.find(path); if (typeof(translated) === "object" && !Array.isArray(translated)) { console.warn("Could not translate %o: path '%s' is of type object", ele, path); } else if(typeof(translated) !== "undefined") { clean(ele); ele.appendChild(toDom(translated)); ele.lang = language; } } function getLang(ele, threshold) { do { if(ele.lang) { return ele.lang.toLowerCase(); } } while((ele = ele.parentElement) && ele !== threshold); } function clean(ele) { var child; while((child = ele.firstChild)) { ele.removeChild(child); } } function toDom(content) { if(Array.isArray(content)) { return content.reduce(function(frag, text) { var ele = document.createElement("p"); ele.textContent = text; frag.appendChild(ele); return frag; }, document.createDocumentFragment()); } return document.createTextNode(content); } global.i18n = { base: (document.documentElement.getAttribute("data-i18n-base") || "locales/"), set: (document.documentElement.getAttribute("data-i18n-set") || "translation"), loadTranslations: function(lang, set, base) { var url = (base || this.base || "") + (lang || language) + "/" + (set || this.set) + ".json"; console.info("loading translations from: " + url); return fetch(url, { headers: { "Accept": "application/json" } }).then(function (res) { if (res.status >= 200 && res.status < 300) { console.info("successfully loaded translations"); return res.json().then(function(obj) { return new Translations(obj); }); } // TODO add error object instead of false return Promise.reject(false); }).catch(function (err) { console.error("Error loading translations: %o", err); }); }, translate: function(ele) { if(!this.translations) { this.translations = this.loadTranslations(); } return this.translations.then(function(translations) { return translations.translate(ele); }); }, translateAll: function() { this.translatedAll = true; return this.translate(document.documentElement); }, set language(lang) { lang = String(lang); if(lang !== language) { language = lang; if(this.translatedAll) { this.translateAll(lang); } else if(this.translations) { this.translations = this.loadTranslations(); } } }, get language() { return language; } }; if(!document.documentElement.hasAttribute("data-i18n-disable-auto")) { global.i18n.translateAll(); } }(this));
JavaScript
0.000026
@@ -568,12 +568,58 @@ ons( -o) %7B +language, o) %7B%0A this.language = language; %0A @@ -945,24 +945,29 @@ le) === +this. language Dialect) @@ -950,39 +950,32 @@ == this.language -Dialect ) %7B%0A @@ -1083,16 +1083,21 @@ ng='%22 + +this. language @@ -1405,24 +1405,29 @@ le) !== +this. language Dialect) @@ -1418,23 +1418,16 @@ language -Dialect ) %7B%0A @@ -3517,16 +3517,34 @@ lations( +lang %7C%7C language, obj);%0A
ce0bfd11074c5b8cba19954a5bffbb3ab74f4458
make way for yousefamar
src/main.js
src/main.js
var https = require('https'); var express = require("express"); var bodyParser = require("body-parser"); // A request wrapper that inserts the container mangers root cert and // arbiter api key into GET and POST requests var request = require('./lib/databox-request/databox-request.js')(); var macaroons = require('macaroons.js'); var timeseriesRouter = require('./timeseries.js'); var keyValueRouter = require('./keyvalue.js'); var actuateRouter = require('./actuate.js'); var hypercat = require('./lib/hypercat/hypercat.js'); const DATABOX_LOCAL_NAME = process.env.DATABOX_LOCAL_NAME || "databox-store-blob"; const DATABOX_ARBITER_ENDPOINT = process.env.DATABOX_ARBITER_ENDPOINT || "https://databox-arbiter:8080" //HTTPS certs georated by the container mangers for this components HTTPS server. const HTTPS_CLIENT_CERT = process.env.HTTPS_CLIENT_CERT || ''; const HTTPS_CLIENT_PRIVATE_KEY = process.env.HTTPS_CLIENT_PRIVATE_KEY || ''; const credentials = { key: HTTPS_CLIENT_PRIVATE_KEY, cert: HTTPS_CLIENT_CERT, }; var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); /* * DATABOX API Logging * Logs all requests and responses to/from the API in bunyan format in nedb */ var logsDb = require('./lib/log/databox-log-db.js')('../database/datastoreLOG.db'); var databoxLoggerApi = require('./lib/log/databox-log-api.js'); var databoxLogger = require('./lib/log/databox-log-middelware.js')(logsDb); app.use(databoxLogger); //Macaroon checker TODO move this into a module? app.use(function (req, res, next) { var mac = null if('macaroon' in req.body) { mac = req.body.macaroon; delete req.body.macaroon } else if ('macaroon' in req.query) { mac = req.query.macaroon; delete req.query.macaroon } else { res.status(400).send('Missing macaroon'); return } macaroon = macaroons.MacaroonsBuilder.deserialize(mac); req.macaroon = new macaroons.MacaroonsVerifier(macaroon).satisfyExact("target = " + DATABOX_LOCAL_NAME); next(); }) app.get("/status", function(req, res) { res.send("active"); }); app.get("/api/status", function(req, res) { res.send("active"); }); app.use('/api/actuate',actuateRouter(app)); app.use('/:var(api/data|api/ts)?',timeseriesRouter(app)); app.use('/api/key',keyValueRouter(app)); app.use('/api/cat',hypercat(app)); app.use('/logs',databoxLoggerApi(app,logsDb)); var server = null; if(credentials.cert === '' || credentials.key === '') { var http = require('http'); console.log("WARNING NO HTTPS credentials supplied running in http mode!!!!"); server = http.createServer(app); } else { server = https.createServer(credentials,app); } //Websocket connection to live stream data var WebSocketServer = require('ws').Server; app.wss = new WebSocketServer({ server: server }); app.broadcastDataOverWebSocket = require('./lib/websockets/broadcastDataOverWebSocket.js')(app); //Register with arbiter and get secret app.arbiterSecret = null; request.get(DATABOX_ARBITER_ENDPOINT+'/store/secret') .then((error, response, body) => { console.log(error,response,body) app.arbiterSecret = Buffer.from(body,'base64'); server.listen(8080,function() { console.log("listening on 8080"); }); }) .catch((error)=>{ console.log(error); throw new Error(error); }); module.exports = app;
JavaScript
0.000002
@@ -1505,555 +1505,9 @@ TODO - move this into a module?%0Aapp.use(function (req, res, next) %7B%0A var mac = null%0A if('macaroon' in req.body) %7B%0A mac = req.body.macaroon;%0A delete req.body.macaroon%0A %7D else if ('macaroon' in req.query) %7B%0A mac = req.query.macaroon;%0A delete req.query.macaroon%0A %7D else %7B%0A res.status(400).send('Missing macaroon');%0A return%0A %7D%0A%0A macaroon = macaroons.MacaroonsBuilder.deserialize(mac);%0A req.macaroon = new macaroons.MacaroonsVerifier(macaroon).satisfyExact(%22target = %22 + DATABOX_LOCAL_NAME);%0A%0A next();%0A%7D) +%0A %0A%0Aap
c6a5620c760dd60a2a8792497d6f5d345b0f6566
Fix loading translations when switching lang
src/main.js
src/main.js
(function (global) { "use strict"; var languageDialect = (function(lang) { window.location.search.slice(1).split("&").some(function (searchTerm) { if (searchTerm.indexOf("lang=") === 0) { lang = searchTerm.split("=").slice(1).join("="); return true; } }); return lang.toLowerCase(); })(window.navigator.userLanguage || window.navigator.language), language = languageDialect.split("-")[0], Translations = (function() { var scope = "_scope"; function Translations(language, o) { this.language = language; this[scope] = o; } Translations.prototype.find = function(path) { return path.split(".").reduce(function (obj, key) { return obj ? obj[key] : undefined; }, this[scope]); }; Translations.prototype.translate = function(ele) { if(getLang(ele) === this.language) { if(!ele.hasAttribute("data-i18n")) { [].slice.call(ele.querySelectorAll("[lang]:not([lang='" + this.language + "'])")).forEach(this.translate.bind(this)); } } else if(ele.hasAttribute("data-i18n")) { applyTranslationToElement(ele, this); } else { [].slice.call(ele.querySelectorAll("[data-i18n]")).map(function(match) { if(getLang(match, ele) !== this.language) { applyTranslationToElement(match, this); } }); } return ele; }; return Translations; }()); function applyTranslationToElement(ele, obj) { if(ele.hasAttribute("data-i18n")) { applyTranslation(ele, ele.getAttribute("data-i18n"), obj); } } function applyTranslation(ele, path, obj) { var translated = obj.find(path); if (typeof(translated) === "object" && !Array.isArray(translated)) { console.warn("Could not translate %o: path '%s' is of type object", ele, path); } else if(typeof(translated) !== "undefined") { clean(ele); ele.appendChild(toDom(translated)); ele.lang = language; } } function getLang(ele, threshold) { do { if(ele.lang) { return ele.lang.toLowerCase(); } } while((ele = ele.parentElement) && ele !== threshold); } function clean(ele) { var child; while((child = ele.firstChild)) { ele.removeChild(child); } } function toDom(content) { if(Array.isArray(content)) { return content.reduce(function(frag, text) { var ele = document.createElement("p"); ele.textContent = text; frag.appendChild(ele); return frag; }, document.createDocumentFragment()); } return document.createTextNode(content); } global.i18n = { base: (document.documentElement.getAttribute("data-i18n-base") || "locales/"), set: (document.documentElement.getAttribute("data-i18n-set") || "translation"), loadTranslations: function(lang, set, base) { var url = (base || this.base || "") + (lang || language) + "/" + (set || this.set) + ".json"; console.info("loading translations from: " + url); return fetch(url, { headers: { "Accept": "application/json" } }).then(function (res) { if (res.status >= 200 && res.status < 300) { console.info("successfully loaded translations"); return res.json().then(function(obj) { return new Translations(lang || language, obj); }); } // TODO add error object instead of false return Promise.reject(false); }).catch(function (err) { console.error("Error loading translations: %o", err); }); }, translate: function(ele) { if(!this.translations) { this.translations = this.loadTranslations(); } return this.translations.then(function(translations) { return translations.translate(ele); }); }, translateAll: function() { this.translatedAll = true; return this.translate(document.documentElement); }, set language(lang) { lang = String(lang); if(lang !== language) { language = lang; if(this.translatedAll) { this.translateAll(lang); } else if(this.translations) { this.translations = this.loadTranslations(); } } }, get language() { return language; } }; if(!document.documentElement.hasAttribute("data-i18n-disable-auto")) { global.i18n.translateAll(); } }(this));
JavaScript
0.000001
@@ -1499,32 +1499,38 @@ %7D%0A %7D +, this );%0A %7D%0A%0A @@ -4276,21 +4276,20 @@ translat -edAll +ions ) %7B%0A @@ -4311,17 +4311,37 @@ slat -eAll(lang +ions = this.loadTranslations( );%0A @@ -4344,29 +4344,32 @@ );%0A %7D - else +%0A if(this.tra @@ -4365,36 +4365,37 @@ if(this.translat -ions +edAll ) %7B%0A th @@ -4409,37 +4409,17 @@ slat -ions = this.loadTranslations( +eAll(lang );%0A
e152a06c1425a476d91d6db68e315edebb66e448
Add complex prop types
__tests__/props.spec.js
__tests__/props.spec.js
/* global jest, describe, it, expect */ import React from 'react' import * as Schemative from '../src/schemative' console.error = jest.fn() describe('React prop types suite', () => { it(`should fail when props don't match`, () => { const Simple = (props) => (<div className={props.name} />) const errorMessage = 'Warning: Failed prop type: Invalid prop `foo` of type `number` supplied to `Simple`, expected `string`.\n in Simple' const schema = Schemative.createSchema({ foo: Schemative.string }) Simple.propTypes = schema.PropTypes ;(<Simple foo={2} />) expect(console.error).toHaveBeenCalledWith(errorMessage) }) it(`should fail when props don't match with nested props`, () => { const Complex = (props) => (<div className={props.name} />) const errorMessage = 'Warning: Failed prop type: Invalid prop `name` of type `number` supplied to `Foo`, expected `string`.\n in Foo' const schema = Schemative.createSchema({ foo: Schemative.objectOf({ bar: Schemative.arrayOf([ Schemative.string, Schemative.string ]) }) }) Complex.propTypes = schema.PropTypes ;(<Complex foo={{ bar: 2 }} />) expect(console.error).toHaveBeenLastCalledWith(errorMessage) }) })
JavaScript
0.000007
@@ -133,16 +133,271 @@ est.fn() +%0Aconst createErrorMessage = (%7B attr, type, expected, component %7D) =%3E %5B%0A 'Warning: Failed prop type: Invalid prop',%0A %60%5C%60$%7Battr%7D%5C%60 of type %5C%60$%7Btype%7D%5C%60%60,%0A %60supplied to %5C%60$%7Bcomponent%7D%5C%60,%60,%0A %60expected %5C%60$%7Bexpected%7D%5C%60.%5Cn%60,%0A %60 in $%7Bcomponent%7D%60%0A%5D.join(' ') %0A%0Adescri @@ -576,93 +576,102 @@ e = -'Warning: Failed prop type: Invalid prop %60foo%60 of +createErrorMessage(%7B%0A attr: 'foo',%0A type - %60 +: ' number -%60 supplied to %60Simple%60, +',%0A component: 'Simple',%0A exp @@ -679,34 +679,25 @@ cted - %60 +: ' string -%60.%5Cn in Simple' +'%0A %7D) %0A @@ -1072,123 +1072,132 @@ e = -'Warning: Failed prop type: Invalid prop %60name%60 of +createErrorMessage(%7B%0A attr: 'foo.bar',%0A type - %60 +: ' number -%60 supplied to %60Foo%60, expected %60string%60.%5Cn in Foo' +',%0A component: 'Complex',%0A expected: 'array'%0A %7D) %0A @@ -1264,16 +1264,13 @@ ive. -objectOf +shape (%7B%0A @@ -1301,80 +1301,8 @@ rray -Of(%5B%0A Schemative.string,%0A Schemative.string%0A %5D) %0A @@ -1434,12 +1434,8 @@ Been -Last Call
dd1f2a1cb5af2fd2dcc178f3f30d149fde659c7b
Add creep.energy and creep.energyCapacity to Creep prototype
src/main.js
src/main.js
var spawnController = require("SpawnController"); var CreepController = require("CreepController"); var MilitaryController = require("MilitaryController"); var StructureMaintainer = require("StructureMaintainer"); var linkController = require("LinkController"); var RoomMaintainer = require("RoomMaintainer"); Memory.sources = Memory.sources || {}; Object.defineProperty(Source.prototype, "memory", { enumerable : true, configurable : false, get: function () { Memory.sources[this.id] = Memory.sources[this.id] || {}; return Memory.sources[this.id]; } }); Memory.structures = Memory.structures || {}; Object.defineProperty(Structure.prototype, "memory", { enumerable : true, configurable : false, get: function () { Memory.structures[this.id] = Memory.structures[this.id] || {}; return Memory.structures[this.id]; } }); Creep.prototype.advMove = function(target) { var reCalc = false; if(!target.pos) { return; } if (!this.memory.movement || !Array.isArray(this.memory.movement.path) || !this.memory.movement.lastPos || this.memory.movement.step === undefined || this.memory.movement.lastCalc === undefined) { reCalc = true; } if(reCalc || !this.memory.movement.path.length || target.pos !== this.memory.movement.targetPos || JSON.stringify(this.pos) === this.memory.movement.lastPos || this.memory.movement.step >= (this.memory.movement.lastCalc/2 || undefined) ) { this.memory.movement = { path: this.pos.findPathTo(target.pos.x, target.pos.y), step: 0, lastPos: this.pos, lastCalc: 0, targetPos: target.pos }; this.memory.movement.lastCalc = this.memory.movement.path.length; } this.memory.movement.lastPos = this.pos; if(this.memory.movement.path.length) { this.move(this.memory.movement.path[this.memory.movement.step].direction); this.memory.movement.step = this.memory.movement.step + 1; return OK; } else { return ERR_NOT_FOUND; } }; Object.keys(Memory.spawnList).forEach(function(spawnName) { spawnController.decide(Game.spawns[spawnName]); }); Memory.linkList.forEach(function(linkId) { linkController.decide(Game.getObjectById(linkId)); }); Object.keys(Memory.roleList).forEach(function(roleType) { Memory.roleList[roleType].forEach(function(name, index) { var spawningIndex = Memory.spawning.indexOf(name); if(!Game.creeps[name]) { if(spawningIndex < 0) { Memory.roleList[roleType].splice(index, 1); Memory.creeps[name] = undefined; } } else { if(spawningIndex >= 0) { Memory.spawning.splice(spawningIndex, 1); } CreepController.decide(Game.creeps[name]); } }); }); if((Game.time % 101) === 0) { StructureMaintainer(); } if((Game.time % 103) === 0) { (new RoomMaintainer()).updateRooms(); } // MilitaryController.calculateOrders();
JavaScript
0
@@ -879,16 +879,401 @@ %7D%0A%7D);%0A%0A +Object.defineProperty(Creep.prototype, %22energy%22, %7B%0A enumerable : true,%0A configurable : true,%0A writable : false,%0A get: function () %7B%0A return this.carry.energy;%0A %7D%0A%7D);%0AObject.defineProperty(Creep.prototype, %22energyCapacity%22, %7B%0A enumerable : true,%0A configurable : true,%0A writable : false,%0A get: function () %7B%0A return this.carryCapacity;%0A %7D%0A%7D);%0A Creep.pr
260745d8c8163bac97f09dfda641dfeb71712897
update sample
src/main.js
src/main.js
GLBoost.TARGET_WEBGL_VERSION = 1; var SCREEN_WIDTH = 640; var SCREEN_HEIGHT = 640; phina.define('MainScene', { superClass: 'phina.display.CanvasScene', init: function(options) { this.superInit(); var layer = this.layer = phina.display.GLBoostLayer({ width: SCREEN_WIDTH, height: SCREEN_HEIGHT }).addChildTo(this); var lookat = { eye: new GLBoost.Vector4(0.0, 1.5, 10.0, 1), center: new GLBoost.Vector3(0.0, 1.5, 0.0), up: new GLBoost.Vector3(0.0, 1.0, 0.0) }; var perspective = { fovy: 45.0, aspect: 1.0, zNear: 0.1, zFar: 1000.0 }; var camera = phina.glboost.Camera(lookat, perspective).addChildTo(layer); /* var obj = phina.asset.AssetManager.get("mqo", "gradriel"); var mesh = obj.getMesh(layer.canvas); layer.scene.add(mesh[0]); layer.scene.prepareForRender(); */ /* var mesh = phina.glboost.Mesh('gradriel'); mesh.addChildTo(layer); */ this.createObject(); layer.prepareForRender(); layer.update = function() { var rotateMatrix = GLBoost.Matrix44.rotateY(-0.02); var rotatedVector = rotateMatrix.multiplyVector(camera.eye); camera.eye = rotatedVector; }; var label = phina.display.Label('phina.jsとGLBoostの\n夢の共演!').addChildTo(this); label.fill = 'white'; label.stroke = 'black'; label.fontSize = 32; label.strokeWidth = 4; label.x = this.gridX.center(); label.y = this.gridY.center(); }, createObject: function() { var material = new GLBoost.ClassicMaterial(this.layer.canvas); material.shader = new GLBoost.PhongShader(this.layer.canvas); var geometry = new GLBoost.Cube( new GLBoost.Vector3(20,20,20), new GLBoost.Vector4(Math.random()*1,Math.random()*1,Math.random()*1,1), this.layer.canvas); for (var i = 0; i < 2000; i ++) { var object = phina.glboost.Mesh({ geometry: geometry, material: material }); object.translate = new GLBoost.Vector3(Math.randint(0, 800) - 400, Math.randint(0, 800) - 400, Math.randint(0, 800) - 400); object.rotate = new GLBoost.Vector3(Math.randfloat(0, 2)*Math.PI, Math.randfloat(0, 2)*Math.PI, Math.randfloat(0, 2)*Math.PI); object.scale = new GLBoost.Vector3(Math.randfloat(0.5, 1.5), Math.randfloat(0.5, 1.5), Math.randfloat(0.5, 1.5)); object.dirty = true; object.tweener.clear() .to({scaleY: 3}, 500, "easeOutSine") .to({scaleY: 1}, 500, "easeOutElastic") .setLoop(true); object.addChildTo(this.layer); } }, }); phina.main(function() { var app = phina.game.GameApp({ /* assets: { mqo: { 'gradriel': 'assets/gradriel_pose.mqo', }, }, */ startLabel: 'main', width: SCREEN_WIDTH, height: SCREEN_HEIGHT }); app.run(); });
JavaScript
0
@@ -2368,16 +2368,40 @@ true;%0A%0A + if (i%253 == 0) %7B%0A ob @@ -2421,32 +2421,34 @@ clear()%0A + .to(%7BscaleY: 3%7D, @@ -2441,17 +2441,17 @@ o(%7Bscale -Y +X : 3%7D, 50 @@ -2468,32 +2468,34 @@ tSine%22)%0A + .to(%7BscaleY: 1%7D, @@ -2488,17 +2488,17 @@ o(%7Bscale -Y +X : 1%7D, 50 @@ -2526,16 +2526,18 @@ + .setLoop @@ -2540,24 +2540,32 @@ Loop(true);%0A + %7D%0A object
18080398171b09881f08a67308d29db6db23ed22
Add missing unquote function
test/utils/transform.js
test/utils/transform.js
import _ from 'lodash'; import fs from 'fs'; import gutil from 'gulp-util'; import path from 'path'; import hash from 'sha1'; import table from 'text-table'; // Parses hash arguments for Handlebars block helper // @see [Hash Arguments]{@http://code.demunskin.com/other/Handlebars/block_helpers.html#hash-arguments} // @see [Regular expression for parsing name value pairs]{@link http://stackoverflow.com/questions/168171/regular-expression-for-parsing-name-value-pairs} // @example <caption>Example usage:</caption> // it will output ["id=nav-bar", "class = "top"", "foo = "bar\"baz""] // var str = ' id=nav-bar class = "top" foo = "bar\\"baz" '; // str.match(/([^=,\s]*)\s*=\s*((?:"(?:\\.|[^"\\]+)*"|'(?:\\.|[^'\\]+)*')|[^'"\s]*)/igm) || []; // @param [string] str A string representation of hash arguments // @return {object} var parseHashArguments = function(str) { var hash = {}; var results = str.match(/([^=,\s]*)\s*=\s*((?:"(?:\\.|[^"\\]+)*"|'(?:\\.|[^'\\]+)*')|[^'"\s]*)/igm) || []; results.forEach((result) => { result = _.trim(result); var r = result.match(/([^=,\s]*)\s*=\s*((?:"(?:\\.|[^"\\]+)*"|'(?:\\.|[^'\\]+)*')|[^'"\s]*)/) || []; if (r.length < 3 || _.isUndefined(r[1]) || _.isUndefined(r[2])) { return; } var key = _.trim(r[1]); var value = _.trim(r[2]); { // value is enclosed with either single quote (') or double quote (") characters var quoteChars = '\'"'; var quoteChar = _.find(quoteChars, (quoteChar) => { return value.charAt(0) === quoteChar; }); if (quoteChar) { // single quote (') or double quote (") value = unquote(value, quoteChar); } } hash[key] = value; }); return hash; }; const transform = function(file, enc, done) { const parser = this.parser; const extname = path.extname(file.path); const content = fs.readFileSync(file.path, enc); const tableData = [ ['Key', 'Value'] ]; gutil.log('parsing ' + JSON.stringify(file.relative) + ':'); { // Using Gettext style i18n parser.parseFuncFromString(content, { list: ['i18n._'] }, function(key) { const value = key; key = hash(value); // returns a hash value as its default key parser.set(key, value); tableData.push([key, _.isUndefined(value) ? parser.options.defaultValue : value ]); }); } { // Handlebars - i18n function helper const results = content.match(/{{i18n\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')?([^}]*)}}/gm) || []; _.each(results, function(result) { let key, value; const r = result.match(/{{i18n\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')?([^}]*)}}/m) || []; if ( ! _.isUndefined(r[1])) { value = _.trim(r[1], '\'"'); // Replace double backslash with single backslash value = value.replace(/\\\\/g, '\\'); value = value.replace(/\\\'/, '\''); } const params = parseHashArguments(r[2]); if (_.has(params, 'defaultKey')) { key = params['defaultKey']; } if (_.isUndefined(key) && _.isUndefined(value)) { return; } if (_.isUndefined(key)) { key = hash(value); // returns a hash value as its default key } parser.set(key, value); tableData.push([key, _.isUndefined(value) ? parser.options.defaultValue : value ]); }); } { // Handlebars - i18n block helper const results = content.match(/{{#i18n\s*([^}]*)}}((?:(?!{{\/i18n}})(?:.|\n))*){{\/i18n}}/gm) || []; _.each(results, function(result) { let key, value; const r = result.match(/{{#i18n\s*([^}]*)}}((?:(?!{{\/i18n}})(?:.|\n))*){{\/i18n}}/m) || []; if ( ! _.isUndefined(r[2])) { value = _.trim(r[2], '\'"'); } if (_.isUndefined(value)) { return; } key = hash(value); // returns a hash value as its default key parser.set(key, value); tableData.push([key, _.isUndefined(value) ? parser.options.defaultValue : value ]); }); } if (_.size(tableData) > 1) { gutil.log('result of ' + JSON.stringify(file.relative) + ':\n' + table(tableData, {'hsep': ' | '})); } done(); }; export default transform;
JavaScript
0.998138
@@ -152,16 +152,228 @@ able';%0A%0A +const unquote = (str, quoteChar) =%3E %7B%0A quoteChar = quoteChar %7C%7C '%22';%0A if (str%5B0%5D === quoteChar && str%5Bstr.length - 1%5D === quoteChar) %7B%0A return str.slice(1, str.length - 1);%0A %7D%0A return str;%0A%7D;%0A%0A // Parse @@ -1034,19 +1034,21 @@ object%7D%0A -var +const parseHa @@ -1081,19 +1081,19 @@ ) %7B%0A -var +let hash = @@ -1101,19 +1101,21 @@ %7D;%0A%0A -var +const results @@ -1285,19 +1285,21 @@ -var +const r = res @@ -1501,19 +1501,19 @@ -var +let key = _ @@ -1533,19 +1533,19 @@ -var +let value = @@ -1655,35 +1655,37 @@ ers%0A -var +const quoteChars = '%5C @@ -1701,19 +1701,21 @@ -var +const quoteCh
e70f8bea9508b8d5105f51463f5e9bb3a3f46d49
add some more test cases
test/visibility.spec.js
test/visibility.spec.js
/* eslint-env jasmine, jquery */ /* global loadFixtures */ 'use strict'; describe('visibility', function() { var select = false; beforeEach(function() { jasmine.getFixtures().fixturesPath = 'base/test/fixtures'; loadFixtures('basic.html'); select = $('#basic'); select.selectric(); }); it('should toggle visibility on click', function() { $('.selectric-wrapper').find('.selectric').trigger('click'); expect($('.selectric-items').is(':visible')).toBe(true); $('.selectric-wrapper').find('.selectric').trigger('click'); expect($('.selectric-items').is(':visible')).toBe(false); }); it('should open on focus', function() { $('.selectric-input').focusin(); expect($('.selectric-items').is(':visible')).toBe(true); }); it('should open/close on click', function() { $('.selectric').click(); expect($('.selectric-items').is(':visible')).toBe(true); $('.selectric').click(); expect($('.selectric-items').is(':visible')).toBe(false); }); it('should open/close programmatically', function() { select.selectric('open'); expect($('.selectric-items').is(':visible')).toBe(true); select.selectric('close'); expect($('.selectric-items').is(':visible')).toBe(false); }); it('should open on mouseover and close after timeout', function(done) { select.selectric({ openOnHover: true, hoverIntentTimeout: 30 }); var $wrapper = $('.selectric-wrapper'); var $optionsBox = $('.selectric-items'); $wrapper.trigger('mouseenter'); expect($optionsBox.is(':visible')).toBe(true); $wrapper.trigger('mouseleave'); setTimeout(function() { expect($optionsBox.is(':visible')).toBe(false); done(); }, 40); }); });
JavaScript
0
@@ -760,32 +760,658 @@ e(true);%0A %7D);%0A%0A + it('should add .selectric-focus on focusin', function() %7B%0A $('.selectric-input').focusin();%0A expect($('.selectric-wrapper').hasClass('selectric-focus')).toBe(true);%0A %7D);%0A%0A it('should remove .selectric-focus on focusout', function() %7B%0A $('.selectric-input').focusin().focusout();%0A expect($('.selectric-wrapper').hasClass('selectric-focus')).toBe(false);%0A %7D);%0A%0A it('should prevent the flicker when focusing out and back again', function() %7B%0A var spy = spyOn($.fn, 'blur');%0A $('.selectric-input').focusin().trigger('blur').trigger('blur').trigger('blur');%0A expect(spy).toHaveBeenCalledTimes(1);%0A %7D);%0A%0A it('should ope @@ -2368,8 +2368,9 @@ %7D);%0A%7D); +%0A
becb5648ab434398767884d9fbbe1d397e9698b0
Refactor getTopTracks to accept params as object.
src/api/user.js
src/api/user.js
"use strict"; var _ = require('lodash'); var getJSONP = require('./getJSONP'); var credentials = require("./credentials.json"); var baseUrl = "http://ws.audioscrobbler.com/2.0/?format=json&user=slwen&api_key=" + credentials.key; var routes = { getInfo: baseUrl + "&method=user.getinfo", getTopAlbums: baseUrl + "&method=user.gettopalbums", getTopTracks: baseUrl + "&method=user.gettoptracks", getTopArtists: baseUrl + "&method=user.gettopartists", getRecentTracks: baseUrl + "&method=user.getrecenttracks" }; var formatUrl = function(params) { return _.map(params, function(value, key) { return '&' + key + '=' + value; }).join(''); }; exports.getInfo = function(callback) { var route = routes.getInfo; return getJSONP(route, callback); }; exports.getTopArtists = function(params, callback) { var route = routes.getTopArtists + formatUrl(params); return getJSONP(route, callback); }; exports.getTopAlbums = function(limit, callback) { var route = routes.getTopAlbums + "&limit=" + limit; return getJSONP(route, callback); }; exports.getTopTracks = function(limit, period, callback) { var route = routes.getTopTracks + "&limit=" + limit + "&period=" + period; return getJSONP(route, callback); }; exports.getRecentTracks = function(limit, startDate, endDate, page, callback) { var route = routes.getRecentTracks + "&limit=" + limit + "&from=" + startDate + "&to=" + endDate + "&page=" + page; return getJSONP(route, callback); };
JavaScript
0
@@ -1108,21 +1108,14 @@ ion( -limit, period +params , ca @@ -1164,47 +1164,25 @@ s + -%22&limit=%22 + limit + %22&period=%22 + period +formatUrl(params) ;%0A
bd8ee87fdf58e83ece23a562390d1a2221356d3d
Update codebase
src/app/main.js
src/app/main.js
//const {app, globalShortcut} = require('electron') var menubar = require('menubar'); var mb = menubar(); mb.on('ready', function ready () { console.log('app is ready'); // // Register a 'CommandOrControl+X' shortcut listener. // const ret = globalShortcut.register('CommandOrControl+X', function () { // console.log('CommandOrControl+X is pressed') // }); // // if (!ret) { // console.log('registration failed') // } // // // Check whether a shortcut is registered. // console.log(globalShortcut.isRegistered('CommandOrControl+X')) });
JavaScript
0.000001
@@ -1,10 +1,9 @@ -//cons +impor t %7Ba @@ -24,20 +24,26 @@ tcut -%7D = require( +, clipboard%7D from 'ele @@ -52,13 +52,16 @@ ron' -)%0Avar +;%0Aimport men @@ -69,18 +69,13 @@ bar -= require( +from 'men @@ -83,488 +83,358 @@ bar' -) ;%0A%0A -var mb = menubar();%0A%0Amb.on('ready', function ready () %7B%0A console.log('app is ready');%0A%0A // // Register a 'CommandOrControl+X' shortcut listener.%0A // const ret = globalShortcut.register('CommandOrControl+X', function () %7B%0A // console.log('CommandOrControl+X is pressed')%0A // %7D);%0A //%0A // if (!ret) %7B%0A // console.log('registration failed')%0A // %7D%0A //%0A // // Check whether a shortcut is registered.%0A // console.log(globalShortcut.isRegistered('CommandOrControl+X')) +const dir = process.cwd();%0Aconst mb = menubar(%7B%0A index: %60file://$%7Bdir%7D/dist/app/index.html%60%0A%7D);%0A%0Afunction saveContents() %7B%0A console.log(clipboard.readText());%0A%7D%0A%0Amb.on('ready', () =%3E %7B%0A globalShortcut.register('Control+Command+S', saveContents);%0A%0A if (!globalShortcut.isRegistered('Control+Command+S')) %7B%0A // TODO: alert and eld process%0A %7D %0A%7D);
ade6a78c921ec47b1e1ba0e2d52eeea1c759a9c3
Fix test
web/src/js/utils/__tests__/feature-flags.test.js
web/src/js/utils/__tests__/feature-flags.test.js
/* eslint-env jest */ const anonUserSignInEnv = process.env.FEATURE_FLAG_ANON_USER_SIGN_IN afterEach(() => { // Reset env vars after tests process.env.FEATURE_FLAG_ANON_USER_SIGN_IN = anonUserSignInEnv }) describe('feature flags', () => { test('isAnonymousUserSignInEnabled is false if the env var is "false"', () => { const isAnonymousUserSignInEnabled = require('js/utils/feature-flags') .isAnonymousUserSignInEnabled process.env.FEATURE_FLAG_ANON_USER_SIGN_IN = 'false' expect(isAnonymousUserSignInEnabled()).toBe(false) }) test('isAnonymousUserSignInEnabled is true if the env var is "true"', () => { const isAnonymousUserSignInEnabled = require('js/utils/feature-flags') .isAnonymousUserSignInEnabled process.env.FEATURE_FLAG_ANON_USER_SIGN_IN = 'true' expect(isAnonymousUserSignInEnabled()).toBe(true) }) test('isAnonymousUserSignInEnabled is false if the env var is a string other than "true"', () => { const isAnonymousUserSignInEnabled = require('js/utils/feature-flags') .isAnonymousUserSignInEnabled process.env.FEATURE_FLAG_ANON_USER_SIGN_IN = 'yes' expect(isAnonymousUserSignInEnabled()).toBe(false) }) test('isVariousAdSizesEnabled is true', () => { const isVariousAdSizesEnabled = require('js/utils/feature-flags') .isVariousAdSizesEnabled expect(isVariousAdSizesEnabled()).toBe(true) }) })
JavaScript
0.000004
@@ -1220,19 +1220,20 @@ bled is -tru +fals e', () = @@ -1372,30 +1372,31 @@ Enabled()).toBe( -tru +fals e)%0A %7D)%0A%7D)%0A