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
a7b7fd31a59be062ac01e004f0797c1486ca0ca5
Add some resilience and cleanup
extension.js
extension.js
'use strict'; function Followers(nodecg) { this.nodecg = nodecg; this.twitch = nodecg.extensions['lfg-twitchapi']; this.request = require('request'); this.latestFollower = nodecg.Replicant('latestFollower', { defaultValue: null, persistent: true }); this.username = nodecg.bundleConfig.username; this.pollInterval = nodecg.bundleConfig.pollInterval * 1000; this._scheduleFollowers(); } Followers.prototype._scheduleFollowers = function() { this.nodecg.log.debug('Polling for TwitchTV Followers.'); this.request('https://api.twitch.tv/kraken/channels/' + this.username + '/follows?limit=5', (err, response, body) => { if (err) { this.nodecg.log.error(err); setTimeout(() => { this._scheduleFollowers(); }, this.pollInterval); return; } if (response.statusCode != 200) { this.nodecg.log.error('Unknown response code: ' + response.statusCode); setTimeout(() => { this._scheduleFollowers(); }, this.pollInterval); return; } var lastFollowerTs = 0; if (this.latestFollower.value) { lastFollowerTs = Date.parse(this.latestFollower.value.created_at); } body = JSON.parse(body); if (body.follows.length > 0) { this.nodecg.log.debug('Discovered ' + body.follows.length + ' followers.'); this.latestFollower.value = body.follows[0]; body.follows.reverse().map((follower) => { var parsedTs = Date.parse(follower.created_at); if (parsedTs > lastFollowerTs) { this.nodecg.sendMessage('follower', follower); } }); } setTimeout(() => { this._scheduleFollowers(); }, this.pollInterval); } ); }; module.exports = function(api) { return new Followers(api); };
JavaScript
0
@@ -65,60 +65,8 @@ cg;%0A - this.twitch = nodecg.extensions%5B'lfg-twitchapi'%5D;%0A th @@ -94,24 +94,24 @@ 'request');%0A + this.lates @@ -549,16 +549,17 @@ ?limit=5 +0 ',%0A ( @@ -1109,24 +1109,38 @@ );%0A %7D%0A%0A + try %7B%0A body = @@ -1158,16 +1158,103 @@ (body);%0A + %7D catch (error) %7B%0A this.nodecg.log.error(error);%0A return;%0A %7D%0A%0A if
8bf340db7ce134cd350ab0f64029935790ac2a65
Add format: quarters as vulgar fractions
extension.js
extension.js
const Main = imports.ui.main; const GLib = imports.gi.GLib; const ExtensionUtils = imports.misc.extensionUtils; const Me = ExtensionUtils.getCurrentExtension(); const Convenience = Me.imports.convenience; var settings; function init() { settings = Convenience.getSettings(); } var fromCodePoint = function() { var MAX_SIZE = 0x4000; var codeUnits = []; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } var result = ''; while (++index < length) { var codePoint = Number(arguments[index]); if ( !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` codePoint < 0 || // not a valid Unicode code point codePoint > 0x10FFFF || // not a valid Unicode code point Math.floor(codePoint) != codePoint // not an integer ) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { // BMP code point codeUnits.push(codePoint); } else { // Astral code point; split in surrogate halves // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } if (index + 1 == length || codeUnits.length > MAX_SIZE) { result += String.fromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; }; function overrider(lbl) { var t = lbl.get_text(); var FORMAT = settings.get_string("override-string"); var desired = FORMAT; if (FORMAT.indexOf("%") > -1) { var now = GLib.DateTime.new_now_local(); var utcnow = GLib.DateTime.new_now_utc(); if (FORMAT.indexOf("%f") > -1) { var hour = now.get_hour(); // convert from 0-23 to 1-12 if (hour > 12) { hour -= 12; } if (hour == 0) { hour = 12; } var clockFaceCodePoint = 0x1f550 + (hour - 1); var minute = now.get_minute(); if (minute >= 30) { clockFaceCodePoint += 12; } var repl; if (String.fromCodePoint) { repl = String.fromCodePoint(clockFaceCodePoint) } else { repl = fromCodePoint(clockFaceCodePoint); } desired = desired.replace(/%f/g, repl); } if (FORMAT.indexOf("%@") > -1) { var beat_time = 0 | (((utcnow.get_hour() + 1) % 24) + utcnow.get_minute() / 60 + utcnow.get_second() / 3600) * 1000 / 24; beat_time = ('000' + beat_time).slice(-3); desired = desired.replace("%@", beat_time); } desired = now.format(desired); } if (t != desired) { last = t; lbl.set_text(desired); } } var lbl, signalHandlerID, last = ""; function enable() { var sA = Main.panel._statusArea; if (!sA) { sA = Main.panel.statusArea; } if (!sA || !sA.dateMenu || !sA.dateMenu.actor) { print("Looks like Shell has changed where things live again; aborting."); return; } sA.dateMenu.actor.first_child.get_children().forEach(function(w) { // assume that the text label is the first StLabel we find. // This is dodgy behaviour but there's no reliable way to // work out which it is. if (w.get_text && !lbl) { lbl = w; } }); if (!lbl) { print("Looks like Shell has changed where things live again; aborting."); return; } signalHandlerID = lbl.connect("notify::text", overrider); last = lbl.get_text(); overrider(lbl); } function disable() { if (lbl && signalHandlerID) { lbl.disconnect(signalHandlerID); lbl.set_text(last); } }
JavaScript
0.999999
@@ -1927,16 +1927,307 @@ utc();%0A%0A + if (FORMAT.indexOf(%22%25vf%22) %3E -1) %7B%0A var quarters = Math.round(now.get_minute() / 15);%0A var vulgar_fraction = %5B%22%5Cu00B9/%5Cu2081%22, %22%5Cu00B9/%5Cu2084%22, %22%5Cu00B9/%5Cu2082%22, %22%5Cu00B3/%5Cu2084%22%5D%5Bquarters%5D;%0A desired = desired.replace(%22%25vf%22, vulgar_fraction);%0A %7D%0A
838bad24f197e18bd010b46a2e4e0672cdb39b77
Fix typo
extension.js
extension.js
var fs = require('fs'); var path = require('path'); var vscode = require('vscode'); var axios = require('axios'); var errorEx = require('error-ex'); function activate(context) { console.log('Extension "gi" is now active!'); var disposable = vscode.commands.registerCommand('extension.gi', function () { var giURL = 'https://www.gitignore.io/api/'; var giError = new errorEx('giError'); axios.get(giURL + 'list') .then(function (response) { var rawList = response.data; rawList = rawList.replace(/(\r\n|\n|\r)/gm, ","); var formattedList = rawList.split(','); const options = { ignoreFocusOut: false, placeHolder: 'Search Operating Systems, IDEs, or Programming Languages', }; vscode.window.showQuickPick(formattedList, options) .then(function (val) { if (val === undefined) { vscode.window.setStatusBarMessage('gi escaped', 3000); var err = new giError('EscapeException'); throw err; } vscode.window.setStatusBarMessage('You picked ' + val, 3000); axios.get(giURL + val) .then(function (response) { makeFile(response.data); }) .catch(function (err) { console.log(err); }); }); function makeFile(content) { const choices = [{ label: 'Overwrite', description: `Overwrite current .gitignore` }, { label: 'Append', description: 'Append to current .gitignore' }]; const options = { matchOnDescription: true, placeHolder: "A .gitignore file already exists in your current working directory. What would you like to do?" }; var giFile = path.join(vscode.workspace.rootPath, '.gitignore'); fs.access(giFile, fs.F_OK, function (err) { if (!err) { console.log('.gitinore already exits'); vscode.window.showQuickPick(choices, options) .then(function (val) { if (!val || val === undefined) { var err = new giError('EscapeException'); vscode.window.setStatusBarMessage('gi escaped', 3000); throw err; } if (val.label === 'Overwrite') { writeToFile(content, true); vscode.window.showInformationMessage('.gitignore overwritten'); return; } if (val.label === 'Append') { writeToFile(content, false); vscode.window.showInformationMessage('.gitignore appended'); return; } }); } else { console.log('.gitinore does not exit'); writeToFile(content, true); vscode.window.showInformationMessage('.gitignore created'); return; } }); function writeToFile(content, flag) { if (flag === true) { fs.writeFileSync(giFile, content, 'utf-8', function (err) { if (err) { console.log('Failed to write to .gitignore'); } else { console.log('.gitignore created'); } }); } else { var lines = content.split('\n'); lines.splice(0,2); content = lines.join('\n'); fs.appendFileSync(giFile, content, 'utf-8', function (err) { if (err) { console.log('Failed to append to .gitignore'); } else { console.log('.gitignore appended'); } }); } } } }) .catch(function (err) { console.log(err); }); }); context.subscriptions.push(disposable); } exports.activate = activate; function deactivate() { } exports.deactivate = deactivate;
JavaScript
0.999999
@@ -2482,24 +2482,25 @@ e.log('.giti +g nore already @@ -3737,16 +3737,17 @@ g('.giti +g nore doe
932aba59fb6ed88e22afcf4183ea73a69321ab16
Clear message textbox after message is sent.
resources/chat-client/client.js
resources/chat-client/client.js
var CHAT_SERVER = "http://localhost:7000" var DEFAULT_USERNAME = "Guest"; $(document).ready(function(){ var socket = io.connect(CHAT_SERVER); socket.on('welcome', showGreetings); socket.on('message', showIncomingMessage); socket.on('info', showSystemInfo); addWaterMark(); sendButtonOnClick(); changeButtonOnClick(); function showGreetings(msg){ $("#title").text(msg['greetings']); } function showIncomingMessage(msg){ $("#messages").append("<div class='in-message'>" + msg['msgOwner'] + ": " + msg['msgContent'] + "</div>"); } function addWaterMark(){ $("#outgoing-message").watermark("Enter your message here"); } function sendButtonOnClick(){ $("#send").click(function(){ var msg = $("#outgoing-message").val(); showOutgoingMessage(msg); socket.emit('message', msg); }); } function showOutgoingMessage(msg){ $("#messages").append("<div class='out-message'>Me: " + msg + "</div>"); } function showSystemInfo(msg){ $("#messages").append("<div class='info-message'>" + msg['msgOwner'] + ": " + msg['msgContent'] + "</div>"); } function changeButtonOnClick(){ $("#change").click(function(){ var username = $("#username").val(); if(!username) username = DEFAULT_USERNAME; registerUsername(username); }); } function registerUsername(username){ socket.emit('user-join', username); } });
JavaScript
0
@@ -797,24 +797,62 @@ ssage(msg);%0A + $(%22#outgoing-message%22).val('');%0A socket
0e13c8bec06ad6213ac7450d1feb52f8263cc3b8
Increase invocation payload limit to 6 mb
src/lambda/routes/invocations/invocationsRoute.js
src/lambda/routes/invocations/invocationsRoute.js
import { Buffer } from 'node:buffer' import InvocationsController from './InvocationsController.js' const { parse } = JSON // https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html export default function invocationsRoute(lambda, options) { const invocationsController = new InvocationsController(lambda) return { async handler(request, h) { const { headers, params: { functionName }, payload, } = request const _headers = new Headers(headers) const clientContextHeader = _headers.get('x-amz-client-context') const invocationType = _headers.get('x-amz-invocation-type') // default is undefined let clientContext // check client context header was set if (clientContextHeader) { const clientContextBuffer = Buffer.from(clientContextHeader, 'base64') clientContext = parse(clientContextBuffer.toString('utf-8')) } // check if payload was set, if not, default event is an empty object const event = payload.length > 0 ? parse(payload.toString('utf-8')) : {} const invokeResults = await invocationsController.invoke( functionName, invocationType, event, clientContext, ) // Return with correct status codes let resultPayload = '' let statusCode = 200 let functionError = null if (invokeResults) { const isPayloadDefined = typeof invokeResults.Payload !== 'undefined' resultPayload = isPayloadDefined ? invokeResults.Payload : '' statusCode = invokeResults.StatusCode || 200 functionError = invokeResults.FunctionError || null } const response = h.response(resultPayload).code(statusCode) if (functionError) { // AWS Invoke documentation is wrong. The header for error type is // 'x-amzn-ErrorType' in production, not 'X-Amz-Function-Error' response.header('x-amzn-ErrorType', functionError) } if (invokeResults && invokeResults.UnhandledError) { response.header('X-Amz-Function-Error', 'Unhandled') } return response }, method: 'POST', options: { cors: options.corsConfig, payload: { // allow: ['binary/octet-stream'], defaultContentType: 'binary/octet-stream', // request.payload will be a raw buffer parse: false, }, tags: ['api'], }, path: '/2015-03-31/functions/{functionName}/invocations', } }
JavaScript
0.000002
@@ -2307,16 +2307,153 @@ tream',%0A + // Set maximum size to 6 MB to match maximum invocation payload size in synchronous responses%0A maxBytes: 1024 * 1024 * 6,%0A
c6d4e632c5eccd685b783204f46f6ec3ba709744
Refactor executeFkQueries
lib/execute-fk-queries.js
lib/execute-fk-queries.js
var _ = require('lodash'); var bluebird = require('bluebird'); var util = require('./util'); module.exports = function resolveQueryObjects(config, knexInst) { var pendingQueries = []; _.forIn(config, function(entries, table) { entries = config[table] = util.asArray(entries); entries.forEach(function(entry, index) { _.forIn(entry, function(colValue, colName, record) { if (isQueryObject(colValue)) { var constraints = colValue; pendingQueries.push( knexInst(constraints.from) .where(constraints.where) .then(function(result) { if (result.length > 1) { var where = JSON.stringify(constraints); throw new Error(where + ' matches >1 possible FK!'); } else { record[colName] = result[0].id; } }) ); } }); }); }); return pendingQueries; }; function isQueryObject(value) { return _(value).has('from', 'where') }
JavaScript
0.000001
@@ -85,16 +85,26 @@ /util'); +%0Avar knex; %0A%0Amodule @@ -189,16 +189,35 @@ es = %5B%5D; +%0A knex = knexInst; %0A%0A _.fo @@ -217,18 +217,20 @@ %0A _.for -In +Each (config, @@ -242,56 +242,35 @@ tion -(entries, table) %7B%0A entries = config%5Btable%5D = + handleTable(entries) %7B%0A uti @@ -291,22 +291,8 @@ ies) -;%0A%0A entries .for @@ -308,54 +308,200 @@ tion -(entry, index) %7B%0A _.forIn(entry, function + (entry) %7B%0A var promises = _.map(entry, resolveSingleValue);%0A pendingQueries = pendingQueries.concat(promises);%0A %7D);%0A %7D);%0A return pendingQueries;%0A%7D;%0A%0Afunction resolveSingleValue (col @@ -520,24 +520,17 @@ me, -record) %7B%0A +entry) %7B%0A if @@ -566,120 +566,35 @@ - - var constraints = colValue;%0A pendingQueries.push(%0A knexInst(constraints.from)%0A +return knex(colValue.from)%0A @@ -604,25 +604,22 @@ where(co -nstraints +lValue .where)%0A @@ -624,24 +624,16 @@ )%0A - - .then(fu @@ -657,24 +657,16 @@ - - if (resu @@ -692,24 +692,16 @@ - - var wher @@ -725,28 +725,17 @@ y(co -nstraints);%0A +lValue);%0A @@ -793,24 +793,16 @@ FK!');%0A - @@ -824,22 +824,13 @@ - - record +entry %5Bcol @@ -863,109 +863,25 @@ - - %7D%0A %7D)%0A );%0A %7D%0A %7D);%0A %7D);%0A %7D);%0A return pendingQueries;%0A%7D; +%7D%0A %7D);%0A %7D%0A%7D %0A%0Afu
1a4545a3bf9f1da8aa24ccb46c25404b60b51949
add domcomplete from xhr to beacon
plugins/navtiming.js
plugins/navtiming.js
/* * Copyright (c), Buddy Brewer. */ /** \file navtiming.js Plugin to collect metrics from the W3C Navigation Timing API. For more information about Navigation Timing, see: http://www.w3.org/TR/navigation-timing/ */ (function() { // First make sure BOOMR is actually defined. It's possible that your plugin is loaded before boomerang, in which case // you'll need this. BOOMR = BOOMR || {}; BOOMR.plugins = BOOMR.plugins || {}; if (BOOMR.plugins.NavigationTiming) { return; } // A private object to encapsulate all your implementation details var impl = { complete: false, xhr_done: function(edata) { var w = BOOMR.window, res, data = {}, k; if (!edata) { return; } if (edata.data) { edata = edata.data; } if (edata.url && w.performance && w.performance.getEntriesByName) { res = w.performance.getEntriesByName(edata.url); if(res && res.length > 0) { res = res[0]; data = { nt_red_st: res.redirectStart, nt_red_end: res.redirectEnd, nt_fet_st: res.fetchStart, nt_dns_st: res.domainLookupStart, nt_dns_end: res.domainLookupEnd, nt_con_st: res.connectStart, nt_con_end: res.connectEnd, nt_req_st: res.requestStart, nt_res_st: res.responseStart, nt_res_end: res.responseEnd }; if (res.secureConnectionStart) { // secureConnectionStart is OPTIONAL in the spec data.nt_ssl_st = res.secureConnectionStart; } for(k in data) { if (data.hasOwnProperty(k) && data[k]) { data[k] += w.performance.timing.navigationStart; } } } } if (edata.timing) { res = edata.timing; if (!data.nt_req_st) { data.nt_req_st = res.requestStart; } if (!data.nt_res_st) { data.nt_res_st = res.responseStart; } if (!data.nt_res_end) { data.nt_res_end = res.responseEnd; } data.nt_domint = res.domInteractive; data.nt_load_st = res.loadEventEnd; data.nt_load_end = res.loadEventEnd; } for(k in data) { if (data.hasOwnProperty(k) && !data[k]) { delete data[k]; } } BOOMR.addVar(data); try { impl.addedVars.push.apply(impl.addedVars, Object.keys(data)); } catch(ignore) {} this.complete = true; BOOMR.sendBeacon(); }, done: function() { var w = BOOMR.window, p, pn, pt, data; if(this.complete) { return this; } impl.addedVars = []; p = w.performance || w.msPerformance || w.webkitPerformance || w.mozPerformance; if(p && p.timing && p.navigation) { BOOMR.info("This user agent supports NavigationTiming.", "nt"); pn = p.navigation; pt = p.timing; data = { nt_red_cnt: pn.redirectCount, nt_nav_type: pn.type, nt_nav_st: pt.navigationStart, nt_red_st: pt.redirectStart, nt_red_end: pt.redirectEnd, nt_fet_st: pt.fetchStart, nt_dns_st: pt.domainLookupStart, nt_dns_end: pt.domainLookupEnd, nt_con_st: pt.connectStart, nt_con_end: pt.connectEnd, nt_req_st: pt.requestStart, nt_res_st: pt.responseStart, nt_res_end: pt.responseEnd, nt_domloading: pt.domLoading, nt_domint: pt.domInteractive, nt_domcontloaded_st: pt.domContentLoadedEventStart, nt_domcontloaded_end: pt.domContentLoadedEventEnd, nt_domcomp: pt.domComplete, nt_load_st: pt.loadEventStart, nt_load_end: pt.loadEventEnd, nt_unload_st: pt.unloadEventStart, nt_unload_end: pt.unloadEventEnd }; if (pt.secureConnectionStart) { // secureConnectionStart is OPTIONAL in the spec data.nt_ssl_st = pt.secureConnectionStart; } if (pt.msFirstPaint) { // msFirstPaint is IE9+ http://msdn.microsoft.com/en-us/library/ff974719 data.nt_first_paint = pt.msFirstPaint; } BOOMR.addVar(data); try { impl.addedVars.push.apply(impl.addedVars, Object.keys(data)); } catch(ignore) {} } // XXX Inconsistency warning. msFirstPaint above is in milliseconds while // firstPaintTime below is in seconds.microseconds. The server needs to deal with this. // This is Chrome only, so will not overwrite nt_first_paint above if(w.chrome && w.chrome.loadTimes) { pt = w.chrome.loadTimes(); if(pt) { data = { nt_spdy: (pt.wasFetchedViaSpdy?1:0), nt_first_paint: pt.firstPaintTime }; BOOMR.addVar(data); try { impl.addedVars.push.apply(impl.addedVars, Object.keys(data)); } catch(ignore) {} } } this.complete = true; BOOMR.sendBeacon(); }, clear: function(vars) { if (impl.addedVars && impl.addedVars.length > 0) { BOOMR.removeVar(impl.addedVars); impl.addedVars = []; } this.complete = false; } }; BOOMR.plugins.NavigationTiming = { init: function() { if (!impl.initialized) { // we'll fire on whichever happens first BOOMR.subscribe("page_ready", impl.done, null, impl); BOOMR.subscribe("xhr_load", impl.xhr_done, null, impl); BOOMR.subscribe("page_unload", impl.done, null, impl); BOOMR.subscribe("onbeacon", impl.clear, null, impl); impl.initialized = true; } return this; }, is_complete: function() { return impl.complete; } }; }());
JavaScript
0
@@ -1857,16 +1857,54 @@ active;%0A +%09%09%09data.nt_domcomp = res.domComplete;%0A %09%09%09data.
296796c92f16a5081dbf7ad8468dfb6c2b8bd3bc
tweak reloadPage, add user message stuff
htdocs/components/02_LayoutManager.js
htdocs/components/02_LayoutManager.js
// $Revision$ Ensembl.LayoutManager = new Base(); Ensembl.LayoutManager.extend({ constructor: null, /** * Creates events on elements outside of the domain of panels */ initialize: function () { this.id = 'LayoutManager'; Ensembl.EventManager.register('reloadPage', this, this.reloadPage); Ensembl.EventManager.register('validateForms', this, this.validateForms); Ensembl.EventManager.register('makeZMenu', this, this.makeZMenu); $('#local-tools').show(); $('.modal_link').show().live('click', function () { // If ajax is not enabled, make popup config window // If ajax is enabled, modalOpen is triggered. If it doesn't returns true then there's no ModalContainer panel, so make popup config window if (Ensembl.ajax != 'enabled' || !Ensembl.EventManager.trigger('modalOpen', this)) { var name = 'cp_' + window.name; var w = window.open(this.href, name.replace(/cp_cp_/, 'cp_'), 'width=950,height=500,resizable,scrollbars'); w.focus(); } return false; }); $('.popup').live('click', function () { var w = window.open(this.href, 'popup_' + window.name, 'width=950,height=500,resizable,scrollbars'); w.focus(); return false; }); $('a[rel="external"]').live('click', function () { this.target = '_blank'; }); // using livequery plugin because .live doesn't support blur, focus, mouseenter, mouseleave, change or submit in IE $('form.check').livequery('submit', function () { var form = $(this); var rtn = form.parents('#modal_panel').length ? Ensembl.EventManager.trigger('modalFormSubmit', form) : Ensembl.FormValidator.submit(form); form = null; return rtn; }); $(':input', 'form.check').live('keyup', function () { Ensembl.FormValidator.check($(this)); }).livequery('change', function () { Ensembl.FormValidator.check($(this)); }).livequery('blur', function () { // IE is stupid, so we need blur as well as change if you select from browser-stored values Ensembl.FormValidator.check($(this)); }).each(function () { Ensembl.FormValidator.check($(this)); }); // For non ajax support - popup window close button var close = $('.popup_close'); if (close.length) { if ($('input.panel_type[value=Configurator]').length) { close.html('Save and close').click(function () { if (Ensembl.EventManager.trigger('updateConfiguration') || window.location.search.match('reset=1')) { window.open(Ensembl.replaceTimestamp(this.href), window.name.replace(/^cp_/, '')); // Reload the main page } window.close(); return false; }); } else { close.hide(); } } close = null; // Close modal window if the escape key is pressed $(document).keyup(function (event) { if (event.keyCode == 27) { Ensembl.EventManager.trigger('modalClose'); } }).mouseup(function (e) { Ensembl.EventManager.trigger('dragStop', e); }); }, reloadPage: function () { var date = new Date(); var time = date.getTime() + date.getMilliseconds() / 1000; var url = window.location.href.replace(/&/g, ';').replace(/#.*$/g, '').replace(/\?time=[^;]+;?/g, '?').replace(/;time=[^;]+;?/g, ';').replace(/[\?;]$/g, ''); window.location = url + (url.match(/\?/) ? ';' : '?') + 'time=' + time; }, validateForms: function (context) { $('form.check', context).find(':input').each(function () { Ensembl.FormValidator.check($(this)); }); }, makeZMenu: function (id, params) { $('<table class="zmenu" id="' + id + '" style="display:none">' + ' <thead>' + ' <tr><th class="caption" colspan="2"><span class="close">X</span><span class="title"></span></th></tr>' + ' </thead>' + ' <tbody></tbody>' + '</table>').draggable({ handle: 'thead' }).appendTo('body'); Ensembl.EventManager.trigger('addPanel', id, 'ZMenu', undefined, undefined, params, 'showExistingZMenu'); } });
JavaScript
0
@@ -203,20 +203,16 @@ ion () %7B - %0A thi @@ -3198,299 +3198,862 @@ ;%0A -%7D,%0A %0A + -reloadPage: function () %7B%0A var date = new Date( + var userMessage = unescape(Ensembl.cookie.get('user_message'));%0A %0A if (userMessage) %7B%0A userMessage = userMessage.split('%5Cn' );%0A + -var time = date.getTime() + date.getMilliseconds() / 1000;%0A var url = window.location.href.replace(/&/g, ';').replace(/#.*$/g, '').replace(/%5C?time=%5B%5E;%5D+;?/g, '?').replace(/;time=%5B%5E;%5D+;?/g, ';').replace(/%5B%5C?;%5D$/g, '' +%0A $('%3Cdiv class=%22hint%22 style=%22margin: 10px 25%25;%22%3E' +%0A ' %3Ch3%3E%3Cimg src=%22/i/close.gif%22 alt=%22Hide hint panel%22 title=%22Hide hint panel%22 /%3E' + userMessage%5B0%5D + '%3C/h3%3E' +%0A ' %3Cp%3E' + userMessage%5B1%5D + '%3C/p%3E' +%0A '%3C/div%3E').prependTo('#main').find('h3 img, a').click(function () %7B%0A $(this).parents('div.hint').remove();%0A Ensembl.cookie.set('user_message', '', -1);%0A %7D);%0A %7D%0A %7D,%0A %0A reloadPage: function (args) %7B%0A if (typeof args == 'string') %7B%0A Ensembl.EventManager.triggerSpecific('updatePanel', args);%0A %7D else if (typeof args == 'object') %7B%0A for (var i in args) %7B%0A Ensembl.EventManager.triggerSpecific('updatePanel', i );%0A + %7D %0A + %7D else %7B%0A @@ -4074,61 +4074,61 @@ n = -url + (url.match(/%5C?/) ? ';' : '?') + 'time=' + time; +Ensembl.replaceTimestamp(window.location.href);%0A %7D %0A %7D
1618d999b7b586edd2f6a841bb04c88ab2f547df
remove unused $harfile variable
filmstrip.js
filmstrip.js
<?php /* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ require_once("utils.php"); $gPageid = ( array_key_exists('pageid', $_GET) ? $_GET['pageid'] : "" ); $query = "select harfile, url, wptid, wptrun, onLoad, renderStart from $gPagesTable where pageid=$gPageid;"; $result = doQuery($query); $row = mysql_fetch_assoc($result); $harfile = $row['harfile']; $url = $row['url']; $wptid = $row['wptid']; $wptrun = $row['wptrun']; $onLoad = $row['onLoad']; $interval = ( $onLoad > 15000 ? 5000 : ( $onLoad > 4000 ? 1000 : ( $onLoad > 1000 ? 500 : 100 ) ) ); $renderStart = $row['renderStart']; $xmlurl = "http://httparchive.webpagetest.org/xmlResult.php?test=$wptid"; $xmlstr = file_get_contents($xmlurl); $xml = new SimpleXMLElement($xmlstr); $frames = $xml->data->run[($wptrun - 1)]->firstView->videoFrames; $aTimes = array(); foreach($frames->frame as $frame) { $time = floatval($frame->time) * 1000; $aTimes[$time] = true; } $sTh = ""; $sTd = ""; $aMatches = array(); $url = ""; $pattern = '/([0-9][0-9])([0-9][0-9])([0-9][0-9])_(.*)/'; if ( preg_match($pattern, $wptid, $aMatches) ) { $url = "http://httparchive.webpagetest.org/results/" . $aMatches[1] . "/" . $aMatches[2] . "/" . $aMatches[3] . "/" . $aMatches[4] . "/video_$wptrun/frame_"; } $lastFrameTime = 0; for ( $i = 0; $i < ($onLoad+100); $i += 100 ) { $sTh .= "<th id=th$i style='display: none;'>" . ($i/1000) . "s</th> "; //$border = ""; $class = "thumb"; if ( array_key_exists($i, $aTimes) ) { $lastFrameTime = $i; //$border = "style='border: 3px solid #FEB301;'"; $class = "thumb changed"; } $f = "0000" . ($lastFrameTime/100); $f = substr($f, strlen($f)-4); $sTd .= "<td id=td$i class='$class' style='display: none;'><a target='_blank' href='$url$f.jpg'><img width=200 height=140 id='http://httparchive.webpagetest.org/thumbnail.php?test=$wptid&width=200&file=video_$wptrun/frame_$f.jpg'></a></td>"; } ?> var sTh = "<?php echo $sTh ?>"; var sTd = "<?php echo $sTd ?>"; document.getElementById('videoDiv').innerHTML = "<table id='video'><tr>" + sTh + "</tr><tr>" + sTd + "</tr></table>"; showInterval(<?php echo $interval ?>);
JavaScript
0.000006
@@ -681,17 +681,8 @@ lect - harfile, url @@ -828,36 +828,8 @@ t);%0A -$harfile = $row%5B'harfile'%5D;%0A $url
5224e0d9e48613b6c7b455e4f846738150d828f3
Improve LiteCreditCardInput field navigations
src/LiteCreditCardInput.js
src/LiteCreditCardInput.js
import React, { Component, PropTypes } from "react"; import { View, Text, TextInput, StyleSheet, Image, LayoutAnimation, TouchableOpacity, } from "react-native"; import Icons from "./Icons"; import CCInput from "./CCInput"; import { InjectedProps } from "./connectToState"; const INFINITE_WIDTH = 1000; const s = StyleSheet.create({ container: { paddingLeft: 10, paddingRight: 10, flexDirection: "row", alignItems: "center", overflow: "hidden", }, icon: { width: 48, height: 40, resizeMode: "contain", }, expanded: { flex: 1, }, hidden: { width: 0, }, leftPart: { overflow: "hidden", }, rightPart: { overflow: "hidden", flexDirection: "row", marginLeft: 10, }, last4: { flex: 1, justifyContent: "center", }, numberInput: { width: INFINITE_WIDTH, }, expiryInput: { width: 80, }, cvcInput: { width: 80, }, }); /* eslint react/prop-types: 0 */ // https://github.com/yannickcr/eslint-plugin-react/issues/106 export default class LiteCreditCardInput extends Component { static propTypes = { ...InjectedProps, placeholders: PropTypes.object, inputStyle: Text.propTypes.style, validColor: PropTypes.string, invalidColor: PropTypes.string, placeholderColor: PropTypes.string, }; componentDidMount = () => this._focus(this.props.focused); componentWillReceiveProps = newProps => { if (this.props.focused !== newProps.focused) this._focus(newProps.focused); }; _focusNumber = () => this._focus("number"); _focus = field => { if (!field) return; this.refs[field].focus(); LayoutAnimation.easeInEaseOut(); } _inputProps = field => { const { inputStyle, validColor, invalidColor, placeholderColor, placeholders, values, status, onFocus, onChange, onBecomeEmpty, onBecomeValid, } = this.props; return { inputStyle, validColor, invalidColor, placeholderColor, ref: field, field, placeholder: placeholders[field], value: values[field], status: status[field], onFocus, onChange, onBecomeEmpty, onBecomeValid, }; }; _iconToShow = () => { const { focused, values: { type } } = this.props; if (focused === "cvc" && type === "american-express") return "cvc_amex"; if (focused === "cvc") return "cvc"; if (type) return type; return "placeholder"; } render() { const { focused, values: { number }, inputStyle } = this.props; const showRightPart = focused && focused !== "number"; return ( <View style={s.container}> <View style={[ s.leftPart, showRightPart ? s.hidden : s.expanded, ]}> <CCInput {...this._inputProps("number")} containerStyle={s.numberInput} /> </View> <Image style={s.icon} source={{ uri: Icons[this._iconToShow()] }} /> <View style={[ s.rightPart, showRightPart ? s.expanded : s.hidden, ]}> <TouchableOpacity onPress={this._focusNumber} style={s.last4}> <View pointerEvents={"none"}> <TextInput editable={false} underlineColorAndroid={"transparent"} style={[inputStyle]} value={ number ? number.substr(number.length - 4, 4) : "" } /> </View> </TouchableOpacity> <CCInput {...this._inputProps("expiry")} containerStyle={s.expiryInput} /> <CCInput {...this._inputProps("cvc")} containerStyle={s.cvcInput} /> </View> </View> ); } } LiteCreditCardInput.defaultProps = { placeholders: { number: "1234 5678 1234 5678", expiry: "MM/YY", cvc: "CVC", }, validColor: "", invalidColor: "red", placeholderColor: "gray", };
JavaScript
0
@@ -1567,16 +1567,62 @@ umber%22); +%0A _focusExpiry = () =%3E this._focus(%22expiry%22); %0A%0A _foc @@ -2867,32 +2867,126 @@ %3C/View%3E%0A + %3CTouchableOpacity onPress=%7BshowRightPart ? this._focusNumber : this._focusExpiry %7D%3E%0A %3CImage s @@ -2999,16 +2999,18 @@ s.icon%7D%0A + @@ -3056,24 +3056,52 @@ ow()%5D %7D%7D /%3E%0A + %3C/TouchableOpacity%3E%0A %3CVie
0f2db4b35ab4b7bae25807cdb6deabfb7c435a54
remove callback from finalize. old code.
lib/modules/json/index.js
lib/modules/json/index.js
/** * node-archiver * * Copyright (c) 2012-2014 Chris Talkington, contributors. * Licensed under the MIT license. * https://github.com/ctalkington/node-archiver/blob/master/LICENSE-MIT */ var inherits = require('util').inherits; var Transform = require('readable-stream').Transform; var crc32 = require('buffer-crc32'); var util = require('../../util'); var Json = module.exports = function(options) { options = this.options = util.defaults(options, {}); Transform.call(this, options); this.supports = { directory: true }; this.files = []; }; inherits(Json, Transform); Json.prototype._transform = function(chunk, encoding, callback) { callback(null, chunk); }; Json.prototype._writeStringified = function() { var fileString = JSON.stringify(this.files); this.write(fileString); }; Json.prototype.append = function(source, data, callback) { var self = this; data.crc32 = 0; function onend(err, sourceBuffer) { if (err) { callback(err); return; } data.size = sourceBuffer.length || 0; data.crc32 = crc32.unsigned(sourceBuffer); self.files.push(data); callback(null, data); } if (data.sourceType === 'buffer') { onend(null, source); } else if (data.sourceType === 'stream') { util.collectStream(source, onend); } }; Json.prototype.finalize = function(callback) { callback = callback || function() {}; this._writeStringified(); this.end(); callback(); };
JavaScript
0
@@ -1346,60 +1346,11 @@ ion( -callback) %7B%0A callback = callback %7C%7C function() %7B%7D;%0A +) %7B %0A t @@ -1374,17 +1374,16 @@ fied();%0A -%0A this.e @@ -1391,22 +1391,7 @@ d(); -%0A%0A callback(); %0A%7D;
12a083ac75b3f218126e7ad90c7da32685bb3270
Make promise compatible with Angular 1.6
lib/net/BaseHttpClient.js
lib/net/BaseHttpClient.js
"use strict"; var Parser = require('./Parser'), Methods = require('./Methods'), UrlNormalizer = require('./UrlNormalizer'), inherits = require('inherits'), HttpClient = require('./HttpClient'), Promise = require('bluebird'), _ = require('lodash'); var BaseHttpClient = function (http) { this._http = http; }; inherits(BaseHttpClient, HttpClient); BaseHttpClient.prototype.unwrapResponse = function () { return false; }; BaseHttpClient.prototype.credentialsRequestsEnabled = function () { return false; }; BaseHttpClient.prototype.get = function (url, parser, headers) { return this._handleRequest(url, Methods.GET, null, parser, headers); }; BaseHttpClient.prototype.post = function (url, data, parser, headers) { return this._handleRequest(url, Methods.POST, data, parser, headers); }; BaseHttpClient.prototype.put = function (url, data, parser, headers) { return this._handleRequest(url, Methods.PUT, data, parser, headers); }; BaseHttpClient.prototype.delete = function (url, parser, headers) { return this._handleRequest(url, Methods.DELETE, null, parser, headers); }; BaseHttpClient.prototype.jsonp = function (url, parser, headers) { url = UrlNormalizer.normalizeJsonp(url); return this._handleRequest(url, Methods.JSONP, null, parser, headers); }; BaseHttpClient.prototype.multipart = function (url, data, parser, headers) { return this._handleRequest(url, Methods.MULTIPART, data, parser, headers); }; BaseHttpClient.prototype._handleRequest = function (url, method, data, parser, headers, plainResponse) { return new Promise(_.bind(function (resolve, reject) { parser = parser || new Parser(); var unwrapResponse = this.unwrapResponse(); this._getNetworkPromise(url, method, data, headers, plainResponse) .success(function (response, status, headers, config) { if (!unwrapResponse) resolve(parser.parse(response)); else resolve([parser.parse(response), status, headers, config]); }) .error(function (error, status, headers, config) { if (!unwrapResponse) reject(error); else reject({data: error, status: status, headers: headers, config: config}); }); }, this)); }; BaseHttpClient.prototype._getNetworkPromise = function (url, method, data, headers, plainResponse) { var config = { headers: headers, withCredentials: this.credentialsRequestsEnabled() }; if (plainResponse) config.transformResponse = undefined; if (method === Methods.MULTIPART) { config.transformRequest = angular.identity; config.headers = config.headers || {}; config.headers['Content-Type'] = undefined; } switch (method) { case Methods.GET: return this._http.get(url, config); case Methods.POST: case Methods.MULTIPART: return this._http.post(url, data, config); case Methods.PUT: return this._http.put(url, data, config); case Methods.DELETE: return this._http.delete(url, config); case Methods.JSONP: return this._http.jsonp(url, config); } }; module.exports = BaseHttpClient;
JavaScript
0
@@ -1828,15 +1828,12 @@ . -success +then (fun @@ -1851,33 +1851,8 @@ onse -, status, headers, config ) %7B%0A @@ -1937,16 +1937,21 @@ response +.data ));%0A @@ -2021,28 +2021,60 @@ onse -), status, headers, +.data), response.status, response.headers, response. conf @@ -2107,21 +2107,21 @@ . -error +catch (functio @@ -2132,33 +2132,8 @@ rror -, status, headers, config ) %7B%0A @@ -2259,16 +2259,22 @@ (%7Bdata: +error. error, s @@ -2280,16 +2280,22 @@ status: +error. status, @@ -2295,32 +2295,38 @@ tatus, headers: +error. headers, config: @@ -2326,16 +2326,22 @@ config: +error. config%7D)
a930977d579f7109da37cc0ca1d837a46259940e
Update output_hep.js (#103)
lib/outputs/output_hep.js
lib/outputs/output_hep.js
var abstract_udp = require('./abstract_udp'), hepjs = require('hep-js'), util = require('util'), logger = require('log4node'); function OutputHep() { abstract_udp.AbstractUdp.call(this); this.mergeConfig({ name: 'Udp', }); this.mergeConfig(this.serializer_config()); this.mergeConfig({ name: 'HEP/EEP Server', optional_params: ['hep_id', 'hep_pass', 'hep_cid', 'hep_type', 'src_ip', 'src_port', 'dst_ip', 'dst_port', 'hep_payload_type', 'hep_ip_family', 'hep_protocol', 'transaction_type'], default_values: { host: '127.0.0.1', port: 9063, hep_id: '2001', hep_pass: 'MyHep', hep_cid: '#{correlation_id}', hep_type: 100, hep_payload_type: 1, hep_ip_family: 1, hep_protocol: 17, src_ip: '127.0.0.1', src_port: '0', dst_ip: '127.0.0.2', dst_port: '0', hep_timefield: false }, }); } util.inherits(OutputHep, abstract_udp.AbstractUdp); OutputHep.prototype.preHep = function(data) { try { // IF HEP JSON if (data.rcinfo && data.payload) { logger.debug('PRE-PACKED HEP JSON!'); data.rcinfo.captureId = this.hep_id; data.rcinfo.capturePass = this.hep_pass; return hepjs.encapsulate(data.payload,data.rcinfo); }; // Default HEP RCINFO var hep_proto = { 'type': 'HEP', 'version': 3, 'payload_type': this.hep_payload_type, 'proto_type': this.hep_type, 'captureId': this.hep_id, 'capturePass': this.hep_pass, 'ip_family': this.hep_ip_family, 'protocol': this.hep_protocol }; var datenow = new Date(); hep_proto.time_sec = data.time_sec || Math.floor(datenow.getTime() / 1000); hep_proto.time_usec = data.time_usec || datenow.getMilliseconds() * 1000; // Build HEP3 w/ null network parameters - TBD configurable hep_proto.srcIp = data.srcIp || this.src_ip; hep_proto.dstIp = data.dstIp || this.dst_ip; hep_proto.srcPort = data.srcPort || this.src_port; hep_proto.dstPort = data.dstPort || this.dst_port; // pair correlation id from pattern hep_proto.correlation_id = data.correlation_id || ''; // Optional Transaction Type if (this.transaction_type) { hep_proto.transaction_type = this.transaction_type; } if (data.payload) { // Pack HEP3 return hepjs.encapsulate(JSON.stringify(data.payload),hep_proto); } else { // Pack HEP3 Log Type fallback hep_proto.payload_type = 100; return hepjs.encapsulate(JSON.stringify(data),hep_proto); } } catch(e) { logger.error('PREHEP ERROR:',e); } }; OutputHep.prototype.formatPayload = function(data, callback) { if (data) callback(this.preHep(data)); }; OutputHep.prototype.to = function() { return 'HEP udp to ' + this.host + ':' + this.port; }; exports.create = function() { return new OutputHep(); };
JavaScript
0
@@ -1209,16 +1209,31 @@ psulate( +JSON.stringify( data.pay @@ -1236,16 +1236,17 @@ .payload +) ,data.rc
6d13b64c7891795ce1d5d390b5fd9da11e36c64b
Fix Olio upgrade.
mingle.http/test/http.t.js
mingle.http/test/http.t.js
require('proof')(3, prove) function prove (okay, callback) { var Destructible = require('destructible') var destructible = new Destructible('test/http.t') var path = require('path') destructible.completed.wait(callback) var cadence = require('cadence') var UserAgent = require('vizsla') var Mock = require('olio/mock') cadence(function (async) { async(function () { destructible.durable('mock', Mock, { socket: path.join(__dirname, 'socket'), children: { http: { path: path.resolve(__dirname, '../olio.js'), properties: { port: 8888, iface: '127.0.0.1' } }, mingle: { path: path.resolve(__dirname, './mingle.js'), properties: {} } } }, async()) }, function () { var ua = new UserAgent async(function () { ua.fetch({ url: 'http://127.0.0.1:8888/', parse: 'text', raise: true }, async()) }, function (body) { okay(body, 'Mingle API\n', 'index') ua.fetch({ url: 'http://127.0.0.1:8888/health', parse: 'json', raise: true }, async()) }, function (body) { okay(body, { http: { occupied: 1, waiting: 0, rejecting: 0, turnstiles: 24 } }, 'health') ua.fetch({ url: 'http://127.0.0.1:8888/discover', parse: 'json', raise: true }, async()) }, function (body) { okay(body, [ '127.0.0.1:8080' ], 'discover') }) }) })(destructible.durable('test')) }
JavaScript
0
@@ -157,17 +157,16 @@ ttp.t')%0A -%0A var @@ -530,15 +530,19 @@ c -hildren +onstituents : %7B%0A
801c8c3119bd5073615312799cd8ca217c8dd3de
fix delim
StringCalculator/stringcalculator.js
StringCalculator/stringcalculator.js
"use strict" var assert = require('assert'); var add = function(str) { var delimiter = customDelimiter(str); if (delimiter) { str = str.substr(str.indexOf('\n')); } else { delimiter = ','; } str = str.replace('\n',delimiter); var numbers = str.split(delimiter); return numbers.reduce(function(x,y) { return x + (y|0); }, 0); }; var StringCalculator = function() { this.add = add; return this; }; var customDelimiter = function(str) { if (str.indexOf('//') === 0) { return str[2]; } }; describe('string calculator', function() { describe('simple add', function() { var calculator = new StringCalculator(); it('should return 0 for empty string', function() { assert.equal(0, calculator.add('')); }); it('should return a single digit', function() { assert.equal(99, calculator.add('99')); }); it('should add numbers separaetd by commas', function() { assert.equal(101, calculator.add('77,24')); }); it('should add a variable number of commas', function() { assert.equal(10, calculator.add('1,2,3,4')); }); it('should also consider \\n a separate', function() { assert.equal(10, calculator.add('6\n4')); }); it('should identify custom delimiters', function() { var delim = customDelimiter('//q\n1q2'); assert.equal('q', delim.separator); assert.equal('1q2', delim.line); }); it('should return default separator', function() { var delim = customDelimiter('1,2'); assert.equal(',', delim.separator); assert.equal('1,2', delim.line); }); it('should add using the custom delimiter', function() { assert.equal(3, calculator.add('//q\n1q2')); }); }); });
JavaScript
0.000001
@@ -512,14 +512,84 @@ urn -str%5B2%5D +%7B%0A line: str.substr(str.indexOf('%5Cn')+1),%0A separator: str%5B2%5D%0A %7D ;%0A
5540e14fad01cf9567631dd453a41fef69e8de1c
update reload command to allow all extendables
src/commands/System/reload.js
src/commands/System/reload.js
const { Command } = require('klasa'); module.exports = class extends Command { constructor(...args) { super(...args, { aliases: ['r'], permLevel: 10, description: "Reloads the klasa piece, if it's been updated or modified.", // eslint-disable-next-line max-len usage: '<inhibitors|finalizers|monitors|languages|providers|events|commands|Inhibitor:inhibitor|Extendable:extendable|Finalizer:finalizer|Monitor:monitor|Language:language|Provider:provider|Event:event|Command:cmd>' }); } async run(msg, [piece]) { if (typeof piece === 'string') return this.client[piece].loadAll().then(() => msg.sendMessage(msg.language.get('COMMAND_RELOAD_ALL', piece))); return piece.reload() .then(itm => msg.sendMessage(msg.language.get('COMMAND_RELOAD', itm.type, itm.name))) .catch(err => { this.client[`${piece.type}s`].set(piece); msg.sendMessage(`❌ ${err}`); }); } };
JavaScript
0
@@ -350,16 +350,28 @@ ommands%7C +extendables%7C Inhibito
8dde8f4c8bec664610082e7585011c5131fdd7e8
Update line-endings.js
lib/rules/line-endings.js
lib/rules/line-endings.js
// Copyright 2014 SAP SE. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http: //www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific // language governing permissions and limitations under the License. /** * @fileoverview Check for correct line endings * @author Christoph Kraemer <[email protected]> */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function (context) { var config = { ending: "\\n" }; if (context.options[0]) { config.ending = context.options[0]; } return { "Program": function checkLineEndings(node) { // Get the whole source code, not for node only. var src = context.getSource(), re; switch (config.ending) { case "\\r\\n": re = /[^\r]\n|\r(?!\n)/; break; case "\\r": re = /\n/; break; default: re = /\r/; } if (re.test(src)) { context.report(node, 0, "Invalid line endings."); } } }; };
JavaScript
0.000001
@@ -1389,17 +1389,17 @@ t(node, -0 +1 , %22Inval
913988de160878b38ee739e8db16f06bbdd10be1
Prevent event handlers from mutating current iteration
src/TargetEventHandlers.js
src/TargetEventHandlers.js
import eventOptionsKey from './eventOptionsKey'; export default class TargetEventHandlers { constructor(target) { this.target = target; this.events = {}; } getEventHandlers(eventName, options) { const key = `${eventName} ${eventOptionsKey(options)}`; if (!this.events[key]) { this.events[key] = { handlers: [], handleEvent: undefined, }; } return this.events[key]; } handleEvent(eventName, options, event) { const { handlers } = this.getEventHandlers(eventName, options); handlers.forEach((handler) => { if (handler) { // We need to check for presence here because a handler function may // cause later handlers to get removed. This can happen if you for // instance have a waypoint that unmounts another waypoint as part of an // onEnter/onLeave handler. handler(event); } }); } add(eventName, listener, options) { // options has already been normalized at this point. const eventHandlers = this.getEventHandlers(eventName, options); if (eventHandlers.handlers.length === 0) { eventHandlers.handleEvent = this.handleEvent.bind(this, eventName, options); this.target.addEventListener( eventName, eventHandlers.handleEvent, options, ); } eventHandlers.handlers.push(listener); let isSubscribed = true; const unsubscribe = () => { if (!isSubscribed) { return; } isSubscribed = false; const index = eventHandlers.handlers.indexOf(listener); eventHandlers.handlers.splice(index, 1); if (eventHandlers.handlers.length === 0) { // All event handlers have been removed, so we want to remove the event // listener from the target node. if (this.target) { // There can be a race condition where the target may no longer exist // when this function is called, e.g. when a React component is // unmounting. Guarding against this prevents the following error: // // Cannot read property 'removeEventListener' of undefined this.target.removeEventListener( eventName, eventHandlers.handleEvent, options, ); } eventHandlers.handleEvent = undefined; } }; return unsubscribe; } }
JavaScript
0.999999
@@ -392,160 +392,566 @@ -%7D%0A%0A return this.events%5Bkey%5D;%0A %7D%0A%0A handleEvent(eventName, options, event) %7B%0A const %7B handlers %7D = this.getEventHandlers(eventName, options);%0A + this.events%5Bkey%5D.nextHandlers = this.events%5Bkey%5D.handlers;%0A %7D%0A%0A return this.events%5Bkey%5D;%0A %7D%0A%0A ensureCanMutateNextEventHandlers(eventName, options) %7B%0A const eventHandlers = this.getEventHandlers(eventName, options);%0A if (eventHandlers.handlers === eventHandlers.nextHandlers) %7B%0A eventHandlers.nextHandlers = eventHandlers.handlers.slice();%0A %7D%0A %7D%0A%0A handleEvent(eventName, options, event) %7B%0A const eventHandlers = this.getEventHandlers(eventName, options);%0A eventHandlers.handlers = eventHandlers.nextHandlers;%0A eventHandlers. hand @@ -1475,24 +1475,88 @@ options);%0A%0A + this.ensureCanMutateNextEventHandlers(eventName, options);%0A%0A if (even @@ -1557,33 +1557,37 @@ (eventHandlers. -h +nextH andlers.length = @@ -1811,33 +1811,37 @@ eventHandlers. -h +nextH andlers.push(lis @@ -1991,16 +1991,81 @@ false;%0A%0A + this.ensureCanMutateNextEventHandlers(eventName, options);%0A co @@ -2082,33 +2082,37 @@ = eventHandlers. -h +nextH andlers.indexOf( @@ -2134,33 +2134,37 @@ eventHandlers. -h +nextH andlers.splice(i @@ -2190,33 +2190,37 @@ (eventHandlers. -h +nextH andlers.length =
2f96458bcb6dfe8b8db4ef0101036b09bfa7c5f5
allow backtick in HTML templates as well
esbuild/frappe-html.js
esbuild/frappe-html.js
module.exports = { name: "frappe-html", setup(build) { let path = require("path"); let fs = require("fs/promises"); build.onResolve({ filter: /\.html$/ }, (args) => { return { path: path.join(args.resolveDir, args.path), namespace: "frappe-html", }; }); build.onLoad({ filter: /.*/, namespace: "frappe-html" }, (args) => { let filepath = args.path; let filename = path.basename(filepath).split(".")[0]; return fs .readFile(filepath, "utf-8") .then((content) => { content = scrub_html_template(content); return { contents: `\n\tfrappe.templates['${filename}'] = \`${content}\`;\n`, watchFiles: [filepath], }; }) .catch(() => { return { contents: "", warnings: [ { text: `There was an error importing ${filepath}`, }, ], }; }); }); }, }; function scrub_html_template(content) { content = content.replace(/`/g, "\\`"); return content; }
JavaScript
0
@@ -517,16 +517,31 @@ ntent = +JSON.stringify( scrub_ht @@ -560,16 +560,17 @@ content) +) ;%0A%09%09%09%09%09r @@ -632,18 +632,16 @@ me%7D'%5D = -%5C%60 $%7Bconten @@ -642,18 +642,16 @@ content%7D -%5C%60 ;%5Cn%60,%0A%09%09
d0a90c0d4140a6d150c7e02a48f1413f297c3568
Remove noisy console.error
src/buttons/DefaultButton.js
src/buttons/DefaultButton.js
import React, {PropTypes} from 'react' import Ink from 'react-ink' import styles from 'part:@sanity/components/buttons/default-style' import Spinner from 'part:@sanity/components/loading/spinner' export default class DefaultButton extends React.Component { static propTypes = { kind: PropTypes.oneOf(['secondary', 'simple']), color: PropTypes.oneOf(['primary', 'success', 'danger']), onClick: PropTypes.func, children: PropTypes.node, inverted: PropTypes.bool, icon: PropTypes.func, loading: PropTypes.bool, ripple: PropTypes.bool, className: PropTypes.string, disabled: PropTypes.bool } static defaultProps = { ripple: true, icon: null, onClick() {} } constructor(...args) { super(...args) this.handleClick = this.handleClick.bind(this) } handleClick(event) { this.props.onClick(event) } render() { const {kind, ripple, disabled, inverted, color, icon, loading, className, children, ...rest} = this.props const Icon = icon if (!styles[kind] && kind) { console.error(`There is no ${kind} button`) // eslint-disable-line no-console } const style = ` ${styles[kind] || (inverted && styles.inverted) || styles.default} ${color && styles[`color__${color}`]} ${Icon && styles.hasIcon} ${className} ${disabled && styles.disabled} ` return ( <button {...rest} className={style} type="button" onClick={this.handleClick} disabled={disabled} > { loading && <Spinner /> } { Icon && <span className={styles.iconContainer}><Icon className={styles.icon} /></span> } { children && <span className={styles.content}>{children}</span> } { ripple && !disabled && <Ink duration={200} opacity={0.10} radius={200} /> } </button> ) } }
JavaScript
0.00028
@@ -304,31 +304,27 @@ eOf( -%5B'secondary', 'simple'%5D +Object.keys(styles) ),%0A @@ -1016,132 +1016,8 @@ on%0A%0A - if (!styles%5Bkind%5D && kind) %7B%0A console.error(%60There is no $%7Bkind%7D button%60) // eslint-disable-line no-console%0A %7D%0A%0A
4a26f8786cf601fd9bbfb29609f34d5926ed81d2
change error export method
sandbox/sandbox8.js
sandbox/sandbox8.js
var CronJob = require('cron').CronJob; var request = require("request"); var mongoose = require("mongoose"); mongoose.Promise = require('bluebird'); var url = "https://poloniex.com/public?command=returnTicker"; var mongodbUri = "mongodb://localhost/jpdanta"; var mongodbOptions = { useMongoClient: true, socketTimeoutMS: 0, keepAlive: true, reconnectTries: 30 }; function log(msg) { var date = new Date(); console.log(date.toLocaleString() + " " + msg); } function transform_ticker(whenFetched, tickerjson) { var t_ticker = []; // var colnames = ["", "last", "lowestAsk", "highestBid", "percentChange", "baseVolume", "quoteVolume", "high24hr", "low24hr"] var colnames = ["", "last", "lowestAsk", "highestBid"] // var coinids = []; // var measureids = []; // colnames.forEach(function(value, x) { // if (value != "") { // measureids.push({"id": x, "name": value}); // } // }); for (var i in tickerjson) { // per coin // coinids.push({"id": tickerjson[i]["id"], "name": i}); colnames.forEach(function (value, x) { if (value != "") { t_ticker.push({ a: tickerjson[i]["id"], // coin id b: x, // measure c: tickerjson[i][value], // value d: whenFetched // whenFetched }); } }); } // { // var fs = require('fs'); // console.log(measureids); // console.log(coinids); // fs.writeFileSync("measureids.txt", JSON.stringify(measureids)); // fs.writeFileSync("coinids.txt", JSON.stringify(coinids)); // } return t_ticker; } var Schema = mongoose.Schema; var tickerSchema = new Schema({ a: { type: Number, required: true }, b: { type: Number, required: true }, c: { type: Number, required: true }, d: { type: Date, required: true }, }); module.exports = mongoose.model('ticker', tickerSchema); function requestfn(error, response, body) { // log("got into response"); if (error) { throw error; } var date = new Date(); var ticker2 = transform_ticker(date, JSON.parse(body)); var db = mongoose.connection; // db.on('error', console.error); // db.once('open', function () { // //console.log("Connected to mongodb"); // }); mongoose.connect(mongodbUri, mongodbOptions); // log("mongoose connected"); var Ticker = mongoose.model('ticker', tickerSchema); ticker2.forEach(function (aTicker, x) { var aTickerObj = new Ticker(aTicker); aTickerObj.save(function (err, doc) { if (err) throw err; }); }); mongoose.disconnect(); // log("mongoose disconnected"); } new CronJob('*/3 * * * * *', function () { // log("start"); request(url, requestfn); // log("finish"); }, null, true);
JavaScript
0
@@ -2204,19 +2204,28 @@ -throw +console.error( error +) ;%0A
7383d131833d2d2cb5449514a32068ee97d6fd13
Add translation for 'close'
lib/translations/sk_SK.js
lib/translations/sk_SK.js
// Slovak jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'január', 'február', 'marec', 'apríl', 'máj', 'jún', 'júl', 'august', 'september', 'október', 'november', 'december' ], monthsShort: [ 'jan', 'feb', 'mar', 'apr', 'máj', 'jún', 'júl', 'aug', 'sep', 'okt', 'nov', 'dec' ], weekdaysFull: [ 'nedeľa', 'pondelok', 'utorok', 'streda', 'štvrtok', 'piatok', 'sobota' ], weekdaysShort: [ 'Ne', 'Po', 'Ut', 'St', 'Št', 'Pi', 'So' ], today: 'dnes', clear: 'vymazať', firstDay: 1, format: 'd. mmmm yyyy', formatSubmit: 'yyyy/mm/dd' });
JavaScript
0.999684
@@ -495,16 +495,38 @@ maza%C5%A5',%0A + close: 'zavrie%C5%A5',%0A firs
f51d9e56ffeacdb0b11a8b102ac7084348acbed6
update fangorn delete logic
website/addons/figshare/static/figshareFangornConfig.js
website/addons/figshare/static/figshareFangornConfig.js
'use strict'; var m = require('mithril'); var Fangorn = require('js/fangorn').Fangorn; // Define Fangorn Button Actions var _figshareItemButtons = { view: function (ctrl, args, children) { var buttons = []; var tb = args.treebeard; var item = args.item; if (tb.options.placement !== 'fileview') { // If File and FileRead are not defined dropzone is not supported and neither is uploads if (window.File && window.FileReader && item.data.permissions && item.data.permissions.edit && item.kind === 'folder') { buttons.push( m.component(Fangorn.Components.button, { onclick: function (event) { Fangorn.ButtonEvents._uploadEvent.call(tb, event, item); }, icon: 'fa fa-upload', className: 'text-success' }, 'Upload') ); } // Download file or Download-as-zip if (item.kind === 'file') { buttons.push( m.component(Fangorn.Components.button, { onclick: function (event) { Fangorn.ButtonEvents._downloadEvent.call(tb, event, item); }, icon: 'fa fa-download', className: 'text-primary' }, 'Download') ); } else { buttons.push( m.component(Fangorn.Components.button, { onclick: function (event) { Fangorn.ButtonEvents._downloadZipEvent.call(tb, event, item); }, icon: 'fa fa-download', className: 'text-primary' }, 'Download as zip') ); } // All files are viewable on the OSF. if (item.kind === 'file' && item.data.permissions && item.data.permissions.view) { buttons.push( m.component(Fangorn.Components.button, { onclick: function (event) { Fangorn.ButtonEvents._gotoFileEvent.call(tb, item); }, icon: 'fa fa-file-o', className: 'text-info' }, 'View')); } // Files can be deleted if private or if it is in a dataset that contains more than one file var privateOrSiblings = (item.data.extra && item.data.extra.status !== 'public') || (!item.parent().data.isAddonRoot && item.parent().children.length > 1); if (item.kind === 'file' && privateOrSiblings && item.data.permissions && item.data.permissions.edit) { buttons.push( m.component(Fangorn.Components.button, { onclick: function (event) { Fangorn.ButtonEvents._removeEvent.call(tb, event, tb.multiselected()); }, icon: 'fa fa-trash', className: 'text-danger' }, 'Delete') ); } // Files are only viewable on figshare if they are public if (item.kind === 'file' && item.data.permissions && item.data.permissions.view && item.data.extra.status === 'public') { buttons.push( m('a.text-info.fangorn-toolbar-icon', {href: item.data.extra.webView}, [ m('i.fa.fa-external-link'), m('span', 'View on figshare') ]) ); } } return m('span', buttons); // Tell fangorn this function is used. } }; Fangorn.config.figshare = { // Fangorn options are called if functions, so return a thunk that returns the column builder itemButtons: _figshareItemButtons };
JavaScript
0.000001
@@ -2451,16 +2451,28 @@ / Files +and folders can be d @@ -2492,66 +2492,9 @@ vate - or if it is in a dataset that contains more than one file +. %0A @@ -2506,33 +2506,25 @@ var -p +isP rivate -OrSiblings = (item @@ -2578,157 +2578,35 @@ ic') - %7C%7C%0A (!item.parent().data.isAddonRoot && item.parent().children.length %3E 1);%0A if (item.kind === 'file' && privateOrSiblings +;%0A if (isPrivate &&
75436484672a08074f444b8e890617c5c56a37d6
Add a preview to RequestForm
src/components/RequestForm.js
src/components/RequestForm.js
import React, { Component } from 'react'; import { Grid, Row, Col, Image, FormGroup, FormControl, ControlLabel, HelpBlock } from 'react-bootstrap'; import DatePicker from 'react-bootstrap-date-picker'; import _ from 'lodash'; import moment from 'moment'; import AddControls from './AddControls'; import TopicChooser from './TopicChooser'; import { topics } from './stories/fixtures'; class RequestForm extends Component { constructor(props) { super(props); var {name: issuerName, picture: issuerAvatar} = props.route.auth.getProfile(); this.state = { request: { fromDate: moment().toISOString(), toDate: moment().add(1, 'months').toISOString(), reason: '', topics: null, issuerName, issuerAvatar } } this.save = this.save.bind(this); this.handleChange = this.handleChange.bind(this); this.handleInputChange = this.handleInputChange.bind(this); } save() { console.log('save', this.state.request); } handleChange(key, value) { var request = this.state.request; request[key] = value; this.setState({ request }); } handleInputChange(key, evt) { this.handleChange(key, evt.target.value); } render(){ return ( <Grid> <Row> <Col xsOffset={3} xs={6}> <h2>Request Access to Entries</h2> </Col> </Row> <Row> <Col xsOffset={3} xs={6}> <Image src={this.state.request.issuerAvatar} className='profile-img' circle /> <span>{this.state.request.issuerName}</span> </Col> </Row> <Row> <Col xsOffset={3} xs={6}> <TopicChooser label="Would like to see entries about" topics={this.props.topics} maxSelections={1} onChange={_.partial(this.handleChange, 'topics')} /> <FormGroup> <ControlLabel>From</ControlLabel> <DatePicker value={this.state.request.fromDate} onChange={_.partial(this.handleChange, 'fromDate')} /> </FormGroup> <FormGroup> <ControlLabel>To</ControlLabel> <DatePicker value={this.state.request.toDate} onChange={_.partial(this.handleChange, 'toDate')} /> </FormGroup> <FormGroup> <ControlLabel>Because</ControlLabel> <FormControl componentClass="textarea" maxLength={this.props.maxLength} onChange={_.partial(this.handleInputChange, 'reason')} /> <HelpBlock>{this.state.request.reason.length} of {this.props.maxLength} letters used</HelpBlock> </FormGroup> </Col> </Row> <Row> <Col xsOffset={3} xs={6}> <AddControls onNext={this.save} /> </Col> </Row> </Grid> ); } } RequestForm.propTypes = { maxLength: React.PropTypes.number, topics: React.PropTypes.array } RequestForm.defaultProps = { maxLength: 240, topics: topics } export default RequestForm;
JavaScript
0
@@ -331,16 +331,49 @@ hooser'; +%0Aimport Request from './Request'; %0A%0Aimport @@ -804,12 +804,10 @@ cs: -null +%5B%5D ,%0A @@ -1707,21 +1707,32 @@ %3C -Image +h3%3EPreview:%3C/h3%3E %0A @@ -1752,231 +1752,99 @@ - src=%7Bthis.state.request.issuerAvatar%7D%0A className='profile-img'%0A circle%0A /%3E%0A %3Cspan%3E%7Bthis.state.request.issuerName%7D%3C/span +%3CRequest%0A %7B...this.state.request%7D%0A / %3E%0A
ee830e11a9a59f93d585ba6432c1a3a15f468f87
Update photon URL to HTTPS
src/providers/photon.js
src/providers/photon.js
/** * @class Photon */ export class Photon { /** * @constructor */ constructor() { this.settings = { url: 'http://photon.komoot.de/api/', params: { q: '', limit: 10, lang: 'en' }, langs: ['de', 'it', 'fr', 'en'] }; } getParameters(options) { options.lang = options.lang.toLowerCase(); return { url: this.settings.url, params: { q: options.query, limit: options.limit || this.settings.params.limit, lang: this.settings.langs.indexOf(options.lang) > -1 ? options.lang : this.settings.params.lang } }; } handleResponse(results) { return results.map(result => ({ lon: result.geometry.coordinates[0], lat: result.geometry.coordinates[1], address: { name: result.properties.name, postcode: result.properties.postcode, city: result.properties.city, state: result.properties.state, country: result.properties.country }, original: { formatted: result.properties.name, details: result.properties } })); } }
JavaScript
0.000001
@@ -127,16 +127,17 @@ l: 'http +s ://photo
b2d15719216e451244a8304df3f72b783a517551
Fix answering replyQuerys
modules/botQueryHandler.js
modules/botQueryHandler.js
'use strict' var botQueryHandler = require('./storage/replyQuery'); var tg = require('./telegram/telegramAPI'); var replyQuery = require('./storage/replyQuery'); var lfm = require('./lfmController') /* queryData.a - artist queryData.o - object (track/album) queryData.m - method short because of Telegram 64 bytes limit */ botQueryHandler.execute = function (query, queryData) { botQueryHandler[queryData.m](query, queryData, botQueryHandler._answer); }; botQueryHandler.youtube = function (query, queryData, answer) { var replyData = replyQuery.get(queryData.a, queryData.o, 'tracks'); if (!replyData) { botQueryHandler._outdatedButton(query); return answer(query); }; lfm.getYouTubeLink(replyData.artist, replyData.object, function (response) { tg.sendTextMessage(response, query.message.chat.id); return answer(query); }); }; botQueryHandler.prevPage = function (query, queryData) { var artist = replyQuery.getArtist(queryData.a); if (!artist) { botQueryHandler._outdatedButton(query); return answer(query); }; if (queryData.page == '1') { tg.sendTextMessage('You are on page 1', query.message.chat.id); return answer(query); }; lfm.getTopTracks(artist, +queryData.page - 1, function (response, replyMarkup) { botQueryHandler._editMessage(query, response, replyMarkup); answer(query); }); }; botQueryHandler.nextPage = function (query, queryData) { var artist = replyQuery.getArtist(queryData.a); if (!artist) { botQueryHandler._outdatedButton(query); return answer(query); }; lfm.getTopTracks(artist, +queryData.page + 1, function (response, replyMarkup) { botQueryHandler._editMessage(query, response, replyMarkup); answer(query); }); }; botQueryHandler._outdatedButton = function (query) { tg.sendTextMessage('Sorry, this button is outdated', query.message.chat.id); }; botQueryHandler._editMessage = function (query, response, replyMarkup) { tg.editMessageText( query.message.chat.id, query.message.message_id, null, response, 'HTML', 1, replyMarkup ); }; botQueryHandler._answer = function (query) { tg.answerCallbackQuery(query.id); }; module.exports = botQueryHandler;
JavaScript
0.000069
@@ -937,32 +937,40 @@ query, queryData +, answer ) %7B%0A var arti @@ -1488,32 +1488,40 @@ query, queryData +, answer ) %7B%0A var arti
2dbd6ca39d03dc02e686498f39a88825563e19d6
Use basic string for Spotify API requests
src/components/Track/index.js
src/components/Track/index.js
import { h, Component } from 'preact'; import style from './style'; export default class Track extends Component { state = { playing: false }; sanitizeQuery(query) { query = query.toLowerCase(); // to lower case query = query.replace(/(dj set)/g, ''); // remove dj set info from name query = query.replace(/(official)/g, ''); // remove official info from name query = query.replace(/\./g, ''); // remove .s return query; } findArtist(query) { const url = new URL('https://api.spotify.com/v1/search'); query = this.sanitizeQuery(query); url.searchParams.append('q', query); url.searchParams.append('type', 'artist'); url.searchParams.append('limit', '1'); return new Promise((resolve, reject) => { return fetch(url) .then(response => response.json()) .then(data => { if (data.artists.total <= 0) { return reject(`Spotify found no artists with query: "${query}".`); } const items = data.artists.items; const item = items.find(item => item.name.toLowerCase() === query); if (!item) { return reject(`No artist called "${query}".`); } return resolve(item.id); }) .catch(reject); }); } getTopTrack(id) { const url = new URL(`https://api.spotify.com/v1/artists/${id}/top-tracks`); url.searchParams.append('country', 'GB'); url.searchParams.append('limit', '1'); return fetch(url).then(response => response.json()); } getTopTrackInfo(data) { return new Promise((resolve, reject) => { const { name } = this.props; // return nothing if no data sent to template if (data.tracks.length <= 0) { reject('No tracks for this artist'); } const tracks = data.tracks; let track = tracks.find(track => track.artists[0].name.toLowerCase() === name.toLowerCase()); if (!track) { track = tracks[0]; } if (track.album.images.length > 0) { track.image = track.album.images[1].url; } resolve(track); }); } getMusic() { const { name } = this.props; this.findArtist(name) .then(this.getTopTrack) .then(this.getTopTrackInfo.bind(this)) .then(track => this.setState({ track })); } // gets called when this route is navigated to componentDidMount() { this.getMusic(); } // gets called just before navigating away from the route componentWillUnmount() { if (this.state.audio) { this.stopAudio(); } } playAudio () { this.state.audio.play(); this.setState({ playing: true }); } pauseAudio () { this.state.audio.pause(); this.setState({ playing: false }); } stopAudio () { this.state.audio.pause(); this.setState({ playing: false, audio: null }); } handleClick() { const { playing, track } = this.state; let { audio } = this.state; if (!track) { return false; } if (!audio) { audio = new Audio(track.preview_url); audio.addEventListener('paused', this.pauseAudio); audio.addEventListener('ended', this.stopAudio); this.setState({ audio }); } if (playing) { this.pauseAudio(); } else { this.playAudio(); } } render() { const { track, playing } = this.state; if (!track || !track.artists || track.artists.length <= 0) { return false; } const trackArtists = track.artists.map(artist => artist.name).join(', '); return ( <div class={style.track}> <div class={`${style.cover} ${playing ? style.coverPlaying : ''}`} style={{ backgroundImage: `url(${track ? track.image : ''})` }} onClick={this.handleClick.bind(this)} /> <a class={style.info} href={track ? track.external_urls.spotify : '#'} target="_blank"> <span>{track && track.name}</span> <span>{track && trackArtists}</span> <span>{track && track.album.name}</span> </a> </div> ); } }
JavaScript
0.000002
@@ -469,24 +469,63 @@ st(query) %7B%0A + query = this.sanitizeQuery(query);%0A const ur @@ -528,24 +528,16 @@ t url = -new URL( 'https:/ @@ -567,178 +567,136 @@ rch' -); + + %0A -query = this.sanitizeQuery( + %60?q=$%7B query -); +%7D%60 + %0A -url.searchParams.append('q', query);%0A url.searchParams.append('type', ' + '&type= artist' -); + + %0A -url.searchParams.append('limit', '1' + '&limit=1';%0A%0A console.log(url );%0A%0A @@ -828,24 +828,112 @@ n(data =%3E %7B%0A + if (data.error) %7B%0A return reject(data.error.message);%0A %7D%0A%0A if @@ -1395,16 +1395,8 @@ l = -new URL( %60htt @@ -1448,98 +1448,69 @@ cks%60 -); + + %0A -url.searchParams.append(' + '? country -', 'GB'); +=GB' + %0A -url.searchParams.append(' + '& limit -', ' += 1' -) ;%0A%0A @@ -1638,24 +1638,24 @@ eject) =%3E %7B%0A - const @@ -1672,24 +1672,105 @@ this.props; +%0A if (data.error) %7B%0A return reject(data.error.message);%0A %7D %0A%0A // r
9cfc4b42cad4c84d36aec39ef43135776e2b7aea
add offenders for domainsWithCookies
modules/cookies/cookies.js
modules/cookies/cookies.js
/** * cookies metrics */ 'use strict'; exports.version = '0.2'; exports.module = function(phantomas) { // monitor cookies in HTTP headers var cookiesSent = 0, cookiesRecv = 0, cookiesDomains = {}; phantomas.on('send', function(entry, res) { res.headers.forEach(function(header) { switch (header.name) { case 'Cookie': cookiesSent += header.value.length; cookiesDomains[entry.domain] = true; break; } }); }); phantomas.on('recv', function(entry, res) { res.headers.forEach(function(header) { switch (header.name) { case 'Set-Cookie': cookiesRecv += header.value.length; cookiesDomains[entry.domain] = true; break; } }); }); // domain cookies (accessible by the browser) phantomas.on('report', function() { /* global document: true, window: true */ phantomas.setMetric('cookiesSent', cookiesSent); // @desc length of cookies sent in HTTP requests @unreliable phantomas.setMetric('cookiesRecv', cookiesRecv); // @desc length of cookies received in HTTP responses @unreliable // domains with cookies var domainsWithCookies = 0; for (var domain in cookiesDomains) { domainsWithCookies++; } phantomas.setMetric('domainsWithCookies', domainsWithCookies); // @desc number of domains with cookies set phantomas.setMetricEvaluate('documentCookiesLength', function() { // @desc length of document.cookie try { return document.cookie.length; } catch(ex) { window.__phantomas.log('documentCookiesLength: not set because ' + ex + '!'); return 0; } }); phantomas.setMetricEvaluate('documentCookiesCount', function() { //@desc number of cookies in document.cookie try { return document.cookie.split(';').length; } catch(ex) { window.__phantomas.log('documentCookiesCount: not set because ' + ex + '!'); return 0; } }); }); };
JavaScript
0
@@ -60,9 +60,9 @@ '0. -2 +3 ';%0A%0A @@ -145,66 +145,541 @@ var -cookiesSent = 0,%0A%09%09cookiesRecv = 0,%0A%09%09cookiesDomains = %7B%7D; +Collection = require('../../lib/collection'),%0A%09%09cookiesDomains = new Collection();%0A%0A%09phantomas.setMetric('cookiesSent'); // @desc length of cookies sent in HTTP requests @unreliable%0A%09phantomas.setMetric('cookiesRecv'); // @desc length of cookies received in HTTP responses%0A%09phantomas.setMetric('domainsWithCookies'); // @desc number of domains with cookies set%0A%09phantomas.setMetric('documentCookiesLength'); // @desc length of document.cookie%0A%09phantomas.setMetric('documentCookiesCount'); //@desc number of cookies in document.cookie %0A%0A%09p @@ -808,24 +808,46 @@ okie':%0A%09%09%09%09%09 +phantomas.incrMetric(' cookiesSent @@ -845,19 +845,18 @@ kiesSent - += +', header. @@ -859,32 +859,33 @@ der.value.length +) ;%0A%09%09%09%09%09cookiesDo @@ -881,33 +881,38 @@ %09%09cookiesDomains -%5B +.push( entry.domain%5D = @@ -903,32 +903,104 @@ entry.domain -%5D = true +);%0A%0A%09%09%09%09%09phantomas.log('Cookie: sent %22%25s%22 (for %25s)', header.value, entry.domain) ;%0A%09%09%09%09%09break @@ -1162,23 +1162,23 @@ %09%09%09%09 +var cookies -Recv + + = +( head @@ -1185,25 +1185,137 @@ er.value + %7C%7C '').split('%5Cn');%0A%0A%09%09%09%09%09cookies.forEach(function(cookie) %7B%0A%09%09%09%09%09%09phantomas.incrMetric('cookiesRecv', cookie .length +) ;%0A +%09 %09%09%09%09%09coo @@ -1329,9 +1329,14 @@ ains -%5B +.push( entr @@ -1347,16 +1347,96 @@ main -%5D = true +);%0A%0A%09%09%09%09%09%09phantomas.log('Cookie: received %22%25s%22 (for %25s)', cookie, entry.domain);%0A%09%09%09%09%09%7D) ;%0A%09%09 @@ -1594,336 +1594,109 @@ */%0A +%0A %09%09 -phantomas.setMetric('cookiesSent', cookiesSent); // @desc length of cookies sent in HTTP requests @unreliable%0A%09%09phantomas.setMetric('cookiesRecv', cookiesRecv); // @desc length of cookies received in HTTP responses @unreliable%0A%0A%09%09// domains with cookies%0A%09%09var domainsWithCookies = 0;%0A%09%09for (var domain in cookiesDomains) %7B%0A%09%09%09 +// domains with cookies%0A%09%09cookiesDomains.forEach(function(domain, cnt) %7B%0A%09%09%09phantomas.incrMetric(' doma @@ -1713,16 +1713,13 @@ kies -++ +') ;%0A%09 -%09%7D%0A %09%09ph @@ -1722,33 +1722,35 @@ %09%09phantomas. -setMetric +addOffender ('domainsWit @@ -1764,72 +1764,47 @@ s', -domainsWithC +'%25s: %25d c ookie +( s) -; // @desc number of domains with cookies set +', domain, cnt);%0A%09%09%7D); %0A%0A%09%09 @@ -1872,43 +1872,8 @@ () %7B - // @desc length of document.cookie %0A%09%09%09 @@ -2111,53 +2111,8 @@ () %7B - //@desc number of cookies in document.cookie %0A%09%09%09
6717954b380ed90bd159c6fac8f06f49ccd6b7c0
Fix trust logic
src/selectors/trustForm.js
src/selectors/trustForm.js
export default (petition, me) => ({ initialValues: { // For TrustSupportForm user: me || {}, // For TrustPublishForm owner: petition.owner || {} }, mobileConfirmed: (me && me.mobile_trusted) || false, petition: petition || {}, me: me || {}, trustedFields: { // For TrustSupportForm 'user.email': (me && me.email_trusted) || false, 'user.mobile': (me && me.mobile_trusted) || false, // For TrustPublishForm 'owner.email': (me && me.email_trusted) || false, 'owner.mobile': (me && me.mobile_trusted) || false } });
JavaScript
0.000053
@@ -1,8 +1,62 @@ +import petitionOwned from 'selectors/petitionOwned';%0A%0A export d @@ -188,16 +188,42 @@ owner: + petitionOwned(petition) ? petitio @@ -230,16 +230,21 @@ n.owner +: me %7C%7C %7B%7D%0A
98fd9822af3bf97569a48b4d1e369ecc35669762
Update transports.js
lib/winston/transports.js
lib/winston/transports.js
/* * transports.js: Set of all transports Winston knows about * * (C) 2010 Charlie Robbins * MIT LICENCE * */ Object.defineProperty(exports, 'Console', { configurable: true, enumerable: true, get: function () { return require('./transports/console') } }); Object.defineProperty(exports, 'File', { configurable: true, enumerable: true, get: function () { return require('./transports/file'); } }); Object.defineProperty(exports, 'Http', { configurable: true, enumerable: true, get: function () { return require('./transports/http'); } }); Object.defineProperty(exports, 'Memory', { configurable: true, enumerable: true, get: function () { return require('./transports/memory'); } });
JavaScript
0.000001
@@ -259,17 +259,26 @@ onsole') +.Console; %0A - %7D%0A%7D);%0A @@ -420,16 +420,21 @@ s/file') +.File ;%0A %7D%0A%7D) @@ -578,16 +578,21 @@ s/http') +.Http ;%0A %7D%0A%7D) @@ -691,32 +691,32 @@ : function () %7B%0A - return requi @@ -740,16 +740,23 @@ memory') +.Memory ;%0A %7D%0A%7D)
5b4e1815e7944edb18d581af2c1982980ade212c
make SRs reread buttons when moving help links
app/jsx/custom_help_link_settings/CustomHelpLink.js
app/jsx/custom_help_link_settings/CustomHelpLink.js
/* * Copyright (C) 2016 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' import I18n from 'i18n!custom_help_link' import CustomHelpLinkPropTypes from './CustomHelpLinkPropTypes' import CustomHelpLinkHiddenInputs from './CustomHelpLinkHiddenInputs' import CustomHelpLinkAction from './CustomHelpLinkAction' const CustomHelpLink = React.createClass({ propTypes: { link: CustomHelpLinkPropTypes.link.isRequired, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, onEdit: PropTypes.func, onRemove: PropTypes.func }, getInitialState () { return { shouldFocus: this.props.shouldFocus }; }, focus (action) { // screenreaders are the worst setTimeout(() => { const ref = this.actions[action]; if (ref && ref.props.onClick) { ref.focus(); } else { const focusable = this.focusable(); if (focusable) { focusable.focus(); } } }, 100); }, focusable () { const focusable = this.rootElement.querySelectorAll('button:not([disabled])'); return focusable[0]; }, render () { const { text } = this.props.link; this.actions = {}; return ( <li className="ic-Sortable-item" ref={(c) => { this.rootElement = c }} > <div className="ic-Sortable-item__Text"> {text} </div> <div className="ic-Sortable-item__Actions"> <div className="ic-Sortable-sort-controls"> <CustomHelpLinkAction ref={(c) => this.actions['moveUp'] = c} link={this.props.link} label={I18n.t('Move %{text} up', { text })} onClick={this.props.onMoveUp} iconClass="icon-mini-arrow-up" /> <CustomHelpLinkAction ref={(c) => this.actions['moveDown'] = c} link={this.props.link} label={I18n.t('Move %{text} down', { text })} onClick={this.props.onMoveDown} iconClass="icon-mini-arrow-down" /> </div> <CustomHelpLinkAction ref={(c) => this.actions['edit'] = c} link={this.props.link} label={I18n.t('Edit %{text}', { text })} onClick={this.props.onEdit} iconClass="icon-edit" /> <CustomHelpLinkAction ref={(c) => this.actions['remove'] = c} link={this.props.link} label={I18n.t('Remove %{text}', { text })} onClick={this.props.onRemove} iconClass="icon-trash" /> </div> <CustomHelpLinkHiddenInputs link={this.props.link} /> </li> ) } }); export default CustomHelpLink
JavaScript
0.000002
@@ -1428,16 +1428,445 @@ e worst%0A + // We have to force a focus change and a delay because clicking the %22up%22 or %22delete%22 buttons%0A // just causes React to rearrange the DOM nodes, so the focus doesn't actually change. If the%0A // focus doesn't change, screenreaders don't read the up button or delete button again like we%0A // want them to. If we don't delay, then screenreaders don't notice the focus changed.%0A this.actions%5B'edit'%5D.focus();%0A se
6f1a5088d72c6a78b0b9f02c5da5517293739080
fix a fs-uninstall logic - fs's all files backup when fs-uninstall time - remove docker container logic added
src/server/fs-uninstall.js
src/server/fs-uninstall.js
/* * Copyright (c) 2012-2015 S-Core Co., 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. */ 'use strict'; var conf = require('./common/conf-manager').conf; var async = require('async'); var fs = require('fs'); var path = require('path'); var linuxfs = require('./fs/lib/linuxfs/' + conf.services.fs.linuxfs); var db = require('./common/db-manager')('wfs', 'system', 'sequence'); var dao = db.dao; function deleteLinuxFS(callback) { console.log('delete LinuxFS'); dao.wfs.$find(function (err, context) { var infos = context.result(); if (err) { return callback(err); } async.each(infos, function (info, cb) { linuxfs.deleteFS(info.key, cb); }, function (err) { console.log('delete linuxFS', err); return callback(err); }); }); } function deleteFiles(callback) { console.log('delete Files'); var src = conf.services.fs.fsPath; var dest = path.normalize(conf.services.fs.fsPath + '/../uninstalled-' + Date.now()); function _move(file) { var srcPath = dest + '/' + file; var destPath = src + '/' + file; fs.mkdir(destPath, function(err) { if (err && err.errno !== 47) { console.log('mkdir failed.', err); return callback('Failed to create uninstalled directory'); } // ~/fs/* move to ~/../uninstalled-* fs.rename(srcPath, destPath, function(err) { console.log('delete files', err); if (err && err.errno !== 34) { return callback(err); } }); }); } fs.mkdir(dest, function (err) { if (err && err.errno !== 47) { console.log('mkdir failed.', err); return callback('Failed to create uninstalled directory'); } fs.readdir(src, function (err, files) { if(err) { return callback('Failed to read ' + src + 'directory'); } console.log('Move all fs/* files to unistalled directory'); files.forEach(_move); callback(); }); }); } function deleteMongoTable(callback) { console.log('delete Tables'); db.transaction([ dao.system.dropAliasTable(), dao.system.dropDownloadLinkTable(), dao.system.dropLockTable(), dao.system.dropKeyStoreTable(), dao.system.dropWfsDelTable(), dao.system.dropWfsTable(), dao.system.dropGcmInfoTable(), function (context, next) { dao.sequence.$remove({space:'wfs'}, function (err) { if (err) { next(err); } next(); }, context); } ], callback); } async.waterfall([ deleteLinuxFS, deleteFiles, deleteMongoTable ], function (err/*, results*/) { if (err) { console.error('uninstall failed.', err, err.stack); } else { console.log('uninstall successfully completed.'); } process.exit(); });
JavaScript
0.000001
@@ -671,16 +671,57 @@ ).conf;%0A +var exec = require('child_process').exec; %0Avar asy @@ -1593,16 +1593,283 @@ ow());%0A%0A + function _remove(file) %7B%0A var cmdRemove = 'rm -rf ' + src + '/' + file%0A%0A console.log('... delete file: ' + file);%0A exec(cmdRemove, function (err) %7B%0A if (err) %7B%0A return callback(err);%0A %7D%0A %7D);%0A %7D%0A%0A func @@ -1909,20 +1909,19 @@ cPath = -dest +src + '/' + @@ -1946,27 +1946,28 @@ destPath = -src +dest + '/' + fil @@ -2005,32 +2005,98 @@ function(err) %7B%0A + var cmdCopy = 'cp -a ' + srcPath + '/. ' + destPath;%0A%0A if ( @@ -2285,20 +2285,20 @@ ~/fs/* -move +copy to ~/.. @@ -2328,35 +2328,20 @@ -fs.rename(srcPath, destPath +exec(cmdCopy , fu @@ -2338,32 +2338,33 @@ mdCopy, function + (err) %7B%0A @@ -2375,85 +2375,15 @@ -console.log('delete files', err);%0A if (err && err.errno !== 34 +if (err ) %7B%0A @@ -2434,32 +2434,62 @@ %7D%0A + _remove(file)%0A %7D);%0A @@ -2920,18 +2920,20 @@ to -unistalled +' + dest + ' dir @@ -2972,49 +2972,306 @@ ach( -_move);%0A callback();%0A %7D +function (file) %7B%0A _move(file);%0A %7D);%0A callback();%0A %7D);%0A %7D);%0A%7D%0A%0Afunction deleteDockerContainer(callback) %7B%0A var cmd = 'docker rm -f $(docker ps -a -q)';%0A%0A console.log('remove docker container');%0A exec(cmd, function (err) %7B%0A callback(err );%0A @@ -3952,16 +3952,43 @@ eFiles,%0A + deleteDockerContainer,%0A dele
70adda1bd4992b6cd7b71d8869f88d92858ddcd6
update config
src/config/config-template.js
src/config/config-template.js
const config = { projectName: "Arion EQMN Modeler", useBackendMock: true, backendRESTRoute: "http://localhost:3000", colors: { primaryDark: "#000051", primary: "#1a237e", primaryLight: "#534bae", accent: "#C99700", accentLight: "#ffc107", accentDark: "#7A5C00", text: "#424242", textAlternate: "#ffffff", border: "#e0e0e0", diagramLine: '#9E9E9E', diagramBackground: "rgba(224, 224, 224, 0.6)", error: "#B71C1C", }, descriptions: {}, messages: {}, }; export default config;
JavaScript
0.000001
@@ -558,24 +558,89 @@ criptions: %7B +%0D%0A toolTipToDetailView: %22See Event Query Hierarchy%22,%0D%0A %7D,%0D%0A mess
1dcfcd65d56306ea1fd19772c9c8aa6b3c380a48
implement route /showEditableUserFields fixes #15
src/routes/UserRoute.js
src/routes/UserRoute.js
import Express from 'express'; import Model from '../models/model'; import Utils from '../utils'; let router = Express.Router(); //POST URL: localhost:8080/api/user?username=testusername&email=testemail&password=testpassword&api_key=testapikey&api_secret=testapisecret router.route('/user') .post(function(req, res) { Model.User .build({ Username: req.body.username, Firstname: req.body.firstname, Lastname: req.body.lastname, Email: req.body.email, AccountCreation_Timestamp: new Date().getTime(), Description: req.body.description }) .save() .then(function(result) { res.send(result); }) .catch(function(error) { console.log(error); res.send(error); }) }) .get(function(req, res) { try{ Model.User.findAll() .then(function(result) { res.send(result); }) } catch(error) { res.send(error); } }); module.exports = router;
JavaScript
0
@@ -922,16 +922,393 @@ %0A%09%09%7D);%0A%0A +router.route('/showEditableUserFields')%0A%09%09.post(function(req, res) %7B%0A%09%09%09try%7B%0A%09%09%09%09Model.User.findOne(%7B%0A%09%09%09%09%09where: %7B%0A%09%09%09%09%09%09GUID: req.body.userguid%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09attributes: %5B'Username', 'Firstname', 'Lastname', 'Email', 'Email_verified', 'Description'%5D%0A%09%09%09%09%7D)%0A%09%09%09%09.then(function(result) %7B%0A%09%09%09%09%09res.send(result);%0A%09%09%09%09%7D)%0A%09%09%09%7D%0A%09%09%09catch(error) %7B%0A%09%09%09%09res.send(error);%0A%09%09%09%7D%0A%09%09%09%0A%09%09%7D);%0A%0A module.e
bc6f645b99f506ec8769f4af6559830d3fcec75a
fix bug
src/routes/appRoutes.js
src/routes/appRoutes.js
// Libraries import React from 'react'; import Router, { Route, IndexRoute } from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory'; // Components import App from '../containers/App/App'; import Main from '../containers/Main/Main'; import AdminPage from '../containers/AdminPage/AdminPage'; import ValidDemoPage from '../containers/ValidDemoPage/ValidDemoPage'; import DashboardPage from '../containers/DashboardPage/DashboardPage'; import ResourceMapPage from '../containers/ResourceMapPage/ResourceMapPage'; import BugTrackingPage from '../containers/BugTrackingPage/BugTrackingPage'; import OvertimePage from '../containers/OvertimePage/OvertimePage'; import TaskPage from '../containers/TaskPage/TaskPage'; import PTOPage from '../containers/PTOPage/PTOPage'; import BugReviewPage from '../containers/BugReviewPage/BugReviewPage'; import BugReportPage from '../containers/BugReportPage/BugReportPage'; import ResourceMapPage from '../containers/ResourceMapPage/ResourceMapPage.js'; import DataExplorerPage from '../containers/DataExplorerPage/DataExplorerPage'; import DataExplorerFolderView from '../containers/DataExplorerFolderView/DataExplorerFolderView'; import DataExplorerFileView from '../containers/DataExplorerFileView/DataExplorerFileView'; import Login from '../containers/Login/Login'; import NotFoundPage from '../containers/NotFoundPage/NotFoundPage'; import DocumentPage from '../containers/DocumentPage/DocumentPage'; import EditArticlePage from '../containers/EditArticlePage/EditArticlePage'; import ViewArticlePage from '../containers/ViewArticlePage/ViewArticlePage'; import FeatureAnalysisPage from '../containers/FeatureAnalysisPage/FeatureAnalysisPage'; import FeatureAnalysisTreePage from '../containers/FeatureAnalysisPage/FeatureAnalysisTree'; import FeatureAnalysisTablePage from '../containers/FeatureAnalysisPage/FeatureAnalysisTable'; // Utilities import requireAuth from '../containers/Require-Auth/Require-Auth'; // Demo Component (To be removed) import DemoPage from '../containers/DemoPage/DemoPage'; const appRoutes = () => ( <Router history={createBrowserHistory()}> <Route path="/" component={App}> <IndexRoute component={Login} /> <Route path="main" component={requireAuth(Main)}> <IndexRoute component={requireAuth(DashboardPage)}/> <Route path="admin" component={requireAuth(AdminPage)} /> <Route path="task" component={requireAuth(TaskPage)} /> <Route path="pto" component={requireAuth(PTOPage)} /> <Route path="redux-demo" component={requireAuth(DemoPage)} /> <Route path="resource-map" component={requireAuth(ResourceMapPage)} /> <Route path="bug-tracking" component={requireAuth(BugTrackingPage)} /> <Route path="overtime" component={requireAuth(OvertimePage)} /> <Route path="bug-analysis" component={requireAuth(BugReviewPage)} /> <Route path="bug-report" component={requireAuth(BugReportPage)} /> <Route path="resource-map" component={requireAuth(ResourceMapPage)} /> <Route path="valid-demo" component={requireAuth(ValidDemoPage)} /> <Route path="articles/edit/:articleId" component={requireAuth(EditArticlePage)} /> <Route path="articles/:articleId" component={requireAuth(ViewArticlePage)} /> <Route path="document" component={requireAuth(DocumentPage)} /> <Route path="feature-analysis" component={requireAuth(FeatureAnalysisPage)}> <IndexRoute component={requireAuth(FeatureAnalysisTreePage)} /> <Route path="table" component={requireAuth(FeatureAnalysisTablePage)} /> </Route> <Route path="data-explorer" component={requireAuth(DataExplorerPage)}> <IndexRoute component={requireAuth(DataExplorerFolderView)}/> <Route path="data-explorer/:folderName" component={requireAuth(DataExplorerFileView)} /> </Route> </Route> <Route path="*" component={NotFoundPage} /> </Route> </Router> ); export default appRoutes;
JavaScript
0
@@ -464,85 +464,8 @@ e';%0A -import ResourceMapPage from '../containers/ResourceMapPage/ResourceMapPage';%0A impo
da5c5b56b62434287cfb5ec514d0c3bd99a17aac
Update cover text #26
src/routes/home/Home.js
src/routes/home/Home.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Layout from '../../components/Layout'; import Link from '../../components/Link'; import s from './Home.css'; function Home() { return ( <Layout> <div className={s.root}> <div className={s.container}> <h1 className={s.title}>Dérangeons la Chambre</h1> <h2 className={s.subtitle}>Une étude des différents mode de scrutins</h2> <Link to="/%C3%A9tude/introduction" className={s.btn}>Dérangez la chambre</Link> </div> </div> </Layout> ); } Home.propTypes = {}; export default withStyles(s)(Home);
JavaScript
0
@@ -692,49 +692,68 @@ le%7D%3E -Une %C3%A9tude des diff%C3%A9rents mode de scrutins +Assembl%C3%A9e Nationale : et si on changeait les r%C3%A8gles du jeu ? %3C/h2
42c28b9de6e4071ed726550d7b2398cca695b59d
Update <br>
formatter.js
formatter.js
var dropdownPrep = function(){ var dropdown = document.getElementById("lang"); var option; for (var lang in l10n){ option = document.createElement("option"); option.innerHTML = l10n[lang]; option.value = lang; dropdown.appendChild(option); } } var render = function(){ var results = document.getElementsByClassName('finish'); for (var i = 0; i < results.length; i++){ results[i].style.display = 'block'; } var dropdown = document.getElementById("lang"); var lang = dropdown.value; var final = {}; final[lang] = {}; final[lang]['language'] = dropdown.selectedOptions[0].text; final[lang]["translator"] = document.getElementById('translator').value.replace(/[\"]/g, "\\\""); var unique1 = document.getElementById('unique1').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/><br/>"; var unique2 = document.getElementById('unique2').value.replace(/[\"]/g, "\\\"") + "<br/>"; var unique3 = document.getElementById('unique3').value.replace(/[\"]/g, "\\\"") + "<br/>"; var unique4 = document.getElementById('unique4').value.replace(/[\"]/g, "\\\"") + "<br/>"; final[lang]["unique"] = unique1 + unique2 + unique3 + unique4; var link = document.getElementById('link').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/>"; var age = document.getElementById('age').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/>"; var appropriate = document.getElementById('appropriate').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/>"; var patience = document.getElementById('patience').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/><br/>"; var whatIsSDS = document.getElementById('whatIsSDS').value.replace(/[\"]/g, "\\\"") + "\n"; var selected = " " + document.getElementById('selected').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/projects/55738732/\">" + "https://scratch.mit.edu/projects/55738732/" + "</a>" + "\n"; var ask = document.getElementById('ask').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/><br/>"; var idea = document.getElementById('idea').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/studios/93627/\">" + "https://scratch.mit.edu/studios/93627/" + "</a>" + "\n" + "<br/><br/>"; var wiki = document.getElementById('wiki').value.replace(/[\"]/g, "\\\"") + " <a href=\"http://wiki.scratch.mit.edu/wiki/SDS/\">" + "http://wiki.scratch.mit.edu/wiki/SDS/" + "</a>" + "\n" + "<br/><br/>"; var account = document.getElementById('account').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/users/SDS-Updates/\">" + "@SDS-Updates" + "</a>" + "\n" + "<br/><br/>"; var thumbnail = document.getElementById('thumbnail').value.replace(/[\"]/g, "\\\""); final[lang]["standard"] = link + age + appropriate + patience + whatIsSDS + selected + ask + idea + wiki + account + thumbnail; var curators = document.getElementById('curatorsp').value.replace(/[\"]/g, "\\\""); var result = document.getElementById('result'); final[lang]["curators"] = curators; result.value = JSON.stringify(final,null,2).slice(2,-2) + ","; console.log(JSON.stringify(final,null,2).slice(2,-2) + ","); }; document.onkeyup = render;
JavaScript
0
@@ -902,32 +902,37 @@ %22%5C%5C%5C%22%22) + %22%3Cbr/%3E +%3Cbr/%3E %22;%0A var unique3 @@ -1000,32 +1000,37 @@ %22%5C%5C%5C%22%22) + %22%3Cbr/%3E +%3Cbr/%3E %22;%0A var unique4
7bac886148644686537b2b3008fbaf839e585022
Fix rendering of /about/financial-statements
src/scenes/home/home.js
src/scenes/home/home.js
/* eslint-disable no-console, react/forbid-prop-types */ import React, { Component } from 'react'; import { Route, withRouter, Switch } from 'react-router-dom'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import * as CookieHelpers from 'shared/utils/cookieHelper'; import Login from 'shared/components/login/login'; import IdmeVerify from 'shared/components/idme/idmeverify/idmeverify'; import AuthenticatedRoute from 'shared/components/authenticatedRoute/authenticatedRoute'; import familyImage from 'images/Family-2.jpg'; import Profile from './profile/profile'; import SignUp from './signup/signup'; import MentorRequestsTable from './mentor/mentorRequestsTable/mentorRequestsTable'; import SquadsTable from './squads/squadsTable/squadsTable'; import Dashboard from './dashboard/dashboard'; import MentorsTable from './mentor/mentorsTable/mentorsTable'; import Thanks from './thanks/thanks'; import Team from './team/team'; import Gala from './gala/gala'; import FAQ from './faq/faq'; import Contact from './contact/contact'; import History from './history/history'; import FinancialStatements from './about/financialStatements/financialStatements'; import Header from './header/header'; import Landing from './landing/landing'; import Footer from './footer/footer'; import FourOhFour from './404/fourOhFour'; import MentorRequest from './mentorRequest/mentorRequest'; import SquadsNew from './squads/squadsNew/squadsNew'; import CodeSchools from './codeSchools/codeSchools'; import About from './about/about'; import Press from './press/press'; import ResetPassword from './resetPassword/resetPassword'; import Challenge from './challenge/challenge'; import styles from './home.css'; class Home extends Component { constructor(props) { super(props); this.state = { bgImage: false, bgImageUrl: null, signedIn: false, mentor: false }; this.props.history.listen((location) => { this.setBgImage(location); }); } componentWillMount() { this.setBgImage(this.props.location); this.updateRootAuthState(); } setBgImage(location) { if (location.pathname === '/') { this.setState({ bgChanged: !(this.state.bgImage), bgImage: true, bgImageUrl: familyImage }); } else { this.setState({ bgChanged: this.state.bgImage, bgImage: false, bgImageUrl: null }); } } updateRootAuthState = (cb) => { const cookies = CookieHelpers.getUserStatus(); this.setState({ signedIn: cookies.signedIn, mentor: cookies.mentor, verified: cookies.verified }, () => { if (cb) { cb(this.props.history); } }); } logOut = () => { CookieHelpers.clearAuthCookies(); this.setState({ signedIn: false, mentor: false, verified: false }, () => this.props.history.push('/')); } render() { const { mentor, signedIn, verified } = this.state; const authProps = { signedIn, mentor, verified }; const classes = classNames({ [`${styles.home}`]: true, [`${styles.backgroundImage}`]: this.state.bgImage }); return ( <div className={classes} style={(this.state.bgImage) ? { backgroundImage: `url(${this.state.bgImageUrl})` } : {}} > <Header transparent={this.state.bgImage} logOut={this.logOut} signedIn={signedIn} mentor={mentor} /> <div className={styles.main} > <Switch> <Route path="/home" component={Dashboard} /> <Route path="/code-schools" component={CodeSchools} /> <Route path="/code_schools" component={CodeSchools} /> <Route path="/signup" component={SignUp} /> <Route path="/join" component={SignUp} /> <Route path="/history" component={History} /> <Route path="/sign-up" component={SignUp} /> <Route path="/thanks" component={Thanks} /> <Route path="/team" component={Team} /> <Route path="/faq" component={FAQ} /> <Route path="/contact" component={Contact} /> <Route path="/about" component={About} /> <Route path="/press" component={Press} /> <Route path="/media" component={Press} /> <Route path="/challenge" component={Challenge} /> <Route exact path="/" render={props => ( <Landing {...props} /> )} /> <Route path="/mentor-request" render={() => ( <MentorRequest {...authProps} /> )} /> <Route path="/requests" render={() => ( <MentorRequestsTable {...authProps} /> )} /> <Route path="/squads/new-squad" render={() => ( <SquadsNew {...authProps} /> )} /> <Route exact path="/mentors" render={() => ( <MentorsTable {...authProps} /> )} /> <Route path="/squads" render={() => ( <SquadsTable {...authProps} /> )} /> <Route path="/gala" render={() => ( <Gala {...authProps} /> )} /> <Route path="/newgibill" component={() => (window.location = 'http://www.benefits.va.gov/gibill/post911_gibill.asp')} /> <Route path="/login" render={() => ( <Login updateRootAuthState={this.updateRootAuthState} {...authProps} /> )} /> <AuthenticatedRoute exact path="/profile" isLoggedIn={CookieHelpers.getUserStatus().signedIn} component={Profile} {...authProps} /> <AuthenticatedRoute exact path="/profile/verify" isLoggedIn={CookieHelpers.getUserStatus().signedIn} component={IdmeVerify} updateRootAuthState={this.updateRootAuthState} {...authProps} /> <Route exact path="/about/financial-statements" component={FinancialStatements} /> <Route exact path="/reset_password" component={ResetPassword} /> <Route path="*" component={FourOhFour} /> </Switch> </div> <Footer /> </div> ); } } Home.propTypes = { history: PropTypes.object.isRequired, location: PropTypes.object.isRequired }; export default withRouter(Home);
JavaScript
0.000246
@@ -4530,32 +4530,181 @@ %3CRoute%0A + exact%0A path=%22/about/financial-statements%22%0A component=%7BFinancialStatements%7D%0A /%3E%0A %3CRoute%0A pa @@ -7056,103 +7056,8 @@ /%3E%0A - %3CRoute exact path=%22/about/financial-statements%22 component=%7BFinancialStatements%7D /%3E%0A
452a5f1f19a5b608cb25c037963f2fcd0e96bdf0
allow suppressing download progress via SUPPRESS_DOWNLOAD_PROGRESS environment variable
modules/http-downloader.js
modules/http-downloader.js
var fs = require('fs'), request = require('request'), debug = require('debug')('http-downloader'); function HttpDownloader(infoLogFunction, debugLogFunction) { this._info = infoLogFunction || console.log; this._debug = debugLogFunction || function () { }; this.assumeDownloadedIfExistsAndSizeMatches = true; } HttpDownloader.prototype = { download: function (url, target) { if (this._request) { throw new Error('Already downloading.'); } this._errored = false; var result = this._createResultPromise(); this._url = url; this._target = target; this._tempTarget = target + '.part'; var self = this; this._info('Start download of "' + url + '"'); this._request = request.get(this._url, { timeout: 30000 }) .on('response', function (response) { self._response = response; self._handleResponse(); }) .on('error', function (e) { self._reject('Download failed: ' + (e || 'unknown error')); }); return result; }, abort: function () { if (this._request) { self._errored = true; this._request.abort(); this._clear(); } }, _handleResponse: function () { this._downloadSize = parseInt(this._response.headers['content-length']); if (this._alreadyDownloaded()) { this._request.destroy(); return this._resolve(this._target); } if (fs.existsSync(this._target)) { fs.unlinkSync(this._target); } this._statusSuffix = '% of ' + this._humanSize(this._downloadSize); this._bindOnResponsedata(); this._bindOnResponseEnd(); this._bindOnResponseError(); }, _bindOnResponsedata: function () { this._lastData = new Date(); this._written = 0; var self = this; this._response.on('data', function (data) { self._lastData = new Date(); self._errored = false; self._debug('writing ' + data.length + ' bytes to ' + self._tempTarget); fs.appendFileSync(self._tempTarget, data); self._updateStatus(data); }); }, _updateStatus: function (data) { this._written += data.length; var perc = Math.round((100 * this._written) / this._downloadSize); if (perc != this._lastPerc) { this._writeStatus(perc + this._statusSuffix); this._lastPerc = perc; } }, _writeStatus: function (msg) { this._clearStatus(); process.stdout.write(msg); }, _bindOnResponseEnd: function () { var self = this; this._response.on('end', function () { if (self._errored) { return; } self._clearStatus(); self._rename(self._tempTarget, self._target); self._clear(); }); }, _rename: function (src, dst, attempts) { try { debug('attempt rename of temp file'); fs.renameSync(src, dst) this._clearStatus(); this._info('-> download complete!'); this._resolve(dst) } catch (e) { debug('rename error:', e); if (attempts > 99) { this._reject(['Unable to rename "', src, '" to "', ds, '": ', e].join('')); } else { var self = this; setTimeout(function () { self._rename(src, dst, attempts++); }, 100); } } }, _bindOnResponseError: function () { var self = this; this._response.on('error', function (err) { self._errored = true; self._handleDownloadError(err); }); }, _handleDownloadError: function (err) { this._reject([ 'Download of "', this._url, '" failed: \n', this._errorStringFor(err) ]); }, _errorStringFor: function (err) { if (!err) { return 'Unknown error'; } if (typeof (err.toString) === 'function') { return err.toString(); } return '' + err; }, _clearStatus: function () { process.stdout.write('\r \r'); }, _humanSize: function (size) { var suffixes = ['b', 'kb', 'mb', 'tb', 'pb']; for (var i = 0; i < suffixes.length - 1; i++) { if (size < 1024) { return size.toFixed(2) + suffixes[i]; } size /= 1024; } return size.toFixed(2) + suffixes[suffixes.length - 1]; }, _createResultPromise: function () { var self = this; return new Promise(function (resolve, reject) { self._resolveFunction = resolve; self._rejectFunction = reject; }); }, _resolve: function (data) { debug('resolving final promise!'); this._resolveFunction(data); }, _reject: function (data) { debug('rejecting final promise!'); this._rejectFunction(data); }, _clear: function () { var self = this; ['_request', '_response', '_downloadSize', '_lastPerc', '_resolveFunction', '_rejectFunction', '_lastData', '_statusSuffix' ].forEach(function (prop) { self[prop] = undefined; }); }, _alreadyDownloaded: function () { if (!this.assumeDownloadedIfExistsAndSizeMatches) { return false; } if (!fs.existsSync(this._target)) { return false; } var lstat = fs.lstatSync(this._target); return lstat.size === this._downloadSize; } } module.exports = HttpDownloader;
JavaScript
0
@@ -2061,24 +2061,94 @@ on (data) %7B%0A + if (process.env.SUPPRESS_DOWNLOAD_PROGRESS) %7B%0A return;%0A %7D%0A this._wr
12864cf9b655abc3ff1f3a53316e1898c545b63d
add check for `contains` method to prevent error from getting thrown in IE11 (#566)
packages/components/bolt-icon/src/icon.standalone.js
packages/components/bolt-icon/src/icon.standalone.js
import { h, render, define, props, withComponent, withPreact, css, spacingSizes, hasNativeShadowDomSupport, supportsCSSVars, colorContrast, rgb2hex, } from '@bolt/core'; import PubSub from 'pubsub-js'; import upperCamelCase from 'uppercamelcase'; import * as Icons from '@bolt/components-icons'; import styles from './icon.scss'; const backgroundStyles = [ 'circle', 'square', ]; const colors = [ 'teal', 'blue', ]; @define export class BoltIcon extends withPreact(withComponent()) { static is = 'bolt-icon'; static props = { name: props.string, size: props.string, background: props.string, color: props.string, // programatically spell out the contrast color that needs to get used contrastColor: props.string, } state = { primaryColor: null, secondaryColor: null, } constructor() { super(); this.useShadow = hasNativeShadowDomSupport; this.useCssVars = supportsCSSVars; } connectedCallback() { const elem = this; // listen for page changes to decide when colors need to get recalculated if (!this.useCssVars) { const checkIfColorChanged = function (msg, data) { /** * The container with the class change contains this particular icon element so * we should double-check the color contrast values. */ if (data.target.contains(elem)) { const recalculatedSecondaryColor = colorContrast( rgb2hex(window.getComputedStyle(elem).getPropertyValue('color')), ); elem.setAttribute('contrast-color', recalculatedSecondaryColor); elem.state.secondaryColor = recalculatedSecondaryColor; } }; const colorObserver = PubSub.subscribe('component.icon', checkIfColorChanged); } } render({ props, state }) { const { size, name, color, background, contrastColor } = this.props; const classes = css( 'c-bolt-icon', size && spacingSizes[size] && spacingSizes[size] !== '' ? `c-bolt-icon--${size}` : '', name ? `c-bolt-icon--${name}` : '', color && colors.includes(color) ? `c-bolt-icon--${color}` : '', ); const backgroundClasses = css( 'c-bolt-icon__background-shape', background && backgroundStyles.includes(background) ? `c-bolt-icon__background-shape--${background}` : '', ); const iconClasses = css( 'c-bolt-icon__icon', ); const Icon = name ? upperCamelCase(name) : ''; const IconTag = Icons[Icon]; const iconSize = size && spacingSizes[size] ? spacingSizes[size].replace('rem', '') * (16 / 2) : spacingSizes.medium.replace('rem', '') * (16 / 2); if (supportsCSSVars) { this.state.primaryColor = 'var(--bolt-theme-icon, currentColor)'; this.state.secondaryColor = 'var(--bolt-theme-background, #fff)'; } else { this.state.primaryColor = 'currentColor'; this.state.primaryColorComputed = rgb2hex(window.getComputedStyle(this).getPropertyValue('color')); if (contrastColor) { this.state.secondaryColor = contrastColor; } else { this.state.secondaryColor = colorContrast(this.state.primaryColorComputed); } } return ( <div className={classes}> {this.useShadow && <style>{styles[0][1]}</style> } <IconTag className={iconClasses} size={iconSize} bgColor={this.state.primaryColor} fgColor={this.state.secondaryColor} /> {background && size === 'xlarge' && <span className={backgroundClasses}></span> } </div> ); } } /** * If CSS Vars are unsupported, listen for class changes on the page to selectively * decide when to check to see if an icon component's color should change. */ const observedElements = []; // Observe body + children for changes, but only once. if (!supportsCSSVars && !observedElements.includes(document.body)) { observedElements.push(document.body); const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.attributeName === 'class') { // publish a topic asyncronously PubSub.publish('component.icon', { event: 'color-change', target: mutation.target }); } }); }); // Attach the mutation observer to the body to listen for className changes observer.observe(document.body, { attributes: true, attributeFilter: [ 'class', ], attributeOldValue: false, childList: false, subtree: true, }); }
JavaScript
0
@@ -1353,16 +1353,54 @@ */%0A + if (data.target.contains) %7B%0A @@ -1429,24 +1429,26 @@ ns(elem)) %7B%0A + co @@ -1495,16 +1495,18 @@ ntrast(%0A + @@ -1581,24 +1581,26 @@ ,%0A + );%0A%0A @@ -1597,24 +1597,26 @@ %0A%0A + + elem.setAttr @@ -1674,24 +1674,26 @@ ;%0A + elem.state.s @@ -1732,24 +1732,36 @@ ndaryColor;%0A + %7D%0A %7D%0A @@ -3673,26 +3673,24 @@ %3E%0A %7D%0A - %3C/div%3E%0A
7a6c09de5b48065087b4075f2f7475f600e5ee20
fix search input parent
packages/entity-list/src/modules/searchForm/sagas.js
packages/entity-list/src/modules/searchForm/sagas.js
import {call, put, fork, select, takeLatest, take, all} from 'redux-saga/effects' import {form} from 'tocco-util' import _reduce from 'lodash/reduce' import * as actions from './actions' import {fetchForm, searchFormTransformer} from '../../util/api/forms' import {getPreselectedValues} from '../../util/searchForm' import {fetchEntities, searchFilterTransformer} from '../../util/api/entities' import {SET_INITIALIZED as LIST_SET_INITIALIZED} from '../entityList/actions' import { actions as formActions, getFormValues } from 'redux-form' import * as formActionTypes from 'redux-form/es/actionTypes' import _forOwn from 'lodash/forOwn' import {validateSearchFields} from '../../util/searchFormValidation' import {getSearchInputsForRequest} from '../../util/searchInputs' export const inputSelector = state => state.input export const searchFormSelector = state => state.searchForm export const entityListSelector = state => state.entityList export const searchValuesSelector = getFormValues('searchForm') const FORM_ID = 'searchForm' export default function* sagas() { yield all([ fork(takeLatest, actions.INITIALIZE, initialize), fork(takeLatest, actions.LOAD_SEARCH_FILTERS, loadSearchFilters), fork(takeLatest, formActionTypes.CHANGE, submitSearchFrom), fork(takeLatest, actions.SUBMIT_SEARCH_FORM, submitSearchFrom), fork(takeLatest, actions.RESET_SEARCH, resetSearch), fork(takeLatest, actions.ADVANCED_SEARCH_UPDATE, advancedSearchUpdate) ]) } export function* initialize({payload: {searchFormVisible}}) { const {searchFormName, initialized} = yield select(searchFormSelector) if (!initialized) { const formDefinition = searchFormVisible ? yield call(loadSearchForm, searchFormName) : null yield call(setInitialFormValues, searchFormVisible, formDefinition) yield put(actions.setInitialized()) } } export function* setInitialFormValues(searchFormVisible, formDefinition) { const {preselectedSearchFields, parent} = yield select(inputSelector) const {model} = yield call(getEntityModel) let formValues = preselectedSearchFields ? yield call(getPreselectedValues, preselectedSearchFields, model, null, searchFormVisible) : {} if (parent && !formValues.hasOwnProperty(parent.reverseRelationName)) { formValues[parent.reverseRelationName] = parent.key } if (searchFormVisible && formDefinition) { const fieldDefinitions = yield call(form.getFieldDefinitions, formDefinition) const fromDefaultValues = yield call(form.getDefaultValues, fieldDefinitions) formValues = {...fromDefaultValues, ...formValues} } const transformedFromValues = yield call(transformFieldNames, formValues) yield put(formActions.initialize(FORM_ID, transformedFromValues)) yield put(actions.setValuesInitialized(true)) } export function* transformFieldNames(formValues) { return _reduce(formValues, (acc, val, key) => ( {...acc, [form.transformFieldName(key)]: val} ), {}) } export function* submitSearchFrom() { yield put(formActions.startSubmit(FORM_ID)) const values = yield select(getFormValues(FORM_ID)) const {formDefinition} = yield select(searchFormSelector) const errors = yield call(validateSearchFields, values, formDefinition) yield put(formActions.stopSubmit(FORM_ID, errors)) if (Object.keys(errors).length === 0) { yield put(actions.executeSearch()) } } export function* loadSearchForm(searchFormName) { const formDefinition = yield call(fetchForm, searchFormName, searchFormTransformer) if (formDefinition) { yield put(actions.setFormDefinition(formDefinition)) } else { yield put(actions.setShowFullTextSearchForm(true)) } return formDefinition } export function* getEntityModel() { let entityList = yield select(entityListSelector) if (!entityList.initialized) { yield take(LIST_SET_INITIALIZED) } entityList = yield select(entityListSelector) return entityList.entityModel } export function* loadSearchFilters({payload}) { const {model, group} = payload const {searchFilter} = yield select(searchFormSelector) if (!searchFilter) { const params = { searchInputs: { entity: model, ...(group ? {'relSearch_filter_group.unique_id': group} : {}) }, fields: ['unique_id'] } const json = yield call(fetchEntities, 'Search_filter', params) const entities = yield call(searchFilterTransformer, json) yield put(actions.setSearchFilter(entities)) } return searchFilter } export function* resetSearch() { yield put(formActions.reset('searchForm')) yield call(submitSearchFrom) } const getFilterArray = v => { if (Array.isArray(v)) { return v.map(e => e.uniqueId) } else { return [v.uniqueId] } } export function* getSearchInputs() { const {valuesInitialized} = yield select(searchFormSelector) if (!valuesInitialized) { yield take(actions.SET_VALUES_INITIALIZED) } const searchInputs = yield select(searchValuesSelector) const {entityModel} = yield select(entityListSelector) const searchInputsRenamed = {} _forOwn(searchInputs, (value, key) => { if (key === 'searchFilter' && value) { searchInputsRenamed._filter = getFilterArray(value) } else if (key === 'txtFulltext') { searchInputsRenamed._search = value } else { searchInputsRenamed[form.transformFieldNameBack(key)] = value } }) return yield call(getSearchInputsForRequest, searchInputsRenamed, entityModel) } export function* advancedSearchUpdate({payload: {field, ids}}) { yield put(formActions.change(FORM_ID, form.transformFieldName(field), ids)) }
JavaScript
0
@@ -2316,16 +2316,22 @@ nName%5D = + %7Bkey: parent. @@ -2333,16 +2333,17 @@ rent.key +%7D %0A %7D%0A%0A
3f0c3ac42ce1b5a557c0a1b80273cc44d518a9a9
check formDefinition for undefined
packages/entity-list/src/modules/searchForm/sagas.js
packages/entity-list/src/modules/searchForm/sagas.js
import {call, put, fork, select, takeLatest, take, all} from 'redux-saga/effects' import {form} from 'tocco-util' import _reduce from 'lodash/reduce' import * as actions from './actions' import {fetchForm, searchFormTransformer} from '../../util/api/forms' import {getPreselectedValues} from '../../util/searchForm' import {fetchEntities, searchFilterTransformer} from '../../util/api/entities' import {SET_INITIALIZED as LIST_SET_INITIALIZED} from '../entityList/actions' import { actions as formActions, getFormValues } from 'redux-form' import * as formActionTypes from 'redux-form/es/actionTypes' import _forOwn from 'lodash/forOwn' import {validateSearchFields} from '../../util/searchFormValidation' import {getSearchInputsForRequest} from '../../util/searchInputs' export const inputSelector = state => state.input export const searchFormSelector = state => state.searchForm export const entityListSelector = state => state.entityList export const searchValuesSelector = getFormValues('searchForm') const FORM_ID = 'searchForm' export default function* sagas() { yield all([ fork(takeLatest, actions.INITIALIZE, initialize), fork(takeLatest, actions.LOAD_SEARCH_FILTERS, loadSearchFilters), fork(takeLatest, formActionTypes.CHANGE, submitSearchFrom), fork(takeLatest, actions.SUBMIT_SEARCH_FORM, submitSearchFrom), fork(takeLatest, actions.RESET_SEARCH, resetSearch), fork(takeLatest, actions.ADVANCED_SEARCH_UPDATE, advancedSearchUpdate) ]) } export function* initialize({payload: {searchFormVisible}}) { const {searchFormName, initialized} = yield select(searchFormSelector) if (!initialized) { const formDefinition = searchFormVisible ? yield call(loadSearchForm, searchFormName) : null yield call(setInitialFormValues, searchFormVisible, formDefinition) yield put(actions.setInitialized()) } } export function* setInitialFormValues(searchFormVisible, formDefinition) { const {preselectedSearchFields, parent} = yield select(inputSelector) const {model} = yield call(getEntityModel) let formValues = preselectedSearchFields ? yield call(getPreselectedValues, preselectedSearchFields, model, null, searchFormVisible) : {} if (parent && !formValues.hasOwnProperty(parent.reverseRelationName)) { formValues[parent.reverseRelationName] = parent.key } if (searchFormVisible && formDefinition) { const fieldDefinitions = yield call(form.getFieldDefinitions, formDefinition) const fromDefaultValues = yield call(form.getDefaultValues, fieldDefinitions) formValues = {...fromDefaultValues, ...formValues} } const transformedFromValues = yield call(transformFieldNames, formValues) yield put(formActions.initialize(FORM_ID, transformedFromValues)) yield put(actions.setValuesInitialized(true)) } export function* transformFieldNames(formValues) { return _reduce(formValues, (acc, val, key) => ( {...acc, [form.transformFieldName(key)]: val} ), {}) } export function* submitSearchFrom() { yield put(formActions.startSubmit(FORM_ID)) const values = yield select(getFormValues(FORM_ID)) const {formDefinition} = yield select(searchFormSelector) const errors = yield call(validateSearchFields, values, formDefinition) yield put(formActions.stopSubmit(FORM_ID, errors)) if (Object.keys(errors).length === 0) { yield put(actions.executeSearch()) } } export function* loadSearchForm(searchFormName) { const formDefinition = yield call(fetchForm, searchFormName, searchFormTransformer) if (formDefinition !== null) { yield put(actions.setFormDefinition(formDefinition)) } else { yield put(actions.setShowFullTextSearchForm(true)) } return formDefinition } export function* getEntityModel() { let entityList = yield select(entityListSelector) if (!entityList.initialized) { yield take(LIST_SET_INITIALIZED) } entityList = yield select(entityListSelector) return entityList.entityModel } export function* loadSearchFilters({payload}) { const {model, group} = payload const {searchFilter} = yield select(searchFormSelector) if (!searchFilter) { const params = { searchInputs: { entity: model, ...(group ? {'relSearch_filter_group.unique_id': group} : {}) }, fields: ['unique_id'] } const json = yield call(fetchEntities, 'Search_filter', params) const entities = yield call(searchFilterTransformer, json) yield put(actions.setSearchFilter(entities)) } return searchFilter } export function* resetSearch() { yield put(formActions.reset('searchForm')) yield call(submitSearchFrom) } const getFilterArray = v => { if (Array.isArray(v)) { return v.map(e => e.uniqueId) } else { return [v.uniqueId] } } export function* getSearchInputs() { const {valuesInitialized} = yield select(searchFormSelector) if (!valuesInitialized) { yield take(actions.SET_VALUES_INITIALIZED) } const searchInputs = yield select(searchValuesSelector) const {entityModel} = yield select(entityListSelector) const searchInputsRenamed = {} _forOwn(searchInputs, (value, key) => { if (key === 'searchFilter' && value) { searchInputsRenamed._filter = getFilterArray(value) } else if (key === 'txtFulltext') { searchInputsRenamed._search = value } else { searchInputsRenamed[form.transformFieldNameBack(key)] = value } }) return yield call(getSearchInputsForRequest, searchInputsRenamed, entityModel) } export function* advancedSearchUpdate({payload: {field, ids}}) { yield put(formActions.change(FORM_ID, form.transformFieldName(field), ids)) }
JavaScript
0.000002
@@ -3535,17 +3535,8 @@ tion - !== null ) %7B%0A
dbfc7b7a046cf0110cdd30deda33ba6cbc9038e3
Improve Message storybook demo
packages/fyndiq-ui-test/stories/component-message.js
packages/fyndiq-ui-test/stories/component-message.js
import React from 'react' import { storiesOf } from '@storybook/react' import Button from 'fyndiq-component-button' import { Message, Wrapper, addMessage } from 'fyndiq-component-message' import { Error, Truck, Warning } from 'fyndiq-icons' storiesOf('Message', module) .addWithInfo('default', () => <Message>Content</Message>) .addWithInfo('color themes', () => ( <div> <div> <Message icon={<Truck />}>Type info</Message> </div> <div> <Message icon={<Truck />} type="confirm"> Type confirm </Message> </div> <div> <Message icon={<Warning />} type="warn"> Type warn </Message> </div> <div> <Message icon={<Error />} type="error"> Type error </Message> </div> </div> )) .addWithInfo('action', () => ( <div> <Wrapper /> <Button onClick={() => addMessage( <Message icon={<Truck />} type="confirm"> Type confirm {Math.random()} </Message>, ) } > Show message </Button> </div> ))
JavaScript
0
@@ -77,16 +77,46 @@ t Button +, %7B Wrapper as ButtonWrapper %7D from 'f @@ -219,16 +219,22 @@ import %7B + Star, Error, @@ -247,16 +247,27 @@ Warning +, Checkmark %7D from @@ -527,36 +527,40 @@ %3CMessage icon=%7B%3C -Truc +Checkmar k /%3E%7D type=%22conf @@ -883,13 +883,25 @@ o('a -ction +ddMessage utility ', ( @@ -904,35 +904,46 @@ ', () =%3E (%0A %3C -div +React.Fragment %3E%0A %3CWrapper @@ -1029,28 +1029,32 @@ sage icon=%7B%3C -Truc +Checkmar k /%3E%7D type=%22 @@ -1082,48 +1082,684 @@ T -ype confirm %7BMath.random()%7D%0A +he message has been successfully shown%0A %3C/Message%3E,%0A )%0A %7D%0A %3E%0A Show message%0A %3C/Button%3E%0A %3C/React.Fragment%3E%0A ))%0A .addWithInfo('custom timeout', () =%3E (%0A %3CReact.Fragment%3E%0A %3CWrapper /%3E%0A %3CButtonWrapper%3E%0A %3CButton%0A onClick=%7B() =%3E%0A addMessage(%0A %3CMessage icon=%7B%3CWarning /%3E%7D type=%22warn%22 timeout=%7B1000%7D%3E%0A I don&apos;t stay very long%0A %3C/Message%3E,%0A )%0A %7D%0A %3E%0A Show 1s message%0A %3C/Button%3E%0A %3CButton%0A onClick=%7B() =%3E%0A addMessage(%0A %3CMessage timeout=%7B10000%7D%3EYou OK if I stay a bit long? %3C/Me @@ -1768,34 +1768,38 @@ age%3E,%0A -)%0A + )%0A %7D%0A @@ -1790,34 +1790,38 @@ %7D%0A + + %3E%0A + Show mes @@ -1813,32 +1813,36 @@ Show +10s message%0A %3C/Butt @@ -1821,32 +1821,34 @@ how 10s message%0A + %3C/Button%3E%0A @@ -1847,24 +1847,58 @@ Button%3E%0A -%3C/div + %3C/ButtonWrapper%3E%0A %3C/React.Fragment %3E%0A ))%0A
f87480c0594cd3945b81d13bc2c4f4c682b5bd8f
deploy to `aframe-core` GitHub Pages since remote name changed (issue #289)
scripts/gh-pages.js
scripts/gh-pages.js
#!/usr/bin/env node /** * Fancy script to deploy to GitHub Pages * ====================================== * * Sample usage * ------------ * * % node ./scripts/gh-pages * gh-pages -d dist -r [email protected]:MozVR/vr-markup.git * * % node ./scripts/gh-pages cvan * gh-pages -d dist -r [email protected]:cvan/vr-markup.git * * % node ./scripts/gh-pages [email protected]:dmarcos/vr-markup.git * gh-pages -d dist -r [email protected]:dmarcos/vr-markup.git * */ var spawn = require('child_process').spawn; var ghpages = require('gh-pages'); var path = require('path'); var repo = { username: 'MozVR', name: 'vr-markup' }; var arg = process.argv[2]; if (arg) { if (arg.indexOf(':') === -1) { repo.username = arg; } else { repo.url = arg; var usernameMatches = arg.match(':(.+)/'); if (usernameMatches) { repo.username = usernameMatches[1]; } } } if (!repo.url) { repo.url = '[email protected]:' + repo.username + '/' + repo.name + '.git'; } repo.ghPagesUrl = 'https://' + repo.username + '.github.io/' + repo.name + '/'; console.log('Publishing to', repo.url); ghpages.clean(); // Wipe out the checkout from scratch every time in case we change repos. ghpages.publish(path.join(process.cwd(), 'gh-pages'), { repo: repo.url, dotfiles: true, logger: function (message) { console.log(message); } }, function () { console.log('Published'); console.log(repo.ghPagesUrl); spawn('open', [repo.ghPagesUrl]); });
JavaScript
0
@@ -213,25 +213,27 @@ m:MozVR/ -vr-markup +aframe-core .git%0A *%0A @@ -309,25 +309,27 @@ om:cvan/ -vr-markup +aframe-core .git%0A *%0A @@ -376,33 +376,35 @@ com:dmarcos/ -vr-markup +aframe-core .git%0A * gh-p @@ -442,25 +442,27 @@ dmarcos/ -vr-markup +aframe-core .git%0A *%0A @@ -622,17 +622,19 @@ e: ' -vr-markup +aframe-core '%0A%7D;
4a061f2ec5befc2e454afdc01d30768b0fe16714
remove not used variable
src/GoogleApiComponent.js
src/GoogleApiComponent.js
import React from 'react' import ReactDOM from 'react-dom' import {ScriptCache} from './lib/ScriptCache' import GoogleApi from './lib/GoogleApi' const defaultMapConfig = {} const defaultCreateCache = (options) => { options = options || {}; const apiKey = options.apiKey; const libraries = options.libraries || ['places']; const version = options.version || '3.29'; const language = options.language || 'en'; return ScriptCache({ google: GoogleApi({ apiKey: apiKey, language: language, libraries: libraries, version: version }) }); }; export const wrapper = (options) => (WrappedComponent) => { const apiKey = options.apiKey; const libraries = options.libraries || ['places']; const version = options.version || '3'; const createCache = options.createCache || defaultCreateCache; class Wrapper extends React.Component { constructor(props, context) { super(props, context); this.scriptCache = createCache(options); this.scriptCache.google.onLoad(this.onLoad.bind(this)) this.state = { loaded: false, map: null, google: null } } onLoad(err, tag) { this._gapi = window.google; this.setState({loaded: true, google: this._gapi}) } render() { const props = Object.assign({}, this.props, { loaded: this.state.loaded, google: window.google }); return ( <div> <WrappedComponent {...props}/> <div ref='map'/> </div> ) } } return Wrapper; } export default wrapper;
JavaScript
0.000022
@@ -687,142 +687,8 @@ %3E %7B%0A - const apiKey = options.apiKey;%0A const libraries = options.libraries %7C%7C %5B'places'%5D;%0A const version = options.version %7C%7C '3';%0A
febe98e0bdbc4f53c219cfbda1386efe957aab3c
tweak allows jblast to use the module, arbitrary region handling.
src/JBrowse/View/FASTA.js
src/JBrowse/View/FASTA.js
define([ 'dojo/_base/declare', 'dojo/dom-construct', 'dijit/Toolbar', 'dijit/form/Button', 'JBrowse/Util', 'JBrowse/has' ], function( declare, dom, Toolbar, Button, Util, has ) { return declare(null, { constructor: function( args ) { this.width = args.width || 78; this.htmlMaxRows = args.htmlMaxRows || 15; this.track = args.track; this.canSaveFiles = args.track && args.track._canSaveFiles && args.track._canSaveFiles(); // hook point if (typeof this.initData === 'function') this.initData(args); }, renderHTML: function( region, seq, parent ) { var thisB = this; var text = this.renderText( region, seq ); var lineCount = text.match( /\n/g ).length + 1; var container = dom.create('div', { className: 'fastaView' }, parent ); if( this.canSaveFiles ) { var toolbar = new Toolbar().placeAt( container ); var thisB = this; // hook point if (typeof thisB.addButtons === 'function') thisB.addButtons(region, seq, toolbar); toolbar.addChild( new Button( { iconClass: 'dijitIconSave', label: 'FASTA', title: 'save as FASTA', disabled: ! has('save-generated-files'), onClick: function() { thisB.track._fileDownload( { format: 'FASTA', filename: Util.assembleLocString(region)+'.fasta', data: text }); } })); } var textArea = dom.create('textarea', { className: 'fasta', cols: this.width, rows: Math.min( lineCount, this.htmlMaxRows ), readonly: true }, container ); var c = 0; textArea.innerHTML = text.replace(/\n/g, function() { return c++ ? '' : "\n"; }); return container; }, renderText: function( region, seq ) { return '>' + region.ref + ' '+Util.assembleLocString(region) + ( region.type ? ' class='+region.type : '' ) + ' length='+(region.end - region.start) + "\n" + this._wrap( seq, this.width ); }, _wrap: function( string, length ) { length = length || this.width; return string.replace( new RegExp('(.{'+length+'})','g'), "$1\n" ); } }); });
JavaScript
0
@@ -315,32 +315,144 @@ gs ) %7B%0A %0A + if (typeof args === 'undefined') %7B%0A this.width = 78;%0A return;%0A %7D;%0A %0A this.wid @@ -2558,24 +2558,59 @@ on, seq ) %7B%0A + console.log('renderText');%0A retu
2dbd09164d6df6170edcd0afb2f1921f29d5536f
remove flat pollyfill in get-files
get-files.js
get-files.js
const corePath = require('path') const fs = require('fs') const junk = require('junk') const once = require('once') const parallel = require('run-parallel') // TODO: When Node 10 support is dropped, replace this with Array.prototype.flat function flat (arr1) { return arr1.reduce( (acc, val) => Array.isArray(val) ? acc.concat(flat(val)) : acc.concat(val), [] ) } function notHidden (file) { return file[0] !== '.' } function traversePath (path, fn, cb) { fs.stat(path, (err, stats) => { if (err) return cb(err) if (stats.isDirectory()) { fs.readdir(path, (err, entries) => { if (err) return cb(err) parallel(entries.filter(notHidden).filter(junk.not).map(entry => cb => { traversePath(corePath.join(path, entry), fn, cb) }), cb) }) } else if (stats.isFile()) { fn(path, cb) } // Ignore other types (not a file or directory) }) } /** * Convert a file path to a lazy readable stream. * @param {string} path * @return {function} */ function getFilePathStream (path) { return () => fs.createReadStream(path) } function getFiles (path, keepRoot, cb) { traversePath(path, getFileInfo, (err, files) => { if (err) return cb(err) if (Array.isArray(files)) files = flat(files) else files = [files] path = corePath.normalize(path) if (keepRoot) { path = path.slice(0, path.lastIndexOf(corePath.sep) + 1) } if (path[path.length - 1] !== corePath.sep) path += corePath.sep files.forEach(file => { file.getStream = getFilePathStream(file.path) file.path = file.path.replace(path, '').split(corePath.sep) }) cb(null, files) }) } function getFileInfo (path, cb) { cb = once(cb) fs.stat(path, (err, stat) => { if (err) return cb(err) const info = { length: stat.size, path } cb(null, info) }) } module.exports = getFiles
JavaScript
0
@@ -155,240 +155,8 @@ ')%0A%0A -// TODO: When Node 10 support is dropped, replace this with Array.prototype.flat%0Afunction flat (arr1) %7B%0A return arr1.reduce(%0A (acc, val) =%3E Array.isArray(val)%0A ? acc.concat(flat(val))%0A : acc.concat(val),%0A %5B%5D%0A )%0A%7D%0A%0A func @@ -1047,17 +1047,18 @@ = f -lat(files +iles.flat( )%0A
f5952a501e6e65a6e89762676f9b7168f95720d6
update ColGroup
src/_ColGroup/ColGroup.js
src/_ColGroup/ColGroup.js
/** * @file ColGroup component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import isEmpty from 'lodash/isEmpty'; import TableFragment from '../_statics/TableFragment'; import HorizontalAlign from '../_statics/HorizontalAlign'; import SelectMode from '../_statics/SelectMode'; import SelectAllMode from '../_statics/SelectAllMode'; import SortingType from '../_statics/SortingType'; import Util from '../_vendors/Util'; class ColGroup extends Component { static Fragment = TableFragment; static Align = HorizontalAlign; static SelectMode = SelectMode; static SelectAllMode = SelectAllMode; static SortingType = SortingType; constructor(props, ...restArgs) { super(props, ...restArgs); } getColStyle = column => { const result = {}; if (column.width != null) { result.width = column.width; } if (column.minWidth != null) { result.minWidth = column.minWidth; } return isEmpty(result) ? null : result; }; render() { const {columns} = this.props; return columns ? <colgroup> { columns.map(({column, span}, index) => column ? <col key={index} style={this.getColStyle(column)} span={span && span > 1 ? span : null}/> : null ) } </colgroup> : null; } } ColGroup.propTypes = { /** * Children passed into table header. */ columns: PropTypes.arrayOf(PropTypes.shape({ /** * fixed position of column ( true / 'left' / 'right' ) */ fixed: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(Util.enumerateValue(HorizontalAlign))]), /** * width of column */ width: PropTypes.number, /** * minimum width of column */ minWidth: PropTypes.number, /** * align of current column */ align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The class name of header. */ headClassName: PropTypes.string, /** * Override the styles of header. */ headStyle: PropTypes.object, /** * align of table header cell */ headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table head. * (1) callback: * function (tableData, colIndex) { * return colIndex; * } * * (2) others: * render whatever you pass */ headRenderer: PropTypes.any, /** * column span of table header */ headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * The class name of td. */ bodyClassName: PropTypes.string, /** * Override the styles of td. */ bodyStyle: PropTypes.object, /** * align of table body cell */ bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table body. * (1) callback: * function (rowData, rowIndex, colIndex) { * return rowData.id; * } * * (2) others: * render whatever you pass */ bodyRenderer: PropTypes.any, /** * column span of table body */ bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * The class name of footer. */ footClassName: PropTypes.string, /** * Override the styles of footer. */ footStyle: PropTypes.object, /** * align of table footer cell */ footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table foot. * (1) callback: * function (tableData, colIndex) { * return colIndex; * } * * (2) others: * render whatever you pass */ footRenderer: PropTypes.any, /** * column span of table foot */ footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * If true,this column can be sorted. */ sortable: PropTypes.bool, /** * Sorting property. */ sortingProp: PropTypes.string, defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)) })).isRequired }; export default ColGroup;
JavaScript
0
@@ -1818,15 +1818,8 @@ mn ( - true / 'le @@ -1864,45 +1864,8 @@ xed: - PropTypes.oneOfType(%5BPropTypes.bool, Pro @@ -1914,18 +1914,16 @@ lAlign)) -%5D) ,%0A%0A
a04cc4402fed422526feb54d49630fb1c3c400bb
Make FastScroll a class, don't register by default
client-vendor/after-body/fastScroll/fastScroll.js
client-vendor/after-body/fastScroll/fastScroll.js
var fastScroll = (function() { // Used to track the enabling of hover effects var enableTimer = 0; /* * Listen for a scroll and use that to remove * the possibility of hover effects */ window.addEventListener('scroll', function() { clearTimeout(enableTimer); removeHoverClass(); enableTimer = setTimeout(addHoverClass, 500); }, false); /** * Removes the hover class from the body. Hover styles * are reliant on this class being present */ function removeHoverClass() { if ('none' !== document.body.style.pointerEvents) { document.body.style.pointerEvents = 'none'; } } /** * Adds the hover class to the body. Hover styles * are reliant on this class being present */ function addHoverClass() { document.body.style.pointerEvents = 'auto'; } })();
JavaScript
0
@@ -1,9 +1,26 @@ +(function() %7B%0A%0A var -f +F astS @@ -27,17 +27,16 @@ croll = -( function @@ -40,481 +40,374 @@ ion( -) %7B%0A%0A%09// Used to track the enabling of hover effects%0A%09var enableTimer = 0;%0A%0A%09/*%0A%09 * Listen for a scroll and use that to remove%0A%09 * the possibility of hover effects%0A%09 */%0A%0A%09window.addEventListener('scroll', function() %7B%0A%09%09clearTimeout(enableTimer);%0A%09%09removeHoverClass();%0A%09%09enableTimer = setTimeout(addHoverClass, 500);%0A%09%7D, false);%0A%0A%09/**%0A%09 * Removes the hover class from the body. Hover styles%0A%09 * are reliant on this class being present%0A%09 */%0A%09function removeHoverClass() %7B%0A%09%09 +delay) %7B%0A this.delay = delay %7C%7C 500;%0A this.enableTimer = 0;%0A%0A var self = this;%0A this.scrollCallback = function() %7B%0A self._onScroll();%0A %7D;%0A window.addEventListener('scroll', this.scrollCallback, false);%0A %7D;%0A%0A FastScroll.prototype = %7B%0A enableTimer: null,%0A delay: null,%0A scrollCallback: null,%0A%0A removeHoverClass: function() %7B%0A if ( @@ -458,11 +458,16 @@ ) %7B%0A -%09%09%09 + docu @@ -510,197 +510,432 @@ e';%0A -%09%09%7D%0A%09%7D%0A%0A%09/**%0A%09 * Adds the h + %7D%0A %7D,%0A%0A addH over - c +C lass - to the body. Hover styles%0A%09 * are reliant on this class being present%0A%09 */%0A%09function addHoverClass() %7B%0A%09%09document.body.style.pointerEvents = 'auto';%0A%09%7D +: function() %7B%0A document.body.style.pointerEvents = 'auto';%0A %7D,%0A%0A destroy: function() %7B%0A window.removeEventListener('scroll', this.scrollCallback, false);%0A %7D,%0A%0A _onScroll: function() %7B%0A clearTimeout(this.enableTimer);%0A this.removeHoverClass();%0A this.enableTimer = setTimeout(this.addHoverClass, this.delay);%0A %7D%0A %7D;%0A%0A window.FastScroll = FastScroll;%0A %0A%7D)(
8e05340a7a4d1ee0f70798ad0d6f31621431146b
Substringing cities to 20 characters
client/app/entityService/entityService.service.js
client/app/entityService/entityService.service.js
'use strict'; // angular.module('memexLinkerApp') // .service('entityService', function () { // // AngularJS will instantiate a singleton by calling "new" on this function // }); angular .module('memexLinkerApp') .factory('entityService', entityService); entityService.$inject = ['$http', '$q', '$resource', 'linkUtils', 'lodash']; // API endpoints // /api/v1/search?size=10&page=1&count=yes -d query=fun -XPOST var _SEARCH_URL = '/api/v1/search'; function entityService($http, $q, $resource, linkUtils, lodash) { var _ = lodash; var EntityResource = $resource('/api/v1/entity/:id', {}, {'query': {method: 'GET', isArray: false }}); var SuggestResource = $resource('/api/v1/entity/:id/suggest', {}, {'query': {method: 'GET', isArray: false }}); var SimilarImageResource = $resource('/api/v1/image/similar', {}, {'query': {method: 'GET', isArray: false }}); var sources = { 1 : 'Backpage', 2 : 'Craigslist', 3 : 'Classivox', 4 : 'MyProviderGuide', 5 : 'NaughtyReviews', 6 : 'RedBook', 7 : 'CityVibe', 8 : 'MassageTroll', 9 : 'RedBookForum', 10 : 'CityXGuide', 11 : 'CityXGuideForum', 12 : 'RubAds', 13 : 'Anunico', 14 : 'SipSap', 15 : 'EscortsInCollege', 16 : 'EscortPhoneList', 17 : 'EroticMugshots', 18 : 'EscortsAdsXXX', 19 : 'EscortsinCA', 20 : 'EscortsintheUS', 21 : 'LiveEscortReviws', 22 : 'MyProviderGuideForum', 23 : 'USASexGuide', 24 : 'EroticReview', 25 : 'AdultSearch', 26 : 'HappyMassage', 27: 'UtopiaGuide', 28 : 'MissingKids' }; var service = { search: search, Entity: EntityResource, Suggest: SuggestResource, SimilarImage: SimilarImageResource, sources: sources }; return service; // $http.post(_SEARCH_URL, {query : $scope.elasticSearchText}) // console.log("bonjour") // console.log($scope.elasticSearchText) /** * [search description] * @param String query [description] * @param Integer size [description] * @param Integer page [description] * @return Array [description] */ function search(query, size, page) { console.log('entityService:search'); var deferred = $q.defer(); var params = { size: size, page: page, count: 'yes' }; $http.post(_SEARCH_URL, {query:query}, {params:params}).then(function(response){ // Callback when response is available. var entities = _.map(response.data.entities, function(e) { var entity = _formatEntity(e); return entity; }); deferred.resolve(entities); }, function(response){ // Callback when an error occurs or server returns response with an error status. deferred.reject(response); }); return deferred.promise; } /** * Cleans up 'entites'. * @param {Object} rawEntity * @return {[type]} [description] */ function _formatEntity(rawEntity) { var ads = rawEntity._source.base; // Aggregate ad details var postTimes = _.map(ads, function(ad){ //console.log(ad); return new Date(ad.posttime); }); var lastPostTime = _.max(postTimes); var firstPostTime = _.min(postTimes); var ages = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'age')).sort(); var rates60 = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'rate60')).sort(); var websites=[]; var sourcesid = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'sources_id')); for (var i = 0; i < sourcesid.length; i++) { websites = websites.concat(sources[sourcesid[i]]); } websites = _.filter(_.uniq(websites), function(element){ return ! _.isUndefined(element); }); var titles = linkUtils.collectAdProperty(ads, 'title'); var texts = linkUtils.collectAdProperty(ads, 'text'); var names = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'name')); // TODO: the city field can contain garbage, like html tags. var cities = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'city')); //var youtube = uniqueFlatAndDefined(collectAdProperty(ads, 'youtube')); //var instagram = uniqueFlatAndDefined(collectAdProperty(ads, 'instagram')); //var twitter = uniqueFlatAndDefined(collectAdProperty(ads, 'twitter')); //var ethnicity = uniqueFlatAndDefined(collectAdProperty(ads, 'ethnicity')); var imageUrls = _.uniq(lodash.flatten( _.map(ads, function(ad) { return ad.image_locations; }), true)); imageUrls = _.filter(imageUrls, function(element){ return ! _.isUndefined(element); }); var faceImageUrls = _.uniq(lodash.flatten( _.map(ads, function(ad) { return ad.face_image_url; }), true )); faceImageUrls = _.filter(faceImageUrls, function(element){ return ! _.isUndefined(element); }); var entity = { id: rawEntity._id, phones: [], names: names, nPosts: ads.length, firstPostTime: firstPostTime, lastPostTime: lastPostTime, websites: websites, cities: cities, ages: ages, rates60: rates60, imageUrls: [], faceImageUrls: faceImageUrls, nSuggestedByImage: 0, nSuggestedByPhone: 0, nSuggestedByText: 0, socialAccounts: [], titles: titles, texts: texts }; return entity; } }
JavaScript
0.999991
@@ -1689,151 +1689,8 @@ e;%0A%0A -%09// $http.post(_SEARCH_URL, %7Bquery : $scope.elasticSearchText%7D)%0A // %09 %09console.log(%22bonjour%22)%0A%0A%09// %09%09console.log($scope.elasticSearchText) %0A%0A%09/ @@ -3806,24 +3806,126 @@ , 'city'));%0A +%09%09for (var i = 0; i %3C cities.length; i++) %7B%0A cities%5Bi%5D=cities%5Bi%5D.substring(0,20);%0A %7D;%0A %09%09//var yout
0c4c0d0c49f43a9b605fd0d00c5141c7949ba8f6
Fix images spinner (shows up when user has no backends)
src/mist/io/static/js/app/controllers/backends.js
src/mist/io/static/js/app/controllers/backends.js
define('app/controllers/backends', [ 'app/models/backend', 'app/models/rule', 'ember' ], /** * Backends controller * * @returns Class */ function(Backend, Rule) { return Ember.ArrayController.extend({ content: [], machineCount: 0, imageCount: 0, loadingImages: true, // TODO make this property dynamic according to all backends states state: "waiting", ok: false, loadingMachines: function() { for (var i = 0; i < this.content.length; i++) { if (this.content[i].loadingMachines) { return true; } } return false; }.property('@each.loadingMachines'), loadingImagesObserver: function() { for (var i = 0; i < this.content.length; i++) { if (this.content[i].loadingImages) { this.set('loadingImages', true); return; } } this.set('loadingImages', false); }.observes('[email protected]'), isOK: function() { if(this.state == 'state-ok') { this.set('ok', true); } else { this.set('ok', false); } }.observes('state'), getBackendById: function(backendId) { for (var i = 0; i < this.content.length; i++) { if (this.content[i].id == backendId) { return this.content[i]; } } return null; }, getMachineById: function(backendId, machineId) { for (var i = 0; i < this.content.length; i++) { if (this.content[i].id == backendId) { for (var j=0; j < this.content[i].machines.content.length; j++) { if (this.content[i].machines.content[j].id == machineId) { return this.content[i].machines.content[j]; } } } } return null; }, getMachineCount: function() { var count = 0; this.content.forEach(function(item) { count += item.machines.get('length', 0); }); this.set('machineCount', count); }, getSelectedMachineCount: function() { var count = 0; this.content.forEach(function(item) { count += item.machines.filterProperty('selected', true).get('length'); }); this.set('selectedMachineCount', count); }, getImageCount: function() { var count = 0; this.content.forEach(function(item){ count += item.images.get('length', 0); }); this.set('imageCount', count); }, getSelectedMachine: function() { if(this.selectedMachineCount == 1) { var that = this; this.content.forEach(function(item) { var machines = item.machines.filterProperty('selected', true); if(machines.get('length') == 1) { that.set('selectedMachine', machines[0]); return; } }); } else { this.set('selectedMachine', null); } }, checkMonitoring: function() { if (!Mist.authenticated) { return; } var that = this; $.ajax({ url: '/monitoring', type: 'GET', dataType: 'json', headers: { "cache-control": "no-cache" }, success: function(data) { machines = data.machines; Mist.set('auth_key', data.auth_key); Mist.set('monitored_machines', data.machines); Mist.set('current_plan', data.current_plan); Mist.set('user_details', data.user_details); //now loop on backend_id, machine_id list of lists and check if pair found machines.forEach(function(machine_tuple){ var b,m; var backend_id = machine_tuple[0]; var machine_id = machine_tuple[1]; for (b=0; b < Mist.backendsController.content.length; b++) { if (Mist.backendsController.content[b]['id'] == backend_id) { break; } } if (b != Mist.backendsController.content.length) { for (m=0; m < Mist.backendsController.content[b].machines.content.length; m++) { if (Mist.backendsController.content[b]['machines'].content[m]['id'] == machine_id) { Mist.backendsController.content[b].machines.content[m].set('hasMonitoring', true); break; } } } }); var rules = data.rules; for (ruleId in rules){ var isInController = false; for (r=0; r < Mist.rulesController.content.length; r++) { if (Mist.rulesController.content[r]['id'] == ruleId) { isInController = true; break; } } if (!(isInController)) { var rule = {}; rule['id'] = ruleId; rule['machine'] = that.getMachineById(rules[ruleId]['backend'], rules[ruleId]['machine']); if (!rule['machine']) { // Mist hasn't loaded this machine yet rule['backend_id'] = rules[ruleId]['backend']; rule['machine_id'] = rules[ruleId]['machine']; } rule['metric'] = rules[ruleId]['metric']; rule['operator'] = Mist.rulesController.getOperatorByTitle(rules[ruleId]['operator']); rule['value'] = rules[ruleId]['value']; rule['actionToTake'] = rules[ruleId]['action']; rule['command'] = rules[ruleId]['command']; rule['maxValue'] = rules[ruleId]['max_value']; if (rule['maxValue'] > 100) { rule['unit'] = 'KB/s'; } else if (rule['metric'] == 'cpu' || rule['metric'] == 'ram') { rule['unit'] = '%'; } else { rule['unit'] = ''; } Mist.rulesController.pushObject(Rule.create(rule)); } } Mist.rulesController.redrawRules(); }, error: function(){ Mist.notificationController.notify('Error checking monitoring'); } }); }, init: function() { this._super(); var that = this; that.addObserver('length', function() { that.getMachineCount(); that.getSelectedMachineCount(); that.getImageCount(); }); $(document).bind('ready', function() { Ember.run.next(function() { $.getJSON('/backends', function(data) { data.forEach(function(item){ that.pushObject(Backend.create(item)); }); that.content.forEach(function(item) { item.machines.addObserver('length', function() { that.getMachineCount(); }); item.machines.addObserver('@each.selected', function() { that.getSelectedMachineCount(); that.getSelectedMachine(); }); item.images.addObserver('length', function() { that.getImageCount(); }); item.addObserver('state', function() { var waiting = false; var state = "ok"; that.content.forEach(function(backend) { if (backend.error) { state = 'error'; } else if(backend.state == 'waiting') { waiting = true; } else if(backend.state == 'offline') { state = 'down'; } }); if (waiting) { state = 'state-wait-' + state; } else { state = 'state-' + state; } that.set('state', state); }); }); }).error(function() { Mist.notificationController.notify("Error loading backends"); }); setTimeout(function() { Mist.backendsController.checkMonitoring(); }, 5000); }); }); } }); } );
JavaScript
0
@@ -354,19 +354,20 @@ Images: -tru +fals e,%0A
d6414d2b3d8be7fae1e3106224e76c7114a28a2e
fix setting page text update
www/js/controllers/landing/AccountSettingsController.js
www/js/controllers/landing/AccountSettingsController.js
angular.module("omniControllers") .controller("AccountSettingsController",["$modal", "$injector", "$scope", "$http", "Account", function AccountSettingsController($modal, $injector, $scope, $http, Account) { mywallet = Account.wallet; $scope.wallet = mywallet; $scope.uuid = mywallet['uuid']; $scope.error = false; $scope.mfa = Account.mfa; $scope.email = Account.getSetting('email'); $http.get('/v1/values/currencylist').success(function(data) { $scope.currencylist = data; }).error(function(){ $scope.currencylist = [{'value':'USD','label':'United States Dollar'}]; }); $scope.selectedCurrency = Account.getSetting("usercurrency") $scope.filterdexdust = Account.getSetting("filterdexdust") $scope.donate = Account.getSetting("donate") $scope.showtesteco = Account.getSetting("showtesteco") $scope.label=function (name, abv) { return name+" ("+abv+")"; } $scope.save = function() { if ($scope.myForm.$error.email) { $scope.saved = false; $scope.error = true; } else { mywallet['email'] = $scope.email; mywallet['settings'] = { 'usercurrency':$scope.selectedCurrency, 'filterdexdust':$scope.filterdexdust, 'donate':$scope.donate, 'showtesteco':$scope.showtesteco }; Account.wallet = mywallet; Account.saveSession(); $scope.saved = true; $scope.error = false; Account.setCurrencySymbol($scope.selectedCurrency); var appraiser= $injector.get("appraiser"); appraiser.updateValues(); } }; $scope.changePassword = function() { $scope.login = { uuid: Account.uuid, displayMFA: Account.mfa, action: 'verify', title: 'Verify Current Password', button: 'Validate', bodyTemplate: "/views/modals/partials/login.html", footerTemplate: "/views/modals/partials/login_footer.html", disable: true //disable UUID field in template }; var modalInstance = $modal.open({ templateUrl: '/views/modals/base.html', controller: LoginController, scope: $scope, backdrop:'static' }); modalInstance.result.then(function() { var newPasswordModal = $modal.open({ templateUrl: '/views/modals/change_password.html', controller: WalletPasswordController, scope: $scope }); newPasswordModal.result.then(function() { $scope.saved = true; $scope.error = false; }, function() { $scope.saved = false; //Closing modal shouldn't generate an error //$scope.error = true; }); }); }; $scope.setupMFA = function() { $scope.login = { uuid: Account.uuid, displayMFA: Account.mfa, action: 'verify', title: 'Verify Current Password', button: 'Validate', bodyTemplate: "/views/modals/partials/login.html", footerTemplate: "/views/modals/partials/login_footer.html", disable: true //disable UUID field in template }; var modalInstance = $modal.open({ templateUrl: '/views/modals/base.html', controller: LoginController, scope: $scope, backdrop:'static' }); //for accounts without mfa setup we preload the new mfa secret before trying to render it if (!Account.mfa) { $http.get('/v1/user/wallet/newmfa?uuid=' + Account.uuid) .success(function(data, status) { if (data.error) { $scope.getsecretError = true; $scope.secret=""; $scope.prov=""; } else { $scope.getsecretError = false; $scope.secret=data.secret; $scope.prov=data.prov; } }).error(function() { $scope.getsecretError = true; $scope.secret=""; $scope.prov=""; }); } else { $scope.prov="<encrypted>"; } modalInstance.result.then(function() { var MfaModal = $modal.open({ templateUrl: '/views/modals/setup_mfa.html', controller: MFASetupController, scope: $scope }); MfaModal.result.then(function() { $scope.saved = true; $scope.error = false; }, function() { $scope.saved = false; }); }); }; } ])
JavaScript
0.000001
@@ -4872,32 +4872,72 @@ .error = false;%0A + $scope.mfa=Account.mfa;%0A %7D,
65ce070edaf1f69951ccce17f94cbc1505eec7e7
Fix spellcheck suggestion redirection on firefox
components/Search/SearchResultsPanel/SpellcheckPanel.js
components/Search/SearchResultsPanel/SpellcheckPanel.js
import React from 'react'; class SpellcheckPanel extends React.Component { renderSpellcheckCollations(){ if(this.props.spellcheckData.length === 0) return; // get the first suggestion const suggestion = this.props.spellcheckData[0]; return <h4>Do you mean <a href="#" key={suggestion} onClick={this.props.handleRedirect.bind(this, { keywords: suggestion })}>{suggestion}</a>?</h4>; } render() { return ( <div ref="spellcheckDiv" className="ui grid"> <div className="column"> {this.renderSpellcheckCollations()} </div> </div> ); } } export default SpellcheckPanel;
JavaScript
0
@@ -69,16 +69,171 @@ onent %7B%0A + handleLink(suggestion, event)%7B%0A event.preventDefault();%0A this.props.handleRedirect(%7B%0A keywords: suggestion %0A %7D);%0A %7D%0A rend @@ -502,51 +502,29 @@ his. -props.handleRedirect.bind(this, %7B keywords: +handleLink.bind(this, sug @@ -530,18 +530,16 @@ ggestion - %7D )%7D%3E%7Bsugg
8893b3dc06b783c38cf368ca6e2d5a4a6f1af48b
Fix incorrect object
src/actions/sale/create.js
src/actions/sale/create.js
const { NotSupportedError } = require('common-errors'); const Promise = require('bluebird'); const paypal = require('paypal-rest-sdk'); const key = require('../../redisKey.js'); const url = require('url'); const paypalPaymentCreate = Promise.promisify(paypal.payment.create, { context: paypal.payment }); const PRICE_REGEXP = /(\d)(?=(\d{3})+\.)/g; const find = require('lodash/find'); const mapValues = require('lodash/mapValues'); const JSONStringify = JSON.stringify.bind(JSON); const moment = require('moment'); const { parseSale, saveCommon } = require('../../utils/transactions'); function saleCreate(message) { const { _config, redis, amqp } = this; const promise = Promise.bind(this); // convert request to sale object const sale = { intent: 'sale', payer: { payment_method: 'paypal', }, transactions: [{ amount: { total: message.amount, currency: 'USD', }, description: `Buy ${message.amount} models for [${message.owner}]`, notify_url: _config.urls.sale_notify, }], redirect_urls: { return_url: _config.urls.sale_return, cancel_url: _config.urls.sale_cancel, }, }; function getPrice() { const path = _config.users.prefix + '.' + _config.users.postfix.getMetadata; const audience = _config.users.audience; const getRequest = { username: message.owner, audience, }; return amqp.publishAndWait(path, getRequest, { timeout: 5000 }) .get(audience) .then(function buildMetadata(metadata) { if (metadata.modelPrice) { // paypal requires stupid formatting const price = metadata.modelPrice.toFixed(2).replace(PRICE_REGEXP, '$1,'); const total = sale.transactions[0].amount.total * metadata.modelPrice; sale.transactions[0].amount.total = total.toFixed(2).replace(PRICE_REGEXP, '$1,'); sale.transactions[0].item_list = { items: [{ name: 'Model', price, quantity: message.amount, currency: 'USD', }], }; return sale; } throw new NotSupportedError('Operation is not available on users not having agreement data.'); // eslint-disable-line }); } function sendRequest(request) { return paypalPaymentCreate(request, _config.paypal).then(newSale => { const approval = find(newSale.links, ['rel', 'approval_url']); if (approval === null) { throw new NotSupportedError('Unexpected PayPal response!'); } const token = url.parse(approval.href, true).query.token; return { token, url: approval.href, sale: newSale, }; }); } function saveToRedis(data) { const saleKey = key('sales-data', data.sale.id); const pipeline = redis.pipeline(); // adjust state sale.hidden = message.hidden; function convertDate(strDate) { return moment(strDate).valueOf(); } const saveData = { sale: data.sale, create_time: convertDate(data.sale.create_time), update_time: convertDate(data.sale.update_time), owner: message.owner, }; pipeline.hmset(saleKey, mapValues(saveData, JSONStringify)); pipeline.sadd('sales-index', data.sale.id); return pipeline.exec().return(data); } function updateCommon(sale) { return Promise.bind(this, parseSale(sale, message.owner)).then(saveCommon).return(sale); } return promise.then(getPrice).then(sendRequest).then(saveToRedis).then(updateCommon); } module.exports = saleCreate;
JavaScript
0.999999
@@ -3359,20 +3359,20 @@ eCommon( -sale +data ) %7B%0A @@ -3407,16 +3407,21 @@ rseSale( +data. sale, me @@ -3458,20 +3458,20 @@ .return( -sale +data );%0A %7D%0A%0A
7cb0a244e8d18ffccff425bfc87415f755c98cb6
refactor demande controller specs
client/app/profil/demande/demande.controller.spec.js
client/app/profil/demande/demande.controller.spec.js
'use strict'; describe('Controller: demande', function() { let RequestService = { getCompletion() { return true; }, postAction() { return { then() { return true; } }; } }; let toastr = { error() {} }; let request = { user: 'userId', prestations: [], status: 'en_cours', $update() {} }; let currentUser = {}; // load the service's module beforeEach(module('impactApp')); it('should have 16 prestations', function() { //given var $scope = {}; //when inject(function($controller) { $controller('DemandeCtrl', { $state: { go() {} }, $scope, currentUser, request, RequestService, toastr }); }); expect($scope.prestations.length, 16); }); it('should select the right prestations', function() { //given var $scope = {}; //when inject(function($controller) { $controller('DemandeCtrl', { $state: { go() {} }, $scope, currentUser, request, RequestService, toastr }); }); $scope.cartestationnement.choice = true; $scope.carteinvalidite.choice = true; $scope.carteinvalidite.renouvellement = true; $scope.submit({$valid: true}); //then expect($scope.request.renouvellements[0]).toEqual('carteinvalidite'); expect($scope.request.prestations[0]).toEqual('cartestationnement'); }); });
JavaScript
0
@@ -59,16 +59,38 @@ %7B%0A let +$controller;%0A%0A const RequestS @@ -256,18 +256,20 @@ %7D;%0A%0A -le +cons t toastr @@ -290,24 +290,61 @@ () %7B%7D%0A %7D;%0A%0A + const $state = %7B%0A go() %7B%7D%0A %7D;%0A%0A let reques @@ -439,18 +439,20 @@ %7D;%0A%0A -le +cons t curren @@ -537,53 +537,152 @@ %0A%0A -it('should have 16 prestations', function() %7B +beforeEach(inject(function(_$controller_) %7B%0A $controller = _$controller_;%0A %7D));%0A%0A describe('prestations list', () =%3E %7B%0A let controller;%0A %0A @@ -686,35 +686,35 @@ //given%0A -var +let $scope = %7B%7D;%0A%0A @@ -720,36 +720,38 @@ -//when%0A inject(function($ +beforeEach(function() %7B%0A cont @@ -752,33 +752,26 @@ controller -) %7B%0A += $controller @@ -806,41 +806,9 @@ tate -: %7B%0A go() %7B%7D%0A %7D,%0A +, %0A @@ -920,29 +920,85 @@ );%0A%0A -expect($scope +it('should have 16 prestations', function() %7B%0A expect(controller .prestat @@ -1015,16 +1015,24 @@ h, 16);%0A + %7D);%0A %7D);%0A%0A @@ -1036,62 +1036,68 @@ %0A%0A -it('should select the right prestations', function() %7B +describe('prestations request', () =%3E %7B%0A let controller;%0A %0A @@ -1113,11 +1113,11 @@ -var +let $sc @@ -1135,36 +1135,38 @@ -//when%0A inject(function($ +beforeEach(function() %7B%0A cont @@ -1171,25 +1171,18 @@ ntroller -) %7B%0A += $contro @@ -1221,41 +1221,9 @@ tate -: %7B%0A go() %7B%7D%0A %7D,%0A +, %0A @@ -1339,59 +1339,188 @@ -$scope.cartestationnement. +it('should select the right prestations', function() %7B%0A //given%0A controller.cartestationnement = _.assign(controller.cartestationnement, %7B choice - = +: true +%7D) ;%0A -$scope + controller .car @@ -1535,51 +1535,63 @@ dite -.choice = true;%0A $scope.carteinvalidite. + = _.assign(controller.carteinvalidite, %7Bchoice: true, reno @@ -1604,17 +1604,21 @@ ment - = +: true -;%0A +%7D);%0A%0A @@ -1657,15 +1657,19 @@ + //then%0A + @@ -1738,24 +1738,26 @@ dite');%0A + expect($scop @@ -1812,16 +1812,24 @@ ement'); +%0A %7D); %0A%0A %7D);%0A
3c89223ead8560bd5a6ecbe58cb331e607d18d59
Update Pathoscope entry UI
client/src/js/analyses/components/Pathoscope/Item.js
client/src/js/analyses/components/Pathoscope/Item.js
import CX from "classnames"; import React from "react"; import { Col, Row } from "react-bootstrap"; import { connect } from "react-redux"; import { Flex, FlexItem } from "../../../base/index"; import { toScientificNotation } from "../../../utils"; import { toggleExpanded } from "../../actions"; import AnalysisValueLabel from "../ValueLabel"; export const PathoscopeItem = (props) => { const className = CX("list-group-item", "spaced", {hoverable: !props.expanded}); let closeButton; if (props.expanded) { closeButton = ( <button type="button" className="close" onClick={() => props.onExpand(props.id)}> <span>×</span> </button> ); } const piValue = props.showReads ? Math.round(props.reads) : toScientificNotation(props.pi); return ( <div className={className} onClick={props.expanded ? null : () => props.onExpand(props.id)}> <Row> <Col xs={12} md={6}> <Flex> <FlexItem> {props.name} </FlexItem> <FlexItem pad={5}> <small className="text-primary"> <strong className="text-warning"> {props.abbreviation} </strong> </small> </FlexItem> </Flex> </Col> <Col xs={12} mdHidden lgHidden> <div style={{height: "20px"}} /> </Col> <Col xs={6} sm={4} md={2}> <AnalysisValueLabel bsStyle="success" label={props.showReads ? "Reads" : "Weight"} value={piValue} /> </Col> <Col xs={6} sm={4} md={2}> <AnalysisValueLabel bsStyle="danger" label="Depth" value={props.depth.toFixed(1)} /> </Col> <Col xs={6} sm={4} md={2}> <Flex justifyContent="space-between"> <FlexItem> <AnalysisValueLabel bsStyle="primary" label="Coverage" value={props.coverage.toFixed(3)} /> </FlexItem> <FlexItem> {closeButton} </FlexItem> </Flex> </Col> </Row> </div> ); }; const mapStateToProps = (state, ownProps) => ({ ...state.analyses.data[ownProps.index], showMedian: state.analyses.showMedian, showReads: state.analyses.showReads }); const mapDispatchToProps = (dispatch) => ({ onExpand: (id) => { dispatch(toggleExpanded(id)); } }); export default connect(mapStateToProps, mapDispatchToProps)(PathoscopeItem);
JavaScript
0
@@ -289,17 +289,16 @@ tions%22;%0A -%0A import A @@ -590,16 +590,27 @@ e=%22close + pull-right %22 onClic @@ -977,14 +977,21 @@ %7B12%7D + sm=%7B5%7D md=%7B -6 +5 %7D%3E%0A @@ -1513,33 +1513,32 @@ %3C/Col%3E%0A -%0A @@ -1550,141 +1550,16 @@ xs=%7B -12%7D mdHidden lgHidden%3E%0A %3Cdiv style=%7B%7Bheight: %2220px%22%7D%7D /%3E%0A %3C/Col%3E%0A%0A %3CCol xs=%7B6 +4 %7D sm=%7B -4 +2 %7D md @@ -1822,32 +1822,32 @@ %3CCol xs=%7B -6 +3 %7D sm=%7B -4 +2 %7D md=%7B2%7D%3E%0A @@ -2093,16 +2093,16 @@ xs=%7B -6 +3 %7D sm=%7B -4 +2 %7D md @@ -2111,109 +2111,8 @@ 2%7D%3E%0A - %3CFlex justifyContent=%22space-between%22%3E%0A %3CFlexItem%3E%0A @@ -2167,32 +2167,24 @@ - bsStyle=%22pri @@ -2209,32 +2209,24 @@ - - label=%22Cover @@ -2230,24 +2230,16 @@ verage%22%0A - @@ -2304,32 +2304,24 @@ - - /%3E%0A @@ -2331,70 +2331,58 @@ - %3C/FlexItem%3E%0A %3CFlexItem%3E%0A +%3C/Col%3E%0A %3CCol xs=%7B2%7D sm=%7B1%7D md=%7B1%7D%3E%0A @@ -2397,17 +2397,16 @@ - %7BcloseBu @@ -2415,72 +2415,8 @@ on%7D%0A - %3C/FlexItem%3E%0A %3C/Flex%3E%0A
ac8ba01426799a4a15666b1db39182ad9f1f3dd1
Add a transform queue on the connector
src/orbit/orbit/connectors/transform_connector.js
src/orbit/orbit/connectors/transform_connector.js
import Orbit from 'orbit/core'; import clone from 'orbit/lib/clone'; import diffs from 'orbit/lib/diffs'; import eq from 'orbit/lib/eq'; var TransformConnector = function(source, target, options) { var _this = this; this.source = source; this.target = target; options = options || {}; // TODO - allow filtering of transforms // if (options.actions) this.actions = Orbit.arrayToOptions(options.actions); // if (options.types) this.types = Orbit.arrayToOptions(options.types); this.blocking = options.blocking !== undefined ? options.blocking : true; var active = options.active !== undefined ? options.active : true; if (active) this.activate(); }; TransformConnector.prototype = { constructor: TransformConnector, activate: function() { var _this = this; if (this._active) return; this.source.on('didTransform', this._processTransform, this); this._active = true; }, deactivate: function() { this.source.off('didTransform', this._processTransform, this); this._active = false; }, isActive: function() { return this._active; }, ///////////////////////////////////////////////////////////////////////////// // Internals ///////////////////////////////////////////////////////////////////////////// _processTransform: function(operation) { // TODO - add filtering back in // if (this.actions && !this.actions[action]) return; // if (this.types && !this.types[type]) return; // console.log(this.target.id, 'processTransform', operation); if (this.blocking) { return this._transformTarget(operation); } else { this._transformTarget(operation); } }, _transformTarget: function(operation) { //TODO-log console.log('****', ' transform from ', this.source.id, ' to ', this.target.id, operation); if (this.target.retrieve) { var currentValue = this.target.retrieve(operation.path); if (currentValue) { if (operation.op === 'add' || operation.op === 'replace') { if (eq(currentValue, operation.value)) { //TODO-log console.log('==', ' transform from ', this.source.id, ' to ', this.target.id, operation); return; } else { return this._resolveConflicts(operation.path, currentValue, operation.value); } } } else if (operation.op === 'remove') { return; } } return this.target.transform(operation); }, _resolveConflicts: function(path, currentValue, updatedValue) { var ops = diffs(currentValue, updatedValue, {basePath: path}); //TODO-log console.log(this.target.id, 'resolveConflicts', path, currentValue, updatedValue, ops); return this.target.transform(ops); } }; export default TransformConnector;
JavaScript
0.000001
@@ -21,24 +21,76 @@ rbit/core';%0A +import TransformQueue from 'orbit/transform_queue';%0A import clone @@ -244,37 +244,16 @@ ions) %7B%0A - var _this = this;%0A%0A this.s @@ -291,16 +291,88 @@ target; +%0A this.transformQueue = new TransformQueue(this, %7BautoProcess: false%7D); %0A%0A opti @@ -972,32 +972,132 @@ ansform, this); +%0A this.target.transformQueue.on('didComplete', this.transformQueue.process, this.transformQueue); %0A%0A this._acti @@ -1208,16 +1208,117 @@ this); +%0A this.target.transformQueue.off('didComplete', this.transformQueue.process, this.transformQueue); %0A%0A th @@ -1870,38 +1870,32 @@ this._transform -Target (operation);%0A%0A @@ -1926,22 +1926,16 @@ ransform -Target (operati @@ -1967,14 +1967,8 @@ form -Target : fu @@ -1965,32 +1965,485 @@ nsform: function +(operation) %7B%0A // If the target's transformQueue is processing, then we should queue up the%0A // transform on the connector instead of on the target.%0A // This ensures that comparisons are made against the target's most up to%0A // date state. Note that this connector's queue processing is triggered%0A // by the %60didComplete%60 event for the target's queue.%0A if (this.target.transformQueue.processing) %7B%0A return this.transformQueue.push (operation) %7B%0A// @@ -2437,18 +2437,24 @@ eration) - %7B +;%0A %7D%0A %0A//TODO-
d999d0bdd0d9c9a845db274377835a9f9f43b7ca
remove console.log
gamestate.js
gamestate.js
var GameState = function(){ this.STATE_SPLASH = 0; this.STATE_GAME = 1; this.STATE_GAMEOVER = 2; this.STATE_MAIN_MENU = 3; this.STATE_HIGH_SCORES = 4; this.state = 0; console.log(this.state); } GameState.prototype.setState = function(state) { this.state = state; };
JavaScript
0.000006
@@ -189,37 +189,8 @@ 0;%0A - console.log(this.state);%0A %7D%0A%0AG
ec103c90f6c190a6ea79dedd50e935423b3099e9
use Chrome and Firefox on Travis, since PhantomJS was inconsistent
gruntFile.js
gruntFile.js
/* jshint node:true */ 'use strict'; module.exports = function(grunt) { require('load-grunt-tasks')(grunt); // Default task. grunt.registerTask('default', ['test']); grunt.registerTask('test', ['jshint', 'karma:unit']); grunt.registerTask('serve', ['karma:continuous', 'dist', 'build:gh-pages', 'connect:continuous', 'watch']); grunt.registerTask('dist', ['ngmin', 'surround', 'uglify' ]); grunt.registerTask('coverage', ['jshint', 'karma:coverage']); grunt.registerTask('junit', ['jshint', 'karma:junit']); // HACK TO ACCESS TO THE COMPONENT PUBLISHER function fakeTargetTask(prefix){ return function(){ if (this.args.length !== 1) { return grunt.log.fail('Just give the name of the ' + prefix + ' you want like :\ngrunt ' + prefix + ':bower'); } var done = this.async(); var spawn = require('child_process').spawn; spawn('./node_modules/.bin/gulp', [ prefix, '--branch='+this.args[0] ].concat(grunt.option.flags()), { cwd : './node_modules/angular-ui-publisher', stdio: 'inherit' }).on('close', done); }; } grunt.registerTask('build', fakeTargetTask('build')); grunt.registerTask('publish', fakeTargetTask('publish')); // // HACK TO MAKE TRAVIS WORK var testConfig = function(configFile, customOptions) { var options = { configFile: configFile, singleRun: true }; var travisOptions = process.env.TRAVIS && { browsers: ['Firefox', 'PhantomJS'], reporters: ['dots', 'coverage', 'coveralls'], preprocessors: { 'src/*.js': ['coverage'] }, coverageReporter: { reporters: [{ type: 'text' }, { type: 'lcov', dir: 'coverage/' }] }, }; return grunt.util._.extend(options, customOptions, travisOptions); }; // // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner: ['/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' * @version v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>', ' * @link <%= pkg.homepage %>', ' * @license <%= pkg.license %>', ' */', ''].join('\n') }, connect: { options: { base : 'out/built/gh-pages', open: true, livereload: true }, server: { options: { keepalive: true } }, continuous: { options: { keepalive: false } } }, coveralls: { options: { coverage_dir: 'coverage/', // debug: true // dryRun: true, // force: true, // recursive: true } }, karma: { unit: testConfig('test/karma.conf.js'), server: {configFile: 'test/karma.conf.js'}, continuous: {configFile: 'test/karma.conf.js', background: true }, coverage: { configFile: 'test/karma.conf.js', reporters: ['progress', 'coverage'], preprocessors: { 'src/*.js': ['coverage'] }, coverageReporter: { reporters: [{ type: 'text' }, { type: 'lcov', dir: 'coverage/' }] }, singleRun: true }, junit: { configFile: 'test/karma.conf.js', reporters: ['progress', 'junit'], junitReporter: { outputFile: 'junit/unit.xml', suite: 'unit' }, singleRun: true } }, jshint: { src: { files:{ src : ['src/**/*.js', 'demo/**/*.js'] }, options: { jshintrc: '.jshintrc' } }, test: { files:{ src : [ 'test/*.js', 'gruntFile.js'] }, options: grunt.util._.extend({}, grunt.file.readJSON('.jshintrc'), grunt.file.readJSON('test/.jshintrc')) } }, uglify: { build: { expand: true, cwd: 'dist', src: ['*.js', '!*.min.js'], ext: '.min.js', dest: 'dist' } }, surround: { options: { prepend: ['(function(window, angular, undefined) {', '\'use strict\';'].join('\n'), append: '})(window, window.angular);' }, main: { expand: true, cwd: 'src', src: ['*.js'], dest: 'dist' } }, ngmin: { main: { expand: true, cwd: 'src', src: ['*.js'], dest: 'dist' } }, changelog: { options: { dest: 'CHANGELOG.md' } }, watch: { src: { files: ['src/*'], tasks: ['jshint:src', 'karma:unit:run', 'dist', 'build:gh-pages'] }, test: { files: ['test/*.js'], tasks: ['jshint:test', 'karma:unit:run'] }, demo: { files: ['demo/*', 'publish.js'], tasks: ['jshint', 'build:gh-pages'] }, livereload: { files: ['out/built/gh-pages/**/*'], options: { livereload: true } } } }); };
JavaScript
0.000005
@@ -1444,28 +1444,25 @@ : %5B' -Firefox', 'PhantomJS +Chrome', 'Firefox '%5D,%0A
45497499e4ed184b41ca3334eb24243fbaacf294
Add `lib/browser/*.js` to grunt browserify watch task.
gruntfile.js
gruntfile.js
'use strict'; var istanbul = require('browserify-istanbul'); module.exports = function(grunt) { var lessFiles = { 'lib/dashboard/src/dashboard.less': 'lib/dashboard/public/dashboard.css' }; var jshintFiles = ['index.js', 'lib/**/*.js', '!lib/browser/public/*.js']; var browserifyFiles = ['lib/api.js']; var gruntConfig = { less: { compile: { files: lessFiles } }, jshint: { options: { jshintrc: true }, all: jshintFiles }, browserify: { dist: { files: { './lib/browser/public/browserifiedApi.min.js': browserifyFiles }, options: { browserifyOptions: { debug: true }, plugin: [ ['minifyify', { map: '/nodecg-api.map.json', output: 'lib/browser/public/browserifiedApi.map.json' }] ], transform: [ ['aliasify', { aliases: { './logger': './lib/browser/logger', './replicant': './lib/browser/replicant' }, verbose: false }], ['envify', { _: 'purge', browser: true }], 'brfs' ], ignore: [ './lib/server/index.js', './lib/replicator.js', './lib/util.js' ] } }, coverage: { files: { './lib/browser/public/browserifiedTestApi.js': browserifyFiles }, options: { browserifyOptions: { debug: true }, transform: [ ['aliasify', { aliases: { './logger': './lib/browser/logger', './replicant': './lib/browser/replicant' }, verbose: false }], ['envify', { _: 'purge', browser: true }], 'brfs', istanbul ], ignore: [ './lib/server/index.js', './lib/replicator.js', './lib/util.js' ] } } }, watch: { stylesheets: { files: lessFiles, tasks: ['less'], options: { debounceDelay: 250 } }, scripts: { files: jshintFiles, tasks: ['jshint'], options: { debounceDelay: 250 } }, clientScripts: { files: browserifyFiles, tasks: ['browserify'], options: { debounceDelay: 250 } } } }; grunt.initConfig(gruntConfig); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['less', 'jshint', 'browserify']); };
JavaScript
0
@@ -3456,31 +3456,50 @@ files: -browserifyFiles +%5B'lib/api.js', 'lib/browser/*.js'%5D ,%0A
66bd86c5cb53c751128086320e2ac9aac1f40c46
remove nodemon from grunt
gruntfile.js
gruntfile.js
'use strict'; module.exports = function(grunt) { // Unified Watch Object var watchFiles = { serverViews: ['app/views/**/*.*'], serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js', '!app/tests/'], clientViews: ['public/modules/**/views/**/*.html'], clientJS: ['public/js/*.js', 'public/modules/**/*.js'], clientCSS: ['public/modules/**/*.css'], mochaTests: ['app/tests/**/*.js'] }; // Project Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { serverViews: { files: watchFiles.serverViews, options: { livereload: true } }, serverJS: { files: watchFiles.serverJS, tasks: ['jshint'], options: { livereload: true } }, clientViews: { files: watchFiles.clientViews, options: { livereload: true } }, clientJS: { files: watchFiles.clientJS, tasks: ['jshint'], options: { livereload: true } }, clientCSS: { files: watchFiles.clientCSS, tasks: ['csslint'], options: { livereload: true } }, mochaTests: { files: watchFiles.mochaTests, tasks: ['test:server'], } }, jshint: { all: { src: watchFiles.clientJS.concat(watchFiles.serverJS), options: { jshintrc: true } } }, csslint: { options: { csslintrc: '.csslintrc' }, all: { src: watchFiles.clientCSS } }, uglify: { production: { options: { mangle: false }, files: { 'public/dist/application.min.js': 'public/dist/application.js' } } }, cssmin: { combine: { files: { 'public/dist/application.min.css': '<%= applicationCSSFiles %>' } } }, nodemon: { dev: { script: 'server.js', options: { nodeArgs: ['--debug'], ext: 'js,html', watch: watchFiles.serverViews.concat(watchFiles.serverJS) } } }, forever: { dev: { options: { index: 'server.js', } } }, 'node-inspector': { custom: { options: { 'web-port': 1337, 'web-host': 'localhost', 'debug-port': 5858, 'save-live-edit': true, 'no-preload': true, 'stack-trace-limit': 50, 'hidden': [] } } }, ngAnnotate: { production: { files: { 'public/dist/application.js': '<%= applicationJavaScriptFiles %>' } } }, concurrent: { default: ['nodemon', 'watch', 'forever'], debug: ['nodemon', 'watch', 'node-inspector'], options: { logConcurrentOutput: true, limit: 10 } }, env: { test: { NODE_ENV: 'test' }, secure: { NODE_ENV: 'secure' } }, mochaTest: { src: watchFiles.mochaTests, options: { reporter: 'spec', require: 'server.js' } }, karma: { unit: { configFile: 'karma.conf.js' } } }); // Load NPM tasks require('load-grunt-tasks')(grunt); // Making grunt default to force in order not to break the project. grunt.option('force', true); // A Task for loading the configuration object grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() { var init = require('./config/init')(); var config = require('./config/config'); grunt.config.set('applicationJavaScriptFiles', config.assets.js); grunt.config.set('applicationCSSFiles', config.assets.css); }); // Default task(s). grunt.registerTask('default', ['lint', 'concurrent:default']); // Debug task. grunt.registerTask('debug', ['lint', 'concurrent:debug']); // Secure task(s). grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']); // Lint task(s). grunt.registerTask('lint', ['jshint', 'csslint']); // Build task(s). grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']); // Test task. grunt.registerTask('test', ['test:server', 'test:client']); grunt.registerTask('test:server', ['env:test', 'mochaTest']); grunt.registerTask('test:client', ['env:test', 'karma:unit']); grunt.loadNpmTasks('grunt-forever'); };
JavaScript
0.000459
@@ -2376,27 +2376,16 @@ fault: %5B -'nodemon', 'watch',
e2fa84be641080cb6a575071fccc4bc4b533dafd
include data on object properties to make json debugger work
src/api/object-property.js
src/api/object-property.js
import createProperty from './property' import factory from './factory' export default function(data, parent) { const object = { ...createProperty(data, parent) } object.properties = data.properties.map(property => factory(property, object)) for (const property of object.properties) { object[property.id] = property.value || property.items || property } return object }
JavaScript
0
@@ -156,16 +156,22 @@ parent) +, data %7D%0A%0A ob
6741aa0f10592d3337e2276d37ea41696d511d8a
Typo correct
gruntfile.js
gruntfile.js
/*! * @ Package for Responsive Boilerplate Micro Framework @!!!!! */ module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> v<%= pkg.version %>, <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, files: { src: [ 'js/*.js' ], dest: 'js/', expand: true, flatten: true, ext: '.min.js' } }, jshint: { options: { browser: true, globals: { jQuery: true, console: true, module: true, document: true } }, all: { files: { src: ['gruntfile.js', 'js/custom.js'] } } }, concat: { options: { }, dist: { src: [ 'src/rb-menu.js', 'src/rb-tabs.js', 'src/rb-accordion.js', 'src/rb-modal.js' ], dest: 'js/rb-ui.js' } }, less: { development: { options: { paths: ['less'], yuicompress: false }, files: { 'css/responsiveboilerplate.css':'less/responsiveboilerplate.less' } } }, cssmin: { options: { banner: '/*! <%= pkg.name %> v<%= pkg.version %>, <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, compress: { files: { 'css/responsiveboilerplate.min.css': ['css/responsiveboilerplate.css'] } } }, watch: { scripts: { files: ['Gruntfile.js', 'js/**/*.js', 'libs/**/*.js', 'css/**/*.css'], tasks: ['jshint','concat','uglify'], options: { debounceDelay: 250 } }, less: { files: 'less/**/*.less', tasks: ['less','cssmin'], options: { debounceDelay: 250 } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.registerTask('default', ['jshint','concat','uglify','less','cssmin','watch']); };
JavaScript
0.999793
@@ -47,17 +47,11 @@ cro -Framework +Lib @!!
aa61c96b0058ed28015adb7eed5129a7c401ac21
Fix median calculation.
perftracker/app/scripts/util.js
perftracker/app/scripts/util.js
Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] == obj) { return true; } } return false; } Array.prototype.mode = function () { var histogram = {}; for (var i = 0; i < this.length; i++) { if (histogram[this[i]]) { histogram[this[i]]++; } else { histogram[this[i]] = 1; } } var maxIndex = 0; var maxValue = 0; for (var key in histogram) { if (histogram[key] > maxValue) { maxIndex = key; maxValue = histogram[key]; } } return maxIndex; } Array.prototype.max = function() { return Math.max.apply(Math, this); }; Array.prototype.min = function() { return Math.min.apply(Math, this); }; Array.prototype.sum = function() { var sum = 0; for (var i = this.length - 1; i >= 0; i--) { sum += this[i]; } return sum; }; Array.prototype.average = function() { if (!this.length) return 0; return this.sum() / this.length; }; Array.prototype.median = function() { if (!this.length) return 0; var sorted = this.clone().sort(); var lower = sorted[Math.floor((sorted.length + 1) / 2) - 1]; if (sorted.length == 1) { return sorted[0]; } else if (sorted.length % 2) { return lower; } else { var upper = sorted[Math.floor((sorted.length + 1) / 2)]; return (lower + upper) / 2; } }; Array.prototype.clone = function() { var newArr = []; for (var i = 0; i < this.length; i++) { newArr.push(this[i]); } return newArr; }; window.location.queryString = function() { var result = {}; var raw_string = decodeURI(location.search); if (!raw_string || raw_string.length == 0) { return result; } raw_string = raw_string.substring(1); // trim leading '?' var name_values = raw_string.split("&"); for (var i = 0; i < name_values.length; ++i) { var elts = name_values[i].split('='); if (result[elts[0]]) result[elts[0]] += "," + elts[1]; else result[elts[0]] = elts[1]; } return result; }; // Wrapper around XHR. function XHRGet(url, callback, data) { var self = this; var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status != 200) { alert("Error: could not download (" + url + "): " + xhr.status); } callback(xhr.responseText, data); } } } // Given a stddev and a sample count, compute the stderr function stderr(stddev, sample_count) { return stddev / Math.sqrt(sample_count); } // Given a stderr, compute the 95% confidence interval function ci(stderr) { return 1.96 * stderr; } // Returns true if the given averages have a statistically significant // difference based on their standard deviations. function isSignificant(avg1, stddev1, len1, avg2, stddev2, len2) { var ci1 = ci(stderr(stddev1, len1)); var ci2 = ci(stderr(stddev2, len2)); return (avg1 + ci1) < (avg2 - ci2) || (avg1 - ci1) > (avg2 + ci2); } // Sets the selected option of the <select> with id=|id|. function setSelectValue(id, value) { if (!id || !value) return; var elt = document.getElementById(id); if (!elt) return; for (var i = 0; i < elt.options.length; i++) { if (elt.options[i].value == value) { elt.options[i].selected = true } else { elt.options[i].selected = false; } } } // Gets the value of the selected option of the <select> with id=|id|. function getSelectValue(id) { var elt = document.getElementById(id); if (!elt) return ""; return elt[elt.selectedIndex].value; } // Sets the parameters in the URL fragment to those in the |newParams| // key:value map. function setParams(params) { var hashString = ""; for (var param in params) { if (!param) continue; hashString += "&" + param + "=" + encodeURIComponent(params[param]); } window.location.hash = "#" + hashString.substring(1); } // Returns a key:value map of all parameters in the URL fragment. function getParams() { var map = {}; var hash = window.location.hash.substring(1); pairs = hash.split("&"); for (var i = 0; i < pairs.length; i++) { var key_val = pairs[i].split("="); map[key_val[0]] = decodeURIComponent(key_val[1]); } return map; }
JavaScript
0.999999
@@ -951,24 +951,71 @@ length;%0A%7D;%0A%0A +function sortNumber(a, b) %7B%0A return a - b;%0A%7D%0A%0A Array.protot @@ -1103,16 +1103,26 @@ ().sort( +sortNumber );%0A var
04cf2912a687c367b8c62a8858be5c6754f66c90
add missing semi-colon.
gulp/util.js
gulp/util.js
var config = require('./config'); var gulp = require('gulp'); var gutil = require('gulp-util'); var frep = require('gulp-frep'); var fs = require('fs'); var args = require('minimist')(process.argv.slice(2)); var path = require('path'); var rename = require('gulp-rename'); var filter = require('gulp-filter'); var concat = require('gulp-concat'); var autoprefixer = require('gulp-autoprefixer'); var series = require('stream-series'); var lazypipe = require('lazypipe'); var glob = require('glob').sync; var uglify = require('gulp-uglify'); var sass = require('gulp-sass'); var plumber = require('gulp-plumber'); var ngAnnotate = require('gulp-ng-annotate'); var minifyCss = require('gulp-minify-css'); var insert = require('gulp-insert'); var gulpif = require('gulp-if'); var constants = require('./const'); var VERSION = constants.VERSION; var BUILD_MODE = constants.BUILD_MODE; var IS_DEV = constants.IS_DEV; var ROOT = constants.ROOT; var utils = require('../scripts/gulp-utils.js'); exports.buildJs = buildJs; exports.autoprefix = autoprefix; exports.buildModule = buildModule; exports.filterNonCodeFiles = filterNonCodeFiles; exports.readModuleArg = readModuleArg; exports.themeBuildStream = themeBuildStream; exports.args = args; /** * Builds the entire component library javascript. * @param {boolean} isRelease Whether to build in release mode. */ function buildJs () { var jsFiles = config.jsBaseFiles.concat([path.join(config.paths, '*.js')]); gutil.log("building js files..."); var jsBuildStream = gulp.src( jsFiles ) .pipe(filterNonCodeFiles()) .pipe(utils.buildNgMaterialDefinition()) .pipe(plumber()) .pipe(ngAnnotate()) .pipe(utils.addJsWrapper(true)); var jsProcess = series(jsBuildStream, themeBuildStream() ) .pipe(concat('angular-material.js')) .pipe(BUILD_MODE.transform()) .pipe(insert.prepend(config.banner)) .pipe(insert.append('window.ngMaterial={version:{full: "' + VERSION +'"}}')) .pipe(gulp.dest(config.outputDir)) .pipe(gulpif(!IS_DEV, uglify({ preserveComments: 'some' }))) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest(config.outputDir)); return series(jsProcess, deployMaterialMocks()); // Deploy the `angular-material-mocks.js` file to the `dist` directory function deployMaterialMocks() { return gulp.src(config.mockFiles) .pipe(gulp.dest(config.outputDir)); } } function autoprefix () { return autoprefixer({browsers: [ 'last 2 versions', 'last 4 Android versions' ]}); } function buildModule(module, opts) { opts = opts || {}; if ( module.indexOf(".") < 0) { module = "material.components." + module; } gutil.log('Building ' + module + (opts.isRelease && ' minified' || '') + ' ...'); var name = module.split('.').pop(); utils.copyDemoAssets(name, 'src/components/', 'dist/demos/'); var stream = utils.filesForModule(module) .pipe(filterNonCodeFiles()) .pipe(gulpif('*.scss', buildModuleStyles(name))) .pipe(gulpif('*.js', buildModuleJs(name))); if (module === 'material.core') { stream = splitStream(stream); } return stream .pipe(BUILD_MODE.transform()) .pipe(insert.prepend(config.banner)) .pipe(gulpif(opts.minify, buildMin())) .pipe(gulpif(opts.useBower, buildBower())) .pipe(gulp.dest(BUILD_MODE.outputDir + name)); function splitStream (stream) { var js = series(stream, themeBuildStream()) .pipe(filter('*.js')) .pipe(concat('core.js')); var css = stream.pipe(filter('*.css')); return series(js, css); } function buildMin() { return lazypipe() .pipe(gulpif, /.css$/, minifyCss(), uglify({ preserveComments: 'some' }) .on('error', function(e) { console.log('\x07',e.message); return this.end(); } ) ) .pipe(rename, function(path) { path.extname = path.extname .replace(/.js$/, '.min.js') .replace(/.css$/, '.min.css'); }) (); } function buildBower() { return lazypipe() .pipe(utils.buildModuleBower, name, VERSION)(); } function buildModuleJs(name) { var patterns = [ { pattern: /\@ngInject/g, replacement: 'ngInject' } ]; return lazypipe() .pipe(plumber) .pipe(ngAnnotate) .pipe(frep, patterns) .pipe(concat, name + '.js') (); } function buildModuleStyles(name) { var files = []; config.themeBaseFiles.forEach(function(fileGlob) { files = files.concat(glob(fileGlob, { cwd: ROOT })); }); var baseStyles = files.map(function(fileName) { return fs.readFileSync(fileName, 'utf8').toString(); }).join('\n'); return lazypipe() .pipe(insert.prepend, baseStyles) .pipe(gulpif, /theme.scss/, rename(name + '-default-theme.scss'), concat(name + '.scss') ) .pipe(sass) .pipe(autoprefix) (); // invoke the returning fn to create our pipe } } function readModuleArg() { var module = args.c ? 'material.components.' + args.c : (args.module || args.m); if (!module) { gutil.log('\nProvide a compnent argument via `-c`:', '\nExample: -c toast'); gutil.log('\nOr provide a module argument via `--module` or `-m`.', '\nExample: --module=material.components.toast or -m material.components.dialog'); process.exit(1); } return module; } function filterNonCodeFiles() { return filter(function(file) { return !/demo|module\.json|script\.js|\.spec.js|README/.test(file.path); }); } // builds the theming related css and provides it as a JS const for angular function themeBuildStream() { return gulp.src( config.themeBaseFiles.concat(path.join(config.paths, '*-theme.scss')) ) .pipe(concat('default-theme.scss')) .pipe(utils.hoistScssVariables()) .pipe(sass()) .pipe(utils.cssToNgConstant('material.core', '$MD_THEME_CSS')); }
JavaScript
0
@@ -1968,16 +1968,17 @@ ON +'%22%7D%7D +; '))%0A
7fd7429d59dfa5b04b0bf7ba1cd14e5cec472fe7
Add getValue for checkbox-form-field to return the correct value
Kwf_js/FrontendForm/Checkbox.js
Kwf_js/FrontendForm/Checkbox.js
Kwf.FrontendForm.Checkbox = Ext.extend(Kwf.FrontendForm.Field, { initField: function() { this.el.select('input').each(function(input) { input.on('click', function() { this.fireEvent('change', this.getValue()); }, this); }, this); }, clearValue: function() { var inp = this.el.child('input'); inp.dom.checked = false; }, setValue: function(value) { var inp = this.el.child('input'); inp.dom.checked = !!value; } }); Kwf.FrontendForm.fields['kwfFormFieldCheckbox'] = Kwf.FrontendForm.Checkbox;
JavaScript
0.000001
@@ -510,16 +510,129 @@ !value;%0A + %7D,%0A getValue: function(value) %7B%0A var inp = this.el.child('input');%0A return inp.dom.checked;%0A %7D%0A%7D)
3f1bca7d26eb63be968d70908fd4dafa2a3de5f7
Fix truncate tests
Libraries/Utilities/truncate.js
Libraries/Utilities/truncate.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule truncate * @flow */ 'use strict'; var merge = require('merge'); type truncateOptions = { breakOnWords: boolean; minDelta: number; elipsis: string; } var defaultOptions = { breakOnWords: true, minDelta: 10, // Prevents truncating a tiny bit off the end elipsis: '...', }; // maxChars (including ellipsis) var truncate = function( str: ?string, maxChars: number, options: truncateOptions ): ?string { options = merge(defaultOptions, options); if (str && str.length && str.length - options.minDelta + options.elipsis.length >= maxChars) { str = str.slice(0, maxChars - options.elipsis.length + 1); if (options.breakOnWords) { var ii = Math.max(str.lastIndexOf(' '), str.lastIndexOf('\n')); str = str.slice(0, ii); } str = str.trim() + options.elipsis; } return str; }; module.exports = truncate;
JavaScript
0.000054
@@ -361,39 +361,8 @@ ';%0A%0A -var merge = require('merge');%0A%0A type @@ -449,19 +449,21 @@ ing;%0A%7D%0A%0A -var +const default @@ -613,19 +613,21 @@ lipsis)%0A -var +const truncat @@ -732,14 +732,26 @@ s = -merge( +Object.assign(%7B%7D, defa
28bb32a4669d680c78342ccfd37d406cf8384c89
clean up the main App
Markup/publisher/src/app/App.js
Markup/publisher/src/app/App.js
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter as Router, Redirect, Route, Switch} from 'react-router-dom' import {getAsyncComponent} from 'async-react-component'; const APIOnBoarding = () => import('./components/Apis/OnBoarding/listing'); const Indexpage = () => import('../pages/index'); class Publisher extends Component { render(){ return( <Router basename="/publisher"> <Switch> <Route path={"/apis/"} component={getAsyncComponent(APIOnBoarding)}/> <Route path={"/"} component={getAsyncComponent(Indexpage)}/> </Switch> </Router> ); }; } export default Publisher;
JavaScript
0.000001
@@ -710,42 +710,8 @@ t';%0A -import ReactDOM from 'react-dom';%0A impo @@ -788,16 +788,16 @@ er-dom'%0A + import %7B @@ -972,16 +972,71 @@ index'); +%0Aconst Login = () =%3E import('./components/Login/login') %0A%0Aclass @@ -1158,32 +1158,114 @@ %3CSwitch%3E%0A + %3CRoute path=%7B%22/login%22%7D component=%7BgetAsyncComponent(Login)%7D/%3E%0A @@ -1287,17 +1287,16 @@ =%7B%22/apis -/ %22%7D compo
f24040edd03123ff735e2701309410d24f91b99d
Fix deprecation warning for Github button on examples page
example/components/GithubStarsButton.react.js
example/components/GithubStarsButton.react.js
import React from 'react'; import {findDOMNode} from 'react-dom'; const AUTHOR_REPO = 'ericgio/react-bootstrap-typeahead'; const GitHubStarsButton = React.createClass({ componentDidMount() { const node = findDOMNode(this); node.dataset.style = window.innerWidth > 480 ? 'mega': null; }, render() { return ( <a aria-label={`Star ${AUTHOR_REPO} on GitHub`} className="github-button" data-count-api={`/repos/${AUTHOR_REPO}#stargazers_count`} data-count-aria-label="# stargazers on GitHub" data-count-href={`/${AUTHOR_REPO}/stargazers`} href={`https://github.com/${AUTHOR_REPO}`}> Star </a> ); }, }); export default GitHubStarsButton;
JavaScript
0.000009
@@ -421,74 +421,8 @@ on%22%0A - data-count-api=%7B%60/repos/$%7BAUTHOR_REPO%7D#stargazers_count%60%7D%0A @@ -527,16 +527,47 @@ azers%60%7D%0A + data-show-count=%7Btrue%7D%0A
6effb0886e36547a55d83105ab2f10bf681cb4c9
Fix CSS font in Android
hooks/after_prepare/050_clean_unused_directories.js
hooks/after_prepare/050_clean_unused_directories.js
#!/usr/bin/env node "use strict"; var gulp = require('gulp'); var gutil = require('gulp-util'); var allConfig = require('../../app/config.json'); var path = require("path"); var del = require('del'); var cmd = process.env.CORDOVA_CMDLINE; var rootdir = process.argv[2]; var argv = require('yargs').argv; var skip = true; if (cmd.indexOf("--release") > -1 || cmd.indexOf("--useref") > -1) { skip = false; } if (rootdir && !skip) { // go through each of the platform directories that have been prepared var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []); for(var x=0; x<platforms.length; x++) { var platform = platforms[x].trim().toLowerCase(); var wwwPath; if(platform == 'android') { wwwPath = path.join(rootdir, 'platforms', platform, 'assets', 'www'); } else { wwwPath = path.join(rootdir, 'platforms', platform, 'www'); } // Clean unused directories console.log('Cleaning dir ' + path.join(wwwPath, 'lib', '**')); del([ path.join(wwwPath, 'i18n'), path.join(wwwPath, 'js'), path.join(wwwPath, 'templates'), path.join(wwwPath, 'css'), path.join(wwwPath, 'dist'), path.join(wwwPath, 'js'), path.join(wwwPath, 'cordova-js-src'), path.join(wwwPath, 'plugins', 'es'), path.join(wwwPath, 'lib', '**'), // Keep Ionic lib/ionic/fonts directory '!'+path.join(wwwPath, 'lib'), '!'+path.join(wwwPath, 'lib', 'ionic'), '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts'), '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', '**', '*') ]); } }
JavaScript
0.000057
@@ -1595,19 +1595,1393 @@ s', '**' -, ' +),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Black'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Black', '**'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Bold'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Bold', '**'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'BoldItalic'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'BoldItalic', '**'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Italic'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Italic', '**'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Light'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Light', '**'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Medium'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Medium', '**'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Regular'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Regular', '**'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Thin'),%0A '!'+path.join(wwwPath, 'lib', 'ionic', 'fonts', 'robotdraft', 'Thin', '* *')%0A
cc66b11b8355827e1a66926179b4b8a94aee3620
Fix FTP deploy hang when transferring many files
src/commands/deploy/index.js
src/commands/deploy/index.js
// Native const { existsSync, statSync } = require('fs'); // External const loadJsonFile = require('load-json-file'); const pify = require('pify'); const pump = require('pump'); const rsyncwrapper = require('rsyncwrapper'); const SSH = require('ssh2'); const through = require('through2'); const vfs = require('vinyl-fs'); const VTFP = require('vinyl-ftp'); // Ours const { command } = require('../../cli'); const { packs, throws, unpack } = require('../../utils/async'); const { dry, info, spin, warn } = require('../../utils/logging'); const { DEFAULTS, OPTIONS, MESSAGES, VALID_TYPES } = require('./constants'); // Wrapped const getJSON = packs(loadJsonFile); const ftp = packs(target => { const vftp = new VTFP({ host: target.host, port: target.port || 21, user: target.username, password: target.password, parallel: 10 }); return pify(pump)( vfs.src(target.files, { buffer: false, cwd: target.from }), vftp.dest(target.to), through.obj() ); }); const rsync = packs(target => { let opts = Object.assign({}, DEFAULTS.RSYNC, { src: `${target.from}/${Array.isArray(target.files) ? target.files[0] : target.files}`, dest: `${target.username}@${target.host}:${target.to}`, args: [`--rsync-path="mkdir -p ${target.to} && rsync"`] }); return pify(rsyncwrapper)(opts); }); const symlink = packs(async target => { const symlinkName = typeof target.symlink === 'string' ? target.symlink : DEFAULTS.SYMLINK.NAME; const symlinkPath = target.to.replace(target.id, symlinkName); if (symlinkPath === target.to) { warn(MESSAGES.NO_MAPPABLE_ID); return; } const ssh = new SSH(); ssh.connect(target); await pify(ssh.on)('ready'); const stream = await pify(ssh.exec)(`rm -rf ${symlinkPath} && ln -s ${target.to} ${symlinkPath}`); await pify(stream.on)('exit'); ssh.end(); }); const deployToServer = packs(async target => { info(MESSAGES.deployment(target.type, target.from, target.to, target.host)); const spinner = spin('Deploy'); try { if (target.type === 'ftp') { throws(await ftp(target)); } else if (target.type === 'ssh') { // ensure target directory has a trailing slash target.to = target.to.replace(/\/?$/, '/'); throws(await rsync(target)); if (target.symlink) { throws(await symlink(target)); } } } catch (err) { spinner.fail(); throw err; } spinner.succeed(); if (target.publicURL) { info(MESSAGES.publicURL(target.publicURL)); } }); module.exports.deploy = command( { name: 'deploy', options: OPTIONS, usage: MESSAGES.usage, isConfigRequired: true }, async (argv, config) => { // 1) Get known/specified deployment target(s) let keys = Object.keys(config.deploy); if (argv.target) { keys = keys.filter(key => key === argv.target); if (keys.length < 1) { throw MESSAGES.targetDoesNotExist(argv.target); } } if (keys.length < 1) { throw MESSAGES.NO_TARGETS; } // 2) Create an array of config objects for each target we know about const credentials = unpack(await getJSON(argv.credentials)); const targets = keys.map(key => Object.assign( { __key__: key, id: config.id, name: config.pkg.name, files: '**' }, credentials[key], config.deploy[key], argv.shouldRespectTargetSymlinks ? {} : { symlink: null } ) ); // 3) Validate & normalise those configs (in parallel) await Promise.all( targets.map(async target => { // 3.1) Check 'type' is valid if (!VALID_TYPES.has(target.type)) { throw MESSAGES.unrecognisedType(target.__key__, target.type); } // 3.2) Check all properties are present VALID_TYPES.get(target.type).REQUIRED_PROPERTIES.forEach(prop => { if (target[prop] == null) { throw MESSAGES.targetNotConfigured(target.__key__, prop); } }); // 3.3) Check 'from' directory exists if (!existsSync(target.from) || !statSync(target.from).isDirectory()) { throw MESSAGES.sourceIsNotDirectory(target.from); } // 3.4) Remove temporary properties delete target._from; delete target._to; }) ); if (argv.dry) { return dry( targets.reduce((memo, target) => { memo[`Deployment to ${target.__key__}`] = target; return memo; }, {}) ); } for (const target of targets) { throws(await deployToServer(target)); } } );
JavaScript
0.000001
@@ -981,26 +981,8 @@ o),%0A - through.obj()%0A );
3e3006e8c1ac121a59866f67b72a642ff8f52e4c
fix domainData naming. Add delimiter field - 1
src/components/Choropleth.js
src/components/Choropleth.js
/** * Choropleth Element for React-Dashboard * Author Paul Walker (https://github.com/starsinmypockets) * * Based on the following projects: * * React D3 Map Choropleth (https://github.com/react-d3/react-d3-map-choropleth) * Apache 2.0 License * * Mike Bostock's Choropleth (https://github.com/react-d3/react-d3-map-choropleth for documentation) * GNU/GPL License https://opensource.org/licenses/GPL-3.0 * **/ import BaseComponent from './BaseComponent'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import {Legend} from 'react-d3-core'; import Registry from '../utils/Registry'; import {MapChoropleth} from 'react-d3-map-choropleth'; import {mesh, feature} from 'topojson'; import {range} from 'd3'; import CSV from 'csv-es6-data-backend'; // @@TODO Add geojson implementation let legendWidth = 500, legendHeight = 400, legendMargins = {top: 40, right: 50, bottom: 40, left: 50}, legendClassName = "test-legend-class", legendPosition = 'left', legendOffset = 90; // Whack some css into the page function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = str; document.head.appendChild(node); } // Fetch css function fetchStyleSheet(url) { return new Promise((resolve, reject) => { fetch(url) .then(res => { return res.text(); }) .then(css => { resolve(css); }) .catch(e => { reject(e); }); }); } export default class Choropleth extends BaseComponent { constructor(props){ super(props); this.levels = 9; let domainField = this.props.settings.domainField; let domainKey = this.props.settings.domainKey; console.log('domains', domainKey, domainField); var self = this; Object.assign(this, { choroplethFunctions : { tooltipContent: function (d) { console.log(d, domainField, d[domainKey]); return {rate: d.properties[d[domainKey]]}; }, domainValue: function (d) { return +d[domainField]; }, domainKey: function (d) { return +d[domainKey]; }, mapKey: function (d) { return +d[domainKey]; } } }); } // fetchData should set topoData and domainData onDataReady(data) { // @@TODO Maybe we should validate this stuff console.log('on Data', data); this.setState({domaindata: data.domaindata, topodata: data.topodata}); } componentDidMount () { this._attachResize(); this._setSize(); // add stylesheet if (this.props.settings.cssPath) { fetchStyleSheet(this.props.settings.cssPath) .then(css => { addStyleString(css) }) .catch(e => { console.log('Trouble fetching component stylesheet', this.props.type, e); }); } if (this.props.fetchData && this[this.props.fetchData]) { this.fetchData().then(this.onData.bind(this)).catch(e => {console.log('Error fetching data', e)}); } addStyleString(this.css()); super.componentDidMount(); } fetchData() { console.log('fetfch!'); return new Promise((resolve, reject) => { let response = {}; fetch(this.props.settings.topoJson) .then(res => { return res.json(); }) .then(data => { response.topodata = data; CSV.fetch({url: this.props.settings.domainDataUrl}) .then(data => { console.log('CSV response', data); response.domaindata = data.records; return resolve(response); }) .catch(e => { return reject(e); }) }) .catch(e => { return reject(e); }); }); } _setSize() { const { offsetWidth, offsetHeight } = this.refs.choropleth; this.setState({ gridWidth: offsetWidth, gridHeight: offsetHeight }); } _attachResize() { window.addEventListener('resize', this._setSize.bind(this), false); } // generate css string from colors array css () { let _css = ''; let colors = this.props.settings.colors; for (var i = 0; i < this.levels; i++) { _css += `.q${i}-${this.levels} { fill:${colors[i]}; }`; } return _css; } legendSeries () { let series = []; let domainVal = .015; for (var i = 0; i < this.levels; i++) { let lower = domainVal*i.toFixed(2); let upper = domainVal*(i+1).toFixed(2); let item = { field: `${lower} -- ${upper}`, name: `${lower} -- ${upper}`, color: this.props.settings.colors[i] } series.push(item); } return series; } render () { let v; let settings = Object.assign({}, this.props.settings); console.log('>', settings, this.state); if (this.state.domaindata) { Object.assign(settings, this.state.data, {type : this.props.type}, this.choroplethFunctions); settings.topodata = this.state.topodata; settings.domainData = this.state.domaindata; console.log('>1',settings); settings.dataPolygon = feature(this.state.topodata, this.state.topodata.objects.counties).features; settings.dataMesh = mesh(this.state.topodata, this.state.topodata.objects.states, function(a, b) { return a !== b; }); settings.scale = this.state.gridWidth; settings.domain = { scale: 'quantize', domain: [settings.domainLower, settings.domainUpper], range: range(settings.levels).map(function(i) { return `q${i}-${settings.levels}`; }) }; console.log('>>', settings); v = <div className="choropleth-container"> <MapChoropleth ref="choropleth" {...settings} /> <Legend width= {legendWidth} height= {legendHeight} margins= {legendMargins} legendClassName= {legendClassName} legendPosition= {legendPosition} legendOffset= {legendOffset} chartSeries = {this.legendSeries()} /> </div>; } else { v = <p ref="choropleth" className='laoding'>Loading...</p>; } return(v); } } Registry.set('Choropleth', Choropleth);
JavaScript
0.000316
@@ -2395,17 +2395,17 @@ (%7Bdomain -d +D ata: dat @@ -2412,17 +2412,17 @@ a.domain -d +D ata, top @@ -3395,16 +3395,33 @@ nDataUrl +, delimiter: '%5Ct' %7D)%0A @@ -3515,17 +3515,17 @@ e.domain -d +D ata = da @@ -4814,17 +4814,17 @@ e.domain -d +D ata) %7B%0A @@ -5015,17 +5015,17 @@ e.domain -d +D ata;%0A
243cf537ff9b42d4409629dc6944dc633d9ab997
fix MenuItem className
src/components/menu/index.js
src/components/menu/index.js
import React from 'react'; import PropTypes from 'prop-types'; import style from './style.styl'; let MenuItem = ({title, active}) => ( <li classeName={active ? 'active' : null}><a href="">{title}</a></li> ) let Menu = ({items, active}) => ( <nav className={style['app-menu']}> <ul> {items.map((i, k) => ( <MenuItem key={k} active={active === k} {...i} /> ))} </ul> <i className={style['active-marker']}></i> </nav> ) Menu.propTypes = { items: PropTypes.array.isRequired, selected: PropTypes.number } Menu.defaultProps = { active: 1 } export {Menu as default}
JavaScript
0.000006
@@ -143,17 +143,16 @@ li class -e Name=%7Bac
1e7dfae30287bee2eff1d1a16d79106076869e6c
update individual type
src/core/types/individual.js
src/core/types/individual.js
// @flow import type { ServiceAccessHash, Identity } from './' export type Individual = { id: String, fullname: string, email: Array<string>, serviceIdentities: { [string]: Identity }, // { "github": "shamwow16" } accessRules: ServiceAccessHash, groups: Array<string> }
JavaScript
0
@@ -124,28 +124,29 @@ ,%0A -email: Array%3C +primaryEmail: ? string -%3E ,%0A @@ -191,37 +191,8 @@ y %7D, - // %7B %22github%22: %22shamwow16%22 %7D %0A a
96a4b465758eb50cceb003ca8b97e9c7e93578f1
Rebuild crel.min
crel.min.js
crel.min.js
!function(e,n){"object"==typeof exports?module.exports=n():"function"==typeof define&&define.amd?define(n):e.crel=n()}(this,function(){function e(){var o,a=arguments,p=a[0],m=a[1],x=2,v=a.length,b=e[f];if(p=e[c](p)?p:d.createElement(p),1===v)return p;if((!l(m,t)||e[u](m)||s(m))&&(--x,m=null),v-x===1&&l(a[x],"string")&&void 0!==p[r])p[r]=a[x];else for(;v>x;++x)if(o=a[x],null!=o)if(s(o))for(var g=0;g<o.length;++g)y(p,o[g]);else y(p,o);for(var h in m)if(b[h]){var N=b[h];typeof N===n?N(p,m[h]):p[i](N,m[h])}else p[i](h,m[h]);return p}var n="function",t="object",o="nodeType",r="textContent",i="setAttribute",f="attrMap",u="isNode",c="isElement",d=typeof document===t?document:{},l=function(e,n){return typeof e===n},a=typeof Node===n?function(e){return e instanceof Node}:function(e){return e&&l(e,t)&&o in e&&l(e.ownerDocument,t)},p=function(n){return e[u](n)&&1===n[o]},s=function(e){return e instanceof Array},y=function(n,t){e[u](t)||(t=d.createTextNode(t)),n.appendChild(t)};return e[f]={},e[c]=p,e[u]=a,"undefined"!=typeof Proxy&&(e.proxy=new Proxy(e,{get:function(n,t){return!(t in e)&&(e[t]=e.bind(null,t)),e[t]}})),e});
JavaScript
0.017282
@@ -149,11 +149,11 @@ var -o,a +a,d =arg @@ -163,37 +163,37 @@ nts, -p=a +s=d %5B0%5D, -m=a +p=d %5B1%5D, -x=2,v=a +y=2,x=d .length, b=e%5B @@ -192,31 +192,31 @@ gth, -b=e%5Bf +m=e%5Bo %5D;if( -p=e%5Bc%5D(p)?p:d +s=e%5Bu%5D(s)?s:c .cre @@ -230,82 +230,83 @@ ent( -p),1===v)return p;if((!l(m,t +s),x%3E1)%7Bif((!n(p,r )%7C%7Ce%5B -u%5D(m)%7C%7Cs(m +f%5D(p)%7C%7CArray.isArray(p ))&&(-- -x,m +y,p =null), -v-x= +x-y ==1&& -l(a%5Bx +n(d%5By %5D,%22s @@ -316,32 +316,26 @@ ng%22) -&&void 0!==p%5Br%5D)p%5Br%5D=a%5Bx +)s.textContent=d%5By %5D;el @@ -346,89 +346,38 @@ or(; -v%3E +y%3C x;++ -x)if(o=a%5Bx%5D,null!=o)if(s(o))for(var g=0;g%3Co.length;++g)y(p,o%5Bg%5D);else y(p,o +y)null!==(a=d%5By%5D)&&l(s,a );fo @@ -386,76 +386,70 @@ var -h +v in -m +p )if( -b%5Bh +m%5Bv %5D)%7Bvar -N=b%5Bh%5D;typeof N===n?N(p,m%5Bh%5D):p +A=m%5Bv%5D;n(A,t)?A(s,p%5Bv%5D):s %5Bi%5D( -N,m%5Bh +A,p%5Bv %5D)%7Delse p%5Bi%5D @@ -448,45 +448,64 @@ lse -p%5Bi%5D(h,m%5Bh%5D); +n(p%5Bv%5D,t)?s%5Bv%5D=p%5Bv%5D:s%5Bi%5D(v,p%5Bv%5D)%7D return -p +s %7Dvar n= -%22 function %22,t= @@ -504,47 +504,56 @@ tion -%22,t=%22object%22,o=%22nodeType%22,r=%22textConten +(e,n)%7Breturn typeof e===n%7D,t=%22function%22,r=%22objec t%22,i @@ -568,17 +568,17 @@ ribute%22, -f +o =%22attrMa @@ -580,17 +580,17 @@ ttrMap%22, -u +f =%22isNode @@ -591,17 +591,17 @@ isNode%22, -c +u =%22isElem @@ -609,196 +609,60 @@ nt%22, -d=typeof document===t?document:%7B%7D,l=function(e,n)%7Breturn typeof e===n%7D,a=typeof Node===n?function(e)%7Breturn e instanceof Node%7D:function(e)%7Breturn e&&l(e,t)&&o in e&&l(e.ownerDocument,t)%7D,p +c=document,a=function(e)%7Breturn e instanceof Node%7D,d =fun @@ -679,17 +679,17 @@ eturn e%5B -u +f %5D(n)&&1= @@ -695,14 +695,20 @@ ===n -%5Bo%5D%7D,s +.nodeType%7D,l =fun @@ -717,57 +717,75 @@ ion( -e)%7Breturn e instanceof Array%7D,y=function(n,t)%7Be%5Bu +n,t)%7Bif(Array.isArray(t))return void t.map(function(e)%7Bl(n,e)%7D);e%5Bf %5D(t) @@ -789,17 +789,17 @@ (t)%7C%7C(t= -d +c .createT @@ -841,28 +841,36 @@ n e%5B -f +o %5D=%7B%7D,e%5B -c%5D=p,e%5Bu +u%5D=d,e%5Bf %5D=a, +n(Proxy, %22und @@ -880,24 +880,11 @@ ned%22 -!=typeof Proxy&& +)%7C%7C (e.p
79d1e91d0bdb920e78f8972a1f95b3b242a5cb82
Solve day 19 part 2
day19/19.js
day19/19.js
'use strict'; const fs = require('fs'); const _ = require('lodash'); fs.readFile('input.txt', 'utf8', (error, contents) => { let split = contents.split('\n'); // pull out the substitutions by filtering on '=>' let subs = split.filter(s => s.indexOf('=>') > 0); // the last line of the input is the molecule let molecule = split[split.length - 1]; let results = doSubstitutions(molecule, subs); console.log(results.length); }); const doSubstitutions = function(molecule, subs) { let results = []; subs.forEach(sub => { sub = sub.split(' => '); let re = new RegExp(sub[0], 'g'); let indices = []; let i = -1; while ((i = molecule.indexOf(sub[0], i+1)) >= 0) { indices.push(i); } for (let n = 0; n < indices.length; n++) { let begin = molecule.substr(0, indices[n]); let rest = molecule.substr(indices[n] + sub[0].length); results.push(begin + sub[1] + rest); } }); return _.uniq(results); };
JavaScript
0.999999
@@ -352,16 +352,28 @@ - 1%5D;%0A%0A + // part 1%0A let re @@ -427,16 +427,29 @@ ole.log( +'Part 1: ' + results. @@ -456,16 +456,63 @@ length); +%0A%0A // part 2%0A countTransformations(molecule); %0A%7D);%0A%0Aco @@ -1042,7 +1042,946 @@ s);%0A - %7D;%0A +%0A%0A/**%0AI unfortunately can not take credit for these insights about part 2, taken from%0Ahttps://www.reddit.com/r/adventofcode/comments/3xflz8/day_19_solutions/cy4etju%0A*/%0Aconst countTransformations = function(molecule) %7B%0A // Count of all total elements in the molecule%0A let elements = molecule.match(/%5BA-Z%5D/g);%0A // %22Rn%22 and %22Ar%22 are boundaries of multiple possible transformations,%0A // can be thought of as %22(%22 and %22)%22. They are not %22real%22 elements themselves.%0A // %22Y%22 is the separator within an %22Rn%22 & %22Ar%22 boundary, similar to a %22,%22.%0A let Rns = molecule.match(/Rn/g);%0A let Ars = molecule.match(/Ar/g);%0A let Ys = molecule.match(/Y/g);%0A%0A // So, the minimum possible transformations to create the molecule starting%0A // from %22e%22 can be described as: elements - Rns - Ars - 2*Ys - 1%0A let transforms = elements.length - Rns.length - Ars.length - (2 * Ys.length) - 1;%0A console.log('Minumum transformations required: ' + transforms);%0A%7D%0A
ffdedb965af8acad757de17a7407b38334ff3601
Build filter: storing the named filters locally
ontrack-web/src/app/service/service.buildfilter.js
ontrack-web/src/app/service/service.buildfilter.js
angular.module('ot.service.buildfilter', [ 'ot.service.core', 'ot.service.form' ]) .service('otBuildFilterService', function (ot, $q, $http, otFormService) { var self = {}; /** * Creating a new build filter * @param config.branchId ID of the branch * @param config.buildFilterForm Build filter form * @return Promise with the created filter */ self.createBuildFilter = function (config) { var result = {}; var d = $q.defer(); otFormService.display({ title: "New filter", form: config.buildFilterForm.form, submit: function (filterData) { // Stores locally the filter data if named if (filterData.name) { // TODO self.storeForBranch(config, filterData); } // Stores locally as current self.storeCurrent(config, filterData); // Stores for the reuse result.filterData = filterData; // OK return true; } }).then(function () { d.resolve(result.filterData); }); return d.promise; }; self.storeCurrent = function (config, filterData) { localStorage.setItem('build_filter_' + config.branchId + '_current', JSON.stringify(filterData) ); }; return self; }) ;
JavaScript
0.000002
@@ -831,16 +831,8 @@ -// TODO self @@ -860,32 +860,32 @@ g, filterData);%0A + @@ -1493,16 +1493,16 @@ erData)%0A - @@ -1512,32 +1512,1000 @@ );%0A %7D;%0A%0A + self.storeForBranch = function (config, filterData) %7B%0A // Gets the store for this branch%0A var store = self.getStoreForBranch(config.branchId);%0A // Stores the resource in the store%0A store%5BfilterData.name%5D = %7B%0A name: filterData.name,%0A type: config.buildFilterForm.type,%0A filter: filterData%0A %7D;%0A // Saves the store back%0A localStorage.setItem(self.getStoreIdForBranch(config.branchId),%0A JSON.stringify(store)%0A );%0A %7D;%0A%0A self.getStoreForBranch = function (branchId) %7B%0A var json = localStorage.getItem(self.getStoreIdForBranch(branchId));%0A if (json) %7B%0A return JSON.parse(json);%0A %7D else %7B%0A return %7B%7D;%0A %7D%0A %7D;%0A%0A self.getStoreIdForBranch = function (branchId) %7B%0A return 'build_filter_' + branchId;%0A %7D;%0A%0A return s
da1e0e1d991ffcbd21011845c1ba1272b62a5117
Update form-wizard-directive.js
src/form-wizard-directive.js
src/form-wizard-directive.js
(function(){ 'use strict'; angular.module("sflFormWizard", []) .directive('formWizard', ['$http', function($http) { this.template = function() { return $http.get('angular-form-wizard-directive.html').then(function(response) { return response; }); }; this.linker = function(scope, element, attributes) { scope.formWizardEnabled = true; scope.formWizardSelectedIndex = 0; scope.formWizardMaxIndex = fieldsetCount; }; return { restrict: 'E', scope: true, compile: function(element, attributes) { var navigatorHtmlPrefix = '<div class="panel-heading">'; var navigatorHtmlSuffix = '<div class="btn-group pull-right">' + '<button class="btn btn-default" ' + 'ng-click="formWizardSelectedIndex = formWizardSelectedIndex-1" ' + 'ng-disabled="formWizardSelectedIndex <= 0">PREV</button>' + '<button class="btn btn-default" ' + 'ng-click="formWizardSelectedIndex = formWizardSelectedIndex+1" ' + 'ng-disabled="formWizardSelectedIndex >= formWizardMaxIndex">NEXT</button>' + '</div><div class="clearfix"></div></div>'; var form = element.find('form'); form.addClass('panel-body'); var fieldsetTitles = []; angular.forEach(form.find('fieldset'), function(value, key) { var fieldset = angular.element(value); var legend = fieldset.find('legend'); fieldsetTitles.push(legend ? legend.text() : 'Step ' + (key+1)); fieldset.attr('data-form-wizard-index', key); fieldset.attr('ng-show', 'formWizardSelectedIndex == ' + key); }); if(fieldsetTitles.length) { var navigatorHtml = '<div class="btn-group pull-left">'; angular.forEach(fieldsetTitles, function(value, key) { navigatorHtml += '<button type="button" ' + 'class="btn btn-default" ' + 'ng-class="{ active: formWizardSelectedIndex == ' + key + ', }" ' + 'ng-click="formWizardSelectedIndex = ' + key + '">' + '<span class="badge">' + (key+1) + '</span>&nbsp;' + value + '</button>' }); navigatorHtml += '</div>'; } element.prepend(navigatorHtmlPrefix + navigatorHtml + navigatorHtmlSuffix); form.wrap('<div class="panel panel-default"></div>'); return function(scope, element, attributes) { scope.formWizardEnabled = true; scope.formWizardSelectedIndex = 0; scope.formWizardMaxIndex = fieldsetTitles.length - 1; }; } }; }]); })();
JavaScript
0
@@ -61,13 +61,15 @@ %22sfl -FormW +.form.w izar
e21dae1b4b1ed1010265fd17eca3c104f5b7c47c
Fix linter
lib/assets/test/spec/builder/routes/router.spec.js
lib/assets/test/spec/builder/routes/router.spec.js
var Backbone = require('backbone'); var Router = require('builder/routes/router'); Backbone.history.start({ pushState: false, hashChange: true, root: 'builder/id' }); // // Mock this, because it fails // Router.getCurrentRoute = function () { // return '/la/promosio'; // }; describe('routes/router', function () { var editorModel; var modals; var handleModalsRouteSpy; var handleAnalysesRouteSpy; var onChangeRouteSpy; beforeAll(function () { editorModel = new Backbone.Model({ edition: false }); widgetDefinitionsCollection = { trigger: jasmine.createSpy() }; modals = { destroy: jasmine.createSpy() }; handleModalsRouteSpy = jasmine.createSpy('handleModalsRouteSpy'); handleAnalysesRouteSpy = jasmine.createSpy('handleAnalysesRouteSpy'); handleWidgetRouteSpy = jasmine.createSpy('handleWidgetRouteSpy'); onChangeRouteSpy = spyOn(Router, '_onChangeRoute'); Router.init({ modals: modals, editorModel: editorModel, widgetDefinitionsCollection: widgetDefinitionsCollection, handleModalsRoute: handleModalsRouteSpy, handleAnalysesRoute: handleAnalysesRouteSpy, handleWidgetRoute: handleWidgetRouteSpy, }); spyOn(Backbone.History.prototype, 'matchRoot').and.returnValue(true); }); afterEach(function () { // Reset URL Hashtag. If the URL keeps the hashtag, the test will fail next time. window.history.pushState('', document.title, window.location.pathname + window.location.search); }); describe('._initBinds', function () { it('should handle analyses route', function () { onChangeRouteSpy.and.callThrough(); editorModel.set({ edition: true }, { silent: true }); Router.navigate('/layer/l1-1/analyses/a1'); var routeModel = Router.getRouteModel().get('currentRoute'); expect(handleModalsRouteSpy).toHaveBeenCalledWith(routeModel, modals); expect(handleAnalysesRouteSpy).toHaveBeenCalledWith(routeModel); expect(editorModel.get('edition')).toBe(false); }); it('should handle widget route', function () { onChangeRouteSpy.and.callThrough(); Router.navigate('/widget/widget-1337'); var routeModel = Router.getRouteModel().get('currentRoute'); expect(handleWidgetRouteSpy).toHaveBeenCalledWith(routeModel, widgetDefinitionsCollection); }); }); });
JavaScript
0.000002
@@ -346,16 +346,51 @@ modals;%0A + var widgetDefinitionsCollection;%0A var ha @@ -435,24 +435,52 @@ esRouteSpy;%0A + var handleWidgetRouteSpy;%0A var onChan @@ -1271,25 +1271,24 @@ dgetRouteSpy -, %0A %7D);%0A%0A
43ce783e5ec2dcf1d0533d0123822614c7645918
fix 'Unhandled Rejection' in kuberntes-enrichment plugin
lib/plugins/output-filter/kubernetes-enrichment.js
lib/plugins/output-filter/kubernetes-enrichment.js
const { KubeConfig } = require('kubernetes-client') const Client = require('kubernetes-client').Client const Request = require('kubernetes-client/backends/request') const kubeconfig = new KubeConfig() var consoleLogger = require('../../util/logger.js') var LRU = require('lru-cache') var podCache = new LRU({ max: 2000, maxAge: 1000 * 60 * 60 }) var digestRegEx = /sha256:.+/i var client = null const FALSE_REGEX = /false/i if (process.env.KUBERNETES_PORT_443_TCP !== undefined) { kubeconfig.loadFromCluster() } else { kubeconfig.loadFromDefault() } client = new Client({ backend: new Request({ kubeconfig }) }) client.loadSpec().catch(error => { consoleLogger.error('Error in k8s client', error) }) function kubernetesOutputFilter (context, config, eventEmitter, data, callback) { // we use the config object to track state of each plugin instance if (!config.client) { initKubernetesClient(config) } else { enrichLogs(context, config, eventEmitter, data, callback) } } function initKubernetesClient (config) { // do we run in k8s cluster? config.client = client config.getPodSpec = function (namespace, podName, cb) { this.client.api.v1.namespaces(namespace).pods(podName).get(cb) }.bind(config) } async function getPodSpec (config, namespace, podName, cb) { if (config.client && config.client.api) { var spec = await config.client.api.v1.namespaces(namespace).pods(podName).get() cb(null, spec.body) } else { cb(new Error('Kuberntes API not ready')) } } function removeFields (pod, data) { if (pod && pod.stRemoveFields === false) { return } var annotations = pod.metadata.annotations var removeFields = annotations['REMOVE_FIELDS'] || annotations['sematext.com/logs-remove-fields'] if (removeFields) { var fieldNames = removeFields.split(',') for (var i = 0; i < fieldNames.length; i++) { delete data[fieldNames[i]] } } else { pod.stRemoveFields = false } } function checkLogsEnabled (pod, data, context) { if (pod.stLogEnabled === false) { data.stLogEnabled = false return } var annotations = pod.metadata.annotations if (annotations) { var logsEnabled = annotations['sematext.com/logs-enabled'] if (FALSE_REGEX.test(logsEnabled)) { data.stLogEnabled = false pod.stLogEnabled = false if (process.env.DEBUG) { consoleLogger.error('stLogEnabled = false', key) } } else { pod.stLogEnabled = true } } } function addLogsIndex (pod, data) { if (pod.stLogsTokenSet === false) { return } // get ST Logs Token from pod annotation var index = pod.metadata.annotations['sematext.com/logs-token'] // get comma separated list of fields from pod annotation if (index) { data._index = index } else { pod.stLogsTokenSet = false } } function replaceDockerImageName (pod, data) { if (data.kubernetes && data.container && pod.stImageCache) { var containerName = data.kubernetes.pod.container.name var imageInfo = pod.stImageCache[data.kubernetes.pod.name + containerName] if (!imageInfo) { return } if (data.container.image.name === 'sha256') { data.container.image.digest = 'sha256:' + data.container.image.tag } data.container.image.name = imageInfo.name data.container.image.tag = imageInfo.tag } else { pod.stLogsTokenSet = false } } function processAnnotations (data, context) { var pod = podCache.get(data.kubernetes.namespace + '/' + data.kubernetes.pod.name) if (pod && pod.metadata) { checkLogsEnabled(pod, data, context) if (data.stLogEnabled === false) { // logs will be droped, so no need for other processing return } replaceDockerImageName(pod, data) removeFields(pod, data) addLogsIndex(pod, data) } } function enrichLogs (context, config, eventEmitter, data, callback) { if (!(data.kubernetes && data.kubernetes.pod)) { return callback(null, data) } if (podCache.get(data.kubernetes.namespace + '/' + data.kubernetes.pod.name)) { processAnnotations(data, context) if (data.stLogEnabled === false) { // allow input plugins to close the input stream, e.g. input/docker/docker.js eventEmitter.emit('dropLogsRequest', context, data) if (config.debug === true) { consoleLogger.log('logs dropped ' + data.kubernetes.namespace + '/' + data.kubernetes.pod.name, data.message) } return callback() } else { return callback(null, data) } } else { getPodSpec( config, data.kubernetes.namespace, data.kubernetes.pod.name, function (err, pod) { if (err) { consoleLogger.log(err.message) return callback(null, data) } podCache.set(data.kubernetes.namespace + '/' + data.kubernetes.pod.name, pod) // create hashtable with containerName -> imageInformation pod.stImageCache = {} if (pod.spec && pod.spec.containers) { var podContainers = pod.spec.containers for (var i = 0; i < podContainers.length; i++) { var container = podContainers[i] // split imageName:version var imageInfo = container.image.split(':') // split registry/imageName var imageRegistryInfo = container.image.split('/') var imageKey = pod.metadata.name + container.name pod.stImageCache[imageKey] = { image: container.image, name: imageInfo[0], registry: imageRegistryInfo[0] } if (imageInfo.length > 1) { pod.stImageCache[imageKey].tag = imageInfo[1] } if (imageRegistryInfo.length > 1) { pod.stImageCache[imageKey].plainImageName = imageRegistryInfo[1] } } } if (config.debug) { consoleLogger.log('pod spec: ' + JSON.stringify(pod, null, ' ')) } processAnnotations(data, context) if (data.stLogEnabled === false) { // allow input plugins to close the input stream, e.g. input/docker/docker.js eventEmitter.emit('dropLogsRequest', context, data) return callback() } else { return callback(null, data) } } ) } } module.exports = kubernetesOutputFilter
JavaScript
0
@@ -1654,16 +1654,84 @@ tations%0A + if (!annotations) %7B%0A pod.stRemoveFields = false%0A return%0A %7D%0A var re
fd61e70ff7141f8059e6609875be8ce498071898
handle title attribute change while connected
src/js/components/tooltip.js
src/js/components/tooltip.js
import Container from '../mixin/container'; import Togglable from '../mixin/togglable'; import Position from '../mixin/position'; import { append, attr, flipPosition, hasAttr, includes, isFocusable, isTouch, matches, offset, on, once, pointerDown, pointerEnter, pointerLeave, remove, within, } from 'uikit-util'; export default { mixins: [Container, Togglable, Position], args: 'title', props: { delay: Number, title: String, }, data: { pos: 'top', title: '', delay: 0, animation: ['uk-animation-scale-up'], duration: 100, cls: 'uk-active', }, beforeConnect() { this.id = `uk-tooltip-${this._uid}`; this._hasTitle = hasAttr(this.$el, 'title'); attr(this.$el, { title: '', 'aria-describedby': this.id, }); makeFocusable(this.$el); }, disconnected() { this.hide(); attr(this.$el, 'title', this._hasTitle ? this.title : null); }, methods: { show() { if (this.isToggled(this.tooltip || null) || !this.title) { return; } this._unbind = once( document, `keydown ${pointerDown}`, this.hide, false, (e) => (e.type === pointerDown && !within(e.target, this.$el)) || (e.type === 'keydown' && e.keyCode === 27) ); clearTimeout(this.showTimer); this.showTimer = setTimeout(this._show, this.delay); }, async hide() { if (matches(this.$el, 'input:focus')) { return; } clearTimeout(this.showTimer); if (!this.isToggled(this.tooltip || null)) { return; } await this.toggleElement(this.tooltip, false, false); remove(this.tooltip); this.tooltip = null; this._unbind(); }, _show() { this.tooltip = append( this.container, `<div id="${this.id}" class="uk-${this.$options.name}" role="tooltip"> <div class="uk-${this.$options.name}-inner">${this.title}</div> </div>` ); on(this.tooltip, 'toggled', (e, toggled) => { if (!toggled) { return; } this.positionAt(this.tooltip, this.$el); const [dir, align] = getAlignment(this.tooltip, this.$el, this.pos); this.origin = this.axis === 'y' ? `${flipPosition(dir)}-${align}` : `${align}-${flipPosition(dir)}`; }); this.toggleElement(this.tooltip, true); }, }, events: { focus: 'show', blur: 'hide', [`${pointerEnter} ${pointerLeave}`](e) { if (!isTouch(e)) { this[e.type === pointerEnter ? 'show' : 'hide'](); } }, // Clicking a button does not give it focus on all browsers and platforms // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#clicking_and_focus [pointerDown](e) { if (isTouch(e)) { this.show(); } }, }, }; function makeFocusable(el) { if (!isFocusable(el)) { attr(el, 'tabindex', '0'); } } function getAlignment(el, target, [dir, align]) { const elOffset = offset(el); const targetOffset = offset(target); const properties = [ ['left', 'right'], ['top', 'bottom'], ]; for (const props of properties) { if (elOffset[props[0]] >= targetOffset[props[1]]) { dir = props[1]; break; } if (elOffset[props[1]] <= targetOffset[props[0]]) { dir = props[0]; break; } } const props = includes(properties[0], dir) ? properties[1] : properties[0]; if (elOffset[props[0]] === targetOffset[props[0]]) { align = props[0]; } else if (elOffset[props[1]] === targetOffset[props[1]]) { align = props[1]; } else { align = 'center'; } return [dir, align]; }
JavaScript
0.000001
@@ -994,24 +994,69 @@ his.hide();%0A +%0A if (!attr(this.$el, 'title')) %7B%0A attr @@ -1108,24 +1108,34 @@ le : null);%0A + %7D%0A %7D,%0A%0A
60e162c2fc714fa11a58bf38c0fa9f8299c49619
Update slashdot-tests.js
snippets/slashdot-tests.js
snippets/slashdot-tests.js
// ==UserScript== // @name SlashdotTest // @namespace https://github.com/skurtn/TampermonkeyScripts // @version 1.0.2 // @description Tinkers with Slashdot's landing page // @author S. Kurt Newman // @match https://slashdot.org/* // @run-at document-end // @grant GM_log // @noiframes // @updateUrl https://raw.githubusercontent.com/skurtn/TampermonkeyScripts/master/snippets/slashdot-tests.meta.js // @downloadUrl https://raw.githubusercontent.com/skurtn/TampermonkeyScripts/master/snippets/slashdot-tests.js // @require https://code.jquery.com/jquery-3.0.0.min.js#sha256=6069398299730203aa434d1520ccf88ee8bf0aeee241aca18edbd85c78943432 // ==/UserScript== (function() { 'use strict'; var version = "1.0.1"; GM_log( "Slashdot test script started: v" + version ); // display a list of story headlines on slashdot $( "span.story-title > a" ).each( function( index ) { GM_log( "Story: " + $(this).html() ); }); GM_log( "Test tampermonkey script ended" ); })();
JavaScript
0.000001
@@ -442,120 +442,8 @@ .js%0A -// @downloadUrl https://raw.githubusercontent.com/skurtn/TampermonkeyScripts/master/snippets/slashdot-tests.js%0A // @
bf94da05df3bc4dfaa09d6ada93af096c891f85d
remove version from api
src/server/api/index.js
src/server/api/index.js
import { version } from '../../../package.json'; import { Router } from 'express'; import userRoutes from './user-routes'; import authRoutes from './auth-routes'; import patientRoutes from './patient-routes'; import professionalRoutes from './professional-routes'; import appointmentRoutes from './appointment-routes'; import targetTypeRoutes from './target-type-routes'; import dttTypeRoutes from './dtt-type-routes'; import skillRoutes from './skill-routes'; import curriculumRoutes from './curriculum-routes'; import clientCurriculumRoutes from './client-curriculum-routes'; import skillDataRoutes from './skill-data-routes'; export default ({ config, db }) => { let api = Router(); // mount user routes at /users api.use('/users', userRoutes); api.use('/auth', authRoutes); api.use('/patients', patientRoutes); api.use('/professionals', professionalRoutes); api.use('/appointments', appointmentRoutes); api.use('/targettypes', targetTypeRoutes); api.use('/dtttypes', dttTypeRoutes); api.use('/skills', skillRoutes); api.use('/curriculums', curriculumRoutes); api.use('/clientcurriculums', clientCurriculumRoutes); api.use('/skilldatas', skillDataRoutes); // perhaps expose some API metadata at the root api.get('/', (req, res) => { res.json({ version }); }); return api; }
JavaScript
0
@@ -1,16 +1,18 @@ +// import %7B version @@ -1220,16 +1220,19 @@ e root%0A%09 +// api.get( @@ -1253,16 +1253,19 @@ ) =%3E %7B%0A%09 +// %09res.jso @@ -1281,16 +1281,19 @@ on %7D);%0A%09 +// %7D);%0A%0A%09re
ef35a2cad8dd29dc451cd1fbdbcc72b0f1124908
add reject
src/server/createApp.js
src/server/createApp.js
/** * createApp at server */ import * as _ from '../share/util' import createMatcher from '../share/createMatcher' import { defaultAppSettings } from '../share/constant' import * as defaultViewEngine from './viewEngine' import History from '../share/history' import createMemoryHistory from 'create-history/lib/createMemoryHistory' export default function createApp(appSettings) { let finalAppSettings = _.extend({ viewEngine: defaultViewEngine }, defaultAppSettings) _.extend(finalAppSettings, appSettings) let { routes, viewEngine, loader, context, } = finalAppSettings let matcher = createMatcher(routes) let history = createHistory(finalAppSettings) function render(requestPath, callback) { let location = history.createLocation(requestPath) let matches = matcher(location.pathname) if (!matches) { let error = new Error(`Did not match any route with path:${requestPath}`) callback && callback(error) return Promise.reject(error) } let { path, params, controller } = matches location.pattern = path location.params = params let initController = createInitController(location, callback) let controllerType = typeof controller let Controller = null if (controllerType === 'string') { Controller = loader(controller, location) } else if (controllerType === 'function') { Controller = controller(location, loader) } else { throw new Error('controller must be string or function') } if (_.isThenable(Controller)) { return Controller.then(initController) } else { return initController(Controller) } } let controllers = {} function getController(pattern, Controller) { if (controllers.hasOwnProperty(pattern)) { return controllers[pattern] } // implement the controller's life-cycle and useful methods class WrapperController extends Controller { constructor(location, context) { super(location, context) this.location = this.location || location this.context = this.context || context } // history apis goReplace(targetPath) { return render(targetPath) } goTo(targetPath) { return render(targetPath) } } controllers[pattern] = WrapperController return WrapperController } function createInitController(location, callback) { return function initController(Controller) { let FinalController = getController(location.pattern, Controller) let controller = new FinalController(location, context) let component = controller.init() if (_.isThenable(component)) { let promise = component.then(renderToString) if (callback) { promise.then(result => callback(null, result), callback) } return promise } let result = renderToString(component) if (callback) { callback(null, result) } return result } } function renderToString(component) { return viewEngine.render(component) } function publicRender(requestPath, callback) { try { return render(requestPath, callback) } catch (error) { callback && callback(error) } } return { render: publicRender, history, } } function createHistory(settings) { let create = createMemoryHistory create = History.useBasename(create) create = History.useQueries(create) return create(settings) }
JavaScript
0.000006
@@ -3659,32 +3659,73 @@ callback(error)%0A + return Promise.reject(error)%0A %7D%0A %7D%0A
7aa747c5a0e61fe0d000affbfbb302035a1ca9e0
Attach schema i18n
both/collections/homes.js
both/collections/homes.js
Homes = new Mongo.Collection('homes'); var HomesSchema = new SimpleSchema({ name:{ type:String, label: 'Home Name', }, groupId: { type: String, label: 'Group', autoform: { options: function() { return _.map(Groups.find().fetch(), function(group) { return { label: group.name, value: group._id }; }); } } } }); Homes.attachSchema(HomesSchema); Homes.helpers({ groupName: function () { // Get the Group ID; var groupId = this.groupId; // Get Group from Groups collection, by ID(s) var group = Groups.findOne(groupId); // Return the Group name return group.name; } }); Homes.allow({ insert: function () { return true; }, update: function () { return true; } });
JavaScript
0.000006
@@ -405,24 +405,69 @@ %7D%0A %7D%0A%7D);%0A%0A +// Add i18n tags%0AHomesSchema.i18n(%22homes%22);%0A%0A Homes.attach
8edd99b6b0ba77788b1cdd3fc8b6e8a1fcdc0754
Append '.request' to module name
src/services/request.js
src/services/request.js
;(function() { 'use strict'; angular.module('gebo-client-performatives', ['ngRoute', 'ngResource']). factory('Request', function () { /** * Initiate a request * * @param string * @param string * @param string * @param string * * @return Object */ function _request(sender, receiver, action, gebo) { return { sender: sender, receiver: receiver, performative: 'request', action: action, gebo: gebo, }; }; /** * Cancel a request * * @param Object - social commitment * @param string - email of sender * * @return Object */ function _cancel(sc, email) { return { sender: email, receiver: sc.debtor === email? sc.creditor: sc.debtor, performative: 'cancel request', action: sc.action, }; }; /** * Communicate misunderstanding * * @param Object - social commitment * @param string - email of sender * * @return Object */ function _notUnderstood(sc, email) { return { sender: email, receiver: sc.debtor === email? sc.creditor: sc.debtor, performative: 'not-understood ' + sc.performative.split(' ').pop(), action: sc.action, }; }; /** * Refuse an agent's assertion * * @param Object - social commitment * @param string - email of sender * * @return Object */ function _refuse(sc, email) { return { sender: email, receiver: sc.debtor === email? sc.creditor: sc.debtor, performative: 'refuse ' + sc.performative.split(' ').pop(), action: sc.action, }; }; /** * Refuse an agent's assertion * * @param Object - social commitment * @param string - email of sender * * @return Object */ function _timeout(sc, email) { return { sender: email, receiver: sc.debtor === email? sc.creditor: sc.debtor, performative: 'timeout ' + sc.performative.split(' ').pop(), action: sc.action, }; }; /** * Agree to an agent's assertion * * @param Object - social commitment * @param string - email of sender * * @return Object */ function _agree(sc, email) { return { sender: email, receiver: sc.debtor === email? sc.creditor: sc.debtor, performative: 'agree ' + sc.performative.split(' ').pop(), action: sc.action, }; }; /** * Signal failure to perform action * * @param Object - social commitment * @param string - email of sender * * @return Object */ function _failure(sc, email) { return { sender: email, receiver: sc.debtor === email? sc.creditor: sc.debtor, performative: 'failure ' + sc.performative.split(' ').pop(), action: sc.action, }; }; /** * Signal that the request action has been performed * * @param Object - social commitment * @param string - email of sender * * @return Object */ function _proposeDischarge(sc, email) { return { sender: email, receiver: sc.debtor === email? sc.creditor: sc.debtor, performative: 'propose ' + sc.performative.split(' ').pop(), action: sc.action, }; }; /** * Get the name of the appropriate directive * * (This will likely be moved in reorganization) * * @param Object - social commitment * @param string - email of would-be sender * * @return string */ function _getDirectiveName(sc, email) { // Determine the agent's role var role = 'server'; switch(sc.performative) { case 'reply request': role = sc.debtor === email? 'server': 'client'; break; case 'propose discharge|perform': role = sc.debtor === email? 'server': 'client'; break; case 'reply propose|discharge|perform': role = sc.debtor === email? 'client': 'server'; break; } // Remove spaces and pipes return role + '-' + sc.performative.replace(' ', '-').replace(/\|/g, '-'); }; return { agree: _agree, cancel: _cancel, failure: _failure, getDirectiveName: _getDirectiveName, notUnderstood: _notUnderstood, proposeDischarge: _proposeDischarge, refuse: _refuse, request: _request, timeout: _timeout, }; }); }());
JavaScript
0.000024
@@ -82,16 +82,24 @@ rmatives +.request ', %5B'ngR
3a45af7004895030c7cb3a29d39a13e7fe20147d
Update some URLs in the constants with new values
src/shared/constants.js
src/shared/constants.js
module.exports = Object.freeze({ APP_ID: 'openwmail.openwmail', MAILBOX_INDEX_KEY: '__index__', MAILBOX_SLEEP_WAIT: 1000 * 30, // 30 seconds WEB_URL: 'https://github.com/openwmail/openwmail/', GITHUB_URL: 'https://github.com/openwmail/openwmail/', GITHUB_ISSUE_URL: 'https://github.com/openwmail/openwmail/issues', UPDATE_DOWNLOAD_URL: 'https://github.com/openwmail/openwmail/releases', UPDATE_CHECK_URL: 'http://geekgonecrazy.com/misc/wmail/version.json', PRIVACY_URL: 'https://github.com/openWMail/openWMail/wiki/Privacy-Policy', USER_SCRIPTS_WEB_URL: 'https://github.com/Thomas101/wmail-user-scripts', UPDATE_CHECK_INTERVAL: 1000 * 60 * 60 * 24, // 24 hours GMAIL_PROFILE_SYNC_MS: 1000 * 60 * 60, // 60 mins GMAIL_UNREAD_SYNC_MS: 1000 * 60, // 60 seconds GMAIL_NOTIFICATION_MAX_MESSAGE_AGE_MS: 1000 * 60 * 60 * 2, // 2 hours GMAIL_NOTIFICATION_FIRST_RUN_GRACE_MS: 1000 * 30, // 30 seconds REFOCUS_MAILBOX_INTERVAL_MS: 300, DB_EXTENSION: 'wmaildb', DB_WRITE_DELAY_MS: 500 // 0.5secs })
JavaScript
0.000002
@@ -166,38 +166,27 @@ s:// -github.com/openwmail/openwmail +openwmail.github.io /',%0A @@ -414,39 +414,31 @@ http +s :// -geekgonecrazy.com/misc/wmail +openwmail.github.io /ver @@ -477,56 +477,33 @@ s:// -github.com/openWMail/openWMail/wiki/Privacy-Poli +openwmail.github.io/priva cy',
0c9f59db75ede7a1fc4d96b4ca4d386b618ac6a6
add `AggregateError#message`
packages/core-js/modules/esnext.aggregate-error.js
packages/core-js/modules/esnext.aggregate-error.js
var $ = require('../internals/export'); var getPrototypeOf = require('../internals/object-get-prototype-of'); var setPrototypeOf = require('../internals/object-set-prototype-of'); var create = require('../internals/object-create'); var createPropertyDescriptor = require('../internals/create-property-descriptor'); var iterate = require('../internals/iterate'); var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var anObject = require('../internals/an-object'); var $AggregateError = function AggregateError(errors, message) { var that = this; if (!(that instanceof $AggregateError)) return new $AggregateError(errors, message); if (setPrototypeOf) { that = setPrototypeOf(new Error(message), getPrototypeOf(that)); } var errorsArray = []; iterate(errors, errorsArray.push, errorsArray); createNonEnumerableProperty(that, 'errors', errorsArray); if (message !== undefined) createNonEnumerableProperty(that, 'message', String(message)); return that; }; $AggregateError.prototype = create(Error.prototype, { constructor: createPropertyDescriptor(5, $AggregateError), name: createPropertyDescriptor(5, 'AggregateError'), toString: createPropertyDescriptor(5, function toString() { var name = anObject(this).name; name = name === undefined ? 'AggregateError' : String(name); var message = this.message; message = message === undefined ? '' : String(message); return name + ': ' + message; }) }); $({ global: true }, { AggregateError: $AggregateError });
JavaScript
0
@@ -1124,16 +1124,60 @@ Error),%0A + message: createPropertyDescriptor(5, ''),%0A name:
b832baa7df433d7c05aa5e72df3c3945d3b80e78
Use more specific div.sub selector
R7.Epsilon/Menu/Mega2Epsilon.js
R7.Epsilon/Menu/Mega2Epsilon.js
function splitSubMenu(columns) { jQuery("div.sub").each(function (i) { var items = jQuery(this).find('ul'); var blockCount = columns; for (var i = 0; i < items.length; i += blockCount) { var slice = items.slice(i, i + blockCount); slice.wrapAll("<div class=\"row\"></div>"); } }); } jQuery(document).ready(function () { // calculate height of top level menu and set top style for menu placement jQuery('ul.megamenu li .sub').css('top', jQuery('ul.megamenu > li').height()); // set hover class to parent item jQuery('li.level0 div').mouseover(function () { jQuery(this).closest('li.level0').find('a.level0').addClass("megahover") }).mouseout(function () { jQuery(this).closest('li.level0').find('a.level0').removeClass("megahover") }); function megaHoverOver() { jQuery(this).find(".sub").stop().fadeTo('slow', 1).show(); // calculate width of all ul's (function (jQuery) { jQuery.fn.calcSubWidth = function () { rowWidth = 0; //Calculate row $(this).find("ul").each(function () { rowWidth += $(this).width(); }); }; })(jQuery); if (jQuery(this).find(".row").length > 0) { // if row exists... var biggestRow = 0; // calculate each row jQuery(this).find(".row").each(function () { jQuery(this).calcSubWidth(); // find biggest row if (rowWidth > biggestRow) { biggestRow = rowWidth; } }); // set width jQuery(this).find(".sub").css({ 'width': biggestRow }); jQuery(this).find(".row:last").css({ 'margin': '0' }); } else { // if row does not exist... jQuery(this).calcSubWidth(); // set width jQuery(this).find(".sub").css({ 'width': rowWidth }); } } function megaHoverOut() { jQuery(this).find(".sub").stop().fadeTo('slow', 0, function () { jQuery(this).hide(); }); } var config = { sensitivity: 2, // number = sensitivity threshold (must be 1 or higher) interval: 100, // number = milliseconds for onMouseOver polling interval over: megaHoverOver, // function = onMouseOver callback (REQUIRED) timeout: 100, // number = milliseconds delay before onMouseOut out: megaHoverOut // function = onMouseOut callback (REQUIRED) }; jQuery("ul.megamenu li .sub").css({ 'opacity': '0' }); jQuery("ul.megamenu li").hoverIntent(config); });
JavaScript
0
@@ -36,16 +36,28 @@ jQuery(%22 +ul.megamenu div.sub%22
8619fb5a57b2573afb7f55e926d0b6186d33a19f
add raven wrap
angular-raven.js
angular-raven.js
(function(module, angular, undefined) { "use strict"; module.provider('Raven', function() { var _development = null; this.development = function(config) { _development = config || _development; return this; } this.$get = ['$window', '$log', function($window, $log) { var service = { VERSION: $window.Raven.VERSION, TraceKit: $window.Raven.TraceKit, captureException: function captureException(exception, cause) { if (_development) { $log.error('Raven: Exception ', exception, cause); } else { $window.Raven.captureException(exception, cause); } }, captureMessage: function captureMessage(message, data) { if (_development) { $log.error('Raven: Message ', message, data); } else { $window.Raven.captureMessage(message, data); } }, context: function context(func) { try { func(); } catch(event) { _captureException(event); } }, setUser: function setUser(user) { if (_development) { $log.error('Raven: User ', user); } else { $window.Raven.setUser(user); } }, lastException: function lastException() { if (_development) { $log.error('Raven: Last Exception'); } else { $window.Raven.lastException(); } }, context: function(options, func, args) { var RavenService = this; if (isFunction(options)) { args = func || []; func = options; options = undefined; } return RavenService.wrap(options, func).apply(this, args); }, } }; return service; }]; // end $get }); // end provider module.factory('$exceptionHandler', ['Raven', function(Raven) { return function(exception, cause) { Raven.captureException(exception, cause); }; }]); }(angular.module('ngRaven', []), angular));
JavaScript
0.999987
@@ -1694,24 +1694,938 @@ );%0A %7D,%0A + wrap: function(options, func) %7B%0A var RavenService = this;%0A%0A if (isUndefined(func) && !isFunction(options)) %7B%0A return options;%0A %7D%0A%0A if (isFunction(options)) %7B%0A func = options;%0A options = undefined;%0A %7D%0A%0A if (!isFunction(func)) %7B%0A return func;%0A %7D%0A%0A if (func.__raven__) %7B%0A return func;%0A %7D%0A%0A function wrapped() %7B%0A var args = %5B%5D, i = arguments.length;%0A while(i--) args%5Bi%5D = Raven.wrap(options, arguments%5Bi%5D);%0A try %7B%0A return func.apply(this, args);%0A %7D catch(e) %7B%0A RavenService.captureException(e, options);%0A %7D%0A %7D%0A%0A for (var property in func) %7B%0A if (func.hasOwnProperty(property)) %7B%0A wrapped%5Bproperty%5D = func%5Bproperty%5D;%0A %7D%0A %7D%0A wrapped.__raven__ = true;%0A return wrapped;%0A %7D%0A%0A
e32518c75cfd021849138d529c024ec8bbe293df
Update createView script to include new view as export in views index.js
build/utils/createView.js
build/utils/createView.js
require('babel/register'); const fs = require('fs'); const path = require('path'); const args = require('yargs').argv; const name = args._[0]; const config = require('../../config'); const connect = !!args.connect; if (typeof name !== 'string' || !name.match(/^[A-Z]([A-Z]|[a-z])+$/)) { console.error('Missing valid view name.' + ' Ensure name starts with a capital letter and is a string,' + ' e.g. node createView.js MyView'); process.exit(9); } const dir = path.resolve(__dirname, '__templates__'); new Promise((resolve, reject) => { fs.readdir(dir, (err, files) => err ? reject(err) : resolve(files)) }).then((result) => { return new Promise((resolve) => { var fileList = [], total = result.length; result.forEach((filename) => { fs.readFile(path.resolve(dir, filename), 'utf-8', (err, data) => { if (!connect && /ViewConnect__js/.test(filename) || connect && /View__js/.test(filename)) { console.log(filename, connect); return total--; } fileList.push({fileName: filename, fileData: err || data}); if (fileList.length === total) { resolve(fileList); } }); }); }) }).then((result) => { function resolveFileName(fileName) { if (fileName.match(/^package/)) { return 'package.json'; } return name + '.' + (fileName.replace(/__/g, '.').replace(/^.+?\.(.+)\.txt$/, '$1')); } return new Promise((resolve, reject) => { result.forEach((data) => { var fileData = data.fileData.replace(/\$\{NAME\}/g, name); var fileName = resolveFileName(data.fileName); var filePath = path.resolve(config.get('utils_paths').src('views'), name, fileName); var length = result.length; var directory = path.dirname(filePath); if (!fs.existsSync(path.dirname(filePath))) { fs.mkdirSync(path.dirname(filePath)); } fs.writeFile(filePath, fileData, (err) => { if (err) { reject(err) } else if (!--length) { resolve(); } }); }) }) }).catch((err) => { console.log(err); });
JavaScript
0
@@ -17,24 +17,131 @@ egister');%0A%0A +//%0A// Modules and config%0A// -----------------------------------------------------------------------------%0A%0A const fs = r @@ -290,40 +290,189 @@ ');%0A -%0Aconst connect = !!args.connect; +const paths = config.get('utils_paths');%0A%0Aconst connect = !!args.connect;%0A%0A//%0A// Argument validation%0A// ----------------------------------------------------------------------------- %0A%0Aif @@ -715,16 +715,123 @@ (9);%0A%7D%0A%0A +//%0A// Core functionality%0A// -----------------------------------------------------------------------------%0A%0A const di @@ -1298,50 +1298,8 @@ ) %7B%0A - console.log(filename, connect);%0A @@ -1769,24 +1769,55 @@ eject) =%3E %7B%0A + var total = result.length;%0A result.f @@ -1991,33 +1991,13 @@ lve( -config.get('utils_ paths -') .src @@ -2028,88 +2028,8 @@ e);%0A - var length = result.length;%0A var directory = path.dirname(filePath);%0A @@ -2243,22 +2243,21 @@ if (!-- -length +total ) %7B%0A @@ -2345,12 +2345,424 @@ g(err);%0A + process.exit(0);%0A%7D).then(() =%3E %7B%0A return new Promise((resolve, reject) =%3E %7B%0A const file = paths.src('views/index.js');%0A fs.readFile(file, 'utf8', (err, data) =%3E %7B%0A return err ? reject(err) : resolve(%7Bfile, data%7D);%0A %7D)%0A %7D);%0A%7D).then((result) =%3E %7B%0A fs.writeFileSync(result.file, %60export %7Bdefault as $%7Bname + 'View'%7D%7D from './$%7Bname%7D';%5Cn$%7Bresult.data%7D%60);%0A%7D).catch((err) =%3E %7B%0A console.error(err);%0A %7D);%0A
f47036dc2f5654ff735762300c561a94acf0a8a1
Correct scale
src/static/js/sensor.js
src/static/js/sensor.js
$(window).load(function(){ // Place for us to stash debug info for JS console access. window.sensors = {}; // --------------------------------------------------------------------------- // Utility functions // --------------------------------------------------------------------------- function log(msg) { try{ console.log(msg); } catch (e) { // Browser doesn't support console. } } // --------------------------------------------------------------------------- // Startup. // --------------------------------------------------------------------------- function drawChart() { jQuery.getJSON("/readings", null, function(data) { log("Downloaded " + data["readings"].length + " readings"); window.sensors["data"] = data; var chartData = new google.visualization.DataTable(); chartData.addColumn('datetime', 'Date'); chartData.addColumn('number', 'Temperature/C'); var readings = data["readings"]; for (var i = 0; i < readings.length; i++) { readings[i][0] = new Date(readings[i][0]*1000); } chartData.addRows(readings); // Set chart options var options = {'title':'Temperature', 'width': 900, 'height':600, 'hAxis.format': 'MMM d HH:mm'}; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(chartData, options); }) .error(function() { log("Failed to load readings"); }); } drawChart(); });
JavaScript
0.000365
@@ -1199,16 +1199,27 @@ ions = %7B +%0A 'title': @@ -1233,27 +1233,16 @@ ature',%0A - @@ -1267,27 +1267,16 @@ - - 'height' @@ -1281,27 +1281,16 @@ t':600,%0A - @@ -1297,17 +1297,21 @@ 'hAxis -. +': %7B' format': @@ -1325,16 +1325,24 @@ HH:mm'%7D +%0A %7D ;%0A%0A
26791c88208d589dc2b74c93f4cfaf3dbb634068
switch property order for readability
client/utils/StoreMixin.js
client/utils/StoreMixin.js
var DEFAULT_CHANGE_HANDLER = 'onChange', React = require('react') var StoreMixin = { contextTypes: { getStore: React.PropTypes.func.isRequired }, /** * Registers staticly declared listeners * @method componentDidMount */ componentDidMount: function componentDidMount () { this.listeners = [] // Register static listeners this.getListeners().forEach(listener => { this._attachStoreListener(listener) }) }, /** * Gets a store instance from the context * @param {Function|String} store The store to get * @returns {Object} * @method getStore */ getStore: function getStore (store) { if (!this.context.getStore) throw new Error('getStore was called but was not found in the context') return typeof store !== 'object' ? this.context.getStore(store) : store }, /** * Gets from the context all store instances required by this component * @returns {Object} * @method getStores */ getStores: function getStores () { var storesByName = this.getListeners().reduce((accum, listener) => { accum[listener.store.constructor.storeName] = listener.store return accum }, {}) return Object.keys(storesByName).map(storeName => storesByName[storeName]) }, /** * Gets a store-change handler from the component * @param {Function|String} handler The handler to get * @returns {Function} * @method getHandler */ getHandler: function (handler) { if (typeof handler === 'string') handler = this[handler] if (!handler) throw new Error('storeListener attempted to add undefined handler') return handler }, /** * Gets a listener descriptor for a store and store-change handler * @param {Function|String} store Store * @param {Function|String} handler The handler function or method name * @returns {Object} * @method getListener */ getListener: function (store, handler) { return { store: this.getStore(store), handler: this.getHandler(handler) } }, /** * Gets all store-change listener descriptors from the component * @returns {Object} * @method getListeners */ getListeners: function () { var storeListeners = this.constructor.storeListeners // Static property on component if (!storeListeners) return [] if (Array.isArray(storeListeners)) return storeListeners.map(store => this.getListener(store, DEFAULT_CHANGE_HANDLER)) return Object.keys(storeListeners).reduce((accum, handler) => { var stores = storeListeners[handler] if (!Array.isArray(stores)) stores = [stores] return accum.concat(stores.map(store => this.getListener(store, handler))) }, []) }, /** * If provided with events, will attach listeners to events on EventEmitter objects(i.e. Stores) * If the component isn't mounted, events aren't attached. * @param {Object} listener * @param {Object} listener.store Store instance * @param {Object} listener.handler Handler function or method name * @method _attachStoreListener * @private */ _attachStoreListener: function _attachStoreListener (listener) { if (this.isMounted && !this.isMounted()) throw new Error(`storeListener mixin called listen when component wasn't mounted`) listener.store.addChangeListener(listener.handler) this.listeners.push(listener) }, /** * Removes all listeners * @method componentWillUnmount */ componentWillUnmount: function componentWillUnmount () { this.listeners.forEach((listener) => { listener.store.removeChangeListener(listener.handler) }) this.listeners = [] } } module.exports = StoreMixin
JavaScript
0
@@ -1958,21 +1958,23 @@ %7B%0A -store +handler : this.g @@ -1975,27 +1975,31 @@ this.get -Store(store +Handler(handler ),%0A @@ -1995,31 +1995,29 @@ ler),%0A -handler +store : this.getHa @@ -2014,31 +2014,27 @@ this.get -Handler(handler +Store(store )%0A %7D%0A
3a48e509a03e5b42ab7f51df1e1d0b1ea291a7e4
Fix lint
solutions/uri/1008/1008.js
solutions/uri/1008/1008.js
const input = require('fs').readFileSync('/dev/stdin', 'utf8') const [_a, _b, _c] = input .trim() .split('\n') const [a, b] = [_a, _b].map(x => parseInt(x)) const c = parseFloat(_c) console.log(`NUMBER = ${parseInt(a)}`); console.log(`SALARY = U$ ${(b * c).toFixed(2)}`);
JavaScript
0.000032
@@ -219,17 +219,16 @@ nt(a)%7D%60) -; %0Aconsole @@ -272,6 +272,5 @@ )%7D%60) -; %0A
c4d9e137a57ee18ee34b941386e61cf889046be5
Load Intl polyfill and locale data as needed. #5624
src/app/containers/Root.js
src/app/containers/Root.js
import React, { Component, PropTypes } from 'react'; import { Provider } from 'react-redux'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import ReactGA from 'react-ga'; import { IntlProvider, addLocaleData } from 'react-intl'; import App from './App'; import { IndexComponent, TermsOfService, NotFound, CreateAccount, AccessDenied, PrivacyPolicy, UserConfirmed, UserUnconfirmed } from '../components'; import { Sources, Source, User, Me } from '../components/source'; import Team from '../components/team/Team'; import { CreateProjectMedia, ProjectMedia } from '../components/media'; import TeamMembers from '../components/team/TeamMembers'; import CreateTeam from '../components/team/CreateTeam'; import JoinTeam from '../components/team/JoinTeam.js'; import Project from '../components/project/Project.js'; import ProjectHeader from '../components/project/ProjectHeader'; import ProjectEdit from '../components/project/ProjectEdit'; import Teams from '../components/team/Teams.js'; import Search from '../components/Search.js'; import CheckContext from '../CheckContext'; import translations from '../../../localization/translations/translations'; import config from 'config'; // Localization global.Intl = require('intl'); // polyfill let locale = config.locale || navigator.languages || navigator.language || navigator.userLanguage || 'en'; if (locale.constructor === Array) { locale = locale[0]; } locale = locale.replace(/[-_].*$/, ''); try { const localeData = require('react-intl/locale-data/' + locale); addLocaleData([...localeData]); } catch (e) { locale = 'en'; } export default class Root extends Component { static propTypes = { store: PropTypes.object.isRequired, }; getContext() { const context = new CheckContext(this); return context; } setStore() { const history = syncHistoryWithStore(browserHistory, this.props.store); const context = this.getContext(); const store = context.store || this.props.store; const data = { history }; if (config.pusherKey) { Pusher.logToConsole = !!config.pusherDebug; const pusher = new Pusher(config.pusherKey, { encrypted: true }); data.pusher = pusher; } context.setContextStore(data, store); this.setState(data); } componentWillMount() { this.setStore(); } componentWillUpdate() { this.setStore(); } componentDidMount() { if (config.googleAnalyticsCode) { ReactGA.initialize(config.googleAnalyticsCode, { debug: false }); } } logPageView() { if (config.googleAnalyticsCode) { ReactGA.set({ page: window.location.pathname }); ReactGA.pageview(window.location.pathname); } } render() { const { store } = this.props; window.Checkdesk = { store }; return ( <IntlProvider locale={locale} messages={translations[locale]}> <Provider store={store}> <Router history={this.state.history} onUpdate={this.logPageView.bind(this)}> <Route path="/" component={App}> <IndexRoute component={Team} /> <Route path="check/tos" component={TermsOfService} public /> <Route path="check/privacy" component={PrivacyPolicy} public /> <Route path="check/user/confirmed" component={UserConfirmed} public /> <Route path="check/user/unconfirmed" component={UserUnconfirmed} public /> <Route path="check/forbidden" component={AccessDenied} public /> <Route path="check/404" component={NotFound} public /> <Route path="check/sources" component={Sources} /> <Route path="check/sources/new" component={CreateAccount} /> <Route path="check/source/:sourceId" component={Source} /> <Route path="check/user/:userId" component={User} /> <Route path="check/me" component={Me} /> <Route path="check/teams/new" component={CreateTeam} /> <Route path="check/teams" component={Teams} /> <Route path=":team/medias/new" component={CreateProjectMedia} /> <Route path=":team/project/:projectId/media/:mediaId" component={ProjectMedia} /> <Route path=":team/join" component={JoinTeam} /> <Route path=":team/members" component={TeamMembers} /> <Route path=":team/project/:projectId" component={Project} /> <Route path=":team/project/:projectId/edit" component={ProjectEdit} /> <Route path=":team/search(/:query)" component={Search} /> <Route path=":team" component={Team} /> <Route path="*" component={NotFound} public /> </Route> </Router> </Provider> </IntlProvider> ); } } Root.contextTypes = { store: React.PropTypes.object, };
JavaScript
0
@@ -1282,51 +1282,8 @@ ion%0A -global.Intl = require('intl'); // polyfill%0A let @@ -1485,16 +1485,163 @@ /, '');%0A +%0Aif (!global.Intl) %7B%0A require(%5B'intl'%5D, function(intl)%7B%0A global.Intl = intl;%0A require('intl/locale-data/jsonp/' + locale + '.js');%0A %7D);%0A%7D%0A%0A try %7B%0A @@ -3711,38 +3711,24 @@ %7D public /%3E%0A - %0A @@ -4178,38 +4178,24 @@ =%7BTeams%7D /%3E%0A - %0A @@ -4777,30 +4777,16 @@ eam%7D /%3E%0A - %0A
9b43a839b14e943fef25b23ae240e988017c1f00
Remove duplicate teams methods from bad merge
src/app/utilities/teams.js
src/app/utilities/teams.js
import http from '../utilities/http'; export default class teams { static getAll() { return http.get(`/zebedee/teams`) .then(response => { return response.teams; }) } static get(teamName) { return http.get(`/zebedee/teams/${teamName}`) .then(response => { return response; }) } static add(teamName) { return http.post(`/zebedee/teams/${teamName}`) .then(response => { return response; }) } static remove(teamName) { return http.delete(`/zebedee/teams/${teamName}`) .then(response => { return response; }) } static add(teamName) { return http.post(`/zebedee/teams/${teamName}`) .then(response => { return response; }) } static remove(teamName) { return http.delete(`/zebedee/teams/${teamName}`) .then(response => { return response; }) } static addMember(teamName, email) { return http.post(`/zebedee/teams/${teamName}?email=${email}`) .then(response => { return response; }) } static removeMember(teamName, email) { return http.delete(`/zebedee/teams/${teamName}?email=${email}`) .then(response => { return response; }) } }
JavaScript
0.000016
@@ -734,351 +734,8 @@ %7D%0A%0A - static add(teamName) %7B%0A return http.post(%60/zebedee/teams/$%7BteamName%7D%60)%0A .then(response =%3E %7B%0A return response;%0A %7D)%0A %7D%0A%0A static remove(teamName) %7B%0A return http.delete(%60/zebedee/teams/$%7BteamName%7D%60)%0A .then(response =%3E %7B%0A return response;%0A %7D)%0A %7D%0A%0A
0096b3d35dc1c5ba58ea14e9bb3725d15bf789b6
reset passphrase
src/js/controllers/backup.js
src/js/controllers/backup.js
'use strict'; angular.module('copayApp.controllers').controller('backupController', function($rootScope, $scope, $timeout, $log, $state, $compile, go, lodash, profileService, gettext, bwcService, bwsError) { var self = this; var fc = profileService.focusedClient; var customWords = []; var mnemonic = null; function init() { resetAllButtons(); customWords = []; mnemonic = null; self.xPrivKey = null; self.step1 = true; self.step2 = false; self.step3 = false; self.step4 = false; self.deleted = false; self.credentialsEncrypted = false; self.selectComplete = false; self.backupError = false; } init(); if (fc.credentials && !fc.credentials.mnemonicEncrypted && !fc.credentials.mnemonic) self.deleted = true; if (fc.isPrivKeyEncrypted()) { self.credentialsEncrypted = true; passwordRequest(); } else setWords(getMnemonic()); function getMnemonic() { mnemonic = fc.getMnemonic(); self.xPrivKey = fc.credentials.xPrivKey; profileService.lockFC(); return mnemonic; } self.goToStep = function() { if (self.step2) { self.goToStep1(); } else if (self.step3) { self.goToStep2(); } } self.goToStep1 = function() { init(); $timeout(function() { $scope.$apply(); }, 1); } self.goToStep2 = function() { self.step1 = false; self.step2 = true; self.step3 = false; self.step4 = false; $timeout(function() { $scope.$apply(); }, 1); } self.goToStep3 = function() { if (self.mnemonicHasPassphrase) { self.step1 = false; self.step2 = false; self.step3 = true; self.step4 = false; } else { self.goToStep4(); } $timeout(function() { $scope.$apply(); }, 1); } self.goToStep4 = function() { self.confirm(); self.step1 = false; self.step2 = false; self.step3 = false; self.step4 = true; $timeout(function() { $scope.$apply(); }, 1); } function setWords(words) { if (words) { self.mnemonicWords = words.split(/[\u3000\s]+/); self.shuffledMnemonicWords = lodash.shuffle(self.mnemonicWords); self.mnemonicHasPassphrase = fc.mnemonicHasPassphrase(); self.useIdeograms = words.indexOf("\u3000") >= 0; } }; self.toggle = function() { self.error = ""; if (self.credentialsEncrypted) passwordRequest(); $timeout(function() { $scope.$apply(); }, 1); }; function passwordRequest() { try { setWords(getMnemonic()); } catch (e) { if (e.message && e.message.match(/encrypted/) && fc.isPrivKeyEncrypted()) { $timeout(function() { $scope.$apply(); }, 1); profileService.unlockFC(function(err) { if (err) { self.error = bwsError.msg(err, gettext('Could not decrypt')); $log.warn('Error decrypting credentials:', self.error); //TODO return; } self.credentialsEncrypted = false; setWords(getMnemonic()); $timeout(function() { $scope.$apply(); }, 1); }); } } } function resetAllButtons() { var node = document.getElementById('addWord'); node.innerHTML = ''; lodash.each(self.mnemonicWords, function(d) { document.getElementById(d).disabled = false; }); } self.enableButton = function(word) { document.getElementById(word).disabled = false; lodash.remove(customWords, function(v) { return v == word; }); } self.disableButton = function(word) { document.getElementById(word).disabled = true; customWords.push(word); self.addButton(word); } self.addButton = function(word) { var btnhtml = '<button class="button radius tiny words"' + 'data-ng-click="wordsC.removeButton($event)" id="_' + word + '" > ' + word + ' </button>'; var temp = $compile(btnhtml)($scope); angular.element(document.getElementById('addWord')).append(temp); self.shouldContinue(); } self.removeButton = function(event) { var id = (event.target.id); var element = document.getElementById(id); element.remove(); self.enableButton(id.substring(1)); self.shouldContinue(); } self.shouldContinue = function() { if (customWords.length == 12) self.selectComplete = true; else self.selectComplete = false; } self.confirm = function() { self.backupError = false; var walletClient = bwcService.getClient(); try { var formatedCustomWords = ''; lodash.each(customWords, function(d) { return formatedCustomWords += ' ' + d; }); var passphrase = $scope.passphrase || ''; walletClient.seedFromMnemonic(formatedCustomWords.trim(), { network: fc.credentials.network, passphrase: passphrase, account: fc.credentials.account }) if (walletClient.credentials.xPrivKey != self.xPrivKey) throw 'Private key mismatch'; } catch (err) { $log.debug('Failed to verify backup: ', err); self.backupError = true; $timeout(function() { $scope.$apply(); }, 1); return; } var words = lodash.map(mnemonic.split(' '), function(d) { return d; }); if (lodash.isEqual(words, customWords)) { $rootScope.$emit('Local/BackupDone'); } } });
JavaScript
0.000075
@@ -339,24 +339,54 @@ on init() %7B%0A + $scope.passphrase = '';%0A resetA
d01e15e4ae4b09efe0a3f9550014228c1951262f
remove extra console logging
browser/plugins/three_vr_camera.plugin.js
browser/plugins/three_vr_camera.plugin.js
(function() { var ThreeVRCameraPlugin = E2.plugins.three_vr_camera = function(core) { this.desc = 'THREE.js VR Camera' console.log("VR Camera inputs: ", this.input_slots ? this.input_slots.length : "undefined") this.defaultFOV = 20 // try to find out default fov from the device if (window.HMDVRDevice && window.HMDVRDevice.getEyeParameters) { console.log('has VR device') var eyeParams = window.HMDVRDevice.getEyeParameters() console.log(eyeParams) if (eyeParams.recommendedFieldOfView) { this.defaultFOV = eyeParams.recommendedFieldOfView console.log('has recommended FOV') } else if (eyeParams.leftDegrees && eyeParams.rightDegrees) { this.defaultFOV = eyeParams.leftDegrees + eyeParams.rightDegrees console.log('has left & right degrees') } } this.input_slots = [ { name: 'position', dt: core.datatypes.VECTOR }, { name: 'fov', dt: core.datatypes.FLOAT, def: this.defaultFOV }, { name: 'aspectRatio', dt: core.datatypes.FLOAT, def: 1.0}, { name: 'near', dt: core.datatypes.FLOAT, def: 1.0 }, { name: 'far', dt: core.datatypes.FLOAT, def: 1000.0 } ] this.output_slots = [ {name: 'camera', dt: core.datatypes.CAMERA}, {name: 'position', dt: core.datatypes.VECTOR}, {name: 'rotation', dt: core.datatypes.VECTOR} ] this.always_update = true this.dirty = false } ThreeVRCameraPlugin.prototype = Object.create(Plugin.prototype) ThreeVRCameraPlugin.prototype.reset = function() { console.log('ThreeVRCameraPlugin reset camera') this.domElement = E2.dom.webgl_canvas[0] this.perspectiveCamera = new THREE.PerspectiveCamera( this.defaultFOV, this.domElement.clientWidth / this.domElement.clientHeight, 0.1, 1000) this.controls = new THREE.VRControls(this.perspectiveCamera) } ThreeVRCameraPlugin.prototype.play = function() { this.resize() } ThreeVRCameraPlugin.prototype.resize = function() { console.log('ThreeVRCameraPlugin.resize') var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement); var wh = { width: window.innerWidth, height: window.innerHeight } if (!isFullscreen) { wh.width = this.domElement.clientWidth wh.height = this.domElement.clientHeight if (typeof(E2.app.calculateCanvasArea) !== 'undefined') wh = E2.app.calculateCanvasArea() } this.perspectiveCamera.aspect = wh.width / wh.height this.perspectiveCamera.updateProjectionMatrix() } ThreeVRCameraPlugin.prototype.update_state = function() { if (this.dirty) this.perspectiveCamera.updateProjectionMatrix() this.controls.update(this.positionFromGraph) this.updated = true } ThreeVRCameraPlugin.prototype.update_input = function(slot, data) { if (!this.perspectiveCamera) { return } switch(slot.index) { case 0: // position this.positionFromGraph = data this.perspectiveCamera.position.set(data.x, data.y, data.z) this.dirty = true break case 1: // fov this.perspectiveCamera.fov = data this.dirty = true break case 2: // aspect ratio this.perspectiveCamera.aspectRatio = data this.dirty = true break case 3: // near this.perspectiveCamera.near = data this.dirty = true break case 4: // far this.perspectiveCamera.far = data this.dirty = true break default: break } } ThreeVRCameraPlugin.prototype.update_output = function(slot) { if (slot.index === 0) { // camera return this.perspectiveCamera } else if (slot.index === 1) { // position return this.perspectiveCamera.position } else if (slot.index === 2) { // rotation var euler = new THREE.Euler().setFromQuaternion(this.perspectiveCamera.quaternion) return new THREE.Vector3(euler.x, euler.y, euler.z) } } ThreeVRCameraPlugin.prototype.state_changed = function(ui) { if (!ui) { E2.core.on('resize', this.resize.bind(this)) } } })()
JavaScript
0
@@ -119,103 +119,10 @@ ra'%0A -%0A %09%09 -console.log(%22VR Camera inputs: %22, this.input_slots ? this.input_slots.length : %22undefined%22)%0A %0A%09%09t @@ -138,17 +138,17 @@ ltFOV = -2 +9 0%0A%0A%09%09// @@ -262,40 +262,8 @@ ) %7B%0A -%09%09%09console.log('has VR device')%0A %09%09%09v @@ -318,34 +318,8 @@ rs() -%0A%09%09%09console.log(eyeParams) %0A%0A%09%09 @@ -418,47 +418,8 @@ iew%0A -%09%09%09%09console.log('has recommended FOV')%0A %09%09%09%7D @@ -555,52 +555,8 @@ ees%0A -%09%09%09%09console.log('has left & right degrees')%0A %09%09%09%7D @@ -1238,58 +1238,8 @@ ) %7B%0A -%09%09console.log('ThreeVRCameraPlugin reset camera')%0A %09%09th @@ -1569,24 +1569,24 @@ esize()%0A%09%7D%0A%0A + %09ThreeVRCame @@ -1630,53 +1630,8 @@ ) %7B%0A -%09%09console.log('ThreeVRCameraPlugin.resize')%0A%0A %09%09va
474d40f2998bbfb67a1c2f5a29880058fb3c12fe
fix url argType
src/arguments/hyperlink.js
src/arguments/hyperlink.js
const { parse } = require('url'); const { Argument } = require('klasa'); module.exports = class extends Argument { constructor(...args) { super(...args, { aliases: ['url'] }); } run(arg, possible, msg) { const res = parse(arg); const hyperlink = res.protocol && res.hostname ? hyperlink : null; if (hyperlink !== null) return hyperlink; throw (msg.language || this.client.languages.default).get('RESOLVER_INVALID_URL', possible.name); } };
JavaScript
0.998852
@@ -282,25 +282,19 @@ tname ? -hyperlink +arg : null;
618bb8da623a2271bb82ef1c2e133ac018c620ef
Change a bit of text
events/commandError.js
events/commandError.js
"use strict"; const { Event } = require("sosamba"); const { version: sosambaVersion } = require("sosamba/package.json"); const { version } = require("../package.json"); class CommandErrorEvent extends Event { constructor(...args) { super(...args, { name: "commandError" }); } async run(e, ctx) { if (e.constructor.name !== "ExtensionError") this.log.error(e); try { await ctx.send({ embed: { title: ":x: Error running the command", description: `I am unable to run the command because of a coding error:\n\`\`\`js\n${e.stack}\n\`\`\``, color: 0xFF0000, footer: { text: `Please tell the command developers about this. | tt.bot v${version} running on Sosamba v${sosambaVersion}` } } }); } catch {} } } module.exports = CommandErrorEvent;
JavaScript
0.999999
@@ -764,46 +764,60 @@ ase -tell the command developers about this +report this issue on our support server or on GitHub . %7C