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
a24663bd9b42d20543f903bfb31ec5171fd32938
update internal vars in setBio to use info
commands/info/setBio.js
commands/info/setBio.js
/** * @file setBio command * @author Sankarsan Kampa (a.k.a k3rn31p4nic) * @license GPL-3.0 */ exports.exec = async (Bastion, message, args) => { try { if (args.length < 1) { /** * The command was ran with invalid parameters. * @fires commandUsage */ return Bastion.emit('commandUsage', message, this.help); } args = args.join(' '); let charLimit = 160; let bio = await Bastion.methods.encodeString(args); if (bio.length > charLimit) { /** * Error condition is encountered. * @fires error */ return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'bioRange', charLimit), message.channel); } let userModel = await Bastion.database.models.user.findOne({ attributes: [ 'info' ], where: { userID: message.author.id } }); if (!userModel) { return message.channel.send({ embed: { description: `<@${args.id}> you didn't had a profile yet. I've now created your profile. Now you can use the command again to set your bio.` } }).catch(e => { Bastion.log.error(e); }); } await Bastion.database.models.user.update({ info: bio }, { where: { userID: message.author.id }, fields: [ 'info' ] }); message.channel.send({ embed: { color: Bastion.colors.GREEN, title: 'Bio Set', description: args, footer: { text: args.tag } } }).catch(e => { Bastion.log.error(e); }); } catch (e) { Bastion.log.error(e); } }; exports.config = { aliases: [], enabled: true }; exports.help = { name: 'setBio', description: 'Sets your bio that shows up in the Bastion user profile.', botPermission: '', userTextPermission: '', userVoicePermission: '', usage: 'setBio <text>', example: [ 'setBio I\'m awesome. :sunglasses:' ] };
JavaScript
0
@@ -409,18 +409,19 @@ let -b i +nf o = awai @@ -467,18 +467,19 @@ if ( -b i +nf o.length @@ -1231,18 +1231,19 @@ info: -b i +nf o%0A %7D,
bc9e0b78a528787d917d97e728fa8fd70837e6a3
Add getAllKeys support
src/app/store/storage.js
src/app/store/storage.js
let storage = chrome.storage.local; storage._lastData = null; // Deal with Chrome issue https://code.google.com/p/chromium/issues/detail?id=361113 storage.getItem = (key, callback) => { chrome.storage.local.get(key, obj => { if (obj[key]) callback(null, obj[key]); else callback(chrome.runtime.lastError, null); }); }; storage.setItem = (key, value, callback) => { let obj = {}; obj[key] = value; chrome.storage.local.set(obj, () => { if (chrome.runtime.lastError) callback(key); }); storage._lastData = value; }; storage.removeItem = storage.remove; storage.getAllKeys = callback => { // Do not need this, use storage.clear() for purgeAll instead }; export default storage;
JavaScript
0
@@ -616,69 +616,91 @@ %7B%0A -// Do not need this, use storage.clear() for purgeAll instead +chrome.storage.local.get(null, obj =%3E %7B%0A callback(null, Object.keys(obj));%0A %7D); %0A%7D;%0A
661d1afd4f316db590a7c9a3812d4637c701dc06
update conversationHandler to use Bastion Cleverbot API
handlers/conversationHandler.js
handlers/conversationHandler.js
/** * @file conversationHandler * @author Sankarsan Kampa (a.k.a k3rn31p4nic) * @license GPL-3.0 */ const CLEVERBOT = xrequire('cleverbot.js'); const CREDENTIALS = xrequire('./settings/credentials.json'); const BOT = new CLEVERBOT({ APIKey: CREDENTIALS.cleverbotAPIkey }); /** * Handles conversations with Bastion * @param {Message} message Discord.js message object * @returns {void} */ module.exports = async message => { try { if (message.content.length <= `${message.client.user} `.length) return; let guildModel = await message.client.database.models.guild.findOne({ attributes: [ 'chat' ], where: { guildID: message.guild.id } }); if (!guildModel.dataValues.chat) return; let response = await BOT.write(message.content); if (response.output) { message.channel.startTyping(); setTimeout(async () => { try { message.channel.stopTyping(true); await message.channel.send(response.output); } catch (e) { message.client.log.error(e); } }, response.output.length * 100); } } catch (e) { message.client.log.error(e); } };
JavaScript
0
@@ -108,67 +108,18 @@ nst -CLEVERBOT = xrequire('cleverbot.js');%0Aconst CREDENTIALS +request = -x requ @@ -127,106 +127,31 @@ re(' -./settings/credentials.json');%0Aconst BOT = new CLEVERBOT(%7B%0A APIKey: CREDENTIALS.cleverbotAPIkey%0A%7D +request-promise-native' );%0A%0A @@ -606,24 +606,60 @@ eturn;%0A%0A + message.channel.startTyping();%0A%0A let response @@ -654,166 +654,272 @@ let -resp +opti ons -e = -await BOT.write(message.content);%0A if (response.output) %7B%0A message.channel.startTyping( +%7B%0A url: 'https://bastion-cleverbot.glitch.me/api',%0A qs: %7B%0A message: message.content.replace(/%3C@!?%5B0-9%5D%7B1,20%7D%3E ?/i, '')%0A %7D,%0A json: true%0A %7D;%0A let response = await request(options );%0A +%0A - setTimeout(async () =%3E %7B%0A try %7B%0A +if (response.status === 'success') %7B%0A @@ -960,20 +960,16 @@ ;%0A - - await me @@ -1000,133 +1000,134 @@ nse. -output);%0A %7D%0A catch (e) %7B%0A message.client.log.error(e);%0A %7D%0A %7D, response.output.length * 100 +response);%0A %7D%0A else %7B%0A message.channel.stopTyping(true);%0A await message.channel.send('Beep. Beep. Boop. Boop.' );%0A
4bc73dec9677cd0439fe836c8d47bd9148f05912
Move some code from router to external file
BackofficeBundle/Resources/public/js/backboneRouter.js
BackofficeBundle/Resources/public/js/backboneRouter.js
var OrchestraBORouter = Backbone.Router.extend({ //========[ROUTES LIST]===============================// routes: { 'node/show/:nodeId': 'showNode', 'template/show/:templateId': 'showTemplate', 'template/create': 'createTemplate', 'contents/list/:contentTypeId': 'listContents', 'websites/list': 'listSites', 'content-types/list': 'listContentTypes', 'translation': 'listTranslations', '': 'showHome' }, initialize: function() { }, //========[ACTIONS LIST]==============================// showHome: function() { drawBreadCrumb(); }, showNode: function(nodeId) { this.initDisplayRouteChanges(); showNode($("#nav-node-" + nodeId).data("url")); }, createNode: function(parentNodeId) { this.showNodeForm($("#nav-createNode-" + parentNodeId)); }, showTemplate: function(templateId) { this.initDisplayRouteChanges(); showTemplate($("#nav-template-" + templateId).data("url")); }, listContents: function(contentTypeId) { this.initDisplayRouteChanges(); tableViewLoad($("#nav-contents-" + contentTypeId)); }, listSites: function() { this.initDisplayRouteChanges(); tableViewLoad($("#nav-websites")); }, listContentTypes: function() { this.initDisplayRouteChanges(); tableViewLoad($("#nav-contentTypes")); }, createTemplate: function() { var templateRoot = $("#nav-createTemplate"); this.showNodeForm(templateRoot); }, listTranslations: function() { drawBreadCrumb(); return new TranslationView( {url : $("#nav-translation").data("url")} ); }, //========[INTERNAL FUNCTIONS]========================// initDisplayRouteChanges: function() { var url = '#' + Backbone.history.fragment; $('nav li.active').removeClass("active"); $('nav li:has(a[href="' + url + '"])').addClass("active"); var title = ($('nav a[href="' + url + '"]').attr('title')) document.title = (title || document.title); drawBreadCrumb(); displayLoader(); }, showNodeForm: function(parentNode) { $('.modal-title').text(parentNode.text()); $.ajax({ url: parentNode.data('url'), method: 'GET', success: function(response) { $('#OrchestraBOModal').modal('show'); var view; return view = new adminFormView({ html: response }); } }); }, //========[INTERNAL FUNCTIONS]========================// initDisplayRouteChanges: function() { var url = '#' + Backbone.history.fragment; $('nav li.active').removeClass("active"); $('nav li:has(a[href="' + url + '"])').addClass("active"); var title = ($('nav a[href="' + url + '"]').attr('title')) document.title = (title || document.title); drawBreadCrumb(); displayLoader(); }, }); var appRouter = new OrchestraBORouter(); Backbone.history.start();
JavaScript
0
@@ -744,29 +744,24 @@ deId) %7B%0A -this. showNodeForm @@ -2372,432 +2372,8 @@ %7D,%0A%0A -//========%5BINTERNAL FUNCTIONS%5D========================//%0A%0A initDisplayRouteChanges: function() %7B%0A var url = '#' + Backbone.history.fragment;%0A $('nav li.active').removeClass(%22active%22);%0A $('nav li:has(a%5Bhref=%22' + url + '%22%5D)').addClass(%22active%22);%0A %0A var title = ($('nav a%5Bhref=%22' + url + '%22%5D').attr('title'))%0A document.title = (title %7C%7C document.title);%0A %0A drawBreadCrumb();%0A displayLoader();%0A %7D,%0A%0A %7D);%0A
c4384bc0eb70db1dc53b48b087e1463551b6487e
Use the matchToken in common
common.notifications.js
common.notifications.js
// Notifications collection Push.notifications = new Mongo.Collection('_raix_push_notifications'); // This is a general function to validate that the data added to notifications // is in the correct format. If not this function will throw errors var _validateDocument = function(notification) { // Define how tokens should look like var matchToken = Match.OneOf({ apn: String }, { gcm: String }); // Check the general notification check(notification, { from: String, title: String, text: String, count: Number, query: Match.Optional(Object), token: Match.Optional(matchToken), tokens: Match.Optional([matchToken]), createdAt: Date, createdBy: Match.OneOf(String, null) }); // Make sure a token selector or query have been set if (!notification.token && !notification.tokens && !notification.query) throw new Error('No token selector or query found'); // If tokens array is set it should not be empty if (notification.tokens && !notification.tokens.length) throw new Error('No tokens in array'); }; Push.send = function(options) { // Rig the notification object var notification = { from: options.from, title: options.title, text: options.text, count: options.count || 0, createdAt: new Date(), // If on the client we set the user id - on the server we need an option // set or we default to "<SERVER>" as the creator of the notification createdBy: (Meteor.isClient) ? Meteor.userId() : (options.createdBy || '<SERVER>') }; // Set one token selector, this can be token, array of tokens or query if (options.query) { // Set query notification.query = options.query; } else if (options.token) { // Set token notification.token = options.token; } else if (options.tokens) { // Set tokens notification.tokens = options.tokens; } // Validate the notification _validateDocument(notification); // Try to add the notification to send, we return an id to keep track return Push.notifications.insert(notification); }; Push.allow = function(rules) { if (rules.send) { Push.notifications.allow({ 'insert': function(userId, notification) { // Validate the notification _validateDocument(notification); // Set the user defined "send" rules return rules.send.apply(this, [userId, notification]); } }); } }; Push.deny = function(rules) { if (rules.send) { Push.notifications.deny({ 'insert': function(userId, notification) { // Validate the notification _validateDocument(notification); // Set the user defined "send" rules return rules.send.apply(this, [userId, notification]); } }); } };
JavaScript
0.000001
@@ -292,114 +292,8 @@ n) %7B -%0A // Define how tokens should look like%0A var matchToken = Match.OneOf(%7B apn: String %7D, %7B gcm: String %7D); %0A%0A @@ -485,16 +485,17 @@ ptional( +_ matchTok @@ -527,16 +527,17 @@ tional(%5B +_ matchTok
14c3ee2a8b4112ac0cce7d9decaa84cd4f7b3e9e
Update http-event-collector.js
http-event-collector/http-event-collector.js
http-event-collector/http-event-collector.js
var bunyan = require("bunyan"); var splunkBunyan = require("splunk-bunyan-logger"); module.exports = function(RED) { function HTTPEventCollector(config) { RED.nodes.createNode(this,config); var context = this.context(); var node = this; var myMessage = null; /** * Only the token property is required. */ this.myURI = config.inputURI.toString(); this.myToken = config.inputToken.toString(); this.mySourcetype = config.inputSourcetype.toString(); this.myHost = config.inputHost.toString(); this.mySource = config.inputSource.toString(); this.myIndex = config.inputIndex.toString(); var config = { token: this.myToken, url: this.myURI }; var splunkStream = splunkBunyan.createStream(config); // Note: splunkStream must be set to an element in the streams array var Logger = bunyan.createLogger({ name: "my logger", streams: [ splunkStream ] }); Logger.error = function(err, context) { // Handle errors here console.log("error", err, "context", context); }; this.on('input', function(msg) { // Attempt to convert msg.payload to a json structure. try{ myMessage = JSON.parse(msg.payload) } catch(err){ myMessage = msg.payload } var payload = { // Data sent from previous node msg.payload message : { payload: myMessage, msgMetaData : msg }, // Metadata metadata: { source: this.mySource, sourcetype: this.mySourcetype, index: this.myIndex, host: this.myHost }, // Severity is also optional severity: "info" }; delete payload.message.msgMetaData.payload; console.log("Sending payload", payload); Logger.info(payload, "Chicken coup looks stable."); }); } RED.nodes.registerType("http-event-collector",HTTPEventCollector); };
JavaScript
0
@@ -2187,34 +2187,47 @@ d, %22 -Chicken coup looks stable. +Data from Node-RED HTTP Event Collector %22);%0A
eaa6cc1aca486e07771c198c0564f85b456cc221
change for flashcard, arrows moving
public/vishEditor/js/VISH.Editor.Flashcard.js
public/vishEditor/js/VISH.Editor.Flashcard.js
VISH.Editor.Flashcard = (function(V,$,undefined){ var init = function(){ $(document).on("click", "#flashcard_button", _onFlashcardButtonClicked ); }; var _onFlashcardButtonClicked = function(){ //first action, set excursion type to "flashcard" V.Editor.setExcursionType("flashcard"); //hide slides V.Editor.Utils.hideSlides(); //change thumbnail onclick event (preview slide instead of go to edit it) //it will change itself depending on excursionType V.Editor.Thumbnails.redrawThumbnails(); //show flashcard background, should be an image with help $("#flashcard-background").show(); //show change background button //show draggable items to create the flashcard //THIS ACTION WILL HAVE TO BE CALLED AFTER THE THUMBNAILS HAVE BEEN REWRITTEN //var también si se pudiese hacer appendTo al background y así poder calcular facil la posición final $("#poi1").draggable(); $(".image_carousel").css("overflow", "auto"); }; return { init : init }; }) (VISH, jQuery);
JavaScript
0
@@ -698,16 +698,20 @@ ard%0A%09%09// +ALL THIS ACT @@ -713,16 +713,17 @@ S ACTION +S WILL HA @@ -953,22 +953,238 @@ %22, %22 -auto +visible%22);%0A%09%09$(%22#menubar%22).css(%22z-index%22, %222000 %22);%0A +%09%09 %0A%09%09 -%0A%09%09 +//cuando se salva en el vish.editor.js puedo recorrer todos los poiX y ver su offset(), que da la posicion en el iframe%0A%09%09//con eso calculo su posici%C3%B3n final en el background %0A%09%7D;
1f005908a4d989ad2b6984f1fda3b83d65f95b8f
Fix failing boilerplate tests (#23234)
aio/tools/examples/example-boilerplate.spec.js
aio/tools/examples/example-boilerplate.spec.js
const path = require('canonical-path'); const fs = require('fs-extra'); const glob = require('glob'); const shelljs = require('shelljs'); const exampleBoilerPlate = require('./example-boilerplate'); describe('example-boilerplate tool', () => { describe('add', () => { const sharedDir = path.resolve(__dirname, 'shared'); const sharedNodeModulesDir = path.resolve(sharedDir, 'node_modules'); const BPFiles = { cli: 18, i18n: 1, universal: 2, systemjs: 7, common: 1 }; const exampleFolders = ['a/b', 'c/d']; beforeEach(() => { spyOn(fs, 'ensureSymlinkSync'); spyOn(fs, 'existsSync').and.returnValue(true); spyOn(exampleBoilerPlate, 'copyFile'); spyOn(exampleBoilerPlate, 'getFoldersContaining').and.returnValue(exampleFolders); spyOn(exampleBoilerPlate, 'loadJsonFile').and.returnValue({}); }); it('should process all the example folders', () => { const examplesDir = path.resolve(__dirname, '../../content/examples'); exampleBoilerPlate.add(); expect(exampleBoilerPlate.getFoldersContaining) .toHaveBeenCalledWith(examplesDir, 'example-config.json', 'node_modules'); }); it('should symlink the node_modules', () => { exampleBoilerPlate.add(); expect(fs.ensureSymlinkSync).toHaveBeenCalledTimes(exampleFolders.length); expect(fs.ensureSymlinkSync).toHaveBeenCalledWith(sharedNodeModulesDir, path.resolve('a/b/node_modules')); expect(fs.ensureSymlinkSync).toHaveBeenCalledWith(sharedNodeModulesDir, path.resolve('c/d/node_modules')); }); it('should error if the node_modules folder is missing', () => { fs.existsSync.and.returnValue(false); expect(() => exampleBoilerPlate.add()).toThrowError( `The shared node_modules folder for the examples (${sharedNodeModulesDir}) is missing.\n` + `Perhaps you need to run "yarn example-use-npm" or "yarn example-use-local" to install the dependencies?`); expect(fs.ensureSymlinkSync).not.toHaveBeenCalled(); }); it('should copy all the source boilerplate files for systemjs', () => { const boilerplateDir = path.resolve(sharedDir, 'boilerplate'); exampleBoilerPlate.loadJsonFile.and.callFake(filePath => filePath.indexOf('a/b') !== -1 ? { projectType: 'systemjs' } : {}) exampleBoilerPlate.add(); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledTimes( (BPFiles.cli) + (BPFiles.systemjs) + (BPFiles.common * exampleFolders.length) ); // for example expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/systemjs`, 'a/b', 'package.json'); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/common`, 'a/b', 'src/styles.css'); }); it('should copy all the source boilerplate files for cli', () => { const boilerplateDir = path.resolve(sharedDir, 'boilerplate'); exampleBoilerPlate.add(); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledTimes( (BPFiles.cli * exampleFolders.length) + (BPFiles.common * exampleFolders.length) ); // for example expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/cli`, 'a/b', 'package.json'); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/common`, 'c/d', 'src/styles.css'); }); it('should copy all the source boilerplate files for i18n', () => { const boilerplateDir = path.resolve(sharedDir, 'boilerplate'); exampleBoilerPlate.loadJsonFile.and.callFake(filePath => filePath.indexOf('a/b') !== -1 ? { projectType: 'i18n' } : {}) exampleBoilerPlate.add(); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledTimes( (BPFiles.cli + BPFiles.i18n) + (BPFiles.cli) + (BPFiles.common * exampleFolders.length) ); // for example expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/i18n`, 'a/b', '../cli/.angular-cli.json'); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/i18n`, 'a/b', 'package.json'); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/common`, 'c/d', 'src/styles.css'); }); it('should copy all the source boilerplate files for universal', () => { const boilerplateDir = path.resolve(sharedDir, 'boilerplate'); exampleBoilerPlate.loadJsonFile.and.callFake(filePath => filePath.indexOf('a/b') !== -1 ? { projectType: 'universal' } : {}) exampleBoilerPlate.add(); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledTimes( (BPFiles.cli + BPFiles.universal) + (BPFiles.cli) + (BPFiles.common * exampleFolders.length) ); // for example expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/universal`, 'a/b', '../cli/tslint.json'); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/universal`, 'a/b', '.angular-cli.json'); expect(exampleBoilerPlate.copyFile).toHaveBeenCalledWith(`${boilerplateDir}/common`, 'c/d', 'src/styles.css'); }); it('should try to load the example config file', () => { exampleBoilerPlate.add(); expect(exampleBoilerPlate.loadJsonFile).toHaveBeenCalledTimes(exampleFolders.length); expect(exampleBoilerPlate.loadJsonFile).toHaveBeenCalledWith(path.resolve('a/b/example-config.json')); expect(exampleBoilerPlate.loadJsonFile).toHaveBeenCalledWith(path.resolve('c/d/example-config.json')); }); }); describe('remove', () => { it('should run `git clean`', () => { spyOn(shelljs, 'exec'); exampleBoilerPlate.remove(); expect(shelljs.exec).toHaveBeenCalledWith('git clean -xdfq', {cwd: path.resolve(__dirname, '../../content/examples') }); }); }); describe('getFoldersContaining', () => { it('should use glob.sync', () => { spyOn(glob, 'sync').and.returnValue(['a/b/config.json', 'c/d/config.json']); const result = exampleBoilerPlate.getFoldersContaining('base/path', 'config.json', 'node_modules'); expect(glob.sync).toHaveBeenCalledWith(path.resolve('base/path/**/config.json'), { ignore: [path.resolve('base/path/**/node_modules/**')] }); expect(result).toEqual(['a/b', 'c/d']); }); }); describe('copyFile', () => { it('should use copySync and chmodSync', () => { spyOn(fs, 'copySync'); spyOn(fs, 'chmodSync'); exampleBoilerPlate.copyFile('source/folder', 'destination/folder', 'some/file/path'); expect(fs.copySync).toHaveBeenCalledWith( path.resolve('source/folder/some/file/path'), path.resolve('destination/folder/some/file/path'), { overwrite: true }); expect(fs.chmodSync).toHaveBeenCalledWith(path.resolve('destination/folder/some/file/path'), 444); }); }); describe('loadJsonFile', () => { it('should use fs.readJsonSync', () => { spyOn(fs, 'readJsonSync').and.returnValue({ some: 'value' }); const result = exampleBoilerPlate.loadJsonFile('some/file'); expect(fs.readJsonSync).toHaveBeenCalledWith('some/file', {throws: false}); expect(result).toEqual({ some: 'value' }); }); it('should return an empty object if readJsonSync fails', () => { spyOn(fs, 'readJsonSync').and.returnValue(null); const result = exampleBoilerPlate.loadJsonFile('some/file'); expect(result).toEqual({}); }); }); });
JavaScript
0
@@ -430,17 +430,17 @@ cli: 1 -8 +9 ,%0A @@ -4007,28 +4007,23 @@ '../cli/ -. angular --cli .json');
e51acda37585cba3d7907a06a7b7c80aae6c81b9
Implement low-level execution method.
lib/wepay.js
lib/wepay.js
/* WePay API for Node.js * (c)2012 Matt Farmer * Release without warranty under the terms of the * Apache License. For more details, see the LICENSE * file at the root of this project. */ restler = require('restler'); var WePay = (function() { /** * The release number of wepay-node, for internal use. **/ var release = "0.1.0"; /** * The Client ID that uniquely identifies our application. **/ var client_id = null; /** * The Client Secret we can use to request OAuth access tokens. **/ var client_secret = null; /** * The current environment that we're using. **/ var environment = null; /** * The OAuth redirect URI **/ var oauth_redirect_uri = ""; /** * The User Agent that will be displayed for requests to WePay. **/ var user_agent = "wepay-node " + release; /** * API endpoints bases **/ var endpoints = { stage: { oauth: "https://stage.wepay.com", api: "https://stage.wepayapi.com" }, prod: { oauth: "https://wepay.com", api: "https://stage.wepayapi.com" } }; /** * The current API version indicator we're using. **/ var api_version = "v2"; /** * Generate a resource URL based on the desired action. **/ function resourceUrlFor(resource, oauth) { if (! environment) throw "The environment hasn't been properly specified."; var callType = (oauth) ? "oauth" : "api", baseUrl = endpoints[environment][callType]; return baseUrl + "/" + api_version + resource; } /** * Generate the headers to be sent with a request. **/ function generateRequestHeaders(token_object) { var headers = {'User-Agent': user_agent}; if (token_object && token_object.access_token && token_object.token_type) headers['Authorization'] = token_object.token_type + " " + token_object.access_token; return headers; } return { /** * Initilize the WePay connection with all the required * parameters to start an OAuth sequence. **/ init: function(init_environment, init_client_id, init_client_secret, init_oauth_redirect_uri) { environment = init_environment; client_id = init_client_id; client_secret = init_client_secret; oauth_redirect_uri = init_oauth_redirect_uri; }, /** * Generate and return the authorize URL for the user * to hit to grant access to the application for the * requested permissions. **/ authorizeUrl: function(scope) { return resourceUrlFor("/oauth2/authorize", true) + "?client_id=" + client_id + "&redirect_uri=" + encodeURIComponent(oauth_redirect_uri) + "&scope=" + encodeURIComponent(scope); }, /** * Retrieve the access token for the user based on * the code provided. **/ retrieveToken: function(code, callback) { restler.post(resourceUrlFor('/oauth2/token', true), { data: JSON.stringify({ "client_id": client_id, "redirect_uri": oauth_redirect_uri, "client_secret": client_secret, "code": code }), headers: generateRequestHeaders() }).on('complete', callback); }, /** * Execute an action against the WePay API. **/ execute: function(action, request_json, access_token) { //TODO } } })(); module.exports = WePay
JavaScript
0.000004
@@ -3284,36 +3284,739 @@ on, -access_token) %7B%0A //TODO +token_object, callback) %7B%0A // Callback is always the last param, so if it is undefined, and token_object%0A // is a function, then swap the two.%0A if (! callback && token_object instanceof Function) %7B%0A callback = token_object;%0A token_object = undefined;%0A %7D%0A%0A // If there is a request_json object, then we're using the POST HTTP method.%0A // If not, this is a GET. (Their API isn't strictly restful, so that's fine.)%0A var executionMethod = (request_json) ? %22post%22 : %22get%22;%0A%0A restler.request(resourceUrlFor(action), %7B%0A method: executionMethod,%0A data: JSON.stringify(request_json),%0A headers: generateRequestHeaders(token_object)%0A %7D).on('complete', callback); %0A
c9350a96beb4f36030a010bc442d0d4e14820253
Refactor Store constructor to support dehydrate/rehydrate.
shared/Stores/Store.js
shared/Stores/Store.js
var EventEmitter = require('eventemitter').EventEmitter; var Store = function (data) { EventEmitter.call(this); this._data = data; this.size = 0; }; Store.prototype = Object.create(EventEmitter.prototype); Store.prototype.constructor = Store; Store.prototype.emitChange = function () { this.emit('CHANGE'); }; Store.prototype.addChangeListener = function (callback) { this.addListener('CHANGE', callback); }; Store.prototype.removeChangeListener = function (callback) { this.removeChangeListener('CHANGE', callback); }; Store.prototype.get = function (id) { return this._data[id]; }; Store.prototype.getAll = function () { return this._data; }; Store.prototype.create = function (value) { this._data[value.id] = value; this.size++; this.emitChange(); }; Store.prototype.read = function (data) { this._data = data; this.size = Object.keys(data).length; this.emitChange(); }; Store.prototype.update = function (value, newValue) { this._data[value.id] = newValue; this.emitChange(); }; Store.prototype.delete = function (value) { delete this._data[value.id]; this.size--; this.emitChange(); }; module.exports = Store;
JavaScript
0
@@ -69,28 +69,28 @@ = function ( -data +name ) %7B%0A EventE @@ -115,36 +115,54 @@ %0A this._data = -data +%7B%7D;%0A this.name = name ;%0A this.size = @@ -225,16 +225,16 @@ otype);%0A - Store.pr @@ -263,16 +263,180 @@ Store;%0A%0A +Store.prototype.dehydrate = function () %7B%0A return %5Bthis.name. this._data%5D;%0A%7D;%0A%0AStore.prototype.rehydrate = function (state) %7B%0A this._data = state%5Bthis.name%5D;%0A%7D;%0A%0A Store.pr
5e75459883de97c6e5925ca5af0bb6cd84b78672
Make HashList use console.error to provide stack traces on invalid operations
shared/lib/HashList.js
shared/lib/HashList.js
"use strict"; // Hash List Utility Class ----------------------------------------------------- function HashList(max) { this.maximum = max || -1; this.clear(); } // Methods -------------------------------------------------------------------- HashList.prototype = { // General Methods --------------------------------------------------------- clear: function() { this.hash = new Object(); this.items = []; this.length = 0; }, destroy: function() { this.hash = null; this.items = null; this.length = 0; }, isFull: function() { return this.maximum === -1 ? false : this.length === this.maximum; }, // Index based Methods ----------------------------------------------------- contains: function(item) { return this.items.indexOf(item) !== -1; }, indexOf: function(item) { return this.items.indexOf(item); }, at: function(index) { return this.items[index]; }, // ID based methods -------------------------------------------------------- has: function(obj) { if (typeof obj !== 'object') { return obj in this.hash; } else { return obj.id in this.hash; } }, get: function(obj) { if (typeof obj !== 'object') { return this.hash[obj]; } else { return this.hash[obj.id]; } }, add: function(obj) { if (!this.has(obj) && !this.isFull()) { this.hash[obj.id] = obj; this.items.push(obj); this.length++; return obj; } else { console.warn('(HashList) Add of contained object', obj); return false; } }, put: function(id, obj) { if (!this.has(id) && !this.isFull()) { this.hash[id] = obj; this.items.push(obj); this.length++; return obj; } else { return false; } }, remove: function(obj) { obj = this.get(obj); if (obj) { this.items.splice(this.items.indexOf(obj), 1); delete this.hash[obj.id]; this.length--; return obj; } else { console.warn('(HashList) Remove of uncontained object', obj); return false; } }, // Sorting ----------------------------------------------------------------- sort: function(func) { this.items.sort(func); return this; }, // Iteration --------------------------------------------------------------- each: function(cb, scope) { for(var i = 0; i < this.length; i++) { var oldLength = this.length; var item = this.items[i]; if (cb.call(scope || item, item)) { return true; } if (this.length < oldLength) { i--; } } }, eachIn: function(items, cb, scope) { for(var i = 0; i < this.length; i++) { var oldLength = this.length, item = this.items[i]; if (items.indexOf(item) !== -1) { if (cb.call(scope || item, item)) { return true; } if (this.length < oldLength) { i--; } } } }, eachNot: function(items, cb, scope) { for(var i = 0; i < this.length; i++) { var oldLength = this.length, item = this.items[i]; if (items.indexOf(item) === -1) { if (cb.call(scope || item, item)) { return true; } if (this.length < oldLength) { i--; } } } }, eachCall: function(method) { for(var i = 0; i < this.length; i++) { this.items[i][method](); } }, eachEach: function(check, func, after, scope) { for(var i = 0; i < this.length; i++) { var oldLength = this.length, item = this.items[i]; if (check.call(scope || item, item)) { for(var e = i + 1;; e++) { var oldLengthInner = this.length; if (e === this.length) { e = 0; } if (e === i) { break; } var itemInner = this.items[e]; if (func.call(scope || itemInner, item, itemInner)) { break; } if (this.length < oldLengthInner) { e--; } } after.call(scope || item, item); } if (this.length < oldLength) { i--; } } } }; // Exports -------------------------------------------------------------------- exports.HashList = HashList;
JavaScript
0
@@ -1666,36 +1666,37 @@ console. -warn +error ('(HashList) Add @@ -2295,12 +2295,13 @@ ole. -warn +error ('(H
38073f0a811b68f90baf632680ef8d90d67bf4a5
Fix stop video on modal close
app/components/Modal.js
app/components/Modal.js
import React from 'react'; import PropTypes from 'prop-types'; import YTPlayer from 'youtube-player'; import styles from './Modal.scss'; let player; const Modal = ({ title, isGallery, trailerId, children, id }) => { window.onclick = ({ target }) => { if (target.id === id) closeModal(); }; const closeModal = () => { const modal = document.getElementById(id); if (trailerId) stopVideo(); modal.style.display = 'none'; }; const stopVideo = () => { if (!player) player = YTPlayer(trailerId); player.stopVideo(); }; const renderHeader = () => ( <div className={styles.Header}> <button className={styles.ButtonClose} onClick={closeModal}> <i className="fa fa-times" /> </button> <p className={styles.Title}>{title}</p> </div> ); return ( <div id={id} className={styles.Modal}> <div className={styles.Content} style={isGallery ? { padding: '30px', borderRadius: '4px' } : {}}> {title ? renderHeader() : null} {children} </div> </div> ); }; Modal.propTypes = { children: PropTypes.node.isRequired, id: PropTypes.string.isRequired, title: PropTypes.string, isGallery: PropTypes.bool, trailerId: PropTypes.string, }; Modal.defaultProps = { title: '', isGallery: false, trailerId: '' }; export default Modal;
JavaScript
0.000001
@@ -135,21 +135,8 @@ ';%0A%0A -let player;%0A%0A cons @@ -421,32 +421,46 @@ = 'none';%0A %7D;%0A%0A + let player;%0A const stopVide
e435c7ed479346583dad1b7c32802334dc1b0c84
Add chart key
app/components/Stats.js
app/components/Stats.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Immutable, { List } from 'immutable'; import { VictoryBar } from "victory-native"; import { Button, Navigator, StyleSheet, Text, ScrollView, View, ActivityIndicator } from 'react-native'; import { VictoryPie } from 'victory-native'; import fuelStatsContainer from '../containers/fuelStatsContainer'; import userContainer from '../containers/userContainer'; class Stats extends Component { constructor (props) { super(props); this.state = { pieData: [] }; } _routeBack() { this.props.navigator.pop(); } transformData(obj){ let arr = []; for(let thing in obj){ let subobj = obj[thing]; let value = subobj['total']; arr.push({fueltype: thing, count: value}); } return arr; } render() { return ( <ScrollView contentContainerStyle={styles.container}> <Button style={styles.button} onPress={this._routeBack.bind(this)} title="← Go Back" /> <Text style={styles.chart}> National distribution of alternative fuels: </Text> { Array.isArray(this.props.stateCounts) ? <View> <Text>Loading chart...</Text> <ActivityIndicator style={styles.centering} size="large" /> </View> : <VictoryPie colorScale='green' data={this.transformData(this.props.nationalCounts)} x="fueltype" y="count" /> } <Text style={styles.chart}> Your state&apos;s distribution of alternative fuels: </Text> { Array.isArray(this.props.stateCounts) ? <View> <Text>Loading charts...</Text> <ActivityIndicator style={styles.centering} size="large" /> </View> : <VictoryPie colorScale='green' data={this.transformData(this.props.stateCounts)} x="fueltype" y="count" /> } </ScrollView> ) } } const styles = StyleSheet.create({ container: { alignItems: 'center', }, chart: { fontSize: 30, }, button: { marginTop: 20 } }); export default userContainer(fuelStatsContainer(Stats));
JavaScript
0.000001
@@ -1577,32 +1577,366 @@ %0A /%3E %7D%0A + %3CText style=%7Bstyles.list%7D%3E%0A Fuel Types:%0A BD:%09Biodiesel (B20 and above)%0A CNG: Compressed Natural Gas%0A E85:%09Ethanol (E85)%0A ELEC:%09Electric%0A HY:%09Hydrogen%0A LNG:%09Liquefied Natural Gas%0A LPG:%09Liquefied Petroleum Gas (Propane)%0A %3C/Text%3E%0A %3CText @@ -2474,32 +2474,386 @@ /%3E %7D%0A + %3CText style=%7Bstyles.list%7D%3E%0A Fuel Types:%0A BD:%09Biodiesel (B20 and above)%0A CNG: Compressed Natural Gas%0A E85:%09Ethanol (E85)%0A ELEC:%09Electric%0A HY:%09Hydrogen%0A LNG:%09Liquefied Natural Gas%0A LPG:%09Liquefied Petroleum Gas (Propane)%0A %3C/Text%3E%0A %3C/Scro
5ecd030f46958f5fe5692b17d951ecc8ef3d97aa
Handle undefined rendered version.
src/compile/compiler.js
src/compile/compiler.js
// FIX reconsider name, but compiler.compile.compiler.compile() method calls would rock. compiler.compile.compiler = def( [ compiler.meta.metalator, compiler.tools.io, compiler.tools.error, ephox.bolt.kernel.module.analyser, ephox.bolt.kernel.fp.functions, ephox.bolt.kernel.fp.object ], function (metalator, io, error, analyser, fn, obj) { var modules = {}; // id -> [id] var rendered = {}; // id -> rendered var printed = {}; var unexpected = fn.curry(error.die, "unexpected call to require, define or demand by compile modulator."); var load = function (regulator, id) { if (!regulator.can(id, unexpected)) error.die("No modulator can load module: " + id); var spec = regulator.regulate(id, unexpected, unexpected, unexpected); rendered[id] = spec.render(); spec.load(function (id, dependencies) { modules[id] = dependencies; }); }; var analyse = function (ids) { var results = analyser.analyse(ids, modules); if (results.cycle) error.die('cycle detected whilst compiling modules: ' + results.cycle.join(' ~> ')); return results; }; var render = function (ids) { var renderer = function (id) { if (printed[id]) return ""; var dependencies = modules[id]; var deps = dependencies.map(renderer); printed[id] = true; return deps.join('\n') + '\n' + rendered[id]; }; return ids.map(renderer).join('\n'); }; var compile = function (regulator, ids) { var loader = fn.curry(load, regulator); var results = analyse(ids); while (results.load.length > 0) { results.load.forEach(loader); results = analyse(ids); } return render(ids); }; var write = function (regulator, ids, target) { var header = metalator.render(ids); var content = compile(regulator, ids); io.write(target, header + content); return obj.keys(rendered); }; return { compile: compile, write: write }; } );
JavaScript
0
@@ -1441,16 +1441,17 @@ '%5Cn' + +( rendered @@ -1450,24 +1450,31 @@ rendered%5Bid%5D + %7C%7C %22%22) ;%0A %7D;%0A
a2bb34881ac1a8050a143119091e881c69695860
disable dashboard form only if doc is standard
frappe/desk/doctype/dashboard/dashboard.js
frappe/desk/doctype/dashboard/dashboard.js
// Copyright (c) 2019, Frappe Technologies and contributors // For license information, please see license.txt frappe.ui.form.on('Dashboard', { refresh: function(frm) { frm.add_custom_button(__("Show Dashboard"), () => frappe.set_route('dashboard', frm.doc.name)); if (!frappe.boot.developer_mode) { frm.disable_form(); } frm.set_query("chart", "charts", function() { return { filters: { is_public: 1, } }; }); frm.set_query("card", "cards", function() { return { filters: { is_public: 1, } }; }); } });
JavaScript
0
@@ -296,16 +296,39 @@ per_mode + && frm.doc.is_standard ) %7B%0A%09%09%09f
e52674dadd9cff7341a65e39b8bb705adca61db5
Fix icon of media upload button after failed upload via media list
wcfsetup/install/files/js/WoltLabSuite/Core/Media/List/Upload.js
wcfsetup/install/files/js/WoltLabSuite/Core/Media/List/Upload.js
/** * Uploads media files. * * @author Matthias Schmidt * @copyright 2001-2017 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @module WoltLabSuite/Core/Media/List/Upload */ define( [ 'Core', 'Dom/ChangeListener', 'Dom/Traverse', 'Dom/Util', 'Language', 'Ui/Confirmation', 'Ui/Notification', '../Upload' ], function( Core, DomChangeListener, DomTraverse, DomUtil, Language, UiConfirmation, UiNotification, MediaUpload ) { "use strict"; /** * @constructor */ function MediaListUpload(buttonContainerId, targetId, options) { options = options || {}; // only one file may be uploaded file list upload for proper error display options.multiple = false; MediaUpload.call(this, buttonContainerId, targetId, options); } Core.inherit(MediaListUpload, MediaUpload, { /** * Creates the upload button. */ _createButton: function() { this._fileUpload = elCreate('input'); elAttr(this._fileUpload, 'type', 'file'); elAttr(this._fileUpload, 'name', this._options.name); this._fileUpload.addEventListener('change', this._upload.bind(this)); this._button = elCreate('p'); this._button.className = 'button uploadButton'; this._button.innerHTML = '<span class="icon icon16 fa-upload"></span> <span>' + Language.get('wcf.global.button.upload') + '</span>'; DomUtil.prepend(this._fileUpload, this._button); this._insertButton(); DomChangeListener.trigger(); }, /** * @see WoltLabSuite/Core/Upload#_success */ _success: function(uploadId, data) { var icon = DomTraverse.childByClass(this._button, 'icon'); icon.classList.remove('fa-spinner'); icon.classList.add('fa-upload'); var file = this._fileElements[uploadId][0]; var internalFileId = elData(file, 'internal-file-id'); var media = data.returnValues.media[internalFileId]; if (media) { UiNotification.show(Language.get('wcf.media.upload.success'), function() { window.location.reload(); }); } else { var error = data.returnValues.errors[internalFileId]; if (!error) { error = { errorType: 'uploadFailed', filename: elData(file, 'filename') }; } UiConfirmation.show({ confirm: function() { // do nothing }, message: Language.get('wcf.media.upload.error.' + error.errorType, { filename: error.filename }) }); } }, /** * @see WoltLabSuite/Core/Upload#_success */ _upload: function(event, file, blob) { var uploadId = MediaListUpload._super.prototype._upload.call(this, event, file, blob); var icon = DomTraverse.childByClass(this._button, 'icon'); window.setTimeout(function() { icon.classList.remove('fa-upload'); icon.classList.add('fa-spinner'); }, 500); return uploadId; } }); return MediaListUpload; });
JavaScript
0
@@ -1654,24 +1654,63 @@ n, 'icon');%0A +%09%09%09elData(icon, 'add-spinner', false);%0A %09%09%09icon.clas @@ -2528,39 +2528,38 @@ te/Core/Upload#_ -success +upload %0A%09%09 */%0A%09%09_upload @@ -2753,39 +2753,121 @@ %0A%09%09%09 -window.setTimeout(function() %7B%0A +elData(icon, 'add-spinner', true);%0A%09%09%09window.setTimeout(function() %7B%0A%09%09%09%09if (elDataBool(icon, 'add-spinner')) %7B%0A%09 %09%09%09%09 @@ -2902,16 +2902,17 @@ load');%0A +%09 %09%09%09%09icon @@ -2941,16 +2941,22 @@ nner');%0A +%09%09%09%09%7D%0A %09%09%09%7D, 50
563d7072db04bec4a2958488ab68a471eb3ec9fb
Handle case where there are no files.
website/app/global.services/select-items/select-items.service.js
website/app/global.services/select-items/select-items.service.js
(function(module) { module.factory('selectItems', selectItemsService); selectItemsService.$inject = ["$modal"]; function selectItemsService($modal) { return { open: function() { var tabs = { processes: false, files: false, samples: false, reviews: false }; if (arguments.length === 0) { throw "Invalid arguments to service selectItems:open()"; } for (var i = 0; i < arguments.length; i++) { tabs[arguments[i]] = true; } var modal = $modal.open({ size: 'lg', templateUrl: 'global.services/select-items/select-items.html', controller: 'SelectItemsServiceModalController', controllerAs: 'ctrl', resolve: { showProcesses: function() { return tabs.processes; }, showFiles: function() { return tabs.files; }, showSamples: function() { return tabs.samples; }, showReviews: function() { return tabs.reviews; } } }); return modal.result; } }; } module.controller('SelectItemsServiceModalController', SelectItemsServiceModalController); SelectItemsServiceModalController.$inject = ['$modalInstance', 'showProcesses', 'showFiles', 'showSamples', 'showReviews', 'projectsService', '$stateParams', 'project']; function SelectItemsServiceModalController($modalInstance, showProcesses, showFiles, showSamples, showReviews, projectsService, $stateParams, project) { var ctrl = this; ctrl.project = project.get(); ctrl.tabs = loadTabs(); ctrl.activeTab = ctrl.tabs[0].name; ctrl.setActive = setActive; ctrl.isActive = isActive; ctrl.ok = ok; ctrl.cancel = cancel; ctrl.processes = []; ctrl.samples = []; ///////////////////////// function setActive(tab) { ctrl.activeTab = tab; } function isActive(tab) { return ctrl.activeTab === tab; } function ok() { var selectedProcesses = ctrl.processes.filter(function(p) { return p.input || p.output; }); var selectedSamples = ctrl.samples.filter(function(s) { return s.selected; }); var selectedFiles = getSelectedFiles(); $modalInstance.close({ processes: selectedProcesses, samples: selectedSamples, files: selectedFiles }); } function getSelectedFiles() { var files = [], treeModel = new TreeModel(), root = treeModel.parse(project.get().files[0]); // Walk the tree looking for selected files and adding them to the // list of files. Also reset the selected flag so the next time // the popup for files is used it doesn't show previously selected // items. root.walk({strategy: 'pre'}, function(node) { if (node.model.data.selected) { node.model.data.selected = false; if (node.model.data._type === 'file') { files.push(node.model.data); } } }); return files; } function cancel() { $modalInstance.dismiss('cancel'); } function loadTabs() { var tabs = []; if (showProcesses) { tabs.push(newTab('processes', 'fa-code-fork')); projectsService.getProjectProcesses($stateParams.project_id).then(function(processes) { ctrl.processes = processes; }); } if (showSamples) { tabs.push(newTab('samples', 'fa-cubes')); projectsService.getProjectSamples($stateParams.project_id).then(function(samples) { ctrl.samples = samples; }); } if (showFiles) { tabs.push(newTab('files', 'fa-files-o')); } if (showReviews) { tabs.push(newTab('reviews', 'fa-comment')); } tabs.sort(function compareByName(t1, t2) { if (t1.name < t2.name) { return -1; } if (t1.name > t2.name) { return 1; } return 0; }); return tabs; } function newTab(name, icon) { return { name: name, icon: icon }; } } }(angular.module('materialscommons')));
JavaScript
0
@@ -3134,24 +3134,95 @@ edFiles() %7B%0A + if (!showFiles) %7B%0A return %5B%5D;%0A %7D%0A
458f889d12f2decda892f3ede5b19076904db5bc
Delete some console.logs
components/Card/Card.js
components/Card/Card.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, {PropTypes} from 'react'; import config from '../../config'; import moment from 'moment'; import BlockButton from '../buttons/BlockButton' import ProgressMeter from '../progress-meter' import CardMetadata from '../CardMetadata' import CardHelpDirections from '../CardHelpDirections' // import './Card.scss'; // import CustomProgressBar from '../CustomProgressBar' let answerColor = 'rgb(0, 62, 136)' // #0678FE' let clientWidth = window.document.documentElement.clientWidth function linearTransform(domain, range, x) { // rise / run let slope = (range[1] - range[0]) / (domain[1] - domain[0]) // b = y - mx var intercept = range[0] - slope * domain[0]; if (typeof x === "number") { // If a domain value was provided, return the transformed result return slope * x + intercept; } else { // If no domain value was provided, return a function return (x) => { return slope * x + intercept } } } let getLightness = linearTransform([0, 1], [100, 25]) export default class Card extends React.Component { constructor(props) { super(props); this.state = { isShowingQuestion: !!props.isShowingQuestion, }; } showAnswer() { this.setState({ isShowingQuestion: false }); } showQuestion() { this.setState({ isShowingQuestion: true }); } flipCard() { this.props.onFlip(); this.setState({ isShowingQuestion: !this.state.isShowingQuestion }); } onTouchStart(e) { let {clientX:x, clientY:y} = e.targetTouches[0] this.setState({ lastTouchStart: {x, y} }) } onTouchMove(e) { let {clientX:x, clientY:y} = e.targetTouches[0] let lastTouchStart = this.state.lastTouchStart let deltaXRatio = (x - lastTouchStart.x) / clientWidth // let hslValue = `hsl(${hue}, 100%, ${getLightness(Math.abs(deltaXRatio))}%)` let rgbaValue = deltaXRatio > 0 ? `rgba(0, 128, 0, ${Math.abs(deltaXRatio)})` : `rgba(204, 0, 0, ${Math.abs(deltaXRatio)})` document.body.style.backgroundColor = rgbaValue // document.body.style.opacity = Math.abs(deltaXRatio) } onTouchEnd(e) { document.body.style.backgroundColor = 'white' // document.body.style.opacity = 1 } onKeyDown(e) { // console.log('Got keydown', e) if (e.keyIdentifier === 'Up') this.props.onBackToAllDecks() else if (e.keyIdentifier === 'Left') this.props.onAnsweredIncorrectly() else if (e.keyIdentifier === 'Right') this.props.onAnsweredCorrectly() else if (e.keyIdentifier === 'Down') this.props.onSkip() else if (e.keyCode === 32) this.flipCard() // SPACE else this.flipCard() } componentDidMount() { if (window.iNoBounce) window.iNoBounce.enable() this._keyDownListener = this.onKeyDown.bind(this) document.addEventListener('keydown', this._keyDownListener) } componentWillUnmount() { // console.log('Card will unmount') document.removeEventListener('keydown', this._keyDownListener) } render() { let style = { transition: '1s', cursor: 'pointer', fontFamily:'Monospace', margin: 0, padding: 10, // paddingTop: 20, // background: this.state.isShowingQuestion ? 'white' : '#DDF5FF', // height: screen.height, height: window.document.documentElement.clientHeight - 20, // to account for padding color: this.state.isShowingQuestion ? 'black' : answerColor } // <CardHelpDirections /> let text = this.state.isShowingQuestion ? this.props.question : this.props.answer text = text .replace(/\s\s/g, '<br/><br/>') .replace(/\\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') .replace(/\\n/g, '<br/>') let dangerousHtml = {__html: text} return ( <div className="flashcard" style={style} onClick={this.flipCard.bind(this)} onTouchStart={this.onTouchStart.bind(this)} onTouchMove={this.onTouchMove.bind(this)} onTouchEnd={this.onTouchEnd.bind(this)}> <ProgressMeter color={this.state.isShowingQuestion ? 'black' : answerColor} height={5} complete={(this.props.cardIndex+1)/this.props.totalCards}/> <h1>{this.state.isShowingQuestion ? "Question" : "Answer"}</h1> <p dangerouslySetInnerHTML={dangerousHtml} style={{position: 'absolute', top: '35%', transform: 'translateY(-50%)', width: '80%', left: '10%'}}/> <CardMetadata style={{/*color: this.state.isShowingQuestion ? 'gray' : answerColor*/}} {...this.props} /> </div> ); } } // Card.propTypes = { initialCount: React.PropTypes.number }; Card.defaultProps = { lastSeen: null, isShowingQuestion: true, onFlip: function() {} };
JavaScript
0.000003
@@ -1936,91 +1936,8 @@ dth%0A - // let hslValue = %60hsl($%7Bhue%7D, 100%25, $%7BgetLightness(Math.abs(deltaXRatio))%7D%25)%60%0A @@ -2116,67 +2116,8 @@ lue%0A - // document.body.style.opacity = Math.abs(deltaXRatio)%0A %7D%0A @@ -2191,103 +2191,27 @@ '%0A - // document.body.style.opacity = 1%0A %7D%0A%0A onKeyDown(e) %7B%0A // console.log('Got keydown', e) +%7D%0A%0A onKeyDown(e) %7B %0A @@ -2799,48 +2799,8 @@ ) %7B%0A - // console.log('Card will unmount')%0A
672d47e1ed80e25ca84f3e92750f2227a31e0ae9
Update ShareIcon.js content
components/ShareIcon.js
components/ShareIcon.js
import React from 'react'; import Icon from './Icon'; export default ({type, url, name, description}) => { const caption = encodeURIComponent("Support the " + name + " collective"); const body = encodeURIComponent("Support the " + name + " collective: " + url + '\n\n' + description); const url_encoded = encodeURIComponent(url); const link = { twitter: `https://twitter.com/intent/tweet?status=${caption}%20${url_encoded}`, facebook: `https://www.facebook.com/sharer.php?url=${url_encoded}`, mail: `mailto:?subject=${caption}&body=${body}`, }; const w = 650; const h = 450; const left = (screen.width / 2) - (w / 2); const top = (screen.height / 2) - (h / 2); return ( <span onClick={() => window.open(link[type], 'ShareWindow', `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${top}, left=${left}`)} className='ShareIcon'> <Icon type={type} /> </span> ) };
JavaScript
0
@@ -133,39 +133,45 @@ deURIComponent(%22 -Support +I just backed the %22 + name + @@ -163,33 +163,32 @@ the %22 + name + %22 - collective%22);%0A @@ -224,15 +224,21 @@ nt(%22 -Support +I just backed the @@ -293,16 +293,46 @@ cription + %22Join me in supporting them!%22 );%0A con
0f9be6da28fed64b0dd047d6411c97fce9397bec
add notification for reset and put task name in notif
front/src/components/TaskDetailProvider.js
front/src/components/TaskDetailProvider.js
import React, { Component } from 'react'; import moment from 'moment'; import { axios, getErrorMessage } from '../axios'; import notification from '../notification'; const HOURS_12 = 12 * 60 * 60 * 1000; export default class TaskDetailProvider extends Component { constructor(props) { super(props); const today = moment() .hours(12) .minutes(0) .seconds(0); this.state = { loadingHistory: false, history: [], startDate: today, endDate: today }; } componentDidMount() { this.fetchHistory(this.state.startDate, this.state.endDate); } getUrl(path = '', prefix = 'scheduler') { const { type, match: { params } } = this.props; return `/${prefix}/${type}/${params.task}/${path}`; } triggerTask = (type) => { const options = {}; if (type) { options.params = { type }; } axios .post(this.getUrl('trigger'), undefined, options) .then(() => { notification.addNotification({ title: `Trigger ${type}`, description: `Trigger ${type} was successful`, type: 'success', timeout: 5000 }); }) .catch((e) => { let error = getErrorMessage(e); notification.addNotification({ title: `Trigger ${type}`, description: `error: ${error}`, type: 'error' }); }); }; fetchHistory(startDate, endDate) { this.setState({ loadingHistory: true }); axios .get(this.getUrl('history'), { params: { from: +startDate - HOURS_12, to: +endDate + HOURS_12 } }) .then((response) => { const history = response.data; for (const elem of history) { elem.state.sort((a, b) => { const byDate = b.date.localeCompare(a.date); if (byDate !== 0) { return byDate; } else { return b._id.localeCompare(a._id); } }); } this.setState({ loadingHistory: false, history: response.data }); }); } resetDatabase = () => { axios.delete(this.getUrl('', 'db')); }; onDatesChange(event) { this.setState({ startDate: event.startDate, endDate: event.endDate }); if (event.startDate && event.endDate) { this.fetchHistory(event.startDate, event.endDate); } } render() { const Component = this.props.component; return ( <Component onDatesChange={this.onDatesChange.bind(this)} startDate={this.state.startDate} endDate={this.state.endDate} history={this.state.history} loadingHistory={this.state.historyLoading} name={this.props.match.params.task} triggerTask={this.triggerTask} resetDatabase={this.resetDatabase} /> ); } }
JavaScript
0
@@ -797,24 +797,68 @@ (type) =%3E %7B%0A + const params = this.props.match.params;%0A const op @@ -869,16 +869,16 @@ s = %7B%7D;%0A - if ( @@ -1088,32 +1088,47 @@ %60Trigger $%7Btype%7D + $%7Bparams.task%7D %60,%0A des @@ -1377,16 +1377,31 @@ $%7Btype%7D + $%7Bparams.task%7D %60,%0A @@ -2220,42 +2220,539 @@ -axios.delete(this.getUrl('', 'db') +const params = this.props.match.params;%0A axios.delete(this.getUrl('', 'db')).then(%0A () =%3E %7B%0A notification.addNotification(%7B%0A title: %60Reset $%7Bparams.task%7D%60,%0A description: 'Database successfully reset',%0A type: 'success',%0A timeout: 5000%0A %7D);%0A %7D,%0A (e) =%3E %7B%0A let error = getErrorMessage(e);%0A notification.addNotification(%7B%0A title: %60Reset $%7Bparams.task%7D%60,%0A description: %60error: $%7Berror%7D%60,%0A type: 'error'%0A %7D);%0A %7D%0A );%0A
e586badf3bf51b47d821a8a8e623c2c8bb1c922b
Check logic
frappe/public/js/frappe/form/controls/attach.js
frappe/public/js/frappe/form/controls/attach.js
frappe.ui.form.ControlAttach = frappe.ui.form.ControlData.extend({ make_input: function() { let me = this; this.$input = $('<button class="btn btn-default btn-sm btn-attach">') .html(__("Attach")) .prependTo(me.input_area) .on("click", function() { me.on_attach_click(); }); this.$value = $( `<div class="attached-file flex justify-between align-center"> <div class="ellipsis"> <i class="fa fa-paperclip"></i> <a class="attached-file-link" target="_blank"></a> </div> <div> <a class="btn btn-xs btn-default" data-action="reload_attachment">${__('Reload File')}</a> <a class="btn btn-xs btn-default" data-action="clear_attachment">${__('Clear')}</a> </div> </div>`) .prependTo(me.input_area) .toggle(false); this.input = this.$input.get(0); this.set_input_attributes(); this.has_input = true; frappe.utils.bind_actions_with_object(this.$value, this); this.toggle_reload_button(); }, clear_attachment: function() { let me = this; if(this.frm) { me.parse_validate_and_set_in_model(null); me.refresh(); me.frm.attachments.remove_attachment_by_filename(me.value, function() { me.parse_validate_and_set_in_model(null); me.refresh(); me.frm.doc.docstatus == 1 ? me.frm.save('Update') : me.frm.save(); }); } else { this.dataurl = null; this.fileobj = null; this.set_input(null); this.parse_validate_and_set_in_model(null); this.refresh(); } }, reload_attachment() { if (this.file_uploader) { this.file_uploader.uploader.upload_files(); } }, on_attach_click() { this.set_upload_options(); this.file_uploader = new frappe.ui.FileUploader(this.upload_options); }, set_upload_options() { let options = { allow_multiple: false, on_success: file => { this.on_upload_complete(file); this.toggle_reload_button(); } }; if (this.frm) { options.doctype = this.frm.doctype; options.docname = this.frm.docname; options.fieldname = this.df.fieldname; } if (this.df.options) { Object.assign(options, this.df.options); } this.upload_options = options; }, set_input: function(value, dataurl) { this.value = value; if(this.value) { this.$input.toggle(false); // value can also be using this format: FILENAME,DATA_URL // Important: We have to be careful because normal filenames may also contain "," let file_url_parts = this.value.match(/^([^:]+),(.+):(.+)$/); let filename; if (!file_url_parts) { filename = file_url_parts[1]; dataurl = file_url_parts[2] + ':' + file_url_parts[3]; } this.$value.toggle(true).find(".attached-file-link") .html(filename || this.value) .attr("href", dataurl || this.value); } else { this.$input.toggle(true); this.$value.toggle(false); } }, get_value: function() { return this.value || null; }, on_upload_complete: function(attachment) { if(this.frm) { this.parse_validate_and_set_in_model(attachment.file_url); this.frm.attachments.update_attachment(attachment); this.frm.doc.docstatus == 1 ? this.frm.save('Update') : this.frm.save(); } this.set_value(attachment.file_url); }, toggle_reload_button() { this.$value.find('[data-action="reload_attachment"]') .toggle(this.file_uploader && this.file_uploader.uploader.files.length > 0); } });
JavaScript
0.000012
@@ -2468,9 +2468,8 @@ if ( -! file
c158f563bb89788728d49953675e0bc376beba85
remove space for readibility
libs/getFilesSync.js
libs/getFilesSync.js
var fs = require('fs') module.exports.getFilesSync = function (dir, files_, filter){ files_ = files_ || [] var files = fs.readdirSync(dir) for (var i in files){ var name = dir + '/' + files[i] if (fs.statSync(name).isDirectory()){ module.exports.getFilesSync (name, files_, filter) } else { if (filter && filter.length > 0 && name.indexOf (filter) >= 0) { files_.push(name) } else if (!filter || filter && ! (filter.length > 0)) { files_.push(name) } } } return files_ }
JavaScript
0.004861
@@ -491,17 +491,16 @@ ter && ! - (filter.
bd35a3c8112657a56e0241cb392f161cd48c2112
fix interceptor can not get router param
libs/core.js
libs/core.js
const glob = require('glob'); const nunjucks = require('nunjucks'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const env = require('../utils/env'); const memoryCache = require('../utils/memory-cache'); const parseMultiName = require('../utils/parse-multi-name'); const parseRouter = require('./parse-router'); const Stage = require('./stage'); const pageInfo = require('../stages/page-info'); const matchRouter = require('../stages/match-router'); const requestProxy = require('../stages/request-proxy'); const handleInterceptor = require('../stages/handle-interceptor'); const handleRouter = require('../stages/handle-router'); const runTask = require('../stages/run-task'); const getViewPath = require('../stages/get-view-path'); const render = require('../stages/render'); const initHttpRequest = require('../stages/init-http-request'); const pwd = process.cwd(); const defaultRouterDir = `${pwd}/routers`; const defaultInterceptorDir = `${pwd}/interceptors`; const defaultViewDir = `${pwd}/views`; function loadRoutes(dir) { const map = {}; const files = glob.sync(`${dir}/**/*.js`); files.forEach(file => { const routesPart = require(file); // eslint-disable-line global-require Object.assign(map, parseMultiName(routesPart)); }); return map; } function simpleApiDataName(api) { return api.substr(api.lastIndexOf('/') + 1); } /** * 框架定名 route-coc,基于express.js用于简化前端页面直出流程的框架 * coc 意为 约定优于配置(convention over configuration) * * @param {[type]} app express app对象 * @param {[type]} args 配置对象 * args.routerDir: 路由配置目录 * args.handleAPI: 预处理api地址 * @return {[type]} [description] */ module.exports = (app, args = {}) => { const defaultStages = [ pageInfo, initHttpRequest, handleInterceptor, matchRouter, requestProxy, handleRouter, runTask, getViewPath, render ]; // mount see more @ http://expressjs.com/en/4x/api.html#path-examples const { routerDir = defaultRouterDir, // 路由目录 interceptorDir = defaultInterceptorDir, // 拦截器目录 interceptXhr = false, // 是否拦截ajax请求,默认不拦截 viewDir = defaultViewDir, // 视图模板目录 viewExclude = ['**/include/**'], // 排除自动渲染模板的目录,采用glob匹配规则 stages = defaultStages, // 默认stage列表 mount = '/', // 程序挂载路径,默认为根路径,类型符合express path examples apiDataCache = memoryCache, // 接口数据缓存方法,默认存储于内存中 apiDataName = simpleApiDataName, // 接口数据名方法,默认为获取api地址最后一个/后面的单词名 handleAPI = url => url, // router.api地址预处理方法,默认返回自身 ajaxCache = true // 是否允许缓存ajax响应结果,默认允许缓存 } = args; const interceptorMap = loadRoutes(interceptorDir); const routerMap = loadRoutes(routerDir); const routers = parseRouter(routerMap); const interceptors = parseRouter(interceptorMap, interceptor => { interceptor.type = 'interceptor'; }); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); app.use(cookieParser()); // nginx代理转发后,要获取正确host需要: app.set('trust proxy', 'loopback'); app.set('query parser', 'extended'); const stage = new Stage(stages); // 存储 stage.set('interceptorMap', interceptorMap); stage.set('interceptors', interceptors); stage.set('routerMap', routerMap); stage.set('routers', routers); stage.set('views', viewDir); stage.set('viewExclude', viewExclude); stage.set('interceptXhr', interceptXhr); // 保存接口数据缓存方法 stage.set('apiDataCache', apiDataCache); // 保存接口数据名方法 stage.set('apiDataName', apiDataName); // 保存接口地址处理方法 stage.set('handleAPI', handleAPI); stage.set('ajaxCache', ajaxCache); // 添加默认模板引擎 const nunjucksEnv = nunjucks.configure(viewDir, { autoescape: true, noCache: env.isDev, watch: env.isDev }); stage.set('nunjucks', nunjucks); stage.set('nunjucksEnv', nunjucksEnv); app.engine('njk', nunjucks.render); // 设置引擎默认后缀 if (!app.get('view engine')) { app.set('view engine', 'njk'); } app.use(mount, (req, res, next) => { stage.handle(req, res, next); }); return stage; };
JavaScript
0.000001
@@ -1762,16 +1762,29 @@ Request, + matchRouter, handleI @@ -1794,29 +1794,16 @@ rceptor, - matchRouter, %0A req
374d8df714872fd8f2c8e7e0b74ba9beeb0e380e
Make object-literatl/getter a kata.
katas/es6/language/object-literal/getter.js
katas/es6/language/object-literal/getter.js
// 66: object-literal - getter // To do: make all tests pass, leave the assert lines unchanged! describe('An object literal can also contain getters', () => { it('just prefix the property with `get` and make it a function', function() { const obj = { get x() { return 'ax'; } }; assert.equal(obj.x, 'ax'); }); it('must have NO parameters', function() { const obj = { get x() { return 'ax'; } }; assert.equal(obj.x, 'ax'); }); it('can be a computed property', function() { const keyName = 'x'; const obj = { get [keyName]() { return 'ax'; } }; assert.equal(obj.x, 'ax'); }); it('can be removed using delete', function() { const obj = { get x() { return 'ax'; } }; delete obj.x; assert.equal(obj.x, void 0); }); // The following dont seem to work in the current transpiler version // but should be correct, as stated here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get // It might be corrected later, new knowledge welcome. //it('must not overlap with a pure property', function() { // const obj = { // x: 1, // get x() { return 'ax'; } // }; // // assert.equal(obj.x, 'ax'); //}); // //it('multiple `get` for the same property are not allowed', function() { // const obj = { // x: 1, // get x() { return 'ax'; }, // get x() { return 'ax1'; } // }; // // assert.equal(obj.x, 'ax'); //}); });
JavaScript
0.000045
@@ -196,16 +196,17 @@ h %60get%60 +( and make @@ -219,16 +219,17 @@ function +) ', funct @@ -252,36 +252,32 @@ t obj = %7B%0A -get x() %7B return 'ax @@ -392,38 +392,39 @@ t obj = %7B%0A -get x( +x(param ) %7B return 'ax'; @@ -501,32 +501,65 @@ omputed property + (an expression enclosed in %60%5B%5D%60) ', function() %7B%0A @@ -615,17 +615,15 @@ get -%5B keyName -%5D () %7B @@ -802,31 +802,8 @@ %0A - delete obj.x;%0A %0A
a377d85dd633af5eddfed2713c7571791dcfe60f
remove entity useless UID and added name for easy debug
ecs/Entity.js
ecs/Entity.js
let lastUID = 0; let entitiesSet = new Set(); let componentEntities = new Map(); export default class Entity { static getEntities(ComponentClass) { if (!ComponentClass) { return entitiesSet; } let entities = componentEntities.get(ComponentClass); if (!entities) { entities = new Set(); componentEntities.set(ComponentClass, entities); } return entities; } constructor() { this._UID = lastUID++; this._components = new Map(); this._componentsSaved = new Map(); this.active = true; entitiesSet.add(this); } get UID() { return this._UID; } addComponent(ComponentClass, ...args) { let component = this._componentsSaved.get(ComponentClass) || this.getComponent(ComponentClass); if (component && !args.length) { this._componentsSaved.delete(ComponentClass); } else { component = new ComponentClass(this, ...args); } this._components.set(ComponentClass, component); let entities = Entity.getEntities(ComponentClass); entities.add(this); return component; } getComponent(ComponentClass) { return this._components.get(ComponentClass); } hasComponent(ComponentClass) { return this._components.has(ComponentClass); } removeComponent(ComponentClass) { let component = this.getComponent(ComponentClass); if (!component) { return; } this._componentsSaved.set(ComponentClass, component); this._components.delete(ComponentClass); Entity.getEntities(ComponentClass).delete(this); return component; } toggleComponent(ComponentClass, force, ...args) { if (force || force === undefined && !this.getComponent(ComponentClass)) { this.addComponent(ComponentClass, ...args) } else { this.removeComponent(ComponentClass) } } }
JavaScript
0
@@ -1,21 +1,4 @@ -let lastUID = 0;%0A let @@ -398,37 +398,49 @@ tor( -) %7B%0A this._UID = lastUID++ +%7Bname = %22%22%7D = %7B%7D) %7B%0A this._name = name ;%0A%0A @@ -575,19 +575,20 @@ %0A%0A get -UID +name () %7B%0A @@ -605,11 +605,12 @@ is._ -UID +name ;%0A
0bb7d15ce4e380ef949d7c23f3db32d84fca2d06
Add feedback to edit button after successful save.
frontend/src/app/components/higherOrder/edit.js
frontend/src/app/components/higherOrder/edit.js
import React from "react"; import {Button, Modal} from "react-bootstrap"; import {List} from "immutable"; export default (Component) => { class EditForm extends React.Component { constructor(props) { super(props); this.state = {show: false}; } componentWillReceiveProps(nextProps) { if (this.props.model.id !== nextProps.model.id) { const {model} = nextProps; this.setState({changeSet: new model.ChangeSet(model.toJS())}); } } showModal = () => { this.setState({show: true}); } hideModal = () => { this.setState({show: false}); } handleChange = (evnt) => { const {changeSet} = this.state; this.setState({ changeSet: changeSet.set(evnt.target.name, evnt.target.value) }); } handleSubmit = (evnt) => { const {actions, model} = this.props; const {changeSet} = this.state; const successCb = List([() => this.hideModal()]); const errorCb = List([ (response) => this.setState({ changeSet: changeSet.set("_errors", response.body) }) ]); evnt.preventDefault(); actions.saveModel({model, successCb, errorCb, changeSet}); } render() { const {model} = this.props; const {changeSet} = this.state; return( <a className="btn btn-app" onClick={this.showModal}> <i className="fa fa-edit"></i> Edit <Modal onHide={this.hideModal} show={this.state.show} > <Modal.Header closeButton> <Modal.Title>Edit {model.toString()}</Modal.Title> </Modal.Header> <Modal.Body> <Component changeSet={changeSet} handleChange={this.handleChange} handleSubmit={this.handleSubmit} {...this.props} /> </Modal.Body> <Modal.Footer> <Button className="pull-left" onClick={this.hideModal}>Cancel </Button> <Button onClick={this.handleSubmit}>Save</Button> </Modal.Footer> </Modal> </a> ); } } return EditForm; };
JavaScript
0
@@ -259,27 +259,96 @@ tate = %7B -show: false +%0A show: false,%0A saveSuccessful: false%0A %7D;%0A @@ -501,24 +501,25 @@ nextProps;%0A +%0A @@ -537,16 +537,37 @@ tState(%7B +%0A changeSe @@ -602,16 +602,76 @@ .toJS()) +,%0A saveSuccessful: false%0A %7D);%0A @@ -1193,16 +1193,17 @@ .state;%0A +%0A @@ -1230,16 +1230,33 @@ = List(%5B +%0A () =%3E th @@ -1269,20 +1269,95 @@ eModal() +,%0A () =%3E this.setState(%7BsaveSuccessful: true%7D)%0A %5D);%0A +%0A @@ -1732,32 +1732,48 @@ const %7BchangeSet +, saveSuccessful %7D = this.state;%0A @@ -1862,16 +1862,224 @@ Modal%7D%3E%0A + %7BsaveSuccessful &&%0A %3Cspan className=%22badge bg-green%22%3E%0A %3Ci className=%22fa fa-check%22/%3E%0A %3C/span%3E%0A %7D%0A
1373a04f05faa86226c6579a482ae6c4c87a640e
Update entry.js
javascript/es6/entry.js
javascript/es6/entry.js
/** import sections */ import Grid from './dev/grid'; /** attaching behaviors to global object */ window.SilverStripe.behaviors.Grid = new Grid();
JavaScript
0.000001
@@ -46,16 +46,101 @@ v/grid'; +%0Aimport PageTransitions from './dev/page_transitions';%0Aimport Body from './dev/body'; %0A%0A/** at @@ -225,8 +225,130 @@ Grid(); +%0Awindow.SilverStripe.behaviors.PageTransitions = new PageTransitions();%0Awindow.SilverStripe.behaviors.Body = new Body();%0A%0A
833a90177c8577730499b288bd04446e2e6bdc8e
add quotes to themes, fix #3
src/js/editableThemes.js
src/js/editableThemes.js
/* Editable themes: - default - bootstrap 2 - bootstrap 3 Note: in postrender() `this` is instance of editableController */ angular.module('xeditable').factory('editableThemes', function() { var themes = { //default default: { formTpl: '<form class="editable-wrap"></form>', noformTpl: '<span class="editable-wrap"></span>', controlsTpl: '<span class="editable-controls"></span>', inputTpl: '', errorTpl: '<div class="editable-error" ng-show="$error">{{$error}}</div>', buttonsTpl: '<span class="editable-buttons"></span>', submitTpl: '<button type="submit">save</button>', cancelTpl: '<button type="button" ng-click="$form.$hide()">cancel</button>' }, //bs2 bs2: { formTpl: '<form class="form-inline editable-wrap" role="form"></form>', noformTpl: '<span class="editable-wrap"></span>', controlsTpl: '<div class="editable-controls controls control-group" ng-class="{\'error\': $error}"></div>', inputTpl: '', errorTpl: '<div class="editable-error help-block" ng-show="$error">{{$error}}</div>', buttonsTpl: '<span class="editable-buttons"></span>', submitTpl: '<button type="submit" class="btn btn-primary"><span class="icon-ok icon-white"></span></button>', cancelTpl: '<button type="button" class="btn" ng-click="$form.$hide()">'+ '<span class="icon-remove"></span>'+ '</button>' }, //bs3 bs3: { formTpl: '<form class="form-inline editable-wrap" role="form"></form>', noformTpl: '<span class="editable-wrap"></span>', controlsTpl: '<div class="editable-controls form-group" ng-class="{\'has-error\': $error}"></div>', inputTpl: '', errorTpl: '<div class="editable-error help-block" ng-show="$error">{{$error}}</div>', buttonsTpl: '<span class="editable-buttons"></span>', submitTpl: '<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span></button>', cancelTpl: '<button type="button" class="btn btn-default" ng-click="$form.$hide()">'+ '<span class="glyphicon glyphicon-remove"></span>'+ '</button>', //bs3 specific props to change buttons class: btn-sm, btn-lg buttonsClass: '', //bs3 specific props to change standard inputs class: input-sm, input-lg inputClass: '', postrender: function() { //apply `form-control` class to std inputs switch(this.directiveName) { case 'editableText': case 'editableSelect': case 'editableTextarea': this.inputEl.addClass('form-control'); if(this.theme.inputClass) { this.inputEl.addClass(this.theme.inputClass); } break; } //apply buttonsClass (bs3 specific!) if(this.buttonsEl && this.theme.buttonsClass) { this.buttonsEl.find('button').addClass(this.theme.buttonsClass); } } } }; return themes; });
JavaScript
0
@@ -231,23 +231,25 @@ lt%0D%0A +' default +' : %7B%0D%0A @@ -775,19 +775,21 @@ s2%0D%0A +' bs2 +' : %7B%0D%0A @@ -1546,19 +1546,21 @@ s3%0D%0A +' bs3 +' : %7B%0D%0A
3b86a2b62daade3103a8c2098aef018df1549be5
appropriate filename
listen-to.js
listen-to.js
#!/usr/bin/env node var del = require('del'); var fs = require('fs'); var Player = require('player'); var program = require('commander'); var request = require('superagent'); var youtubedl = require('youtube-dl'); function searchMusic(query, cb) { superagent .get('http://partysyncwith.me:3005/search/'+ query +'/1') .end(function(err, res) { if(err) { console.log(err); } else { if (typeof JSON.parse(res.text).data !== 'undefined') { if (JSON.parse(res.text).data[0].duration < 600) { var url = JSON.parse(res.text).data[0].video_url; cb(url); } else { cb(null); } } } }) } program .version('0.0.0') .command('listen-to <title>') .action(function (title) { searchMusic(title, function(url) { var video = youtubedl(searchMusic(url), ['--extract-audio']); video.on('info', function(info) { console.log('Download started'); console.log('filename: ' + info.filename); console.log('size: ' + info.size); }); video.pipe(fs.createWriteStream('song.mp3')); var player = new Player('./song.mp3'); player.play(function(err, player){ console.log('end!'); }); del(['song.mp3'], function (err, deletedFiles) { console.log('Deleted ', deletedFiles.join(', ')); }); }); }); program.parse(process.argv);
JavaScript
0.999936
@@ -1086,20 +1086,20 @@ Stream(' -song +temp .mp3')); @@ -1133,20 +1133,20 @@ ayer('./ -song +temp .mp3');%0A @@ -1216,32 +1216,33 @@ nd!');%0A %7D); +q %0A%0A del(%5B'so @@ -1243,12 +1243,12 @@ l(%5B' -song +temp .mp3
b819e51a025f78ddd10d994b7377995fbdfacdfa
fix moment
site/bisheng.config.js
site/bisheng.config.js
const path = require('path'); module.exports = { port: 8001, source: [ './components', './docs', 'CHANGELOG.md', // TODO: fix it in bisheng ], lazyLoad: true, entry: { index: { theme: './site/theme', htmlTemplate: './site/theme/static/template.html', }, 'kitchen-sink': { theme: './site/mobile', htmlTemplate: './site/mobile/static/template.html', }, }, plugins: [ 'bisheng-plugin-description', 'bisheng-plugin-toc?maxDepth=2', 'bisheng-plugin-react?lang=__react', 'bisheng-plugin-antd', ], doraConfig: { verbose: true, plugins: ['dora-plugin-upload'], }, webpackConfig(config) { config.resolve.alias = { 'antd-mobile': process.cwd(), site: path.join(process.cwd(), 'site'), }; config.babel.plugins.push([ require.resolve('babel-plugin-antd'), { style: true, libraryName: 'antd-mobile', libDir: 'components', }, ]); return config; }, };
JavaScript
0.000006
@@ -672,16 +672,59 @@ nfig) %7B%0A + config.module.noParse = %5B/moment.js/%5D;%0A conf
5bcc7adf040230daaa488377a737a9c534ea2837
add differentialCentrifugalSedimentation and hgPorosimetry
eln/jpaths.js
eln/jpaths.js
import Datas from 'src/main/datas'; import API from 'src/util/api'; const DataObject = Datas.DataObject; const jpaths = {}; // general jpaths.image = ['$content', 'image']; jpaths.video = ['$content', 'video']; jpaths.attachments = ['attachmentList']; // For samples jpaths.sampleCode = ['$id', 0]; jpaths.batchCode = ['$id', 1]; jpaths.creationDate = ['$creationDate']; jpaths.modificationDate = ['$modificationDate']; jpaths.content = ['$content']; jpaths.general = ['$content', 'general']; jpaths.molfile = ['$content', 'general', 'molfile']; jpaths.firstPeptide = ['$content', 'biology', 'peptidic', '0', 'seq', '0']; jpaths.firstNucleotide = ['$content', 'biology', 'nucleic', '0', 'seq', '0']; jpaths.mf = ['$content', 'general', 'mf']; jpaths.mw = ['$content', 'general', 'mw']; jpaths.em = ['$content', 'general', 'em']; jpaths.description = ['$content', 'general', 'description']; jpaths.title = ['$content', 'general', 'title']; jpaths.name = ['$content', 'general', 'name']; jpaths.keyword = ['$content', 'general', 'keyword']; jpaths.meta = ['$content', 'general', 'meta']; jpaths.physical = ['$content', 'physical']; jpaths.bp = ['$content', 'physical', 'bp']; jpaths.nd = ['$content', 'physical', 'nd']; jpaths.mp = ['$content', 'physical', 'mp']; jpaths.density = ['$content', 'physical', 'density']; jpaths.stock = ['$content', 'stock']; jpaths.stockHistory = ['$content', 'stock', 'history']; jpaths.lastStock = ['$content', 'stock', 'history', 0]; jpaths.supplier = ['$content', 'stock', 'supplier']; jpaths.ir = ['$content', 'spectra', 'ir']; jpaths.raman = ['$content', 'spectra', 'raman']; jpaths.uv = ['$content', 'spectra', 'uv']; jpaths.iv = ['$content', 'spectra', 'iv']; jpaths.mass = ['$content', 'spectra', 'mass']; jpaths.nmr = ['$content', 'spectra', 'nmr']; jpaths.nucleic = ['$content', 'biology', 'nucleic']; jpaths.peptidic = ['$content', 'biology', 'peptidic']; jpaths.chromatogram = ['$content', 'spectra', 'chromatogram']; jpaths.biology = ['$content', 'biology']; jpaths.xrd = ['$content', 'spectra', 'xrd']; jpaths.xps = ['$content', 'spectra', 'xps']; jpaths.isotherm = ['$content', 'spectra', 'isotherm']; jpaths.thermogravimetricAnalysis = [ '$content', 'spectra', 'thermogravimetricAnalysis', ]; jpaths.cyclicVoltammetry = ['$content', 'spectra', 'cyclicVoltammetry']; jpaths.elementalAnalysis = ['$content', 'spectra', 'elementalAnalysis']; jpaths.differentialScanningCalorimetry = [ '$content', 'spectra', 'differentialScanningCalorimetry', ]; jpaths.xray = ['$content', 'spectra', 'xray']; // For reactions jpaths.reactionCode = ['$id']; jpaths.procedure = ['$content', 'procedure']; jpaths.reagents = ['$content', 'reagents']; jpaths.products = ['$content', 'products']; export function createVar(variable, varName) { check(varName); API.setVariable(varName, variable, jpaths[varName]); } export function getData(sample, varName) { check(varName); sample = _getData(sample); return sample.getChildSync(jpaths[varName]); } export function setData(sample, varName) { check(varName); // todo fix this // sample = get(sample); sample.setChildSync(jpaths[varName]); } function check(varName) { if (!jpaths[varName]) { throw new Error(`jpath for ${varName} not defined`); } } function _getData(variable) { if (DataObject.getType(variable) === 'string') { return API.getData(variable); } return variable; }
JavaScript
0
@@ -2311,24 +2311,256 @@ tammetry'%5D;%0A +jpaths.hgPorosimetry = %5B'$content', 'spectra', 'hgPorosimetry'%5D;%0Ajpaths.differentialCentrifugalSedimentation = %5B'$content', 'spectra', 'differentialCentrifugalSedimentation'%5D;%0Ajpaths.disc = %5B'$content', 'spectra', 'hgPorosimetry'%5D;%0A jpaths.eleme
20fc024365638d8ea5516efddc0ccdf09470f576
Use chai.assert in typeAssertionModule tests.
test/feature/TypeAssertions/resources/assert.js
test/feature/TypeAssertions/resources/assert.js
export var assert = this.assert; assert.type = function (actual, type) { if (type === $traceurRuntime.type.any) { return actual; } if (type === $traceurRuntime.type.void) { assert.isUndefined(actual); return actual; } if ($traceurRuntime.type[type.name] === type) { // chai.assert treats Number as number :'( // Use runtime to handle symbol assert.equal($traceurRuntime.typeof(actual), type.name); } else if (type instanceof $traceurRuntime.GenericType) { assert.type(actual, type.type); if (type.type === Array) { for (var i = 0; i < actual.length; i++) { assert.type(actual[i], type.argumentTypes[0]); } } else { throw new Error(`Unsupported generic type${type}`); } } else { assert.instanceOf(actual, type); } // TODO(arv): Handle more generics, structural types and more. return actual; }; assert.argumentTypes = function(...params) { for (var i = 0; i < params.length; i += 2) { if (params[i + 1] !== null) { assert.type(params[i], params[i + 1]); } } }; assert.returnType = assert.type;
JavaScript
0
@@ -17,12 +17,12 @@ t = -this +chai .ass
2dee01a23db8df87df7725c4e331eff02dfac8c4
Generate specs dynamically
ssr-express/spec/lib/AmpSsrMiddlewareSpec.js
ssr-express/spec/lib/AmpSsrMiddlewareSpec.js
/** * Copyright 2018 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const MockExpressRequest = require('mock-express-request'); const MockExpressResponse = require('mock-express-response'); const AmpSsrMiddleware = require('../../lib/AmpSsrMiddleware'); class TestTransformer { transformHtml(body, options) { return Promise.resolve('transformed: ' + options.ampUrl); } } function runMiddlewareForUrl(middleware, url, accepts = () => 'html') { return new Promise(resolve => { const mockResponse = new MockExpressResponse(); const next = () => mockResponse.send('original'); const mockRequest = new MockExpressRequest({ url: url }); mockRequest.accepts = accepts; const end = mockResponse.end; mockResponse.end = chunks => { mockResponse.end = end; mockResponse.end(chunks); resolve(mockResponse._getString()); }; middleware(mockRequest, mockResponse, next); }); } describe('Express Middleware', () => { describe('Default configuration', () => { const middleware = AmpSsrMiddleware.create({ampSsr: new TestTransformer()}); it('Transforms URLs', () => { runMiddlewareForUrl(middleware, '/stuff?q=thing') .then(result => { expect(result).toEqual('transformed: /stuff?q=thing&amp='); }); }); it('Skips Urls starting with "/amp/"', () => { runMiddlewareForUrl(middleware, '/amp/stuff?q=thing&amp') .then(result => { expect(result).toEqual('original'); }); }); it('Skips Resource Requests', () => { const staticResources = ['/image.jpg', '/image.svg', '/script.js', '/style.css']; const runStaticTest = url => { runMiddlewareForUrl(middleware, url) .then(result => { expect(result).toEqual('original'); }); }; staticResources.forEach(url => runStaticTest(url)); }); it('Applies transformation if req.accept method does not exist', () => { runMiddlewareForUrl(middleware, '/page.html', null) .then(result => { expect(result).toEqual('transformed: /page.html?amp='); }); }); it('Skips transformation if request does not accept HTML', () => { runMiddlewareForUrl(middleware, '/page.html', () => '') .then(result => { expect(result).toEqual('original'); }); }); }); });
JavaScript
0.999994
@@ -2077,140 +2077,8 @@ );%0A%0A - it('Skips Resource Requests', () =%3E %7B%0A const staticResources = %5B'/image.jpg', '/image.svg', '/script.js', '/style.css'%5D;%0A @@ -2104,26 +2104,24 @@ = url =%3E %7B%0A - runMid @@ -2155,26 +2155,24 @@ rl)%0A - - .then(result @@ -2169,34 +2169,32 @@ hen(result =%3E %7B%0A - expect @@ -2231,26 +2231,24 @@ - - %7D);%0A %7D;%0A @@ -2243,46 +2243,130 @@ - %7D;%0A +%0A - staticResources.forEach(url +%5B'/image.jpg', '/image.svg', '/script.js', '/style.css'%5D.forEach(url =%3E %7B%0A it(%60Does not transform $%7Burl%7D%60, () =%3E
ef020e254052cdaf7d0afc53379ec380270c0bd0
remove some manual reflect metadata manipulation
generators/app/templates/gulp_tasks/systemjs.js
generators/app/templates/gulp_tasks/systemjs.js
const gulp = require('gulp'); const replace = require('gulp-replace'); <% if (framework === 'angular1' && js !== 'typescript') { -%> const Builder = require('systemjs-builder'); <% } else if (framework === 'angular2') { -%> const Builder = require('jspm').Builder; const inlineNg2Template = require('gulp-inline-ng2-template'); const del = require('del'); <% } else { -%> const Builder = require('jspm').Builder; <% } -%> const conf = require('../conf/gulp.conf'); <% if (framework === 'angular2') { -%> gulp.task('systemjs', gulp.series(replaceTemplates, systemjs)); gulp.task('systemjs:html', updateIndexHtml); <% } else { -%> gulp.task('systemjs', systemjs); gulp.task('systemjs:html', updateIndexHtml); <% } -%> function systemjs(done) { const builder = new Builder('./', 'jspm.config.js'); builder.config({ paths: { "github:*": "jspm_packages/github/*", "npm:*": "jspm_packages/npm/*" }, packageConfigPaths: [ 'npm:@*/*.json', 'npm:*.json', 'github:*/*.json' ] }); builder.buildStatic( <%- entry %>, conf.path.tmp('index.js'), { production: true, browser: true } ).then(() => { <% if (framework === 'angular2') { -%> del([conf.path.tmp('templates')]); <% } -%> done(); }, done); } <% if (framework === 'angular2') { -%> function replaceTemplates() { return gulp.src(conf.path.src(`**/*.<%- extensions.js %>`)) .pipe(inlineNg2Template({base: conf.path.src('app'), useRelativePaths: true})) .pipe(gulp.dest(conf.path.tmp('templates'))); } <% } -%> function updateIndexHtml() { return gulp.src(conf.path.src('index.html')) .pipe(replace( /<script src="jspm_packages\/system.js">[\s\S]*System.import.*\n\s*<\/script>/, `<script src="index.js"></script>` )) <% if (framework === 'angular2') { -%> .pipe(replace( /<!-- <script src="(node_modules)(\/([\s\S]*?))*"><\/script> -->/g, `<script src="vendor$2"></script>` )) <% } -%> .pipe(gulp.dest(conf.path.tmp())); }
JavaScript
0
@@ -567,53 +567,8 @@ ));%0A -gulp.task('systemjs:html', updateIndexHtml);%0A %3C%25 %7D @@ -612,16 +612,25 @@ temjs);%0A +%3C%25 %7D -%25%3E%0A gulp.tas @@ -665,25 +665,16 @@ exHtml); -%0A%3C%25 %7D -%25%3E %0A%0Afuncti
aea57e14badda691d7fc971b04619d5b103efcce
delete console
src/board/basic_block.js
src/board/basic_block.js
"use strict"; goog.require('Entry.STATIC'); Entry.block.run = { skeleton: "basic", color: "#3BBD70", contents: [ "this is", "basic block" ], func: function() { } }; Entry.block.jr_start = { skeleton: "pebble_event", color: "#3BBD70", contents: [ { type: "Indicator", img: "/img/assets/ntry/bitmap/jr/block_play_image.png", highlightColor: "#3BBD70", size: 22 } ], func: function() { console.log('start'); return Entry.STATIC.RETURN; } }; Entry.block.jr_repeat = { skeleton: "pebble_loop", color: "#3BBD70", contents: [ "1", "반복" ], func: function() { console.log('repeat'); } }; Entry.block.jr_item = { skeleton: "pebble_basic", color: "#F46C6C", contents: [ "꽃 모으기", { type: "Indicator", img: "/img/assets/ntry/bitmap/jr/block_item_image.png", highlightColor: "#FFF", position: {x: 83, y: 0}, size: 22 } ], func: function() { } }; Entry.block.jr_north = { skeleton: "pebble_basic", color: "#A751E3", contents: [ " 위로", { type: "Indicator", img: "/img/assets/ntry/bitmap/jr/block_up_image.png", position: {x: 83, y: 0}, size: 22 } ], func: function() { console.log('up'); return Entry.STATIC.RETURN; } }; Entry.block.jr_east = { skeleton: "pebble_basic", color: "#A751E3", contents: [ "오른쪽", { type: "Indicator", img: "/img/assets/ntry/bitmap/jr/block_right_image.png", position: {x: 83, y: 0}, size: 22 } ], func: function() { console.log('east'); return Entry.STATIC.RETURN; } }; Entry.block.jr_south = { skeleton: "pebble_basic", color: "#A751E3", contents: [ "아래로", { type: "Indicator", img: "/img/assets/ntry/bitmap/jr/block_down_image.png", position: {x: 83, y: 0}, size: 22 } ], func: function() { console.log('south'); return Entry.STATIC.RETURN; } }; Entry.block.jr_west = { skeleton: "pebble_basic", color: "#A751E3", contents: [ " 왼쪽", { type: "Indicator", img: "/img/assets/ntry/bitmap/jr/block_left_image.png", position: {x: 83, y: 0}, size: 22 } ], func: function() { console.log('west'); return Entry.STATIC.RETURN; } };
JavaScript
0.000004
@@ -508,38 +508,8 @@ ) %7B%0A - console.log('start');%0A
4fa9d210dae2bbb7a288cbd572e58a3ede64d97b
fix tz
js/application/action/api.js
js/application/action/api.js
if(App.namespace) { App.namespace('Action.Api', function(App) { /** * @namespace App.Action.Api * @type {*} */ var api = {}; var Error = null; /** * @namespace App.Action.Api.init * @param error */ api.init = function(error) { Error = App.Action.Error; }; /** * identifier ready the request to the server * @type {boolean} */ api.saveAllReady = true; /** * Save all tasks, links and project data * @namespace App.Action.Api.saveAll * @param callback */ api.saveAll = function(callback) { var store = App.Module.DataStore, tasks = App.Action.Project.tasks(), visitortime = new Date(), visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60, dataSend = { tasks: JSON.stringify( tasks ), links: JSON.stringify( gantt.getLinks() ), project: JSON.stringify( store.get('project') ), timezone: api.gezTimezone() }; // Update states App.Action.Chart.addStates(Util.objClone(tasks)); //console.log(tasks); if(api.saveAllReady){ api.saveAllReady = false; api.request('saveall', function(response){ api.saveAllReady = true; callback.call(this, response); console.log(response); }, dataSend); } }; api.gezTimezone = function () { if (jstz && jstz.determine) { var tz = jstz.determine(); var date = new Date(); var hrs = date.toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; var tzname = date.toString().match(/\(([A-Za-z\s].*)\)/)[1]; return { hrs: hrs, geo: tzname, timezone: tz.name() } } }; /** * @namespace App.Action.Api.request * @param key * @param callback * @param args * @param timeout_ms */ api.request = function(key, callback, args, timeout_ms) { //console.log('dataSend-request', args); $.ajax({ url: App.url + '/api', data: {key: key, uid: App.uid, data: args}, type: 'POST', timeout: timeout_ms || 36000, headers: {requesttoken: App.requesttoken}, success: function (response) { if (typeof callback === 'function') { callback.call(App, response); } }, error: function (error) { console.error("API request error to the key: [" + key + "] Error message: ", error); }, complete: function (jqXHR, status) { if (status == 'timeout') { console.error("You have exceeded the request time. possible problems with the Internet, or an error on the server"); } } }); }; /** * @namespace App.Action.Api.sendEmails * @param emails * @param resources * @param link */ api.sendEmails = function(emails, resources, link){ // change all icon to loading emails $('.share_email_butn') .css('background', 'url("/apps/owncollab_chart/img/loading-small.gif") no-repeat center center'); app.api('sendshareemails', function(response) { if(typeof response === 'object' && !response['error'] ) { // App.requesttoken = response.requesttoken; && response['requesttoken'] $('.share_email_butn') .css('background', 'url("/apps/owncollab_chart/img/sent.png") no-repeat center center'); } else { Error.inline('Error Request on send share emails'); } } , { emails: emails, resources: resources, link: link, projemail: App.Action.Project.urlName() }); }; return api; })}
JavaScript
0.000003
@@ -695,123 +695,8 @@ (),%0A - visitortime = new Date(),%0A visitortimezone = %22GMT %22 + -visitortime.getTimezoneOffset()/60,%0A @@ -1450,318 +1450,59 @@ -var tz = jstz.determine();%0A var date = new Date();%0A var hrs = date.toString().match(/(%5BA-Z%5D+%5B%5C+-%5D%5B0-9%5D+)/)%5B1%5D;%0A var tzname = date.toString().match(/%5C((%5BA-Za-z%5Cs%5D.*)%5C)/)%5B1%5D;%0A return %7B%0A hrs: hrs,%0A geo: tzname,%0A timezone: tz +return %7B%0A timezone: jstz.determine() .nam
7db1dc907a7e4b156ff5aebc8671758124afe3ca
revert generic.js
js/base/functions/generic.js
js/base/functions/generic.js
"use strict"; /* ------------------------------------------------------------------------ */ const { isObject, isNumber, isInteger, isDictionary, isArray } = require ('./type') /* ------------------------------------------------------------------------ */ const keys = Object.keys , values = x => !isArray (x) // don't copy arrays if they're already arrays! ? Object.values (x) : x , index = x => new Set (values (x)) , extend = (...args) => Object.assign ({}, ...args) // NB: side-effect free , clone = x => isArray (x) ? Array.from (x) // clones arrays : extend (x) // clones objects /* ------------------------------------------------------------------------ */ module.exports = { keys , values , extend , clone , index , ordered: x => x // a stub to keep assoc keys in order (in JS it does nothing, it's mostly for Python) , unique: x => Array.from (index (x)) /* ............................................. */ , inArray (needle, haystack) { return haystack.includes (needle) } , toArray (object) { return Object.values (object) } , isEmpty (object) { if (!object) return true; return (Array.isArray (object) ? object : Object.keys (object)).length < 1; } /* ............................................. */ , keysort (x, out = {}) { for (const k of keys (x).sort ()) out[k] = x[k] return out } /* ............................................. */ /* Accepts a map/array of objects and a key name to be used as an index: array = [ { someKey: 'value1', anotherKey: 'anotherValue1' }, { someKey: 'value2', anotherKey: 'anotherValue2' }, { someKey: 'value3', anotherKey: 'anotherValue3' }, ] key = 'someKey' Returns a map: { value1: { someKey: 'value1', anotherKey: 'anotherValue1' }, value2: { someKey: 'value2', anotherKey: 'anotherValue2' }, value3: { someKey: 'value3', anotherKey: 'anotherValue3' }, } Array objects itself can be array too: array = [ [7900.0, 10.0], [7901.0, 8.8], ] key = 0 Returns: { 7900.0: [7900.0, 10.0], 7901.0: [7901.0, 8.8], } */ , indexBy (x, k, out = {}) { const isIntKey = isInteger (k) for (const v of values (x)) { if ((isIntKey && (k < v.length)) || (k in v)) { out[v[k]] = v } } return out } /* ............................................. */ /* Accepts a map/array of objects and a key name to be used as a grouping parameter: array = [ { someKey: 'value1', anotherKey: 'anotherValue1' }, { someKey: 'value1', anotherKey: 'anotherValue2' }, { someKey: 'value3', anotherKey: 'anotherValue3' }, ] key = 'someKey' Returns a map: { value1: [ { someKey: 'value1', anotherKey: 'anotherValue1' }, { someKey: 'value1', anotherKey: 'anotherValue2' }, ] value3: [ { someKey: 'value3', anotherKey: 'anotherValue3' } ], } */ , groupBy (x, k, out = {}) { for (const v of values (x)) { if (k in v) { const p = v[k] out[p] = out[p] || [] out[p].push (v) } } return out } /* ............................................. */ /* Accepts a map/array of objects, a key name and a key value to be used as a filter: array = [ { someKey: 'value1', anotherKey: 'anotherValue1' }, { someKey: 'value2', anotherKey: 'anotherValue2' }, { someKey: 'value3', anotherKey: 'anotherValue3' }, ] key = 'someKey' value = 'value1' Returns an array: [ value1: { someKey: 'value1', anotherKey: 'anotherValue1' }, ] */ , filterBy (x, k, value = undefined, out = []) { for (const v of values (x)) if (v[k] === value) out.push (v) return out } /* ............................................. */ , sortBy: (array, // NB: MUTATES ARRAY! key, descending = false, direction = descending ? -1 : 1) => array.sort ((a, b) => ((a[key] < b[key]) ? -direction : ((a[key] > b[key]) ? direction : 0))) /* ............................................. */ , flatten: function flatten (x, out = []) { for (const v of x) { if (isArray (v)) flatten (v, out) else out.push (v) } return out } /* ............................................. */ , pluck: (x, k) => values (x) .filter (v => k in v) .map (v => v[k]) /* ............................................. */ , omit (x, ...args) { if (!Array.isArray (x)) { const out = clone (x) for (const k of args) { if (isArray (k)) { // omit (x, ['a', 'b']) for (const kk of k) { delete out[kk] } } else delete out[k] // omit (x, 'a', 'b') } return out } return x } /* ............................................. */ , sum (...xs) { const ns = xs.filter (isNumber) // leave only numbers return (ns.length > 0) ? ns.reduce ((a, b) => a + b, 0) : undefined } /* ............................................. */ , deepExtend: function deepExtend (...xs) { let out = undefined for (const x of xs) { if (isDictionary (x)) { if (!isObject (out)) out = {} for (const k in x) out[k] = deepExtend (out[k], x[k]) } else out = x } return out } /* ------------------------------------------------------------------------ */ }
JavaScript
0.000001
@@ -120,19 +120,8 @@ ber, - isInteger, isD @@ -2195,247 +2195,8 @@ %7D -%0A%0A Array objects itself can be array too:%0A array = %5B%0A %5B7900.0, 10.0%5D,%0A %5B7901.0, 8.8%5D,%0A %5D%0A key = 0%0A%0A Returns:%0A %7B%0A 7900.0: %5B7900.0, 10.0%5D,%0A 7901.0: %5B7901.0, 8.8%5D,%0A %7D %0A @@ -2237,46 +2237,8 @@ ) %7B%0A - const isIntKey = isInteger (k) %0A @@ -2261,34 +2261,32 @@ v of values (x)) - %7B %0A if @@ -2288,41 +2288,8 @@ if - ((isIntKey && (k %3C v.length)) %7C%7C (k @@ -2293,19 +2293,16 @@ (k in v) -) %7B %0A @@ -2324,39 +2324,16 @@ k%5D%5D = v%0A - %7D%0A %7D %0A
5e71ceced825a8495725c24d3790fbe564de237a
Make 'height' property of wire-handle
js/components/wire-handle.js
js/components/wire-handle.js
(function(app) { 'use strict'; var jCore = require('jcore'); var dom = app.dom || require('../dom.js'); var WireHandle = jCore.Component.inherits(function(props) { this.cx = this.prop(props.cx); this.cy = this.prop(props.cy); this.type = this.prop(props.type); this.visible = this.prop(props.visible); this.highlighted = this.prop(props.highlighted); this.width = this.prop(24); this.port = props.port; }); WireHandle.prototype.render = function() { return dom.render(WireHandle.HTML_TEXT); }; WireHandle.prototype.onredraw = function() { this.redrawBy('cx', 'cy', function(cx, cy) { dom.translate(this.element(), cx - this.width() / 2, cy - this.width() / 2); }); this.redrawBy('type', function(type) { dom.data(this.element(), 'type', type); }); this.redrawBy('visible', function(visible) { dom.toggleClass(this.element(), 'hide', !visible); }); this.redrawBy('highlighted', function(highlighted) { dom.toggleClass(this.element(), 'highlighted', highlighted); }); }; WireHandle.HTML_TEXT = '<div class="wire-handle"></div>'; if (typeof module !== 'undefined' && module.exports) { module.exports = WireHandle; } else { app.WireHandle = WireHandle; } })(this.app || (this.app = {}));
JavaScript
0.00258
@@ -406,16 +406,49 @@ op(24);%0A + this.height = this.prop(24);%0A this @@ -731,29 +731,30 @@ , cy - this. -width +height () / 2);%0A
da1e58a7c5b6a722e64a8d92da757b7ed74014b0
Handle case where no directory is resolved
src/lib/ModuleBundler.js
src/lib/ModuleBundler.js
import Promise from 'bluebird' import path, { sep } from 'path' import fs from 'fs-extra' import resolvePackage from 'resolve-pkg' import { walker, handleFile } from './utils' import UglifyTransform from './transforms/Uglify' Promise.promisifyAll(fs) /** * @class ModuleBundler * * Handles the inclusion of node_modules. */ export default class ModuleBundler { constructor(config = {}, artifact) { this.config = { servicePath : '', // serverless.config.servicePath uglify : null, // UglifyJS config zip : null, // Yazl zip config ...config, } this.artifact = artifact } /** * Determines module locations then adds them into ./node_modules * inside the artifact. */ async bundle({ include = [], exclude = [], deepExclude = [] }) { const modules = await this._resolveDependencies(this.config.servicePath, { include, exclude, deepExclude }) const transforms = await this._createTransforms() await Promise.map(modules, async ({ packagePath, relativePath }) => { const onFile = async (basePath, stats, next) => { const relPath = path.join( relativePath, basePath.split(relativePath)[1], stats.name ).replace(/^\/|\/$/g, '') const filePath = path.join(basePath, stats.name) await handleFile({ filePath, relPath, transforms, transformExtensions : ['js', 'jsx'], useSourceMaps : false, artifact : this.artifact, zipConfig : this.config.zip, }) next() } await walker(packagePath) .on('file', onFile) .end() }) return this } async _createTransforms() { const transforms = [] let uglifyConfig = this.config.uglify if ( uglifyConfig ) { if ( uglifyConfig === true ) uglifyConfig = null transforms.push( new UglifyTransform(uglifyConfig) ) } return transforms } /** * Resolves a package's dependencies to an array of paths. * * @returns {Array} * [ { name, packagePath, packagePath } ] */ async _resolveDependencies(initialPackageDir, { include = [], exclude = [], deepExclude = [] } = {}) { const resolvedDeps = [] const cache = {} const seperator = `${sep}node_modules${sep}` /** * Resolves packages to their package root directory & also resolves dependant packages recursively. * - Will also ignore the input package in the results */ async function recurse(packageDir, _include = [], _exclude = []) { const packageJson = require( path.join(packageDir, './package.json') ) const { name, dependencies } = packageJson for ( let packageName in dependencies ) { /** * Skips on exclude matches, if set * Skips on include mis-matches, if set */ if ( _exclude.length && _exclude.indexOf(packageName) > -1 ) continue if ( _include.length && _include.indexOf(packageName) < 0 ) continue const resolvedDir = resolvePackage(packageName, { cwd: packageDir }) const relativePath = path.join( 'node_modules', resolvedDir.split(`${seperator}`).slice(1).join(seperator) ) if ( relativePath in cache ) continue cache[relativePath] = true const result = await recurse(resolvedDir, undefined, deepExclude) resolvedDeps.push({ ...result, relativePath }) } return { name, packagePath: packageDir, } } await recurse(initialPackageDir, include, exclude) return resolvedDeps } }
JavaScript
0.000001
@@ -3478,16 +3478,80 @@ geDir %7D) +%0A%0A if ( ! resolvedDir ) continue%0A %0A
87d5f4c8bc11c855b4d675954d6ca150cf7a484f
Use 'helper' from WebGLHelper in tests
test/spec/ol/renderer/webgl/pointslayer.test.js
test/spec/ol/renderer/webgl/pointslayer.test.js
import Feature from '../../../../../src/ol/Feature.js'; import Point from '../../../../../src/ol/geom/Point.js'; import VectorLayer from '../../../../../src/ol/layer/Vector.js'; import VectorSource from '../../../../../src/ol/source/Vector.js'; import WebGLPointsLayerRenderer from '../../../../../src/ol/renderer/webgl/PointsLayer.js'; import {get as getProjection} from '../../../../../src/ol/proj.js'; import ViewHint from '../../../../../src/ol/ViewHint.js'; import {POINT_VERTEX_STRIDE, WebGLWorkerMessageType} from '../../../../../src/ol/renderer/webgl/Layer.js'; describe('ol.renderer.webgl.PointsLayer', function() { describe('constructor', function() { let target; beforeEach(function() { target = document.createElement('div'); target.style.width = '256px'; target.style.height = '256px'; document.body.appendChild(target); }); afterEach(function() { document.body.removeChild(target); }); it('creates a new instance', function() { const layer = new VectorLayer({ source: new VectorSource() }); const renderer = new WebGLPointsLayerRenderer(layer); expect(renderer).to.be.a(WebGLPointsLayerRenderer); }); }); describe('#prepareFrame', function() { let layer, renderer, frameState; beforeEach(function() { layer = new VectorLayer({ source: new VectorSource() }); renderer = new WebGLPointsLayerRenderer(layer); const projection = getProjection('EPSG:3857'); frameState = { skippedFeatureUids: {}, viewHints: [], viewState: { projection: projection, resolution: 1, rotation: 0, center: [0, 0] }, size: [2, 2], extent: [-100, -100, 100, 100] }; }); it('calls WebGlHelper#prepareDraw', function() { const spy = sinon.spy(renderer.helper_, 'prepareDraw'); renderer.prepareFrame(frameState); expect(spy.called).to.be(true); }); it('fills up a buffer with 2 triangles per point', function(done) { layer.getSource().addFeature(new Feature({ geometry: new Point([10, 20]) })); layer.getSource().addFeature(new Feature({ geometry: new Point([30, 40]) })); renderer.prepareFrame(frameState); const attributePerVertex = POINT_VERTEX_STRIDE; renderer.worker_.addEventListener('message', function(event) { if (event.data.type !== WebGLWorkerMessageType.GENERATE_BUFFERS) { return; } expect(renderer.verticesBuffer_.getArray().length).to.eql(2 * 4 * attributePerVertex); expect(renderer.indicesBuffer_.getArray().length).to.eql(2 * 6); expect(renderer.verticesBuffer_.getArray()[0]).to.eql(10); expect(renderer.verticesBuffer_.getArray()[1]).to.eql(20); expect(renderer.verticesBuffer_.getArray()[4 * attributePerVertex + 0]).to.eql(30); expect(renderer.verticesBuffer_.getArray()[4 * attributePerVertex + 1]).to.eql(40); done(); }); }); it('clears the buffers when the features are gone', function(done) { const source = layer.getSource(); source.addFeature(new Feature({ geometry: new Point([10, 20]) })); source.removeFeature(source.getFeatures()[0]); source.addFeature(new Feature({ geometry: new Point([10, 20]) })); renderer.prepareFrame(frameState); renderer.worker_.addEventListener('message', function(event) { if (event.data.type !== WebGLWorkerMessageType.GENERATE_BUFFERS) { return; } const attributePerVertex = 12; expect(renderer.verticesBuffer_.getArray().length).to.eql(4 * attributePerVertex); expect(renderer.indicesBuffer_.getArray().length).to.eql(6); done(); }); }); it('rebuilds the buffers only when not interacting or animating', function() { const spy = sinon.spy(renderer, 'rebuildBuffers_'); frameState.viewHints[ViewHint.INTERACTING] = 1; frameState.viewHints[ViewHint.ANIMATING] = 0; renderer.prepareFrame(frameState); expect(spy.called).to.be(false); frameState.viewHints[ViewHint.INTERACTING] = 0; frameState.viewHints[ViewHint.ANIMATING] = 1; renderer.prepareFrame(frameState); expect(spy.called).to.be(false); frameState.viewHints[ViewHint.INTERACTING] = 0; frameState.viewHints[ViewHint.ANIMATING] = 0; renderer.prepareFrame(frameState); expect(spy.called).to.be(true); }); it('rebuilds the buffers only when the frame extent changed', function() { const spy = sinon.spy(renderer, 'rebuildBuffers_'); renderer.prepareFrame(frameState); expect(spy.callCount).to.be(1); renderer.prepareFrame(frameState); expect(spy.callCount).to.be(1); frameState.extent = [10, 20, 30, 40]; renderer.prepareFrame(frameState); expect(spy.callCount).to.be(2); }); }); });
JavaScript
0.000004
@@ -1896,17 +1896,16 @@ r.helper -_ , 'prepa
711be69effacb9548a9e3d55f9571f2da316d44c
Allow alternate XMLHttpRequest in Client
proximal.js
proximal.js
/* * proximal - minimal JSON RPC over HTTP with Proxy/Promise interface * https://github.com/gavinhungry/proximal */ ((global, props, factory) => { (typeof define === 'function' && define.amd) ? define(props.name, factory) : (typeof module === 'object' && module.exports) ? module.exports = factory() : global[props.export || props.name] = factory(); })(this, { name: 'proximal' }, () => { 'use strict'; /** * Proximal client constructor * * @param {Object} opts * @param {String} opts.url - URL of remote endpoint */ let Client = (() => { let Client = function ProximalClient(opts = {}) { if (!opts.url) { throw new Error('url is required'); } this.url = opts.url; }; Client.prototype = { /** * Get a Proxy object representing a remote module * * @param {String} moduleName * @return {Proxy} */ getModule: function(moduleName) { if (!moduleName) { throw new Error('moduleName is required'); } return new Proxy({ url: this.url, moduleName: moduleName }, { get: (obj, methodName) => { return (...args) => { return new Promise((res, rej) => { let xhr = new XMLHttpRequest(); xhr.open('POST', this.url); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onerror = e => rej(xhr.responseText); xhr.onload = e => { if (xhr.status !== 200) { return xhr.onerror(e); } try { res(JSON.parse(xhr.responseText)); } catch(err) { res(null); } }; xhr.send(JSON.stringify({ moduleName, methodName, args })); }); }; } }); } }; return Client; })(); /** * Proximal server constructor * * @param {Object} opts * @param {Object} opts.modules - map of modules to be included */ let Server = (() => { class ImplError extends Error {}; let Server = function ProximalServer(opts = {}) { if (!opts.modules || !Object.keys(opts.modules).length) { throw new Error('modules are required'); } this.modules = opts.modules; }; Server.prototype = { /** * Get the parsed JSON body from a request, even without body-parser * * @private * * @param {Request} req * @return {Promise<Object>} */ _getReqCall: function(req) { if (!req) { throw new Error('no body'); } if (req.body) { return Promise.resolve(req.body); } return new Promise((resolve, reject) => { let data = ''; req.on('data', chunk => data += chunk ); req.on('end', () => { try { resolve(JSON.parse(data)); } catch(err) { reject(err); } }); }); }, /** * Get the result of a module method * * @private * * @param {Object} call * @param {String} call.moduleName * @param {String} call.methodName * @param {Array<Mixed>} call.args * @return {Mixed} method result */ _getCallResult: function(call = {}) { let module = this.modules[call.moduleName]; if (!module) { throw new ImplError('module not found'); } let method = module[call.methodName]; if (!method || typeof method !== 'function') { throw new ImplError('method not found'); } return method.apply(module, call.args); }, /** * */ middleware: function() { return (req, res) => { this._getReqCall(req).then(call => this._getCallResult(call), err => { res.status(400).json('Error parsing RPC request body'); }).then(result => res.json(result), err => { res.status(err instanceof ImplError ? 501 : 500).json(err.message); }); }; } }; return Server; })(); return { Client, Server }; });
JavaScript
0.000001
@@ -537,16 +537,89 @@ ndpoint%0A + * @param %7BFunction%7D %5Bopts.xhr%5D - alternate XMLHttpRequest constructor%0A */%0A @@ -762,32 +762,77 @@ red');%0A %7D%0A%0A + this.XHR = opts.xhr %7C%7C XMLHttpRequest;%0A this.url = @@ -1402,30 +1402,24 @@ r = new -XMLHttpRequest +this.XHR ();%0A
7551ab2aadf2c73553299888a38e2c05c85c79a1
use semantic commit message in bump command hint (#120)
src/cli/commands/bump.js
src/cli/commands/bump.js
/** * Copyright 2018, Google, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; require('colors'); const fs = require('fs'); const path = require('path'); const semver = require('semver'); const buildPack = require('../../build_packs').getBuildPack(); const utils = require('../../utils'); const CLI_CMD = 'bump'; const COMMAND = `tools ${CLI_CMD} ${'<rev>'.yellow}`; const DESCRIPTION = `Bumps the specified semver value in both the main package and dependent packages (e.g. samples). ${ 'rev'.yellow.bold } can be one of ${'major'.green.bold}, ${'minor'.green.bold}, or ${ 'patch'.green.bold }.`; const USAGE = `Usage: ${COMMAND.bold} Description: ${DESCRIPTION} Positional arguments: ${'<rev>'.bold} The semver version to increase.`; exports.command = `${CLI_CMD} <rev>`; exports.description = DESCRIPTION; exports.builder = yargs => { yargs.usage(USAGE); }; exports.handler = opts => { try { if (opts.dryRun) { utils.logger.log(CLI_CMD, 'Beginning dry run.'.cyan); } if (!opts.rev) { throw new Error( `For argument "rev" expected one of "major", "minor", or "patch".` ); } else if (!opts.rev.match(/^major|minor|patch$/)) { throw new Error( `For argument "rev" expected one of "major", "minor", or "patch".` ); } buildPack.expandConfig(opts); let oldVersion = buildPack.config.pkgjson.version; let name = buildPack.config.pkgjson.name; let newVersion = semver.inc(oldVersion, opts.rev); utils.logger.log( CLI_CMD, `Version will be bumped from ${oldVersion.yellow} to ${ newVersion.yellow }.` ); let samplesPackageJson; let samplesPackageJsonPath = path.join( buildPack.config.global.localPath, 'samples', 'package.json' ); if (fs.existsSync(samplesPackageJsonPath)) { try { samplesPackageJson = JSON.parse( fs.readFileSync(samplesPackageJsonPath) ); } catch (err) { throw new Error( `Cannot parse samples package.json located at ${samplesPackageJsonPath}: ${err.toString()}` ); } } utils.logger.log( CLI_CMD, `Version in ${'package.json'.yellow} will be set to ${newVersion.yellow}.` ); if (samplesPackageJson !== undefined) { let dependency = `'${name}': '${newVersion}'`; utils.logger.log( CLI_CMD, `${'samples/package.json'.yellow} will depend on ${dependency.yellow}.` ); } if (opts.dryRun) { utils.logger.log(CLI_CMD, 'Dry run complete.'.cyan); return; } buildPack.config.pkgjson['version'] = newVersion; let packageJsonPath = path.join(opts.localPath, 'package.json'); try { fs.writeFileSync( packageJsonPath, JSON.stringify(buildPack.config.pkgjson, null, ' ') + '\n' ); } catch (err) { throw new Error(`Cannot write ${packageJsonPath}: ${err.toString()}`); } if (samplesPackageJson !== undefined) { if (samplesPackageJson['dependencies'] === undefined) { samplesPackageJson['dependencies'] = {}; } samplesPackageJson['dependencies'][name] = newVersion; try { fs.writeFileSync( samplesPackageJsonPath, JSON.stringify(samplesPackageJson, null, ' ') + '\n' ); } catch (err) { throw new Error( `Cannot write ${samplesPackageJsonPath}: ${err.toString()}` ); } } let message = `Files updated. Please regenerate package lock files and commit them: ${'rm -f package-lock.json && npm install && npm link'.yellow} ${'git add package.json package-lock.json'.yellow}`; if (samplesPackageJson !== undefined) { message += ` ${ 'cd samples && rm -f package-lock.json && npm link ../ && npm install && cd ..' .yellow } ${'git add samples/package.json samples/package-lock.json'.yellow}`; } message += ` ${'git commit -m "bump version to'.yellow} ${newVersion.yellow}${ '"'.yellow }`; utils.logger.log('bump', message); } catch (err) { utils.logger.error(CLI_CMD, err.toString()); // eslint-disable-next-line no-process-exit process.exit(1); } };
JavaScript
0
@@ -4523,16 +4523,23 @@ mit -m %22 +chore: bump ver
76e97a6de35dafb1e6602a05857fde78c4e94799
Fix expand / collapse
src/client/info-panel.js
src/client/info-panel.js
import React from 'react' class InfoPanel extends React.Component { constructor() { super() this.state = { collapsed: true } } render() { if (this.state.collapsed) { return <div id="side-info-panel-open" onClick={this.expand}>&lt;</div> } return <div className="side-info-panel"> <button id="close-side-info" onClick={this.collapse}>Sulje</button> <div className="logo-container"> <img src="/img/sataako-logo-white.png" alt="Sataako kohta logo - sataako.fi" title="Sataako kohta logo - sataako.fi" /> </div> <div className="description-container"> <h1>Sataako<br/>kohta?</h1> <div className="fb-share-button" data-layout="button_count"></div> <p>Live-sadetilanne kätevästi Suomessa ja lähialueilla. Milloin lähteä lenkille, uimarannalle, piknikille tai kalaan? Katso, missä lähin sadepilvi luuraa! Unohda hankalat täsmäsääpalvelut ja tuntiennusteet.</p> <p>Tutkakuva päivittyy automaattisesti ja jatkuvasti, viiden minuutin välein. Mitä lähempänä väri on punaista, sitä enemmän sataa.</p> <p>Tämän palvelun on tehnyt vapaa-ajallaan <a href="https://twitter.com/p0ra" target="_blank" rel="noopener noreferrer" title="Heikki Pora Twitter">Heikki&nbsp;Pora</a>, jonka sade pääsi yllättämään.</p> <p>Kartalla esitetään <a href="https://ilmatieteenlaitos.fi/avoin-data/" target="_blank" rel="noopener noreferrer" title="Ilmatieteenlaitos Avoin Data">Ilmatieteen laitoksen</a> toimittamia tietoaineistoja. Tiedot ovat kaikille avointa tietoa eli <a href="http://www.hri.fi/fi/mita-on-avoin-data/" target="_blank" rel="noopener noreferrer" title="Helsinki Region Infoshare: Mitä on avoin data?">open dataa</a>.</p> </div> </div> } collapse() { this.setState({collapsed: true}) } expand() { this.setState({collapsed: false}) } } module.exports = InfoPanel
JavaScript
0.000004
@@ -253,16 +253,27 @@ s.expand +.bind(this) %7D%3E&lt;%3C/ @@ -386,16 +386,27 @@ collapse +.bind(this) %7D%3ESulje%3C
b7e4d112e0b908e718b7cf03a8acd5369f5c8dfa
Implement prompting
src/command-line-tool.js
src/command-line-tool.js
const core = require('./core'), nodeGetoptLong = require('node-getopt-long'), P = require('bluebird'), config = require('./config') const commands = { 'list': list(), 'create': create(), 'run': run(), 'ensure-no-development-scripts': ensureNoDevelopmentScripts() } P.try(async function () { const cmdLine = parseCommandLine() if (cmdLine.options.config) { config.setupConfig(require(cmdLine.options.config)) } else { config.findAndLoadConfig() } await cmdLine.command.action(cmdLine.options) }).catch(err => { if (!err.printed) { console.error(err.stack || err) } process.exit(1) }) function parseCommandLine() { const command = process.argv[2] process.argv.splice(2, 1) let cmdImpl = commands[command] if (!cmdImpl) throw new Error('Invalid command: ' + command + '; available commands are ' + Object.keys(commands).join(', ')) const defaultOptions = [[ 'config|conf|c=s', 'Configuration file' ]] const options = nodeGetoptLong.options((cmdImpl.options || []).concat(defaultOptions), { name: 'migsi' }) return { command: cmdImpl, options } } function list() { return { options: [], action: async function (options) { const migrations = await core.loadAllMigrations() for (let migration of migrations) { console.log(migration.migsiName, migration.inDevelopment ? 'dev ' : 'prod', migration.runDate || 'to-be-run') } } } } function create() { return { options: [ ['friendlyName|n=s', 'Friendly name for migration script'], ['template|t=s', 'Template name'] ], async action({friendlyName, template = 'default'}) { if (!friendlyName) { friendlyName = await query('Friendly name') } const filename = await core.createMigrationScript(friendlyName, template) console.log('Migration script created: ' + filename) } } } function run() { return { options: [ ['production|prod|p', 'Only run production scripts'] ], action({production = false}) { return core.runMigrations(production) } } } function ensureNoDevelopmentScripts() { return { async action() { const migrations = await core.loadAllMigrations() if (migrations.any(mig => mig.inDevelopment)) { throw new Error('There are migration scripts still in develoment.') } } } } async function query(prompt) { process.stdout.write(prompt + ': ') throw new Error("TODO: implement") }
JavaScript
0.000153
@@ -131,16 +131,50 @@ config') +,%0A readline = require('readline') %0A%0Aconst @@ -2450,79 +2450,251 @@ %7B%0A -process.stdout.write(prompt + ': ')%0A throw new Error(%22TODO: implement%22)%0A%7D +const readlineImpl = readline.createInterface(%7B%0A input: process.stdin,%0A output: process.stdout%0A %7D)%0A try %7B%0A return await new Promise(resolve =%3E readlineImpl.question(prompt + ': ', resolve))%0A %7D finally %7B%0A readlineImpl.close()%0A %7D%0A%7D%0A %0A
61b0864ba829feefec7ead60e3d40fc1183efa2f
avoid showing content when show is false
src/comments/Comments.js
src/comments/Comments.js
import React, { Component, PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import CommentsList from './CommentsList'; import * as commentsActions from './commentsActions'; import { getCommentsFromState } from '../helpers/stateHelpers'; import Loading from '../widgets/Loading'; import './Comments.scss'; @connect( state => ({ comments: state.comments, auth: state.auth, }), dispatch => bindActionCreators({ getComments: commentsActions.getComments, showMoreComments: commentsActions.showMoreComments, likeComment: (id) => commentsActions.likeComment(id), unlikeComment: (id) => commentsActions.likeComment(id, 0), }, dispatch) ) export default class Comments extends Component { constructor(props) { super(props); } static propTypes = { postId: PropTypes.string.isRequired, comments: PropTypes.object, getComments: PropTypes.func, className: PropTypes.string, }; componentDidMount() { if (this.props.show) { this.props.getComments(this.props.postId); } } componentDidUpdate(prevProps) { if (this.props.show && prevProps.show !== this.props.show) { this.props.getComments(this.props.postId); } } handleShowMore = (e) => { e.stopPropagation(); this.props.showMoreComments(this.props.postId); }; render() { const { postId, comments, className } = this.props; const hasMore = (comments.lists[postId] && comments.lists[postId].hasMore); const isFetching = (comments.lists[postId] && comments.lists[postId].isFetching); const classNames = className ? `Comments ${className}` : 'Comments'; return ( <div className={classNames}> <CommentsList postId={postId} comments={comments} likeComment={this.props.likeComment} unlikeComment={this.props.unlikeComment} auth={this.props.auth} /> { isFetching && <Loading /> } { hasMore && <a className="Comments__showMore" tabIndex="0" onClick={this.handleShowMore} > See More Comments </a> } </div> ); } }
JavaScript
0.999766
@@ -1414,16 +1414,22 @@ lassName +, show %7D = thi @@ -1437,16 +1437,59 @@ .props;%0A + if (!show) %7B%0A return null;%0A %7D%0A%0A cons
bd649ef0e5215cf83f92482ec5be2b50cf6e145a
fix role not being assigned
src/manage/room/spawn.js
src/manage/room/spawn.js
/* * manage Spawn system * * handles spawning for all rooms * */ var Spawn = function() { // init }; Spawn.prototype.doRoom = function(room) { if (!room) { return -1; } let energy = room.energyAvailable; let maxEnergy = room.energyCapacityAvailable * C.SPAWN_ENERGY_MAX; if (energy < C.ENERGY_CREEP_SPAWN_MIN) { return true; } let records = _.filter(Game.Queue.spawn.getQueue(), record => (record.rooms.indexOf(room.name) >= 0 || record.rooms.length == 0) && !record.spawned ); if (records.length <= 0) { return true; } let maxAge = Game.time - Math.min.apply(null, records.tick); records = _.sortBy(records, record => 100 + record.priority - (100 * ((Game.time - record.tick) / maxAge)) ); let spawns = room.getSpawns(); if (spawns.length <= 0) { return true; } for (let s = 0; s < spawns.length; s++) { if (spawns[s].spawning) { continue; } for (let r = 0; r < records.length; r++) { if (records[r].spawned) { continue; } let spawnEnergy = energy > maxEnergy ? maxEnergy : energy; if (records[r].minSize && spawnEnergy < records[r].minSize) { continue; } let minSize = 0; if (Game.time < (records[r].tick + C.SPAWN_COST_DECAY)) { minSize = (maxEnergy - C.ENERGY_CREEP_SPAWN_MIN) - ((maxEnergy / C.SPAWN_COST_DECAY) * (Game.time - records[r].tick)); minSize = minSize >= 0 ? minSize : 0; } minSize += C.ENERGY_CREEP_SPAWN_MIN; if (minSize > spawnEnergy) { continue; } if (records[r].maxSize && spawnEnergy > records[r].maxSize) { spawnEnergy = records[r].maxSize; } let args = {}; args.spawnRoom = room.name; if (records[r].creepArgs) { for (let item in records[r].creepArgs) { args[item] = records[r].creepArgs[item]; }; } let body = Game.Manage.role.getBody(records[r].role, spawnEnergy, args); if (this.getBodyCost(body) > energy) { continue; } let name = this.doSpawn(spawns[s], body, records[r].role, args); if (name != undefined && !(name < 0)) { energy -= this.getBodyCost(body); records[r].spawned = true; records[r].name = name; if (C.DEBUG >= 1) { console.log('INFO - spawning' + ' room: <p style=\"display:inline; color: #ed4543\"><a href=\"#!/room/' + room.name + '\">' + room.name + '</a></p>' + ', role: ' + records[r].role + ', parts: ' + Game.creeps[name].body.length + ', name: ' + name); } break; } } if (energy < C.ENERGY_CREEP_SPAWN_MIN) { break; } } return true; }; /** * Spawn the creep * @param {Spawn} spawn The spawn to be used * @param {array} body The creep body * @param {Object} args Extra arguments **/ Spawn.prototype.doSpawn = function(spawn, body, role, args) { if (!spawn) { return ERR_INVALID_ARGS; } if (!Array.isArray(body) || body.length < 1) { return ERR_INVALID_ARGS; } let name = this.getName(role); return spawn.createCreep(body, name, args); }; /** * get a body for the creep * @param {array} body The creep body **/ Spawn.prototype.getBodyCost = function(body) { if (!Array.isArray(body)) { return ERR_INVALID_ARGS; } let cost = 0; for (let i = 0; i < body.length; i++) { cost += BODYPART_COST[body[i]]; } return cost; }; Spawn.prototype.getName = function(role) { let name = role.replace(/\./g, '_'); name += '_' + Math.random().toString(36).substr(2, 1); name += '_' + Game.time % 1000; return name; }; module.exports = Spawn;
JavaScript
0
@@ -1965,24 +1965,65 @@ = room.name; +%0A args.role = records%5Br%5D.role; %0A%0A @@ -2438,25 +2438,8 @@ ody, - records%5Br%5D.role, arg @@ -3331,14 +3331,8 @@ ody, - role, arg @@ -3488,16 +3488,21 @@ getName( +args. role);%0A%0A
e920b754e7134c879f726f03a1aaa7db3eb5aac6
Add method to request
src/common/api/client.js
src/common/api/client.js
import axios from 'axios'; import get from 'lodash/get'; import constants from '../../../app/constants/AppConstants'; import { getUrl, getHeaders } from './utils'; export class ApiClient { baseUrl; constructor(baseUrl) { this.baseUrl = baseUrl; } request = async ({ method, endpoint, data = {}, headers = {}, }) => { const dataOrParams = ['GET', 'DELETE'].includes(method.toUpperCase()) ? 'params' : 'data'; return axios .request({ url: getUrl(endpoint), headers: { ...getHeaders(), ...headers, }, [dataOrParams]: data, }) .then((response) => { return { data: get(response, 'data'), error: null, }; }) .catch((error) => { return { data: null, error: get(error, 'response'), }; }); }; /** * Make a GET request into the API. * @param endpoint * @param data * @param config * @returns {Promise} */ get = (endpoint, data = {}, config = {}) => { return this.request({ method: 'GET', endpoint, data, ...config, }); }; /** * Make a POST request into the API. * @param endpoint * @param data * @param config * @returns {Promise} */ post = (endpoint, data = {}, config = {}) => { return this.request({ method: 'POST', endpoint, data, ...config, }); }; /** * Make a DELETE request into the API. * @param endpoint * @param data * @param config * @returns {Promise} */ delete = (endpoint, data = {}, config = {}) => { return this.request({ method: 'DELETE', endpoint, data, ...config, }); }; /** * Make a PUT request into the API. * @param endpoint * @param data * @param config * @returns {Promise} */ put = (endpoint, data = {}, config = {}) => { return this.request({ method: 'PUT', endpoint, data, ...config, }); }; /** * Make a PATCH request into the API. * @param endpoint * @param data * @param config * @returns {Promise} */ patch = (endpoint, data = {}, config = {}) => { return this.request({ method: 'PATCH', endpoint, data, ...config, }); }; } export default new ApiClient(constants.API_URL);
JavaScript
0
@@ -470,24 +470,40 @@ .request(%7B%0A + method,%0A url:
d8c2b5b5c4ca0cbf6fc5e2703b4dd3137286a4d1
Fix post model default fields
src/common/model/post.js
src/common/model/post.js
'use strict'; /** * model */ export default class extends think.model.mongo { init(...args) { super.init(...args); this.schema = { authorId: { type: 'string', required: true }, title: { type: 'string', required: true }, content: { type: 'string' }, viewCount: { type: 'integer', default: 0 }, hide: { type: 'boolean', default: false }, createdAt: { type: 'date', default: new Date(), readonly: true }, updatedAt: { type: 'date', default: new Date() } }; this.indexes = { createdAt: -1 }; } }
JavaScript
0
@@ -401,9 +401,45 @@ lt: -0 +() =%3E %7B%0A return 0;%0A %7D %0A @@ -504,13 +504,49 @@ lt: -false +() =%3E %7B%0A return false;%0A %7D %0A
afd57893475a8d91e2f8957d70c28231d549a1cb
Use IndexLink for abakus logo
src/components/Header.js
src/components/Header.js
import '../styles/Header.css'; import React, { PropTypes, Component } from 'react'; import { Link } from 'react-router'; import { Modal } from 'react-overlays'; import cx from 'classnames'; import LoginForm from './LoginForm'; import { ButtonTriggeredDropdown } from './ui'; const Search = ({ closeSearch }) => ( <div className={cx('Search')}> <div className='Search__overlay u-container'> <div className='Search__input'> <input type='search' placeholder='Hva leter du etter?' autoFocus /> <button type='button' className='Search__closeButton' onClick={closeSearch}> <i className='fa fa-close u-scale-on-hover' /> </button> </div> <div className='Search__results'> <ul className='Search__results__items'> <li><span className='u-pill'>article</span> Hugh hefner on a roll</li> <li><span className='u-pill'>page</span> An awesome page</li> </ul> <div className='Search__results__quickLinks'> <ul> <li><a href=''>Interessegrupper</a></li> <li><a href=''>Butikk</a></li> <li><a href=''>Kontakt</a></li> </ul> </div> </div> </div> </div> ); export default class Header extends Component { static propTypes = { children: PropTypes.array, auth: PropTypes.object.isRequired, login: PropTypes.func.isRequired, logout: PropTypes.func.isRequired, search: PropTypes.object.isRequired, loggedIn: PropTypes.bool.isRequired } state = { accountOpen: false, searchOpen: false, notificationsOpen: false } render() { const { login, logout, auth, loggedIn } = this.props; return ( <header className='Header'> <div className='Header__content u-container'> <Link to='' className='Header__logo'>Abakus</Link> <div className='Header__navigation'> <Link to='/events'>Arrangementer</Link> <Link to=''>Karriere</Link> <Link to=''>README</Link> </div> <div> <ButtonTriggeredDropdown className='Header__content__button' iconName='bell' show={this.state.notificationsOpen} toggle={() => this.setState({ notificationsOpen: !this.state.notificationsOpen })} > Notifications </ButtonTriggeredDropdown> <ButtonTriggeredDropdown className='Header__content__button' iconName='user' show={this.state.accountOpen} toggle={() => this.setState({ accountOpen: !this.state.accountOpen })} > {!loggedIn && ( <LoginForm login={login} /> )} {loggedIn && ( <div> <b>{auth && auth.username}</b><br/> <a onClick={logout}>Log out</a> </div> )} </ButtonTriggeredDropdown> <button className='Header__content__button' onClick={() => this.setState({ searchOpen: !this.state.searchOpen })}> <i className='fa fa-search' /> </button> <Modal show={this.state.searchOpen} onHide={() => this.setState({ searchOpen: false })} backdropClassName='Backdrop' backdrop > <Search isOpen={this.state.searchOpen} closeSearch={() => this.setState({ searchOpen: false })} /> </Modal> </div> </div> </header> ); } }
JavaScript
0
@@ -90,16 +90,27 @@ t %7B Link +, IndexLink %7D from @@ -1795,32 +1795,37 @@ er'%3E%0A %3C +Index Link to='' class @@ -1817,16 +1817,17 @@ ink to=' +/ ' classN @@ -1853,16 +1853,21 @@ Abakus%3C/ +Index Link%3E%0A%0A
be215599108fc42ceea844229d55b80a3b6fd2eb
make brand clickable
src/components/Header.js
src/components/Header.js
import React from 'react'; import { connect } from 'react-redux'; import { Navbar, CollapsibleNav, Nav, NavItem, Glyphicon } from 'react-bootstrap'; import { PATH_COMMENT_NEW, PATH_COMMENT_LIST } from 'constants'; @connect(state => ({ dispatch: state })) export class Header extends React.Component { static propTypes = { dispatch: React.PropTypes.func, location: React.PropTypes.object } getMenus() { let output; switch (this.props.location.pathname) { case PATH_COMMENT_NEW: output = ( <NavItem eventKey={1} href={PATH_COMMENT_LIST}> <Glyphicon glyph="glyphicon glyphicon-chevron-left"/> Go Back </NavItem> ); break; default: output = ( <NavItem eventKey={1} href={PATH_COMMENT_NEW}> <Glyphicon glyph="glyphicon glyphicon-pencil"/> New comment </NavItem> ); } return output; } render () { return ( <Navbar className="myNav" brand="React-Comments" toggleNavKey={0} staticTop inverse> <CollapsibleNav eventKey={0}> <Nav navbar right> {this.getMenus()} </Nav> </CollapsibleNav> </Navbar> ); } }
JavaScript
0.000016
@@ -206,16 +206,53 @@ stants'; +%0Aimport %7B Link %7D from 'react-router'; %0A%0A@conne @@ -952,24 +952,108 @@ render () %7B%0A + const homeUrl = (%3CLink to=%22/%22%3E%3CGlyphicon glyph=%22leaf%22/%3E React-comments%3C/Link%3E);%0A return ( @@ -1095,24 +1095,17 @@ and= -%22React-Comments%22 +%7BhomeUrl%7D tog
091c854013791d331d089fc30d01b14bc3e3740b
Revert "Update Header.js"
src/components/Header.js
src/components/Header.js
import React from 'react'; import Reel from './Reel'; import particles from 'particles.js'; const Header = React.createClass({ getInitialState(){ return({ playing: false }) }, componentDidMount(){ particlesJS.load('particles-js', 'assets/particles.json'); }, togglePlay(){ this.setState({ playing: !this.state.playing }) }, render () { if(this.state.playing){ var content = ( <Reel/> ) } else { var content = ( <div className="col-md-10" style={{paddingLeft: 64}}> <p style={{fontWeight: 700, marginBottom: -8}}>Hello.</p> <p style={{fontWeight: 700, marginBottom: 48}}>My Name is Mike Johnson.</p> <p style={{fontSize: 24}}>I am a UX Engineer specializing in motion design, prototypes, and user testing.</p> </div> ) } return ( <div className="hero"> <div id="particles-js" className="particles"></div> <img src="assets/images/stack.png" style={{position: 'absolute', bottom: 16, right: 16, opacity: 0.5}}/> <div className="header-content"> {content} </div> </div> ) } }) export default Header;
JavaScript
0
@@ -750,18 +750,28 @@ am a - UX Engine +n interaction design er s @@ -791,23 +791,16 @@ n motion - design , protot
1456fa7819d1f3f49de550bdcab9e9bafe54189e
update narrow links
src/components/Header.js
src/components/Header.js
import React from 'react'; import { Link } from 'gatsby'; import PropTypes from 'prop-types'; import { SprkTextInput, SprkLink, SprkMasthead, } from '@sparkdesignsystem/spark-react'; import SiteLogo from './site-logo'; import { useInstallingSparkData } from '../hooks/use-installing-spark'; import { useUsingSparkData } from '../hooks/use-using-spark'; import { usePrincipleSparkData } from '../hooks/use-principle-spark'; const Header = ({ context, setContext }) => { const utilityItems = [ ( <SprkLink onClick={ () => { setContext('installing-spark'); } } additionalClasses="sprk-c-Masthead__link" variant="plain" element={Link} to="/installing-spark/setting-up-your-environment" > Installing Spark </SprkLink> ), ( <SprkLink onClick={ () => { setContext('using-spark'); } } additionalClasses="sprk-c-Masthead__link" variant="plain" element={Link} to="/using-spark/foundations/color" > Using Spark </SprkLink> ), ( <SprkLink onClick={ () => { setContext('principles'); } } additionalClasses="sprk-c-Masthead__link" variant="plain" element={Link} to="/principles/accessibility-guidelines" > Principles </SprkLink> ), ( <SprkTextInput additionalClasses="docs-header-search sprk-u-mbn" leadingIcon="search" hiddenLabel name="InlineSearch" placeholder="Search" /> ), ]; const installingSparkPages = useInstallingSparkData().map(page => ( { text: page.node.frontmatter.title, to: `/installing-spark/${page.node.parent.name}`, element: Link, } )); const usingSparkComponents = useUsingSparkData().components.map(page => ( { text: page.node.frontmatter.title, to: `/using-spark/${page.node.parent.name}`, element: Link, } )); const usingSparkExamples = useUsingSparkData().examples.map(page => ( { text: page.node.frontmatter.title, to: `/using-spark/${page.node.parent.name}`, element: Link, } )); const usingSparkFoundations = useUsingSparkData().foundations.map(page => ( { text: page.node.frontmatter.title, to: `/using-spark/${page.node.parent.name}`, element: Link, } )); const usingSparkPages = usingSparkComponents.concat( usingSparkComponents, usingSparkExamples, usingSparkFoundations, ); const principlePages = usePrincipleSparkData().map(page => ( { text: page.node.frontmatter.title, to: `/principles/${page.node.parent.name}`, element: Link, } )); const narrowNavLinks = [ { element: Link, text: 'Installing Spark', to: '/installing-spark/setting-up-your-environment', onClick: () => { setContext('installing-spark'); }, subNavLinks: installingSparkPages, }, { element: Link, text: 'Using Spark', to: '/using-spark/foundations/color', onClick: () => { setContext('using-spark'); }, subNavLinks: usingSparkPages, }, { element: Link, text: 'Principles', to: '/principles/accessibility-guidelines', onClick: () => { setContext('principles'); }, subNavLinks: principlePages, }, ]; return ( <SprkMasthead siteLogo={( <SiteLogo onClick={() => { setContext('homepage'); }} /> )} additionalClasses="docs-masthead" utilityContents={utilityItems} navLink={( <SprkTextInput additionalClasses="docs-header-search sprk-u-Width-100" leadingIcon="search" hiddenLabel name="InlineSearch" placeholder="Search" /> )} narrowNavLinks={narrowNavLinks} /> ); }; Header.propTypes = { context: PropTypes.string, setContext: PropTypes.func, }; export default Header;
JavaScript
0
@@ -2021,32 +2021,43 @@ : %60/using-spark/ +components/ $%7Bpage.node.pare @@ -2059,32 +2059,32 @@ .parent.name%7D%60,%0A - element: L @@ -2236,32 +2236,41 @@ : %60/using-spark/ +examples/ $%7Bpage.node.pare @@ -2431,32 +2431,32 @@ ntmatter.title,%0A - to: %60/usin @@ -2455,32 +2455,44 @@ : %60/using-spark/ +foundations/ $%7Bpage.node.pare
e6e7f942e2b38992f5834c77f257c26841d78903
Convert to react-bootstrap buttons.
src/components/Recipe.js
src/components/Recipe.js
import React from 'react'; import PropTypes from 'prop-types'; const Recipe = ({ title, ingredients, removeRecipe }) => { return ( <div className='recipe-container'> <h4>{title}</h4> <ul>{ingredients}</ul> <button onClick={() => removeRecipe(title)} className="btn btn-danger">Delete</button> </div> ); } Recipe.propTypes = { title: PropTypes.string.isRequired, ingredients: PropTypes.array.isRequired, removeRecipe: PropTypes.func.isRequired } export default Recipe;
JavaScript
0.004786
@@ -55,16 +55,58 @@ -types'; +%0Aimport %7B Button %7D from 'react-bootstrap'; %0A%0Aconst @@ -136,16 +136,32 @@ edients, + showEditRecipe, removeR @@ -289,17 +289,17 @@ %3C -b +B utton on @@ -311,22 +311,24 @@ =%7B() =%3E -remove +showEdit Recipe(t @@ -358,14 +358,98 @@ tn-d -anger%22 +efault%22%3EEdit%3C/Button%3E%0A %3CButton bsStyle=%22danger%22 onClick=%7B() =%3E removeRecipe(title)%7D %3EDel @@ -453,17 +453,17 @@ Delete%3C/ -b +B utton%3E%0A @@ -582,16 +582,61 @@ quired,%0A + showEditRecipe: PropTypes.func.isRequired,%0A remove
b69f00d221eb721987c8ee7e895c77cca37824b2
change message
src/components/Render.js
src/components/Render.js
import Block from './Block'; import BlockStyle from './Block.less'; import getChar from './Alphabet'; /** Parent Render Class */ export default class Render { constructor(element) { this.width = 20; this.height = 5; this.rows = 5; this.cols = 5; this.blocks = []; this.element = element; this.message = 'wxyz'; this.perspective = this.createPerspective(); this.renderLoop(); } createPerspective() { const perspective = document.createElement('div'); perspective.className = 'perspective'; this.element.appendChild(perspective); return perspective; } renderLoop() { const message = this.message.split('').reverse(); let holder; const size = parseInt(BlockStyle.size, 10); // Get half the size of the message to center text // const offset = (size * 5) * message.length / 2; for (let r = 0; r < message.length; r++) { holder = getChar(message[r]); // Current X for position of Character in message. size * 6 = rows + 1 // const currentX = -offset + (size * 6) * r; let counter = 0; for (let y = 0; y < this.rows; y++) { for (let x = 0; x < this.cols; x++) { if (holder[counter] === 1) { const block = new Block(counter, currentX - (x * size), (y * size), this.perspective); this.blocks.push(block); } counter ++; } } } // window.requestAnimationFrame(this.renderLoop); } }
JavaScript
0.000001
@@ -332,12 +332,21 @@ = ' -wxyz +paul j karlik ';%0A
e3a4b9dbd14336dc2232c5e813e42d12f9be278e
删除页面中iframe元素,大多情况下是广告
removeAD.js
removeAD.js
for(var i=0;i<5;i++){ setTimeout(function(){ removeAD(); },1000*i); } function removeAD(){ if(/.*\.qq\.com.*/.test(location.href)){//qq.coms $("div[bosszone='rightAD'],.l_qq_com").remove(); } //$("iframe").remove(); $("[class]").each(function(){ var classArr= this.className.split(" "); for(var i in classArr){ var name=classArr[i]; if(name&&test(name)){//判断为广告就移除 $(this).remove(); console.log("remove class:"+name); } } }) $("[id]").each(function(){ var id= this.id; if(id&&test(id)){//判断为广告就移除 $(this).remove(); console.log("remove id:"+id); } }); } function test(val){ val=$.trim(val); if(isAllow(val)){ return false; } var arr=[ "_ad$","^ad_",".*_ad_.*","-ad$","^ad-",".*-ad-.*"//一般广告 ,'sinaad.*'//新浪广告 ]; for(var i in arr){ if(new RegExp(arr[i],"i").test(val)){ return true; } } return false; } function isAllow(val){ var arr=["sina_keyword_ad_area2"]; for(var i in arr){ if( val==arr[i]){ return true; } } return false; }
JavaScript
0
@@ -201,18 +201,16 @@ ;%0A%09%7D%0A%09%0A%09 -// $(%22ifram @@ -700,17 +700,16 @@ %09 - %22_ad$%22,%22
5e17745cf13a8126c0a956c4ac5b544b0538c93b
add API function stub
src/model/LocationApi.js
src/model/LocationApi.js
'use strict'; /** * Model layer API functions for the {@link Location} class (used by * GSJS code). These functions are attached to `Location.prototype` at * server startup. * * @mixin */ var LocationApi = module.exports = function LocationApi() {}; /** * Puts the item into the location at the given position, merging it * with existing nearby items of the same class. * * @param {Item} item the item to place * @param {number} x x coordinate of the item's position * @param {number} y y coordinate of the item's position * @param {boolean} [merge] if `false`, item will **not** be merged * with other nearby items (default behavior if omitted is * to merge) */ LocationApi.prototype.apiPutItemIntoPosition = function apiPutItemIntoPosition(item, x, y, merge) { log.debug('%s.apiPutItemIntoPosition(%s, %s, %s, %s)', this, item, x, y, merge); this.addItem(item, x, y, typeof merge === 'boolean' ? !merge : false); }; LocationApi.prototype.apiGetPointOnTheClosestPlatformLineBelow = function apiGetPointOnTheClosestPlatformLineBelow(x, y) { log.debug('%s.apiGetPointOnTheClosestPlatformLineBelow(%s, %s)', this, x, y); //TODO implement&document me log.warn('TODO Location.apiGetPointOnTheClosestPlatformLineBelow not ' + 'implemented yet'); return {x: 1, y: 1}; }; LocationApi.prototype.apiGetPointOnTheClosestPlatformLineAbove = function apiGetPointOnTheClosestPlatformLineAbove(x, y) { log.debug('%s.apiGetPointOnTheClosestPlatformLineAbove(%s, %s)', this, x, y); //TODO implement&document me log.warn('TODO Location.apiGetPointOnTheClosestPlatformLineAbove not ' + 'implemented yet'); return {x: 1, y: 1}; }; /** * Sends a message to all players in this location. * * @param {object} msg the message to send */ LocationApi.prototype.apiSendMsg = function apiSendMsg(msg) { log.debug('%s.apiSendMsg', this); this.send(msg, false); }; /** * Sends a message to all players in this location (except those in the * optional exclusion parameter). * * See {@link Location#send} for details about the parameters. * * @param {object} msg the message to send * @param {object|array|string|Player} exclude exclusion parameter */ LocationApi.prototype.apiSendMsgX = function apiSendMsgX(msg, exclude) { log.debug('%s.apiSendMsgX', this); this.send(msg, false, exclude); }; /** * Sends a message to all players in this location, without adding the * 'changes' segment. * * @param {object} msg the message to send */ LocationApi.prototype.apiSendMsgAsIs = function apiSendMsgAsIs(msg) { log.debug('%s.apiSendMsgAsIs', this); this.send(msg, true); }; /** * Sends a message to all players in this location (except those in the * optional exclusion parameter), without adding the 'changes' segment. * * See {@link Location#send} for details about the parameters. * * @param {object} msg the message to send * @param {object|array|string|Player} exclude exclusion parameter */ LocationApi.prototype.apiSendMsgAsIsX = function apiSendMsgAsIsX(msg, exclude) { log.debug('%s.apiSendMsgAsIsX', this); this.send(msg, true, exclude); }; /** * Adds an announcement to the announcements queue for all players in * the location. * * @param {object} annc announcement data */ LocationApi.prototype.apiSendAnnouncement = function apiSendAnnouncement(annc) { log.debug('%s.apiSendAnnouncement', this); this.queueAnnc(annc); }; /** * Adds an announcement to the announcements queue for all players in * the location except one. * * @param {object} annc announcement data * @param {Player} [skipPlayer] announcement is **not** queued for this * player */ LocationApi.prototype.apiSendAnnouncementX = function apiSendAnnouncementX(annc, skipPlayer) { log.debug('%s.apiSendAnnouncementX', this); this.queueAnnc(annc, skipPlayer); }; /** * Initiates an inter-GS location move by removing the player from the * current location, calling various "onExit" handlers and updating the * player's `location` property with the new location. * * @param {Player} pc the player to move out * @param {Location} newLoc the target location * @param {number} x x coordinate of the player in the new location * @param {number} y y coordinate of the player in the new location */ LocationApi.prototype.apiMoveOutX = function apiMoveOutX(pc, newLoc, x, y) { log.debug('%s.apiMoveOutX(%s, %s, %s, %s)', this, pc, newLoc, x, y); pc.startMove(newLoc, x, y); }; /** * Finishes an inter-GS location move by adding the player to the list * of players in the new (this) location, and calling various "onEnter" * handlers. * * @param {Player} pc player to move in */ LocationApi.prototype.apiMoveIn = function apiMoveIn(pc) { log.debug('%s.apiMoveIn(%s)', this, pc); pc.endMove(); }; /** * Tries to acquire a lock on an item in the location for exclusive * access (e.g. for item verb processing). The lock is released * automatically at the end of the current request. * * Locking is an "expensive" operation and should only be used * where necessary. * * @param {string} path a path string pointing to an item in this * location (like "B1/B2/I3") * @returns {Item|null} the requested item, or `null` if not found or * if the lock could not be acquired */ LocationApi.prototype.apiLockStack = function apiLockStack(path) { log.trace('%s.apiLockStack(%s)', this, path); //TODO: locking return this.getPath(path); };
JavaScript
0
@@ -5426,12 +5426,275 @@ h(path);%0A%7D;%0A +%0A%0ALocationApi.prototype.apiNotifyItemStateChanged =%0A%09function apiNotifyItemStateChanged(item) %7B%0A%09log.debug('%25s.apiNotifyItemStateChanged(%25s)', this, item);%0A%09//TODO implement&document me%0A%09log.warn('TODO Location.apiNotifyItemStateChanged not implemented yet');%0A%7D;%0A
2fa869f19aea532c09e03916091baaca21b592cb
add loading icon for non-apple device
src/components/Weeper.js
src/components/Weeper.js
import React from 'react'; import Grid from '../containers/Grid'; import ControlBar from '../containers/ControlBar'; import ConfigBar from '../containers/ConfigBar'; import ConfigPanel from '../containers/ConfigPanel'; import { BlockRecord } from '../minesweeper'; import Radium from 'radium'; const style = { base: { display: "block", position: "absolute", left: "50%", top: "50%", transform: "translate(-50%, -50%)", padding: "20px 30px", boxShadow: "0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)", backgroundColor: "#FFF" }, row: { display: "flex", justifyContent: "center", alignItems: "center", flexDirection: "row", backgroundColor: "#FFF" }, loading: { position: "relative", top: 0, left: 0, right: 0, bottom: 0, height: "100%", width: "100%", filter: "blur(0px)", transition: "filter 0.5s ease-out" }, isLoading: { filter: "blur(5px)" }, loadingBackground: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, height: "100%", width: "100%" }, loadingIcon: { display: "block", fontFamily: "'AppleColorEmoji', 'Roboto', sans-serif", fontSize: "30px", textAlign: "center", position: "absolute", top: "50%", left: 0, right: 0, margin: "auto", transform: "translateY(-50%)" } }; let Row = ({ cols, row }) => ( <div style={style.row}> {new Array(cols).fill(0).map((cur, col) => { return ( <Grid key={`${row}${col}`} row={row} col={col} > </Grid> ); })} </div> ); Row = Radium(Row); let LoadingWrapper = ({ isLoading, children }) => ( <div style={[ style.loading, isLoading && style.isLoading ]}> {children} <div style={[isLoading && style.loadingBackground]}></div> </div> ); LoadingWrapper = Radium(LoadingWrapper); let LoadingIcon = ({ isLoading }) => ( <span style={style.loadingIcon}>⏳</span> ); LoadingIcon = Radium(LoadingIcon); const Weeper = ({ rows, cols, isLoading }) => ( <div style={[ style.base ]}> <LoadingWrapper isLoading={isLoading}> <ControlBar /> {new Array(rows).fill(0).map((cur, row) => ( <Row key={"row" + row} cols={cols} row={row} /> ))} <ConfigBar /> <ConfigPanel /> { isLoading && (<LoadingIcon />) } </LoadingWrapper> { isLoading && (<LoadingIcon />) } </div> ); export default Radium(Weeper);
JavaScript
0.000001
@@ -286,16 +286,61 @@ radium'; +%0Aimport hasFont from '../hasAppleColorEmoji'; %0A%0Aconst @@ -1857,16 +1857,74 @@ (%0A%09%3Cspan + className=%7BhasFont() %7C%7C %22emoji s_hourglass_flowing_sand%22%7D style=%7B
e4bca60752c777af40dd872f66a3a495c1392d84
fix to re-resolve plugins when placeholder props change, closes #601
src/components/editor.js
src/components/editor.js
import Content from './content' import Debug from 'debug' import React from 'react' import Stack from '../models/stack' import State from '../models/state' import noop from '../utils/noop' /** * Debug. * * @type {Function} */ const debug = Debug('slate:editor') /** * Event handlers to mix in to the editor. * * @type {Array} */ const EVENT_HANDLERS = [ 'onBeforeInput', 'onBlur', 'onCopy', 'onCut', 'onDrop', 'onKeyDown', 'onPaste', 'onSelect', ] /** * Plugin-related properties of the editor. * * @type {Array} */ const PLUGINS_PROPS = [ ...EVENT_HANDLERS, 'plugins', 'schema', ] /** * Editor. * * @type {Component} */ class Editor extends React.Component { /** * Property types. * * @type {Object} */ static propTypes = { className: React.PropTypes.string, onBeforeChange: React.PropTypes.func, onChange: React.PropTypes.func, onDocumentChange: React.PropTypes.func, onSelectionChange: React.PropTypes.func, placeholder: React.PropTypes.any, placeholderClassName: React.PropTypes.string, placeholderStyle: React.PropTypes.object, plugins: React.PropTypes.array, readOnly: React.PropTypes.bool, role: React.PropTypes.string, schema: React.PropTypes.object, spellCheck: React.PropTypes.bool, state: React.PropTypes.instanceOf(State).isRequired, style: React.PropTypes.object, tabIndex: React.PropTypes.number }; /** * Default properties. * * @type {Object} */ static defaultProps = { onChange: noop, onDocumentChange: noop, onSelectionChange: noop, plugins: [], readOnly: false, schema: {}, spellCheck: true }; /** * When constructed, create a new `Stack` and run `onBeforeChange`. * * @param {Object} props */ constructor(props) { super(props) this.tmp = {} this.state = {} // Create a new `Stack`, omitting the `onChange` property since that has // special significance on the editor itself. const { onChange, ...rest } = props // eslint-disable-line no-unused-vars const stack = Stack.create(rest) this.state.stack = stack // Resolve the state, running `onBeforeChange` first. const state = stack.onBeforeChange(props.state, this) this.cacheState(state) this.state.state = state // Create a bound event handler for each event. for (const method of EVENT_HANDLERS) { this[method] = (...args) => { const next = this.state.stack[method](this.state.state, this, ...args) this.onChange(next) } } } /** * When the `props` are updated, create a new `Stack` if necessary, and * run `onBeforeChange`. * * @param {Object} props */ componentWillReceiveProps = (props) => { let { stack } = this.state // If any plugin-related properties will change, create a new `Stack`. for (const prop of PLUGINS_PROPS) { if (props[prop] == this.props[prop]) continue const { onChange, ...rest } = props // eslint-disable-line no-unused-vars stack = Stack.create(rest) this.setState({ stack }) } // Resolve the state, running the before change handler of the stack. const state = stack.onBeforeChange(props.state, this) this.cacheState(state) this.setState({ state }) } /** * Cache a `state` in memory to be able to compare against it later, for * things like `onDocumentChange`. * * @param {State} state */ cacheState = (state) => { this.tmp.document = state.document this.tmp.selection = state.selection } /** * Programmatically blur the editor. */ blur = () => { const state = this.state.state .transform() .blur() .apply() this.onChange(state) } /** * Programmatically focus the editor. */ focus = () => { const state = this.state.state .transform() .focus() .apply() this.onChange(state) } /** * Get the editor's current schema. * * @return {Schema} */ getSchema = () => { return this.state.stack.schema } /** * Get the editor's current state. * * @return {State} */ getState = () => { return this.state.state } /** * When the `state` changes, pass through plugins, then bubble up. * * @param {State} state */ onChange = (state) => { if (state == this.state.state) return const { tmp, props } = this const { stack } = this.state const { onChange, onDocumentChange, onSelectionChange } = props state = stack.onChange(state, this) onChange(state) if (state.document != tmp.document) onDocumentChange(state.document, state) if (state.selection != tmp.selection) onSelectionChange(state.selection, state) this.cacheState(state) } /** * Render the editor. * * @return {Element} */ render = () => { const { props, state } = this const handlers = {} for (const property of EVENT_HANDLERS) { handlers[property] = this[property] } debug('render', { props, state }) return ( <Content {...handlers} editor={this} onChange={this.onChange} schema={this.getSchema()} state={this.getState()} className={props.className} readOnly={props.readOnly} spellCheck={props.spellCheck} style={props.style} tabIndex={props.tabIndex} role={props.role} /> ) } } /** * Mix in the property types for the event handlers. */ for (const property of EVENT_HANDLERS) { Editor.propTypes[property] = React.PropTypes.func } /** * Export. * * @type {Component} */ export default Editor
JavaScript
0
@@ -589,16 +589,81 @@ NDLERS,%0A + 'placeholder',%0A 'placeholderClassName',%0A 'placeholderStyle',%0A 'plugi
6f5a66600b80112f7694b5bcb1f2b7f6e06c3fed
add selecting
wsgi/static/js/main.js
wsgi/static/js/main.js
//main.js /*var flights = [[{dest: "Poland", price: "242", carrier: "Ryan Air"}, {dest: "Poland", price: "60", carrier: "British Airways"}, {dest: "Poland", price: "260", carrier: "Joe's Hardware"}], [ {dest: "Bristol", price: "160", carrier: "British Airways"}, {dest: "Bristol", price: "20", carrier: "Joe's Hardware"}]]; */ var flights; var ready = false; //get flight data $.get( "/top_flights", function( data ) { flights = JSON.parse(data); populate_data(); }); $(document).ready( function () { $('#chooser a').click(function (e) { e.preventDefault(); $(this).tab('show'); if(!$("#tab-main").hasClass("active")){ $("#tab-main").removeClass("hide");} else { $("#tab-main").addClass("hide"); } if(!$("#tab-friends").hasClass("active")){ $("#tab-friends").removeClass("hide");} else { $("#tab-friends").addClass("hide"); } }); $(".btn-modal").on("click", function () { //set modal to loading! if(ready) { reset_modal(); $('#myModal').modal('toggle'); //populate the modal here!!! populate_modal($(this).attr("location")); } }); $('#search').on("keyup", function () { var q = $('#search').val(); $(".friend-name").each(function () { if ($(this).text().toLowerCase().indexOf(q.toLowerCase()) != -1) { $(this).parent().parent().show(); } else { $(this).parent().parent().hide(); } }); }); }); function reset_modal() { //resets the modal to a loading screen $("#modalTitle").text("Loading..."); $("#flight-data tr").remove(); $("#flight-data").html("<tr><th>Date</th><th>Agent</th><th>Fly Now!</th></tr>"); } function populate_modal(city_id) { //this gets all relevant data for the modal var data = flights[city_id]; $("#modalTitle").text(data.name[0]+", "+data.name[1]+", "+data.name[2]); $("#skyscanner-url").attr('href', flights[city_id]['url']); $("#flight-data tr:last").after(prepare_flight(data.cheapest_quote)); data.quotes.forEach(function (entry) { $("#flight-data tr:last").after(prepare_flight(entry)); }); $(".date-tooltip").tooltip(); } function populate_data() { ready = true; $("#Loading-Content").addClass("hidden"); $("#first-location h1").html(flights[0].name[1] + "<br />&pound;"+flights[0].cheapest_quote.MinPrice); $("#first-location p").html("Go and see <em>"+flights[0].friends[0].name+", "+flights[0].friends[1].name+"</em> and "+(flights[0].friends.length - 2)+" others in "+flights[0].name[1]+", "+flights[0].name[2]); $("#first-location button").attr("location", 0); $("#first-location").removeClass("hidden"); $("#second-location h1").html(flights[1].name[1] + "<br />&pound;"+flights[1].cheapest_quote.MinPrice); $("#second-location p").html("You have <em>"+flights[1].friends.length+"</em> friends near "+flights[1].name[1]+", including <em>"+flights[1].friends[0].name+"</em>"); $("#second-location button").attr("location", 1); $("#second-location").removeClass("hidden"); $("#third-location h1").html(flights[2].name[1] + "<br />&pound;"+flights[2].cheapest_quote.MinPrice); $("#third-location p").html("Flights available to go and see <em>"+flights[2].friends[0].name+"</em> and "+(flights[2].friends.length -1)+" others in "+flights[2].name[1]); $("#third-location button").attr("location", 2); $("#third-location").removeClass("hidden"); } function prepare_flight(dest) { var date = moment(dest.InboundLeg.DepartureDate).format('ll'); var rel_date = moment(dest.InboundLeg.DepartureDate).fromNow(); //add a 'time until' event using .fromNow() as a tooltip var r = "<tr>"; r += "<td class='date'><div class='date-tooltip' data-toggle='tooltip' data-placement='auto left' title='"+rel_date+"'></div>"+date+"</td>"; r += "<td class='carrier'>"+dest.InboundLeg.Carrier+"</td>"; r += "<td class='price'><button class='btn btn-success'>&pound;"+dest.MinPrice+"</button></td>"; r += "</tr>"; return r; }
JavaScript
0
@@ -1221,24 +1221,118 @@ %7D%0A %7D);%0A%0A + $(%22.friendlist tr%22).on(%22click%22, function() %7B%0A $(this).toggleClass(%22active%22);%0A %7D%0A $('#sear
023dbf44d6403d78ff97b7a12606652bae7eacfa
add comments to special handling
src/Main/ProgressBar.js
src/Main/ProgressBar.js
import React from 'react'; import PropTypes from 'prop-types'; const BACKGROUND_COLOR = '#fff'; const FILL_COLOR = '#fb6d35'; const FULL_FILL_COLOR = '#1d9c07'; const ProgressBar = props => { const { width, height, percentage } = props; const wrapperWidth = width + 2 * height; const fillColor = percentage === 100 ? FULL_FILL_COLOR : FILL_COLOR; return ( <svg className="ProgressBar" width={wrapperWidth} > <path strokeWidth={height} stroke={BACKGROUND_COLOR} strokeLinejoin="round" strokeLinecap="round" fill="none" d={`M${height} ${height / 2} h 0 ${width}`} /> {!!percentage && <path strokeWidth={height} stroke={fillColor} strokeLinejoin="round" strokeLinecap="round" fill="none" d={`M${height} ${height / 2} h 0 ${width * percentage / 100}`} /> } </svg> ); }; ProgressBar.propTypes = { width: PropTypes.number, height: PropTypes.number, percentage: PropTypes.number, }; ProgressBar.defaultProps = { width: 150, height: 3, percentage: 0, }; export default ProgressBar;
JavaScript
0
@@ -234,16 +234,205 @@ props;%0A + // We use round stroke so there is additional width created by the border radius.%0A // Add the height(radius of the bar) to the wrapper's width to make sure the bars presented correctly.%0A const
bdf75ef0932f136278e22159a33c935e2017edf1
Remove people that left
config.notifications.js
config.notifications.js
'use strict' module.exports = [ { user: '@michal.brasna', services: ['tankovna', 'lokal-hamburk', 'globus'] }, { user: '@jan.pavlovsky', services: ['peters', 'meat-market', 'globus', 'u-sani', 'lokal-hamburk'] }, { user: '@ottokovarik', services: ['tankovna', 'lokal-hamburk', 'globus'] }, { user: '@radim', services: ['tankovna', 'lokal-hamburk', 'u-zabranskych'] }, { user: '@tomas.pokorny', services: ['tankovna', 'lokal-hamburk'] }, { user: '@radek.carda', services: ['peters', 'globus', 'meat-market', 'lokal-hamburk', 'u-zabranskych'] }, { user: '@zdenek.cejka', services: ['peters', 'tankovna', 'u-sani', 'meat-market', 'globus'] }, { user: '@mafo', services: ['tankovna', 'lokal-hamburk', 'globus'] }, { user: '@martin.kadlec', services: ['tankovna', 'lokal-hamburk', 'globus'] }, { user: '@adamsobotka', services: ['tankovna', 'lokal-hamburk', 'meat-market', 'globus'] }, { user: '@tomasbauer', services: ['tankovna', 'lokal-hamburk', 'globus'] }, { user: '@navratj', services: ['tankovna', 'lokal-hamburk', 'u-zabranskych'] }, { user: '@snajby', services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych'] }, { user: '@milanlepik', services: ['peters', 'tankovna', 'u-sani', 'meat-market', 'lokal-hamburk', 'globus'] }, { user: '@vaclavhosticka', services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych'] }, { user: '@ango', services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-sani', 'u-tunelu'] }, { user: '@ondram', services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-sani', 'u-tunelu'] } ]
JavaScript
0
@@ -911,268 +911,72 @@ : '@ -adamsobotka',%0A services: %5B'tankovna', 'lokal-hamburk', 'meat-market', 'globus'%5D%0A %7D,%0A %7B%0A user: '@tomasbauer',%0A services: %5B'tankovna', 'lokal-hamburk', 'globus'%5D%0A %7D,%0A %7B%0A user: '@navratj',%0A services: %5B'tankovna', 'lokal-hamburk', 'u-zabranskych +tomasbauer',%0A services: %5B'tankovna', 'lokal-hamburk', 'globus '%5D%0A
7bb941bfc106c9fd6501c963f6c8851f3c45e21d
add new build
jquery.instagram.min.js
jquery.instagram.min.js
(function($){"use strict";$.fn.instagram=function(options){var $this=this,settings={tag:null,client_id:null,proxy:null,display:5};for(var key in settings)options.hasOwnProperty(key)&&options[key]!==void 0&&(settings[key]=options[key]);$.ajax({url:settings.proxy,type:"GET",data:{client_id:settings.client_id,tag:settings.tag},success:function(data){for(var hits=data.data,images=[],i=0;hits.length>i;i++){var hit=hits[i];images.push({thumb:hit.images.thumbnail.url,full:hit.images.standard_resolution.url,text:hit.caption.text,created:parseInt(hit.created_time),filter:hit.filter,likes:hit.likes.count,name:hit.user.full_name})}images.sort(function(a,b){return b.created-a.created}),images=images.slice(0,settings.display),console.log(images);for(var i=0;images.length>i;i++){var image=images[i];$this.append('<img src="'+image.thumb+'" title="'+image.text+'" onclick="window.open(\''+image.full+"')\" />")}},error:function(){console.error("instagram: failed to load.")}})}})(jQuery);
JavaScript
0
@@ -266,16 +266,32 @@ e:%22GET%22, +dataType:%22json%22, data:%7Bcl @@ -358,16 +358,34 @@ n(data)%7B +console.log(data); for(var
4dea9ba580380ad33ea8521c8335e42d15451901
Remove redundant ref causing crash in React 16.1 (#643)
src/MessageContainer.js
src/MessageContainer.js
/* eslint no-console: 0, no-param-reassign: 0, no-use-before-define: ["error", { "variables": false }], no-return-assign: 0, react/no-string-refs: 0 */ import PropTypes from 'prop-types'; import React from 'react'; import { ListView, View, StyleSheet } from 'react-native'; import shallowequal from 'shallowequal'; import InvertibleScrollView from 'react-native-invertible-scroll-view'; import md5 from 'md5'; import LoadEarlier from './LoadEarlier'; import Message from './Message'; export default class MessageContainer extends React.Component { constructor(props) { super(props); this.renderRow = this.renderRow.bind(this); this.renderFooter = this.renderFooter.bind(this); this.renderLoadEarlier = this.renderLoadEarlier.bind(this); this.renderScrollComponent = this.renderScrollComponent.bind(this); const dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => { return r1.hash !== r2.hash; }, }); const messagesData = this.prepareMessages(props.messages); this.state = { dataSource: dataSource.cloneWithRows(messagesData.blob, messagesData.keys), }; } componentWillReceiveProps(nextProps) { if (this.props.messages === nextProps.messages) { return; } const messagesData = this.prepareMessages(nextProps.messages); this.setState({ dataSource: this.state.dataSource.cloneWithRows(messagesData.blob, messagesData.keys), }); } shouldComponentUpdate(nextProps, nextState) { if (!shallowequal(this.props, nextProps)) { return true; } if (!shallowequal(this.state, nextState)) { return true; } return false; } prepareMessages(messages) { return { keys: messages.map((m) => m._id), blob: messages.reduce((o, m, i) => { const previousMessage = messages[i + 1] || {}; const nextMessage = messages[i - 1] || {}; // add next and previous messages to hash to ensure updates const toHash = JSON.stringify(m) + previousMessage._id + nextMessage._id; o[m._id] = { ...m, previousMessage, nextMessage, hash: md5(toHash), }; return o; }, {}), }; } scrollTo(options) { this._invertibleScrollViewRef.scrollTo(options); } renderLoadEarlier() { if (this.props.loadEarlier === true) { const loadEarlierProps = { ...this.props, }; if (this.props.renderLoadEarlier) { return this.props.renderLoadEarlier(loadEarlierProps); } return <LoadEarlier {...loadEarlierProps} />; } return null; } renderFooter() { if (this.props.renderFooter) { const footerProps = { ...this.props, }; return this.props.renderFooter(footerProps); } return null; } renderRow(message) { if (!message._id && message._id !== 0) { console.warn('GiftedChat: `_id` is missing for message', JSON.stringify(message)); } if (!message.user) { if (!message.system) { console.warn('GiftedChat: `user` is missing for message', JSON.stringify(message)); } message.user = {}; } const messageProps = { ...this.props, key: message._id, currentMessage: message, previousMessage: message.previousMessage, nextMessage: message.nextMessage, position: message.user._id === this.props.user._id ? 'right' : 'left', }; if (this.props.renderMessage) { return this.props.renderMessage(messageProps); } return <Message {...messageProps} />; } renderScrollComponent(props) { const { invertibleScrollViewProps } = this.props; return ( <InvertibleScrollView {...props} {...invertibleScrollViewProps} ref={(component) => (this._invertibleScrollViewRef = component)} /> ); } render() { const contentContainerStyle = this.props.inverted ? {} : styles.notInvertedContentContainerStyle; return ( <View ref="container" style={styles.container}> <ListView enableEmptySections automaticallyAdjustContentInsets={false} initialListSize={20} pageSize={20} {...this.props.listViewProps} dataSource={this.state.dataSource} contentContainerStyle={contentContainerStyle} renderRow={this.renderRow} renderHeader={this.props.inverted ? this.renderFooter : this.renderLoadEarlier} renderFooter={this.props.inverted ? this.renderLoadEarlier : this.renderFooter} renderScrollComponent={this.renderScrollComponent} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, notInvertedContentContainerStyle: { justifyContent: 'flex-end', }, }); MessageContainer.defaultProps = { messages: [], user: {}, renderFooter: null, renderMessage: null, onLoadEarlier: () => { }, inverted: true, loadEarlier: false, listViewProps: {}, invertibleScrollViewProps: {}, }; MessageContainer.propTypes = { messages: PropTypes.arrayOf(PropTypes.object), user: PropTypes.object, renderFooter: PropTypes.func, renderMessage: PropTypes.func, renderLoadEarlier: PropTypes.func, onLoadEarlier: PropTypes.func, listViewProps: PropTypes.object, inverted: PropTypes.bool, loadEarlier: PropTypes.bool, invertibleScrollViewProps: PropTypes.object, };
JavaScript
0
@@ -4040,24 +4040,8 @@ View - ref=%22container%22 sty
be890bdcdb55c225f29a0d57ffa40d47b71ed90f
fix again
www/js/impl/Content.js
www/js/impl/Content.js
var Content = function(jQueryL18n, cda){ this.jQueryL18n = jQueryL18n; this.cda = cda; }; Content.prototype = Object.create(IContent); Content.prototype.initializeL18n = function(lang) { this.jQueryL18n.properties(lang); }; Content.prototype.loadMessages = function(withinDivId) { var j = this.jQueryL18n; $(withinDivId + " div[id^='msg_']").each(function() { $div = $(this); // get pure id of message key, assuming that every key has a corresponding div var id_string = "msg_"+this.id.match(/^msg_c_([a-zA-Z0-9_]*)/).slice(1)[0]; $div.text(j.getMsg(id_string)); }); }; Content.prototype.loadContent = function(path) { this.loadIntoSection(path, "#content"); }; Content.prototype.loadHeader = function(path) { this.loadIntoSection(path, "#header"); }; Content.prototype.loadFooter = function(path) { this.loadIntoSection(path, "#footer"); }; Content.prototype.loadIntoSection = function(path, withinDivId) { var instance = this; $(withinDivId).load(path, '', function() { instance.loadMessages(withinDivId); $(document).foundation(); if (typeof instance.cda !== "undefined") { instance.cda.setOnClickEvent(withinDivId, this); } }); };
JavaScript
0
@@ -1151,20 +1151,24 @@ nDivId, -this +instance );%0A%09%09%7D%0A%09
3c862e8187b93e4ec4e358b77d97527db7dfa64f
Clean view.js
core/view.js
core/view.js
"use strict"; // Работа с канвой, отрисовкой и масштабированием function View(canvas, fast) { this.scale = 1.0; this.offsetX = 0.0; this.offsetY = 0.0; this.canvas = fast ? fast : canvas; var ctx = canvas.getContext('2d'), fctx = fast.getContext('2d'); /*var h = canvas.clientHeight, w = canvas.clientWidth; canvas.height = h; canvas.width = w; fast.height = h; fast.width = w;*/ var v = this; v.onresize = function(state) { var h = canvas.clientHeight, w = canvas.clientWidth; canvas.height = h; canvas.width = w; if(fast) {fast.height = h; fast.width = w;} ctx.setTransform(v.scale, 0, 0, v.scale, v.offsetX, v.offsetY); fctx.setTransform(v.scale, 0, 0, v.scale, v.offsetX, v.offsetY); v.needRedraw = true; v.commit(state); }; v.seq = []; v.needRedraw = true; /*v.insert = function(what, after, before) { if(after) for(var x in seq) if(seq[x] === after) { seq.splice(x + 1, 0, what); return;} if(before) for(var x in seq) if(seq[x] === before) { seq.splice(x, 0, what); return;} seq.push(what); }*/ var needClear = false; v.commit = function(state) { if(needClear) fctx.clearRect(-v.offsetX / v.scale, -v.offsetY / v.scale, canvas.width / v.scale, canvas.height / v.scale); if(state.draw) { state.draw(fctx); needClear = true; } if(v.needRedraw) { var seq = v.seq; for(var x in seq) seq[x](ctx); v.needRedraw = false; } } v.clear = function clear(ctx) { ctx.clearRect(-v.offsetX / v.scale, -v.offsetY / v.scale, canvas.width / v.scale, canvas.height / v.scale); }; //v.insert(v.clear); //v.insert(v.draw); v.transform = function() { ctx.setTransform(v.scale, 0, 0, v.scale, v.offsetX, v.offsetY); fctx.setTransform(v.scale, 0, 0, v.scale, v.offsetX, v.offsetY); v.needRedraw = true; }; }
JavaScript
0.000001
@@ -91,20 +91,35 @@ )%0A%7B%0A -this +var v = this;%0A v .scale = @@ -124,28 +124,25 @@ = 1.0;%0A -this +v .offsetX = 0 @@ -149,20 +149,17 @@ .0;%0A -this +v .offsetY @@ -171,20 +171,17 @@ 0;%0A%0A -this +v .canvas @@ -277,174 +277,8 @@ ');%0A - /*var h = canvas.clientHeight, w = canvas.clientWidth;%0A canvas.height = h;%0A canvas.width = w;%0A fast.height = h; %0A fast.width = w;*/%0A var v = this;%0A @@ -1629,57 +1629,8 @@ %7D;%0A - //v.insert(v.clear);%0A //v.insert(v.draw);%0A @@ -1842,8 +1842,9 @@ %7D;%0A%7D +%0A
5fe313014b3155a3d9e2df01e165c92d06c8d5b5
Hide time if type of input is date
src/components/Input.js
src/components/Input.js
import _ from 'lodash' // eslint-disable-line import React, {PropTypes} from 'react' import warning from 'warning' import ReactDatetime from 'react-datetime' import Inflection from 'inflection' import ReactQuill from 'react-quill' import Select from 'react-select' import {FormGroup, Checkbox, ControlLabel, FormControl, HelpBlock} from 'react-bootstrap' import S3Uploader from './S3Uploader' import {validationHelp, validationState} from '../validation' function ensureArray(values) { if (_.isArray(values)) return values if (!values) return [] if (_.isString(values)) return values.split(',') warning(false, `[fl-react-utils] Input: react-select gave a strange value: ${JSON.stringify(values)}`) return [] } export default class Input extends React.Component { static propTypes = { label: PropTypes.string, helpTop: PropTypes.bool, help: PropTypes.string, defaultHelp: PropTypes.string, type: PropTypes.string, bsProps: PropTypes.object, meta: PropTypes.object, input: PropTypes.object, inputProps: PropTypes.object, options: PropTypes.oneOfType([ PropTypes.array, PropTypes.object, ]), value: PropTypes.any, includeEmpty: PropTypes.bool, onBlur: PropTypes.func, quillTheme: PropTypes.string, quillFormat: PropTypes.array, } static defaultProps = { type: 'text', quillTheme: 'snow', quillFormat: [ 'bold', 'italic', 'strike', 'underline', 'font', 'size', 'bullet', 'list', 'link', 'align', ], } render() { const {label, meta, helpTop, type, bsProps} = this.props const inputProps = _.extend({ autoComplete: 'on', }, this.props.input, this.props.inputProps) let help = this.props.help if (_.isUndefined(help)) { help = validationHelp(meta) || this.props.defaultHelp } const id = Inflection.dasherize((label || '').toLowerCase()) let feedback = true let hideLabel = false let control switch (type) { case 'rich': case 'rich-text': case 'quill': control = (<ReactQuill theme={this.props.quillTheme} format={this.props.quillFormat} {...inputProps} />) break case 'date': case 'datetime': const placeholder = type === 'date' ? 'DD/MM/YYYY' : 'DD/MM/YYYY 9:00 AM' control = (<ReactDatetime closeOnSelect inputProps={{placeholder}} {..._.omit(inputProps, 'onFocus')} />) break case 'select': if (!this.props.options) { warning(false, 'select components require an options prop') return null } control = ( <FormControl componentClass="select" {...inputProps} value={inputProps.value}> {this.props.includeEmpty && (<option />)} {_.map(this.props.options, option => ( <option key={option.value} value={option.value}>{option.label}</option> ))} </FormControl> ) break case 'react-select': if (!this.props.options) { warning(false, 'react-select components require an options prop') return null } const {onChange, onBlur, value, ...props} = inputProps feedback = false const stringValue = _.isArray(value) ? value.join(',') : value const funcs = {} if (onChange) funcs.onChange = value => onChange(inputProps.multi ? ensureArray(value) : value) if (onBlur) funcs.onBlur = () => onBlur(inputProps.multi ? ensureArray(value) : value) control = ( <Select options={this.props.options} value={stringValue} {...funcs} {...props} /> ) break case 'image': case 'file': control = ( <S3Uploader inputProps={inputProps} /> ) break case 'static': control = ( <FormControl.Static {...bsProps} {...inputProps}>{inputProps.value}</FormControl.Static> ) break case 'checkbox': case 'boolean': inputProps.checked = !!inputProps.value hideLabel = true control = ( <Checkbox inline {...bsProps} {...inputProps}>{label}</Checkbox> ) break case 'textarea': control = ( <FormControl componentClass="textarea" {...bsProps} {...inputProps} /> ) break // case 'text': // case 'email': // case 'password': default: control = ( <FormControl type={type} {...bsProps} {...inputProps} /> ) } return ( <FormGroup controlId={id} validationState={validationState(meta)}> {label && !hideLabel && <ControlLabel>{label}</ControlLabel>} {help && helpTop && (<HelpBlock>{help}</HelpBlock>)} {control} {feedback && <FormControl.Feedback />} {help && !helpTop && (<HelpBlock>{help}</HelpBlock>)} </FormGroup> ) } }
JavaScript
0.999847
@@ -2345,16 +2345,75 @@ :00 AM'%0A + if (type === 'date') inputProps.timeFormat = false%0A
ee5916cf447c9134d9080e006540e70fee051f54
add m.ls.copy menu
src/pages/debug/index.js
src/pages/debug/index.js
console.log('__DEBUG_MODE__') const menu = require('chrome-console-debug-menu') const { resetLocalStorage, serializeLocalStorage } = menu global.m = menu.create('m', { ls: { description: 'localStorage controls', methods: { clear: { description: 'Clear localStorage', func () { return resetLocalStorage({ message: 'Clearing localStorage' }) } }, dump: { description: 'dump the data as JSON', func (message) { return serializeLocalStorage(message) } }, preset0: { description: 'Sets localStorage in a typical state', func () { return resetLocalStorage(require('./preset0')) } } } } })
JavaScript
0
@@ -1,12 +1,31 @@ +/* global copy */%0A%0A console.log( @@ -563,24 +563,187 @@ %7D%0A %7D,%0A + copy: %7B%0A description: 'copy the data to clipboard',%0A func (message) %7B%0A return copy(serializeLocalStorage(message))%0A %7D%0A %7D,%0A preset
5b321f903b7d32bf0fef4516bfc033450dfa6693
remove incorrect margin styling
src/components/styles.js
src/components/styles.js
export var styles = { errorBox: { fontFamily: "sans-serif", border: 1, borderColor: "#FF3131", borderStyle: "dashed", padding: 3, borderRadius: 3, background: "#FFF2F2", position: "relative", top: 8, left: 6, }, logos: { container: { display: "flex", height: "inherit", }, toolbar: { height: "80%", alignSelf: "center", paddingLeft: 15, paddingRight: 15, }, }, spinners: { toolbar: { height: 30, }, window: { paddingTop: 110, paddingBottom: 80, height: 50, width: "auto", margin: "auto", display: "flex", }, }, toolbar: { base: { display: "flex", justifyContent: "space-between", backgroundColor: "#C0C0C0", height: 40, }, tools: { height: "inherit", display: "flex", justifyContent: "flex-start", }, controls: { height: "inherit", display: "flex", justifyContent: "flex-end", }, }, forms: { width: 194, }, buttons: { base: { display: "flex", justifyContent: "space-around", alignItems: "center", width: 150, border: "none", fontSize:"15px", fontFamily: "sans-serif", color: "white", marginLeft: 3, }, toolbar: { width: 120, backgroundColor: "gray", }, run: { waiting: { backgroundColor: "#317BCF" }, running: { color: "gray", }, }, stop: { stopping: { backgroundColor: "#FF0000", color: "white", }, waiting: { color: "gray", }, }, more: { moreButton:{ height: 40, position: "absolute", marginLeft: 3, justifyContent: "center", }, menuContainer: { display: "flex", flexDirection: "column", position: "absolute", marginTop: 40, marginLeft: 3, zIndex: 1, }, menuItems: { height: 40, color: "black", backgroundColor: "#EFEFEF", textDecoration: "none", }, }, googleDrive: { float: "left", width: 194, backgroundColor: "gray" }, }, linkStyle: { textDecoration: "none", color: "black", }, };
JavaScript
0.000002
@@ -1289,37 +1289,16 @@ white%22,%0A - marginLeft: 3,%0A %7D,%0A
8837537a804a9b3740c546b5bbe990e4e2d816ee
rename heatCoolSlider to slider, https://github.com/phetsims/scenery-phet/issues/442
js/HeaterCoolerFront.js
js/HeaterCoolerFront.js
// Copyright 2015-2018, University of Colorado Boulder /** * Front of the HeaterCoolerNode. It is independent from the HeaterCoolerBack so that one can easily layer objects * inside of the HeaterCoolerNode. The HeaterCoolerFront contains the heater body, labels, and control slider. * * @author Siddhartha Chinthapally (Actual Concepts) on 20-11-2014. * @author Jesse Greenberg * */ define( require => { 'use strict'; // modules const Color = require( 'SCENERY/util/Color' ); const Dimension2 = require( 'DOT/Dimension2' ); const HeaterCoolerBack = require( 'SCENERY_PHET/HeaterCoolerBack' ); const LinearGradient = require( 'SCENERY/util/LinearGradient' ); const Node = require( 'SCENERY/nodes/Node' ); const Path = require( 'SCENERY/nodes/Path' ); const PhetFont = require( 'SCENERY_PHET/PhetFont' ); const Range = require( 'DOT/Range' ); const sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' ); const Shape = require( 'KITE/Shape' ); const Tandem = require( 'TANDEM/Tandem' ); const Text = require( 'SCENERY/nodes/Text' ); const VSlider = require( 'SUN/VSlider' ); // strings const coolString = require( 'string!SCENERY_PHET/cool' ); const heatString = require( 'string!SCENERY_PHET/heat' ); // constants const DEFAULT_WIDTH = 120; // in screen coords, much of the rest of the size of the stove derives from this value class HeaterCoolerFront extends Node { /** * * @param {NumberProperty} [heatCoolAmountProperty] // +1 for max heating, -1 for max cooling * @param {Object} [options] that can be passed on to the underlying node * @constructor */ constructor( heatCoolAmountProperty, options ) { super(); Tandem.indicateUninstrumentedCode(); options = _.extend( { baseColor: new Color( 159, 182, 205 ), // Base color used for the stove body. width: 120, // In screen coords, much of the rest of the size of the stove derives from this value. snapToZero: true, // controls whether the slider will snap to the off. heatEnabled: true, // Allows slider to reach positive values (corresponding to heating) coolEnabled: true, // Allows slider to reach negative values (corresponding to cooling) // slider label options heatLabel: heatString, coolLabel: coolString, labelFont: new PhetFont( 14 ), labelMaxWidth: null, // slider options thumbSize: new Dimension2( 22, 45 ), thumbTouchAreaXDilation: 11, thumbTouchAreaYDilation: 11, thumbMouseAreaXDilation: 0, thumbMouseAreaYDilation: 0, thumbFillEnabled: '#71edff', // {Color|string|null} thumbFillHighlighted: '#bff7ff' // {Color|string|null} }, options ); // Dimensions for the rest of the stove, dependent on the specified stove width. Empirically determined, and could // be made into options if needed. const height = DEFAULT_WIDTH * 0.75; const burnerOpeningHeight = DEFAULT_WIDTH * HeaterCoolerBack.OPENING_HEIGHT_SCALE; const bottomWidth = DEFAULT_WIDTH * 0.80; // Create the body of the stove. const stoveBodyShape = new Shape() .ellipticalArc( DEFAULT_WIDTH / 2, burnerOpeningHeight / 4, DEFAULT_WIDTH / 2, burnerOpeningHeight / 2, 0, 0, Math.PI, false ) .lineTo( ( DEFAULT_WIDTH - bottomWidth ) / 2, height + burnerOpeningHeight / 2 ) .ellipticalArc( DEFAULT_WIDTH / 2, height + burnerOpeningHeight / 4, bottomWidth / 2, burnerOpeningHeight, 0, Math.PI, 0, true ).lineTo( DEFAULT_WIDTH, burnerOpeningHeight / 2 ); const stoveBody = new Path( stoveBodyShape, { stroke: 'black', fill: new LinearGradient( 0, 0, DEFAULT_WIDTH, 0 ) .addColorStop( 0, options.baseColor.brighterColor( 0.5 ) ) .addColorStop( 1, options.baseColor.darkerColor( 0.5 ) ) } ); // Create the label strings and scale them to support translations. const titleOptions = { font: options.labelFont, maxWidth: options.labelMaxWidth }; const heatTitle = new Text( options.heatLabel, titleOptions ); const coolTitle = new Text( options.coolLabel, titleOptions ); const titles = [ heatTitle, coolTitle ]; // Scale the titles to fit within the bucket front if necessary. const maxTitleWidth = Math.max( coolTitle.width, heatTitle.width ); if ( maxTitleWidth > bottomWidth / 2 ) { titles.forEach( function( title ) { title.scale( ( bottomWidth / 2 ) / maxTitleWidth ); } ); } // Create the slider. assert && assert( ( options.coolEnabled || options.heatEnabled ), 'Either heating or cooling must be enabled.' ); // @protected this.heatCoolSlider = new VSlider( heatCoolAmountProperty, new Range( options.coolEnabled ? -1 : 0, options.heatEnabled ? 1 : 0 ), { trackSize: new Dimension2( DEFAULT_WIDTH / 2, 10 ), trackFillEnabled: new LinearGradient( 0, 0, DEFAULT_WIDTH / 2, 0 ) .addColorStop( 0, '#0A00F0' ) .addColorStop( 1, '#EF000F' ), thumbSize: options.thumbSize, thumbLineWidth: 1.4, thumbTouchAreaXDilation: options.thumbTouchAreaXDilation, thumbTouchAreaYDilation: options.thumbTouchAreaYDilation, thumbMouseAreaXDilation: options.thumbMouseAreaXDilation, thumbMouseAreaYDilation: options.thumbMouseAreaYDilation, thumbFillEnabled: options.thumbFillEnabled, thumbFillHighlighted: options.thumbFillHighlighted, thumbCenterLineStroke: 'black', majorTickLength: 15, minorTickLength: 12, centerY: stoveBody.centerY, right: stoveBody.right - DEFAULT_WIDTH / 8, endDrag: function() { if ( options.snapToZero ) { heatCoolAmountProperty.set( 0 ); } } } ); if ( options.heatEnabled ) { this.heatCoolSlider.addMajorTick( 1, heatTitle ); } this.heatCoolSlider.addMinorTick( 0 ); if ( options.coolEnabled ) { this.heatCoolSlider.addMajorTick( -1, coolTitle ); } this.addChild( stoveBody ); this.addChild( this.heatCoolSlider ); this.mutate( options ); } } return sceneryPhet.register( 'HeaterCoolerFront', HeaterCoolerFront ); } );
JavaScript
0
@@ -4737,33 +4737,25 @@ %0A this. -heatCoolS +s lider = new @@ -5942,33 +5942,25 @@ ed ) %7B this. -heatCoolS +s lider.addMaj @@ -5992,33 +5992,25 @@ %0A this. -heatCoolS +s lider.addMin @@ -6058,33 +6058,25 @@ ed ) %7B this. -heatCoolS +s lider.addMaj @@ -6167,17 +6167,9 @@ his. -heatCoolS +s lide
edf23fc243cb89c11326008bc48298cd60ad3f5d
make selectRange undefined when clicking out of it
src/components/Score.js
src/components/Score.js
import React, { Component } from 'react'; import shouldPureComponentUpdate from 'react-pure-render/function'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { setSelectRange } from '../actions/cursor'; import { scoreSelector } from '../util/selectors'; import Measure from './measure/Measure'; import SelectBox from './SelectBox'; const SVG_TOP = 50; const NOTE_WIDTH = 10; // Give some room for user error when selecting a range of notes const SELECT_ERROR = 3; const style = { top: 0, marginLeft: 5, display: 'flex', flexWrap: 'wrap', flex: 1 }; class Score extends Component { shouldComponentUpdate = shouldPureComponentUpdate; constructor(props) { super(props); this.state = { dragStart: undefined, dragEnd: undefined }; } getNoteRangeForMeasure = (measure, xStart, xEnd) => { const notes = measure.notes.map((note, i) => { const noteX = note.x + measure.xOfMeasure; return noteX + SELECT_ERROR - NOTE_WIDTH > xStart && noteX - SELECT_ERROR < xEnd ? i : null; }); return notes.filter(note => note !== null); }; getSelectedRangeForSingleRow = (measure, xStart, xEnd) => { if(xStart > measure.xOfMeasure && xEnd < measure.xOfMeasure + measure.width) { return this.getNoteRangeForMeasure(measure, xStart, xEnd); } else if((xStart < measure.xOfMeasure && xEnd > measure.xOfMeasure) || (xStart > measure.xOfMeasure && xStart < measure.xOfMeasure + measure.width)) { if(measure.xOfMeasure < xStart) { return this.getNoteRangeForMeasure(measure, xStart, measure.xOfMeasure + measure.width); } else if(xEnd < measure.xOfMeasure + measure.width) { return this.getNoteRangeForMeasure(measure, measure.xOfMeasure, xEnd); } else { return 'all'; } } else { return undefined; } }; getSelectedRange = (measure, xStart, xEnd, selectedRows) => { if(!selectedRows) { return undefined; } const selectedRowIndex = selectedRows.indexOf(measure.rowIndex); if(selectedRowIndex === -1) { return undefined; } if(selectedRows.length === 1) { return this.getSelectedRangeForSingleRow(measure, xStart, xEnd); } else if(selectedRowIndex === 0) { if(measure.xOfMeasure + measure.width > xStart) { if(measure.xOfMeasure < xStart) { // starting measure, need note index return this.getNoteRangeForMeasure(measure, xStart, measure.xOfMeasure + measure.width); } else { return 'all'; } } } else if(selectedRowIndex === selectedRows.length - 1) { if(xEnd > measure.xOfMeasure) { if(xEnd < measure.xOfMeasure + measure.width) { // last measure return this.getNoteRangeForMeasure(measure, measure.xOfMeasure, xEnd); } else { return 'all'; } } } else { return 'all'; } }; onMouseDown = (e) => { e.preventDefault(); const x = e.pageX; const y = e.pageY - SVG_TOP; this.setState({ dragStart: { x, y }, x, y, selectedRanges: undefined }); }; onMouseUp = () => { const { x, y, dragHeight, dragWidth } = this.state; let selectedRows; if(dragWidth > 5 && dragHeight > 5) { const startRow = Math.floor(y / this.props.rowHeight); const endRow = Math.floor((y + dragHeight) / this.props.rowHeight); selectedRows = Array.from({ length: endRow - startRow + 1 }, (_, k) => k + startRow); } const selectRange = this.props.measures.reduce((accum, measure, i) => { const measureRange = this.getSelectedRange(measure, x, x + dragWidth, selectedRows); const obj = {}; obj[i] = measureRange; return measureRange ? Object.assign({}, accum, obj) : accum; }, {}); this.props.setSelectRange(selectRange); this.setState({ dragStart: undefined, x: undefined, y: undefined, dragWidth: undefined, dragHeight: undefined }); }; onMouseMove = (e) => { if(this.state.dragStart) { e.preventDefault(); const x = e.pageX + 5; const y = e.pageY - SVG_TOP; this.setState({ x: Math.min(this.state.dragStart.x, x), y: Math.min(this.state.dragStart.y, y), dragWidth: Math.abs(this.state.dragStart.x - x), dragHeight: Math.abs(this.state.dragStart.y - y) }); } } render() { const { height, width, measures } = this.props; const { x, y, dragWidth, dragHeight, selectRanges } = this.state; return ( <div style={{ ...style, height, width }} onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} onMouseMove={this.onMouseMove}> { measures.map((_, i) => <Measure key={i} measureIndex={i} selected={selectRanges ? selectRanges[i] : undefined} />) } <SelectBox height={height} width={width} x={x} y={y} dragWidth={dragWidth} dragHeight={dragHeight} /> </div> ); } } function mapDispatchToProps(dispatch) { return { setSelectRange: bindActionCreators(setSelectRange, dispatch) }; } export default connect(scoreSelector, mapDispatchToProps)(Score);
JavaScript
0
@@ -3818,51 +3818,163 @@ %7D);%0A - this.props.setSelectRange(selectRange); +%0A if(Object.keys(selectRange).length %3E 0) %7B%0A this.props.setSelectRange(selectRange);%0A %7D else %7B%0A this.props.setSelectRange(undefined);%0A %7D %0A%0A
c7436cae90ea76af38d9cc5d85ed1f86fa7bf8d5
Update chart.js
src/components/chart.js
src/components/chart.js
import React from 'react' import {Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines' import _ from 'lodash' function average(data){ console.log('data--',data.length); return _.round(_.sum(data)/data.length) } export default (props)=>{ return ( <div> <Sparklines data={props.data} svgWidth={250} svgHeight={200}> <SparklinesLine color={props.color}/> <SparklinesReferenceLine type="avg"/> </Sparklines> <div>{average(props.data)} {props.units}</div> </div> ) }
JavaScript
0.000001
@@ -157,45 +157,8 @@ a)%7B%0A - console.log('data--',data.length);%0A re
aca6a373564ee381b0c401b7528c814a78e52768
fix contaxt of select-option initial onChange call
src/pat/select-option.js
src/pat/select-option.js
/** * Patterns checkedflag - Add checked flag to checkbox labels * * Copyright 2013 Simplon B.V. - Wichert Akkerman * Copyright 2013 Florian Friesdorf */ define([ "jquery", "../registry", "../utils" ], function($, patterns, utils) { var select_option = { name: "select-option", trigger: "label select", init: function($el) { $el.on("change.pat-select-option", select_option._onChange); select_option._onChange(); return $el; }, destroy: function($el) { return $el.off(".pat-select-option"); }, _onChange: function() { var label = utils.findLabel(this); if (label !== null) { $(label).attr('data-option', $(this).val() || ""); } } }; patterns.register(select_option); return select_option; });
JavaScript
0
@@ -472,17 +472,26 @@ onChange -( +.call(this );%0A
eafc0d202e6a83a7c694b97d021b3229d5949169
Add comment about #clockwise magic happening in #append*() methods.
src/path/CompoundPath.js
src/path/CompoundPath.js
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Distributed under the MIT license. See LICENSE file for details. * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * All rights reserved. */ var CompoundPath = this.CompoundPath = PathItem.extend({ initialize: function(paths) { this.base(); this._children = []; // Do not reassign to paths, since arguments would get modified, which // we potentially use as array, depending on what is passed. var items = !paths || !Array.isArray(paths) || typeof paths[0] !== 'object' ? arguments : paths; for (var i = 0, l = items.length; i < l; i++) { var path = items[i]; // All paths except for the top one (last one in list) are set to // clockwise orientation when creating a compound path, so that they // appear as holes, but only if their orientation was not already // specified before (= _clockwise is defined). if (path._clockwise === undefined) path.setClockwise(i < l - 1); this.appendTop(path); } }, /** * If this is a compound path with only one path inside, * the path is moved outside and the compound path is erased. * Otherwise, the compound path is returned unmodified. * * @return the simplified compound path. */ simplify: function() { if (this._children.length == 1) { var child = this._children[0]; child.moveAbove(this); this.remove(); return child; } return this; }, smooth: function() { for (var i = 0, l = this._children.length; i < l; i++) this._children[i].smooth(); }, draw: function(ctx, param) { var firstChild = this._children[0]; ctx.beginPath(); param.compound = true; for (var i = 0, l = this._children.length; i < l; i++) Item.draw(this._children[i], ctx, param); firstChild._setStyles(ctx); var fillColor = firstChild.getFillColor(), strokeColor = firstChild.getStrokeColor(); if (fillColor) { ctx.fillStyle = fillColor.getCanvasStyle(ctx); ctx.fill(); } if (strokeColor) { ctx.strokeStyle = strokeColor.getCanvasStyle(ctx); ctx.stroke(); } param.compound = false; } }, new function() { // Injection scope for PostScript-like drawing functions function getCurrentPath(that) { if (!that._children.length) throw new Error('Use a moveTo() command first'); return that._children[that._children.length - 1]; } var fields = { moveTo: function(point) { var path = new Path(); this.appendTop(path); path.moveTo.apply(path, arguments); }, moveBy: function(point) { this.moveTo(getCurrentPath(this).getLastSegment()._point.add( Point.read(arguments))); }, closePath: function() { getCurrentPath(this).setClosed(true); } }; // Redirect all other drawing commands to the current path Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', 'arcTo', 'lineBy', 'curveBy', 'arcBy'], function(key) { fields[key] = function() { var path = getCurrentPath(this); path[key].apply(path, arguments); }; }); return fields; });
JavaScript
0
@@ -1118,16 +1118,88 @@ fined).%0A +%09%09%09// TODO: This should really be handled in appendTop / Bottom, right?%0A %09%09%09if (p
a0b5f87465d0f21de97dc937e3cc6ac6ba0bdcf6
Fix error in panel-link click handling.
src/patterns/carousel.js
src/patterns/carousel.js
/** * @license * Patterns @VERSION@ carousel * * Copyright 2012 Simplon B.V. */ define([ "jquery", "../logging", "../core/parser", "../3rdparty/jquery.anythingslider" ], function($, logging, Parser) { var log = logging.getLogger("carousel"), parser = new Parser(); parser.add_argument("auto-play", true); parser.add_argument("loop", true); parser.add_argument("resize", false); parser.add_argument("expand", false); parser.add_argument("control-arrows", false); parser.add_argument("control-navigation", false); parser.add_argument("control-startstop", false); parser.add_argument("time-delay", 3000); parser.add_argument("time-animation", 600); var carousel = { markup_trigger: ".pt-carousel", init: function($el) { return $el.each(function() { var options = parser.parse(this.dataset.carousel), settings = {hashTags: false}; if (Array.isArray(options)) { log.warn("Multiple options not supported for carousels."); options = options[0]; } settings.autoPlay = options["auto-play"]; settings.stopAtEnd = !options.loop; settings.resizeContents = options.resize; settings.expand = options.expand; settings.buildArrows = options["control-arrows"]; settings.buildNavigation = options["control-navigation"]; settings.buildStartStop = options["control-startstop"]; settings.delay = options["time-delay"]; settings.animationTime = options["time-animation"]; var $carousel = $(this).anythingSlider(settings), control = $carousel.data("AnythingSlider"), $panel_links = $(); $carousel .children().each(function(index, el) { if (!this.id) return; var $links = $("a[href=#" + this.id+"]"); $panel_links = $panel_links.add($links); $links.on("click.carousel", null, control, carousel.onPanelLinkClick); }).end() .on("slide_complete.carousel", null, $panel_links, carousel.onSlideComplete); }); }, onPanelLinkClick: function(event) { var control = event.data; control.gotoPage(index, false); event.preventDefault(); }, onSlideComplete: function(event, slider) { var $panel_links = event.data; $panel_links.removeClass("current"); if (slider.$targetPage[0].id) $panel_links.filter("[href=#" + slider.$targetPage[0].id + "]").addClass("current"); } }; return carousel; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
JavaScript
0
@@ -2242,23 +2242,48 @@ , null, +%7B control +: control, index: index%7D , carous @@ -2519,46 +2519,19 @@ -var control = event.data;%0A +event.data. cont @@ -2543,16 +2543,27 @@ otoPage( +event.data. index, f
cbfd3db3b642f916659b90894818c94bbba4d842
add removeTailPeriodFormatter
src/answer-formatter.js
src/answer-formatter.js
var toStringFormatter = function(answer){ return answer.toString(); }; var toLowerCaseFormatter = function(answer){ return answer.toLowerCase(); }; var stringFormUtils = require('string-form-utils'); var fullwidthFormatter = function(answer){ return stringFormUtils.transformToHalfwidth(answer); }; var removeSpaceFormatter = function(answer){ return answer.replace(/\s/g, ''); }; var numberFormatter = function(answer){ return answer.replace(/(\d?),(\d?)/g, "$1$2"); }; var formatters = [ toStringFormatter, toLowerCaseFormatter, fullwidthFormatter, removeSpaceFormatter, numberFormatter ]; var format = function (answer){ var result = answer; for(var i=0 ; i<formatters.length ; i++){ result = formatters[i](result); } return result; }; var equals = function (answer1, answer2){ return format(answer1) == format(answer2) }; var answerFormatter = { format : format, equals : equals }; if (typeof module !== "undefined" && module !== null) { module.exports = answerFormatter; } if (typeof window !== "undefined" && window !== null) { window.answerFormatter = answerFormatter; }
JavaScript
0.000032
@@ -378,24 +378,119 @@ g, '');%0A%7D;%0A%0A +var removeTailPeriodFormatter = function(answer)%7B%0A%09return answer.replace(/%5E(.+)%E3%80%82$/, '$1');%0A%7D;%0A%0A var numberFo @@ -675,16 +675,44 @@ matter,%0A +%09removeTailPeriodFormatter,%0A %09numberF
cf4e85dbe185852a03b979bf6f2d46a19eb70d0d
test a vdom injection export for preact smoke test
src/preact/index.test.js
src/preact/index.test.js
/* global describe, it, expect */ import { createStore } from "./index"; describe("preact/index", () => { it("smoke test", () => { expect(createStore).toBeTruthy(); }); });
JavaScript
0
@@ -37,27 +37,25 @@ mport %7B -createStore +Container %7D from @@ -141,32 +141,41 @@ ect( -createStore).toBeTruthy( +typeof Container).toBe(%22function%22 );%0A
26f74d2f2e8857b8113e83e0f8b48152a95bc9bd
Correct code
js/variables_dynamic.js
js/variables_dynamic.js
var sentence = 2; var sentence = "This is the sentence."; console.log(sentence); console.log(sentence);
JavaScript
0.999882
@@ -11,20 +11,16 @@ ce = 2;%0A -var sentence
6755a64bbf437a11cd9a505b1206c61cac75b9a9
return changes of BertT which were lost by a git conflict
src/app/scripts/main.js
src/app/scripts/main.js
/*jslint browser: true*/ /*global L */ /*global GEOHEX */ var geohexcode = 'PO2670248'; var startZoomlevel = 12; var user = "barack"; var satelliteImages = null; var map = null; var polygon = null; var default_geohex_level = 7; function getSatelliteImageByDate(date) { for (var i = 0; i < satelliteImages.features.length; i++) { if (satelliteImages.features[i].properties.Published === date) { return satelliteImages.features[i]; } } return null; } function findEarthWatchersLayer() { var result = null; map.eachLayer(function (layer) { if (layer.options.type !== null) { if (layer.options.type === 'earthWatchers') { result = layer; } } }); return result; } function sendObservation(observation) { colorizePolygon(observation); var zone = GEOHEX.getZoneByCode(geohexcode); var obs = { "user": user, "lat": zone.lat, "lon": zone.lon, "level": zone.getLevel(), "observation": observation, "geohex": geohexcode }; var url = 'api/observations'; var request = new XMLHttpRequest(); request.open('POST', url, true); request.setRequestHeader("Content-type", "application/json"); request.send(JSON.stringify(obs)); request.onload = function () { if (request.status == 201) { // var data = JSON.parse(request.responseText); getHexagon(geohexcode, hexagonCallback); } }; } function getColorByObservation(observation) { var color = "#32cd32"; if (observation === "yes") { color = "#b23618"; } else if (observation === "maybe") { color = "#ffd900"; } return color; } function colorizePolygon(observation) { var color = getColorByObservation(observation); polygon.setStyle({color: color}); } function timeSliderChanged(ctrl) { var day = satelliteImages.features[ctrl.value].properties.Published; document.getElementById('rangeValLabel').innerHTML = day; var earthWatchersLayer = findEarthWatchersLayer(); var s = getSatelliteImageByDate(day); var url = s.properties.UrlTileCache + '/{z}/{x}/{y}.png'; var maxlevel = s.properties.MaxLevel; var newLayer = L.tileLayer(url, { tms: true, maxZoom: maxlevel, type: 'earthWatchers' }); map.addLayer(newLayer); if (earthWatchersLayer !== null) { map.removeLayer(earthWatchersLayer); } } function getGeohexPolygon(geohexcode, style) { var zone = GEOHEX.getZoneByCode(geohexcode); return L.polygon(zone.getHexCoords(), style); } function getSatelliteImageData(bbox, imagetype, callback) { var url = 'api/satelliteimages?bbox=' + bbox + '&imagetype=' + imagetype; var request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = function () { if (request.status >= 200 && request.status < 400) { var data = JSON.parse(request.responseText); callback(data); } }; request.send(); } function getHexagon(geohex, callback) { var url = 'api/hexagons/' + geohex; var request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = function () { if (request.status >= 200 && request.status < 400) { var data = JSON.parse(request.responseText); callback(data); } }; request.send(); } function compare(a, b) { if (a.properties.Published < b.properties.Published) { return -1; } if (a.properties.Published > b.properties.Published) { return 1; } return 0; } function random(low, high) { return Math.random() * (high - low) + low; } function satelliteImagesCallback(req) { satelliteImages = req; var sel = document.getElementById('timeSlider'); satelliteImages.features.sort(compare); sel.onchange(); } function next() { location.reload(); } function hexagonCallback(req) { // alert("obs: " + req); document.getElementById('btnYes').innerHTML = 'Yes (' + req.yes + ')'; document.getElementById('btnNo').innerHTML = 'No (' + req.no + ')'; document.getElementById('btnMaybe').innerHTML = 'Maybe (' + req.maybe + ')'; console.log(req); } function satelliteTypeSelectionChanged(sel) { var currentImageType = sel.value; var polygon = getGeohexPolygon(geohexcode); var bbox = polygon.getBounds().toBBoxString(); getSatelliteImageData(bbox, currentImageType, satelliteImagesCallback); } (function (window, document, L) { 'use strict'; L.Icon.Default.imagePath = 'images/'; var lon_min = 111.0; var lon_max = 112.0; var lat_min = 1; var lat_max = 2; var lon_rnd = random(lon_min, lon_max); var lat_rnd = random(lat_min, lat_max); geohexcode = GEOHEX.getZoneByLocation(lat_rnd, lon_rnd, default_geohex_level).code; // fire onchange event of first combobox var selectImageType = document.getElementById('selectImageType'); selectImageType.onchange(); map = L.map('map', { zoomControl: false, attributionControl: false }); var myStyle = { 'color': '#000000', 'weight': 5, 'opacity': 0.65, fillOpacity: 0 }; getHexagon(geohexcode, hexagonCallback); polygon = getGeohexPolygon(geohexcode, myStyle); var centerHex = polygon.getBounds().getCenter(); map.setView(centerHex, startZoomlevel, { animation: true }); map.addControl(new L.Control.ZoomMin({ position: 'topright', startLevel: startZoomlevel, startCenter: centerHex })); L.control.scale({imperial: false, position: 'topleft'}).addTo(map); var ggl2 = new L.Google('satellite'); map.addLayer(ggl2); //omnivore.topojson('project.topojson').addTo(map); map.addLayer(polygon); }(window, document, L));
JavaScript
0
@@ -4004,37 +4004,8 @@ ) %7B%0A - // alert(%22obs: %22 + req);%0A @@ -4050,16 +4050,36 @@ rHTML = +window.toStaticHTML( 'Yes (' @@ -4089,24 +4089,25 @@ eq.yes + ')' +) ;%0A docume @@ -4145,16 +4145,36 @@ rHTML = +window.toStaticHTML( 'No (' + @@ -4182,24 +4182,25 @@ req.no + ')' +) ;%0A docume @@ -4241,16 +4241,36 @@ rHTML = +window.toStaticHTML( 'Maybe ( @@ -4292,29 +4292,8 @@ ')' -;%0A console.log(req );%0A%7D
ffb736001eee16a1efea752dfc433e83aac0c8ed
添加 audio clip 接口需求
src/asset/audio-clip.js
src/asset/audio-clip.js
Fire.AudioClip = (function () { var AudioClip = Fire.define("Fire.AudioClip", Fire.Asset, null); AudioClip.prop('rawData', null, Fire.RawType('audio')); return AudioClip; })();
JavaScript
0
@@ -153,24 +153,561 @@ 'audio'));%0A%0A + AudioClip.get('buffer', function () %7B%0A return Fire.AudioContext.getClipBuffer(this);%0A %7D);%0A%0A AudioClip.get(%22length%22, function () %7B%0A return Fire.AudioContext.getClipLength(this);%0A %7D);%0A%0A AudioClip.get(%22samples%22, function () %7B%0A return Fire.AudioContext.getClipSamples(this);%0A %7D);%0A%0A AudioClip.get(%22channels%22, function () %7B%0A return Fire.AudioContext.getClipChannels(this);%0A %7D);%0A%0A AudioClip.get(%22frequency%22, function () %7B%0A return Fire.AudioContext.getClipFrequency(this);%0A %7D);%0A%0A return A
1cba55f868458dfea2005050e75b825ac35287fb
Fix wrong parameter (#271) (#301)
src/auth/auth.action.js
src/auth/auth.action.js
import { AsyncStorage } from 'react-native'; import uniqby from 'lodash.uniqby'; import { delay, resetNavigationTo, configureLocale } from 'utils'; import { saveLanguage } from 'locale'; import { fetchAccessToken, fetchAuthUser, fetchAuthUserOrgs, fetchUserOrgs, fetchUserEvents, fetchStarCount, } from 'api'; import { LOGIN, LOGOUT, GET_AUTH_USER, GET_AUTH_ORGS, GET_EVENTS, CHANGE_LANGUAGE, GET_AUTH_STAR_COUNT, } from './auth.type'; export const auth = (code, state, navigation) => { return dispatch => { dispatch({ type: LOGIN.PENDING }); delay(fetchAccessToken(code, state), 2000) .then(data => { dispatch({ type: LOGIN.SUCCESS, payload: data.access_token, }); resetNavigationTo('Main', navigation); }) .catch(error => { dispatch({ type: LOGIN.ERROR, payload: error, }); }); }; }; export const signOut = () => { return dispatch => { dispatch({ type: LOGOUT.PENDING }); return AsyncStorage.clear() .then(() => { dispatch({ type: LOGOUT.SUCCESS, }); }) .catch(error => { dispatch({ type: LOGOUT.ERROR, payload: error, }); }); }; }; export const getUser = () => { return (dispatch, getState) => { const accessToken = getState().auth.accessToken; dispatch({ type: GET_AUTH_USER.PENDING }); fetchAuthUser(accessToken) .then(data => { dispatch({ type: GET_AUTH_USER.SUCCESS, payload: data, }); }) .catch(error => { dispatch({ type: GET_AUTH_USER.ERROR, payload: error, }); }); }; }; export const getStarCount = () => { return (dispatch, getState) => { const user = getState().auth.user.name; dispatch({ type: GET_AUTH_STAR_COUNT.PENDING }); fetchStarCount(user) .then(data => { dispatch({ type: GET_AUTH_STAR_COUNT.SUCCESS, payload: data, }); }) .catch(error => { dispatch({ type: GET_AUTH_STAR_COUNT.ERROR, payload: error, }); }); }; }; export const getOrgs = () => { return (dispatch, getState) => { const accessToken = getState().auth.accessToken; const login = getState().auth.user.login; dispatch({ type: GET_AUTH_ORGS.PENDING }); Promise.all([ fetchAuthUserOrgs(accessToken), fetchUserOrgs(login, accessToken), ]) .then(data => { const orgs = data[0].concat(data[1]); dispatch({ type: GET_AUTH_ORGS.SUCCESS, payload: uniqby(orgs, 'login').sort( (org1, org2) => org1.login > org2.login ), }); }) .catch(error => { dispatch({ type: GET_AUTH_ORGS.ERROR, payload: error, }); }); }; }; export const getUserEvents = user => { return (dispatch, getState) => { const accessToken = getState().auth.accessToken; dispatch({ type: GET_EVENTS.PENDING }); fetchUserEvents(user, accessToken) .then(data => { dispatch({ type: GET_EVENTS.SUCCESS, payload: data, }); }) .catch(error => { dispatch({ type: GET_EVENTS.ERROR, payload: error, }); }); }; }; export const changeLanguage = lang => { return dispatch => { dispatch({ type: CHANGE_LANGUAGE.SUCCESS, payload: lang }); saveLanguage(lang); configureLocale(lang); }; };
JavaScript
0.000001
@@ -1851,12 +1851,13 @@ ser. -name +login ;%0A%0A
96af9d00403b35c27e704deaacf829a73654f149
fix lint and reduce throttle
src/reducers/monitors.js
src/reducers/monitors.js
const UPDATE_MONITORS = 'scratch-gui/monitors/UPDATE_MONITORS'; const REMOVE_MONITORS = 'scratch-gui/monitors/REMOVE_MONITORS'; const initialState = []; const reducer = function (state, action) { if (typeof state === 'undefined') state = initialState; let newState; switch (action.type) { // Adds or updates monitors case UPDATE_MONITORS: newState = [...state]; for (let i = 0, updated = false; i < action.monitors.length; i++) { for (let j = 0; j < state.length; j++) { if (action.monitors[i].id == state[j].id) { newState[j] = action.monitors[i]; updated = true; continue; } } if (!updated) { newState.push(action.monitors[i]); } updated = false; } return newState; // Removes monitors case REMOVE_MONITORS: newState = [...state]; for (let i = 0; i < action.monitors.length; i++) { // Move backwards to keep indices aligned for (let j = state.length - 1; j >= 0; j--) { if (action.monitors[i].id == state[j].id) { newState.splice(j, 1); continue; } } } return newState; default: return state; } }; reducer.updateMonitors = function (monitors) { return { type: UPDATE_MONITORS, monitors: monitors, meta: { throttle: 100 } }; }; reducer.removeMonitors = function (monitors) { return { type: REMOVE_MONITORS, monitors: monitors, meta: { throttle: 30 } }; }; module.exports = reducer;
JavaScript
0
@@ -550,32 +550,33 @@ onitors%5Bi%5D.id == += state%5Bj%5D.id) %7B%0A @@ -1180,16 +1180,17 @@ i%5D.id == += state%5Bj @@ -1543,10 +1543,9 @@ le: -10 +3 0%0A
57a4ed30ca7257ca562d569eea1df35c602503dd
Revert "Fix function wrapping bug in JavaScript RTS"
jsrts/Runtime-common.js
jsrts/Runtime-common.js
/** @constructor */ var i$VM = function() { this.valstack = []; this.valstack_top = 0; this.valstack_base = 0; this.ret = null; this.callstack = []; } var i$vm; var i$valstack; var i$valstack_top; var i$valstack_base; var i$ret; var i$callstack; var i$Int = {}; var i$String = {}; var i$Integer = {}; var i$Float = {}; var i$Char = {}; var i$Ptr = {}; var i$Forgot = {}; /** @constructor */ var i$CON = function(tag,args,app,ev) { this.tag = tag; this.args = args; this.app = app; this.ev = ev; } /** @constructor */ var i$POINTER = function(addr) { this.addr = addr; } var i$SCHED = function(vm) { i$vm = vm; i$valstack = vm.valstack; i$valstack_top = vm.valstack_top; i$valstack_base = vm.valstack_base; i$ret = vm.ret; i$callstack = vm.callstack; } var i$SLIDE = function(args) { for (var i = 0; i < args; ++i) i$valstack[i$valstack_base + i] = i$valstack[i$valstack_top + i]; } var i$PROJECT = function(val,loc,arity) { for (var i = 0; i < arity; ++i) i$valstack[i$valstack_base + i + loc] = val.args[i]; } var i$CALL = function(fun,args) { i$callstack.push(args); i$callstack.push(fun); } var i$ffiWrap = function(fid,oldbase,myoldbase) { return function() { i$callstack = []; var res = fid; for(var i = 0; i < (arguments.length ? arguments.length : 1); ++i) { i$valstack_top += 1; i$valstack[i$valstack_top] = res; i$valstack[i$valstack_top + 1] = arguments[i]; i$SLIDE(2); i$valstack_top = i$valstack_base + 2; i$CALL(_idris__123_APPLY0_125_,[oldbase]) while (i$callstack.length) { var func = i$callstack.pop(); var args = i$callstack.pop(); func.apply(this,args); } res = i$ret; } i$callstack = i$vm.callstack; return i$ret; } } var i$charCode = function(str) { if (typeof str == "string") return str.charCodeAt(0); else return str; } var i$fromCharCode = function(chr) { if (typeof chr == "string") return chr; else return String.fromCharCode(chr); }
JavaScript
0
@@ -1330,24 +1330,63 @@ 1); ++i) %7B%0A + while (res instanceof i$CON) %7B%0A i$vals @@ -1398,32 +1398,34 @@ top += 1;%0A + + i$valstack%5Bi$val @@ -1442,16 +1442,18 @@ = res;%0A + i$ @@ -1503,16 +1503,18 @@ ;%0A + + i$SLIDE( @@ -1517,16 +1517,18 @@ IDE(2);%0A + i$ @@ -1569,16 +1569,18 @@ ;%0A + + i$CALL(_ @@ -1615,24 +1615,26 @@ ase%5D)%0A + while (i$cal @@ -1654,24 +1654,26 @@ ) %7B%0A + + var func = i @@ -1682,32 +1682,34 @@ allstack.pop();%0A + var args @@ -1722,32 +1722,34 @@ allstack.pop();%0A + func.app @@ -1769,18 +1769,22 @@ ;%0A -%7D%0A + %7D%0A re @@ -1794,16 +1794,24 @@ i$ret;%0A + %7D%0A %7D%0A%0A
c8344ca8e047329b8c4fdf0b676c226aa6c71d41
Update SauceLabs config (#119)
karma-saucelabs.conf.js
karma-saucelabs.conf.js
// Karma configuration module.exports = function(config) { var customLaunchers = { 'latest-chrome': { base: 'SauceLabs', browserName: 'chrome' }, 'latest-firefox': { base: 'SauceLabs', browserName: 'firefox' }, 'internet-explorer-9': { base: 'SauceLabs', browserName: 'internet explorer', version: '9' }, 'safari-5': { base: 'SauceLabs', platform: "OS X 10.6", browserName: 'safari', version: '5' }, 'ios-6': { base: 'SauceLabs', platform: "OS X 10.8", browserName: 'iphone', version: "6.0" }, 'android-4': { base: 'SauceLabs', platform: "Linux", device: 'Motorola Droid Razr Emulator', browserName: 'android', version: "4.0" } }; config.set({ frameworks: ['qunit'], files: [ { pattern: 'tests/images/circle.png', served: true, watched: false, included: false }, 'node_modules/jquery/dist/jquery.min.js', 'dist/circle-progress.js', 'tests/modernizr.js', 'tests/test_utils.js', 'tests/tests.js' ], sauceLabs: { testName: 'Unit Tests for jquery-circle-progress' }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), reporters: ['dots', 'saucelabs'], singleRun: true }); };
JavaScript
0
@@ -93,21 +93,35 @@ ' -l +L atest --c + C hrome + on Windows 10 ': %7B @@ -144,32 +144,68 @@ e: 'SauceLabs',%0A + platform: 'Windows 10',%0A brow @@ -221,16 +221,47 @@ 'chrome' +,%0A version: 'latest' %0A @@ -277,22 +277,36 @@ ' -l +L atest --f + F irefox + on Windows 10 ': %7B @@ -353,29 +353,96 @@ -browserName: 'firefox +platform: 'Windows 10',%0A browserName: 'firefox',%0A version: 'latest '%0A @@ -463,27 +463,24 @@ ' -internet-explorer-9 +IE9 on Windows 7 ': %7B @@ -503,32 +503,67 @@ e: 'SauceLabs',%0A + platform: 'Windows 7',%0A brow @@ -641,16 +641,35 @@ ' -safari-5 +Latest Safari on OS X 10.11 ': %7B @@ -722,25 +722,25 @@ atform: -%22 +' OS X 10. 6%22,%0A @@ -735,10 +735,11 @@ 10. -6%22 +11' ,%0A @@ -797,9 +797,14 @@ n: ' -5 +latest '%0A @@ -826,12 +826,36 @@ 'i -os-6 +Phone emulator on OS X 10.11 ': %7B @@ -921,9 +921,10 @@ 10. -8 +11 %22,%0A @@ -983,11 +983,11 @@ n: %22 -6.0 +8.1 %22%0A @@ -1008,17 +1008,33 @@ ' -a +A ndroid --4 + emulator on Linux ': %7B @@ -1091,66 +1091,14 @@ rm: -%22 +' Linux -%22,%0A device: 'Motorola Droid Razr Emulator ',%0A @@ -1157,13 +1157,13 @@ on: -%224.0%22 +'5.0' %0A
703505bb768714e4f8760300a27a69f6525bfbb3
Add iOS 8 to SauceLabs test suite
karma.conf.saucelabs.js
karma.conf.saucelabs.js
// Config file used as example: https://github.com/angular/angular.js/blob/master/karma-shared.conf.js var package = require('./package.json') var debug = require('logdown')('Karma') // // SauceLabs conf // var sauceLabsConf = { sauceLabs: { testName: package.name, username: process.env.SAUCELABS_USERNAME, accessKey: process.env.SAUCELABS_ACCESS_KEY }, customLaunchers: { sl_chrome: { base: 'SauceLabs', browserName: 'chrome', version: 'latest', platform: 'Windows 10' }, sl_firefox: { base: 'SauceLabs', browserName: 'firefox', version: 'latest', platform: 'Windows 10' }, 'sl_safari_8': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.10', version: '8' }, 'sl_safari_9': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.11', version: '9' }, sl_safari_ios_latest: { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.10', version: 'latest', deviceName: 'iPhone 6 Plus' } } } // // Export // module.exports = function(config) { if (!process.env.SAUCELABS_USERNAME || !process.env.SAUCELABS_ACCESS_KEY) { debug.error('Set env variables `SAUCELABS_USERNAME` and `SAUCELABS_ACCESS_KEY` with your SauceLabs credentials.') throw new Error() } var confOptions = { plugins: [ require('karma-webpack'), require('karma-tap'), require('karma-sauce-launcher') ], basePath: '', frameworks: [ 'tap' ], files: [ 'test/*.js' ], preprocessors: { 'test/*.js': [ 'webpack' ] }, webpack: { node : { fs: 'empty' } }, webpackMiddleware: { noInfo: true }, reporters: ['dots', 'saucelabs'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: [], singleRun: false, // To avoid DISCONNECTED messages browserDisconnectTimeout : 10000, browserDisconnectTolerance : 1, browserNoActivityTimeout : 60000, } // Add SauceLabs browsers Object.assign(confOptions, sauceLabsConf) confOptions.browsers.push(...Object.keys(sauceLabsConf.customLaunchers)) config.set(confOptions) };
JavaScript
0
@@ -1084,13 +1084,240 @@ ne 6 - Plus +',%0A deviceOrientation: 'portrait'%0A %7D,%0A sl_ios_8: %7B%0A base: 'SauceLabs',%0A browserName: 'safari',%0A platform: 'OS X 10.11',%0A version: '8.4',%0A deviceName: 'iPhone 6',%0A deviceOrientation: 'portrait '%0A
7c5fbf50d231dfa7cd37459db4a75e35e53fd546
increase browserNoActivityTimeout for Karma
karma.conf.saucelabs.js
karma.conf.saucelabs.js
var karmaBaseConf = require('./karma.base.conf') var browsers = { sl_chrome: { base: 'SauceLabs', browserName: 'chrome', platform: 'Windows 10', version: '50.0' }, sl_firefox: { base: 'SauceLabs', browserName: 'firefox', platform: 'Windows 10', version: '46.0' }, sl_ie_11: { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 10', version: '11.103' }, sl_edge: { base: 'SauceLabs', browserName: 'MicrosoftEdge', platform: 'Windows 10', version: '13.10586' } } module.exports = function (config) { karmaBaseConf.plugins.push(require('karma-sauce-launcher')) karmaBaseConf.reporters.push('saucelabs') karmaBaseConf.logLevel = config.LOG_DEBUG karmaBaseConf.customLaunchers = browsers karmaBaseConf.captureTimeout = 200000 karmaBaseConf.browserDisconnectTolerance = 3 karmaBaseConf.concurrency = 5 karmaBaseConf.browsers = Object.keys(browsers) karmaBaseConf.sauceLabs = { // Should be false for running on travis, as travis already starts its own // sauce connect startConnect: false, // https://github.com/karma-runner/karma-sauce-launcher/issues/73 tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER } config.set(karmaBaseConf) }
JavaScript
0.000002
@@ -874,16 +874,65 @@ nce = 3%0A + karmaBaseConf.browserNoActivityTimeout = 20000%0A karmaB
a3de0194a4bad64882f366cc173d20a1bc7b3d49
Fix constructor of Path
unify/framework/source/class/unify/view/Path.js
unify/framework/source/class/unify/view/Path.js
/* =============================================================================================== Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2009-2010 Deutsche Telekom AG, Germany, http://telekom.com =============================================================================================== */ /** * Class to manage an in-application path. * * A Path is basically an array which is somewhat comparable to a typical Unix path. It uses * "/" for dividing path fragments. Each fragments might contain information about a view * (the class you look at), a segment (a e.g. tab selected inside the view) and a param (the * selected email ID etc.). */ (function(global) { core.Class("unify.view.Path", {}); unify.view.Path.prototype = new Array(); core.Main.addMembers("unify.view.Path", { /** * Deep clones a Path instance. * * @return {unify.view.Path} Returns the deeply cloned Path instance. */ clone : function() { var clone = new unify.view.Path(); var entry; for (var i=0, l=this.length; i<l; i++) { entry = this[i]; clone.push({ view : entry.view, segment : entry.segment, param : entry.param }); } return clone; }, /** * Serializes a Path object into a location string. The result * can be re-used for {@link unify.view.Path.fromString}. * * @return {String} Location string */ serialize : function() { var result = []; var part, temp; for (var i=0, l=this.length; i<l; i++) { part = this[i]; temp = part.view; if (part.segment) { temp += "." + part.segment; } if (part.param) { temp += ":" + part.param; } result.push(temp); } return result.join("/"); } }); core.Main.addStatics("unify.view.Path", { /** * Converts a location string into a path object. * * Format is "fragment1/fragment2/fragment3". * Each fragment has the format "view.segment:param". * * @param str {String} A location string with supported special charaters * @return {unify.view.Path} Returns the path object */ fromString : function(str) { var obj = new unify.view.Path; if (str && str.length > 0) { var fragments = str.split("/"); for (var i=0, l=fragments.length; i<l; i++) { obj.push(this.parseFragment(fragments[i])); } } return obj; }, /** {RegExp} Matches location fragments (view.segment:param) */ __fragmentMatcher : /^([a-z0-9-]+)?(\.([a-z-]+))?(\:([a-zA-Z0-9_%=-]+))?$/, /** * Parses a location fragment into a object with the keys "view", "segment" and "param". * * @param fragment {String} Location fragment to parse * @return {Map} The parsed fragment. */ parseFragment : function(fragment) { var match = this.__fragmentMatcher.exec(fragment); if (core.Env.getValue("debug")) { if (!match) { throw new Error("Invalid location fragment: " + fragment); } } return { view : RegExp.$1 || null, segment : RegExp.$3 || null, param : RegExp.$5 || null }; }, /** * Checks wheter all single chunks of paths are equal. * * @param a {unify.view.Path} Path a * @param b {unify.view.Path} Path b * * @return {Boolean} true if paths are equal, otherwise false */ chunkEquals : function(a, b) { if (!a || !b) { return false; } return (a.view == b.view && a.segment == b.segment && a.param == b.param); } }); })(this);
JavaScript
0.000002
@@ -764,16 +764,115 @@ Path%22, %7B +%0A construct : function(params) %7B%0A if (params) %7B%0A this.push(params);%0A %7D%0A %7D%0A %7D);%0A un
ae319ca9385dd7f8ee3242f27d1945b3270c53b9
Reverse order of catch() and then() calls on promises
src/discoverServices.js
src/discoverServices.js
/* * This function probes Okapi to discover what versions of what * interfaces are supported by the services that it is proxying * for. This information can be used to configure the UI at run-time * (e.g. not attempting to fetch loan information for a * non-circulating library that doesn't provide the circ interface) */ import 'isomorphic-fetch'; function discoverInterfaces(okapiUrl, store, entry) { fetch(`${okapiUrl}/_/proxy/modules/${entry.id}`) .then((response) => { if (response.status >= 400) { store.dispatch({ type: 'DISCOVERY_FAILURE', code: response.status }); } else { response.json().then((json) => { store.dispatch({ type: 'DISCOVERY_INTERFACES', data: json }); }); } }) .catch((reason) => { store.dispatch({ type: 'DISCOVERY_FAILURE', message: reason }); }); } export function discoverServices(okapiUrl, store) { fetch(`${okapiUrl}/_/proxy/modules`) .then((response) => { if (response.status >= 400) { store.dispatch({ type: 'DISCOVERY_FAILURE', code: response.status }); } else { response.json().then((json) => { store.dispatch({ type: 'DISCOVERY_SUCCESS', data: json }); for (const entry of json) { discoverInterfaces(okapiUrl, store, entry); } }); } }) .catch((reason) => { store.dispatch({ type: 'DISCOVERY_FAILURE', message: reason }); }); } export function discoveryReducer(state = {}, action) { switch (action.type) { case 'DISCOVERY_FAILURE': return Object.assign({}, state, { failure: action }); case 'DISCOVERY_SUCCESS': { const modules = {}; for (const entry of action.data) { modules[entry.id] = entry.name; } return Object.assign({}, state, { modules }); } case 'DISCOVERY_INTERFACES': { const interfaces = {}; for (const entry of action.data.provides) { interfaces[entry.id] = entry.version; } return Object.assign({}, state, { interfaces: Object.assign(state.interfaces || {}, interfaces), }); } default: return state; } } export function isVersionCompatible(got, wanted) { const [gmajor, gminor] = got.split('.'); const [wmajor, wminor] = wanted.split('.'); return wmajor === gmajor && parseInt(wminor, 10) >= parseInt(gminor, 10); }
JavaScript
0.999691
@@ -454,24 +454,121 @@ y.id%7D%60)%0A +.catch((reason) =%3E %7B%0A store.dispatch(%7B type: 'DISCOVERY_FAILURE', message: reason %7D);%0A %7D) .then((respo @@ -837,32 +837,127 @@ ;%0A %7D%0A %7D) +;%0A%7D%0A%0Aexport function discoverServices(okapiUrl, store) %7B%0A fetch(%60$%7BokapiUrl%7D/_/proxy/modules%60) %0A .catch((rea @@ -1046,108 +1046,8 @@ %7D) -;%0A%7D%0A%0Aexport function discoverServices(okapiUrl, store) %7B%0A fetch(%60$%7BokapiUrl%7D/_/proxy/modules%60)%0A .the @@ -1433,110 +1433,8 @@ %7D%0A - %7D)%0A .catch((reason) =%3E %7B%0A store.dispatch(%7B type: 'DISCOVERY_FAILURE', message: reason %7D);%0A
d40b0c06401eb5dd72cbb5b075e1e4b61a27b089
Update example-main-2.js
Training-Session-3/Examples/Example2/example-main-2.js
Training-Session-3/Examples/Example2/example-main-2.js
(function() { /* The goal of this file is to provide the basic understanding 1. Create a View class. 2. Reference with DOM using el & this.$el 3. DOM events hash. 4. Scope of DOM event. How to run this example. 1. Open Example-1.html in Google Chrome browser. 2. Press F12, go to console tab. 3. See the message get displayed on that console tab. */ /* Creating a new View called MasterView by extending Backbone.View class. Syntax: Backbone.View.extend(properties, [classProperties]) */ var MasterView = Backbone.View.extend({ /* All views have a DOM element at all times (the el property), whether they've already been inserted into the page or not. */ el: '.workspace' /* Events hash. */ events: { 'click input[type=submit]': 'submitForm', 'click input[type=reset]': 'resetForm', 'click input[type=button]': 'buttonForm' }, /* Custom function gets fired when specific event gets called. */ submitForm: function() { console.log("Submit Button got clicked. Time to validate form data."); }, resetForm: function() { console.log("Reset Button got clicked. Time to reset form data."); }, buttonForm: function() { console.log("Won't able to access this function. This is out of view scope."); }, /* This is the view's render function; Used to render data. */ render: function() { console.log("View render function."); } }); /* Creating an object from MasterView which calls initialize function. */ var masterView = new MasterView(); console.log(masterView.el); })();
JavaScript
0
@@ -705,16 +705,17 @@ rkspace' +, %0A%0A%09%09/*%0A%09
5bddc321884bf5e3e3fde2ab52c2362f6be07064
Tidy up
electron/index.js
electron/index.js
/* global require, process */ (function () { 'use strict'; var electron = require('electron'); var path = require('path'); var url = require('url'); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var win; function createWindow () { var template = [{ label: "Application", submenu: [ { label: "About Application", selector: "orderFrontStandardAboutPanel:" }, { type: "separator" }, { label: "Quit", accelerator: "Command+Q", click: function() { app.quit(); }} ]}, { label: "Edit", submenu: [ { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" }, { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" }, { type: "separator" }, { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" }, { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" }, { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" }, { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" } ]} ]; // No menu on Windows if (process.platform !== 'win32') { var Menu = electron.Menu; Menu.setApplicationMenu(Menu.buildFromTemplate(template)); } // Create the browser window. var BrowserWindow = electron.BrowserWindow; win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }); // and load the index.html of the app. win.loadURL(url.format({ pathname: path.join(__dirname, 'app/index.html'), protocol: 'file:', slashes: true })); // Open the DevTools. // win.webContents.openDevTools(); // Emitted when the window is closed. win.on('closed', function () { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null; }); } var app = electron.app; // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow); // Quit when all windows are closed. app.on('window-all-closed', function () { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow(); } }); })();
JavaScript
0.000027
@@ -68,17 +68,17 @@ electron - +%09 = requir @@ -101,17 +101,18 @@ var path - +%09%09 = requir @@ -130,17 +130,19 @@ %09var url - +%09%09%09 = requir @@ -320,16 +320,315 @@ r win;%0A%0A +%09var app = electron.app;%0A%09app.on('ready', createWindow);%0A%09app.on('window-all-closed', close);%0A%09app.on('activate', activate);%0A%0A%09// This method will be called when Electron has finished%0A%09// initialization and is ready to create browser windows.%0A%09// Some APIs can only be used after this event occurs.%0A %09functio @@ -2314,240 +2314,8 @@ %09%7D%0A%0A -%09var app = electron.app;%0A%0A%09// This method will be called when Electron has finished%0A%09// initialization and is ready to create browser windows.%0A%09// Some APIs can only be used after this event occurs.%0A%09app.on('ready', createWindow);%0A%0A %09// @@ -2353,36 +2353,8 @@ d.%0A%09 -app.on('window-all-closed', func @@ -2350,32 +2350,37 @@ osed.%0A%09function +close () %7B%0A%09%09// On mac @@ -2560,32 +2560,11 @@ %7D%0A%09%7D -); %0A%0A%09 -app.on('activate', func @@ -2564,24 +2564,32 @@ %0A%0A%09function +activate () %7B%0A%09%09// On @@ -2759,17 +2759,15 @@ ;%0A%09%09%7D%0A%09%7D -); %0A%7D)();%0A
7fc3582e1d5cba0ce64ff88434339d16afa339be
Fix condition that shows loading screen
src/engine/automatic.js
src/engine/automatic.js
import Base from '../index'; import Login from './automatic/login'; import SignUp from './automatic/sign_up_screen'; import ResetPassword from '../connection/database/reset_password'; import { renderSSOScreens } from '../core/sso/index'; import { additionalSignUpFields, authWithUsername, defaultDatabaseConnection, defaultDatabaseConnectionName, getScreen, initDatabase } from '../connection/database/index'; import { defaultEnterpriseConnection, defaultEnterpriseConnectionName, initEnterprise, isADEnabled, isEnterpriseDomain, isHRDActive, isInCorpNetwork, quickAuthConnection } from '../connection/enterprise'; import { initSocial } from '../connection/social/index'; import { setEmail } from '../field/email'; import { setUsername } from '../field/username'; import * as l from '../core/index'; import KerberosScreen from '../connection/enterprise/kerberos_screen'; import HRDScreen from '../connection/enterprise/hrd_screen'; import EnterpriseQuickAuthScreen from '../connection/enterprise/quick_auth_screen'; import { hasSkippedQuickAuth } from '../quick_auth'; import { lastUsedConnection } from '../core/sso/index'; import LoadingScreen from '../core/loading_screen'; import ErrorScreen from '../core/error_screen'; import LastLoginScreen from '../core/sso/last_login_screen'; import { hasError, isDone, isSuccess } from '../sync'; import * as c from '../field/index'; import { swap, updateEntity } from '../store/index'; export function isSSOEnabled(m) { return isEnterpriseDomain( m, usernameStyle(m) === "username" ? c.username(m) : c.email(m) ); } export function usernameStyle(m) { return authWithUsername(m) && !isADEnabled(m) ? "username" : "email"; } class Automatic { static SCREENS = { login: Login, forgotPassword: ResetPassword, signUp: SignUp }; didInitialize(model, options) { model = initSocial(model, options); model = initDatabase(model, options); model = initEnterprise(model, options); const { email, username } = options.prefill || {}; if (typeof email === "string") model = setEmail(model, email); if (typeof username === "string") model = setUsername(model, username); swap(updateEntity, "lock", l.id(model), _ => model); } didReceiveClientSettings(m) { const anyDBConnection = l.hasSomeConnections(m, "database"); const anySocialConnection = l.hasSomeConnections(m, "social"); const anyEnterpriseConnection = l.hasSomeConnections(m, "enterprise"); if (!anyDBConnection && !anySocialConnection && !anyEnterpriseConnection) { // TODO: improve message throw new Error("At least one database, enterprise or social connection needs to be available."); } if (defaultDatabaseConnectionName(m) && !defaultDatabaseConnection(m)) { l.warn(m, `The provided default database connection "${defaultDatabaseConnectionName(m)}" is not enabled.`); } if (defaultEnterpriseConnectionName(m) && !defaultEnterpriseConnection(m)) { l.warn(m, `The provided default enterprise connection "${defaultEnterpriseConnectionName(m)}" is not enabled or does not allow email/password authentication.`); } } render(m) { // TODO: remove the detail about the loading pane being pinned, // sticky screens should be handled at the box module. if (!isDone(m) || m.get("isLoadingPanePinned")) { return new LoadingScreen(); } const anyDBConnection = l.hasSomeConnections(m, "database"); const anySocialConnection = l.hasSomeConnections(m, "social"); const anyEnterpriseConnection = l.hasSomeConnections(m, "enterprise"); const noConnection = !anyDBConnection && !anySocialConnection && !anyEnterpriseConnection; if (l.hasStopped(m) || hasError(m, ["sso"]) || noConnection) { return new ErrorScreen(); } if (!hasSkippedQuickAuth(m) && l.ui.rememberLastLogin(m)) { if (isInCorpNetwork(m)) { return new KerberosScreen(); } const conn = lastUsedConnection(m); if (conn && isSuccess(m, "sso")) { if (l.hasConnection(m, conn.get("name"))) { return new LastLoginScreen(); } } } if (quickAuthConnection(m)) { return new EnterpriseQuickAuthScreen(); } if (isHRDActive(m)) { return new HRDScreen(); } const Screen = Automatic.SCREENS[getScreen(m)]; if (Screen) return new Screen(); throw new Error("unknown screen"); } } export default new Automatic();
JavaScript
0.000002
@@ -3316,16 +3316,17 @@ %0A if +( (!isDone @@ -3328,16 +3328,42 @@ sDone(m) + && !hasError(m, %5B%22sso%22%5D)) %7C%7C m.ge
32e21c94ce817c901669ca5665a98affa24968bc
load QRCode properly, add constructor
src/etheriumQRplugin.js
src/etheriumQRplugin.js
import DrawIcon from 'tokenIcon'; import {tokenSchemaEIP67, tokenSchemaBitcoin} from 'utils'; class etheriumQRplugin { generate(config) { this.parseRequest(config); this.drawQrCodeContainer(); let generatedCode = this.schemaGenerator(this.tokenAdress, this.tokenName, this.tokenAmount); new QRCode(this.uiElement, { text: generatedCode, width: this.size, height: this.size }); this.drawTokenIcon(); } parseRequest(request){ this.tokenName = request.tokenName; this.tokenAdress = request.tokenAdress; this.tokenAmount = request.tokenAmount; this.size = request.size || 128 this.imgUrl = request.imgUrl || false; this.schemaGenerator = request.schema === 'bitcoin' ? tokenSchemaBitcoin : tokenSchemaEIP67; } drawTokenIcon(){ if (this.imgUrl) { const iconDraw = new DrawIcon(); iconDraw.addIcon(this.imgUrl, this.size, this.uiElement, () => { this.uiElement.parentNode.removeChild(this.uiElement); }); } } drawQrCodeContainer(){ this.uiElement = document.createElement('div'); document.body.appendChild(this.uiElement); this.uiElement.id = "qrcode-generation-container"; } } export default etheriumQRplugin;
JavaScript
0
@@ -15,16 +15,18 @@ n from ' +./ tokenIco @@ -85,16 +85,18 @@ om ' +./ utils';%0A %0Acla @@ -95,55 +95,188 @@ s';%0A -%0Aclass etheriumQRplugin %7B%0A%0A generate(config) +import QRCode from 'qrcodejs2';%0A%0Aclass etheriumQRplugin %7B%0A%0A constructor(el)%7B%0A%0A if(!el) %7B%0A this.drawQrCodeContainer();%0A return;%0A %7D%0A try %7B%0A @@ -286,33 +286,191 @@ + + this. -parseRequest +uiElement = document.querySelectorAll(el)%5B0%5D;%0A %7D%0A catch(e)%7B%0A console.log('Error, QR code container not found');%0A %7D%0A %7D%0A%0A generate (config) ;%0A @@ -465,17 +465,18 @@ (config) -; + %7B %0A @@ -481,36 +481,35 @@ this. -drawQrCodeContainer( +parseRequest(config );%0A @@ -997,16 +997,17 @@ e %7C%7C 128 +; %0A
84782a31505697d54c2f2cd9aad8a25dfe329286
Fix failing AboutFunctions tests
koans/AboutFunctions.js
koans/AboutFunctions.js
describe("About Functions", function() { it("should declare functions", function() { function add(a, b) { return a + b; } expect(add(1, 2)).toBe(FILL_ME_IN); }); it("should know internal variables override outer variables", function () { var message = "Outer"; function getMessage() { return message; } function overrideMessage() { var message = "Inner"; return message; } expect(getMessage()).toBe(FILL_ME_IN); expect(overrideMessage()).toBe(FILL_ME_IN); expect(message).toBe(FILL_ME_IN); }); it("should have lexical scoping", function () { var variable = "top-level"; function parentfunction() { var variable = "local"; function childfunction() { return variable; } return childfunction(); } expect(parentfunction()).toBe(FILL_ME_IN); }); it("should use lexical scoping to synthesise functions", function () { function makeMysteryFunction(makerValue) { var newFunction = function doMysteriousThing(param) { return makerValue + param; }; return newFunction; } var mysteryFunction3 = makeMysteryFunction(3); var mysteryFunction5 = makeMysteryFunction(5); expect(mysteryFunction3(10) + mysteryFunction5(5)).toBe(FILL_ME_IN); }); it("should allow extra function arguments", function () { function returnFirstArg(firstArg) { return firstArg; } expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN); function returnSecondArg(firstArg, secondArg) { return secondArg; } expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN); function returnAllArgs() { var argsArray = []; for (var i = 0; i < arguments.length; i += 1) { argsArray.push(arguments[i]); } return argsArray.join(","); } expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN); }); it("should pass functions as values", function () { var appendRules = function (name) { return name + " rules!"; }; var appendDoubleRules = function (name) { return name + " totally rules!"; }; var praiseSinger = { givePraise: appendRules }; expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN); praiseSinger.givePraise = appendDoubleRules; expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN); }); });
JavaScript
0.000003
@@ -157,34 +157,25 @@ 1, 2)).toBe( -FILL_ME_IN +3 );%0A %7D);%0A%0A @@ -452,34 +452,31 @@ age()).toBe( -FILL_ME_IN +%22Outer%22 );%0A expec @@ -497,34 +497,31 @@ age()).toBe( -FILL_ME_IN +%22Inner%22 );%0A expec @@ -532,34 +532,31 @@ ssage).toBe( -FILL_ME_IN +%22Outer%22 );%0A %7D);%0A%0A @@ -829,34 +829,31 @@ ion()).toBe( -FILL_ME_IN +%22local%22 );%0A %7D);%0A%0A @@ -1277,34 +1277,26 @@ n5(5)).toBe( -FILL_ME_IN +23 );%0A %7D);%0A%0A @@ -1480,34 +1480,31 @@ ird%22)).toBe( -FILL_ME_IN +%22first%22 );%0A%0A func @@ -1630,34 +1630,33 @@ arg%22)).toBe( -FILL_ME_IN +undefined );%0A%0A func @@ -1904,26 +1904,36 @@ )).toBe( -FILL_ME_IN +%22first,second,third%22 );%0A %7D); @@ -2258,34 +2258,37 @@ ohn%22)).toBe( -FILL_ME_IN +%22John rules!%22 );%0A%0A prai @@ -2381,18 +2381,29 @@ oBe( -FILL_ME_IN +%22Mary totally rules!%22 );%0A%0A
4d53cc8d3003e41696246be699a86427e7f4663c
bump build number 580
src/front/app.config.js
src/front/app.config.js
import * as dotenv from 'dotenv'; dotenv.config(); const baseBundleId = 'gov.dts.ugrc.utahwvcr'; const bundleIds = { development: `${baseBundleId}.dev`, staging: `${baseBundleId}.staging`, production: baseBundleId, }; const bundleId = bundleIds[process.env.ENVIRONMENT]; const names = { development: 'Utah Roadkill Dev', staging: 'Utah Roadkill Staging', production: 'Utah Roadkill', }; const name = names[process.env.ENVIRONMENT]; // perhaps this bump could be automated using a combo of app.config.json and this file? const buildNumber = 579; export default { name, slug: 'wildlife-vehicle-collision-reporter', // changing this may result in new signing keys being generated (https://forums.expo.dev/t/changed-app-json-slug-and-android-build-keys-changed-can-i-get-them-back/9927/3) description: 'A mobile application for reporting and removing roadkill in Utah.', scheme: bundleId, githubUrl: 'https://github.com/agrc/roadkill-mobile', version: '3.0.1', orientation: 'portrait', icon: process.env.ENVIRONMENT === 'production' ? './assets/icon.png' : `./assets/icon_${process.env.ENVIRONMENT}.png`, splash: { image: process.env.ENVIRONMENT === 'production' ? './assets/splash.png' : `./assets/splash_${process.env.ENVIRONMENT}.png`, resizeMode: 'contain', backgroundColor: '#ffffff', }, assetBundlePatterns: ['**/*'], // hermes was causing issues with environment variables. For some reason // it was making the prod app point to the staging api // wait until upgrade to expo 47 to try again // jsEngine: 'hermes', ios: { bundleIdentifier: bundleId, googleServicesFile: process.env.GOOGLE_SERVICES_IOS, buildNumber: buildNumber.toString(), supportsTablet: true, config: { usesNonExemptEncryption: false, googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY_IOS, }, infoPlist: { NSLocationAlwaysUsageDescription: 'The app uses your location in the background for tracking routes. *Note* this is only applicable for agency employees or contractors. Background location is not used for public users.', NSLocationWhenInUseUsageDescription: 'The app uses your location to help record the location of the animal that you are reporting.', UIBackgroundModes: ['location'], }, }, android: { package: bundleId, googleServicesFile: process.env.GOOGLE_SERVICES_ANDROID, versionCode: buildNumber, softwareKeyboardLayoutMode: 'pan', adaptiveIcon: { foregroundImage: process.env.ENVIRONMENT === 'production' ? './assets/adaptive-icon.png' : `./assets/adaptive-icon_${process.env.ENVIRONMENT}.png`, backgroundColor: '#FFFFFF', }, permissions: [ 'ACCESS_FINE_LOCATION', 'ACCESS_COARSE_LOCATION', 'ACCESS_BACKGROUND_LOCATION', 'FOREGROUND_SERVICE', 'READ_EXTERNAL_STORAGE', 'WRITE_EXTERNAL_STORAGE', ], config: { googleMaps: { apiKey: process.env.GOOGLE_MAPS_API_KEY_ANDROID, }, }, }, hooks: { postPublish: [ { file: 'sentry-expo/upload-sourcemaps', config: { organization: 'utah-ugrc', project: 'roadkill', authToken: process.env.SENTRY_AUTH_TOKEN, }, }, ], }, plugins: [ 'sentry-expo', 'expo-notifications', [ 'expo-image-picker', { photosPermission: 'The app accesses to your photos to allow you to submit a photo of the animal.', cameraPermission: 'The app accesses your camera to allow you to capture and submit a photo of the animal.', }, ], [ 'react-native-fbsdk-next', { appID: process.env.FACEBOOK_OAUTH_CLIENT_ID, clientToken: process.env.FACEBOOK_OAUTH_CLIENT_TOKEN, displayName: `${name} Reporter`, advertiserIDCollectionEnabled: false, autoLogAppEventsEnabled: false, }, ], [ 'expo-build-properties', { ios: { // required for react-native-maps, expo default for sdk 46 is 12.0 // ref: https://github.com/react-native-maps/react-native-maps/blob/master/docs/installation.md#enabling-google-maps deploymentTarget: '13.0', // this will be needed when expo-firebase-analytics (7.2+) and react-native-maps (1.3.2+) are bumped // it fixes firebase but breaks maps // waiting on https://github.com/react-native-maps/react-native-maps/discussions/4389 // // https://docs.expo.dev/versions/latest/sdk/firebase-analytics/#additional-configuration-for-ios // useFrameworks: 'static', }, }, ], ], extra: { eas: { projectId: '648c99de-696c-4704-8723-7f8838dc6896', }, }, // required for eas update command runtimeVersion: '1.0.1', updates: { url: 'https://u.expo.dev/648c99de-696c-4704-8723-7f8838dc6896', }, };
JavaScript
0.000002
@@ -552,10 +552,10 @@ = 5 -79 +80 ;%0A%0Ae
705c01d2f4b303366f803620471d4921886647a2
add imports
meteor/client/layout.js
meteor/client/layout.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/. Copyright (c) 2014 Mozilla Corporation */ if (Meteor.isClient) { //events that could fire in any sub template Template.layout.events({ "click .ipmenu-copy": function(e,t){ var ipText=$(e.target).attr('data-ipaddress') var ipTextArea = document.createElement("textarea"); ipTextArea.value = ipText; e.target.appendChild(ipTextArea); ipTextArea.focus(); ipTextArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; Session.set('displayMessage','copy & '+ msg); } catch (err) { Session.set('errorMessage','copy failed & ' + JSON.stringify(err)); } e.target.removeChild(ipTextArea); }, "click .ipmenu-whois": function(e,t){ Session.set('ipwhoisipaddress',($(e.target).attr('data-ipaddress'))); $('#modalwhoiswindow').modal() }, "click .ipmenu-dshield": function(e,t){ Session.set('ipdshieldipaddress',($(e.target).attr('data-ipaddress'))); $('#modaldshieldwindow').modal() }, "click .ipmenu-blockip": function(e,t){ Session.set('blockIPipaddress',($(e.target).attr('data-ipaddress'))); $('#modalBlockIPWindow').modal() }, "click .ipmenu-intel": function(e,t){ Session.set('ipintelipaddress',($(e.target).attr('data-ipaddress'))); $('#modalintelwindow').modal() }, "click .dropdown": function(e,t){ $(e.target).addClass("hover"); $('ul:first',$(e.target)).css('visibility', 'visible'); } }); }
JavaScript
0.000001
@@ -230,16 +230,185 @@ ation%0A*/ +%0Aimport %7B Meteor %7D from 'meteor/meteor'%0Aimport %7B Template %7D from 'meteor/templating';%0Aimport %7B Session %7D from 'meteor/session';%0Aimport %7B Tracker %7D from 'meteor/tracker'; %0A%0Aif (Me
2612693aa051c72dbb7c384aba4b88674108f73b
add en-us date format
src/global/date/date.js
src/global/date/date.js
'use strict'; var moment = require('moment'); var StringMask = require('string-mask'); function isISODateString(date) { return /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}([-+][0-9]{2}:[0-9]{2}|Z)$/ .test(date.toString()); } function DateMaskDirective($locale) { var dateFormatMapByLocale = { 'pt-br': 'DD/MM/YYYY', 'ru': 'DD.MM.YYYY', }; var dateFormat = dateFormatMapByLocale[$locale.id] || 'YYYY-MM-DD'; return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { attrs.parse = attrs.parse || 'true'; dateFormat = attrs.uiDateMask || dateFormat; var dateMask = new StringMask(dateFormat.replace(/[YMD]/g,'0')); function formatter(value) { if (ctrl.$isEmpty(value)) { return value; } var cleanValue = value; if (typeof value === 'object' || isISODateString(value)) { cleanValue = moment(value).format(dateFormat); } cleanValue = cleanValue.replace(/[^0-9]/g, ''); var formatedValue = dateMask.apply(cleanValue) || ''; return formatedValue.trim().replace(/[^0-9]$/, ''); } ctrl.$formatters.push(formatter); ctrl.$parsers.push(function parser(value) { if (ctrl.$isEmpty(value)) { return value; } var formatedValue = formatter(value); if (ctrl.$viewValue !== formatedValue) { ctrl.$setViewValue(formatedValue); ctrl.$render(); } return attrs.parse === 'false' ? formatedValue : moment(formatedValue, dateFormat).toDate(); }); ctrl.$validators.date = function validator(modelValue, viewValue) { if (ctrl.$isEmpty(modelValue)) { return true; } return moment(viewValue, dateFormat).isValid() && viewValue.length === dateFormat.length; }; } }; } DateMaskDirective.$inject = ['$locale']; module.exports = DateMaskDirective;
JavaScript
0
@@ -314,16 +314,41 @@ ale = %7B%0A +%09%09'en-us': 'MM/DD/YYYY',%0A %09%09'pt-br @@ -384,17 +384,16 @@ MM.YYYY' -, %0A%09%7D;%0A%0A%09v
478be34730bd852979ce9a2968f05e65a9def466
move needle down
generators/app/templates/client/app/app.js
generators/app/templates/client/app/app.js
/** * @ngdoc overview * @name <%= scriptAppName %> * @description * Module definition for the <%= scriptAppName %> module. */ (function () { 'use strict'; angular .module('<%= scriptAppName %>', [ // Add modules below<% angularModules.forEach(function(angularModule) { %> '<%= angularModule %>',<% }); %> ]) .config(appConfig)<% if(features.auth) { %> .run(appRun)<% } %>; /* App configuration */ // add appConfig dependencies to inject appConfig.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider', '$locationProvider', '$mdThemingProvider', '$mdIconProvider'<% if (features.auth) { %>, '$httpProvider'<% } %>]; /** * Application config function * * @param $stateProvider * @param $urlRouterProvider * @param $locationProvider */ function appConfig($urlRouterProvider, $urlMatcherFactoryProvider, $locationProvider, $mdThemingProvider, $mdIconProvider<% if (features.auth) { %>, $httpProvider<% } %>) { $urlRouterProvider.otherwise('/'); $urlMatcherFactoryProvider.strictMode(false); $locationProvider.html5Mode(true); <% if(features.auth) { %> $httpProvider.interceptors.push('AuthInterceptor');<% } %> // set the default palette name var defaultPalette = 'blue'; // define a palette to darken the background of components var greyBackgroundMap = $mdThemingProvider.extendPalette(defaultPalette, {'A100': 'fafafa'}); $mdThemingProvider.definePalette('grey-background', greyBackgroundMap); $mdThemingProvider.setDefaultTheme(defaultPalette); // customize the theme $mdThemingProvider .theme(defaultPalette) .primaryPalette(defaultPalette) .accentPalette('pink') .backgroundPalette('grey-background'); var spritePath = 'bower_components/material-design-icons/sprites/svg-sprite/'; $mdIconProvider.iconSet('navigation', spritePath + 'svg-sprite-navigation.svg'); $mdIconProvider.iconSet('action', spritePath + 'svg-sprite-action.svg'); $mdIconProvider.iconSet('content', spritePath + 'svg-sprite-content.svg'); $mdIconProvider.iconSet('toggle', spritePath + 'svg-sprite-toggle.svg'); $mdIconProvider.iconSet('alert', spritePath + 'svg-sprite-alert.svg'); }<% if(features.auth) { %> /* App run bootstrap */ // add appConfig dependencies to inject appRun.$inject = ['$rootScope', '$location', 'Auth']; /** * Application run function * * @param $rootScope * @param $location * @param Auth */ function appRun($rootScope, $location, Auth) { // Redirect to login if route requires auth and you're not logged in $rootScope.$on('$stateChangeStart', function (event, next) { if (!next.authenticate) { return; } Auth.isLoggedInAsync(function (loggedIn) { if (!loggedIn || next.role && !Auth.hasRole(next.role)) { $location.path('/login'); } }); }); }<% } %>; })();
JavaScript
0.002398
@@ -208,35 +208,8 @@ ', %5B -%0A // Add modules below %3C%25 a @@ -294,24 +294,51 @@ ',%3C%25 %7D); %25%3E%0A + // Add modules below%0A %5D)%0A .
9d3e65e73c326ca5d8b6c3ef62b06395e2d755fd
check if target is defined
tasks/grunt-appengine.js
tasks/grunt-appengine.js
'use strict'; module.exports = function (grunt) { var _ = grunt.util._; var defaultOpts = { root: '.', manageScript: 'appcfg.py', manageFlags: { oauth2: true }, runScript: 'dev_appserver.py', runFlags: { port: 8080 } }; function spawned(done, cmd, args, opts) { function spawnFunc() { var spawn = require('child_process').spawn; opts.stdio = 'inherit'; spawn(cmd, args || [], opts).on('exit', function (status) { done(status === 0); }); } return spawnFunc; } // expecting 'appengine:<command>:<target>(:<profile>)' function validateArgs(args) { if (args.length === 0) { grunt.log.error('Unable to run task: no action specified (e.g. run or update)'); return false; } else if (args.length === 1) { grunt.log.error('Unable to run task: no target specified'); return false; } else if (args.length > 3) { grunt.log.error('Unable to run task: too many arguments (up to 3 allowed)'); return false; } return true; } // ==== INTERFACE var exports = { execute: function (dryRun) { var self = this; var name = self.name || 'appengine'; // ==== read task parameters var taskArgs = this.args || []; grunt.log.debug('Task args: ' + taskArgs); if (validateArgs(taskArgs) === false) { return false; } var action = taskArgs[0]; var target = taskArgs[1]; var profile = taskArgs[2]; var taskOpts = _.defaults( grunt.config([name, target, profile]) || {}, grunt.config([name, target]) || {}, grunt.config([name, 'options']) || {}, defaultOpts ); //console.log(grunt.config([name, target, profile])); grunt.log.debug('Task opts: ' + JSON.stringify(taskOpts)); var appdir = taskOpts['root']; // ==== assemble script name var cmd = taskOpts['manageScript']; var optsFlagsName = 'manageFlags'; if (action === 'run') { cmd = taskOpts['runScript']; optsFlagsName = 'runFlags'; } var taskFlagsOpts = _.defaults( (grunt.config([name, target, profile]) || {})[optsFlagsName] || {}, (grunt.config([name, target]) || {})[optsFlagsName] || {}, (grunt.config([name, 'options']) || {})[optsFlagsName] || {}, defaultOpts[optsFlagsName] ); var sdk = taskOpts['sdk']; if (sdk) { cmd = sdk + '/' + cmd; } // ==== assemble script action var cmdAction = []; if (taskOpts['backend'] === true) { cmdAction.push('backends'); cmdAction.push(appdir); cmdAction.push(action); var backendName = taskOpts['backendName']; if (backendName) { cmdAction.push(backendName); } } else { if (action !== 'run') { cmdAction.push(action); } cmdAction.push(appdir); } // ==== assemble script flags var cmdFlags = []; for (var attrname in taskFlagsOpts) { var attrval = taskFlagsOpts[attrname]; if (attrval === true) { cmdFlags.push('--' + attrname); } else { cmdFlags.push('--' + attrname + '=' + attrval); } } // ==== assemble script process opts var cmdOpts = {}; cmdOpts['env'] = process.env || {}; var envTaskOpts = taskOpts['env'] || {}; for (var envName in envTaskOpts) { cmdOpts['env'][envName] = envTaskOpts[envName]; } grunt.log.debug('CMD opts: ' + JSON.stringify(cmdOpts)); // ==== execute and return var cmdArgs = cmdFlags.concat(cmdAction); var fullCmd = cmd + ' ' + cmdArgs.join(' '); grunt.log.writeln('executing: ' + fullCmd); if (dryRun !== true) { var done = this.async(); spawned(done, cmd, cmdArgs, cmdOpts)(); } else { grunt.log.write('(dry run: script not executed)'); } grunt.log.writeln(); return { cmd: fullCmd, opts: cmdOpts }; } }; // ==== TASK grunt.registerTask('appengine', 'Managing App Engine.', exports.execute); return exports; };
JavaScript
0.000006
@@ -1505,16 +1505,174 @@ gs%5B2%5D;%0A%0A + if (!grunt.config(%5Bname, target%5D)) %7B%0A grunt.log.error('Unable to run task: target %5C'' + target + '%5C' not found');%0A return false;%0A %7D%0A%0A va
796acbcea59607a875ca158cb615c740ef1e74ba
Fix missing "new" statement
homedisplay/info_torrents/static/js/torrents.js
homedisplay/info_torrents/static/js/torrents.js
var Torrents = function() { var update_interval; function clearItems() { $("#torrent-items tr").remove(); } function processData(items) { clearItems(); $.each(items, function() { $("#torrent-items").append("<tr data-hash='"+this.hash+"'><td>"+this.filename+"</td><td>"+this.size+"</td><td>"+this.downloaded_percent+"%</td><td>"+this.up_speed+"</td><td>"+this.eta+"</td><td>"+this.netdisk+"</td><td><div class='action-button animate-click stripe-box' data-action='remove'><i data-original-classes='fa fa-trash' class='fa fa-trash'></i></div> <div class='action-button animate-click stripe-box' data-action='stop'><i data-original-classes='fa fa-stop' class='fa fa-stop'></i></div> <div class='action-button animate-click stripe-box' data-action='play'><i data-original-classes='fa fa-play' class='fa fa-play'></i></div> </td></tr>") }); $("#torrent-items .action-button").on("click", function () { var command = $(this).data("action"); var hash = $(this).parent().data("hash"); $(this).find("i").removeClass().addClass("fa fa-spin fa-spinner"); $.post("/homecontroller/torrents/action/"+command+"/"+hash, function () { // No need to remove spinner, as whole table will be redrawn. }); }); } function update() { $.get("/homecontroller/torrents/list", function(data) { processData(items); }) } function startInterval() { stopInterval(); update(); update_interval = startInterval(update, 60 * 60 * 1000); } function stopInterval() { if (update_interval) { update_interval = clearInterval(update_interval); } } ws_generic.register("torrent-list", processData); ge_refresh.register("torrent-list", update); this.update = update; this.startInterval = startInterval; this.stopInterval = stopInterval; }; var torrents; $(document).ready(function () { torrents = Torrents(); $(".main-button-box .linux-downloads").on("click", function () { torrents.update(); switchVisibleContent("#linux-downloads-modal"); }); $("#linux-downloads-modal .close").on("click", function() { switchVisibleContent("#main-content"); }); });
JavaScript
0.999999
@@ -1896,16 +1896,20 @@ rrents = + new Torrent
75dbd8fc0935528548128baece4887291075f97d
remove dead code
source/markup/templates/modules/topbar.js
source/markup/templates/modules/topbar.js
'use strict' //---------------------------------------------------------- // modules //---------------------------------------------------------- // npm const m = require('mithril') //---------------------------------------------------------- // logic //---------------------------------------------------------- const topbar = data => m('header' , { class: 'topbar' , role: 'heading' } , [ topbarContent(data) ]) const topbarContent = data => m('div' , { class: 'topbar__content' } , [ topbarTitle(data) ]) const topbarTitle = data => m('h1' , { class: 'topbar__title' } , data.title ) // function topbar(data) { // const header = // m('header' // , { class: 'topbar' // , role: 'heading' // } // , [ content ]) // const content = // m('div' // , { class: 'topbar__content' } // , [ title(data) ]) // const title = data => // m('h1' // , { class: 'topbar__title' } // , data.title // ) // return header // } //---------------------------------------------------------- // exports //---------------------------------------------------------- module.exports = topbar
JavaScript
0.999454
@@ -633,410 +633,8 @@ )%0A%0A -// function topbar(data) %7B%0A// const header =%0A// m('header'%0A// , %7B class: 'topbar'%0A// , role: 'heading'%0A// %7D%0A// , %5B content %5D)%0A%0A// const content =%0A// m('div'%0A// , %7B class: 'topbar__content' %7D%0A// , %5B title(data) %5D)%0A%0A// const title = data =%3E%0A// m('h1'%0A// , %7B class: 'topbar__title' %7D%0A// , data.title%0A// )%0A%0A// return header%0A// %7D%0A%0A //--
aeebf8d58b79d754bad66da7619a8decee4e6445
update what's new
src/scenes/AboutScene.js
src/scenes/AboutScene.js
"use strict"; import React, {Component} from 'react'; import { Linking, StyleSheet, View, ScrollView, Text, } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; import IconSocial from 'react-native-vector-icons/FontAwesome'; import CONFIG from './../config'; import _ from './../l10n'; import { Layout, Touchable, } from './../components'; import Scene from './Scene'; class Link extends Component { static propTypes = { title: React.PropTypes.string.isRequired, href: React.PropTypes.string.isRequired, icon: React.PropTypes.string, }; static defaultProps = {}; onPress() { Linking.openURL(this.props.href); } render() { let icon; if (this.props.icon) { icon = ( <IconSocial name={this.props.icon} size={24} color="#FFFFFF" /> ); } return ( <Touchable onPress={() => this.onPress()}> <View style={styles.link}> {icon} <Text style={styles.linkTitle}>{this.props.title}</Text> <Icon name="open-in-browser" size={24} color="#FFFFFF" /> </View> </Touchable> ); } } export class AboutScene extends Scene { constructor(props, context, updater) { super(props, context, updater); this.hardwareBackPress = () => this.navigationPop(); } render() { return ( <Layout toolbarTitle={_('INFORMATION')} onToolbarIconPress={() => this.navigationPop()} background={require('./../assets/background_about_gray.jpg')} styles={styles.container} > <View style={styles.top}/> <ScrollView style={styles.center} contentContainerStyle={styles.centerContentContainerStyle}> <Text style={styles.label}>{`${_('ABOUT_TITLE').toUpperCase()}`}</Text> <View style={styles.section}> <Text style={styles.text}>{_('ABOUT_TEXT')}</Text> </View> <Text style={styles.label}>{`${_('COPYRIGHT_TITLE').toUpperCase()}`}</Text> <View style={styles.section}> <Text style={styles.text}>{_('COPYRIGHT_TEXT')}</Text> </View> <Text style={styles.label}>{`${_('DEVELOPERS').toUpperCase()}`}</Text> <View style={styles.section}> <Text style={styles.title}>{`${_('CODE')}:`.toUpperCase()}</Text> <Link title="david volkov" href="http://davidvolkov.tech"/> <Text style={styles.title}>{`${_('DESIGN')}:`.toUpperCase()}</Text> <Link title="dmitry kurashkin" href="https://www.reddit.com/user/dimitryk_52"/> <Text style={styles.title}>{`${_('SPECIAL_THANKS')}:`.toUpperCase()}</Text> <Link icon="vk" title="danila semenov" href="https://vk.com/mhgny"/> <Link icon="reddit-alien" title="/u/FixKun" href="https://www.reddit.com/user/FixKun"/> </View> <Text style={styles.label}>{`${_('THANKS_TITLE').toUpperCase()}`}</Text> <View style={styles.section}> <Text style={styles.title}>{`${_('THANKS_TEXT_IDEA_INITIAL_DESIGN')}:`.toUpperCase()}</Text> <Link icon="reddit-alien" title="/u/izzepizze" href="https://www.reddit.com/user/izzepizze"/> <Text style={styles.title}>{`${_('THANKS_TEXT_SOURCES_AND_ASSETS')}:`.toUpperCase()}</Text> <Link icon="reddit-alien" title="/u/js41637" href="https://www.reddit.com/user/js41637"/> <Link icon="github" title="js41637" href="https://github.com/Js41637"/> <Link title="Overwatch Item Tracker" href="https://js41637.github.io/Overwatch-Item-Tracker"/> <Link icon="github" title="Overwatch Item Tracker" href="https://github.com/Js41637/Overwatch-Item-Tracker"/> <Text style={styles.title}>{`${_('THANKS_TEXT_COMMUNITY')}:`.toUpperCase()}</Text> <Link icon="reddit-alien" title="/r/overwatch" href="https://www.reddit.com/r/overwatch"/> </View> </ScrollView> <View style={styles.bottom}> <Text onPress={() => this.navigator.push({name: 'WelcomeScene', props: {type: 'whats-new'},})} style={styles.version} > {`${_('VERSION').toUpperCase()}: ${CONFIG.VERSION}`} </Text> </View> </Layout> ); } } const styles = StyleSheet.create({ container: { }, top: {}, center: { flex: 1, }, centerContentContainerStyle: {}, bottom: {}, label: { marginHorizontal: 16, fontSize: 32, fontFamily: 'BigNoodleToo', color: CONFIG.COLORS.LIGHT_BLUE, }, section: { paddingTop: 8, paddingBottom: 16, }, title: { marginHorizontal: 16, fontSize: 18, fontFamily: 'Futura', color: CONFIG.COLORS.LEGENDARY, }, text: { marginHorizontal: 16, fontSize: 16, fontFamily: 'Futura', color: '#F5F5F5', }, version: { fontSize: 11, margin: 16, fontFamily: 'Futura', color: '#F5F5F5', }, link: { height: 48, marginVertical: 2, paddingHorizontal: 16, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: CONFIG.COLORS.DARK_BLUE_OPACITY, }, linkTitle: { flex: 1, marginHorizontal: 8, fontSize: 18, fontFamily: 'Futura', color: '#F5F5F5', }, });
JavaScript
0.000001
@@ -5794,22 +5794,23 @@ -marg +padd in +g : 16,%0A