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
9c840f23f2e6f74fab22c24f4f3814782fae2e78
Simplify Clip.play() since offset always given.
ncph.js
ncph.js
// Copyright (C) 2016 ncph Authors // This file is free software: You can redistribute it and/or modify it under // the terms of the GNU AGPLv3 or later. See COPYING for details. // Implementation of the Fischer-Yates-Durstenfeld O(n) shuffle algorithm. This // variant is non-destructive (does not modify the input array), and takes the // random number generator as a parameter, for deterministic operation. // // https://en.wikipedia.org/wiki/Fisher-Yates_shuffle // function shuffle(orig, rng) { arr = orig.slice(0); for (var i = arr.length - 1; i > 0; i--) { var j = Math.floor(rng.gen() * (i + 1)); var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } return arr; } // Implementation of a simple linear congruential generator, using the // parameters from Teukolsky-Vetterling-Flannery's Numerical Recipes. // // https://en.wikipedia.org/wiki/Linear_congruential_generator // function Lcg32(seed) { this.state = (seed + 0xad2158e3) % 0x100000000; this.advance(); this.advance(); this.advance(); this.advance(); } Lcg32.prototype.advance = function() { this.state = (this.state * 1664525 + 1013904223) % 0x100000000; }; Lcg32.prototype.gen = function() { this.advance(); return this.state / 0x100000000; }; var vid = document.getElementById('vid'); var vidCounter = 0; var clipDuration = 60000; function Clip(name) { this.name = name; } Clip.prototype.path = function() { return 'clips/opt/' + this.name + '.mp4'; }; Clip.prototype.play = function(offset) { if (this.cached !== undefined) { vid.src = this.cached; } else { if (offset === undefined) { vid.src = this.path(); } else { vid.src = this.path() + "#t=" + offset / 1000; } } vid.play(); ++vidCounter; }; Clip.prototype.preload = function() { if (this.cached === undefined) { var req = new XMLHttpRequest(); req.open('GET', this.path(), true); req.responseType = 'blob'; req.onload = function() { if (this.status === 200) { this.cached = URL.createObjectURL(this.response); } }; req.send(); } }; var clips = [ new Clip('wicker-notthebees'), new Clip('zandalee-inevitable'), new Clip('firebirds-kiss'), new Clip('therock-gottago'), new Clip('driveangry-disrobe'), new Clip('faceoff-hallelujah'), new Clip('wildheart-sing'), new Clip('corelli-sing'), new Clip('leavinglas-meet'), new Clip('gone60s-letsride'), new Clip('8mm-becausehecould'), new Clip('adaptation-narcissistic'), ]; // Get the permutation of clips for a given run. // // This computes a sequence such that the clips are always played in an order // that appears random to humans, which very rarely should show a clip more than // once in a single sitting. // // The sequence is first permuted using the runblock (blocks of 100 runs) as the // seed, then split into groups of 6, and each group is permuted again using // the run as the seed. // // By maintaing distinct groups within a runblock, seeing the same clip twice in // a single sitting is only possible when straddling runblocks. Permuting groups // as well adds variation between sequential runs. Within a runblock, the // minimum spacing between two screenings of the same clip is N-6, where N is // the total number of clips. // function getSequence(run) { var runBlock = Math.floor(run / 100); var permuted = shuffle(clips, new Lcg32(runBlock)); var rng2 = new Lcg32(run); var permuted2 = []; for (var i = 0; i < permuted.length; i += 6) { var group = permuted.slice(i, i + 6); var shuffled = shuffle(group, rng2); permuted2 = permuted2.concat(shuffled); } return permuted2; } // Get the current clip from a timestamp. function getClip(ts) { var total = Math.floor(ts / clipDuration); var run = Math.floor(total / clips.length); var clip = total % clips.length; var seq = getSequence(run); return seq[clip]; } // Scheduler to be run every clipDuration milliseconds. function scheduleVid(timestamp, offset) { var nextTimestamp = timestamp + clipDuration; window.setTimeout(scheduleVid, clipDuration - offset, nextTimestamp, 0); getClip(timestamp).play(offset); getClip(nextTimestamp).preload(); } // Run this event at startup. window.onload = function() { var timestamp = Date.now(); var rounded = Math.floor(timestamp / clipDuration) * clipDuration; var offset = timestamp % clipDuration; scheduleVid(rounded, offset); }; // Register keyboard event handler. window.addEventListener('keydown', function(event) { switch (event.key) { case 'ArrowDown': vid.volume = Math.max(0.0, vid.volume - 0.05); break; case 'ArrowUp': vid.volume = Math.min(1.0, vid.volume + 0.05); break; default: return; } });
JavaScript
0
@@ -1577,84 +1577,8 @@ e %7B%0A - if (offset === undefined) %7B%0A vid.src = this.path();%0A %7D else %7B%0A @@ -1624,22 +1624,16 @@ / 1000;%0A - %7D%0A %7D%0A vi
f05eedc88b63cbf52d01eca1ab77996194a6e902
Add a few more triggers.
nope.js
nope.js
~function() { var WRITE_LIFECYCLE_MODE = "write"; var knownLifecycleModes = [ "read", WRITE_LIFECYCLE_MODE ]; var lifecycleMode = WRITE_LIFECYCLE_MODE; define(HTMLDocument.prototype, 'write', nope); define(HTMLDocument.prototype, 'writeln', nope); define(HTMLDocument.prototype, 'open', nope); define(HTMLDocument.prototype, 'close', nope); var layoutTriggers = { 'HTMLDocument': { 'getter': [ 'scrollingElement', ], 'method': [ 'execCommand', ] }, 'Element': { 'method': [ 'scrollIntoView', 'scrollBy', // experimental 'scrollTo', // experimental 'getClientRect', 'getBoundingClientRect', 'computedRole', // experimental 'computedName', // experimental 'focus', ], 'getter': [ 'offsetLeft', 'offsetTop', 'offsetWidth', 'offsetHeight', 'offsetParent', 'clientLeft', 'clientWidth', 'clientHeight', 'scrollLeft', 'scrollTop', 'scrollWidth', 'scrollHeight', 'innerText', 'outerText', ], 'setter': [ 'scrollLeft', 'scrollTop', ], }, 'HTMLButtonElement': { 'method': [ 'reportValidity', ] }, 'HTMLFieldSetElement': { 'method': [ 'reportValidity', ] }, 'HTMLInputElement': { 'method': [ 'reportValidity', ] }, 'HTMLButtonElement': { 'method': [ 'reportValidity', ] }, 'HTMLKeygenElement': { 'method': [ 'reportValidity', ] }, 'CSSStyleDeclaration': { 'method': [ 'getPropertyValue', ] } } redefineGetter(HTMLElement.prototype, 'offsetLeft', synthesizeNopeWhenWriting); function nope() { throw new Error('nope'); } function synthesizeNopeWhenWriting(func) { return function() { if (lifecycleMode != WRITE_LIFECYCLE_MODE) { return func.apply(this, arguments); } throw new Error('nope'); } } define(HTMLDocument.prototype, 'setLifecycleMode', function(mode) { if (knownLifecycleModes.indexOf(mode) == -1) { throw new Error(`Unknown lifecycle mode. The known modes are: ${knownLifecycleModes}.`); return; } lifecycleMode = mode; }); function redefineGetter(prot, key, getterSynthesizer) { var descriptor = Object.getOwnPropertyDescriptor(prot, key); if (!descriptor || !descriptor.get) throw new Error(`Unable to redefine getter ${key} on prototype ${prot}.`); descriptor.get = getterSynthesizer(descriptor.get); Object.defineProperty(prot, key, descriptor); } function define(prot, key, func) { Object.defineProperty(prot, key, { value: func, writable: true, configurable: true, enumerable: true }); } }();
JavaScript
0
@@ -1125,24 +1125,232 @@ %5D,%0A %7D,%0A + 'Range': %7B%0A 'method': %5B%0A 'getClientRects',%0A 'getBoundingClientRect',%0A %5D,%0A %7D,%0A 'MouseEvent': %7B%0A 'getter': %5B%0A 'layerX',%0A 'layerY',%0A 'offsetX',%0A 'offsetY',%0A %5D,%0A %7D,%0A 'HTMLButto @@ -1409,24 +1409,95 @@ %0A %5D%0A %7D,%0A + 'HTMLDialogElement': %7B%0A 'method': %5B%0A 'showModal',%0A %5D%0A %7D,%0A 'HTMLField @@ -1558,24 +1558,128 @@ %0A %5D%0A %7D,%0A + 'HTMLImageElement': %7B%0A 'getter': %5B%0A 'width',%0A 'height',%0A 'x',%0A 'y',%0A %5D%0A %7D,%0A 'HTMLInput @@ -1968,16 +1968,314 @@ ,%0A %5D%0A + %7D,%0A 'Window': %7B%0A 'method': %5B%0A 'scrollBy',%0A 'scrollTo',%0A %5D%0A %7D,%0A 'SVGSVGElement': %7B%0A 'setter': %5B%0A 'currentScale',%0A %5D%0A %7D,%0A '@window': %7B // should these stay on instance?%0A 'getter': %5B%0A 'innerHeight',%0A 'innerWidth',%0A 'scrollX',%0A 'scrollY',%0A %5D%0A %7D%0A%7D%0A%0Ar
de5b9fc0e83a810097014387f1d7a128ba469a3f
use node-notify-send instead of doing it myself
alert.js
alert.js
#!/usr/bin/env node // generally the idea is: // 1: create stream // 2: wait for push tickle // 3: fetch updates since the last time we checked var Pushbullet = require('pushbullet'), pusher = new Pushbullet(process.env.ALERT_PUSH_API), stream= pusher.stream(), time = new Date().getTime() / 1000, exec = require('child_process').exec, _sq ='\'', _esq='\\\'', me; // turn a push into something usable by notify-send here var processResponse = function (msg) { var ret = {}; // assign notification subject based on type if (msg.type === 'address') { ret.subject = msg.name; } else ret.subject = msg.type == 'file' ? msg.file_name : msg.title; // double check if (!ret.subject) ret.subject = 'New Push'; // create notification body ret.body = ''; if (msg.type === 'address') ret.body = msg.address; else if (msg.type === 'file') ret.body = msg.file_url; else if (msg.type === 'note') ret.body = msg.body; else if (msg.type === 'link') ret.body = msg.url + (msg.body ? '\n' + msg.body : ''); else if (msg.type === 'list') { msg.items.forEach(function(elem) { ret.body += elem.text + '\n'; }); } // double check if (!ret.body) ret.body = ''; // escape double quotes. we'll surround the whole thing back in doAlert ret.subject = ret.subject.replace(_dq, _edq); ret.body = ret.body.replace(_dq, _edq); return ret; }; // this will eventually do the actual alerting. // it gets the response from the fetched updates and creates alert // also, importantly, updates the time since we last got an update var doAlert = function(err, resp){ if(err) { console.err(err); return; } // variable to hold just the newest push var newest = resp.pushes[0]; // update time to be the created time of the latest push time = newest.modified; // only interested in the newest, non-dismissed push for now if((newest.receiver_iden === me.iden) && (newest.dismissed === false)){ var notif = processResponse(newest); var cmd = 'notify-send -u normal -t 10000 "' + notif.subject + '" "' + notif.body + '"'; var child = exec(cmd, function(err, stdout, stderr) { if (err) console.error(err); }); } }; // function to fetch new data. Uses the creation timestamp from // last message (or start of program) var refresh = function() { console.log('Received tickler. Fetching messages after ' + time); var options = { limit: 5, modified_after: time }; pusher.history(options, doAlert); }; // on connect var connect = function() { console.log('Connected!'); }; // on close var close = function () { console.log('Connection closed'); // may want to try to restart here? // alternatively, if daemonized, may kick itself back off? process.exit(); }; // when we get a tickle, // check if it's a push type, // if so, fetch new pushes var tickle = function(type) { if ( type === 'push') refresh(); }; // close the stream and quit var error = function (err) { console.error(err); stream.close(); }; // function to gracefully shutdown var exit = function () { console.log('Received interrupt. Exiting.'); stream.close(); }; // event handlers stream.on('connect', connect); stream.on('close', close); stream.on('tickle', tickle); stream.on('error', error); // catch SIGNALS so we can gracefully exit process.on('SIGHUP', exit); process.on('SIGTERM', exit); process.on('SIGINT', exit); // start by grabbing our own information pusher.me(function(err, resp) { if(err){ console.error(err); process.exit(1); } me = resp; // connect to websocket stream stream.connect(); });
JavaScript
0
@@ -324,20 +324,24 @@ 00,%0A -exec +notifier = requi @@ -348,56 +348,42 @@ re(' -child_process').exec,%0A _sq ='%5C'', _esq='%5C%5C%5C'' +notify-send').normal.timeout(5000) ,%0A @@ -1061,19 +1061,20 @@ y = +( msg. -url + ( +body ? msg. @@ -1082,31 +1082,30 @@ ody -? ++ '%5Cn' +: '') + msg. -body : '') +url ;%0A @@ -1297,178 +1297,8 @@ ';%0A%0A - // escape double quotes. we'll surround the whole thing back in doAlert%0A ret.subject = ret.subject.replace(_dq, _edq);%0A ret.body = ret.body.replace(_dq, _edq);%0A @@ -1960,226 +1960,49 @@ -var cmd = 'notify-send -u normal -t 10000 %22' +%0A notif.subject + '%22 %22' +%0A notif.body + '%22';%0A%0A var child = exec(cmd, function(err, stdout, stderr) %7B%0A if (err) console.error(err);%0A %7D +notifier.notify(notif.subject, notif.body );%0A
459bcd5a7d22f7634113f0d2012e37030bd48b33
Update SPAControllers.js
App/Controllers/SPAControllers.js
App/Controllers/SPAControllers.js
// TODO: add here AngularJS Module
JavaScript
0
@@ -1,35 +1,2307 @@ -// TODO: add here AngularJS Module +var oOrchidsApp = angular.module('OrchidsApp', %5B'ngRoute'%5D);%0A%0AoOrchidsApp.config(%5B'$routeProvider', function ($routeProvider) %7B%0A%0A $routeProvider%0A%0A .when('/',%0A %7B%0A templateUrl: %22/App/Views/OrchidsList.html%22,%0A controller: %22OrchidsAllCtl%22%0A %7D)%0A .when('/add',%0A %7B%0A templateUrl: %22/App/Views/OrchidsAdd.html%22,%0A controller: %22OrchidsAddCtl%22%0A %7D)%0A .otherwise(%7B redirectTo: %22/%22 %7D);%0A%0A%7D%5D);%0A%0AoOrchidsApp.controller('OrchidsAllCtl', %5B'$scope', '$http', '$log', function ($scope, $http, $log) %7B%0A%0A $scope.angularClass = %22angular%22;%0A $scope.OrchidsList = %5B%5D;%0A $scope.pageSize = 2;%0A var iCurrentPage = -1;%0A %0A%0A $scope.fnShowOrchids = function (direction) %7B%0A%0A iCurrentPage = iCurrentPage + direction;%0A iCurrentPage = iCurrentPage %3E= 0 ? iCurrentPage : 0;%0A%0A var sURL = %22http://carmelwebapi.somee.com/WebAPI/OrchidsWebAPI/%22 +%0A %22?$skip=%22 +%0A iCurrentPage * $scope.pageSize%0A + %22&$top=%22 +%0A $scope.pageSize;%0A%0A%0A $http.get(sURL).success(function (response) %7B%0A%0A $scope.OrchidsList = response;%0A $log.info(%22OK%22);%0A%0A %7D,%0A function (err) %7B $log.error(err) %7D%0A )%0A %7D%0A%0A $scope.fnShowOrchids(1);%0A%0A%0A%7D%0A%5D);%0A%0AoOrchidsApp.controller('OrchidsAddCtl', %0A %5B'$http', '$scope', '$location', '$log', %0A function ($http, $scope, $location, $log) %7B%0A%0A $scope.Flowers = %5B%22haeckel_orchidae%22, %22Bulbophyllum%22, %22Cattleya%22, %0A %22Orchid Calypso%22, %22Paphiopedilum_concolor%22, %0A %22Peristeria%22, %22Phalaenopsis_amboinensis%22, %22Sobralia%22%5D;%0A%0A $scope.fnAdd = function () %7B%0A%0A var oFlower = %7B %22Title%22: $scope.Orchid.Title, %0A %22Text%22: $scope.Orchid.Text, %0A %22MainPicture%22: $scope.Orchid.MainPicture + '.jpg' %0A %7D;%0A %0A%0A $http(%7B%0A url: 'http://carmelwebapi.somee.com/WebAPI/OrchidsWebAPI/',%0A method: %22POST%22,%0A data: oFlower,%0A headers: %7B 'Content-Type': 'application/json' %7D%0A %7D).success(function (data) %7B %0A $scope.msg = %22New Orchid saved%22;%0A %7D).error(function (err) %7B%0A $log.log(err);%0A %7D);%0A%0A %7D%0A%7D%0A%5D); %0A
7e04b0e810ab5caf058a30e2f8f9b7666d17fabd
Fix the file header for the styleguide options file
Build/Grunt-Options/styleguide.js
Build/Grunt-Options/styleguide.js
/** * Grunt-Contrib-Clean * @description Cleans files and folders. * @docs https://github.com/gruntjs/grunt-contrib-clean */ var config = require("../Config"); module.exports = { options: { template: { src: 'Documentation/Private/Template' }, framework: { name: 'kss' } }, all: { files: [{ 'Documentation': config.Sass.sassDir + "/**/*.scss" }] } };
JavaScript
0
@@ -10,21 +10,18 @@ unt- -Contrib-Clean +Styleguide %0A * @@ -37,89 +37,203 @@ ion -Cleans files and folders.%0A * @docs https://github.com/gruntjs/grunt-contrib-clean +Universal CSS styleguide generator for grunt. Easily integrate Styledocco or KSS styleguide generation into your development workflow.%0A * @docs https://github.com/indieisaconcept/grunt-styleguide %0A */
9c3b3bec9c0a4d73ef384e9bdfeab012d7740a84
Fix test
routes/authenticated.js
routes/authenticated.js
module.exports = [ { // shortcut for viewing your own stars path: "/star", method: "GET", handler: require('../handlers/star'), }, { paths: [ "/~", "/profile", ], method: "GET", handler: require('../facets/user/show-profile') }, { path: "/profile-edit", method: "GET", handler: require('../facets/user/show-profile-edit') }, { path: "/profile-edit", method: "PUT", handler: require('../facets/user/show-profile-edit') }, { path: "/profile-edit", method: "POST", handler: require('../facets/user/show-profile-edit') }, { path: "/resend-email-confirmation", method: "GET", handler: require('../facets/user/show-resend-email-confirmation') }, { path: "/email-edit", method: "GET", handler: require('../facets/user/show-email-edit') }, { path: "/email-edit", method: "PUT", handler: require('../facets/user/show-email-edit') }, { path: "/email-edit", method: "POST", handler: require('../facets/user/show-email-edit') }, { // confirm or revert // /email-edit/confirm/1234567 // /email-edit/revert/1234567 path: "/email-edit/{token*2}", method: "GET", handler: require('../facets/user/show-email-edit') }, { path: "/password", method: "GET", handler: require('../facets/user/show-password') }, { path: "/password", method: "POST", handler: require('../facets/user/show-password') }, { path: "/settings/billing", method: "GET", handler: require('../handlers/customer').getBillingInfo }, { path: "/settings/billing", method: "POST", handler: require('../handlers/customer').updateBillingInfo }, { path: "/settings/billing/cancel", method: "POST", handler: require('../handlers/customer').deleteBillingInfo }, { path: "/settings/billing/subscribe", method: "POST", handler: require('../handlers/customer').subscribe }, { paths: [ "/package/{package}/collaborators", "/package/{scope}/{project}/collaborators", ], method: "PUT", handler: require('../handlers/collaborator').add }, { paths: [ "/package/{package}/collaborators/{username}", "/package/{scope}/{project}/collaborators/{username}", ], method: "POST", handler: require('../handlers/collaborator').update }, { paths: [ "/package/{package}/collaborators/{username}", "/package/{scope}/{project}/collaborators/{username}", ], method: "DELETE", handler: require('../handlers/collaborator').del }, { path: "/package/{scope}/{project}", method: "POST", handler: require('../handlers/package').update },{ path: "/org", method: "GET", handler: require('../facets/user/show-orgs') },{ path: "/org/{org}", method: "GET", handler: require('../handlers/org').getOrg },{ path: "/org/{org}", method: "POST", handler: require('../handlers/customer').updateOrg },{ path: "/org/create", method: "GET", handler: function (request, reply) { return reply.view('org/create'); } } ];
JavaScript
0.000004
@@ -2990,32 +2990,134 @@ updateOrg%0A %7D,%7B%0A + path: %22/org/%7Borg%7D%22,%0A method: %22DELETE%22,%0A handler: require('../handlers/org').deleteOrg%0A %7D,%7B%0A path: %22/org/
a1e4b77163a59c41ff9b320be44862f51949b8c2
add data
routes/views/contact.js
routes/views/contact.js
var keystone = require('keystone'), Enquiry = keystone.list('Enquiry'); Navbar = keystone.list('Navbar'), MenuList = keystone.list('Menu'), FooterList = keystone.list('Footer'), CompanyInfoListMenu = keystone.list('CompanyInfoListMenu'), exports = module.exports = function(req, res) { var view = new keystone.View(req, res), locals = res.locals; locals.section = 'contact'; locals.enquiryTypes = Enquiry.fields.enquiryType.ops; locals.formData = req.body || {}; locals.validationErrors = {}; locals.enquirySubmitted = false; view.on('post', { action: 'contact' }, function(next) { var application = new Enquiry.model(), updater = application.getUpdateHandler(req); updater.process(req.body, { flashErrors: true }, function(err) { if (err) { locals.validationErrors = err.errors; } else { locals.enquirySubmitted = true; } next(); }); }); // Load the current Navbar view.on('init', function(next) { var q = Navbar.model.find(); q.exec(function(err, results) { locals.data.navbars = results; next(err); }); }); // Load the current MenuList view.on('init', function(next) { var q = MenuList.model.find(); q.exec(function(err, results) { locals.data.menus = results; next(err); }); }); // Load the current FooterList view.on('init', function(next) { var q = FooterList.model.find(); q.exec(function(err, results) { locals.data.footers = results; next(err); }); }); // Load the current CompanyInfoListMenu view.on('init', function(next) { var q = CompanyInfoListMenu.model.find(); q.exec(function(err, results) { locals.data.companyinfolistmenus = results; next(err); }); }); view.render('contact', { section: 'contact', }); }
JavaScript
0.000819
@@ -909,808 +909,8 @@ ;%0A%0A%09 -// Load the current Navbar%0A%09view.on('init', function(next) %7B%0A%09%09var q = Navbar.model.find();%0A%09%09q.exec(function(err, results) %7B%0A%09%09%09locals.data.navbars = results;%0A%09%09%09next(err);%0A%09%09%7D);%0A%09%7D);%0A%0A%09// Load the current MenuList%0A%09view.on('init', function(next) %7B%0A%09%09var q = MenuList.model.find();%0A%09%09q.exec(function(err, results) %7B%0A %09%09%09locals.data.menus = results;%0A%09%09%09next(err);%0A%09%09%7D);%0A%09%7D);%0A%0A%09// Load the current FooterList%0A%09view.on('init', function(next) %7B%0A%09%09var q = FooterList.model.find();%0A%09%09q.exec(function(err, results) %7B%0A %09%09%09locals.data.footers = results;%0A%09%09%09next(err);%0A%09%09%7D);%0A%09%7D);%0A%0A%09// Load the current CompanyInfoListMenu%0A%09view.on('init', function(next) %7B%0A%09%09var q = CompanyInfoListMenu.model.find();%0A%09%09q.exec(function(err, results) %7B%0A%09%09%09locals.data.companyinfolistmenus = results;%0A%09%09%09next(err);%0A%09%09%7D);%0A%09%7D); %0A%0A%09%0A
46916f84ec7023af894b2b3230ed9d888fa4ba1f
Fix quickAlgo final test rerun
quickAlgo/taskPlatformAdapter.js
quickAlgo/taskPlatformAdapter.js
var taskPlatformAdapterPlatform = { validate: function(mode, success, error) { $('#validateOk').show(); }, getTaskParams: function(key, defaultValue, success, error) { var res = {'minScore': 0, 'maxScore': 100, 'noScore': 0, 'readOnly': true, 'randomSeed': "0", 'options': {}}; // TODO :: randomSeed if(key && key in res) { res = res[key]; } else if(key) { res = defaultValue; } if(success) { success(res); } else { return res; }}, askHint: function(hint, success, error) { success(); }, updateDisplay: function(params, success, error) { success(); } }; platform.setPlatform(taskPlatformAdapterPlatform); $(function () { task.load(null, function () { var source = window.parent.adapterApi.getSource(); task.reloadAnswerObject({'easy': [{'blockly': source.sourceCode}]}); setTimeout(function() { $('.contentCentered').hide(); $('#submitBtn').hide(); $('#displayHelperAnswering').hide(); }, 0); }); var updateHeight = null; updateHeight = function() { window.parent.adapterApi.setHeight($('body').outerHeight(true)); setTimeout(updateHeight, 1000); }; updateHeight(); setTimeout(function() { task.displayedSubTask.getGrade(function(results) { if(results.successRate >= 1) { $('#success').show(); window.parent.adapterApi.displayPopup(); } task.displayedSubTask.run(); }, true); }, 1000); }); if(window.Blockly) { Blockly.JavaScript['input_num'] = function(block) { Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n" + "function readStdin() {\n" + " if (stdinBuffer == '')\n" + " return input();\n" + " if (typeof stdinBuffer === 'undefined')\n" + " stdinBuffer = '';\n" + " return stdinBuffer;\n" + "};"; var code = 'parseInt(readStdin())'; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript['input_num_next'] = function(block) { Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n" + "function readStdin() {\n" + " if (stdinBuffer == '')\n" + " return input();\n" + " if (typeof stdinBuffer === 'undefined')\n" + " stdinBuffer = '';\n" + " return stdinBuffer;\n" + "};"; Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n" + " while (!stdinBuffer || stdinBuffer.trim() == '')\n" + " stdinBuffer = readStdin();\n" + " if (typeof stdinBuffer === 'undefined')\n" + " stdinBuffer = '';\n" + " var re = /\\S+\\s*/;\n" + " var w = re.exec(stdinBuffer);\n" + " stdinBuffer = stdinBuffer.substr(w[0].length);\n" + " return w[0];\n" + "};"; var code = 'parseInt(input_word())'; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript['input_char'] = function(block) { Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n" + "function readStdin() {\n" + " if (stdinBuffer == '')\n" + " return input();\n" + " if (typeof stdinBuffer === 'undefined')\n" + " stdinBuffer = '';\n" + " return stdinBuffer;\n" + "};"; Blockly.JavaScript.definitions_['input_char'] = "function input_char() {\n" + " var buf = readStdin();\n"; + " stdinBuffer = buf.substr(1);\n"; + " return buf.substr(0, 1);\n"; + "};\n"; var code = 'input_char()'; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript['input_word'] = function(block) { Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n" + "function readStdin() {\n" + " if (stdinBuffer == '')\n" + " return input();\n" + " if (typeof stdinBuffer === 'undefined')\n" + " stdinBuffer = '';\n" + " return stdinBuffer;\n" + "};"; Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n" + " while (!stdinBuffer || stdinBuffer.trim() == '')\n" + " stdinBuffer = readStdin();\n" + " if (typeof stdinBuffer === 'undefined')\n" + " stdinBuffer = '';\n" + " var re = /\\S+\\s*/;\n" + " var w = re.exec(stdinBuffer);\n" + " stdinBuffer = stdinBuffer.substr(w[0].length);\n" + " return w[0];\n" + "};"; var code = 'input_word()'; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript['input_line'] = function(block) { Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n" + "function readStdin() {\n" + " if (stdinBuffer == '')\n" + " return input();\n" + " if (typeof stdinBuffer === 'undefined')\n" + " stdinBuffer = '';\n" + " return stdinBuffer;\n" + "};"; var code = 'readStdin()'; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript['input_num_list'] = function(block) { Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n" + "function readStdin() {\n" + " if (stdinBuffer == '')\n" + " return input();\n" + " if (typeof stdinBuffer === 'undefined')\n" + " stdinBuffer = '';\n" + " return stdinBuffer;\n" + "};"; Blockly.JavaScript.definitions_['input_num_list'] = "function input_num_list() {\n" + " var parts = readStdin().split(/\\s+/);\n" + " for(var i=0; i<parts.length; i++) {\n" + " parts[i] = parseInt(parts[i]);\n" + " }\n" + " return parts;\n" + "};"; var code = 'input_num_list()'; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript['text_print'] = function(block) { return "print(" + (Blockly.JavaScript.valueToCode(block, "TEXT", Blockly.JavaScript.ORDER_NONE) || "''") + ");\n"; }; Blockly.JavaScript['text_print_noend'] = function(block) { return "print(" + (Blockly.JavaScript.valueToCode(block, "TEXT", Blockly.JavaScript.ORDER_NONE) || "''") + ", '');\n"; }; }
JavaScript
0.000002
@@ -1641,34 +1641,108 @@ -task.displayedSubTask.run( +setTimeout(function() %7B%0A task.displayedSubTask.run();%0A %7D, 1000 );%0A
a0e0f9b17ca713650526249b59d14587b8d1bfb3
Fix module paths in unloading code in bootstrap.js.
recipe-client-addon/bootstrap.js
recipe-client-addon/bootstrap.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; const {utils: Cu} = Components; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "LogManager", "resource://shield-recipe-client/lib/LogManager.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "ShieldRecipeClient", "resource://shield-recipe-client/lib/ShieldRecipeClient.jsm"); this.install = function() {}; this.startup = async function() { await ShieldRecipeClient.startup(); }; this.shutdown = function(data, reason) { ShieldRecipeClient.shutdown(reason); // Unload add-on modules. We don't do this in ShieldRecipeClient so that // modules are not unloaded accidentally during tests. const log = LogManager.getLogger("bootstrap"); const modules = [ "content/AboutPages.jsm", "lib/ActionSandboxManager.jsm", "lib/CleanupManager.jsm", "lib/ClientEnvironment.jsm", "lib/FilterExpressions.jsm", "lib/EventEmitter.jsm", "lib/Heartbeat.jsm", "lib/LogManager.jsm", "lib/NormandyApi.jsm", "lib/NormandyDriver.jsm", "lib/PreferenceExperiments.jsm", "lib/RecipeRunner.jsm", "lib/Sampling.jsm", "lib/SandboxManager.jsm", "lib/ShieldRecipeClient.jsm", "lib/Storage.jsm", "lib/StudyStorage.jsm", "lib/Uptake.jsm", "lib/Utils.jsm", "vendor/mozjexl.js", ]; for (const module of modules) { log.debug(`Unloading ${module}`); Cu.unload(`resource://shield-recipe-client/${module}`); } }; this.uninstall = function() {};
JavaScript
0
@@ -908,20 +908,18 @@ ap%22);%0A -cons +le t module @@ -928,38 +928,8 @@ = %5B%0A - %22content/AboutPages.jsm%22,%0A @@ -1467,17 +1467,181 @@ js%22,%0A %5D -; +.map(m =%3E %60resource://shield-recipe-client/$%7Bm%7D%60);%0A modules = modules.concat(%5B%0A %22AboutPages.jsm%22,%0A %5D.map(m =%3E %60resource://shield-recipe-client-content/$%7Bm%7D%60));%0A %0A for ( @@ -1723,51 +1723,14 @@ oad( -%60resource://shield-recipe-client/$%7B module -%7D%60 );%0A
4f27802ef185b4410cb4cb612bb7b8d852eac8ce
optimize Guide
src/Guide/Guide.js
src/Guide/Guide.js
/** * @file Guide component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import TriggerPop from '../_TriggerPop'; import AnchorButton from '../AnchorButton'; import Position from '../_statics/Position'; import MsgType from '../_statics/MsgType'; import Util from '../_vendors/Util'; import PopManagement from '../_vendors/PopManagement'; class Guide extends Component { static Position = Position; static Type = MsgType; constructor(props, ...restArgs) { super(props, ...restArgs); } /** * public */ resetPosition = () => { this.refs.guide && this.refs.guide.resetPosition(); }; getIconCls = () => { switch (this.props.type) { case MsgType.SUCCESS: return 'fas fa-check-circle'; case MsgType.WARNING: return 'fas fa-exclamation-triangle'; case MsgType.ERROR: return 'fas fa-times-circle'; default: return 'fas fa-info-circle'; } }; renderHandler = (...args) => { PopManagement.push(this); const {onRender} = this.props; onRender && onRender(...args); }; destroyHandler = (...args) => { PopManagement.pop(this); const {onDestroy} = this.props; onDestroy && onDestroy(...args); }; componentWillUnmount() { PopManagement.pop(this); } render() { const { className, contentClassName, type, iconVisible, iconCls, closeButtonVisible, closeButtonValue, children, onRequestClose,parentEl, ...restProps } = this.props, guideClassName = classNames('guide', { 'icon-hidden': !iconVisible, [className]: className }), guideContentClassName = classNames('guide-content', { 'theme-default': type === MsgType.DEFAULT, [`theme-${type}`]: type !== MsgType.DEFAULT, [contentClassName]: contentClassName }); return ( <TriggerPop {...restProps} ref="guide" parentEl={parentEl} className={guideClassName} contentClassName={guideContentClassName} onRender={this.renderHandler} onDestroy={this.destroyHandler}> { !iconVisible || type === MsgType.DEFAULT ? null : <i className={classNames(iconCls ? iconCls : this.getIconCls(), 'guide-icon')}></i> } <div className="guide-message"> {children} { closeButtonVisible ? <AnchorButton className="guide-close-Button" value={closeButtonValue} onClick={onRequestClose}/> : null } </div> </TriggerPop> ); } } Guide.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * The CSS class name of the content element. */ contentClassName: PropTypes.string, modalClassName: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The type of notification. */ type: PropTypes.oneOf(Util.enumerateValue(MsgType)), parentEl: PropTypes.object, /** * This is the DOM element that will be used to set the position of the popover. */ triggerEl: PropTypes.object, /** * If true,the popover is visible. */ visible: PropTypes.bool, /** * If true,the popover will have a triangle on the top of the DOM element. */ hasTriangle: PropTypes.bool, triangle: PropTypes.element, /** * The guide alignment. */ position: PropTypes.oneOf(Util.enumerateValue(Position)), iconVisible: PropTypes.bool, iconCls: PropTypes.string, /** * If true,guide will have animation effects. */ isAnimated: PropTypes.bool, /** * The depth of Paper component. */ depth: PropTypes.number, isBlurClose: PropTypes.bool, isEscClose: PropTypes.bool, shouldPreventContainerScroll: PropTypes.bool, isTriggerPositionFixed: PropTypes.bool, resetPositionWait: PropTypes.number, showModal: PropTypes.bool, closeButtonVisible: PropTypes.bool, closeButtonValue: PropTypes.string, /** * The function of guide render. */ onRender: PropTypes.func, /** * The function of guide rendered. */ onRendered: PropTypes.func, /** * The function of guide destroy. */ onDestroy: PropTypes.func, /** * The function of guide destroyed. */ onDestroyed: PropTypes.func, /** * Callback function fired when the popover is requested to be closed. */ onRequestClose: PropTypes.func, /** * Callback function fired when wrapper wheeled. */ onWheel: PropTypes.func }; Guide.defaultProps = { parentEl: document.body, type: MsgType.INFO, visible: false, hasTriangle: true, position: Position.BOTTOM, isAnimated: true, iconVisible: true, isBlurClose: true, isEscClose: true, shouldPreventContainerScroll: true, isTriggerPositionFixed: false, resetPositionWait: 250, showModal: false, closeButtonVisible: true, closeButtonValue: 'Close' }; export default Guide;
JavaScript
0
@@ -1743,17 +1743,8 @@ ose, -parentEl, %0A%0A @@ -2304,52 +2304,8 @@ de%22%0A - parentEl=%7BparentEl%7D%0A
274cd7eb9a05c1b32dab563a871c557097bc3392
make every/fps,fpsWhen work well together
src/Native/Time.js
src/Native/Time.js
Elm.Native.Time = {}; Elm.Native.Time.make = function(elm) { elm.Native = elm.Native || {}; elm.Native.Time = elm.Native.Time || {}; if (elm.Native.Time.values) return elm.Native.Time.values; var Signal = Elm.Signal.make(elm); var NS = Elm.Native.Signal.make(elm); var Maybe = Elm.Maybe.make(elm); var Utils = Elm.Native.Utils.make(elm); function fst(pair) { return pair._0; } function fpsWhen(desiredFPS, isOn) { var msPerFrame = 1000 / desiredFPS; var prev = elm.timer.now(), curr = prev, diff = 0, wasOn = true; var ticker = NS.input(diff); function tick(zero) { return function() { curr = elm.timer.now(); diff = zero ? 0 : curr - prev; if (prev > curr) { diff = 0; } prev = curr; elm.notify(ticker.id, diff); }; } var timeoutID = 0; function f(isOn, t) { if (isOn) { timeoutID = elm.setTimeout(tick(!wasOn && isOn), msPerFrame); } else if (wasOn) { clearTimeout(timeoutID); } wasOn = isOn; return t; } return A3( Signal.map2, F2(f), isOn, ticker ); } function every(t) { var ticker = NS.input(Utils.Tuple0); function tellTime() { elm.notify(ticker.id, Utils.Tuple0); } var clock = A2( Signal.map, fst, NS.timestamp(ticker) ); setInterval(tellTime, t); return clock; } function read(s) { var t = Date.parse(s); return isNaN(t) ? Maybe.Nothing : Maybe.Just(t); } return elm.Native.Time.values = { fpsWhen : F2(fpsWhen), fps : function(t) { return fpsWhen(t, Signal.constant(true)); }, every : every, delay : NS.delay, timestamp : NS.timestamp, toDate : function(t) { return new window.Date(t); }, read : read }; };
JavaScript
0.000001
@@ -394,24 +394,74 @@ ir._0;%0A %7D%0A%0A + function snd(pair) %7B%0A return pair._1;%0A %7D%0A%0A function f @@ -537,18 +537,26 @@ var pr -ev +ogramStart = elm.t @@ -569,332 +569,103 @@ ow() -, curr = prev, diff = 0, wasOn = true;%0A var ticker = NS.input(diff);%0A function tick(zero) %7B%0A return function() %7B%0A curr = elm.timer.now();%0A diff = zero ? 0 : curr - prev;%0A if (prev %3E curr) %7B%0A diff = 0;%0A %7D%0A prev = curr;%0A elm.notify(ticker.id, diff);%0A %7D;%0A %7D +;%0A var prev, curr, diff, wasOn = true;%0A var zero = true;%0A var ticker = NS.input(zero); %0A @@ -767,13 +767,44 @@ out( -tick( + function() %7B elm.notify(ticker.id, !was @@ -814,16 +814,20 @@ && isOn) +; %7D , msPerF @@ -938,24 +938,328 @@ rn t;%0A %7D%0A + function g(event, old) %7B%0A prev = snd(old);%0A curr = fst(event);%0A zero = snd(event);%0A diff = zero ? 0 : curr - prev;%0A return Utils.Tuple2(diff, curr);%0A %7D%0A var deltas = A2( Signal.map, fst, A3( Signal.foldp, F2(g), Utils.Tuple2(0, programStart), NS.timestamp(ticker) ) );%0A return A @@ -1287,22 +1287,22 @@ , isOn, -ticker +deltas );%0A %7D%0A
d9d920ce268b151b70ef5fb6798ede794ce0afb0
add logger
public_html/app.js
public_html/app.js
/* * The MIT License * * Copyright 2014 filippov. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var logger = null; var geom = null; function log(msg) { $('.log')[0].textValue += msg; } function parseWKT (){ var format = new ol.format.WKT(); var shape = format.readGeometry($('.coord-area')[0].textContent); if (shape.getType() === 'Polygon') { log('ol.geom.Polygon'); } else if (shape.getType() === 'MutliPolgon') { log('ol.geom.MutliPolgon'); } else { this.data = null; } geom = shape; log('Площадь объекта: ' + shape.getArea()); var newLink = $(this).find('a'); newLink.attr('target', '_blank'); var report = window.open(newLink.attr('href')); report.document.body.innerHTML = getCoordReport(shape); $('.coord-report').toggleClass('hide'); }; function getCoordReport (geom) { // css // html var table = $('<table/>'); var row = $('<tr/>'); row.addClass('coord-report-data-row'); row.append($('<td/>').html('<p>some data</p>')); row.append($('<td/>').html('<p>some data</p>')); table.append(row); return table.html(); };
JavaScript
0.000026
@@ -1208,34 +1208,43 @@ og') -%5B0%5D.textValue += msg;%0A +.val($('.log').val() + '%5Cn' + msg); %0A %7D%0A @@ -1746,24 +1746,26 @@ lank');%0A +// var report = @@ -1805,16 +1805,18 @@ );%0A%0A +// report.d
a3f7a39fd0ebf270b3fcfbcf681f41000284510b
Fix the style of limitations
src/botPage/view/react-components/LimitsPanel.js
src/botPage/view/react-components/LimitsPanel.js
import React, { PureComponent, PropTypes } from 'react' import ReactDOM from 'react-dom' import { translate } from '../../../common/i18n' import { Panel } from './Panel' const errorStyle = { color: 'red', fontSize: '0.8em', } const saveButtonStyle = { display: 'block', float: 'right', marginTop: '1em', } const limitsStyle = { width: '18em', float: 'left', } const inputStyle = { marginLeft: '0.5em', width: '4em', } export class LimitsPanel extends PureComponent { constructor() { super() this.state = { error: null, } } close() { ReactDOM.unmountComponentAtNode(document.getElementById('limits-panel')) } submit() { const maxLoss = +this.maxLossDiv.value const maxTrades = +this.maxTradesDiv.value if (maxLoss && maxTrades) { if (maxTrades <= 100) { this.close() this.props.onSave({ maxLoss, maxTrades, }) } else { this.setState({ error: translate('Maximum allowed number of trades for each session is 100.') }) } } else { this.setState({ error: translate('Both number of trades and loss amount are required.') }) } } render() { return ( <Panel id="saveAs" onClose={() => this.close()} description={translate('Trade Limitations')} content={ <div> <div style={limitsStyle} > <label htmlFor="limitation-max-trades">{translate('Maximum number of trades')}</label> <input style={inputStyle} ref={(el) => (this.maxTradesDiv = el)} type="number" id="limitation-max-trades" /> <label htmlFor="limitation-max-loss">{translate('Maximum loss amount')}</label> <input style={inputStyle} ref={(el) => (this.maxLossDiv = el)} type="number" id="limitation-max-loss" /> {this.state.error ? <p style={errorStyle}>{this.state.error}</p> : null} </div> <button style={saveButtonStyle} onClick={() => this.submit()} >{translate('Start')}</button> </div> } /> ) } props: { onSave: PropTypes.func, } }
JavaScript
0.999998
@@ -164,16 +164,59 @@ Panel'%0A%0A +const contentStyle = %7B%0A width: '18em',%0A%7D%0A%0A const er @@ -294,16 +294,32 @@ yle = %7B%0A + width: '4em',%0A displa @@ -344,31 +344,56 @@ t: ' -right',%0A marginTop: '1 +left',%0A marginLeft: '7em',%0A marginBottom: '0.5 em', @@ -410,32 +410,52 @@ limitsStyle = %7B%0A + display: 'block',%0A width: '18em', @@ -535,16 +535,75 @@ '4em',%0A + float: 'right',%0A%7D%0A%0Aconst fieldStyle = %7B%0A width: '18em',%0A %7D%0A%0Aexpor @@ -1501,16 +1501,37 @@ %3Cdiv + style=%7BcontentStyle%7D %3E%0A @@ -1538,26 +1538,16 @@ %3Cdiv -%0A style=%7B @@ -1562,23 +1562,10 @@ yle%7D +%3E %0A - %3E%0A @@ -1568,32 +1568,51 @@ %3Clabel + style=%7BfieldStyle%7D htmlFor=%22limita @@ -1632,55 +1632,8 @@ es%22%3E -%7Btranslate('Maximum number of trades')%7D%3C/label%3E %0A @@ -1766,86 +1766,132 @@ -%3Clabel htmlFor=%22limitation-max-loss%22%3E%7Btranslate('Maximum loss amount')%7D%3C/label +%7Btranslate('Maximum number of trades')%7D%0A %3C/label%3E%0A %3Clabel style=%7BfieldStyle%7D htmlFor=%22limitation-max-loss%22 %3E%0A @@ -2001,24 +2001,90 @@ ax-loss%22 /%3E%0A + %7Btranslate('Maximum loss amount')%7D%0A %3C/label%3E%0A @@ -2188,24 +2188,11 @@ %3C -button%0A +div sty @@ -2211,16 +2211,17 @@ onStyle%7D +%3E %0A @@ -2219,24 +2219,34 @@ %3E%0A + %3Cbutton onClick=%7B() @@ -2262,16 +2262,17 @@ ubmit()%7D +%3E %0A @@ -2274,17 +2274,20 @@ -%3E + %7Btransla @@ -2302,16 +2302,46 @@ t')%7D -%3C/button +%0A %3C/button%3E%0A %3C/div %3E%0A
1788a9dfa1695bee35388c5bbe73c595eeb0769c
Increase testserver verbosity.
example-server.js
example-server.js
/* Prerequisites: 1. Install node.js and npm 2. npm install ws See also, http://einaros.github.com/ws/ To run, node example-server.js */ "use strict"; // http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ var WebSocketServer = require('ws').Server; var http = require('http'); var server = http.createServer(); var wss = new WebSocketServer({server: server, path: '/foo'}); wss.on('connection', function(ws) { console.log('/foo connected'); ws.on('message', function(data, flags) { if (flags.binary) { return; } console.log('/foo >>> ' + data); if (data == 'goodbye') { ws.send('galaxy'); } if (data == 'hello') { ws.send('world'); } }); ws.on('close', function() { console.log('Connection closed!'); }); ws.on('error', function(e) { }); }); server.listen(8126); console.log('Listening on port 8126...');
JavaScript
0
@@ -582,21 +582,16 @@ le.log(' -/foo %3E%3E%3E ' + @@ -625,24 +625,51 @@ 'goodbye') %7B + console.log('%3C%3C%3C galaxy'); ws.send('ga @@ -708,16 +708,42 @@ ello') %7B + console.log('%3C%3C%3C world'); ws.send
1e197e5c11e5bde5c543bb789f9e212454010816
Fix Registers.sizeof
webui/js/OpenTI/Core/Registers.js
webui/js/OpenTI/Core/Registers.js
define(["../wrap"], function(Wrap) { var Registers = function(pointer) { if (!pointer) { throw "This object can only be instantiated with a memory region predefined!"; } this.pointer = pointer; Wrap.UInt16(this, "AF", pointer); Wrap.UInt8(this, "F", pointer); Wrap.UInt8(this, "A", pointer + 1); this.flags = {}; Wrap.UInt8(this.flags, "C", pointer, 128, 7); Wrap.UInt8(this.flags, "N", pointer, 64, 6); Wrap.UInt8(this.flags, "PV", pointer, 32, 5); Wrap.UInt8(this.flags, "3", pointer, 16, 4); Wrap.UInt8(this.flags, "H", pointer, 8, 3); Wrap.UInt8(this.flags, "5", pointer, 4, 2); Wrap.UInt8(this.flags, "Z", pointer, 2, 1); Wrap.UInt8(this.flags, "S", pointer, 1, 0); pointer += 2; Wrap.UInt16(this, "BC", pointer); Wrap.UInt8(this, "C", pointer); Wrap.UInt8(this, "B", pointer + 1); pointer += 2; Wrap.UInt16(this, "DE", pointer); Wrap.UInt8(this, "E", pointer); Wrap.UInt8(this, "D", pointer + 1); pointer += 2; Wrap.UInt16(this, "HL", pointer); Wrap.UInt8(this, "L", pointer); Wrap.UInt8(this, "H", pointer + 1); pointer += 2; Wrap.UInt16(this, "_AF", pointer); Wrap.UInt16(this, "_BC", pointer + 2); Wrap.UInt16(this, "_DE", pointer + 4); Wrap.UInt16(this, "_HL", pointer + 6); pointer += 8; Wrap.UInt16(this, "PC", pointer); Wrap.UInt16(this, "SP", pointer + 2); pointer += 4; Wrap.UInt16(this, "IX", pointer); Wrap.UInt8(this, "IXL", pointer); Wrap.UInt8(this, "IXH", pointer + 1); pointer += 2; Wrap.UInt16(this, "IY", pointer); Wrap.UInt8(this, "IYL", pointer); Wrap.UInt8(this, "IYH", pointer + 1); pointer += 2; Wrap.UInt8(this, "I", pointer++); Wrap.UInt8(this, "R", pointer++); // 2 dummy bytes needed for 4-byte alignment } Registers.sizeOf = function() { return 26 + 2; } return Registers; });
JavaScript
0
@@ -2112,20 +2112,16 @@ eturn 26 - + 2 ;%0A %7D%0A
957f5c95ee51c29828b5f06edc8a153c307c97a9
Fix the relative require paths for Node.
example/person.js
example/person.js
/* Copyright (c) 2011 Darryl Pogue * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ if (typeof require !== 'undefined') { require.paths.shift('.'); var Key = require('./key.js').Key; var ResManager = require('./resmgr.js').ResManager var gResMgr = require('./resmgr.js').gResMgr; var KeyedObject = require('./keyedobject.js').KeyedObject; } function Person() { this.name = null; } Person.inherits(KeyedObject); Person.prototype.read = function(data) { this.parent.read.call(this, data); if ('name' in data) { this.name = data.name; } } Person.prototype.get_name = function() { return this.name; } Person.prototype.set_name = function(name) { this.name = name; } gResMgr.register_class(0, Person); if (typeof exports !== 'undefined') { exports.Person = Person; }
JavaScript
0.000003
@@ -1194,24 +1194,25 @@ = require('. +. /key.js').Ke @@ -1233,32 +1233,33 @@ ger = require('. +. /resmgr.js').Res @@ -1290,16 +1290,17 @@ quire('. +. /resmgr. @@ -1341,16 +1341,17 @@ quire('. +. /keyedob
dae8c6871fe112c23ab1b42d03d1a919dbee0f06
Make success notification stay until clicked
www/js/duplicate-app.js
www/js/duplicate-app.js
var d = []; var s; var duplicatorService = 'https://localhost:8000'; var app = new Vue({ el: "#app", // validator: null, // private reference data: { app: { error: false }, isCreatingApp: false, showAppCreated: false, selected: "", options: d, newAppOwner: "", newAppName: "" }, // define methods under the `methods` object methods: { createApp: function (event) { // `this` inside methods points to the Vue instance if(!this.validate()) { return; } // Save copy of Vue instance for later use var vueInstance = this; vueInstance.isCreatingApp = true; console.log('Selected template app id: ' + this.selected.appId); console.log('Onwer of new app: ' + this.newAppOwner); console.log('Name of new app: ' + this.newAppName); $.getJSON(duplicatorService + '/duplicateKeepScript?templateAppId=' + this.selected.appId + '&appName=' + this.newAppName + '&ownerUserId=' + this.newAppOwner, {}, function (data) { console.log('App created'); console.log(data); vueInstance.isCreatingApp = false; var msgSuccess = 'Success! Your new app is available <a href="https://ip.of.server/sense/app/' + data.newAppId + '" target="_blank">here</a>.'; notie.alert({type: 'success', text: msgSuccess }); }); }, toggleAppCreated() { this.showAppCreated = !this.showAppCreated; }, validate:function() { this.$validator.validateAll(); if (this.errors.any()) { console.log('The provided data is invalid'); return false; } return true; } }, computed: { modalStyleAppCreated() { return this.showAppCreated ? { 'padding-left': '0px;', display: 'block' } : {}; }, newAppNameLength: function () { return this.newAppName.length; }, newAppOwnerLength: function () { return this.newAppOwner.length; }, // True if we have enough data to start duplicating the app newAppPropertiesOk: function () { // `this` points to the vm instance if ((this.newAppOwner.length > 0) && (this.newAppName.length > 0)){ return true; } else { return false; } } } }); // If some kindof Single Sign On (SSO) solution is used, here is a good place to retrieve currently logged // in user. Place the username in the ssoUser variable // Get currently logged in SSO user, if any var ssoUser = ""; // JQuery helper method getJSON described here: https://api.jquery.com/jquery.getjson/ // Assign handlers immediately after making the request, and remember the jqxhr object for this request notie.alert({ type: 'info', text: ' <i class="fa fa-spinner fa-spin" style="font-size:24px"></i> Loading app templates....' }); var jqxhr1 = $.getJSON(duplicatorService + '/getTemplateList', {}, function (data) { $.each(data, function (index, element) { d.push({ value: element.id, text: element.name, description: element.description }); }); app.selected = { appId: d[0].value, description: d[0].description }; }) .done(function () { notie.alertHide(); }) .fail(function () { notie.alert({type: 'error', text: 'Error: Could not retrieve list of templates from Sense server.', time:5 }); }) .always(function () { // console.log("Done loading templates"); });
JavaScript
0
@@ -1515,16 +1515,28 @@ gSuccess +, stay: true %7D);%0A
6be65d85cb61b314013138dcd8f62b9d8ad6d83c
Fix unsaved typo corrections.
example/simple.js
example/simple.js
/* * netsuite-js * https://github.com/CrossLead/netsuite-js * * Copyright (c) 2015 Christian Yang * Licensed under the Apache license. */ 'use strict'; var denodeify = require('denodeify'); var NetSuite = require('../'); var credentials = require('./credentials.json'); var config = new NetSuite.Configuration(credentials); var c; console.log('Creating NetSuite connection'); config .createConnection() .then(function(client) { c = client; console.log('WSDL processed. Service description:'); console.log(client.describe()); console.log('Getting Employee record'); client.get({ 'platformMsgs:baseRef': { attributes: { internalId: 5084, type: 'employee', 'xsi:type': 'platformCore:RecordRef' } } }, function(err, result, raw, soapHeader) { if (err) { console.error(err); } else { console.log(result); } console.log('Last Request:'); console.log(lastRequest.c); }); }) .catch(function(err) { console.error(err); });
JavaScript
0.000001
@@ -616,21 +616,8 @@ ' -platformMsgs: base @@ -966,16 +966,18 @@ ole.log( +c. lastRequ @@ -979,18 +979,16 @@ tRequest -.c );%0A %7D
bd6a2d4aba552713803bac109b5f099e7b4fa9ad
fix js stream-fn
resources/public/browser_test.js
resources/public/browser_test.js
var r = replikativ.js; var user = "mail:[email protected]"; var ormapId = cljs.core.uuid("07f6aae2-2b46-4e44-bfd8-058d13977a8a"); var uri = "ws://127.0.0.1:31778"; var props = {captures: []}; var streamEvalFuncs = {"add": function(old, params) { var oldCaptures = old.captures; var newCaptures = oldCaptures.push(params); return {captures: newCaptures}; }}; function logError(err) { console.log(err); } var sync = {}; function setupReplikativ() { r.newMemStore().then(function(store) { sync.store = store; return r.clientPeer(store); }, logError).then(function(peer) { sync.peer = peer; return r.createStage(user, peer); }, logError).then(function(stage) { sync.stage = stage; sync.stream = r.streamIntoIdentity(stage, user, ormapId, streamEvalFuncs, props) return r.createOrMap(stage, {id: ormapId, description: "captures"}) }, logError).then(function() { return r.connect(sync.stage, uri); }, logError).then(function () { console.log("stage connected!") }, logError); } function checkIt(value) { r.associate(sync.stage, user, ormapId, hasch.core.uuid(cljs.core.js__GT_clj(value)), [["add", value]]) .then(function(result) { console.log("foo associated with 42"); }, logError); } setupReplikativ();
JavaScript
0.000002
@@ -342,19 +342,19 @@ ptures: -new +old Captures @@ -1211,12 +1211,8 @@ og(%22 -foo asso @@ -1227,11 +1227,17 @@ ith -42%22 +%22 + value );%0A @@ -1276,9 +1276,8 @@ tiv();%0A%0A -%0A
866559c434743fbc7f6b7b2227b666b9b6da462f
Implement `delegate.on()`
delegate.js
delegate.js
/*! delegate.js v0.0.0 - MIT license */ ;(function (global) { function moduleDefinition(matches) { // --------------------------------------------------------------------------- var elem; /** * Specify the event delegate element * * @param {Element} node * @return {delegate} * @api public */ function delegate(node) { if (!_isElem(node)) { throw new Error('delegate(): The argument must be an Element or Document Node'); } elem = node; return delegate; } /** * Determine is a Node is an Element or Document * * @param {Node} node * @return {Boolean} * @api private */ function _isElem(node) { if (node && node.nodeName && (node.nodeType == Node.ELEMENT_NODE || node.nodeType == Node.DOCUMENT_NODE)) { return true; } return false; } /** * Expose delegate */ return delegate; // --------------------------------------------------------------------------- } if (typeof exports === 'object') { // node export module.exports = moduleDefinition(require('matches')); } else if (typeof define === 'function' && define.amd) { // amd anonymous module registration define(['matches'], moduleDefinition); } else { // browser global global.delegate = moduleDefinition(global.matches); }}(this));
JavaScript
0.000003
@@ -481,24 +481,1592 @@ elegate;%0A%7D%0A%0A +/**%0A * Delegate the handling of an event type to the given ancestor-element of%0A * nodes matching a given CSS selector. The callback function is invoked when%0A * an event bubbles up through any nodes that delegated their event handling to%0A * the ancestor.%0A *%0A * @param %7BString%7D type DOM Event type%0A * @param %7BString%7D selector%0A * @param %7BFunction%7D callback%0A * @param %7BBoolean%7D %5Bcapture%5D%0A * @return %7BFunction%7D%0A * @api public%0A */%0A%0Adelegate.on = function (type, selector, callback, capture) %7B%0A function wrapper(e) %7B%0A // if this event has a delegateTarget, then we add it to the event%0A // object (so that handlers may have a reference to the delegator%0A // element) and fire the callback%0A if (e.delegateTarget = _getDelegateTarget(elem, e.target, selector)) %7B%0A callback.call(elem, e);%0A %7D%0A %7D%0A%0A callback._delegateWrapper = wrapper;%0A elem.addEventListener(type, wrapper, capture %7C%7C false);%0A return callback;%0A%7D;%0A%0A/**%0A * Walk up the DOM tree from the %60target%60 element to which the event was%0A * dispatched, up to the delegate %60elem%60. If at any step, a node matches the%0A * given CSS %60selector%60 then we know the event bubbled up through the%0A * delegator.%0A *%0A * @param %7BElement%7D elem%0A * @param %7BElement%7D target%0A * @param %7BString%7D selector%0A * @return %7BElement%7Cnull%7D%0A * @api private%0A */%0A%0Afunction _getDelegateTarget(elem, target, selector) %7B%0A while (target && target !== elem) %7B%0A if (matches(target, selector)) %7B%0A return target;%0A %7D%0A target = target.parentElement;%0A %7D%0A%0A return null;%0A%7D%0A%0A /**%0A * Deter
98794aa03d3cb570f2ab1678898056e72f36c965
move npm root to an internal variable on the require-auto module, and don't fetch that info every time we require a file (cause it's slow)
require-auto.js
require-auto.js
var _path = require ("path"); var _fs = require ("fs"); var _cp = require ("child_process"); var _os = require ("os"); // fileExists - internal helper function because the Node.js "fs" package has // deprecated the "exists" method, and the "approved" async way of getting stat throws // an exception if the file doesn't exist (who is responsible for the API design here? // amateur much?) var fileExists = function (path) { try { var stats = _fs.statSync (path); return true; } catch (exc) { } return false; }; // getNpmRoot - internal helper function to synchronously run npm and return the output // as a string var getNpmRoot = function () { // compute a temporary name for the file I want to use to facilitate my synchronous // execution of the npm root command var outputName = _path.join (__dirname, "" + Date.now ()); //process.stderr.write ("OutputName: " + outputName + "\n"); // compute the path of the npm.js script, and set up the options to run it var npmjs = _path.join(__dirname, "npm.js"); //process.stderr.write ("NPM.js: " + npmjs + "\n"); var options = { stdio: ["ignore", 1, 2] }; _cp.execSync("node " + npmjs + " root " + outputName, options); // read the output file back in, then remove it, and trim the return var result = _fs.readFileSync(outputName, "utf8"); _fs.unlinkSync(outputName); return result.trim (); } var requireAuto = function (name) { // WELLLLL (church lady voice) - npm is *SPECIAL*. Rather than try to look simply // for where npm will put the included packages, I'll have to ask npm directly var path = getNpmRoot (); process.stderr.write ("Root (" + path + ")\n"); // figure out where our package should be var package = _path.join (path, name); //process.stderr.write ("Package (" + package + ")\n"); if (! fileExists (package)) { process.stderr.write ("install (" + name + ")\n"); var options = { stdio: [0, 1, 2] }; // Isn't that *SPECIAL* (church lady voice) - npm doesn't like cygwin // which means this program won't work on vanilla windows now... _cp.execSync("bash -c 'pwd; npm install " + name + "'", options); } return require (name); }; module.exports = requireAuto;
JavaScript
0
@@ -545,20 +545,17 @@ %0A%7D;%0A%0A// -getN +n pmRoot - @@ -586,76 +586,179 @@ n to - synchronously run npm and return the output%0A// as a string +... WELLLLL (church lady voice) - npm is %0A// *SPECIAL*. Rather than try to look simply for where npm will put the included%0A// packages, I'll have to ask npm directly %0Avar -getN +n pmRo @@ -1526,297 +1526,106 @@ );%0A%7D -%0A%0Avar requireAuto = function (name) %7B%0A // WELLLLL (church lady voice) - npm is *SPECIAL*. Rather than try to look simply%0A // for where npm will put the included packages, I'll have to ask npm directly%0A var path = getNpmRoot ();%0A process.stderr.write (%22Root (%22 + path + %22)%5Cn%22);%0A + ();%0A//process.stderr.write (%22npm root (%22 + npmRoot + %22)%5Cn%22);%0A%0Avar requireAuto = function (name) %7B %0A @@ -1697,20 +1697,23 @@ h.join ( -path +npmRoot , name);
afaf0ab5e73137505e5c4a93d647c5a40100fd2c
update main server for outer league wrapper methods
score-tweets.js
score-tweets.js
var http = require('http') , file = require('fs') , db = require('./my_modules/db.js') , NHLScore = require('./my_modules/nhl.js') , NFLScore = require('./my_modules/nfl.js'); var league = Object.create(NHLScore); var rawResponse = ''; var request = http.get(league.updateURL, function(res) { res.on('data', function(chunk) { //console.log('Got %d bytes of data', chunk.length); rawResponse += chunk; }); res.on('end', function() { var array = league.getGameArray(rawResponse); console.log('Response: ' + JSON.stringify(array)); }); }).on('error', function(e) { console.log('Error: ' + e.message); });
JavaScript
0
@@ -1,34 +1,8 @@ var -http = require('http')%0D%0A,%09 file @@ -59,24 +59,22 @@ js')%0D%0A,%09 -NHLScore +config = requi @@ -94,11 +94,14 @@ les/ -nhl +config .js' @@ -110,15 +110,10 @@ %0A,%09N -FLScore +HL = r @@ -134,17 +134,17 @@ odules/n -f +h l.js');%0D @@ -160,256 +160,232 @@ ague +s = -Object.create(NHLScore);%0D%0A%0D%0Avar rawResponse = ''; +%5B%5D;%0D%0Aleagues.push(NHL);%0D%0A%0D%0Afor (var i = 0; i %3C leagues.length; i++) %7B %0D%0A +%09 var -request = http.get(league.updateURL, function(res) %7B%0D%0A%09res.on('data', function(chunk) %7B%0D%0A%09%09//console.log('Got %25d bytes of data', chunk.length);%0D%0A%09%09rawResponse += chunk;%0D%0A%09%7D);%0D%0A%09res.on('end', +leagueName = leagues%5B0%5D.league.leagueName;%0D%0A%09leagues%5Bi%5D.startProcess(config.leagues%5BleagueName%5D.refreshInterval);%0D%0A%7D%0D%0A%0D%0Avar interval;%0D%0Avar end = fun @@ -400,183 +400,146 @@ %7B%0D%0A%09 -%09var array = league.getGameArray(rawResponse);%0D%0A%09%09console.log('Response: ' + JSON.stringify(array));%0D%0A%09%7D);%0D%0A%7D).on('error', function(e) %7B%0D%0A%09console.log('Error: ' + e.message);%0D%0A%7D +for (var i = 0; i %3C leagues.length; i++) %7B%0D%0A%09%09leagues%5Bi%5D.endProcess();%0D%0A%09%7D%0D%0A%09clearInterval(interval);%0D%0A%7D%0D%0A%0D%0Ainterval = setInterval(end,25000 );
1bfb89f49688dae66428f27632321f6dfb96d726
test hotfix
app/js/user/index.js
app/js/user/index.js
module.exports = function(app) { require('./controllers')(app); require('./directives')(app); };
JavaScript
0.000001
@@ -63,39 +63,7 @@ p);%0A - require('./directives')(app);%0A %7D;%0A
c906b99e7cfa0cae75ebbf14e59576187315a3eb
Fix parser bugs reading disabled/checked, and also b="false" and foo="" type attributes (which should be obeyed not ignored).
form/TimeTextBox.js
form/TimeTextBox.js
dojo.provide("dijit.form.TimeTextBox"); dojo.require("dojo.date"); dojo.require("dojo.date.locale"); dojo.require("dojo.date.stamp"); dojo.require("dijit.form._TimePicker"); dojo.require("dijit.form.ValidationTextBox"); dojo.declare( "dijit.form.TimeTextBox", dijit.form.RangeBoundTextBox, { // summary: // A validating, serializable, range-bound date text box. // constraints object: min, max regExpGen: dojo.date.locale.regexp, compare: dojo.date.compare, format: dojo.date.locale.format, parse: dojo.date.locale.parse, serialize: dojo.date.stamp.toISOString, value: new Date(), _popupClass: "dijit.form._TimePicker", postMixInProperties: function(){ dijit.form.RangeBoundTextBox.prototype.postMixInProperties.apply(this, arguments); var constraints = this.constraints; constraints.selector = 'time'; if(typeof constraints.min == "string"){ constraints.min = dojo.date.stamp.fromISOString(constraints.min); } if(typeof constraints.max == "string"){ constraints.max = dojo.date.stamp.fromISOString(constraints.max); } }, onfocus: function(/*Event*/ evt){ // open the calendar this._open(); dijit.form.RangeBoundTextBox.prototype.onfocus.apply(this, arguments); }, setValue: function(/*Date*/date, /*Boolean, optional*/ priorityChange){ // summary: // Sets the date on this textbox this.inherited('setValue', arguments); if(this._picker){ // #3948: fix blank date on popup only if(!date){date=new Date();} this._picker.setValue(date); } }, _open: function(){ // summary: // opens the Calendar, and sets the onValueSelected for the Calendar var self = this; if(!this._picker){ var popupProto=dojo.getObject(this._popupClass, false); this._picker = new popupProto({ onValueSelected: function(value){ self.focus(); // focus the textbox before the popup closes to avoid reopening the popup setTimeout(dijit.popup.close, 1); // allow focus time to take // this will cause InlineEditBox and other handlers to do stuff so make sure it's last dijit.form.TimeTextBox.superclass.setValue.call(self, value, true); }, lang: this.lang, constraints:this.constraints, isDisabledDate: function(/*Date*/ date){ // summary: // disables dates outside of the min/max of the TimeTextBox return self.constraints && (dojo.date.compare(self.constraints.min,date) > 0 || dojo.date.compare(self.constraints.max,date) < 0); } }); this._picker.setValue(this.getValue() || new Date()); } if(!this._opened){ dijit.popup.open({ parent: this, popup: this._picker, around: this.domNode, onClose: function(){ self._opened=false; } }); this._opened=true; } }, _onBlur: function(){ // summary: called magically when focus has shifted away from this widget and it's dropdown dijit.popup.closeAll(); this.inherited('_onBlur', arguments); // don't focus on <input>. the user has explicitly focused on something else. }, postCreate: function(){ this.inherited('postCreate', arguments); this.connect(this.domNode, "onclick", this._open); }, getDisplayedValue:function(){ return this.textbox.value; }, setDisplayedValue:function(/*String*/ value){ this.textbox.value=value; } } );
JavaScript
0.000023
@@ -601,10 +601,20 @@ ate( -), +%22%22),%09// NaN%0A %0A%09%09_
9174b6ae37a8e7b0eae456ccc778adf516e2d42a
Update ByteCount after inserting
res/public/o.js
res/public/o.js
function genUni(){ var code = prompt("Generate Unicode Character:"); $('#code').val($('#code').val() + String.fromCharCode(parseInt(code))); }; function getByteCount(s) { var count = 0, stringLength = s.length; s = String(s || ""); for(var i = 0; i < stringLength; i++){ var partCount = encodeURI(s[i]).split("%").length; count += partCount == 1 ? 1 : partCount - 1; } return count; } function updateByteCount() { var c = $('#code').val(); var byteCount = getByteCount(c); var charCount = c.length; var s = byteCount + " bytes and " + charCount + " chars long."; $('#byteCount').html(s); } updateByteCount(); $(document).ready(function() { $("#permalink").click(function(){ var code = $.param({code: $('#code').val(), input: $('#input').val()}); prompt("Permalink:", "http://" + window.location.hostname + "/link/" + code); window.location.pathname = "/link/" + code; }); $('#code').on('input propertychange paste', function() { updateByteCount(); }); });
JavaScript
0
@@ -141,16 +141,38 @@ de)));%0D%0A + updateByteCount();%0D%0A %7D;%0D%0A%0D%0Afu
09e34298780290bace6b9a36747fdf57bb4ac479
support tts
scripts/back.js
scripts/back.js
/** * Copyright (C) 2015 yanni4night.com * back.js * * changelog * 2015-09-14[15:49:25]:revised * * @author [email protected] * @version 0.1.0 * @since 0.1.0 */ require(['./scripts/meetings'], function (Meetings) { var MeetingsChecker = function () { var started = false; var inError = false; var lastNotification; this.start = function () { var self = this; if (started) { return self; } chrome.alarms.create('checkMeetings', { when: Date.now() + 1e3, periodInMinutes: 1 }); chrome.alarms.onAlarm.addListener(function (alarm) { Meetings.list(function (err, scheduleList) { if (err) { // Do not report error duplicately. if (!inError) { self.reportError(err.message || '获取会议室信息失败'); } inError = true; return; } inError = false; var schedules = scheduleList.schedules; var onSchedulingSize = schedules.filter(function (item) { return '未开始' === item['当前状态'] }).length; var onCheckinginSize = schedules.filter(function (item) { return '可签入' === item['当前状态'] }).length; chrome.browserAction.setBadgeText({ text: onSchedulingSize + '(' + onCheckinginSize + ')' }); if (onCheckinginSize) { if (lastNotification) { lastNotification.close(); } lastNotification = new Notification('签到', { icon: 'img/ask.png', body: '有要签到的会议室' }); } }); }); return self; }; this.reportError = function (errmsg) { //Prevent from mutiple notifications if (lastNotification) { lastNotification.close(); } lastNotification = new Notification('出错', { icon: 'img/warn.png', body: errmsg }); }; }; console.debug('Start checking meetings'); new MeetingsChecker().start(); });
JavaScript
0
@@ -1386,20 +1386,16 @@ eckingin -Size = sched @@ -1492,39 +1492,32 @@ %7D) -.length ;%0A%0A @@ -1626,22 +1626,53 @@ eckingin -Size + +.length +%0A ')'%0A @@ -1729,20 +1729,23 @@ eckingin -Size +.length ) %7B%0A @@ -1860,32 +1860,33 @@ %7D%0A +%0A @@ -2025,42 +2025,329 @@ y: ' -%E6%9C%89%E8%A6%81%E7%AD%BE%E5%88%B0%E7%9A%84%E4%BC%9A%E8%AE%AE%E5%AE%A4'%0A +%E4%BC%9A%E8%AE%AE%E5%AE%A4%E3%80%90' + onCheckingin%5B0%5D%5B'%E4%BC%9A%E8%AE%AE%E5%AE%A4%E5%90%8D%E7%A7%B0'%5D + '%E3%80%91%E9%9C%80%E8%A6%81%E7%AD%BE%E5%88%B0'%0A %7D);%0A%0A chrome.tts.speak('%E6%82%A8%E6%9C%89%E9%9C%80%E8%A6%81%E7%AD%BE%E5%88%B0%E7%9A%84%E4%BC%9A%E8%AE%AE%E5%AE%A4%EF%BC%9A' + onCheckingin%5B0%5D%5B'%E4%BC%9A%E8%AE%AE%E5%AE%A4%E5%90%8D%E7%A7%B0'%5D, %7B%0A lang: 'zh-CN',%0A rate: 1.0,%0A enqueue: true%0A %7D, function () %7B %7D);%0A
a24beb6e52f769a608c545976272d564b8c65905
Update game.js
scripts/game.js
scripts/game.js
var text = document.getElementById('textArea'); // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 function arrows() { thingie = '<button onclick="up()">⇑</button><br>'; thingie += '<button onclick="left()">⇐</button> '; thingie += '<button onclick="right()">⇒</button><br>'; thingie += '<button onclick="down()">⇒</button>'; sumbit.innerHTML = thingie; function start() { text.innerHTML = 'In the year 201X ...'; arrows(); }
JavaScript
0.000001
@@ -40,16 +40,74 @@ tArea'); +%0Avar sumbit = document.getElementById('submitButtonArea'); %0A%0A
ab2012a4791437a0c22b78dbbe3ae587d584bcb7
Update game.js
scripts/game.js
scripts/game.js
var game= { resources: {}, tick: function() { for(var res in game.resources) { game.resources[res].update(); } } }; game.tick.bind(game); game.interval = window.setInterval(game.tick,100); game.buttons = document.getElementById('buttons'); game.labels = document.getElementById('stats'); game.resource = function(name,startingValue,onTick,onClick,label) { this.name = name; this.onTick = onTick?onTick:function(){}; this.onTick.bind(this); this.format=function(value) { if(value>1000000000000000) { return this.format(value/1000000000000000)+"qi"; } if(value>1000000000000) { return this.format(value/1000000000000)+"qa"; } if(value>1000000000) { return this.format(value/1000000000)+"b"; } if(value>1000000) { return this.format(value/1000000)+"m"; } if(value>1000) { return this.format(value/1000)+"k"; } return Math.floor(value)+"."+Math.floor(value*10)%10; }; this.update = function() { this.onTick(); this.label.lastChild.innerHTML=this.format(this.value); }; this.update.bind(this); this.value = startingValue?startingValue:0; this.increase = function(amount) { this.value += !Number.isNaN(amount)?amount:1; } this.decrease = function(amount) { if(amount>this.value) { throw "Not enough "+this.name; } this.value -= amount; } if(onClick){ this.button = document.createElement('button'); this.button.innerHTML = label?label:name+"-action"; this.button.onclick = onClick; game.buttons.appendChild(this.button); } this.label = document.createElement('div'); this.label.setAttribute('class','resource'); this.label.appendChild(document.createElement('div')); this.label.lastChild.innerHTML=this.name; this.label.appendChild(document.createElement('div')); this.label.lastChild.innerHTML=this.format(this.value); game.labels.appendChild(this.label); game.resources[this.name] = this; } game.resources.gold = new game.resource('gold',50, function(){ game.resources["gold"].value+=0.1*game.resources.house.value+0.01*game.resources.human.value+0.0001;}, function(){ game.resources["gold"].value++;}, 'Mine gold') game.resources.house = new game.resource('house',0,function(){ try{ game.resources.house.decrease(Math.round(Math.random())*0.001); }catch(e){ //no issue here } }, function(event) { event = event || window.event; if(game.resources.gold.value > 100*Math.pow(1.1,game.resources.house.value)) { game.resources.gold.decrease(100*Math.pow(1.1,game.resources.house.value)); game.resources.house.increase(); event.target.innerHTML = "Buy House: " + game.resources.house.format(100*Math.pow(1.1,game.resources.house.value)); } },'Buy House'); game.resources.human = new game.resource('human',1,function(){ game.resources.human.increase(Math.round(Math.random(0,game.resources.house))); });
JavaScript
0.000001
@@ -2926,16 +2926,76 @@ es.house +.value*game.resources.human*vlaue*game.resources.human*value )));%0A%7D);
2876057ba7b759c111971fdac8a17415038dc233
bump version number
poly.js
poly.js
/** * polyfill / shim plugin for AMD loaders * * (c) copyright 2011-2012 Brian Cavalier and John Hann * * poly is part of the cujo.js family of libraries (http://cujojs.com/) * * Licensed under the MIT License at: * http://www.opensource.org/licenses/mit-license.php * */ define(['exports'], function (exports) { exports.version = '0.2.2'; exports.load = function (def, require, onload, config) { function success (module) { // check for curl.js's promise onload.resolve ? onload.resolve(module) : onload(module); } function fail (ex) { // check for curl.js's promise if (onload.reject) { onload.reject(ex) } else { throw ex; } } // load module require([def], function (module) { try { // augment native if (module['polyfill']) { module['polyfill'](); } } catch (ex) { fail(ex); } success(module); }); }; return exports; });
JavaScript
0.000004
@@ -344,17 +344,17 @@ = '0.2. -2 +3 ';%0A%0A%09exp
91a3e23125540bee2634be84878bd2237f02235c
Fix to the less-error-prone ++
web/party/profile.js
web/party/profile.js
'use strict'; app.controller('party/profile', [ '$scope', 'displayService', 'party', 'pageService','constantService', function ($scope, display, party, page, constants) { var getUsers = function(volumes){ var users = {}; users.sponsors = []; users.labGroupMembers = []; users.nonGroupAffiliates = []; users.otherCollaborators = []; _(volumes).pluck('access').flatten().each(function(v){ console.log("V: ", v); if(v.children > 0 ){ users.sponsors.push(v); } else if(v.parents && v.parents.length && v.party.members && v.party.members.length) { users.labGroupMembers.push(v); } else if(v.parents && v.parents.length){ users.nonGroupAffiliates.push(v); } else { users.otherCollaborators.push(v); } }).value(); console.log(users); return users; }; // This is a quick helper function to make sure that the isSelected // class is set to empty and to avoid repeating code. var unSetSelected = function(v){ v.isSelected = ''; if(v.v !== undefined){ v.v = _.map(v.v, function(a){ a.isSelected = ''; return a; }); } return v; }; var unselectAll = function(){ $scope.volumes.individual = _.map($scope.volumes.individual, unSetSelected); $scope.volumes.collaborator = _.map($scope.volumes.collaborator, unSetSelected); $scope.volumes.inherited = _.map($scope.volumes.inherited, unSetSelected); $scope.users.sponsors = _.map($scope.users.sponsors, unSetSelected); $scope.users.nonGroupAffiliates = _.map($scope.users.nonGroupAffiliates, unSetSelected); $scope.users.labGroupMembers = _.map($scope.users.labGroupMembers, unSetSelected); $scope.users.otherCollaborators = _.map($scope.users.otherCollaborators, unSetSelected); }; $scope.clickVolume = function(volume) { unselectAll(); volume.isSelected = 'volumeSelected'; for(var i = 0; i < volume.access.length; i += 1 ){ var j; for (j = 0; j < $scope.users.sponsors.length; j += 1){ if($scope.users.sponsors[j].party.id === volume.access[i].party.id){ $scope.users.sponsors[j].isSelected = 'userSelected'; } } for (j = 0; j < $scope.users.labGroupMembers.length; j += 1){ if($scope.users.labGroupMembers[j].party.id === volume.access[i].party.id){ $scope.users.labGroupMembers[j].isSelected = 'userSelected'; } } for (j = 0; j < $scope.users.nonGroupAffiliates.length; j += 1){ if($scope.users.nonGroupAffiliates[j].party.id === volume.access[i].party.id){ $scope.users.nonGroupAffiliates[j].isSelected = 'userSelected'; } } for (j = 0; j < $scope.users.otherCollaborators.length; j += 1){ if($scope.users.otherCollaborators[j].party.id === volume.access[i].party.id){ $scope.users.otherCollaborators[j].isSelected = 'userSelected'; } } } }; // This should take in a user, then select volumes on each thing. $scope.clickUser = function(user){ unselectAll(); var i, j, k; for(i = 0; i < $scope.volumes.individual.length; i += 1){ for(j = 0; j < $scope.volumes.individual[i].v.length; j += 1){ for(k = 0; k < $scope.volumes.individual[i].v[j].access; k += 1){ if($scope.volumes.individual[i].v[j].access[k].party.id == user.party.id){ $scope.volumes.individual[i].v[j].isSelected = 'volumeSelected'; } } } } for(i = 0; i < $scope.volumes.collaborator.length; i++){ for(j = 0; j < $scope.volumes.collaborator[i].v.length; j += 1){ for(k = 0; k < $scope.volumes.collaborator[i].v[j].access.length; k += 1){ if($scope.volumes.collaborator[i].v[j].access[k].party.id == user.party.id) { $scope.volumes.collaborator[i].v[j].isSelected = 'volumeSelected'; } } } } for(i = 0; i < $scope.volumes.inherited.length; i++){ for(j = 0; j < $scope.volumes.inherited[i].v.length; j += 1){ for(k = 0; k < $scope.volumes.inherited[i].v[j].access.length; k += 1){ if($scope.volumes.inherited[i].v[j].access[k].party.id == user.party.id) { $scope.volumes.inherited[i].v[j].isSelected = 'volumeSelected'; } } } } }; var getParents = function(parents) { var tempParents = []; _.each(parents, function(p){ if(p.member){ var v = []; var tempThing = { p: p, v: v }; tempParents.push(tempThing); } }); return tempParents; }; var getVolumes = function(volumes) { var tempVolumes = {}; tempVolumes.individual = []; tempVolumes.collaborator = []; tempVolumes.inherited = getParents(party.parents); _.each(volumes, function(v){ if(v.isIndividual){ tempVolumes.individual.push({v: [v]}); } else if(tempVolumes.isCollaborator){ tempVolumes.collaborator.push({v: [v]}); } else{ for (var i=0;i<v.access.length;i++){ for (var j=0;j<tempVolumes.inherited.length;j++){ if (v.access[i].children && v.access[i].party.id === tempVolumes.inherited[j].p.party.id){ tempVolumes.inherited[j].v.push(v); break; } } } } }); return tempVolumes; }; $scope.party = party; $scope.volumes = getVolumes(party.volumes); console.log("Volumes: ", $scope.volumes); $scope.users = getUsers(party.volumes); $scope.page = page; $scope.profile = page.$location.path() === '/profile'; display.title = party.name; console.log($scope.volumes.inherited); } ]);
JavaScript
0.999995
@@ -3353,21 +3353,18 @@ ength; i - += 1 +++ )%7B%0A @@ -3413,37 +3413,34 @@ l%5Bi%5D.v.length; j - += 1 +++ )%7B%0A for @@ -3494,21 +3494,18 @@ ccess; k - += 1 +++ )%7B%0A @@ -3830,37 +3830,34 @@ r%5Bi%5D.v.length; j - += 1 +++ )%7B%0A for @@ -3912,37 +3912,34 @@ access.length; k - += 1 +++ )%7B%0A i @@ -4255,37 +4255,34 @@ d%5Bi%5D.v.length; j - += 1 +++ )%7B%0A for @@ -4342,21 +4342,18 @@ ength; k - += 1 +++ )%7B%0A
4b5c27a2ff971486fca6decb6ede1bf3f4f8868c
Fix bug
scripts/main.js
scripts/main.js
var percentRef = new Firebase('https://indoor-proto.firebaseio.com/percent'); percentRef.on('value', function(snapshot) { onData(snapshot.val()); }); var ROOMS = { 'TB109': { location: [1824, 1792], distance: 50, zoom: 0.15, pan: [-371, -231], route: 'M3576,1704 L3372,1708 L1932,1732 L1824,1792' }, 'TB103': { location: [3204, 1748], distance: 10, zoom: 0.2, pan: [-655, -276], route: 'M3576,1704 L3372,1708 L3196,1748' }, 'TC163': { location: [1236, 1656], distance: 100, zoom: 0.12, pan: [-264, -190], route: 'M3576,1704 L3372,1708 L1312,1732 L1236,1656' } }; var ROOMS_KEYS = []; for (var room in ROOMS) { if (ROOMS.hasOwnProperty(room)) ROOMS_KEYS.push(room); } var roomIndex = 0; // In pixels in tietotalo.jpg var START_LOCATION = [3576, 1704]; var LOCATION_SIZE = [70, 70]; var MARKER_SIZE = [200, 200]; var currentDestination; function onData(data) { setRoutePosition(data.value); } function showRoute(destination) { currentDestination = destination; $indoorMap = $('#indoor-map'); $marker = $indoorMap.find('#marker'); $route = $indoorMap.find('#route'); $routeInfo = $('#route-info'); var room = ROOMS[destination]; $marker.css({ left: room.location[0] - MARKER_SIZE[0] / 2, top: room.location[1] - MARKER_SIZE[0] }); $indoorMap.panzoom("zoom", room.zoom, { silent: true }); $indoorMap.panzoom("pan", room.pan[0], room.pan[1], { silent: true }); var svg = createRouteSvg(destination); $route.html(''); $route[0].appendChild(svg); setRoutePosition(0); $('#destination').html(destination); $marker.show(); $route.show(); $routeInfo.show(); } function createRouteSvg(destination) { var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.setAttribute("viewBox", "0 0 4183 3213"); var path = document.createElementNS("http://www.w3.org/2000/svg", "path"); path.setAttribute("d", ROOMS[destination].route); path.setAttribute("stroke", '#47ACFF'); path.setAttribute("stroke-width", 30); path.setAttribute("fill-opacity", 0); svg.appendChild(path); path.id = 'route-path' return svg; } function setRoutePosition(percent) { if (!currentDestination) return; var distance = ROOMS[currentDestination].distance; var distanceLeft = distance - distance * percent; var timeLeft = distanceLeft / 4; $('#distance-left').html(distanceLeft.toFixed()); $('#time-left').html(timeLeft.toFixed()); var path = $('#route-path')[0]; var length = path.getTotalLength(); var pathDistance = percent * length; var point = path.getPointAtLength(pathDistance); $('#location').css({ left: point.x - LOCATION_SIZE[0] / 2, top: point.y - LOCATION_SIZE[0] / 2 }); } function setLocation(location) { $location = $('#location'); $location.css({ left: location[0] - LOCATION_SIZE[0] / 2, top: location[1] - LOCATION_SIZE[0] / 2 }); } function hideRoute() { $indoorMap = $('#indoor-map'); $indoorMap.find('#marker').hide(); $indoorMap.find('#route').hide(); $('#route-info').hide(); } function initIndexView() { setTimeout(function() { $('#splash').addClass('zoom'); $('.hidden').removeClass('hidden'); setTimeout(function() { $('#splash').hide(); $('#locating').fadeOut(); }, 1800); }, 3000) var $elem = $('#indoor-map'); hideRoute(); $elem.panzoom({ minScale: 0.1, maxScale: 2, }); $elem.panzoom("zoom", 0.2, { silent: true }); $elem.panzoom("pan", -691, -208, { silent: true} ); var $search = $('#search'); $search.on('click', function() { var room = ROOMS_KEYS[roomIndex]; showRoute(room); roomIndex++; if (roomIndex > ROOMS_KEYS.length) { roomIndex = 0; } }); setLocation(START_LOCATION); } function getViewName() { // /index.html -> index var pathname = window.location.pathname; var parts = pathname.split('/'); var last = parts[parts.length - 1]; var view; if (last.length < 2) { view = 'index'; } else { view = last.substr(0, last.length - 5); } return view; } function hideKeyboard() { document.activeElement.blur(); $("input").blur(); }; function initView(viewName) { console.log('Init view', viewName); var views = { index: initIndexView }; initFunc = views[viewName]; initFunc(); } function onLoad() { var viewName = getViewName(); initView(viewName); } $(window).load(onLoad);
JavaScript
0.000001
@@ -519,20 +519,16 @@ '%0A %7D, - %0A 'TC @@ -3997,16 +3997,20 @@ S.length + - 1 ) %7B%0A
55887a887b188da7ee90123c65f1295559e03fa7
Update main.js
scripts/main.js
scripts/main.js
$(document).ready(function(){ // ---------- vars ---------- var imgsDir = "imgs/"; var extSlideshow = document.getElementById('extSlideshow'); // ---------- functions ---------- function createSlides(slides, slidesEl) { // populate slides & thumbnails var tempStr = ""; for (var i = 0; i < slides.length; i++) { tempStr += "<li style='padding-right: 15%;'><table width='100%' class='slideTable'><tr>"; tempStr += "<td width='30%'><img src='" + imgsDir + slides[i].img + "' /></td>"; tempStr += "<td class='text-center'><h3 style='font-weight: 700;'>" + slides[i].title + "</h3>"; tempStr += "<div class='slideText'>" + slides[i].descr + "</div>"; if (slides == extSlides) { // if setting up extensions slides tempStr += "<p><span class='slideSmallText'>Available for: </span>"; if (!!slides[i].chrome) { tempStr += "<a class='slideLink' href='" + slides[i].chrome + "' target='_blank'>Chrome</a> | "; } if (!!slides[i].firefox) { tempStr += "<a class='slideLink' href='" + slides[i].firefox + "' target='_blank'>Firefox</a> | "; } if (!!slides[i].opera) { tempStr += "<a class='slideLink' href='" + slides[i].opera + "' target='_blank'>Opera</a> | "; } } else if (slides == ossSlides) { // if setting up OSS slides tempStr += "<p><span class='slideSmallText'>On </span>"; if (!!slides[i].github) { tempStr += "<a class='slideLink' href='" + slides[i].github + "' target='_blank'>GitHub</a> | "; } if (!!slides[i].bitbucket) { tempStr += "<a class='slideLink' href='" + slides[i].bitbucket + "' target='_blank'>BitBucket</a> | "; } } // remove any trailing pipes if (tempStr.slice(-3) == " | ") { tempStr = tempStr.slice(0, tempStr.length - 3); } tempStr += "</p></td></tr></table></li>"; } slidesEl.innerHTML = tempStr; } // ---------- event handlers ---------- // ---------- start ---------- $.getScript("https://raw.github.com/username/repo/master/src/file.js", function () { /* do something when loaded */ fontSwitcher(['Anton#g', 'Verdana', 'sans-serif'], '.contentHeader'); fontSwitcher(['Schoolbell#g', 'sans-serif'], '.footer'); fontSwitcher(['Exo#g', 'Verdana', 'sans-serif'], '#navbar'); }); createSlides(extSlides, extSlideshow); createSlides(ossSlides, ossSlideshow); $('#extSlideshow').bxSlider({ mode: 'fade', speed: 1200, auto: true, pause: 5200, autoHover: true }); $('#ossSlideshow').bxSlider({ mode: 'fade', speed: 1200, auto: true, pause: 6000, autoHover: true }); });
JavaScript
0.000001
@@ -2224,56 +2224,60 @@ http -s :// -raw.github.com/username/repo/master/src/file +freginold.github.io/fontSwitcher/fontSwitcher.min .js%22
0cf33bd0a824f1f6be676956adf5d3f004953e4f
Fix race condition between FB.child_added and createRecord
web/static/js/app.js
web/static/js/app.js
window.App = Ember.Application.create({}); App.Router.map(function(){ this.resource('insight', { path: ':insight_id' }, function(){ this.route('chart'); this.route('describe'); this.route('comment'); }); this.resource('queries', { path: '/query' }, function(){ this.route('new'); this.resource('query', { path: ':query_id' }); }); this.route('views'); this.route('schemas'); this.route('functions'); }); App.ObjectTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } }); App.FirebaseAdapter = DS.Adapter.extend({ baseRef: "https://caravela.firebaseio.com/", emptyPromise: function(result){ // resolve immediatly we'll update the store // via push as the records come in result = result || {}; return new Ember.RSVP.Promise(function(resolve, reject) { resolve(result); }); }, refForType: function(type){ return new Firebase(this.get('baseRef')).child( Em.String.pluralize(type.typeKey) ); }, createRecord: function(store, type, record){ var serializer = store.serializerFor(type.typeKey); var data = serializer.serialize(record, { includeId: true }); var ref = this.refForType(type); return new Ember.RSVP.Promise(function(resolve) { var childRef = ref.push( data ); record.id = childRef.name(); resolve(record); }); }, updateRecord: function(store, type, record){ var serializer = store.serializerFor(type.typeKey); var data = serializer.serialize(record, { includeId: true }); var ref = this.refForType(type).child(data.id); return new Ember.RSVP.Promise(function(resolve,reject) { ref.set( data, function(err){ if(err){ reject(err); }else{ resolve(data); } } ); }); }, find: function(store, type, id){ console.log(arguments) return this.emptyPromise({'id': id}); }, findAll: function(store, type){ console.log('finding') var ref = new Firebase(this.get('baseRef')).child( Em.String.pluralize(type.typeKey) ); var controller = this; console.log('finding all', ref.toString()) ref.on('child_added', function(snapshot){ var record = snapshot.val(); record.id = snapshot.name(); console.log('adding', record) store.push(type, record); }); /* ref.on('child_removed', function(snapshot){ controller.removeItem(snapshot.name()); }); */ ref.on('child_changed', function(snapshot){ var record = snapshot.val(); record.id = snapshot.name(); store.push(type, record); }); return this.emptyPromise(); } }); Ember.Table.RowArrayProxy.reopen({ rowContent: function() { return []; }.property('content.@each') });
JavaScript
0.000004
@@ -715,16 +715,17 @@ com/%22,%0A%0A +%0A emptyP @@ -991,24 +991,46 @@ tion(type)%7B%0A + console.log(type)%0A return n @@ -1443,30 +1443,28 @@ );%0A -record +data .id = childR @@ -1478,29 +1478,81 @@ ();%0A + %0A -resolve(record +console.log(%22adding%22, type.typeKey, data)%0A resolve(data );%0A%0A @@ -2084,35 +2084,8 @@ d)%7B%0A - console.log(arguments)%0A @@ -2166,35 +2166,8 @@ e)%7B%0A - console.log('finding')%0A @@ -2299,55 +2299,9 @@ is;%0A - console.log('finding all', ref.toString()) %0A + @@ -2416,44 +2416,204 @@ ();%0A +%0A -console.log('adding', record)%0A +// schedule in next loop so that if this was called because%0A // of createRecord we preform an update rather than a creating%0A // a duplicate.%0A Em.run.next(null, function()%7B%0A @@ -2640,16 +2640,36 @@ ecord);%0A + %7D); %0A%0A%0A %7D);%0A
c4155a6c8032eb398f818d3b987a3af8cc41dd13
Update amazon.js
web.to.plex/scripts/amazon.js
web.to.plex/scripts/amazon.js
// Web to Plex - Toloka Plugin // Aurthor(s) - @ephellon (2019) /* Minimal Required Layout * script { url: string, init: function => ({ type:string, title:string, year:number|null|undefined }) } */ alert('Running amazon.js [GitHub]'); // REQUIRED [script:object]: The script object let script = { // REQUIRED [script.url]: this is what you ask Web to Plex access to; currently limited to a single domain "url": "*://*.amazon.com/*", // PREFERRED [script.ready]: a function to determine that the page is indeed ready "ready": () => !$('[data-automation-id="imdb-rating-badge"], #most-recent-reviews-content > *:first-child').empty, // REQUIRED [script.init]: it will always be fired after the page and Web to Plex have been loaded // OPTIONAL [ready]: if using script.ready, Web to Plex will pass a boolean of the ready state "init": (ready) => { let Y, R = RegExp; let title = $('[data-automation-id="title"], #aiv-content-title, .dv-node-dp-title') .first.textContent .replace(/(?:\(.+?\)|(\d+)|\d+\s+seasons?\s+(\d+))\s*$/gi, '') .trim(), // REQUIRED [title:string] // you have access to the exposed "helper.js" file within the extension year = !(Y = $('[data-automation-id="release-year-badge"], .release-year')).empty? Y.first.textContent.trim(): +(R.$1 || R.$2 || YEAR), // PREFERRED [year:number, null, undefined] image = getComputedStyle( $('.av-bgimg__div, div[style*="sgp-catalog-images"]').first ).backgroundImage, // the rest of the code is up to you, but should be limited to a layout similar to this type = script.getType(); // REQUIRED [{ type:'movie', 'show'; title:string; year:number }] // PREFERRED [{ image:string; IMDbID:string; TMDbID:string, number; TVDbID:string, number }] return { type, title, year, image }; }, // OPTIONAL: the rest of this code is purely for functionality "getType": () => { return !$('[data-automation-id*="seasons"], [class*="seasons"], [class*="episodes"], [class*="series"]').empty? 'tv': 'movie' }, };
JavaScript
0.000003
@@ -210,46 +210,8 @@ */%0A%0A -alert('Running amazon.js %5BGitHub%5D');%0A%0A // R
9be344a18fb6e17e17e32406f693be36553e0367
Refactor statements to function call
web/js/coordinator-console.js
web/js/coordinator-console.js
/** * Created by nkmathew on 05/07/2016. */ var source = $("#email-list-template").html(); function addEmailToList() { var inputboxVal = $('#email-input-box').val(); if (inputboxVal.trim() == '') { $('#email-input-box').focus(); return; } var email = inputboxVal + '@students.jkuat.ac.ke'; var template = Handlebars.compile(source); var html = template({email: email}); $('#email-list-section').append(html); $('.email-delete-btn').click(function () { $(this).closest('.email-line').remove(); }); $(this).val(''); } $(document).ready(function () { $("#email-input-box").keyup(function (e) { var template = Handlebars.compile(source); if (e.keyCode == 13) { addEmailToList(); } }); $('#btn-add-email').click(addEmailToList); $("#btn-invite-sender").click(function () { var emailList = []; $('.email-address a').each(function () { emailList.push($(this).html()); }); if (emailList.length == 0) { $('#email-input-box').focus(); return; } $("#btn-invite-sender").spin({color: 'black'}); $.ajax({ type: 'POST', url: '/site/send-signup-links', data: { 'email-list': JSON.stringify(emailList), }, success: function () { $('.alert-box .msg').html('Signup links sent successfully'); $('.alert-box').addClass('alert-success'); $('.alert-box').show(); $("#alert-box").fadeTo(3000, 500).slideUp(500, function () { $("#alert-box").hide(); }); // Remove spinner $("#btn-invite-sender").spin(false); // Clear list $('.email-line').remove(); }, error: function (xhr, status, error) { $("#btn-invite-sender").spin(false); $('.alert-box .msg').html('<h4>' + error + '</h4><br/>' + xhr.responseText); $('.alert-box').addClass('alert-danger'); $('.alert-box').show(); }, }); }); $("#profile-form").submit(function (e) { $("#btn-submit-profile").spin({color: 'grey'}); var url = '/site/profile'; $.ajax({ type: 'POST', url: url, data: $("#profile-form").serialize(), success: function (data) { // Remove spinner $("#btn-submit-profile").spin(false); }, error: function (xhr, status, error) { $("#btn-invite-sender").spin(false); $('.alert-box .msg').html('<h4>' + error + '</h4><br/>' + xhr.responseText); $('.alert-box').addClass('alert-danger'); $('.alert-box').show(); }, }); e.preventDefault(); }); $('#btn-refresh-sent-invites').click(function () { $('#content-sent-invites').load('/site/list-sent-invites'); $('#content-sent-invites').spin(BIG_SPINNER); }) });
JavaScript
0.000001
@@ -1477,33 +1477,20 @@ -$('. alert --box .msg').html +Success ('Si @@ -1525,253 +1525,8 @@ ');%0D -%0A $('.alert-box').addClass('alert-success');%0D%0A $('.alert-box').show();%0D%0A $(%22#alert-box%22).fadeTo(3000, 500).slideUp(500, function () %7B%0D%0A $(%22#alert-box%22).hide();%0D%0A %7D);%0D %0A%0D%0A
8798e672394dd089aef892c9787a0bb31e23fe3d
修正亂鬥營利紀錄插入時的 data
server/arena.js
server/arena.js
'use strict'; import { _ } from 'meteor/underscore'; import { dbArena } from '/db/dbArena'; import { dbArenaFighters, MAX_MANNER_SIZE, getAttributeNumber } from '/db/dbArenaFighters'; import { dbArenaLog } from '/db/dbArenaLog'; import { dbCompanies } from '/db/dbCompanies'; import { dbLog } from '/db/dbLog'; import { debug } from '/server/imports/debug'; export function startArenaFight() { console.log('start arena fight...'); const lastArenaData = dbArena.findOne({}, { sort: { beginDate: -1 }, fields: { _id: 1 } }); const arenaId = lastArenaData._id; const fighterListBySequence = dbArenaFighters .find( { arenaId: arenaId }, { sort: { agi: -1, createdAt: 1 } } ) .map((arenaFighter) => { arenaFighter.totalInvest = ( arenaFighter.hp + arenaFighter.sp + arenaFighter.atk + arenaFighter.def + arenaFighter.agi ); arenaFighter.hp = getAttributeNumber('hp', arenaFighter.hp); arenaFighter.sp = getAttributeNumber('sp', arenaFighter.sp); arenaFighter.atk = getAttributeNumber('atk', arenaFighter.atk); arenaFighter.def = getAttributeNumber('def', arenaFighter.def); arenaFighter.agi = getAttributeNumber('agi', arenaFighter.agi); arenaFighter.currentHp = arenaFighter.hp; arenaFighter.currentSp = arenaFighter.sp; return arenaFighter; }); debug.log('startArenaFight', fighterListBySequence); //輸家companyId陣列,依倒下的順序排列 const loser = []; //獲得收益的紀錄用hash const gainProfitHash = {}; const arenaLogBulk = dbArenaLog.rawCollection().initializeUnorderedBulkOp(); //log次序 let sequence = 0; //回合數 let round = 1; //直到戰到剩下一人為止 while (loser.length < fighterListBySequence.length - 1) { //超過十萬回合後自動中止 if (round > 500) { console.log('round > 500!'); break; } //所有參賽者依序攻擊 for (const attacker of fighterListBySequence) { //跳過已倒下參賽者的行動 if (attacker.currentHp <= 0) { continue; } //依此攻擊者的攻擊優先順序取得防禦者 let defender; for (const attackTargetIndex of attacker.attackSequence) { defender = fighterListBySequence[attackTargetIndex]; if (defender && defender.currentHp > 0) { break; } } if (! defender || defender.currentHp <= 0) { continue; } const arenaLog = { arenaId: arenaId, sequence: sequence, round: round, companyId: [attacker.companyId, defender.companyId], attackerSp: attacker.currentSp }; //決定使用的招式 arenaLog.attackManner = Math.floor((Math.random() * MAX_MANNER_SIZE) + 1); //決定使用特殊攻擊還是普通攻擊 if (attacker.currentSp >= attacker.spCost) { const randomSp = Math.floor((Math.random() * 10) + 1); if (attacker.spCost >= randomSp) { attacker.currentSp -= attacker.spCost; arenaLog.attackManner *= -1; } } //決定造成的傷害 arenaLog.damage = 0; //特殊攻擊時傷害等於攻擊者atk if (arenaLog.attackManner < 0) { arenaLog.damage = attacker.atk; } else { const randomAgi = Math.floor((Math.random() * 100) + 1); if (randomAgi > 95 || attacker.agi + randomAgi >= defender.agi) { arenaLog.damage = Math.max(attacker.atk - defender.def, 1); } } //若有造成傷害 if (arenaLog.damage > 0) { defender.currentHp -= arenaLog.damage; // hp降到0或0以下則進入loser if (defender.currentHp <= 0) { loser.push(defender.companyId); //取得擊倒盈利 arenaLog.profit = defender.totalInvest; if (_.isNumber(gainProfitHash[attacker.companyId])) { gainProfitHash[attacker.companyId] += defender.totalInvest; } else { gainProfitHash[attacker.companyId] = defender.totalInvest; } } } arenaLog.defenderHp = defender.currentHp; arenaLogBulk.insert(arenaLog); sequence += 1; } //回合結束,所有存活者回復一點sp _.each(fighterListBySequence, (fighter) => { if (fighter.currentHp > 0) { fighter.currentSp = Math.min(fighter.currentSp + 1, fighter.sp); } }); round += 1; } //插入戰鬥紀錄 if (fighterListBySequence.length > 1) { arenaLogBulk.execute(); } //若有任何擊倒收益,則插入一般紀錄 if (_.size(gainProfitHash) > 0) { const logBulk = dbLog.rawCollection().initializeUnorderedBulkOp(); _.each(gainProfitHash, (profit, companyId) => { logBulk.insert({ logType: '亂鬥營利', companyId: companyId, amount: profit }); dbCompanies.update(companyId, { $inc: { profit: profit } }); }); logBulk.execute(); } //取得所有存活者 const aliveList = _.filter(fighterListBySequence, (fighter) => { return fighter.currentHp > 0; }); //取得最後贏家 const sortedWinnerList = _.sortBy(aliveList, 'currentHp'); const sortedWinnerIdList = _.pluck(sortedWinnerList, 'companyId'); const winnerList = sortedWinnerIdList.concat(loser.reverse()); dbArena.update(arenaId, { $set: { winnerList: winnerList, endDate: new Date() } }); } export default startArenaFight;
JavaScript
0
@@ -4606,22 +4606,24 @@ -amount: +data: %7B profit + %7D %0A
3b67c7067aca6d7b1f1e6a8e6020a809402aa7ef
Change To Port: Heroku Fix
server/index.js
server/index.js
const express = require('express') const bodyParser = require('body-parser'); const path = require('path'); const { User, Template, Activity, History } = require('../db/mongoose-schemas.js') const app = express(); const logger = require('morgan'); const PORT = 3000; app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, '../client'))); //HANDLE GET REQUESTS app.get('/users', function(req, res) { var users = []; User.find({}, function(err, user) { if (err) console.log(err); users.push(user); }) .then(function() { console.log(users); res.send(users); }); }); app.get('/templates', function(req, res) { var templates = []; Template.find({}, function(err, template) { if (err) console.log(err); templates.push(template); }) .then(function() { console.log(templates); res.send(templates); }); }); app.get('/activities', function(req, res) { var activities = []; Activity.find({}, function(err, activity) { if (err) console.log(err); activities.push(activity); }) .then(function() { console.log(activities); res.send(activities); }); }); app.get('/histories', function(req, res) { var histories = []; History.find({}, function(err, history) { if (err) console.log(err); Histories.push(history); }) .then(function() { console.log(histories); res.send(histories); }); }); //HANDLE POST REQUESTS app.post('/users', function(req, res) { console.log(req.body); User.create(req.body); res.send('Posted User'); }); app.post('/templates', function(req, res) { console.log(req.body); Template.create(req.body); res.send('Posted Template'); }); app.post('/activities', function(req, res) { console.log(req.body); Activity.create(req.body); res.send('Posted Activity'); }); app.post('/histories', function(req, res) { console.log(req.body); History.create(req.body); res.send('Posted History'); }); app.listen(PORT, function() { console.log(`connected to http://localhost:${PORT}`); });
JavaScript
0.000002
@@ -245,25 +245,83 @@ ');%0A -const +%0A%0Aapp.set('port', (process.env. PORT -= +%7C%7C 3000 +));%0Aconst PORT = app.get('port') ;%0A%0Aa @@ -2127,20 +2127,30 @@ og(%60 -connected to +Node app is running on htt
5b98988df71ddbe4b25de7511ea942101d5b0e3b
Fix index.js
server/index.js
server/index.js
const Express = require('express'); const Path = require('path'); const Server = Express(); // handle some redirections var redirect_map = require('./redirect-map.json'); Server.locals.redirect_map = redirect_map; for (var key in redirect_map) { Server.get(key, (req, res) => { res.redirect(301, Server.locals.redirect_map[req.path]); }); } /** * Check that server is requested securely middle-ware * * @param {object} request - Express request object * @param {object} response - Express response object * @param {function} next - Express next function * * @return {object} - Express object */ const ForwardSSL = ( request, response, next ) => { if( request.headers['x-forwarded-proto'] === 'https' ) { return next(); } response.redirect(`https://${ request.headers.host }${ request.originalUrl }`); }; /** * Start server */ Server // First we make sure all requests come through HTTPS .all( '*', ForwardSSL ) // Let's make sure we had the password passed in .get( '*', AddFakePassword ) // Then we add dynamic routes that overwrite static ones .get( '/dynamic/', ( request, response ) => { response.send(' 🔥 Dynamic routing works 🎈🚀😍 '); }) // Now static assets .use( Express.static( Path.normalize(`${ __dirname }/../site/`) ) ) // In the end we catch all missing requests .get( '*', ( request, response ) => { response.status( 404 ); response.sendFile( Path.normalize(`${ __dirname }/../site/404/index.html`) ); }) // Now let’s start this thing! .listen( 8080, () => { console.log(`Server listening on port 8080`); });
JavaScript
0.001282
@@ -871,16 +871,17 @@ %60);%0A%7D;%0A%0A +%0A /**%0A * S @@ -988,89 +988,8 @@ )%0A%0A -%09// Let's make sure we had the password passed in%0A%09.get( '*', AddFakePassword )%0A%0A %09//
79590afd5227421a5f9471a1b33aa2cab64227cd
Update server to run on port 3000
server/index.js
server/index.js
const express = require('express'); const path = require('path'); const app = express(); app.use(express.static(path.join(__dirname, 'build'))); app.get('/', function (req, res) { res.sendFile(path.join(__dirname, '..', 'build', 'index.html')); }); app.listen(80); console.log('Listening to port 80');
JavaScript
0
@@ -87,31 +87,28 @@ );%0A%0A -app.use(express.static( +const buildFolder = path @@ -123,16 +123,22 @@ dirname, + '..', 'build' @@ -138,16 +138,53 @@ 'build') +;%0A%0Aapp.use(express.static(buildFolder ));%0A%0Aapp @@ -244,32 +244,19 @@ oin( -__dirname, '..', 'build' +buildFolder , 'i @@ -285,17 +285,19 @@ .listen( -8 +300 0);%0Acons @@ -327,9 +327,11 @@ ort -8 +300 0');
fc647c79538f83f446a874108db63bc6582a62b7
add file.pizza
server/index.js
server/index.js
var compress = require('compression') var cors = require('cors') var debug = require('debug')('instant') var downgrade = require('downgrade') var express = require('express') var fs = require('fs') var http = require('http') var https = require('https') var jade = require('jade') var parallel = require('run-parallel') var path = require('path') var twilio = require('twilio') var unlimited = require('unlimited') var url = require('url') var config = require('../config') var CORS_WHITELIST = [ 'http://instant-io.herokuapp.com', 'https://instant-io.herokuapp.com', 'http://instant.rom1504.fr', 'http://whiteboard.webtorrent.io' ] var secret, secretKey, secretCert try { secret = require('../secret') secretKey = fs.readFileSync(path.join(__dirname, '../secret/instant.io.key')) secretCert = fs.readFileSync(path.join(__dirname, '../secret/instant.io.chained.crt')) } catch (err) {} var app = express() var httpServer = http.createServer(app) var httpsServer if (secretKey && secretCert) { httpsServer = https.createServer({ key: secretKey, cert: secretCert }, app) } unlimited() // Templating app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'jade') app.set('x-powered-by', false) app.engine('jade', jade.renderFile) app.use(compress()) app.use(function (req, res, next) { // Force SSL if (config.isProd && req.protocol !== 'https') { return res.redirect('https://' + (req.hostname || 'instant.io') + req.url) } // Redirect www to non-www if (config.isProd && req.hostname === 'www.instant.io') { return res.redirect('https://instant.io' + req.url) } // Strict transport security (to prevent MITM attacks on the site) if (config.isProd) { res.header('Strict-Transport-Security', 'max-age=31536000') } // Add cross-domain header for fonts, required by spec, Firefox, and IE. var extname = path.extname(url.parse(req.url).pathname) if (['.eot', '.ttf', '.otf', '.woff', '.woff2'].indexOf(extname) >= 0) { res.header('Access-Control-Allow-Origin', '*') } // Prevents IE and Chrome from MIME-sniffing a response. Reduces exposure to // drive-by download attacks on sites serving user uploaded content. res.header('X-Content-Type-Options', 'nosniff') // Prevent rendering of site within a frame. res.header('X-Frame-Options', 'DENY') // Enable the XSS filter built into most recent web browsers. It's usually // enabled by default anyway, so role of this headers is to re-enable for this // particular website if it was disabled by the user. res.header('X-XSS-Protection', '1; mode=block') // Force IE to use latest rendering engine or Chrome Frame res.header('X-UA-Compatible', 'IE=Edge,chrome=1') next() }) app.use(express.static(path.join(__dirname, '../static'))) app.get('/', function (req, res) { res.render('index', { title: 'Instant.io - Streaming file transfer over WebTorrent' }) }) // Fetch new ice_servers from twilio token regularly var iceServers var twilioClient try { twilioClient = twilio(secret.twilio.accountSid, secret.twilio.authToken) } catch (err) {} function updateIceServers () { twilioClient.tokens.create({}, function (err, token) { if (err) return error(err) if (!token.ice_servers) { return error(new Error('twilio response ' + token + ' missing ice_servers')) } iceServers = token.ice_servers .filter(function (server) { var urls = server.urls || server.url return urls && !/^stun:/.test(urls) }) iceServers.unshift({ url: 'stun:23.21.150.121' }) // Support new spec (`RTCIceServer.url` was renamed to `RTCIceServer.urls`) iceServers = iceServers.map(function (server) { if (server.urls === undefined) server.urls = server.url return server }) }) } if (twilioClient) { setInterval(updateIceServers, 60 * 60 * 4 * 1000).unref() updateIceServers() } app.get('/rtcConfig', cors({ origin: function (origin, cb) { var allowed = CORS_WHITELIST.indexOf(origin) >= 0 || /https?:\/\/localhost(:|\/)/.test(origin) cb(null, allowed) } }), function (req, res) { if (!iceServers) res.status(404).send({ iceServers: [] }) else res.send({ iceServers: iceServers }) }) app.get('*', function (req, res) { res.status(404).render('error', { title: '404 Page Not Found - Instant.io', message: '404 Not Found' }) }) // error handling middleware app.use(function (err, req, res, next) { error(err) res.status(500).render('error', { title: '500 Server Error - Instant.io', message: err.message || err }) }) var tasks = [ function (cb) { httpServer.listen(config.ports.http, config.host, cb) } ] if (httpsServer) { tasks.push(function (cb) { httpsServer.listen(config.ports.https, config.host, cb) }) } parallel(tasks, function (err) { if (err) throw err debug('listening on port %s', JSON.stringify(config.ports)) downgrade() }) function error (err) { console.error(err.stack || err.message || err) }
JavaScript
0.000003
@@ -633,16 +633,63 @@ rent.io' +,%0A 'http://file.pizza',%0A 'https://file.pizza' %0A%5D%0A%0Avar
a059fa5a67e26ca0805c4e5402bdc7eef4eb251c
remove extension 404 middleware
server/start.js
server/start.js
'use strict' const path = require('path') const express = require('express') const bodyParser = require('body-parser') const {resolve} = require('path') const passport = require('passport') const PrettyError = require('pretty-error') const finalHandler = require('finalhandler') // PrettyError docs: https://www.npmjs.com/package/pretty-error // Bones has a symlink from node_modules/APP to the root of the app. // That means that we can require paths relative to the app root by // saying require('APP/whatever'). // // This next line requires our root index.js: const pkg = require('APP') const app = express() if (!pkg.isProduction && !pkg.isTesting) { // Logging middleware (dev only) app.use(require('volleyball')) } // Pretty error prints errors all pretty. const prettyError = new PrettyError // Skip events.js and http.js and similar core node files. prettyError.skipNodeFiles() // Skip all the trace lines about express' core and sub-modules. prettyError.skipPackage('express') module.exports = app // Session middleware - compared to express-session (which is what's used in the Auther workshop), cookie-session stores sessions in a cookie, rather than some other type of session store. // Cookie-session docs: https://www.npmjs.com/package/cookie-session .use(require('cookie-session')({ name: 'session', keys: [process.env.SESSION_SECRET || 'an insecure secret key'], })) // Body parsing middleware .use(bodyParser.urlencoded({ extended: true })) .use(bodyParser.json()) // Authentication middleware .use(passport.initialize()) .use(passport.session()) // Serve static files from ../public .use(express.static(resolve(__dirname, '..', 'public'))) // Serve our api - ./api also requires in ../db, which syncs with our database .use('/api', require('./api')) // any requests with an extension (.js, .css, etc.) turn into 404 .use((req, res, next) => { if (path.extname(req.path).length) { const err = new Error('Not found') err.status = 404 next(err) } else { next() } }) // Send index.html for anything else. .get('/*', (_, res) => res.sendFile(resolve(__dirname, '..', 'public', 'index.html'))) // Error middleware interceptor, delegates to same handler Express uses. // https://github.com/expressjs/express/blob/master/lib/application.js#L162 // https://github.com/pillarjs/finalhandler/blob/master/index.js#L172 .use((err, req, res) => { console.error(prettyError.render(err)) finalHandler(req, res)(err) }) if (module === require.main) { // Start listening only if we're the main module. // // https://nodejs.org/api/modules.html#modules_accessing_the_main_module const server = app.listen( pkg.port, () => { console.log(`--- Started HTTP Server for ${pkg.name} ---`) const { address, port } = server.address() const host = address === '::' ? 'localhost' : address const urlSafeHost = host.includes(':') ? `[${host}]` : host console.log(`Listening on http://${urlSafeHost}:${port}`) } ) } // This check on line 64 is only starting the server if this file is being run directly by Node, and not required by another file. // Bones does this for testing reasons. If we're running our app in development or production, we've run it directly from Node using 'npm start'. // If we're testing, then we don't actually want to start the server; 'module === require.main' will luckily be false in that case, because we would be requiring in this file in our tests rather than running it directly.
JavaScript
0.000001
@@ -1819,16 +1819,19 @@ ))%0A%0A // + // any req @@ -1887,16 +1887,19 @@ to 404%0A + // .use((r @@ -1920,18 +1920,21 @@ =%3E %7B%0A +// + if (path @@ -1959,24 +1959,27 @@ .length) %7B%0A + // const e @@ -2007,16 +2007,19 @@ ound')%0A + // err @@ -2033,16 +2033,19 @@ = 404%0A + // nex @@ -2052,16 +2052,19 @@ t(err)%0A + // %7D els @@ -2073,20 +2073,23 @@ %7B%0A +// + next()%0A %7D @@ -2084,22 +2084,28 @@ next()%0A + // %7D%0A + // %7D)%0A%0A /
266d9b39ee5ba3441518335daf4733ca0c2d2827
Update store signature on server
server/store.js
server/store.js
var fs = require('fs'), miso = require('../server/miso.util.js'); // Simulated store // TODO: This should interact with the API once we have it. module.exports = function(scope) { // Add a binding object, so we can block till ready scope._misoReadyBinding = miso.readyBinderFactory(); return { load: function(type, args){ var r, loadDone; fs.readFile("client/user.json", {encoding:'utf8'}, function(err, data){ r = JSON.parse(data); loadDone(); }); return { then: function(cb){ loadDone = scope._misoReadyBinding.bind(function(){ cb(r); }); } }; }, save: function(type, args){ console.log('Save', type, args); } }; };
JavaScript
0.000001
@@ -622,23 +622,73 @@ n(type, -args) +model)%7B%0A%09%09%09var v = model.isValid();%0A%09%09%09if(v === true) %7B%0A +%09 %09%09%09conso @@ -712,14 +712,69 @@ pe, -args); +model);%0A%09%09%09%7D else %7B%0A%09%09%09%09console.log('Model invalid', v);%0A%09%09%09%7D %0A%09%09%7D
76684d270f48dfef92304d0d5a1c0924105411d3
add reviews subroute to users router
server/users.js
server/users.js
'use strict' const db = require('APP/db') const User = db.model('users') const {mustBeLoggedIn, forbidden} = require('./auth.filters') module.exports = require('express').Router() .get('/', // The forbidden middleware will fail *all* requests to list users. // Remove it if you want to allow anyone to list all users on the site. // // If you want to only let admins list all the users, then you'll // have to add a role column to the users table to support // the concept of admin users. // // will address this later by having the session ID get the admin info forbidden('listing users is not allowed'), (req, res, next) => User.findAll({}) .then(users => res.send(users)) .catch(next)) .post('/', (req, res, next) => User.create(req.body) .then(user => res.status(201).send(user)) .catch(next)) .get('/:id', mustBeLoggedIn, (req, res, next) => User.findById(req.params.id) .then(user => { if (!user) res.status(404).send('no user found') else res.json(user) }) .catch(next)) .put('/:id', mustBeLoggedIn, (req, res, next) => User.update(req.body, { where: { id: req.params.id }, returning: true, plainText: true }) .then(user => res.json(user[1])) .catch(next)) .delete('/:id', mustBeLoggedIn, (req, res, next) => User.destroy({ where: { id: req.params.id } }) .then(deletedUser => res.send('user deleted')) .catch(next)) // put created to update user // delete created to destroy user
JavaScript
0
@@ -66,16 +66,62 @@ 'users') +%0Aconst reviews = require('APP/server/reviews') %0A%0Aconst @@ -1644,70 +1644,137 @@ t))%0A -%0A// put created to update user%0A// delete created to destroy user%0A + .use('/:id/reviews', (req, res, next) =%3E %7B%0A req.queryIdString = 'user'%0A req.queryId = req.params.id%0A next()%0A %7D, reviews) %0A
bf22d763df75200e31b77c655f190e4f0cdb5dc1
Update sidebars.js (#602)
website/sidebars.js
website/sidebars.js
module.exports = { Sidebar: [ "getting_started", { type: "category", label: "Guides", collapsed: false, items: [ "cookbooks/testing", //"cookbooks/refresh", ], }, { type: "category", label: "Concepts", items: [ "concepts/providers", "concepts/reading", "concepts/combining_providers", "concepts/provider_observer", // "concepts/computed", { type: "category", label: "Modifiers", items: [ "concepts/modifiers/family", "concepts/modifiers/auto_dispose", ], }, ], }, { type: "category", label: "Migration", collapsed: false, items: ["migration/0.13.0_to_0.14.0"], }, { type: "category", label: "Official examples", items: [ { type: "link", label: "Counter", href: "https://github.com/rrousselGit/river_pod/tree/master/examples/counter", }, { type: "link", label: "Todo list", href: "https://github.com/rrousselGit/river_pod/tree/master/examples/todos", }, { type: "link", label: "Marvel API", href: "https://github.com/rrousselGit/river_pod/tree/master/examples/marvel", }, ], }, { type: "category", label: "Third party examples", items: [ { type: "link", label: "Android Launcher", href: "https://github.com/lohanidamodar/fl_live_launcher", }, { type: "link", label: "Worldtime Clock", href: "https://github.com/lohanidamodar/flutter_worldtime", }, { type: "link", label: "Dictionary App", href: "https://github.com/lohanidamodar/fl_dictio", }, { type: "link", label: "Firebase Starter", href: "https://github.com/lohanidamodar/flutter_firebase_starter/tree/feature/riverpod", }, { type: "link", label: "Time Tracking App (with Firebase)", href: "https://github.com/bizz84/starter_architecture_flutter_firebase", }, { type: "link", label: "ListView paging with search", href: "https://github.com/tbm98/flutter_loadmore_search", }, { type: "link", label: "Resocoder's Weather Bloc to Weather Riverpod", href: "https://github.com/campanagerald/flutter-bloc-library-v1-tutorial", }, { type: "link", label: "Blood Pressure Tracker App", href: "https://github.com/UrosTodosijevic/blood_pressure_tracker", }, { type: "link", label: "Firebase Authentication with Riverpod Following Flutter DDD Architecture Pattern", href: "https://github.com/pythonhubpy/firebase_authentication_flutter_DDD", }, ], }, { type: "category", label: "Api references", collapsed: false, items: [ { type: "link", label: "riverpod", href: "https://pub.dev/documentation/riverpod/latest/riverpod/riverpod-library.html", }, { type: "link", label: "flutter_riverpod", href: "https://pub.dev/documentation//flutter_riverpod/latest/flutter_riverpod/flutter_riverpod-library.html", }, { type: "link", label: "hooks_riverpod", href: "https://pub.dev/documentation/hooks_riverpod/latest/hooks_riverpod/hooks_riverpod-library.html", }, ], }, ], };
JavaScript
0
@@ -2359,32 +2359,229 @@ type: %22link%22,%0A + label: %22Firebase Phone Authentication with Riverpod%22,%0A href: %22https://github.com/julienlebren/flutter_firebase_phone_auth_riverpod%22,%0A %7D,%0A %7B%0A type: %22link%22,%0A label:
2c3ea015bfad934560a2abdaa4a637a53b37794c
Address sources of update leaks in event daemon
websocket/daemon.js
websocket/daemon.js
var config = require('./config'); var set = require('simplesets').Set; var queue = require('qu'); var WebSocketServer = require('ws').Server; var wss_receiver = new WebSocketServer({host: config.get_host, port: config.get_port}); var wss_sender = new WebSocketServer({host: config.post_host, port: config.post_port}); var messages = new queue(); var followers = new set(); var pollers = new set(); var max_queue = config.max_queue || 50; var long_poll_timeout = config.long_poll_timeout || 60000; var message_id = Date.now(); if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str){ return this.slice(0, str.length) == str; }; } messages.catch_up = function (client) { this.each(function (message) { if (message.id > client.last_msg) client.got_message(message); }); }; messages.post = function (channel, message) { message = { id: ++message_id, channel: channel, message: message }; this.push(message); if (this.length > max_queue) this.shift(); followers.each(function (client) { client.got_message(message); }); pollers.each(function (request) { request.got_message(message); }); return message.id; }; messages.last = function () { return this.tail().id; }; wss_receiver.on('connection', function (socket) { socket.channel = null; socket.last_msg = 0; var commands = { start_msg: function (request) { socket.last_msg = request.start; }, set_filter: function (request) { var filter = {}; if (Array.isArray(request.filter) && request.filter.every(function (channel, index, array) { if (typeof channel != 'string') return false; filter[channel] = true; return true; })) { socket.filter = request.filter.length == 0 ? true : filter; followers.add(socket); messages.catch_up(socket); } else { socket.send(JSON.stringify({ status: 'error', code: 'invalid-filter', message: 'invalid filter: ' + request.filter })); } }, }; socket.got_message = function (message) { if (socket.filter === true || message.channel in socket.filter) socket.send(JSON.stringify(message)); socket.last_msg = message.id; }; socket.on('message', function (request) { try { request = JSON.parse(request); } catch (err) { socket.send(JSON.stringify({ status: 'error', code: 'syntax-error', message: err.message })); return; } request.command = request.command.replace(/-/g, '_'); if (request.command in commands) commands[request.command](request); else socket.send(JSON.stringify({ status: 'error', code: 'bad-command', message: 'bad command: ' + request.command })); }); socket.on('close', function(code, message) { followers.remove(socket); }); }); wss_sender.on('connection', function (socket) { var commands = { post: function (request) { if (typeof request.channel != 'string') return { status: 'error', code: 'invalid-channel' }; return { status: 'success', id: messages.post(request.channel, request.message) }; }, last_msg: function (request) { return { status: 'success', id: message_id, }; } }; socket.on('message', function (request) { try { request = JSON.parse(request); } catch (err) { socket.send(JSON.stringify({ status: 'error', code: 'syntax-error', message: err.message })); return; } request.command = request.command.replace(/-/g, '_'); if (request.command in commands) socket.send(JSON.stringify(commands[request.command](request))); else socket.send(JSON.stringify({ status: 'error', code: 'bad-command', message: 'bad command: ' + request.command })); }); }); var url = require('url'); require('http').createServer(function (req, res) { var parts = url.parse(req.url, true); if (!parts.pathname.startsWith('/channels/')) { res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('404 Not Found'); return; } var channels = parts.pathname.slice(10).split('|'); req.channels = {}; req.last_msg = parseInt(parts.query.last); if (isNaN(req.last_msg)) req.last_msg = 0; if (!channels.every(function (channel, index, array) { if (!channel || !channel.length) return false; return req.channels[channel] = true; })) req.channels = true; req.on('close', function () { pollers.remove(req); }); req.got_message = function (message) { if (req.channels === true || message.channel in req.channels) { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(message)); pollers.remove(req); return true; } return false; }; var got = false; messages.each(function (message) { if (!got && message.id > req.last_msg) got = req.got_message(message); }); if (!got) { pollers.add(req); res.setTimeout(long_poll_timeout, function () { pollers.remove(req); res.writeHead(504, {'Content-Type': 'application/json'}); res.end('{"error": "timeout"}'); }); } }).listen(config.http_port, config.http_host);
JavaScript
0
@@ -4907,24 +4907,25 @@ turn;%0A %7D%0A +%0A var chan @@ -4964,24 +4964,198 @@ split('%7C');%0A + if (channels.length == 1 && !channels%5B0%5D.length) %7B%0A res.writeHead(400, %7B'Content-Type': 'text/plain'%7D);%0A res.end('400 Bad Request');%0A return;%0A %7D%0A%0A req.chan @@ -5260,29 +5260,24 @@ g = 0;%0A%0A -if (! channels.eve @@ -5273,21 +5273,23 @@ hannels. -every +forEach (functio @@ -5302,107 +5302,19 @@ nnel -, index, array) %7B%0A if (!channel %7C%7C !channel.length)%0A return false;%0A return +) %7B%0A req @@ -5350,29 +5350,8 @@ %7D) -) req.channels = true ;%0A%0A @@ -5480,33 +5480,8 @@ if ( -req.channels === true %7C%7C mess @@ -6189,12 +6189,13 @@ .http_host); +%0A
aa8a3518ab36054d2666688d12850e290628f454
Fix confirm buttons display
ui/src/admin/components/UsersTable.js
ui/src/admin/components/UsersTable.js
import React, {PropTypes} from 'react' import UserRow from 'src/admin/components/UserRow' import EmptyRow from 'src/admin/components/EmptyRow' import FilterBar from 'src/admin/components/FilterBar' const UsersTable = ({users, hasRoles, isEditingUsers, onClickCreate, onEdit, onSave, onCancel, onDelete, onFilter}) => ( <div className="panel panel-info"> <FilterBar type="users" onFilter={onFilter} isEditing={isEditingUsers} onClickCreate={onClickCreate} /> <div className="panel-body"> <table className="table v-center admin-table"> <thead> <tr> <th>User</th> {hasRoles && <th>Roles</th>} <th>Permissions</th> <th></th> </tr> </thead> <tbody> { users.length ? users.filter((u) => !u.hidden).map((user, i) => <UserRow key={i} user={user} onEdit={onEdit} onSave={onSave} onCancel={onCancel} onDelete={onDelete} isEditing={user.isEditing} isNew={user.isNew} />) : <EmptyRow tableName={'Users'} /> } </tbody> </table> </div> </div> ) const { arrayOf, bool, func, shape, string, } = PropTypes UsersTable.propTypes = { users: arrayOf(shape({ name: string.isRequired, roles: arrayOf(shape({ name: string, })), permissions: arrayOf(shape({ name: string, scope: string.isRequired, })), })), isEditingUsers: bool, onClickCreate: func.isRequired, onEdit: func.isRequired, onSave: func.isRequired, onCancel: func.isRequired, addFlashMessage: func.isRequired, hasRoles: bool.isRequired, onDelete: func.isRequired, onFilter: func, } export default UsersTable
JavaScript
0.000001
@@ -817,11 +817,9 @@ ter( -(u) +u =%3E @@ -837,17 +837,12 @@ map( -( user -, i) =%3E%0A @@ -889,17 +889,31 @@ key=%7B -i +user.links.self %7D%0A
eb6bc748838fa14ccfc05ba7ab162a5182cd8446
Fix resize animation height caluculation to work in Safari.
www/javascript/swat-disclosure.js
www/javascript/swat-disclosure.js
function SwatDisclosure(id) { this.image = document.getElementById(id + '_img'); this.input = document.getElementById(id + '_input'); this.div = document.getElementById(id); this.animate_div = this.div.firstChild.nextSibling.firstChild; // prevent closing during opening animation and vice versa this.semaphore = false; // get initial state if (this.input.value == 'opened') { this.open(); } else { this.close(); } } SwatDisclosure.open_text = 'open'; SwatDisclosure.close_text = 'close'; SwatDisclosure.prototype.toggle = function() { if (this.opened) { this.closeWithAnimation(); } else { this.openWithAnimation(); } } SwatDisclosure.prototype.close = function() { YAHOO.util.Dom.removeClass(this.div, 'swat-disclosure-control-opened'); YAHOO.util.Dom.addClass(this.div, 'swat-disclosure-control-closed'); this.semaphore = false; this.image.src = 'packages/swat/images/swat-disclosure-closed.png'; this.image.alt = SwatDisclosure.open_text; this.input.value = 'closed'; this.opened = false; } SwatDisclosure.prototype.closeWithAnimation = function() { if (this.semaphore) return; this.animate_div.style.overflow = 'hidden'; this.animate_div.style.height = ''; var attributes = { height: { to: 0 } }; var animation = new YAHOO.util.Anim(this.animate_div, attributes, 0.25); this.semaphore = true; animation.onComplete.subscribe(SwatDisclosure.handleClose, this); animation.animate(); this.image.src = 'packages/swat/images/swat-disclosure-closed.png'; this.image.alt = SwatDisclosure.open_text; this.input.value = 'closed'; this.opened = false; } SwatDisclosure.prototype.open = function() { YAHOO.util.Dom.removeClass(this.div, 'swat-disclosure-control-closed'); YAHOO.util.Dom.addClass(this.div, 'swat-disclosure-control-opened'); this.semaphore = false; this.image.src = 'packages/swat/images/swat-disclosure-open.png'; this.image.alt = SwatDisclosure.close_text; this.input.value = 'opened'; this.opened = true; } SwatDisclosure.prototype.openWithAnimation = function() { if (this.semaphore) return; YAHOO.util.Dom.removeClass(this.div, 'swat-disclosure-control-closed'); YAHOO.util.Dom.addClass(this.div, 'swat-disclosure-control-opened'); // get display height this.animate_div.style.visibility = 'hidden'; this.animate_div.style.overflow = 'hidden'; this.animate_div.style.display = 'block'; this.animate_div.style.position = 'absolute'; this.animate_div.style.height = ''; var height = this.animate_div.offsetHeight; this.animate_div.style.height = '0'; this.animate_div.style.position = 'static'; this.animate_div.style.visibility = 'visible'; var attributes = { height: { to: height, from: 0 } }; var animation = new YAHOO.util.Anim(this.animate_div, attributes, 0.5, YAHOO.util.Easing.easeOut); this.semaphore = true; animation.onComplete.subscribe(SwatDisclosure.handleOpen, this); animation.animate(); this.image.src = 'packages/swat/images/swat-disclosure-open.png'; this.image.alt = SwatDisclosure.close_text; this.input.value = 'opened'; this.opened = true; } SwatDisclosure.handleClose = function(type, args, disclosure) { YAHOO.util.Dom.removeClass(disclosure.div, 'swat-disclosure-control-opened'); YAHOO.util.Dom.addClass(disclosure.div, 'swat-disclosure-control-closed'); disclosure.semaphore = false; } SwatDisclosure.handleOpen = function(type, args, disclosure) { // allow font resizing to work again disclosure.animate_div.style.height = ''; disclosure.semaphore = false; }
JavaScript
0
@@ -2236,16 +2236,121 @@ height%0A +%09this.animate_div.parentNode.style.overflow = 'hidden';%0A%09this.animate_div.parentNode.style.height = '0';%0A %09this.an @@ -2380,32 +2380,32 @@ ity = 'hidden';%0A - %09this.animate_di @@ -2480,55 +2480,8 @@ k';%0A -%09this.animate_div.style.position = 'absolute';%0A %09thi @@ -2624,63 +2624,123 @@ yle. -position = 'static';%0A%09this.animate_div.style.visibility +visibility = 'visible';%0A%09this.animate_div.parentNode.style.height = '';%0A%09this.animate_div.parentNode.style.overflow = '
b9eeba80f524039c436990c2573083da39807fed
add background gray to global file
src/components/organisms/FileMostRecent/index.js
src/components/organisms/FileMostRecent/index.js
import React, {PropTypes} from 'react'; import styled from 'styled-components'; import {palette} from 'styled-theme'; import Divider from 'material-ui/Divider'; import Paper from 'material-ui/Paper'; import {Grid, Row, Col} from 'react-flexbox-grid'; import Copyright from 'material-ui/svg-icons/action/copyright'; import { IconLink, Link, FileHeader, TitleSection, FileCarousel, FileComment, HomeTitle } from 'components'; import * as FileService from '../../../services/FileService'; const Wrapper = styled.div ` &::before{ content: ""; background: ${palette('grayscale',0)}; height: 100vh; width: 100%; display: block; position: absolute; margin-top: -100vh; z-index: -1; box-shadow: 0 -22px 180px 80px ${palette('grayscale',0)}; } margin-top: 80px; /*box-shadow: 0 -22px 180px 50vh rgba(266,231,231,0.99);*/ .bar-middle{ position: relative; margin-top: -20px; background: #316971 !important; padding: 10px; text-align: center; line-height: 0; svg{ color: white !important; } &::before { content: ""; width: 0; height: 0; border-style: solid; border-width: 0 10px 10px 10px; border-color: transparent transparent #316971 transparent; position: relative; top: -48px; left: 22px; } } .background-1{ background: rgba(248, 248, 248, 0.97) !important; } .background-2{ background: rgba(248, 248, 248, 0.93) !important; } ` class FileMostRecent extends React.Component { constructor(props) { super(props); this.state = { comments: [] } } componentWillMount() { this.renderCommments(); } renderCommments = () => { FileService.getComments(this.props.id).then(comments => { this.setState({comments: comments}); }) } render() { return ( <Wrapper> <div className="bar-middle"><Copyright /></div> <Paper zDepth={0} className="background-1"> <FileCarousel data={this.props.data} title="Fichas relacionadas"/> </Paper> <Paper zDepth={0} className="paper-padding-2 background-2"> <FileComment id={this.props.id} comments={this.state.comments} update={this.renderCommments}/> </Paper> </Wrapper> ) } } export default FileMostRecent;
JavaScript
0
@@ -564,16 +564,56 @@ kground: + rgba(242,242,242,0.93);%0A /*background: $%7Bpalet @@ -631,16 +631,18 @@ le',0)%7D; +*/ %0A heigh @@ -748,32 +748,91 @@ 1;%0A box-shadow: + 0 -22px 180px 80px rgba(242,242,242,0.93);%0A /*box-shadow: 0 -22px 180px 8 @@ -861,16 +861,18 @@ le',0)%7D; +*/ %0A%7D%0A%0A mar
a964141d4059d06bb635efd642bb47e119cd3e24
Add check before calculating labelStyle/labelProps
src/components/victory-scatter/helper-methods.js
src/components/victory-scatter/helper-methods.js
import { values, pick, omit, defaults } from "lodash"; import { Helpers, Events } from "victory-core"; import Scale from "../../helpers/scale"; import Domain from "../../helpers/domain"; import Data from "../../helpers/data"; export default { getBaseProps(props, fallbackProps) { props = Helpers.modifyProps(props, fallbackProps, "scatter"); const calculatedValues = this.getCalculatedValues(props); const { data, style, scale } = calculatedValues; const childProps = { parent: { style: style.parent, scale, data, height: props.height, width: props.width }}; for (let index = 0, len = data.length; index < len; index++) { const datum = data[index]; const eventKey = datum.eventKey; const x = scale.x(datum.x1 || datum.x); const y = scale.y(datum.y1 || datum.y); const dataProps = { x, y, datum, index, scale, size: this.getSize(datum, props, calculatedValues), symbol: this.getSymbol(datum, props), style: this.getDataStyles(datum, style.data) }; const text = this.getLabelText(props, datum, index); const labelStyle = this.getLabelStyle(style.labels, dataProps) || {}; const labelProps = { style: labelStyle, x, y: y - (labelStyle.padding || 0), text, index, scale, datum: dataProps.datum, textAnchor: labelStyle.textAnchor, verticalAnchor: labelStyle.verticalAnchor || "end", angle: labelStyle.angle }; childProps[eventKey] = { data: dataProps, labels: labelProps }; } return childProps; }, getCalculatedValues(props) { const defaultStyles = props.theme && props.theme.scatter && props.theme.scatter.style ? props.theme.scatter.style : {}; const style = Helpers.getStyles(props.style, defaultStyles, "auto", "100%"); const data = Events.addEventKeys(props, Data.getData(props)); const range = { x: Helpers.getRange(props, "x"), y: Helpers.getRange(props, "y") }; const domain = { x: Domain.getDomain(props, "x"), y: Domain.getDomain(props, "y") }; const scale = { x: Scale.getBaseScale(props, "x").domain(domain.x).range(range.x), y: Scale.getBaseScale(props, "y").domain(domain.y).range(range.y) }; const z = props.bubbleProperty || "z"; return {data, scale, style, z}; }, getDataStyles(datum, style) { const stylesFromData = omit(datum, [ "x", "y", "z", "size", "symbol", "name", "label" ]); const baseDataStyle = defaults({}, stylesFromData, style); return Helpers.evaluateStyle(baseDataStyle, datum); }, getLabelText(props, datum, index) { const propsLabel = Array.isArray(props.labels) ? props.labels[index] : Helpers.evaluateProp(props.labels, datum); return datum.label || propsLabel; }, getLabelStyle(labelStyle, dataProps) { const { datum, size, style } = dataProps; const matchedStyle = pick(style, ["opacity", "fill"]); const padding = labelStyle.padding || size * 0.25; const baseLabelStyle = defaults({}, labelStyle, matchedStyle, {padding}); return Helpers.evaluateStyle(baseLabelStyle, datum); }, getSymbol(data, props) { if (props.bubbleProperty) { return "circle"; } const symbol = data.symbol || props.symbol; return Helpers.evaluateProp(symbol, data); }, getBubbleSize(datum, props, calculatedValues) { const {data, z} = calculatedValues; const getMaxRadius = () => { const minPadding = Math.min(...values(Helpers.getPadding(props))); return Math.max(minPadding, 5); }; const zData = data.map((point) => point.z); const zMin = Math.min(...zData); const zMax = Math.max(...zData); const maxRadius = props.maxBubbleSize || getMaxRadius(); const maxArea = Math.PI * Math.pow(maxRadius, 2); const area = ((datum[z] - zMin) / (zMax - zMin)) * maxArea; const radius = Math.sqrt(area / Math.PI); return Math.max(radius, 1); }, getSize(data, props, calculatedValues) { let size; if (data.size) { size = typeof data.size === "function" ? data.size : Math.max(data.size, 1); } else if (typeof props.size === "function") { size = props.size; } else if (data[calculatedValues.z]) { size = this.getBubbleSize(data, props, calculatedValues); } else { size = Math.max(props.size, 1); } return Helpers.evaluateProp(size, data); } };
JavaScript
0
@@ -271,24 +271,62 @@ backProps) %7B + // eslint-disable-line max-statements %0A props = @@ -1135,24 +1135,62 @@ um, index);%0A + if (!text && !props.events) %7B%0A const @@ -1255,24 +1255,26 @@ %7C %7B%7D;%0A + + const labelP @@ -1286,24 +1286,26 @@ = %7B%0A + style: label @@ -1307,24 +1307,26 @@ labelStyle,%0A + x,%0A @@ -1332,16 +1332,18 @@ + y: y - ( @@ -1372,24 +1372,26 @@ 0),%0A + text,%0A @@ -1396,15 +1396,19 @@ + + index,%0A + @@ -1410,32 +1410,34 @@ scale,%0A + datum: d @@ -1456,24 +1456,26 @@ um,%0A + textAnchor: @@ -1497,16 +1497,18 @@ Anchor,%0A + @@ -1567,16 +1567,18 @@ + + angle: l @@ -1595,27 +1595,31 @@ angle%0A + %7D;%0A + childP @@ -1645,16 +1645,18 @@ + data: da @@ -1664,16 +1664,18 @@ aProps,%0A + @@ -1695,27 +1695,37 @@ Props%0A + + %7D;%0A + %7D%0A %7D%0A re
f062a7e0868ec8918767e32978a83c81c45a0c04
Add a 10s timeout to reachable-url
resolve/urls.js
resolve/urls.js
#!/usr/bin/env node 'use strict'; var stdin = process.openStdin(); var async = require('async'); var reachableUrl = require('reachable-url') if (require.main === module) { main(); } else { module.exports = resolveUrls; } function main() { stdin.setEncoding('utf8'); stdin.on('data', function(err, data) { if(err) { return console.error(err); } console.log(JSON.stringify(resolveUrls(JSON.parse(data)), null, 4)); }); } function resolveUrls(urls, cb) { async.mapLimit(urls, 20, resolveUrl, function(err, d) { if(err) { return cb(err); } cb(null, d.filter(id)); }); } function resolveUrl(d, cb) { reachableUrl(d.url).then(({ url }) => { d.url = url cb(null, d) }).catch(err => { console.error(err) cb(); }) } function id(a) {return a;}
JavaScript
0.000014
@@ -719,16 +719,36 @@ rl(d.url +, %7B timeout: 10000 %7D ).then((
bc1c878037f8b5d823a3c7b28d1bc5139dca5c4a
fix typo
server/lib/points_usdan.js
server/lib/points_usdan.js
//points of usdan, schwartz, brown, perlman points_usdan = [ { "id": "schwartz_c01", "coordinate":new Point(42.367527, -71.257568), "type": "crossing", }, // buildings behind usdan { "id":"schwartz_e01", "coordinate":new Point(42.367605, -71.257126), "type":"entrance" }, { "id":"brown_e01", "coordinate":new Point(42.367286, -71.257305), "type":"entrance" }, { "id":"pearlman_e01", "coordinate":new Point(42.367498, -71.257879), "type":"entrance" }, { "id":"pearlman_e02", "coordinate":new Point(42.367492, -71.258030), "type":"entrance" }, // usdan { "id": "usdan_e01", "coordinate":new Point(42.368067, -71.256704), "type": "entrance", }, { "id": "usdan_c01", "coordinate":new Point(42.367368, -71.256159), "type": "crossing", }, { "id": "usdan_c02", "coordinate":new Point(42.367578, -71.256685), "type": "crossing", }, { "id": "usdan_c03", "coordinate":new Point(42.367693, -71.257275), "type": "crossing", }, { "id": "usdan_c04", "coordinate":new Point(42.367903, -71.256899), "type": "crossing", }, { "id": "usdan_c05", "coordinate":new Point(42.368476, -71.256315), "type": "crossing", }, { "id": "usdan_c06", "coordinate":new Point(42.368588, -71.256671), "type": "crossing", }, { "id": "usdan_c07", "coordinate":new Point(42.368636, -71.256826), "type": "crossing", }, { "id": "usdan_c08", "coordinate":new Point(42.368299, -71.256765), "type": "crossing", }, { "id": "usdan_c09", "coordinate":new Point(42.368562, -71.257014), "type": "crossing", }, { "id": "usdan_c10", "coordinate":new Point(42.368353, -71.257438), "type": "crossing", }, { "id":"levin_e01", "coordinate":new Point(42.368117, -71.256926), "type":"entrance" }, { "id":"levin_e02", "coordinate":new Point(42.367992, -71.256964), "type":"entrance" }, ] function Point(x,y) { this.x = x; this.y = y; }
JavaScript
0.999991
@@ -2027,17 +2027,16 @@ ance%22%0A%09%7D -, %0A%5D%0Afunct
fd8c2ab9d04cc7530609ca9e0cc9dafd5d184010
Add "cardsInList" helper
tpl/src/helpers/eachCardInList.js
tpl/src/helpers/eachCardInList.js
'use strict'; module.exports = function() { // silence is golden };
JavaScript
0.000001
@@ -39,34 +39,362 @@ ion( -) %7B%0A // silence is golden +listId, options) %7B%0A var ret = ''%0A , listIdNameMap = %7B%7D;%0A%0A (this.allLists %7C%7C %5B%5D).forEach(function(l) %7B%0A listIdNameMap%5Bl.id%5D = l.name;%0A %7D);%0A%0A (this.allCards %7C%7C %5B%5D)%0A .filter(function(c) %7B%0A return listId === c.idList %7C%7C listId === listIdNameMap%5Bc.idList%5D;%0A %7D)%0A .forEach(function(c) %7B%0A ret += options.fn(c);%0A %7D);%0A%0A return ret; %0A%7D;%0A
ca64b6f321be38ac05c2fdc2eab3dded7f50a9af
Add a bit of usability
web/source/javascripts/all.js
web/source/javascripts/all.js
//= require lodash //= require victor //= require d3 //= require jquery //= require angular //= require_tree . $(function () { var width = 400, height = width/2, radius = width/2, duration = 750 var arc = d3.svg.arc() .outerRadius(radius - 10) .innerRadius(100); var pie = d3.layout.pie() .sort(null) .startAngle(-Math.PI/2) .endAngle(Math.PI/2) .value(function(d) { return d.probability }); var svg = d3.select('#prediction svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + width / 2 + ',' + height + ')'); function update(data) { var arcs = svg.selectAll('.arc').data(pie(data)); // create new elements var new_arcs = arcs.enter().append('g') .attr('class', function(d) { return 'arc ' + d.data.party }) new_arcs.append('path') .attr('d', arc) .each(function(d) { this._current = d }); // for arc tween new_arcs.append('text') .attr('transform', function(d) { return 'translate(' + arc.centroid(d) + ')' }) .attr('dy', '.35em') .style('text-anchor', 'middle') .text(function(d) { return d.data.party }); // update existing elements arcs.attr('class', function(d) { return 'arc ' + d.data.party }) arcs.select('path') .transition() .duration(duration) .attrTween('d', arcTween); arcs.select('text') .text(function(d) { return d.data.party }) .transition() .duration(duration) .attr('transform', function(d) { return 'translate(' + arc.centroid(d) + ')' }); // remove elements without data arcs.exit().remove(); } d3.select('#submit_text').on('click', function() { var text = d3.select('#text_query').node().value; console.log(text); d3.json('/api/predict') .header("Content-Type", "application/x-www-form-urlencoded") .post("text="+text, function(error, data) { console.log(data) data = data.prediction data.forEach(function(d) { d.probability += d.probability }) update(data) }); }); d3.select('#submit_url').on('click', function() { var text = d3.select('#url_query').node().value; console.log(text) d3.json('/api/predict') .header("Content-Type", "application/x-www-form-urlencoded") .post("url="+text, function(error, data) { console.log(data) data = data.prediction data.forEach(function(d) { d.probability += d.probability }) update(data) }); }); update([ {probability: 0.25, party: '?'}, {probability: 0.25, party: '?'}, {probability: 0.25, party: '?'}, {probability: 0.25, party: '?'} ]); function arcTween(d, i, a) { var i = d3.interpolate(this._current, d); this._current = i(0); return function(t) { return arc(i(t)); } } });
JavaScript
0.000371
@@ -2429,16 +2429,121 @@ g(text)%0A + if (!/%5Ehttp/.test(text)) text = 'http://'+text;%0A d3.select('#url_query').node().value = text;%0A d3
9fb8addb7cd04029d8a203640890e66475584e39
move click action handling into dedicated function
prismatic.js
prismatic.js
var INTERVAL_MS_CHECK_CURRRENT_TIME = 10; var MARGIN_S_CHECK_MOVE_ACTION = (INTERVAL_MS_CHECK_CURRRENT_TIME / 1000) * 2; /** * Base object, with option init */ var Prismatic = function (options) { this.registeredAction = { 'move': [], 'click': [], }; if (!options) { options = {}; } this.videoId = options.videoID || 'my-video'; this.videoClass = options.videoClass || 'video-js'; this.jsonFileUrl = options.jsonFileUrl || 'data.json'; this.debug = options.debug || false; } /** * Check if a click (coord. X & Y) is in a specific zone */ Prismatic.prototype.isInZone = function (X, Y, zone) { return (X >= zone.leftX && X <= zone.rightX && Y >= zone.topY && Y <= zone.bottomY); } /** * Check if a time is inside a specific a time, given an error margin */ Prismatic.prototype.isInTiming = function (from, to, current) { return (current >= from - MARGIN_S_CHECK_MOVE_ACTION && current <= to + MARGIN_S_CHECK_MOVE_ACTION); } /** * Handle each "move" action */ Prismatic.prototype.handleMoveAction = function (player) { var prismatic = this; setInterval(function () { var currentTimeValue = player.currentTime(); $.each(prismatic.registeredAction['move'], function (key, val) { if (currentTimeValue >= val.from - MARGIN_S_CHECK_MOVE_ACTION && currentTimeValue <= val.from + MARGIN_S_CHECK_MOVE_ACTION) { player.currentTime(val.to); } }); }, INTERVAL_MS_CHECK_CURRRENT_TIME); } /** * Print log only if debug flag is set to true */ Prismatic.prototype.LOG = function (...data) { if (this.debug) { console.log(...data) } } /** * Print log with error level, only if debug flag is set to true */ Prismatic.prototype.ERROR = function (...data) { if (this.debug) { console.error(...data) } } /** * Start everything to handle each wanted action */ Prismatic.prototype.start = function () { var prismatic = this; videojs('#' + this.videoId).ready(function () { var player = this; window._player = player; // Debug purpose $.getJSON(prismatic.jsonFileUrl, function (data) { $.each(data.events, function (key, val) { if (prismatic.registeredAction[val.type]) { prismatic.registeredAction[val.type].push(val); } else { prismatic.ERROR('Action type [' + val.type + '] doesn\'t exist !'); } }); prismatic.LOG(prismatic.registeredAction); /////////////////////////////////// // Handle move action /////////////////////////////////// prismatic.handleMoveAction(player); /////////////////////////////////// // Handle click action /////////////////////////////////// var videoCanva = $('.' + prismatic.videoClass); videoCanva.click(function (e) { $.each(prismatic.registeredAction['click'], function (key, val) { var actualZone = { "leftX": parseFloat(val.leftX) / parseFloat(data.baseData.baseWidth) * parseFloat(videoCanva.width()), "topY": val.topY / data.baseData.baseHeight * videoCanva.height(), "rightX": val.rightX / data.baseData.baseWidth * videoCanva.width(), "bottomY": parseFloat(val.bottomY) / parseFloat(data.baseData.baseHeight) * parseFloat(videoCanva.height()), }; if (prismatic.isInZone(e.clientX, e.clientY, actualZone) && prismatic.isInTiming(val.starting, val.ending, player.currentTime())) { if (val.jumpTo) { prismatic.LOG('Jump to : ' + val.jumpTo); player.currentTime(val.jumpTo); } } }); }); }); }); }
JavaScript
0
@@ -1450,24 +1450,1040 @@ T_TIME);%0A%7D%0A%0A +/**%0A * Handle each %22click%22 action%0A */%0APrismatic.prototype.handleClickAction = function (data, player) %7B%0A var prismatic = this;%0A var videoCanva = $('.' + prismatic.videoClass);%0A videoCanva.click(function (e) %7B%0A $.each(prismatic.registeredAction%5B'click'%5D, function (key, val) %7B%0A var actualZone = %7B%0A %22leftX%22: parseFloat(val.leftX) / parseFloat(data.baseData.baseWidth) * parseFloat(videoCanva.width()),%0A %22topY%22: val.topY / data.baseData.baseHeight * videoCanva.height(),%0A %22rightX%22: val.rightX / data.baseData.baseWidth * videoCanva.width(),%0A %22bottomY%22: parseFloat(val.bottomY) / parseFloat(data.baseData.baseHeight) * parseFloat(videoCanva.height()),%0A %7D;%0A%0A if (prismatic.isInZone(e.clientX, e.clientY, actualZone) && prismatic.isInTiming(val.starting, val.ending, player.currentTime())) %7B%0A if (val.jumpTo) %7B%0A prismatic.LOG('%5B' + val.name + '%5D Jump to : ' + val.jumpTo + 's');%0A player.currentTime(val.jumpTo);%0A %7D%0A %7D%0A %7D);%0A %7D);%0A%7D%0A%0A /**%0A * Print @@ -3700,928 +3700,48 @@ -var videoCanva = $('.' + prismatic.videoClass);%0A videoCanva.click(function (e) %7B%0A $.each(prismatic.registeredAction%5B'click'%5D, function (key, val) %7B%0A var actualZone = %7B%0A %22leftX%22: parseFloat(val.leftX) / parseFloat(data.baseData.baseWidth) * parseFloat(videoCanva.width()),%0A %22topY%22: val.topY / data.baseData.baseHeight * videoCanva.height(),%0A %22rightX%22: val.rightX / data.baseData.baseWidth * videoCanva.width(),%0A %22bottomY%22: parseFloat(val.bottomY) / parseFloat(data.baseData.baseHeight) * parseFloat(videoCanva.height()),%0A %7D;%0A%0A if (prismatic.isInZone(e.clientX, e.clientY, actualZone) && prismatic.isInTiming(val.starting, val.ending, player.currentTime())) %7B%0A if (val.jumpTo) %7B%0A prismatic.LOG('Jump to : ' + val.jumpTo);%0A player.currentTime(val.jumpTo);%0A %7D%0A %7D%0A %7D);%0A%0A %7D +prismatic.handleClickAction(data, player );%0A
5d364e35a57378aefe860e088206ac7486bf3d08
Fix missing directory
Jakefile.js
Jakefile.js
var fs = require('fs'), jasmine = require('jasmine-node'), browserify = require('browserify'); desc('Runs the tests against node.'); task('testNode', {async: true}, function () { console.log("Testing Node.js integration"); jasmine.executeSpecsInFolder({ specFolders: ['tests/specs'], onComplete: complete }); }); desc('Runs the tests against a browser (PhantomJS).'); task('testBrowser', ['browser'], {async: true}, function () { console.log("Testing browser integration"); jake.exec('phantomjs tests/run-jasmine.js tests/SpecRunner.html', {printStdout: true}, function () { complete(); }); }); desc('Builds the browser bundle.'); task('browser', function () { console.log("Building browser bundle"); var b = browserify(), w = fs.createWriteStream('dist/xmlserializer.js'); b.add('./lib/serializer.js'); b.bundle({ standalone: 'xmlserializer' }).pipe(w); }); task('test', ['testNode', 'testBrowser']); task('default', ['test', 'browser']);
JavaScript
0.000039
@@ -643,24 +643,44 @@ %7D);%0A%7D);%0A%0A +directory(%22dist%22);%0A%0A desc('Builds @@ -718,16 +718,26 @@ rowser', + %5B'dist'%5D, functio
d74d68541b2073855f8c2404373aba1dde1d3d3c
Set attachTo.setImmediate only once, for better minification.
setImmediate.js
setImmediate.js
(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; function addFromSetImmediateArguments(args) { var handler = args[0]; args[0] = undefined; tasksByHandle[nextHandle] = handler.bind.apply(handler, args); return nextHandle++; } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. global.setTimeout(runIfPresent.bind(undefined, handle), 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { task(); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function clearImmediate(handle) { delete tasksByHandle[handle]; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var getProto = Object.getPrototypeOf; var attachTo = getProto && getProto(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if (Object.prototype.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 attachTo.setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); process.nextTick(runIfPresent.bind(undefined, handle)); return handle; }; } else if (canUsePostMessage()) { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var loc = global.location; var origin = loc && loc.hostname || "*"; var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } // For non-IE10 modern browsers attachTo.setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); global.postMessage(messagePrefix + handle, origin); return handle; }; } else if (global.MessageChannel) { // For web workers, where supported var channel = new global.MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; attachTo.setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); channel.port2.postMessage(handle); return handle; }; } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 var html = doc.documentElement; attachTo.setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); return handle; }; } else { // For older browsers attachTo.setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); global.setTimeout(runIfPresent.bind(undefined, handle), 0); return handle; }; } attachTo.clearImmediate = clearImmediate; }(Function("return this")()));
JavaScript
0
@@ -250,16 +250,38 @@ ocument; +%0A var setImmediate; %0A%0A fu @@ -2548,33 +2548,24 @@ 0.9%0A -attachTo. setImmediate @@ -3739,33 +3739,24 @@ ers%0A -attachTo. setImmediate @@ -4214,33 +4214,24 @@ %7D;%0A%0A -attachTo. setImmediate @@ -4541,33 +4541,24 @@ nt;%0A -attachTo. setImmediate @@ -5280,25 +5280,16 @@ -attachTo. setImmed @@ -5487,24 +5487,66 @@ %7D;%0A %7D%0A%0A + attachTo.setImmediate = setImmediate;%0A attachTo
4fcb2e1b65c9ec5aa84107b01a208dfd77e88d4d
fix typo
Keyboard.js
Keyboard.js
define(["dojo/_base/lang", "dojo/_base/event", "dcl/dcl", "dojo/on", "dojo/keys", "dojo/dom-attr", "./_utils", "dui/_FocusMixin"], function (lang, event, dcl, on, keys, domAttr, utils, _FocusMixin) { return dcl(_FocusMixin, { // summary: // Specializes TreeMap to support keyboard navigation and accessibility. // tabIndex: String // Order fields are traversed when user hits the tab key tabIndex: "0", _setTabIndexAttr: "domNode", constructor: function () { }, postCreate: function () { this.own(on(this, "keydown", lang.hitch(this, this._onKeyDown))); this.own(on(this, "mousedown", lang.hitch(this, this._onMouseDown))); }, createRenderer: dcl.superCall(function (sup) { return function (item, level, kind) { var renderer = sup.call(this, item, level, kind); // on Firefox we need a tabindex on sub divs to let the keyboard event be dispatched // put -1 so that it is not tablable domAttr.set(renderer, "tabindex", "-1"); return renderer; }; }), _onMouseDown: function () { this.focus(); }, /* jshint -W074 */ _onKeyDown: function (e) { var selected = this.selectedItem; if (!selected) { // nothing selected selected we can't navigate return; } var renderer = this.itemToRenderer[this.getIdentity(selected)]; var parent = renderer.parentItem; var children, childrenI, selectedI; // we also need items to be sorted out if (e.keyCode !== keys.UP_ARROW && e.keyCode !== keys.NUMPAD_MINUS && e.keyCode !== keys.NUMPAD_PLUS) { children = (e.keyCode === keys.DOWN_ARROW) ? selected.children : parent.children; if (children) { childrenI = utils.initElements(children, lang.hitch(this, this._computeAreaForItem)).elements; selectedI = childrenI[children.indexOf(selected)]; childrenI.sort(function (a, b) { return b.size - a.size; }); } else { return; } } var newSelected; switch (e.keyCode) { case keys.LEFT_ARROW: newSelected = children[childrenI[Math.max(0, childrenI.index(selectedI) - 1)].index]; break; case keys.RIGHT_ARROW: newSelected = children[childrenI[Math.min(childrenI.length - 1, childrenI.indexOf(selectedI) + 1)].index]; break; case keys.DOWN_ARROW: newSelected = children[childrenI[0].index]; break; case keys.UP_ARROW: newSelected = parent; break; // TODO //case "+": case keys.NUMPAD_PLUS: if (!this._isLeaf(selected) && this.drillDown) { this.drillDown(renderer); event.stop(e); } break; // TODO //case "-": case keys.NUMPAD_MINUS: if (!this._isLeaf(selected) && this.drillUp) { this.drillUp(renderer); event.stop(e); } break; } if (newSelected) { if (!this._isRoot(newSelected)) { this.selectedItem = newSelected; event.stop(e); } } } }); });
JavaScript
0.999991
@@ -2048,16 +2048,18 @@ nI.index +Of (selecte
e9d53274d7764b22924a8779d77d17637c21f257
Add storage space stubs
source/datasources/TextDatasource.js
source/datasources/TextDatasource.js
const EventEmitter = require("events"); const hash = require("hash.js"); const Credentials = require("../credentials/Credentials.js"); const { credentialsAllowsPurpose } = require("../credentials/channel.js"); const { detectFormat, getDefaultFormat } = require("../io/formatRouter.js"); const { fireInstantiationHandlers, registerDatasource } = require("./register.js"); /** * @typedef {Object} AttachmentDetails * @property {String} id The attachment ID * @property {String} vaultID The vault ID * @property {String} name Base filename * @property {String} filename Full filename and path * @property {Number} size Size in bytes (0 if invalid) * @property {String|null} mime MIME type if available */ /** * @typedef {Object} LoadedVaultData * @property {VaultFormat} Format The vault format class that was detected * when reading encrypted vault contents * @property {Array.<String>} history Decrypted vault data */ /** * Datasource for text input and output * @memberof module:Buttercup */ class TextDatasource extends EventEmitter { /** * Constructor for the text datasource * @param {Credentials} credentials The credentials and configuration for * the datasource */ constructor(credentials) { super(); this._credentials = credentials; this._credentials.restrictPurposes([Credentials.PURPOSE_SECURE_EXPORT]); this._content = ""; this.type = "text"; fireInstantiationHandlers("text", this); } /** * Datasource credentials * @type {Credentials} * @readonly */ get credentials() { return this._credentials; } /** * Whether the datasource currently has content * Used to check if the datasource has encrypted content that can be * loaded. May be used when attempting to open a vault in offline mode. * @type {Boolean} * @memberof TextDatasource */ get hasContent() { return this._content && this._content.length > 0; } /** * Get attachment buffer * - Downloads the attachment contents into a buffer * @param {String} vaultID The ID of the vault * @param {String} attachmentID The ID of the attachment * @param {Credentials=} credentials Credentials to decrypt * the buffer, defaults to null (no decryption) * @returns {Promise.<Buffer|ArrayBuffer>} * @memberof TextDatasource */ getAttachment(vaultID, attachmentID, credentials = null) { return Promise.reject(new Error("Attachments not supported")); } /** * Get attachment details * @param {String} vaultID The ID of the vault * @param {String} attachmentID The ID of the attachment * @returns {AttachmentDetails} The attactment details * @memberof TextDatasource */ getAttachmentDetails(vaultID, attachmentID) { return Promise.reject(new Error("Attachments not supported")); } /** * Get the ID of the datasource * ID to uniquely identify the datasource and its parameters * @returns {String} A hasn of the datasource (unique ID) * @memberof TextDatasource */ getID() { const type = this.toObject().type; const content = type === "text" ? this._content : this.toString(); if (!content) { throw new Error("Failed getting ID: Datasource requires content for ID generation"); } return hash .sha256() .update(content) .digest("hex"); } /** * Load from the stored content using a password to decrypt * @param {Credentials} credentials The password or Credentials instance to decrypt with * @returns {Promise.<LoadedVaultData>} A promise that resolves with decrypted history * @throws {Error} Rejects if content is empty * @memberof TextDatasource */ load(credentials) { if (!this._content) { return Promise.reject(new Error("Failed to load vault: Content is empty")); } if (credentialsAllowsPurpose(credentials.id, Credentials.PURPOSE_DECRYPT_VAULT) !== true) { return Promise.reject(new Error("Provided credentials don't allow vault decryption")); } const Format = detectFormat(this._content); return Format.parseEncrypted(this._content, credentials).then(history => ({ Format, history })); } /** * Put attachment data * @param {String} vaultID The ID of the vault * @param {String} attachmentID The ID of the attachment * @param {Buffer|ArrayBuffer} buffer The attachment data * @param {Credentials=} credentials Credentials for * encrypting the buffer. If not provided, the buffer * is presumed to be in encrypted-form and will be * written as-is. * @returns {Promise} * @memberof TextDatasource */ putAttachment(vaultID, attachmentID, buffer, credentials = null) { return Promise.reject(new Error("Attachments not supported")); } /** * Remove an attachment * @param {String} vaultID The ID of the vault * @param {String} attachmentID The ID of the attachment * @returns {Promise} * @memberof TextDatasource */ removeAttachment(vaultID, attachmentID) { return Promise.reject(new Error("Attachments not supported")); } /** * Save archive contents with a password * @param {Array.<String>} history Archive history to save * @param {Credentials} credentials The Credentials instance to encrypt with * @returns {Promise.<string>} A promise resolving with the encrypted content * @memberof TextDatasource */ save(vaultCommands, credentials) { if (credentialsAllowsPurpose(credentials.id, Credentials.PURPOSE_ENCRYPT_VAULT) !== true) { return Promise.reject(new Error("Provided credentials don't allow vault encryption")); } return getDefaultFormat().encodeRaw(vaultCommands, credentials); } /** * Set the text content * @param {String} content The encrypted text content * @returns {TextDatasource} Self * @memberof TextDatasource */ setContent(content) { this._content = content || ""; return this; } /** * Whether or not the datasource supports attachments * @returns {Boolean} * @memberof TextDatasource */ supportsAttachments() { return false; } /** * Whether or not the datasource supports the changing of the master password * @returns {Boolean} True if the datasource supports password changing * @memberof TextDatasource */ supportsPasswordChange() { return false; } /** * Whether or not the datasource supports bypassing remote fetch operations * (offline support) * @returns {Boolean} True if content can be set to bypass fetch operations, * false otherwise * @memberof TextDatasource */ supportsRemoteBypass() { return false; } } registerDatasource("text", TextDatasource); module.exports = TextDatasource;
JavaScript
0.000001
@@ -2926,32 +2926,532 @@ rted%22));%0A %7D%0A%0A + /**%0A * Get the available storage space, in bytes%0A * @returns %7BNumber%7Cnull%7D Bytes of free space, or null if not%0A * available%0A * @memberof TextDatasource%0A */%0A getAvailableStorage() %7B%0A return Promise.resolve(null);%0A %7D%0A%0A /**%0A * Get the total storage space, in bytes%0A * @returns %7BNumber%7Cnull%7D Bytes of free space, or null if not%0A * available%0A * @memberof TextDatasource%0A */%0A getTotalStorage() %7B%0A return Promise.resolve(null);%0A %7D%0A%0A /**%0A * G
e730fbcbea887ddef8dc6f6be9ee97559dc8f9ea
Fix _decodePayload()
src/deep-resource/lib/Resource/LambdaResponse.js
src/deep-resource/lib/Resource/LambdaResponse.js
/** * Created by AlexanderC on 6/10/15. */ 'use strict'; import {Response} from './Response'; import {ValidationError} from './Exception/ValidationError'; /** * Response object */ export class LambdaResponse extends Response { /** * @param {*} args */ constructor(...args) { super(...args); this._originalResponse = null; this._logResult = null; // assure calling the very first! this._fillStatusCode(); let responsePayload = this._decodePayload(); this._fillData(responsePayload); this._fillError(responsePayload); } /** * @param {AWS.Response|null} response */ set originalResponse(response) { this._originalResponse = response; } /** * * @returns {AWS.Response|null} */ get originalResponse() { return this._originalResponse; } /** * @returns {Object} */ get headers() { if (!this._headers && this.originalResponse) { this._headers = this.originalResponse.httpResponse ? this.originalResponse.httpResponse.headers : {}; } return this._headers; } /** * @returns {String|null} */ get requestId() { if (!this._requestId && this.headers) { if (this.headers[Response.REQUEST_ID_HEADER.toLowerCase()]) { this._requestId = this.headers[Response.REQUEST_ID_HEADER.toLowerCase()]; } } return this._requestId; } /** * @param {Object|null} responsePayload * @private */ _fillData(responsePayload) { if (responsePayload && !this._request.async && !responsePayload.hasOwnProperty('errorMessage')) { this._data = responsePayload; } } /** * @param {Object|null} responsePayload * @private */ _fillError(responsePayload) { if (this._rawError) { this._error = this._rawError; } else if (!this._request.async) { if (!responsePayload) { this._error = new Error('There is no error nor payload in Lambda response'); } else if (responsePayload.hasOwnProperty('errorMessage')) { this._error = LambdaResponse.getPayloadError(responsePayload); } } else if (this._statusCode !== 202) { // check for failed async invocation this._error = new Error('Unknown async invocation error'); } } /** * @private */ _fillStatusCode() { if (this._rawData) { this._statusCode = parseInt(this._rawData.StatusCode || this._rawData.Status); } else { this._statusCode = 500; } } /** * @returns {Object|null} * @private */ _decodePayload() { let decodedPayload = null; if (this._rawData) { if (this._rawData.Payload) { decodedPayload = LambdaResponse._decodePayloadObject(this._rawData.Payload); // treat the case when error is stored in payload (nested) if (decodedPayload.hasOwnProperty('errorMessage')) { decodedPayload = LambdaResponse._decodeRawErrorObject(decodedPayload.errorMessage); } } else if (this._rawData.errorMessage) { decodedPayload = LambdaResponse._decodeRawErrorObject(this._rawData.errorMessage); } } return decodedPayload; } /** * @param {String|Object|*} rawError * @returns {Object|String|null} * @private */ static _decodeRawErrorObject(rawError) { let errorObj = rawError; if (typeof errorObj === 'string') { try { errorObj = JSON.parse(errorObj); } catch(e) { errorObj = { errorMessage: errorObj, // assume errorObj is the error message errorStack: (new Error('Unknown error occurred.')).stack, errorType: 'UnknownError', }; } } else { errorObj = errorObj || { errorMessage: 'Unknown error occurred.', errorStack: (new Error('Unknown error occurred.')).stack, errorType: 'UnknownError', }; } return errorObj; } /** * @returns {String} */ get logResult() { if (this._logResult) { return this._logResult; } if (this._rawData && this._rawData.hasOwnProperty('LogResult')) { this._logResult = this._decodeBase64(this._rawData.LogResult); } return this._logResult; } /** * @param {String} rawPayload * @returns {Object|String|null} * @private */ static _decodePayloadObject(rawPayload) { let payload = rawPayload; if (typeof rawPayload === 'string') { try { payload = JSON.parse(payload); } catch(e) {} } return payload; } /** * @param {Object} payload * @returns {Error|ValidationError|null} */ static getPayloadError(payload) { if (payload.hasOwnProperty('errorMessage')) { let error = null; if (LambdaResponse.isValidationError(payload)) { error = new ValidationError(payload.errorMessage, payload.validationErrors); } else { payload.errorType = payload.errorType || 'UnknownError'; payload.errorMessage = payload.errorMessage || 'Unknown error occurred.'; payload.errorStack = payload.errorStack || (new Error(payload.errorMessage)).stack; error = new Error(payload.errorMessage); // try to define a custom constructor name // fail silently in case of readonly property... try { Object.defineProperty(error, 'name', { value: payload.errorType, }); } catch (e) { } } try { Object.defineProperty(error, 'stack', { value: payload.errorStack, }); } catch (e) { } return error; } return null; } /** * @param {Object} payload * @returns {Boolean} */ static isValidationError(payload) { return payload.hasOwnProperty('errorType') && payload.hasOwnProperty('errorMessage') && payload.hasOwnProperty('validationErrors') && payload.errorType === LambdaResponse.VALIDATION_ERROR_TYPE; } /** * @returns {String} */ static get VALIDATION_ERROR_TYPE() { return 'ValidationError'; } /** * @param {String} str * @returns {String} * @private */ _decodeBase64(str) { if (typeof Buffer !== 'undefined') { str = new Buffer(str, 'base64').toString('utf8'); } else if (typeof atob !== 'undefined') { str = atob(str); } return str; } }
JavaScript
0.000013
@@ -2802,24 +2802,42 @@ codedPayload + && decodedPayload .hasOwnPrope
67f28d5eff3ef16bfc524b3588adb9cdf9358c06
Allow for pinning columns to the left hand side of the table.
src/main/webapp/resources/js/pages/projects/linelist/reducers/fields.js
src/main/webapp/resources/js/pages/projects/linelist/reducers/fields.js
import { List, fromJS } from "immutable"; /* Special handler for formatting the sample Name Column; */ const sampleNameColumn = { sort: "asc", pinned: "left", cellRenderer: "SampleNameRenderer", checkboxSelection: true, headerCheckboxSelection: true, headerCheckboxSelectionFilteredOnly: true, editable: false }; /** * Fields need to be formatted properly to go into the column headers. * @param {array} cols * @returns {*} */ const formatColumns = cols => cols.map((f, i) => ({ field: f.label, headerName: f.label, lockPinned: true, ...(i === 0 ? sampleNameColumn : {}) })); export const types = { LOAD: "METADATA/FIELDS/LOAD_REQUEST", LOAD_ERROR: "METADATA/FIELDS/LOAD_ERROR", LOAD_SUCCESS: "METADATA/FIELDS/LOAD_SUCCESS" }; export const initialState = fromJS({ initializing: true, // Is the API call currently being made error: false, // Was there an error making the api call} fields: List() // List of metadata fields ==> used for table headers }); export const reducer = (state = initialState, action = {}) => { switch (action.type) { case types.LOAD: return state.set("initializing", true).set("error", false); case types.LOAD_SUCCESS: return state .set("initializing", false) .set("error", false) .delete("fields") .set("fields", fromJS(formatColumns(action.fields))); case types.LOAD_ERROR: return state .set("initializing", false) .set("error", true) .set("fields", List()); default: return state; } }; export const actions = { load: () => ({ type: types.LOAD }), success: fields => ({ type: types.LOAD_SUCCESS, fields }), error: error => ({ type: types.LOAD_ERROR, error }) };
JavaScript
0
@@ -6,20 +6,20 @@ t %7B -List, fromJS +, List %7D f @@ -318,16 +318,36 @@ e: false +,%0A lockPinned: true %0A%7D;%0A%0A/** @@ -564,30 +564,8 @@ el,%0A - lockPinned: true,%0A
4958040fc01a6754616bcf5f083a14cea248cab5
add index to support distinct operation
serverbuild/mongo_setup.js
serverbuild/mongo_setup.js
db.triangles.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1, triangle : "2dsphere" } ); db.triangles.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1 } ); db.hourlydata.createIndex( { measurement_key: 1, valid_date : 1, valid_time : 1 } ); db.hourlydata.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1 } );
JavaScript
0
@@ -347,20 +347,75 @@ eter_name : 1 %7D );%0D%0A +db.hourlydata.createIndex( %7B measurement_key : 1 %7D );%0D%0A
1c213d57d1783e6edee5a12d725d9368d49c4509
version bump
web/webpack/webpack.common.js
web/webpack/webpack.common.js
const SPECMATE_VERSION = '0.2.5' const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const GitRevisionPlugin = require('git-revision-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const helpers = require('./helpers'); const gitRevisionPlugin = new GitRevisionPlugin({ commithashCommand: 'rev-parse --short HEAD' }); module.exports = { entry: { 'polyfills': './src/polyfills.ts', 'vendor': './src/vendor.ts', 'specmate': './src/main.ts', 'assets': './src/assets.ts', }, resolve: { extensions: ['.ts', '.js'] }, module: { rules: [{ test: /\.ts$/, loaders: [{ loader: 'awesome-typescript-loader', options: { configFileName: helpers.root('src', 'tsconfig.json') } }, 'angular2-template-loader'] }, { test: /\.(html|svg)$/, loader: 'html-loader', exclude: [helpers.root('node_modules', 'flag-icon-css'), helpers.root('node_modules', 'font-awesome')] }, { test: /\.svg/, loader: 'file-loader?name=img/[name]_[hash].[ext]', include: [helpers.root('node_modules', 'flag-icon-css'), helpers.root('node_modules', 'font-awesome')] }, { test: /\.(html|svg)$/, loader: 'string-replace-loader', query: { search: '@@version', replace: SPECMATE_VERSION } }, { test: /\.(png|jpe?g|gif|ico)$/, loader: 'file-loader?name=img/[name]_[hash].[ext]' }, { test: /\.css$/, exclude: helpers.root('src', 'app'), use: ['style-loader', 'css-loader'] }, { test: /\.css$/, include: helpers.root('src', 'app'), loader: 'raw-loader' }, { test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/, // We cannot use [hash] or anything similar here, since ng-split will not work then. loader: 'file-loader?name=fonts/[name].[ext]' }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?name=fonts/[name].[ext]", }, { test: /\.scss$/, use: [{ loader: "style-loader" }, { loader: "postcss-loader", options: { sourceMap: true, plugins: function() { return [require("autoprefixer")]; } } }, { loader: "sass-loader", options: { sourceMap: true } } ] } ] }, plugins: [ new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, helpers.root('../src'), {}), new webpack.ContextReplacementPlugin(/\@angular(\\|\/)core(\\|\/)esm5/, helpers.root('../src'), {}), new webpack.optimize.CommonsChunkPlugin({ name: ['specmate', 'vendor', 'polyfills', 'assets'] }), new HtmlWebpackPlugin({ template: 'src/index.html', favicon: 'src/assets/img/favicon.ico' }), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }), new CopyWebpackPlugin([{ from: helpers.root('src', 'assets', 'i18n'), to: 'i18n', copyUnmodified: true }]) ] };
JavaScript
0.000001
@@ -23,17 +23,17 @@ = '0.2. -5 +6 '%0A%0Aconst
ca5e680eba942868c00ccf8e7b34c7dc3cf56364
make myself crazy with this path thing
routes/hello.js
routes/hello.js
var DtoProvider = require('../dto/DtoProvider').DtoProvider; var helloProvider= new DtoProvider('localhost', 27017, 'asok'); helloProvider.setCollectionName('greetings'); var basePath = '/backend/hello'; var random_json = function(req, res) { helloProvider.findAll(function(error, items){ var rand = items[Math.floor(Math.random() * items.length)]; res.send({hello: rand}); }); }; var list_json = function(req, res){ helloProvider.findAll(function(error, items){ res.send({hellos: items}); }); }; var list = function(req, res) { helloProvider.findAll(function(error, items){ res.render('hello/list', { "basepath": basePath, "hellolist" : items }); }); }; var create = function(req, res){ res.render('hello/create', { title: 'Add New hello' }); }; var edit = function(req, res){ helloProvider.findById(req.params.id, function (error, item) { res.render('hello/edit', { title: 'Edit hello', hello: item }); }); }; var update = function (req, res) { var helloGreeting = req.body.hellogreeting; var helloRecipient = req.body.hellorecipient; helloProvider.findById(req.param('_id'), function (error, item) { helloProvider.update(req.param('_id'), { greeting: helloGreeting, recipient: helloRecipient }, function( error, docs) { res.redirect(basePath + '/') }); }); }; var add = function (req, res) { // Get our form values. These rely on the "name" attributes var helloGreeting = req.body.hellogreeting; var helloRecipient = req.body.hellorecipient; helloProvider.save({ greeting: helloGreeting, recipient: helloRecipient }, function( error, docs) { res.redirect(basePath + '/') }); }; var del = function (req, res) { console.log("params", req.params); var delId = req.params.id; helloProvider.delete(delId, function( error, docs) { res.redirect(basePath + '/') }); }; module.exports = function (app) { app.namespace(basePath, function(){ app.get('/list', list); app.get('/new', create); app.get('/edit/:id', edit); app.get('/del/:id', del); app.get('/list.json', list_json); app.get('/random.json', random_json); app.post('/add', add); app.post('/update', update); }); };
JavaScript
0
@@ -190,17 +190,37 @@ /backend -/ +';%0Avar moduleName = ' hello';%0A @@ -1358,32 +1358,51 @@ irect(basePath + + '/' + moduleName + '/')%0A %7D);%0A @@ -1728,32 +1728,51 @@ irect(basePath + + '/' + moduleName + '/')%0A %7D);%0A%0A%7D;%0A @@ -1948,24 +1948,43 @@ t(basePath + + '/' + moduleName + '/')%0A %7D);%0A
6cc1258cd5c0f50ab25718df9fae4357a613a8bd
Clean up console log
routes/icons.js
routes/icons.js
module.exports = function(app, security) { var api = require('../api') , access = require('../access') , fs = require('fs-extra') , archiver = require('archiver'); var p***REMOVED***port = security.authentication.p***REMOVED***port , authenticationStrategy = security.authentication.authenticationStrategy; app.all('/api/icons*', p***REMOVED***port.authenticate(authenticationStrategy)); // TODO when we switch to events we need to change all the *_LAYER roles // to *_EVENT roles // get a zip of all icons app.get( '/api/icons/:formId.zip', access.authorize('READ_LAYER'), function(req, res, next) { var iconBasePath = new api.Icon(req.form).getBasePath(); var archive = archiver('zip'); res.attachment("icons.zip"); archive.pipe(res); archive.bulk([{src: ['**'], dest: '/icons', expand: true, cwd: iconBasePath}]); archive.finalize(); } ); // get icon app.get( '/api/icons/:formId/:type?/:variant?', access.authorize('READ_LAYER'), function(req, res, next) { new api.Icon(req.form, req.params.type, req.params.variant).getIcon(function(err, iconPath) { if (err) return next(err); if (!iconPath) return res.send(404); console.log('getting image', iconPath); res.sendfile(iconPath); }); } ); // Create a new icon app.post( '/api/icons/:formId/:type?/:variant?', access.authorize('CREATE_LAYER'), function(req, res, next) { new api.Icon(req.form, req.params.type, req.params.variant).create(req.files.icon, function(err, icon) { if (err) return next(err); return res.json(icon); }); } ); // Delete an icon app.delete( '/api/icons/:formId/:type?/:variant?', access.authorize('DELETE_LAYER'), function(req, res) { new api.Icon(req.form, req.params.type, req.params.variant).delete(function(err, icon) { if (err) return next(err); return res.send(204); }); } ); }
JavaScript
0.000001
@@ -1245,56 +1245,8 @@ );%0A%0A - console.log('getting image', iconPath);%0A
75045566c00673bb6377cd8f386acf0510d61f62
use auth config
routes/index.js
routes/index.js
exports.main = function (req, res) { // return res.render('manager', { // roles: req.session.roles // }); if (req.session.roles && req.session.roles.length) { return res.render('manager', { roles: req.session.roles }); } return res.render('main', { roles: req.session.roles }); }; exports.switch2normal = function (req, res) { return res.render('main', { roles: req.session.roles }); }; //TODO implement the cas 2.0 logout exports.logout = function (req, res) { if (req.session) { req.session.destroy(function (err) { if (err) { console.error(err); } }); } res.redirect('https://liud-dev.nscl.msu.edu/cas/logout'); };
JavaScript
0.000001
@@ -1,16 +1,66 @@ +var authConfig = require('../config/auth.json');%0A%0A exports.main = f @@ -699,42 +699,26 @@ ect( -'https://liud-dev.nscl.msu.edu/cas +authConfig.cas + ' /log
a5827135765aa90c8df492d26c3652b394176b5b
update getClientAddress
routes/index.js
routes/index.js
import express from 'express' const router = express.Router() const { ROOT_PATH } = require('../config.js') import { scrapePrice } from '../scraper.js' /* GET home page. */ router.get('/', async function(req, res) { res.render('index', { title: 'Care Force Lumber Calculator', description: 'Optimizes lumber orders and provides cut lists for various City Year Care Force schematics.', ROOT_PATH }) }) const getClientAddress = function (req) { return (req.headers['x-forwarded-for'] || '').split(',')[0] || req.connection.remoteAddress }; router.get('/lumber', async (req, res) => { // const price = await scrapePrice(decodeURI(req.query.url)) // res.send(price) const price = await scrapePrice(decodeURI(req.query.url), req.ip) res.send({ price, clientIp: getClientAddress(req) }) }) module.exports = router
JavaScript
0.000001
@@ -482,16 +482,44 @@ return ( +req.headers%5B'forwarded'%5D %7C%7C req.head @@ -730,16 +730,59 @@ (price)%0A + const clientIp = getClientAddress(req)%0A cons @@ -839,13 +839,15 @@ l), -req.i +clientI p)%0A @@ -879,31 +879,8 @@ ntIp -: getClientAddress(req) %7D)%0A
776b144cb073695005a794ba419194aec4ca6ff6
add login + register routes
routes/index.js
routes/index.js
//Home page exports.addRoutes = function(app) { app.get('/', function(req, res){ res.render('index', { body: 'This is LetsGit' }); }); };
JavaScript
0.000001
@@ -136,6 +136,247 @@ %7D);%0A +%09app.get('/login', function(req, res)%7B%0A res.render('login', %7B body: 'This is LetsGit' %7D);%0A %7D);%0A%09app.get('/register', function(req, res)%7B%0A res.render('register', %7B body: 'This is LetsGit' %7D);%0A %7D);%0A %7D; +%0A
9db0ebd95b97cecc1d01e336d2f82769faacdcb6
Update index.js
routes/index.js
routes/index.js
var express = require('express'); var fs = require('file-system'); var router = express.Router(); var mongo = require('mongodb'); var monk = require('monk'); var db = monk('mongodb://akshaykumargowdar:[email protected]:27017,mycluster-shard-00-01-rplbd.mongodb.net:27017,mycluster-shard-00-02-rplbd.mongodb.net:27017/MyCluster?ssl=true&replicaSet=MyCluster-shard-0&authSource=admin'); //var db = monk('localhost:27017/MyApplicationDatabase'); db.createCollection("MyCollection", { capped : true, size : 5242880, max : 5000 } ); var TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1'); var SpeechToTextV1 = require('watson-developer-cloud/speech-to-text/v1'); var watson = require('watson-developer-cloud'); var conversation = watson.conversation({ username: 'e4550c76-2732-4319-99a3-a5ba24353928', password: 'LePjWTbZIsCx', version: 'v1', version_date: '2017-04-14' }); var context = {}; var response; router.get('/firstcall', function(req, res, next) { conversation.message({ workspace_id: 'f9fa4f80-fef3-49eb-b5cb-ca1b40d77e52', input: {'text': " " }, }, function(err, response) { if (err) console.log('error:', err); else { context = response.context; res.send(response.output); } }); }); router.post('/consecutivecalls', function(req, res) { console.log(req.body.context); conversation.message({ workspace_id: 'f9fa4f80-fef3-49eb-b5cb-ca1b40d77e52', input: {'text': req.body.question }, context: context }, function(err, response) { if (err) console.log('error:', err); else { context = response.context; res.send(response.output); } }); }); var text_to_speech = new TextToSpeechV1({ username: '69bfd0da-dd82-416c-8043-901a66dda6b0', password: 'yT2ZMmqPKrDv', headers: { 'X-Watson-Learning-Opt-Out': 'true' } }); var speech_to_text = new SpeechToTextV1({ username : "87f6b0a7-4d1c-4c27-ae4b-177463cfd33f", password : "iDzdOBlQ61v2" , headers: { 'X-Watson-Learning-Opt-Out': 'true' } }); router.get('/texttospeech', function(req, res, next) { var params = { text: 'Welocme to node js', voice: 'en-US_AllisonVoice', accept: 'audio/wav' }; // Pipe the synthesized text to a file. text_to_speech.synthesize(params).on('error', function(error) { console.log('Error:', error); }).pipe(fs.createWriteStream('./public/audio/audio2.wav')); }); router.get('/speechtotext', function(req, res, next) { var params = { audio: fs.createReadStream('./public/audio/audio1.wav'), content_type: 'audio/wav', timestamps: true, word_alternatives_threshold: 0.9, continuous: true }; // Pipe the synthesized text to a file. speech_to_text.recognize(params, function(error, transcript) { if (error) console.log('Error:', error); else res.send(transcript.results[0].alternatives[0].transcript); }); }); router.get('/storedata', function(req, res, next) { db.collection('MyCollection').insert( { product : "phone", brand : "iphone", model : "7s", color : "golden", memory : "16gb", price : 50000 }).then(function(response) { res.send(response); }); }); router.get('/getdata', function(req, res, next) { db.collection('MyCollection').find().then(function(response){ res.send(response); }); }); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.get('/conversationapp', function(req,res,next) { res.render('conversation'); }); module.exports = router;
JavaScript
0.000002
@@ -561,17 +561,16 @@ 5000 %7D ) -; %0A%0A%0Avar T
eae31acd546beaca7bd8ddeaf0ee4042c7f9ca7a
Update PUT /
routes/index.js
routes/index.js
'use strict' // Packages dependencies const express = require('express') const router = express.Router() const jwt = require('jsonwebtoken') // Exports module.exports = function (UsersApiPackage, app, config, db, auth) { // Get pages router.get('/', (req, res, next) => { const lang = req.query.lang || 'en' const Page = db.models.Page Page .findAll() .then(pages => { res.json(pages.map(page => { return page.toJSON(lang) })) }) .catch(next) }) // Get page by id router.get('/:pageId', (req, res, next) => { const Page = db.models.Page const Media = db.models.Media const lang = req.query.lang || 'en' Page .findOne({ where: { id: req.params.pageId }, include: [ { model: Media, as: 'medias' } ] }) .then(page => { res.json(page.toJSON(lang)) }) .catch(next) }) // Create new page router.post('/', (req, res, next) => { const Page = db.models.Page const lang = req.query.lang || 'en' const params = Object.assign({}, req.body, { name: JSON.stringify({en: req.body.name}) }) Page .create(params) .then(page => { res.json(page.toJSON(lang)) }) .catch(next) }) // Edit page by id router.put('/:pageId', (req, res, next) => { const Page = db.models.Page const lang = req.query.lang || 'en' db.transaction(t => { return Page .findOne({ where: { id: req.params.pageId } }, {transaction: t}) .then(page => { const params = Object.assign({}, req.body) if (params.name) { page.setName(params.name, lang) params.name = page.name } if (params.description) { page.setDescription(params.description, lang) params.description = page.description } return params }) .then(params => { return Page .update(params, { where: { id: req.params.pageId } }, {transaction: t}) }) .then(result => { return Page .findOne({ where: { id: req.params.pageId } }, {transaction: t}) }) }) .then(page => { res.json(page.toJSON()) }) .catch(next) }) // Delete page by id router.delete('/:pageId', (req, res, next) => { const Page = db.models.Page Page .findOne({ where: { id: req.params.pageId } }) .then(page => { return Page .destroy({ where: { id: req.params.pageId } }) .then(() => page) }) .then(page => { res.json(page.toJSON()) }) .catch(next) }) return router }
JavaScript
0
@@ -2439,24 +2439,28 @@ page.toJSON( +lang ))%0A %7D)%0A
2963dba7c017342393a99b51cbdd23347437d956
Update index.js
routes/index.js
routes/index.js
var express = require('express'), R = require('ramda'), Promise = require('bluebird'), router = express.Router(), Bluemix = require('../lib/bluemix'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Bluemix Status Demo', }); }); router.get('/api/bluemix/org', function(req, res, next){ var bluemix = new Bluemix(); bluemix.getOrgs().then((data) => { res.send(data); }); }); router.get('/api/bluemix/space/:space/apps', function(req, res, next){ var bluemix = new Bluemix(); bluemix.getSpaceApps(req.params.space).done((promises) => { res.send({data: promises}); }, console.error); }); module.exports = router;
JavaScript
0.000002
@@ -272,16 +272,22 @@ tus Demo + again ',%0A %7D);
473c382c5c7d4d63a88fb88d19ceaf0b9ca6ae2d
add relevant response when GETing the api home resource
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); module.exports = router;
JavaScript
0
@@ -133,44 +133,59 @@ res. -render('index', %7B title: 'Express' %7D +send('API Backend supporting Codingpedia Bookmarks' );%0A%7D
0526ef083c8f13cceefa6637f9cb0df8f9f423a1
Add retries to download-archive
shared/download-archive.js
shared/download-archive.js
'use strict'; const Promise = require('bluebird'); const request = require('request-promise'); Promise.promisifyAll(request); module.exports = function(url) { return request({ uri: url, encoding: null }); };
JavaScript
0
@@ -8,16 +8,84 @@ rict';%0A%0A +const log = require('util').log;%0Aconst f = require('util').format;%0A%0A const Pr @@ -113,16 +113,16 @@ bird');%0A - const re @@ -231,51 +231,382 @@ -return request(%7B uri: url, encoding: null %7D +// httpredir.debian.org is fairly unreliable, so we retry 5 times.%0A return function r(acc) %7B%0A return request(%7B uri: url, encoding: null %7D).catch(function(err) %7B%0A if (acc %3C 5) %7B%0A log(f('Failed downloading %25s, retrying (%25d/%25d)...', url, acc + 1, 5));%0A return r(++acc);%0A %7D%0A throw err;%0A %7D);%0A %7D(0 );%0A%7D
1a0da8df19efaa3c8be7cc2b14511611d3004902
Update index.js
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Got Milk?', pun: randomPun() }); }); function randomPun() { var puns = [ 'Leaves you wanting mooo-re!', 'Udderly amazing!', // 'Vitamins, you don\'t want to lactose', 'Milk-stash-tic!', 'You should have an udder one', 'I dairy you to drink mooo-re', 'You will cow-l for more', 'Cow-nting down to zero', 'Pour some in your decalf coffee', 'Mmh, ice cow-ld!', 'Legen-dairy stuff', ]; var puns_empty = [ 'I’m dairy sorry, but you’re out of milk', 'No whey, you finished the whole bottle!', 'Better cream for a refill!', ]; var rand = Math.floor(Math.random() * puns.length); return puns[rand]; } module.exports = router;
JavaScript
0.000002
@@ -582,16 +582,37 @@ stuff',%0A + 'Cow-dy partner'%0A %5D;%0A%0A
7c0ba1c4771addd1de758fd90ecaf8c7876199ec
change sence
routes/photo.js
routes/photo.js
var express = require('express'); var router = express.Router(); var request = require('superagent'); var db = require('../utils/dbUtils'); var config = require('../configs/config'); const CDN = 'https://static1.ioliu.cn/'; /* GET photo listing. */ router.get('/:photo', function(req, res, next) { var force = req.query.force || ''; var photo = req.params.photo; var isAjax = !!req.headers['x-requested-with']; switch (force) { case 'like': if (isAjax) { var ck = req.cookies['likes'] || ''; ck = ck.split('_'); if (ck.indexOf(photo) > -1) { res.json({ msg: '', code: 200 }); return; } var sql = `update bing as a join (select likes,id from bing WHERE id='${photo}') as b on a.id=b.id set a.likes=(b.likes+1)`; db.commonQuery(sql, function(rows) { var ret = { msg: '', code: 200 }; if (rows.affectedRows == 0) { ret.msg = 'something happend.' } res.json(ret); }); } else {} return; break; case 'download': var ua = req.get('User-Agent'); if (!isAjax && !/(spider|bot)/ig.test(ua)) { var sql = `update bing as a join (select downloads,id from bing WHERE qiniu_url='${photo}') as b on a.id=b.id set a.downloads=(b.downloads+1)`; db.commonQuery(sql, function(rows) {}); res.set({ 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=' + encodeURI(`${photo}_1920x1080.jpg`) }); request.get(`${CDN}bing/${photo}_1920x1080.jpg`) .set({ 'User-Agent': ua, referer: 'https://bing.ioliu.cn' }).pipe(res); } else { res.json({ code: 200, msg: 'bad request' }) } return; break; } var sql = `select id,title,attribute,description,copyright,qiniu_url as photo,city,country,continent,DATE_FORMAT(enddate, '%Y-%m-%d') as dt,likes,views,downloads,thumbnail_pic from bing where qiniu_url='${photo}'`; if (isAjax) { res.send({ code: 200, msg: 'bad request' }); } else { // 修改展示量 db.commonQuery(`update bing as a join (select views,id from bing WHERE qiniu_url='${photo}') as b on a.id=b.id set a.views=(b.views+1)`, function(rows) {}); // 返回数据 db.commonQuery(sql, function(rows) { if (rows.length > 0) { var doc = rows[0]; doc['thumbnail'] = `${CDN}bing/${photo}_1920x1080.jpg`; if (force.indexOf('_') > -1) { var rt = force.split('_'); doc['back_url'] = rt[0] === 'ranking' ? '/ranking?p=' + rt[1] : '/?p=' + rt[1]; } else { doc['back_url'] = '/'; } res.render('detail', { doc: doc }); } else { res.redirect(`/`); } }); } }); /** * 如果没有参数,则跳转到首页 */ router.get('/', function(req, res, next) { res.redirect('/'); }); module.exports = router;
JavaScript
0.000004
@@ -2036,16 +2036,19 @@ + // .set(%7B%0D @@ -2063,24 +2063,27 @@ + // 'User-A @@ -2109,24 +2109,27 @@ + // referer @@ -2175,18 +2175,43 @@ -%7D) +// %7D)%0D%0A .pipe(re
83dad88ad3646edbfd9274ec3d02ca91e930367b
Fix debug reporting of warning/errors
nodes/core/core/58-debug.js
nodes/core/core/58-debug.js
/** * Copyright 2013 IBM Corp. * * 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. **/ module.exports = function(RED) { var util = require("util"); var events = require("events"); var debuglength = RED.settings.debugMaxLength||1000; var useColors = false; // util.inspect.styles.boolean = "red"; function DebugNode(n) { RED.nodes.createNode(this,n); this.name = n.name; this.complete = n.complete||"payload"; if (this.complete === "false") { this.complete = "payload"; } if (this.complete === true) { this.complete = "true"; } this.console = n.console; this.active = (n.active === null || typeof n.active === "undefined") || n.active; var node = this; this.on("input",function(msg) { if (this.complete === "true") { // debug complete msg object if (this.console === "true") { node.log("\n"+util.inspect(msg, {colors:useColors, depth:10})); } if (this.active) { sendDebug({id:this.id,name:this.name,topic:msg.topic,msg:msg,_path:msg._path}); } } else { // debug user defined msg property var property = "payload"; var output = msg[property]; if (this.complete !== "false" && typeof this.complete !== "undefined") { property = this.complete; var propertyParts = property.split("."); try { output = propertyParts.reduce(function (obj, i) { return obj[i]; }, msg); } catch (err) { output = undefined; } } if (this.console === "true") { if (typeof output === "string") { node.log((output.indexOf("\n") !== -1 ? "\n" : "") + output); } else if (typeof output === "object") { node.log("\n"+util.inspect(output, {colors:useColors, depth:10})); } else { node.log(util.inspect(output, {colors:useColors})); } } if (this.active) { sendDebug({id:this.id,name:this.name,topic:msg.topic,property:property,msg:output,_path:msg._path}); } } }); } RED.nodes.registerType("debug",DebugNode); function sendDebug(msg) { if (msg.msg instanceof Error) { msg.msg = msg.msg.toString(); } else if (msg.msg instanceof Buffer) { msg.msg = "(Buffer) "+msg.msg.toString('hex'); } else if (typeof msg.msg === 'object') { var seen = []; var ty = "(Object) "; if (util.isArray(msg.msg)) { ty = "(Array) "; } msg.msg = ty + JSON.stringify(msg.msg, function(key, value) { if (typeof value === 'object' && value !== null) { if (seen.indexOf(value) !== -1) { return "[circular]"; } seen.push(value); } return value; }," "); seen = null; } else if (typeof msg.msg === "boolean") { msg.msg = "(boolean) "+msg.msg.toString(); } else if (msg.msg === 0) { msg.msg = "0"; } else if (msg.msg === null || typeof msg.msg === "undefined") { msg.msg = "(undefined)"; } if (msg.msg.length > debuglength) { msg.msg = msg.msg.substr(0,debuglength) +" ...."; } RED.comms.publish("debug",msg); } DebugNode.logHandler = new events.EventEmitter(); DebugNode.logHandler.on("log",function(msg) { if (msg.level === "warn" || msg.level === "error") { sendDebug(msg); } }); RED.log.addHandler(DebugNode.logHandler); RED.httpAdmin.post("/debug/:id/:state", RED.auth.needsPermission("debug.write"), function(req,res) { var node = RED.nodes.getNode(req.params.id); var state = req.params.state; if (node !== null && typeof node !== "undefined" ) { if (state === "enable") { node.active = true; res.send(200); } else if (state === "disable") { node.active = false; res.send(201); } else { res.send(404); } } else { res.send(404); } }); };
JavaScript
0.000117
@@ -4437,14 +4437,20 @@ === -%22warn%22 +RED.log.WARN %7C%7C @@ -4467,15 +4467,21 @@ === -%22error%22 +RED.log.ERROR ) %7B%0A
af77dd4b12042e138edba5dfc2fe0b303939a849
set 'staleOk' config to false to avoid false data from the registry hits
plugin/registry.js
plugin/registry.js
var _ = require('underscore'), npm = require('npm'), Registry = require('npm-registry-client'), npmconf = require('npmconf'), path = require('path'), config = require('./config'), options, client, connectionConfig = { timeout: 1000, staleOk: true }; function initLocalNPM() { npm.load({ loaded: false }, function (err) { if (err) { throw err; } npm.on("log", function (message) { console.log(message); }); }); } function sync(cb) { var uri = options.registry + "-/all"; client.get(uri, connectionConfig, function (err, data, raw, res) { if (err) { throw err; return; } if (typeof cb === 'function') { cb(data); } }); } module.exports.setup = function (_options, callback) { options = _options; npmconf.load({}, function (err, conf) { if (err) { throw err; return; } conf.set('cache', path.resolve(__dirname + '/../' + config.directory.cache)); conf.set('always-auth', false); conf.set('strict-ssl', false); client = new Registry(conf); //setInterval(sync, config.syncInterval); sync(function (packages) { callback(); }); initLocalNPM(); }); }; module.exports.list = function (page, callback) { var start = page * config.pageSize, end = start + config.pageSize; sync(function (packages) { var keys = Object.keys(packages); keys = keys.splice(1, keys.length); //ignore the first key which is '_updated' callback(_.values(_.pick(packages, keys.slice(start, end)))); }); }; module.exports.packageInfo = function (name, callback) { var uri = options.registry + name; client.get(uri, connectionConfig, function (err, data, raw, res) { if (err) { throw err; return; } callback(data); }); }; module.exports.search = function (key, callback) { npm.commands.search([key], function (err, data) { if (err) { throw err; } var results = [], keys = Object.keys(data); for (var i = 0; i <= keys.length; i+=1) { if (i === config.search.maxResults) { break; } var _package = data[keys[i]]; // this chk safety is to protect against // undefined coming from the search data! if (_package) { // send back just the package name results.push(_.pick(_package, 'name')); } } callback(results); }); };
JavaScript
0
@@ -251,11 +251,12 @@ Ok: -tru +fals e%0A%09%7D
18c5f36f4807515c5f16fb3c327e1aef44ac4dd1
use cloneDeep so data isn't polluted and spec is deterministic
tutor/specs/models/course.spec.js
tutor/specs/models/course.spec.js
import { map, clone, shuffle } from 'lodash'; import Courses from '../../src/models/courses-map'; import Course from '../../src/models/course'; import PH from '../../src/helpers/period'; import { autorun } from 'mobx'; import { bootstrapCoursesList } from '../courses-test-data'; import COURSE from '../../api/courses/1.json'; jest.mock('shared/src/model/ui-settings'); describe('Course Model', () => { beforeEach(() => bootstrapCoursesList()); it('can be bootstrapped and size observed', () => { Courses.clear(); const lenSpy = jest.fn(); autorun(() => lenSpy(Courses.size)); expect(lenSpy).toHaveBeenCalledWith(0); bootstrapCoursesList(); expect(lenSpy).toHaveBeenCalledWith(3); expect(Courses.size).toEqual(3); }); it('#isStudent', () => { expect(Courses.get(1).isStudent).toBe(true); expect(Courses.get(2).isStudent).toBe(false); expect(Courses.get(3).isStudent).toBe(true); }); it('#isTeacher', () => { expect(Courses.get(1).isTeacher).toBe(false); expect(Courses.get(2).isTeacher).toBe(true); expect(Courses.get(3).isTeacher).toBe(true); }); it('#userStudentRecord', () => { expect(Courses.get(1).userStudentRecord).not.toBeNull(); expect(Courses.get(1).userStudentRecord.student_identifier).toEqual('1234'); expect(Courses.get(2).userStudentRecord).toBeNull(); }); it('calculates audience tags', () => { expect(Courses.get(1).tourAudienceTags).toEqual(['student']); const teacher = Courses.get(2); expect(teacher.tourAudienceTags).toEqual(['teacher']); teacher.primaryRole.joined_at = new Date(); expect(teacher.tourAudienceTags).toEqual(['teacher', 'teacher-settings-roster-split']); teacher.is_preview = true; expect(teacher.tourAudienceTags).toEqual(['teacher-preview']); const course = Courses.get(3); expect(course.tourAudienceTags).toEqual(['teacher', 'student']); course.is_preview = false; expect(course.isTeacher).toEqual(true); course.taskPlans.set('1', { id: 1, type: 'reading', is_publishing: true, isPublishing: true }); expect(course.taskPlans.reading.hasPublishing).toEqual(true); expect(course.tourAudienceTags).toEqual(['teacher', 'teacher-reading-published', 'student' ]); }); it('should return expected roles for courses', function() { expect(Courses.get(1).primaryRole.type).to.equal('student'); expect(Courses.get(2).primaryRole.type).to.equal('teacher'); expect(Courses.get(3).primaryRole.type).to.equal('teacher'); expect(Courses.get(1).primaryRole.joinedAgo('days')).toEqual(7); }); it('sunsets cc courses', () => { const course = Courses.get(2); expect(course.isSunsetting).toEqual(false); course.is_concept_coach = true; course.appearance_code = 'physics'; expect(course.isSunsetting).toEqual(false); course.appearance_code = 'micro_econ'; expect(course.isSunsetting).toEqual(true); }); it('restricts joining to links', () => { const course = Courses.get(2); expect(course.is_lms_enabling_allowed).toEqual(false); expect(course.canOnlyUseEnrollmentLinks).toEqual(true); course.is_lms_enabling_allowed = true; expect(course.canOnlyUseEnrollmentLinks).toEqual(false); course.is_lms_enabled = true; course.is_access_switchable = false; expect(course.canOnlyUseEnrollmentLinks).toEqual(false); expect(course.canOnlyUseLMS).toEqual(true); course.is_lms_enabled = false; expect(course.canOnlyUseEnrollmentLinks).toEqual(true); expect(course.canOnlyUseLMS).toEqual(false); }); it('extends periods', () => { const data = clone(COURSE); data.periods = shuffle(data.periods); jest.spyOn(PH, 'sort'); const course = new Course(data); const len = course.periods.length; expect(map(course.periods, 'id')).not.toEqual( map(course.periods.sorted, 'id') ); expect(PH.sort).toHaveBeenCalledTimes(1); const sortedSpy = jest.fn(() => course.periods.sorted); autorun(sortedSpy); expect(course.periods.sorted).toHaveLength(len - 2); expect(sortedSpy).toHaveBeenCalledTimes(1); expect(PH.sort).toHaveBeenCalledTimes(2); course.periods.pop(); expect(course.periods.length).toEqual(len - 1); expect(course.periods.sorted.length).toEqual(len - 3); expect(PH.sort).toHaveBeenCalledTimes(3); expect(sortedSpy).toHaveBeenCalledTimes(2); expect(map(course.periods, 'id')).not.toEqual( map(course.periods.sorted, 'id') ); expect(PH.sort).toHaveBeenCalledTimes(3); expect(sortedSpy).toHaveBeenCalledTimes(2); }); it('calculates if terms are before', () => { const course = Courses.get(2); expect(course.isBeforeTerm('spring', 2013)).toBe(false); expect(course.isBeforeTerm('spring', (new Date()).getFullYear()+1)).toBe(true); expect(course.isBeforeTerm(course.term, course.year)).toBe(false); }); });
JavaScript
0
@@ -12,16 +12,20 @@ p, clone +Deep , shuffl @@ -3616,16 +3616,20 @@ = clone +Deep (COURSE)
6503932c942f03cd24d46ab91614dd01f561d905
Update loading.js
public/app/directives/loading.js
public/app/directives/loading.js
app.directive('loading', ['$http' ,function ($http) { return { restrict: 'A', template: '<div class="loading-spiner"><img src="img/loading.gif" /> </div>', link: function (scope, elm, attrs){ scope.isLoading = function () { return $http.pendingRequests.length > 0; }; scope.$watch(scope.isLoading, function (v){ console.log(elm); if(v){ elm[0].show(); }else{ elm[0].hide(); } }); } }; }]);
JavaScript
0.000001
@@ -499,22 +499,27 @@ -elm%5B0%5D +jQuery(elm) .show(); @@ -572,14 +572,19 @@ -elm%5B0%5D +jQuery(elm) .hid
cb557eda9e55ca56304089c519e4f96b72fb23f4
support streams comming with _publish as well as _all
dvr-ws/routes/index.js
dvr-ws/routes/index.js
var express = require('express'); var router = express.Router(); var config = require('../../common/Configuration'); var logger = require('../logger/logger'); var qio = require('q-io/fs'); var path = require('path') var persistenceFormat = require('../../common/PersistenceFormat'); var request = require('request'); var util = require('util'); var urlPattern='http://localhost/kLive/smil:%s_all.smil/%s'; router.get(/\/smil:([^\/]*)_pass.smil\/(.*)/i, function(req, res) { var entryId = req.params[0]; var path = req.params[1]; request(util.format(urlPattern,entryId,path)).pipe(res); }); router.get(/\/smil:([^\\/]*)_all\.smil\/([^\?]*)/i, function(req, res) { var entryId = req.params[0]; var fileName = req.params[1]; var disk = path.join(persistenceFormat.getEntryFullPath(entryId),fileName); res.sendFile(disk); }); module.exports = router;
JavaScript
0
@@ -631,19 +631,31 @@ %5E%5C%5C/%5D*)_ -all +(?:all%7Cpublish) %5C.smil%5C/
0d0e5bfe429c3b6cb79c977dbec15ff3ce18bea2
Fix tabs shown on reload
front_end/console_counters/WarningErrorCounter.js
front_end/console_counters/WarningErrorCounter.js
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as BrowserSDK from '../browser_sdk/browser_sdk.js'; import * as Common from '../common/common.js'; import * as Host from '../host/host.js'; import * as Root from '../root/root.js'; import * as SDK from '../sdk/sdk.js'; import * as UI from '../ui/ui.js'; /** * @implements {UI.Toolbar.Provider} * @unrestricted */ export class WarningErrorCounter { constructor() { WarningErrorCounter._instanceForTest = this; const countersWrapper = document.createElement('div'); this._toolbarItem = new UI.Toolbar.ToolbarItem(countersWrapper); this._counter = document.createElement('div'); this._counter.addEventListener('click', Common.Console.Console.instance().show.bind(Common.Console.Console.instance()), false); const shadowRoot = UI.Utils.createShadowRootWithCoreStyles(this._counter, 'console_counters/errorWarningCounter.css'); countersWrapper.appendChild(this._counter); this._violationCounter = document.createElement('div'); this._violationCounter.addEventListener('click', () => { UI.ViewManager.ViewManager.instance().showView('lighthouse'); }); const violationShadowRoot = UI.Utils.createShadowRootWithCoreStyles(this._violationCounter, 'console_counters/errorWarningCounter.css'); if (Root.Runtime.experiments.isEnabled('spotlight')) { countersWrapper.appendChild(this._violationCounter); } this._issuesCounter = document.createElement('div'); this._issuesCounter.addEventListener('click', () => { Host.userMetrics.issuesPanelOpenedFrom(Host.UserMetrics.IssueOpener.StatusBarIssuesCounter); UI.ViewManager.ViewManager.instance().showView('issues-pane'); }); const issuesShadowRoot = UI.Utils.createShadowRootWithCoreStyles(this._issuesCounter, 'console_counters/errorWarningCounter.css'); countersWrapper.appendChild(this._issuesCounter); this._errors = this._createItem(shadowRoot, 'smallicon-error'); this._warnings = this._createItem(shadowRoot, 'smallicon-warning'); if (Root.Runtime.experiments.isEnabled('spotlight')) { this._violations = this._createItem(violationShadowRoot, 'smallicon-info'); } this._issues = this._createItem(issuesShadowRoot, 'smallicon-issue-blue-text'); this._titles = ''; /** @type {number} */ this._errorCount = -1; /** @type {number} */ this._warningCount = -1; /** @type {number} */ this._violationCount = -1; /** @type {number} */ this._issuesCount = -1; this._throttler = new Common.Throttler.Throttler(100); SDK.ConsoleModel.ConsoleModel.instance().addEventListener( SDK.ConsoleModel.Events.ConsoleCleared, this._update, this); SDK.ConsoleModel.ConsoleModel.instance().addEventListener(SDK.ConsoleModel.Events.MessageAdded, this._update, this); SDK.ConsoleModel.ConsoleModel.instance().addEventListener( SDK.ConsoleModel.Events.MessageUpdated, this._update, this); BrowserSDK.IssuesManager.IssuesManager.instance().addEventListener( BrowserSDK.IssuesManager.Events.IssuesCountUpdated, this._update, this); this._update(); } _updatedForTest() { // Sniffed in tests. } /** * @param {!Node} shadowRoot * @param {string} iconType * @return {!{item: !Element, text: !Element}} */ _createItem(shadowRoot, iconType) { const item = document.createElement('span'); item.classList.add('counter-item'); UI.ARIAUtils.markAsHidden(item); const icon = /** @type {!UI.UIUtils.DevToolsIconLabel} */ (item.createChild('span', '', 'dt-icon-label')); icon.type = iconType; const text = icon.createChild('span'); shadowRoot.appendChild(item); return {item: item, text: text}; } /** * @param {!{item: !Element, text: !Element}} item * @param {number} count * @param {boolean} first */ _updateItem(item, count, first) { item.item.classList.toggle('hidden', !count); item.item.classList.toggle('counter-item-first', first); item.text.textContent = String(count); } _update() { this._updatingForTest = true; this._throttler.schedule(this._updateThrottled.bind(this)); } /** * @return {!Promise<void>} */ _updateThrottled() { const errors = SDK.ConsoleModel.ConsoleModel.instance().errors(); const warnings = SDK.ConsoleModel.ConsoleModel.instance().warnings(); const violations = SDK.ConsoleModel.ConsoleModel.instance().violations(); const issues = BrowserSDK.IssuesManager.IssuesManager.instance().numberOfIssues(); if (errors === this._errorCount && warnings === this._warningCount && violations === this._violationCount && issues === this._issuesCount) { return Promise.resolve(); } this._errorCount = errors; this._warningCount = warnings; this._violationCount = violations; this._issuesCount = issues; this._counter.classList.toggle('hidden', !(errors || warnings)); this._violationCounter.classList.toggle('hidden', !violations); this._toolbarItem.setVisible(!!(errors || warnings || violations)); let errorCountTitle = ''; if (errors === 1) { errorCountTitle = ls`${errors} error`; } else { errorCountTitle = ls`${errors} errors`; } this._updateItem(this._errors, errors, false); let warningCountTitle = ''; if (warnings === 1) { warningCountTitle = ls`${warnings} warning`; } else { warningCountTitle = ls`${warnings} warnings`; } this._updateItem(this._warnings, warnings, !errors); if (Root.Runtime.experiments.isEnabled('spotlight') && this._violations) { let violationCountTitle = ''; if (violations === 1) { violationCountTitle = ls`${violations} violation`; } else { violationCountTitle = ls`${violations} violations`; } this._updateItem(this._violations, violations, true); this._violationCounter.title = violationCountTitle; } if (this._issues) { let issuesCountTitle = ''; if (issues === 1) { issuesCountTitle = ls`Issues pertaining to ${issues} operation detected.`; } else { issuesCountTitle = ls`Issues pertaining to ${issues} operations detected.`; } this._updateItem(this._issues, issues, true); this._issuesCounter.title = issuesCountTitle; } this._titles = ''; if (errors && warnings) { this._titles = ls`${errorCountTitle}, ${warningCountTitle}`; } else if (errors) { this._titles = errorCountTitle; } else if (warnings) { this._titles = warningCountTitle; } this._counter.title = this._titles; UI.ARIAUtils.setAccessibleName(this._counter, this._titles); UI.InspectorView.InspectorView.instance().toolbarItemResized(); this._updatingForTest = false; this._updatedForTest(); return Promise.resolve(); } /** * @override * @return {?UI.Toolbar.ToolbarItem} */ item() { return this._toolbarItem; } } /** @type {?WarningErrorCounter} */ WarningErrorCounter._instanceForTest = null;
JavaScript
0.000137
@@ -5140,24 +5140,103 @@ iolations);%0A + const violationsEnabled = Root.Runtime.experiments.isEnabled('spotlight');%0A this._to @@ -5281,16 +5281,17 @@ ings %7C%7C +( violatio @@ -5292,16 +5292,48 @@ olations +Enabled && violations) %7C%7C issues ));%0A%0A @@ -5795,55 +5795,25 @@ if ( -Root.Runtime.experiments.isEnabled('spotlight') +violationsEnabled &&
6c732deb9eb0d04b7d95787f762fc563c4d97a92
Fix spacing (#464)
frontend/src/components/profile/country-picker.js
frontend/src/components/profile/country-picker.js
import React, { Component } from 'react' import PropTypes from 'prop-types' import { withStyles, Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Typography } from '@material-ui/core' const countryCodes = [ { country: 'Australia', code: 'AU', image: 'australia' }, { country: 'Austria', code: 'AT', image: 'austria' }, { country: 'Belgium', code: 'BE', image: 'belgium' }, { country: 'Brazil ', code: 'BR', image: 'brazil' }, { country: 'Canada', code: 'CA', image: 'canada' }, { country: 'Denmark', code: 'DK', image: 'denmark' }, { country: 'Finland', code: 'FI', image: 'finland' }, { country: 'France', code: 'FR', image: 'france' }, { country: 'Germany', code: 'DE', image: 'germany' }, { country: 'Hong Kong', code: 'HK', image: 'hong-kong' }, { country: 'Ireland', code: 'IE', image: 'ireland' }, { country: 'Japan', code: 'JP', image: 'japan' }, { country: 'Luxembourg', code: 'LU', image: 'luxembourg' }, { country: 'Mexico ', code: 'MX', image: 'mexico' }, { country: 'Netherlands', code: 'NL', image: 'netherlands' }, { country: 'New Zealand', code: 'NZ', image: 'new-zealand' }, { country: 'Norway', code: 'NO', image: 'norway' }, { country: 'Singapore', code: 'SG', image: 'singapore' }, { country: 'Spain', code: 'ES', image: 'spain' }, { country: 'Sweden', code: 'SE', image: 'sweden' }, { country: 'Switzerland', code: 'CH', image: 'switzerland' }, { country: 'United Kingdom', code: 'GB', image: 'united-kingdom' }, { country: 'United States', code: 'US', image: 'united-states-of-america' }, { country: 'Italy', code: 'IT', image: 'italy' }, { country: 'Portugal', code: 'PT', image: 'portugal' } ] const styles = theme => ({ countryContainer: { padding: 20, display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignContent: 'center' }, countryItem: { display: 'inline-block', textAlign: 'center', padding: 25 } }) class CountryPicker extends Component { static propTypes = { classes: PropTypes.object.required, open: PropTypes.bool, onClose: PropTypes.func } constructor (props) { super(props) this.state = { currentCountryLabel: null, currentCountryCode: null, currentCountryImage: null } } handleCountry = (e, item) => { this.setState({ currentCountryCode: item.code, currentCountryLabel: item.country, currentCountryImage: item.image }) } render () { const { classes } = this.props return ( <div> <Dialog open={ this.props.open } onClose={ (e) => this.props.onClose(e, { code: null, country: null, image: null }) } aria-labelledby='alert-dialog-title' aria-describedby='alert-dialog-description' fullWidth maxWidth={ 'md' } > <DialogTitle id='alert-dialog-title'>{ 'Choose your country' }</DialogTitle> <DialogContent> <DialogContentText id='alert-dialog-description'> Please choose the country that you have your bank account to receive your bounties when conclude any task </DialogContentText> <div className={ classes.countryContainer }> { countryCodes.map((item) => { return ( <Button variant={ this.state.currentCountryCode === item.code ? 'outlined' : '' } onClick={ (e) => this.handleCountry(e, item) } className={ classes.countryItem }> <img width='48' src={ require(`../../images/countries/${item.image}.png`) } /> <Typography component='span'> { item.country } </Typography> </Button> ) }) } </div> </DialogContent> <DialogActions> <Button onClick={ (e) => this.props.onClose(e, { country: null, code: null, image: null }) } size='large'> Cancel </Button> <Button variant='contained' onClick={ (e) => this.props.onClose(e, { country: this.state.currentCountryLabel, code: this.state.currentCountryCode, image: this.state.currentCountryImage }) } size='large' color='primary' autoFocus> Choose { this.state.currentCountryLabel } </Button> </DialogActions> <DialogContent> <DialogContentText id='alert-dialog-footer'> <div>Icons made by <a href='http://www.freepik.com/' title='Freepik'>Freepik</a> from <a href='https://www.flaticon.com/' title='Flaticon'>www.flaticon.com</a> is licensed by <a href='http://creativecommons.org/licenses/by/3.0/' title='Creative Commons BY 3.0' target='_blank'>CC 3.0 BY</a></div> </DialogContentText> </DialogContent> </Dialog> </div> ) } } export default withStyles(styles)(CountryPicker)
JavaScript
0.000068
@@ -3098,16 +3098,18 @@ + Please c
13c7c003f36142547f86f15e3435fda46afe5e65
update keg after pour
RightpointLabs.Pourcast.Web/Scripts/app/model/keg.js
RightpointLabs.Pourcast.Web/Scripts/app/model/keg.js
define(['jquery', 'ko', 'app/events'], function($, ko, events) { function Keg(kegJSON, beer) { var self = this; self.id = ko.observable(kegJSON.Id); self.percentRemaining = ko.observable(Math.floor(kegJSON.PercentRemaining * 100)); self.isEmpty = ko.observable(kegJSON.IsEmpty); self.isPouring = ko.observable(kegJSON.IsPouring); self.capacity = ko.observable(kegJSON.Capacity); self.beer = ko.observable(beer); self.percentRemainingStyle = ko.computed(function () { return self.percentRemaining() + '%'; }); self.percentRemainingHtml = ko.computed(function() { return self.percentRemaining() + '<span class="symbol">%</span>'; }); self.percentRemainingBubble = ko.computed(function() { return self.percentRemaining() > 25 ? "high" : "low"; }); events.on("PourStarted", self.pourStarted); events.on("PourStopped", self.pourStopped); }; Keg.prototype.pourStarted = function(e) { console.log("PourStarted"); }; Keg.prototype.pourStopped = function(e) { console.log("PourStopped"); }; return Keg; });
JavaScript
0
@@ -923,118 +923,106 @@ d%22, -self.pourStarted);%0A events.on(%22PourStopped%22, self.pourStopp +function(e) %7B%0A console.log(%22PourStart ed +%22 );%0A + -%7D;%0A%0A Keg.prototype.pourStarted = + %7D);%0A events.on(%22PourStopped%22, fun @@ -1024,32 +1024,36 @@ , function(e) %7B%0A + console. @@ -1067,104 +1067,100 @@ urSt -art +opp ed%22);%0A +%0A -%7D;%0A%0A Keg.prototype.pourStopped = function(e) %7B%0A console.log(%22PourStopped%22 + self.percentRemaining(Math.floor(e.PercentRemaining * 100));%0A %7D );%0A
c7ca01989eb3d78d9db0db8db0d5b571f8383ed9
fix not found
client-raspberry/core/js/controller/signin.js
client-raspberry/core/js/controller/signin.js
var controller = angular.module('myLazyClock.controller.signin', []); controller.controller('myLazyClock.controller.signin', ['$scope', '$localStorage', '$interval', '$state', 'GApi', function signinCtl($scope, $localStorage, $interval, $state, GApi) { var interval; var interval2; var checkLink = function(id) { GApi.execute('myLazyClock', 'alarmClock.item', {alarmClockId: id}).then( function(resp) { if(resp.user != undefined) { $interval.cancel(interval); $state.go('webapp.home'); } }, function(resp) { $interval.cancel(interval); $localStorage.$reset(); check(); }); } var goToHome = function(id) { checkLink(id); interval = $interval(function() { checkLink(id); }, 4000); } var generate = function() { interval2 = $interval(function() { GApi.execute('myLazyClock', 'alarmClock.generate').then( function(resp) { $localStorage.alarmClockId = resp.id; $scope.alarmClockId = resp.id; $interval.cancel(interval2); goToHome($localStorage.alarmClockId); }); }, 1000); } var check = function() { if($localStorage.alarmClockId == undefined) { generate(); } else { $scope.alarmClockId = $localStorage.alarmClockId; goToHome($localStorage.alarmClockId); } } check(); } ])
JavaScript
0.000006
@@ -663,32 +663,82 @@ unction(resp) %7B%0A + if(resp.code = 404) %7B%0A @@ -789,32 +789,36 @@ + $localStorage.$r @@ -819,18 +819,37 @@ age. -$reset();%0A +alarmClockId = undefined;%0A @@ -860,32 +860,33 @@ + check();%0A @@ -870,32 +870,58 @@ check();%0A + %7D%0A
1ba7ff873ca0fc1a1ff139e81457d547d3e9894c
remove excess newline
packages/babel-core/test/fixtures/transformation/es6.arrow-functions/default-parameters/expected.js
packages/babel-core/test/fixtures/transformation/es6.arrow-functions/default-parameters/expected.js
var some = function () { let count = arguments.length <= 0 || arguments[0] === undefined ? "30" : arguments[0]; console.log("count", count); }; var collect = function () { let since = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; let userid = arguments[1]; console.log(userid); };
JavaScript
0.000003
@@ -143,17 +143,16 @@ t);%0A%7D;%0A%0A -%0A var coll
933a7307cd94e7fbcdf4c5756fc52202dfacc5a3
set init size to adjust parent height
src/js/components/AdminTemplate/Widgets/index.js
src/js/components/AdminTemplate/Widgets/index.js
import React from 'react'; // import ChartComponent from '../../Widgets/ChartComponent'; import options from './optionIndex'; // import Warpper from '../../Widgets/Warpper'; import ReactEcharts from 'echarts-for-react'; // import ReEcharts from 're-echarts'; // class ChartTemplate extends ChartComponent { // componentDidMount() { // const {id, option} = this.props; // this.chart = this.getChart(id); // if (!option.preAction) { // option.preAction = () => { // return { // then: func => func() // }; // }; // } // option.preAction().then(() => { // this.chart.setOption(option); // if (option.addEvents) { // option.addEvents(this.chart); // } // super.componentDidMount(); // }); // } // render() { // const { id } = this.props; // // const { height = 600, width = 800, id, label = id} = this.props; // return ( // // <Warpper name={label} status='success'> // <div id={id} /> // // </Warpper> // ); // } // } const Widgets = {}; options.forEach((option, index) => { let id = 'echart_' + index; // let Widget = <ReEcharts id={id} option={option} />; let Widget = <ReactEcharts option={option} />; // let Widget = <ChartTemplate key={index} id={id} option={option} />; Widgets[id] = Widget; }); export default Widgets;
JavaScript
0
@@ -24,395 +24,130 @@ t';%0A -// import ChartComponent from '../../Widgets/ChartComponent';%0Aimport options from './optionIndex';%0A// import Warpper from '../../Widgets/Warpper';%0Aimport ReactEcharts from 'echarts-for-react';%0A// import ReEcharts from 're-echarts';%0A%0A// class ChartTemplate extends ChartComponent %7B%0A// componentDidMount() %7B%0A// const %7Bid, option%7D = this.props;%0A%0A// this.chart = this.getChart(id); +import options from './optionIndex';%0Aimport ReactEcharts from 'echarts-for-react';%0A// import ReEcharts from 're-echarts';%0A %0A%0A// @@ -525,75 +525,91 @@ %7D%0A%0A%0A -// render() %7B%0A// const %7B id %7D = this.props;%0A// // +const onResize = (chart) =%3E %7B%0A const container = chart._dom.parentElement;%0A const - %7B hei @@ -618,195 +618,91 @@ t = -600, width = 800, id, label = id%7D = this.props;%0A%0A// return (%0A// // %3CWarpper name=%7Blabel%7D status='success'%3E%0A// %3Cdiv id=%7Bid%7D /%3E%0A// // %3C/Warpper%3E%0A// );%0A// %7D%0A// %7D%0A +container.getBoundingClientRect().height %7C%7C 300;%0A%0A chart.resize(%7B height %7D);%0A%7D;%0A %0Acon @@ -718,16 +718,17 @@ s = %7B%7D;%0A +%0A options. @@ -787,19 +787,16 @@ index;%0A - // let Wid @@ -802,171 +802,118 @@ dget - = %3CReEcharts id=%7Bid%7D option=%7Boption%7D /%3E;%0A let Widget = %3CReactEcharts option=%7Boption%7D /%3E;%0A // let Widget = %3CChartTemplate key=%7Bindex%7D id=%7Bid%7D option=%7Boption%7D /%3E; +;%0A %0A Widget = %3CReactEcharts option=%7Boption%7D onChartReady=%7B(chart) =%3E setTimeout(onResize(chart), 200)%7D/%3E;%0A %0A W
c7e7f8475d9c51817bb76f2cbf608ac02b135428
Fix object amount at narrow dev-width
src/js/graphic/background/geometric/geometric.js
src/js/graphic/background/geometric/geometric.js
export default class Geometric { static draw(p) { Geometric.translateByMouse(p) Geometric.generateGeometric(p) } static generateGeometric(p) { p.normalMaterial() const radianX2 = p.PI * 2 let radius = p.width * 1 let xMax = 17 let yMax = 17 let rotateX = p.frameCount * -0.0005 + 1000 let rotateY = p.frameCount * 0.0010 let rotateZ = p.frameCount * 0.0010 let geometricSizeMulti = 1 if (window.screen.width < 600) { radius *= 2 geometricSizeMulti = 0.5 rotateX *= 3 rotateY *= 3 rotateZ *= 3 } for (let x = 0; x <= xMax; ++x) { p.push() for (let y = 0; y <= yMax; ++y) { const xMapped1 = x / xMax const yMapped1 = y / yMax const xRadian = xMapped1 * radianX2 const yRadian = yMapped1 const xSine = p.sin(xRadian) const ySine = p.sin(yRadian) const xCos = p.cos(xRadian) const yCos = p.cos(yRadian) const xTranslate = radius * xSine * ySine const yTranslate = radius * xCos * yCos const zTranslate = radius * xSine * ySine p.push() p.translate(xTranslate, yTranslate, zTranslate) Geometric.addGeometric(p, x, geometricSizeMulti) p.pop() p.rotateX(rotateX) p.rotateY(rotateY) p.rotateZ(rotateZ) Geometric.moveLightByMouse(p) } p.pop() } } static addGeometric(p, unique, multi) { const type = unique % 6 if (type === 0) { p.plane(16 * multi) } else if (type === 1) { p.box(8 * multi, 8 * multi, 8 * multi) } else if (type === 2) { p.cylinder(8 * multi, 16 * multi) } else if (type === 3) { p.cone(8 * multi, 16 * multi) } else if (type === 4) { p.torus(16 * multi, 4 * multi) } else if (type === 5) { p.sphere(8 * multi) } else if (type === 6) { p.ellipsoid(8 * multi, 16, 2) } } static moveLightByMouse(p) { const y = ((p.mouseY / p.height) - 0.5) * 2 const x = ((p.mouseX / p.width) - 0.5) * 2 p.directionalLight(160, 160, 180, x, -y, 0.25) p.specularMaterial(50) } static translateByMouse(p) { p.orbitControl() } }
JavaScript
0.000105
@@ -214,49 +214,8 @@ 2%0A%0A - let radius = p.width * 1%0A @@ -266,32 +266,104 @@ = 17%0A + let geometricSizeMulti = 1%0A let radius = p.width * 1%0A let rotateX @@ -511,39 +511,8 @@ 010%0A - let geometricSizeMulti = 1%0A @@ -579,16 +579,76 @@ *= 2%0A + xMax = 10%0A yMax = 10%0A ge
77e69c4461c170091454826b159607d5a61b1be0
fix warning
packages/fela/menu/item.es6
packages/fela/menu/item.es6
import React from 'react'; import { createComponent } from 'olymp-fela'; import Image from './image'; const Content = createComponent( ({ theme }) => ({ ellipsis: true, flexGrow: 1, opacity: theme.collapsed ? 0 : 1, transition: 'opacity 200ms ease-out', overflowY: 'hidden', '> small': { display: 'block', marginTop: `-${theme.space1}`, color: theme.inverted ? theme.light2 : theme.dark2, }, }), 'div', p => Object.keys(p), ); export default createComponent( ({ theme, large, active, icon, onClick, color }) => ({ height: large ? 54 : 40, flexShrink: 0, width: !theme.collapsed ? '100%' : large ? 54 : 40, marginLeft: theme.collapsed && !large && 7, paddingLeft: !icon && theme.space3, display: 'flex', alignItems: 'center', cursor: !!onClick && 'pointer', borderRadius: theme.collapsed ? '50%' : theme.borderRadius, // backgroundColor: active && theme.dark4, backgroundColor: (color === true && theme.color) || theme[color] || color || (active && theme.dark4), onHover: { backgroundColor: !!onClick && theme.dark4, }, }), ({ large, children, subtitle, icon, extra, _ref, innerRef, ref, ...rest }) => ( <div {...rest} ref={_ref || innerRef || ref}> {!!icon && <Image large={large}>{icon}</Image>} <Content> {children} {!!subtitle && <small>{subtitle}</small>} </Content> {!!extra && <Image extra>{extra}</Image>} </div> ), ({ active, ...p }) => Object.keys(p), );
JavaScript
0.000004
@@ -1252,24 +1252,35 @@ f,%0A ref,%0A + color,%0A ...rest%0A
f07be703aa0654df5adaab376f9668edf99452e9
Upgrade NodeJS to v16 - fixed console.log in grib2json (#2)
packages/grib2json/index.js
packages/grib2json/index.js
import fs from 'fs-extra' import os from 'os' import path from 'path' import { fileURLToPath } from 'url' import { execFile } from 'child_process' const __dirname = path.dirname(fileURLToPath(import.meta.url)) const grib2jsonCommand = process.env.GRIB2JSON || path.join(__dirname, 'bin', os.platform() === 'win32' ? 'grib2json.cmd' : 'grib2json') const INTERNAL_OPTIONS = ['bufferSize', 'version', 'precision', 'verbose'] const grib2json = function (filePath, options) { const numberFormatter = function (key, value) { return value.toFixed ? Number(value.toFixed(options.precision)) : value } const promise = new Promise(function (resolve, reject) { let optionsNames = Object.keys(options) optionsNames = optionsNames.filter(arg => options[arg] && // These ones are used internally !INTERNAL_OPTIONS.includes(arg)) const args = [] optionsNames.forEach(name => { if (typeof options[name] === 'boolean') { args.push('--' + name) } else { args.push('--' + name) args.push(options[name].toString()) } }) // Last to come the file name args.push(filePath) execFile(grib2jsonCommand, args, { maxBuffer: options.bufferSize || 8 * 1024 * 1024 }, (error, stdout, stderr) => { if (error) { console.error(stderr) reject(error) return } if (options.output) { fs.readJson(options.output, (error, json) => { if (error) { reject(error) return } if (options.verbose) { json.forEach(variable => console.log('Wrote ' + variable.data.length + ' points into file for variable ', variable.header)) } if (options.precision >= 0) { fs.writeFile(options.output, JSON.stringify(json, numberFormatter), function (err) { if (err) { console.error('Writing output file failed : ', err) return } resolve(json) }) } else { resolve(json) } }) } else { const json = JSON.parse(stdout) if (options.verbose) { json.forEach(variable => console.log('Generated ' + variable.data.length + ' points in memory for variable ', variable.header)) } console.log(stdout) resolve(json) } }) }) return promise } export default grib2json
JavaScript
0
@@ -2314,32 +2314,34 @@ %7D%0A +// console.log(stdo
61dbe88cf0d1bef2b8acdbba4d001a91d2e91daa
move to createIndex
packages/loodb/src/index.js
packages/loodb/src/index.js
const mongoose = require('mongoose'); const LooSchema = require('./schemae/loo'); const ReportSchema = require('./schemae/report'); module.exports = exports = function connect(url) { const db = mongoose.createConnection(url); return { Loo: db.model('NewLoo', LooSchema), Report: db.model('NewReport', ReportSchema), db, }; };
JavaScript
0.000001
@@ -178,16 +178,56 @@ (url) %7B%0A + mongoose.set('useCreateIndex', true);%0A const
4ed1cc4d6574954ad6e3465929b027e697557381
Update namespace
lib/node_modules/@stdlib/ndarray/base/assert/lib/index.js
lib/node_modules/@stdlib/ndarray/base/assert/lib/index.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace ns */ var ns = {}; /** * @name isAllowedDataTypeCast * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-allowed-data-type-cast} */ setReadOnly( ns, 'isAllowedDataTypeCast', require( '@stdlib/ndarray/base/assert/is-allowed-data-type-cast' ) ); /** * @name isBufferLengthCompatible * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-buffer-length-compatible} */ setReadOnly( ns, 'isBufferLengthCompatible', require( '@stdlib/ndarray/base/assert/is-buffer-length-compatible' ) ); /** * @name isBufferLengthCompatibleShape * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-buffer-length-compatible-shape} */ setReadOnly( ns, 'isBufferLengthCompatibleShape', require( '@stdlib/ndarray/base/assert/is-buffer-length-compatible-shape' ) ); /** * @name isCastingMode * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-casting-mode} */ setReadOnly( ns, 'isCastingMode', require( '@stdlib/ndarray/base/assert/is-casting-mode' ) ); /** * @name isColumnMajor * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-column-major} */ setReadOnly( ns, 'isColumnMajor', require( '@stdlib/ndarray/base/assert/is-column-major' ) ); /** * @name isColumnMajorContiguous * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-column-major-contiguous} */ setReadOnly( ns, 'isColumnMajorContiguous', require( '@stdlib/ndarray/base/assert/is-column-major-contiguous' ) ); /** * @name isContiguous * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-contiguous} */ setReadOnly( ns, 'isContiguous', require( '@stdlib/ndarray/base/assert/is-contiguous' ) ); /** * @name isDataType * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-data-type} */ setReadOnly( ns, 'isDataType', require( '@stdlib/ndarray/base/assert/is-data-type' ) ); /** * @name isIndexMode * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-index-mode} */ setReadOnly( ns, 'isIndexMode', require( '@stdlib/ndarray/base/assert/is-index-mode' ) ); /** * @name isOrder * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-order} */ setReadOnly( ns, 'isOrder', require( '@stdlib/ndarray/base/assert/is-order' ) ); /** * @name isRowMajor * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-row-major} */ setReadOnly( ns, 'isRowMajor', require( '@stdlib/ndarray/base/assert/is-row-major' ) ); /** * @name isRowMajorContiguous * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-row-major-contiguous} */ setReadOnly( ns, 'isRowMajorContiguous', require( '@stdlib/ndarray/base/assert/is-row-major-contiguous' ) ); /** * @name isSafeDataTypeCast * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-safe-data-type-cast} */ setReadOnly( ns, 'isSafeDataTypeCast', require( '@stdlib/ndarray/base/assert/is-safe-data-type-cast' ) ); /** * @name isSameKindDataTypeCast * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-same-kind-data-type-cast} */ setReadOnly( ns, 'isSameKindDataTypeCast', require( '@stdlib/ndarray/base/assert/is-same-kind-data-type-cast' ) ); /** * @name isSingleSegmentCompatible * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/assert/is-single-segment-compatible} */ setReadOnly( ns, 'isSingleSegmentCompatible', require( '@stdlib/ndarray/base/assert/is-single-segment-compatible' ) ); // EXPORTS // module.exports = ns;
JavaScript
0.000001
@@ -3403,32 +3403,256 @@ is-order' ) );%0A%0A +/**%0A* @name isReadOnly%0A* @memberof ns%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/ndarray/base/assert/is-read-only%7D%0A*/%0AsetReadOnly( ns, 'isReadOnly', require( '@stdlib/ndarray/base/assert/is-read-only' ) );%0A%0A /**%0A* @name isRo
569dc0a7fbbe5626f5c9ebe37d42d3b6b458695a
Handle non-string values in arrays and sets used as filters.
django_cradmin/staticsources/django_cradmin/scripts/django_cradmin/widgets/ApiDataListWidget.js
django_cradmin/staticsources/django_cradmin/scripts/django_cradmin/widgets/ApiDataListWidget.js
import HttpDjangoJsonRequest from 'ievv_jsbase/http/HttpDjangoJsonRequest'; import typeDetect from 'ievv_jsbase/utils/typeDetect'; import AbstractDataListWidget from "./AbstractDataListWidget"; export default class ApiDataListWidget extends AbstractDataListWidget { // getDefaultConfig() { // const defaultConfig = super.getDefaultConfig(); // return defaultConfig; // } get classPath() { return 'django_cradmin.widgets.ApiDataListWidget'; } constructor(element, widgetInstanceId) { super(element, widgetInstanceId); if(!this.config.apiUrl) { throw new Error('apiUrl is a required config.'); } } requestItemData(key) { return new Promise((resolve, reject) => { let url = this.config.apiUrl; if(!this.config.apiUrl.endsWith('/')) { url = `${url}/`; } url = `${url}${key}`; const request = new HttpDjangoJsonRequest(url); request.get() .then((response) => { resolve(response.bodydata); }) .catch((error) => { reject(error); }); }); } addFiltersToQueryString(filtersMap, queryString) { for(let [filterKey, filterValue] of filtersMap) { let filterValueType = typeDetect(filterValue); if(filterValueType == 'string') { queryString.set(filterKey, filterValue); } else if(filterValueType == 'number') { queryString.set(filterKey, filterValue.toString()); } else if(filterValueType == 'array' || filterValueType == 'set') { queryString.setIterable(filterKey, filterValue); } else if(filterValueType == 'boolean') { if(filterValue) { queryString.set(filterKey, 'true'); } else { queryString.set(filterKey, 'false'); } } else if(filterValueType == 'null' || filterValueType == 'undefined') { // Do nothing } else { throw new Error( `Invalid filter value type for filterKey "${filterKey}". ` + `Type ${filterValueType} is not supported.`); } } } requestDataList(options) { return new Promise((resolve, reject) => { let url = this.config.apiUrl; if(options.next) { url = this.state.data.next; } else if(options.previous) { url = this.state.data.previous; } const request = new HttpDjangoJsonRequest(url); request.urlParser.queryString.set('search', options.searchString); this.addFiltersToQueryString(options.filtersMap, request.urlParser.queryString); if(this.logger.isDebug) { this.logger.debug('Requesting data list from API:', request.urlParser.buildUrl()); } request.get() .then((response) => { resolve(response.bodydata); }) .catch((error) => { reject(error); }); }); } moveItem(movingItemKey, moveBeforeItemKey) { if(!this.config.moveApiUrl) { throw new Error('Move support requires the moveApiUrl config.'); } return new Promise((resolve, reject) => { let url = this.config.moveApiUrl; const request = new HttpDjangoJsonRequest(url); const requestData = { moving_object_id: movingItemKey, move_before_object_id: moveBeforeItemKey }; if(this.logger.isDebug) { this.logger.debug( `Requesting move with a HTTP POST request to ${url} with the following request data:`, requestData); } request.post(requestData) .then((response) => { resolve(response.bodydata); }) .catch((error) => { reject(error); }); }); } }
JavaScript
0
@@ -1508,24 +1508,134 @@ == 'set') %7B%0A + let values = %5B%5D;%0A for(let value of filterValue) %7B%0A values.push(%60$%7Bvalue%7D%60);%0A %7D%0A quer @@ -1661,35 +1661,30 @@ (filterKey, -filterV +v alue +s );%0A %7D e
1f447239e8ef34b45b65c7ee94f4e44e0fbcca7e
Add fallback if translation is not found
options/options.js
options/options.js
function restoreOptions() { browser.storage.local.get([ "mode", "blacklist", "whitelist", "notificationPopupEnabled", "notificationDuration", ]).then( result => { setTextValue("blacklist", result.blacklist.join("\n")); setTextValue("whitelist", result.whitelist.join("\n")); setBooleanValue("mode" + result.mode.charAt(0).toUpperCase() + result.mode.slice(1), true); setBooleanValue("notificationPopupEnabled", result.notificationPopupEnabled); setTextValue("notificationDuration", result.notificationDuration); } ); } function enableAutosave() { for (let input of document.querySelectorAll("input:not([type=radio]):not([type=checkbox]), textarea")) { input.addEventListener("input", saveOptions); } for (let input of document.querySelectorAll("input[type=radio], input[type=checkbox]")) { input.addEventListener("change", saveOptions); } } function loadTranslations() { for (let element of document.querySelectorAll("[data-i18n]")) { if (typeof browser === "undefined") { element.textContent = element.getAttribute("data-i18n"); } else { element.innerHTML = browser.i18n.getMessage(element.getAttribute("data-i18n")); } } } function setTextValue(elementID, newValue) { let oldValue = document.getElementById(elementID).value; if (oldValue !== newValue) { document.getElementById(elementID).value = newValue; } } function setBooleanValue(elementID, newValue) { document.getElementById(elementID).checked = newValue; } function saveOptions(event) { event.preventDefault(); browser.storage.local.set({ blacklist: document.querySelector("#blacklist").value.split("\n"), whitelist: document.querySelector("#whitelist").value.split("\n"), mode: document.querySelector("#modeOff").checked && "off" || document.querySelector("#modeBlacklist").checked && "blacklist" || document.querySelector("#modeWhitelist").checked && "whitelist", notificationPopupEnabled: document.querySelector("#notificationPopupEnabled").checked, notificationDuration: document.querySelector("#notificationDuration").value, }); } document.addEventListener("DOMContentLoaded", restoreOptions); document.addEventListener("DOMContentLoaded", enableAutosave); document.addEventListener("DOMContentLoaded", loadTranslations); document.querySelector("form").addEventListener("submit", saveOptions); browser.storage.onChanged.addListener(restoreOptions);
JavaScript
0.000001
@@ -1106,42 +1106,150 @@ -if (typeof browser === %22undefined%22 +let translationKey = element.getAttribute(%22data-i18n%22);%0A if (typeof browser === %22undefined%22 %7C%7C !browser.i18n.getMessage(translationKey) ) %7B%0A @@ -1394,41 +1394,22 @@ age( -element.getAttribute(%22data-i18n%22) +translationKey );%0A
bb95834998e21b041e45d1167aeab285b1c3fbcb
Update BoundsArraySet_Depthwise.js
CNN/Conv/BoundsArraySet/BoundsArraySet_Depthwise.js
CNN/Conv/BoundsArraySet/BoundsArraySet_Depthwise.js
export { Depthwise }; import * as Pool from "../../util/Pool.js"; import * as FloatValue from "../../Unpacker/FloatValue.js"; import * as ValueDesc from "../../Unpacker/ValueDesc.js"; import { ConvBiasActivation } from "./BoundsArraySet_ConvBiasActivation.js"; import { ChannelPartInfo, FiltersBiasesPartInfo } from "../Depthwise/Depthwise_ChannelPartInfo.js"; /** * The element value bounds set for depthwise convolution-bias-activation. * * - Only input0 is used. The input1 is always undefined. * - Only outputChannelCount0 is used. The outputChannelCount1 is always zero. * * @see ConvBiasActivation */ class Depthwise extends ConvBiasActivation { /** * Used as default BoundsArraySet.Depthwise provider for conforming to Recyclable interface. */ static Pool = new Pool.Root( "BoundsArraySet.Depthwise.Pool", Depthwise, Depthwise.setAsConstructor ); /** * - The .input0 will be set as input0. * - The .afterUndoPreviousActivationEscaping will be set according to input0 and input0.scaleArraySet.undo.scales. */ constructor( input0, outputChannelCount0, channelShuffler_inputGroupCount ) { super( input0, outputChannelCount0, channelShuffler_inputGroupCount ); Depthwise.setAsConstructor_self.call( this, input0, outputChannelCount0, channelShuffler_inputGroupCount ); } /** @override */ static setAsConstructor( input0, outputChannelCount0, channelShuffler_inputGroupCount ) { super.setAsConstructor( input0, outputChannelCount0, channelShuffler_inputGroupCount ); Depthwise.setAsConstructor_self.call( this, input0, outputChannelCount0, channelShuffler_inputGroupCount ); return this; } /** @override */ static setAsConstructor_self( input0, outputChannelCount0, channelShuffler_inputGroupCount ) { // Infer channelMultiplier. this.channelMultiplier = outputChannelCount0 / input0.channelCount; } ///** @override */ //disposeResources() { // super.disposeResources(); //} /** * Set this.bPassThrough[] according to inChannelPartInfoArray. * * @param {Depthwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray * The input channel range array which describe lower/higher half channels index range. * * @return {BoundsArraySet.Depthwise} * Return the this object. */ set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray ) { let inChannelBegin = 0, inChannelEnd = 0, // [ inChannelBegin, inChannelEnd ) are input channels of the current FiltersBiasesPart. outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart. FiltersBiasesPartIndexLoop: for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) { let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ]; let inChannelPartInfoArray = aFiltersBiasesPartInfo; inChannelBegin = inChannelEnd; outChannelBegin = outChannelEnd; { let inChannel = inChannelBegin; let outChannel = outChannelBegin; InChannelPartIndexLoop: for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) { let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ]; for ( let inChannelSub = 0; inChannelSub < inChannelPartInfo.inputChannelCount; ++inChannelSub, ++inChannel ) { if ( inChannel >= this.inputChannelCount0 ) break InChannelPartIndexLoop; // Never exceeds the total input channel count. for ( let outChannelSub = 0; outChannelSub < this.channelMultiplier; ++outChannelSub, ++outChannel ) { this.bPassThrough[ outChannel ] = inChannelPartInfo.bPassThrough; } // outChannelSub, outChannel } // inChannelSub, inChannel } // inChannelPartIndex inChannelEnd = inChannel; outChannelEnd = outChannel; } } // aFiltersBiasesPartIndex return this; } }
JavaScript
0.000001
@@ -1283,41 +1283,8 @@ unt0 -, channelShuffler_inputGroupCount );%0A @@ -1570,41 +1570,8 @@ unt0 -, channelShuffler_inputGroupCount );%0A @@ -1674,77 +1674,12 @@ unt0 -, channelShuffler_inputGroupCount ) %7B%0A // Infer channelMultiplier. + ) %7B %0A @@ -1746,16 +1746,44 @@ elCount; + // Infer channelMultiplier. %0A %7D%0A%0A
a89e45e5b162eedda7daee3825cd66096dd2b3e4
Update BoundsArraySet_Pointwise.js
CNN/Conv/BoundsArraySet/BoundsArraySet_Pointwise.js
CNN/Conv/BoundsArraySet/BoundsArraySet_Pointwise.js
export { Pointwise }; export { PointwisePool }; import * as FloatValue from "../../Unpacker/FloatValue.js"; import * as ValueDesc from "../../Unpacker/ValueDesc.js"; import * as Weights from "../../Unpacker/Weights.js"; import { ConvBiasActivation } from "./BoundsArraySet_ConvBiasActivation.js"; import { ChannelPartInfo, FiltersBiasesPartInfo } from "../Pointwise/Pointwise_ChannelPartInfo.js"; /** * The element value bounds for pointwise convolution-bias-activation. * * - Only input0 is used. The input1 is always undefined. * - Only outputChannelCount0 is used. The outputChannelCount1 is always zero. * * @see ConvBiasActivation */ class Pointwise extends ConvBiasActivation { /** * - The .input0 will be set as input0. * - The .afterUndoPreviousActivationEscaping will be set according to input0 and input0.scaleArraySet.undo.scales. */ constructor( input0, outputChannelCount0 ) { super( input0, outputChannelCount0 ); } /** * After calling this method, this object should be viewed as disposed and should not be operated again. */ disposeResources_and_recycleToPool() { //this.disposeResources(); PointwisePool.Singleton.recycle( this ); } /** * Set this.bPassThrough[] according to inChannelPartInfoArray. * * @param {Pointwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray * The input channel range array which describe lower/higher half channels index range. * * @return {BoundsArraySet.Pointwise} * Return the this object. */ set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray ) { let outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart. FiltersBiasesPartIndexLoop: for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) { let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ]; let inChannelPartInfoArray = aFiltersBiasesPartInfo.aChannelPartInfoArray; outChannelBegin = outChannelEnd; // Begin from the ending of the previous FiltersBiasesPart. { let outChannel = outChannelBegin; InChannelPartIndexLoop: for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) { let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ]; for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) { if ( outChannel >= this.outputChannelCount0 ) break InChannelPartIndexLoop; // Never exceeds the total output channel count. this.bPassThrough[ outChannel ] = inChannelPartInfo.bPassThrough; } // outChannelSub, outChannel } // inChannelPartIndex outChannelEnd = outChannel; // Record the ending output channel index of the current FiltersBiasesPart. } } // aFiltersBiasesPartIndex return this; } } /** * Providing BoundsArraySet.Pointwise * */ class PointwisePool extends Pool.Root { constructor() { super( Pointwise, PointwisePool.setAsConstructor ); } /** * @param {Depthwise} this * The Depthwise object to be initialized. * * @return {Depthwise} * Return the this object. */ static setAsConstructor( input0, outputChannelCount0 ) { this.set_input0_outputChannelCount0( input0, outputChannelCount0 ); return this; } } /** * Used as default BoundsArraySet.Pointwise provider. */ PointwisePool.Singleton = new PointwisePool();
JavaScript
0
@@ -3208,16 +3208,48 @@ super( + %22BoundsArraySet.PointwisePool%22, Pointwi
8bab75249e848f199b08676e5a744aaa6fddbb8e
Enable first ad render audit for AdSense (#126)
lighthouse-plugin-publisher-ads/audits/first-ad-render.js
lighthouse-plugin-publisher-ads/audits/first-ad-render.js
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. const ComputedAdRenderTime = require('../computed/ad-render-time'); const i18n = require('lighthouse/lighthouse-core/lib/i18n/i18n'); const {auditNotApplicable, runWarning} = require('../messages/common-strings'); const {Audit} = require('lighthouse'); const {isAdIframe, isGptIframe} = require('../utils/resource-classification'); const UIStrings = { title: 'Latency of first ad render', failureTitle: 'Reduce time to render first ad', description: 'This metric measures the time for the first ad iframe to ' + 'render from page navigation. [Learn more](' + 'https://developers.google.com/publisher-ads-audits/reference/audits/metrics' + ').', displayValue: '{timeInMs, number, seconds} s', }; const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); // Point of diminishing returns. const PODR = 2700; // ms const MEDIAN = 3700; // ms /** * Measures the first ad render time. */ class FirstAdRender extends Audit { /** * @return {LH.Audit.Meta} * @override */ static get meta() { // @ts-ignore return { id: 'first-ad-render', title: str_(UIStrings.title), failureTitle: str_(UIStrings.failureTitle), description: str_(UIStrings.description), // @ts-ignore scoreDisplayMode: Audit.SCORING_MODES.NUMERIC, // @ts-ignore requiredArtifacts: ['devtoolsLogs', 'traces'], }; } /** * @param {Artifacts} artifacts * @param {LH.Audit.Context} context * @return {Promise<LH.Audit.Product>} */ static async audit(artifacts, context) { const trace = artifacts.traces[Audit.DEFAULT_PASS]; const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS]; const metricData = { devtoolsLog, trace, settings: context.settings, }; const {timing} = await ComputedAdRenderTime.request(metricData, context); if (!(timing > 0)) { // Handle NaN, etc. // Currently only GPT ads are supported by this audit. const nonGptAdSlots = artifacts.IFrameElements.filter( (iframe) => isAdIframe(iframe) && !isGptIframe(iframe)); if (nonGptAdSlots.length === 0) { context.LighthouseRunWarnings.push(runWarning.NoAdRendered); } return auditNotApplicable.NoAdRendered; } let normalScore = Audit.computeLogNormalScore(timing, PODR, MEDIAN); if (normalScore >= 0.9) normalScore = 1; return { numericValue: timing * 1e-3, score: normalScore, displayValue: str_(UIStrings.displayValue, {timeInMs: timing}), }; } } module.exports = FirstAdRender; module.exports.UIStrings = UIStrings;
JavaScript
0
@@ -838,87 +838,8 @@ e'); -%0Aconst %7BisAdIframe, isGptIframe%7D = require('../utils/resource-classification'); %0A%0Aco @@ -2399,237 +2399,8 @@ tc.%0A - // Currently only GPT ads are supported by this audit.%0A const nonGptAdSlots = artifacts.IFrameElements.filter(%0A (iframe) =%3E isAdIframe(iframe) && !isGptIframe(iframe));%0A if (nonGptAdSlots.length === 0) %7B%0A @@ -2466,16 +2466,8 @@ d);%0A - %7D%0A
6b57036255e0055ce1fbdb91928c1924d7308142
update botmanager
botManager.js
botManager.js
var fs = require('fs'); var separator = '############################################################################\n'; var respId = 0; var variables = require('./variables'); var feedback_chatId = variables['feedback_chatId']; function processOnText(msg, match) { var resp = null; var timestamp = new Date(); var messagesToSend = []; var openingh = require('./openingh'); var chatId = msg.chat.id; //Mensas, die Abendessen Haben var dinner_dict = { "poly" : "Mensa Polyterrasse", "pizzapasta" : "food market - pizza pasta" } //Übersetzt den einfacheren Befehl zum komplizierteren Mensanamen im JSON var dict = { "cliff" : "Clausiusbar", "haoyi" : "Woka", "poly" : "Mensa Polyterrasse", "foodlab" : "foodLAB", "clausiusbar" : "Clausiusbar", "asia" : "Clausiusbar", "fusion" : "FUSION meal", "woka" : "Woka", "tannenbar" : "Tannenbar", "trailer" : "Foodtrailer ETZ", "dozentenfoyer" : "Dozentenfoyer", "grill" : "food market - grill bbQ", "pizzapasta" : "food market - pizza pasta", "green" : "food market - green day", }; console.log(msg); console.log(JSON.stringify(match)); fs.appendFile('logs/requests.log', separator + timestamp + '\n\n' + JSON.stringify(msg) + '\n' + separator, function (err) { console.log(err); }); //Feedback if(match[0].indexOf('/feedback') != -1 || match[0].indexOf('/respond') != -1) { if (match[0] === '/feedback'){ resp = '*Feedback für Dummies:*\n/feedback <Deine Nachricht>'; }else if(match[0].indexOf('/feedback')!=-1){ respId=chatId; fs.appendFile('logs/feedback.log', separator + '\n\n' + timestamp + '\n\n' + JSON.stringify(msg) + '\n\n', function (err) { console.log(err); }); resp = 'Vielen Dank für Dein Feedback!'; messagesToSend.push({chatId:-106064170, message:'New feedback:\n\n' + JSON.stringify(msg)}); }else if(match[0].indexOf('/respond') != -1){ resp = match[0].split('respond'); resp = resp[1]; chatId = respId; } }else{ //Chopping '@...' from the command if needed var command = match[1].split('@'); command = command[0]; //Nicht ideal weil ja nicht ein Strang, aber funktioniert so weit ganz gut (denke ich): //Checking whether a cafeteria has dinner and if its late enough to display the dinner menu if (command in dinner_dict && timestamp.getHours() >= 14){ command = dinner_dict[command]; var mensas = require('./mensas_abig.json'); var t = 1; //Checking whether its a known cafeteria }else if (command in dict){ command = dict[command]; var mensas = require('./mensas.json'); var t = 0; //...help/start, opening hours } if(command in openingh){ resp = openingh[command]; //Mensa }else if(command in mensas){ //Weekend? if(timestamp.getDay() === 6 || timestamp.getDay() === 0){ resp = "Heute haben leider alle Mensen geschlossen, sorry!"; //If weekday, wanted information is formatted as follows: }else{ resp = "*" + command + "*\n_Essen von " + mensas[command].hours.mealtime[t]["from"] +" bis " +mensas[command].hours.mealtime[t]["to"] + " Uhr_\n\n"; for (var meal in mensas[command]["meals"]){ var description = ""; for (i in mensas[command]["meals"][meal]["description"]){ description += mensas[command]["meals"][meal]["description"][i]+ " " ; if (i === "0"){ description += "\n"; } } resp += "*" +mensas[command]["meals"][meal]["label"] + " (" + mensas[command]["meals"][meal]["prices"]["student"]+ "/" +mensas[command]["meals"][meal]["prices"]["staff"] + "/" + mensas[command]["meals"][meal]["prices"]["extern"]+"):*\n" + description + "\n"; } } } } messagesToSend.push({chatId:chatId, message:resp, options:{parse_mode: 'Markdown'}}); fs.appendFile('logs/handled_requests.log', separator + timestamp + '\n\n' + JSON.stringify(msg,null,2) + '\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\nRESPONSE:\n\n' + resp + '\n', function (err) { console.log(err); }); return messagesToSend; } module.exports.processOnText = processOnText;
JavaScript
0.000001
@@ -4436,32 +4436,203 @@ %7D%0A + if (resp === null)%7B%0A resp = %22Tut mir Leid, aber es sieht so aus als g%C3%A4be es f%C3%BCr diese Mensa heute leider kein Men%C3%BC.%22;%0A %7D%0A %7D%0A
513f4f28081594d8994122cf43c2ad47d234caff
Update browser filename.
browserify.js
browserify.js
'use strict'; /** * Dependencies */ var fs = require('fs'); var browserify = require('browserify'); /** * Create directories */ if (!fs.existsSync('./browser')) { fs.mkdirSync('./browser'); } /** * Browserify */ browserify({ 'entries': './src/index.js', 'standalone': 'bus', 'debug': true }) .transform('babelify', {'loose': ['es6.modules']}) .bundle() .on('error', function (err) { console.log('Error : ' + err.message); }) .pipe(fs.createWriteStream('browser/bus.js'));
JavaScript
0
@@ -473,18 +473,20 @@ browser/ -bus +index .js'));
993025c478950440118a81d4a33fc2abad354fd0
Update .pa11yci-pr.conf.js (#42148)
.pa11yci-pr.conf.js
.pa11yci-pr.conf.js
var config = { defaults: { concurrency: 1, runners: ['axe'], useIncognitoBrowserContext: false, chromeLaunchConfig: { args: ['--no-sandbox'], }, }, urls: [ { url: '${HOST}/login', wait: 500, rootElement: '.main-view', threshold: 12, }, { url: '${HOST}/login', wait: 500, actions: [ "wait for element input[name='user'] to be added", "set field input[name='user'] to admin", "set field input[name='password'] to admin", "click element button[aria-label='Login button']", "wait for element [aria-label='Skip change password button'] to be visible", ], threshold: 13, rootElement: '.main-view', }, { url: '${HOST}/?orgId=1', wait: 500, threshold: 0, }, { url: '${HOST}/d/O6f11TZWk/panel-tests-bar-gauge', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/d/O6f11TZWk/panel-tests-bar-gauge?orgId=1&editview=settings', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/?orgId=1&search=open', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/alerting/list', wait: 500, rootElement: '.main-view', // the unified alerting promotion alert's content contrast is too low // see https://github.com/grafana/grafana/pull/41829 threshold: 5, }, { url: '${HOST}/datasources', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/org/users', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/org/teams', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/plugins', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/org', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/org/apikeys', wait: 500, rootElement: '.main-view', threshold: 0, }, { url: '${HOST}/dashboards', wait: 500, rootElement: '.main-view', threshold: 0, }, ], }; function myPa11yCiConfiguration(urls, defaults) { const HOST_SERVER = process.env.HOST || 'localhost'; const PORT_SERVER = process.env.PORT || '3001'; for (var idx = 0; idx < urls.length; idx++) { urls[idx] = { ...urls[idx], url: urls[idx].url.replace('${HOST}', `${HOST_SERVER}:${PORT_SERVER}`) }; } return { defaults: defaults, urls: urls, }; } module.exports = myPa11yCiConfiguration(config.urls, config.defaults);
JavaScript
0
@@ -284,17 +284,17 @@ shold: 1 -2 +3 ,%0A %7D, @@ -690,25 +690,25 @@ threshold: 1 -3 +4 ,%0A root
82abd4455890ab2fe46ae926feb689b93cee2a8e
Fix JS
modules/chat/client/controllers/chat.client.controller.js
modules/chat/client/controllers/chat.client.controller.js
'use strict'; // Create the 'chat' controller angular.module('chat').controller('ChatController', ['$scope', '$location', 'Authentication', 'Socket', function ($scope, $location, Authentication, Socket) { // Create a messages array $scope.discussion = Discussion.get({ discussionId: $stateParams.discussionId }); $scope.messages = []; $scope.rooms = [{ messages: [], name: '' }]; // If user is not signed in then redirect back home $scope.user = Authentication.user; if (!Authentication.user) { $location.path('/'); } // Make sure the Socket is connected if (!Socket.socket) { Socket.connect(); } var room = { roomID: $stateParams.discussionId }; Socket.emit('createRoom', room); // Add an event listener to the 'chatMessage' event Socket.on('chatMessage', function (message) { //$scope.messages.unshift(message); $scope.messages.push(message); }); // Create a controller method for sending messages $scope.sendMessage = function () { // Create a new message object var message = { text: this.messageText }; // Emit a 'chatMessage' message event Socket.emit('chatMessage', message); // Clear the message text this.messageText = ''; }; // Remove the event listener when the controller instance is destroyed $scope.$on('$destroy', function () { Socket.removeListener('chatMessage'); }); } ]);
JavaScript
0.000591
@@ -143,16 +143,46 @@ Socket', + 'Discussion', '$stateParams', %0A funct @@ -223,24 +223,50 @@ tion, Socket +, Discussion, $stateParams ) %7B%0A // C
1a8df5324d1ef2bf5c9951d38f9b6efc6ae285ef
Update girls.js
js/girls.js
js/girls.js
function fetch(url){ $.getJSON(url,function(x,st){ if(st==='success'){ if(x.count>0){ var _ts=x.topics; $.each(_ts,function(i,t){ //well if(t.comments_count>10){ var _ps=t.photos; $.each(_ps,function(j,p){ addIMG(p.alt,p.title); }); }else{ //not popular } }); } } }); } function addIMG(alt,title){ // todo if(!!alt){ var img='<img src="'+alt+'" title="'+title+'" class="img-thumbnail" width="5%" >'; $(img).insertAfter('#_start'); } } var latest; $('.girls').delegate('img','click',function(){ if(!!latest){ sea(latest,'5%'); } sea($(this),'auto'); latest=$(this); }); function sea(obj,arg){ $(obj).css('width',arg); $(obj).css('height',arg); } var _urls=[ 'https://api.douban.com/v2/group/407518/topics?count=1&callback=?', //'https://api.douban.com/v2/group/kaopulove/topics?callback=?', //'https://api.douban.com/v2/group/ai_Junko/topics?callback=?', //'https://api.douban.com/v2/group/haixiuzu/topics?callback=?', ]; function shuffle(o){ for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } function letsdance(){ shuffle(_urls).every(function(x){ fetch(x); return true; }); } letsdance();
JavaScript
0
@@ -397,16 +397,18 @@ alt)%7B%0A%0A%09 +// %09var img @@ -482,16 +482,68 @@ %225%25%22 %3E'; +%0A%09%09var img='%3Cimg src=%22'+alt+'%22 title=%22'+title+'%22 %3E'; %0A%0A%09%09$(im