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
f9aaa39212a4f814c33acb4e9571329253d389fa
Put as-genome component into a wide-container div
app/routing.js
app/routing.js
angular.module('antismash.db.ui.routing', [ 'ui.router', 'antismash.db.ui.query', 'antismash.db.ui.stats', 'antismash.db.ui.browse', 'antismash.db.ui.genome', ]).config([ '$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/start'); $stateProvider. state('start', { url: '/start', templateUrl: 'start/start.html' }). state('stats', { url: '/stats', templateUrl: 'stats/stats.html', controller: 'StatsController', controllerAs: '$ctrl' }). state('query', { url: '/query', templateUrl: 'query/query.html', controller: 'QueryController', controllerAs: 'ctrl' }). state('browse', { url: '/browse', templateUrl: 'browse/browse.html' }). state('show', { url: '/show', abstract: true, template: '<ui-view/>' }). state('show.genome', { url: '/genome/:id', template: '<as-genome genome-id="{{ctrl.id}}"></as-genome>', controller: function ($stateParams) { this.id = $stateParams.id; }, controllerAs: 'ctrl' }). state('help', { url: '/help', templateUrl: 'help/help.html' }); }]);
JavaScript
0
@@ -1046,16 +1046,44 @@ late: '%3C +div class=%22wide-container%22%3E%3C as-genom @@ -1120,16 +1120,22 @@ -genome%3E +%3C/div%3E ',%0A
c6c9bd86d7378cafa65dcd9410a7a27e1b02c147
add search field to listings reducer
client/src/reducers/listings.js
client/src/reducers/listings.js
import { FETCHING_LISTINGS, GET_ALL_LISTINGS_SUCCESS } from '../constants'; export const initialState = { allListings: [], isFetching: false, }; export const listings = (state = initialState, action) => { switch (action.type) { case GET_ALL_LISTINGS_SUCCESS: return ({ ...state, allListings: action.payload, isFetching: false }); case FETCHING_LISTINGS: return ({ ...state, isFetching: true}); default: return state; } };
JavaScript
0
@@ -45,16 +45,37 @@ _SUCCESS +, CHANGE_SEARCH_FIELD %7D from @@ -162,16 +162,35 @@ false,%0A + searchField: '',%0A %7D;%0A%0Aexpo @@ -452,24 +452,110 @@ ng: true%7D);%0A + case CHANGE_SEARCH_FIELD:%0A return (%7B ...state, searchField: action.value %7D);%0A default:
a9a9959c5346c4ac0006c8083f7e3c22d9bac459
allow a non-native event for triggering navbar re-sort
src/collapsible.navbar.js
src/collapsible.navbar.js
/* collapsible extension for navbar functionality */ ;(function( w ){ var $ = w.jQuery; $( w.document ).bind( "init", function( e ){ var pluginName = "collapsible"; var extName = "navbar"; var itemClass = extName + "_item"; var overflowActiveClass = extName + "-overflow"; var itemMenuClass = itemClass + "-overflow"; var itemMoreClass = extName + "_more"; var itemMoreHiddenClass = itemMoreClass + "-nomore"; var readyClass = extName + "-ready"; if( $( e.target ).is( "." + pluginName + "." + extName ) ){ var $collapsible = $( e.target ); var $navItems = $collapsible.find( "." + itemClass ); var $moreBtn = $collapsible.find( "." + itemMoreClass ); $moreBtn.attr( "aria-label", "Toggle more items" ); var resetItems = function(){ $moreBtn.removeClass( itemMoreHiddenClass ); $navItems.removeClass( itemMenuClass ); }; var initItems = function(){ menuNotReady(); resetItems(); var startTop = $navItems[ 0 ].offsetTop; function menuNotReady(){ $collapsible.removeClass( readyClass ); } function menuReady(){ $collapsible.addClass( readyClass ); } function accommodateMoreBtn(){ if( $moreBtn[ 0 ].offsetTop > startTop ){ var $notOverflowedMenuItems = $navItems.not( "." + itemMenuClass ); if( $notOverflowedMenuItems.length ) { $notOverflowedMenuItems.last().addClass( itemMenuClass ); accommodateMoreBtn(); } } else { var $menuItems = $navItems.filter( "." + itemMenuClass ); if( $menuItems.length === 0 ){ $moreBtn.addClass( itemMoreHiddenClass ); $collapsible.removeClass( overflowActiveClass ); } else{ $collapsible.addClass( overflowActiveClass ); } menuReady(); } } accommodateMoreBtn(); }; // init immediately initItems(); // and on window resize $( w ).bind( "resize", initItems ); // and on window load just in case things have shifted $( w ).bind( "load", initItems ); $collapsible .bind( "mouseover." + pluginName, function( e ){ if( $collapsible.is( "[data-collapsible-hover]" ) && !$( e.target ).closest( "." + itemMenuClass + ", ." + itemMoreClass ).length ){ $collapsible.data( pluginName ).collapse(); } } ) .bind( "expand", function( e ){ var $target = $( e.target ); var $childCollapsibles = $target.find( "." + pluginName + "-expanded." + itemMenuClass ); if( $( e.target ).is( this ) ){ $moreBtn.attr( "tabindex", "-1" ); $collapsible.find( "." + itemMenuClass + " a" ).eq(0).focus(); } else if( !$childCollapsibles.length && !$target.is("." + pluginName + "-expanded." + itemMenuClass) ) { $collapsible.data( pluginName ).collapse(); } }) .bind( "collapse", function( e ){ var $target = $( e.target ); var $childCollapsibles = $target.find( "." + pluginName + "-expanded." + itemMenuClass ); if( $childCollapsibles.length && $target.is("." + pluginName + "-expanded." + itemMenuClass) ) { $childCollapsibles.data( pluginName ).collapse(); $target.data( pluginName ).collapse(); } // restore tabindex if( $( e.target ).is( this ) ){ $moreBtn.attr( "tabindex", "0" ); } } ); } }); }( typeof global !== "undefined" ? global : this ));
JavaScript
0.000001
@@ -2358,16 +2358,55 @@ apsible%0A + .bind(%22navbarsort%22, initItems)%0A
e7706a84fde72f424db6db005d983e1d532552da
remove `ember-native-dom-event-dispatcher` check
ember-cli-build.js
ember-cli-build.js
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function (defaults) { let app = new EmberAddon(defaults, { // Add options here autoprefixer: { browsers: ['last 2 version', '> 10%'], cascade: false, }, snippetSearchPaths: ['tests/dummy/app'], }); if (defaults.project.findAddonByName('ember-native-dom-event-dispatcher')) { app.vendorFiles = { 'jquery.js': null }; } /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
JavaScript
0.000001
@@ -327,137 +327,8 @@ );%0A%0A - if (defaults.project.findAddonByName('ember-native-dom-event-dispatcher')) %7B%0A app.vendorFiles = %7B 'jquery.js': null %7D;%0A %7D%0A%0A /*
adcbc39db1b50960286bda60283ff792b3e0c0c4
Exclude emoji images from fingerprinting to speed up production builds
ember-cli-build.js
ember-cli-build.js
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var fingerprint, assetsHost; if (process.env.DISABLE_FINGERPRINTS) { fingerprint = false; } else { fingerprint = { extensions: ['js', 'css', 'png', 'jpg', 'gif', 'map', 'svg'] }; if (assetsHost = process.env.ASSETS_HOST) { if (assetsHost.substr(-1) !== '/') { assetsHost = assetsHost + '/' } fingerprint.prepend = assetsHost } } var app = new EmberApp({ fingerprint: fingerprint, vendorFiles: { // next line is needed to prevent ember-cli to load // handlebars (it happens automatically in 0.1.x) 'handlebars.js': null } }); app.import('vendor/babel-polyfill.js', { prepend: true }); app.import('bower_components/pusher/dist/pusher.js'); app.import('bower_components/jquery-timeago/jquery.timeago.js'); app.import('bower_components/visibilityjs/lib/visibility.core.js'); app.import('bower_components/visibilityjs/lib/visibility.timers.js'); app.import('bower_components/JavaScript-MD5/js/md5.js'); app.import('vendor/ansiparse.js'); app.import('vendor/log.js'); app.import('vendor/customerio.js'); app.import('bower_components/moment/moment.js'); return app.toTree(); };
JavaScript
0
@@ -278,16 +278,49 @@ int = %7B%0A + exclude: %5B'images/emoji'%5D,%0A ex
eb930adce58e59885c213773856bddaddb79b1e7
add babel-core devDependency
server/zip.js
server/zip.js
var Zip = require('node-zip'); var db = require('./database'); var fs = require('fs'); var path = require('path'); var mime = require('mime'); var createLoaders = require('./createLoaders'); var loadersToDependencies = require('./loadersToDependencies'); var defaultFiles = { 'webpack.config.js': fs.readFileSync(path.resolve('server', 'zip', 'webpack.config.js')).toString(), 'index.tpl.html': fs.readFileSync(path.resolve('server', 'zip', 'index.tpl.html')).toString(), 'README.md': fs.readFileSync(path.resolve('server', 'zip', 'README.md')).toString() } module.exports = function (req, res) { db.getBin(req.session.currentBin.id) .then(function (bin) { var packageJson = { "name": "webpackbin-project", "version": "1.0.0", "description": "Project boilerplate", "scripts": { "start": "webpack-dev-server --content-base build/" }, "dependencies": bin.packages, "devDependencies": Object.assign({ "html-webpack-plugin": "1.6.1", "webpack-dev-server": "1.14.1", "webpack": "1.12.13" }, loadersToDependencies(bin.loaders)), "author": "WebpackBin", "license": "ISC" }; var loaders = createLoaders(bin.loaders).map(function (loader) { loader.test = '$$' + loader.test.toString() + '$$'; if (loader.exclude) { loader.exclude = '$$' + loader.exclude.toString() + '$$'; } return loader; }); var loadersString = JSON.stringify(loaders, null, 2); var findRegexps = /\$\$(.*?)\$\$/g; var matches = loadersString.match(findRegexps); loadersString = (matches || []).reduce(function (loadersString, match) { return loadersString.replace('"' + match + '"', match.replace(/\$\$/g, '').replace('\\\\', '\\')); }, loadersString); var webpackConfig = defaultFiles['webpack.config.js'].replace( '$LOADERS$', loadersString ); if (bin.loaders.babel) { packageJson.devDependencies['babel-loader'] = '6.2.4'; if (bin.loaders.babel.stage0) { packageJson.devDependencies['babel-preset-stage-0'] = '6.5.0'; } if (bin.loaders.babel.es2015) { packageJson.devDependencies['babel-preset-es2015'] = '6.6.0'; } if (bin.loaders.babel.react) { packageJson.devDependencies['babel-preset-react'] = '6.5.0'; } } if (bin.loaders.css) { packageJson.devDependencies['style-loader'] = '0.13.0'; packageJson.devDependencies['css-loader'] = '0.23.1'; if (bin.loaders.css.less) { packageJson.devDependencies['less-loader'] = '2.2.2'; } if (bin.loaders.css.sass) { packageJson.devDependencies['sass-loader'] = '3.1.2'; } } if (bin.loaders.typescript) { packageJson.devDependencies['ts-loader'] = '0.8.1'; packageJson.devDependencies['typescript'] = '1.8.7'; } if (bin.loaders.coffeescript) { packageJson.devDependencies['coffee-loader'] = '0.7.2'; } if (bin.loaders.coffeescript) { packageJson.devDependencies['coffee-loader'] = '0.7.2'; } var zip = new Zip(); bin.files.forEach(function (file) { zip.file('src/' + file.name, file.content) }); zip.file('package.json', JSON.stringify(packageJson, null, 2)); zip.file('README.md', defaultFiles['README.md']); zip.file('src/index.tpl.html', defaultFiles['index.tpl.html']); zip.file('webpack.config.js', webpackConfig); var data = zip.generate({base64:false,compression:'DEFLATE'}); res.setHeader("Content-Type", mime.lookup('project.zip')); res.setHeader("Content-Length", data.length); res.send(new Buffer(data, 'binary')); }) .catch(function (err) { console.log(err); res.sendStatus(500); }); };
JavaScript
0
@@ -2064,16 +2064,77 @@ 6.2.4';%0A + packageJson.devDependencies%5B'babel-core'%5D = '6.9.1';%0A
ac30e95b13eb207d4ad870e233f4a8419d47df63
update file /application.js
application.js
application.js
var mbaasApi = require('fh-mbaas-api'); var express = require('express'); var mbaasExpress = mbaasApi.mbaasExpress(); var cors = require('cors'); var bodyParser = require('body-parser'); var app = express(); // Enable CORS for all requests app.use(cors()); // Note: the order which we add middleware to Express here is important! app.use('/mbaas', mbaasExpress.mbaas); // allow serving of static files from the public directory app.use(express.static(__dirname + '/public')); // Note: important that this is added just before your own Routes app.use(mbaasExpress.fhmiddleware()); app.use('/sys', mbaasExpress.sys([])); app.use('/hello', require('./lib/hello.js')()); app.use(bodyParser()); app.use('/auth', require('./lib/auth.js')()); // Important that this is last! app.use(mbaasExpress.errorHandler()); var port = process.env.FH_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8001; var host = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'; app.listen(port, host, function() { console.log("App started at: " + new Date() + " on port: " + port); });
JavaScript
0.000002
@@ -327,16 +327,55 @@ ortant!%0A +app.use('/sys', mbaasExpress.sys(%5B%5D));%0A app.use( @@ -622,46 +622,8 @@ ));%0A -app.use('/sys', mbaasExpress.sys(%5B%5D)); %0Aapp
1770ab21470b058036c7a7a4f0aebb910e90e466
put print outside
src/commands/man/index.js
src/commands/man/index.js
const Discord = require("discord.js"); const MSS = require("./../../functions/"); const config = require("./../../config.json"); const meta = require("./meta.json"); const fs = require("fs"); var commands = []; //Construct the "full" list fs.readdir("./commands/", function(err, items) { var print = "\n`@MSS man <command>`\n```\n"; items.forEach(function(item) { var file = item.replace(/['"]+/g, ""); commands[file] = require(`./../${file}/meta.json`); }); print += items.join(`, `); print += "```"; }); module.exports = function manpages(message) { let input = message.content.replace(/\n/g, " ").split(" "); //Return the usage of the man command if no attributes were given if(!input[2]) { message.reply(`${meta[message.data.lang] && meta[message.data.lang].message_choose_man || "message_choose_man"} ${print}`); return false; } //Return if it doesn't exist if (!commands[input[2]]) { MSS.msg.react(message, false, "link"); message.reply(`${meta[message.data.lang] && meta[message.data.lang].err_not_found || "err_not_found"} ${input[1]}`); return false; } var embed = new Discord.RichEmbed() .setTitle(commands[input[2]][message.data.lang].name) .setAuthor(meta[message.data.lang] && meta[message.data.lang].message_man_pages || "message_man_pages", "http://moustacheminer.com/img/mss.png") .setColor("#00AE86") .setDescription(commands[input[2]][message.data.lang].description) .setFooter("MSS-Discord, " + config.MSS.version, "") .setTimestamp() .setURL(commands[input[2]][message.data.lang].url); commands[input[2]][message.data.lang].examples.forEach(function(element) { embed.addField(input[2] + " " + element.var, element.description); }); message.channel.send(input[2], { embed: embed, disableEveryone: true }); }
JavaScript
0.000002
@@ -203,16 +203,61 @@ ds = %5B%5D; +%0Avar print = %22%5Cn%60@MSS man %3Ccommand%3E%60%5Cn%60%60%60%5Cn%22; %0A%0A//Cons @@ -331,55 +331,8 @@ ) %7B%0A -%09var print = %22%5Cn%60@MSS man %3Ccommand%3E%60%5Cn%60%60%60%5Cn%22;%0A%0A %09ite
91f2c22d7459a6215616995f4548933757f997ad
implement nextseen and many fixes
src/commands/workhours.js
src/commands/workhours.js
import { request, findEmployee, getWeekday, clockEmoji } from '../utils'; import { capitalize } from 'lodash'; import humanDate from 'date.js'; import moment from 'moment'; const printHours = hours => { if (!hours.length) { return 'Oops! I got nothing to show! 😶'; } let output = (hours.length > 1) ? ':timer_clock: Your working hours plan is:\n' : `:timer_clock: Your working hours plan for *${hours[0].weekday}* is:\n`; output += hours.map((hour, id) => `#${id + 1}- *${capitalize(hour.weekday)}* from ${clockEmoji(hour.start)}` + ` *${hour.start}* to ${clockEmoji(hour.end)} *${hour.end}*`).join('\n'); return output; }; const setEmployeeWorkhours = async (uri, userId, dayWorkhours) => { // delete previous hours await request('delete', `${uri}/employee/${userId}/workhours`); // set workhours return await* dayWorkhours.map(async day => { const [startHours, startMinutes] = day.start.split(':'); const start = new Date(); start.setHours(startHours); start.setMinutes(startMinutes || 0); start.setSeconds(0); const [endHours, endMinutes] = day.end.split(':'); const end = new Date(); end.setHours(endHours); end.setMinutes(endMinutes || 0); end.setSeconds(0); const timeFormat = 'HH:mm:ss'; return await request('post', `${uri}/employee/${userId}/workhour`, null, { weekday: day.day, start: moment(start).format(timeFormat), end: moment(end).format(timeFormat) }); }); }; export default async (bot, uri) => { bot.listen(/(?:workhours?|wh)\s?(?!.*\b(set)\b)(.+)?/i, async message => { const [, time] = message.match; console.log(message.match); const employee = await findEmployee(uri, bot, message); let workHours; const weekdays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; if (weekdays.includes(time)) { workHours = await request('get', `${uri}/employee/${employee.id}` + `/workhours?weekday=${time}`); return message.reply(printHours(workHours)); } if (!time) { workHours = await request('get', `${uri}/employee/${employee.id}/workhours`); return message.reply(printHours(workHours)); } try { const date = humanDate(time); if (date instanceof Date) { const weekday = getWeekday(date); workHours = await request('get', `${uri}/employee/${employee.id}` + `/workhours?weekday=${weekday}`); return message.reply(printHours(workHours)); } } catch (e) { bot.log.verbose(e); return message.reply(`I didn't understand what you mean by "${time}"`); } }); bot.listen(/(?:workhours?|wh)\s(?:set)\s(.+)((?:\n.+)*)/i, async message => { // eslint-disable-line let [usernames, data] = message.match; const weeekdayHoursRegex = /((sun|sat|mon|tue|wed|thu|fri)\s(.*)\n*)/gi; if (!weeekdayHoursRegex.test(data)) { return message.reply('Invalid weekdays or hours format.'); } // weekday - workhours per item, remove empty ones data = data.split('\n').filter(item => !!item); const invalidDays = []; const days = []; for (const dayWorkhour of data) { const checkDayRegex = /(sun|sat|mon|tue|wed|thu|fri)\s(?:((\d{1,2})|(\d{1,2}:\d{1,2}))\s?(?:-|to|\s|,))\s?(?:((\d{1,2}:\d{1,2})|(\d{1,2})))/gi; // eslint-disable-line if (checkDayRegex.test(dayWorkhour)) { // JS regex problem: http://stackoverflow.com/questions/4724701/regexp-exec-returns-null-sporadically const cdr = /(sun|sat|mon|tue|wed|thu|fri)\s(?:((\d{1,2})|(\d{1,2}:\d{1,2}))\s?(?:-|to|\s|,))\s?(?:((\d{1,2}:\d{1,2})|(\d{1,2})))/gi; // eslint-disable-line const result = cdr.exec(dayWorkhour); // group 2,3 matches only hour formats (8 - 16) // group 4,5 matches hour and minutes format (8:30 - 16:50) days.push({ day: result[1], start: result[4] || result[2], end: result[5] || result[3] }); } else { invalidDays.push(dayWorkhour); } } usernames = usernames.replace(/(?:@|\s)/gi, '').split(','); const invalidUsers = []; const users = []; let usersMsg = ''; let invalidUsersMsg = ''; let daysMsg = ''; let invalidDaysMsg = ''; for (const username of usernames) { const user = await request('get', `${uri}/employee?username=${username}`); if (user) { users.push(user); await setEmployeeWorkhours(uri, user.id, days); } else { invalidUsers.push(username); } } // print valid users if (users.length) { usersMsg = ` :white_check_mark: The following users workhours are changed: `; usersMsg += users.reduce((prev, curr, currIndex) => { if (currIndex - 1 === users.length) { return `${prev} and @${curr.username}. `; } if (currIndex === 0) { return `@${curr.username}`; } return `${prev}, @${curr.username}`; }, usersMsg); } // print invalid users if (invalidUsers.length) { invalidUsersMsg += ` :no_entry: The following usernames are invalid: `; invalidUsersMsg += invalidUsers.reduce((prev, curr, currIndex) => { if (currIndex - 1 === invalidUsers.length) { return `${prev} and ${curr}. `; } if (currIndex === 0) { return `${curr}`; } return `${prev}, ${curr}`; }, invalidUsersMsg); } // print valid days if (days.length) { daysMsg = ` :white_check_mark: The following days are changed for the users: `; daysMsg += days.reduce((prev, curr, currIndex) => { if (currIndex - 1 === days.length) { return `${prev} and ${curr.day}. `; } if (currIndex === 0) { return `${curr.day}`; } return `${prev}, ${curr.day}`; }, daysMsg); } // print invalid days if (invalidDays.length) { invalidDaysMsg += ` :no_entry: The following days or times are invalid: `; invalidDaysMsg += invalidDays.reduce((prev, curr, currIndex) => { if (currIndex - 1 === invalidDays.length) { return `${prev} and ${curr}. `; } if (currIndex === 0) { return `${curr}`; } return `${prev}, ${curr}`; }, invalidDaysMsg); } message.reply(`${usersMsg}${daysMsg} ${invalidUsersMsg}${invalidDaysMsg}`); }, { permissions: ['admin', 'human-resource'] }); };
JavaScript
0.000001
@@ -1636,40 +1636,8 @@ ch;%0A - console.log(message.match);%0A
d57c965cf1fc9ec8a8386e596a21cd668af1e818
clear list on every refresh
client/js/Panels/Grid/GridPanelSetsControl.js
client/js/Panels/Grid/GridPanelSetsControl.js
"use strict"; define(['logManager', 'clientUtil', 'js/Constants', 'js/NodePropertyNames'], function (logManager, util, CONSTANTS, nodePropertyNames) { var GridPanelSetsControl; GridPanelSetsControl = function (options) { var self = this; this._client = options.client; this._panel = options.panel; this._dataGridWidget = options.widget; this._dataGridWidget._rowDelete = false; this._dataGridWidget._rowEdit = false; this._setContainerID = null; this._logger = logManager.create("GridPanelSetsControl"); this._selectedObjectChanged = function (__project, nodeId) { self.selectedObjectChanged(nodeId); }; this._logger.debug("Created"); }; GridPanelSetsControl.prototype.selectedObjectChanged = function (nodeId) { var self = this; this._logger.debug("SELECTEDOBJECT_CHANGED nodeId '" + nodeId + "'"); //remove current territory patterns if (this._territoryId) { this._client.removeUI(this._territoryId); this._dataGridWidget.clear(); } this._setContainerID = nodeId; if (this._setContainerID || this._setContainerID === CONSTANTS.PROJECT_ROOT_ID) { //put new node's info into territory rules this._selfPatterns = {}; this._selfPatterns[nodeId] = { "children": 0 }; this._territoryId = this._client.addUI(this, function (events) { self._processSetContainer(); }); //update the territory this._client.updateTerritory(this._territoryId, this._selfPatterns); } }; GridPanelSetsControl.prototype.destroy = function () { this.detachClientEventListeners(); this._client.removeUI(this._territoryId); }; GridPanelSetsControl.prototype._processSetContainer = function () { var setContainer = this._client.getNode(this._setContainerID), setDescriptor, setNames, i, set, setMembers, j, memberRegistryNames, k, title = " (" + this._setContainerID + ")"; this._insertList = []; if (setContainer) { title = (setContainer.getAttribute(nodePropertyNames.Attributes.name) || 'N/A') + title; //get set names //get set members //get set registries setNames = setContainer.getSetNames(); i = setNames.length; while (i--) { set = setNames[i]; setMembers = setContainer.getMemberIds(set); //fill set names and member list setDescriptor = {"ID": set, "Members": setMembers }; j = setMembers.length; while (j--) { //get set registry memberRegistryNames = setContainer.getMemberRegistryNames(set, setMembers[j]); k = memberRegistryNames.length; while (k--) { var setMemberRegName = /*set + '_' + */memberRegistryNames[k]; setDescriptor[setMemberRegName] = setDescriptor[setMemberRegName] || []; var keyValue = setMembers[j] + ': ' + JSON.stringify(setContainer.getMemberRegistry(set, setMembers[j], memberRegistryNames[k])); setDescriptor[setMemberRegName].push(keyValue); } } this._insertList.push(setDescriptor); } this._dataGridWidget.insertObjects(this._insertList); } this._panel.setTitle(title); }; GridPanelSetsControl.prototype.attachClientEventListeners = function () { this.detachClientEventListeners(); this._client.addEventListener(this._client.events.SELECTEDOBJECT_CHANGED, this._selectedObjectChanged); }; GridPanelSetsControl.prototype.detachClientEventListeners = function () { this._client.removeEventListener(this._client.events.SELECTEDOBJECT_CHANGED, this._selectedObjectChanged); }; return GridPanelSetsControl; });
JavaScript
0
@@ -2322,16 +2322,55 @@ + %22)%22;%0A%0A + this._dataGridWidget.clear();%0A%0A
ea8089c8d5ee06a4286cbbabbd12f6f1e43d9ab7
update karma
mirrorgate-dashboard/karma.conf.js
mirrorgate-dashboard/karma.conf.js
/* * Copyright 2017 Banco Bilbao Vizcaya Argentaria, S.A. * * 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. */ // Karma configuration // Generated on Wed Jun 24 2015 17:14:26 GMT+0200 (Romance Daylight Time) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine', 'sinon'], // list of files / patterns to load in the browser files: [ 'bower_components/d3/d3.min.js', 'bower_components/jquery/dist/jquery.slim.min.js', 'bower_components/rivets/dist/rivets.bundled.min.js', 'bower_components/moment/min/moment.min.js', 'bower_components/moment-weekday-calc/build/moment-weekday-calc.min.js', 'bower_components/sockjs-client/dist/sockjs.min.js', 'bower_components/jQuery.dotdotdot/dist/jquery.dotdotdot.js', 'node_modules/lodash/lodash.min.js', 'node_modules/karma-read-json/karma-read-json.js', 'test/*.js', 'src/js/core/utils.js', 'src/js/components/BaseComponent.js', 'src/js/components/DashboardComponent.js', 'src/js/components/Tile.js', 'src/js/core/Event.js', 'src/js/core/Clock.js', 'src/js/core/Timer.js', 'src/js/core/Service.js', 'src/js/core/request.js', 'src/js/core/serversideevent.js', 'src/**/*.spec.*', 'src/components/**/*.*', {pattern: 'test/**/*', included: false}, {pattern: 'dist/img/**/*.*', included: false, served: true}, {pattern: 'dist/bower_components/**/*.css', included: false, served: true}, {pattern: 'dist/css/*.css', included: false, served: true}, {pattern: 'bower_components/*/fonts/**/*.*', included: false, served: true} ], // list of files to exclude exclude: [ 'src/js/app.js' ], proxies: { '/css/': '/base/dist/css/', '/img/': '/base/dist/img/', '/node_modules/': '/base/node_modules/', '/bower_components/': '/base/dist/bower_components/', '/test/': '/base/test/' }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // coverage reporter generates the coverage // karma server port port: 9876, hostname: process.env.HOSTNAME || 'localhost', // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_DEBUG, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // custome launch for WebDriver customLaunchers: { 'chrome': { base: 'WebDriver', config: { port: process.env.SELENIUM_PORT || 4444, hostname: process.env.SELENIUM_HOST || 'localhost' }, browserName: 'chrome' } }, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['chrome'], //An browser with WebGLRenderer is needed to pass test // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity, // No activity browser Timeout browserNoActivityTimeout: 10000 }); };
JavaScript
0.000001
@@ -1941,19 +1941,19 @@ ore/ -s +S erver -sidee +SentE vent
09c025803cd921de81d9025c65745f3f85acd1f6
Add submissionNumber to search string
model/business-process-new/base.js
model/business-process-new/base.js
// Base BusinessProcess model 'use strict'; var memoize = require('memoizee/plain') , defineStringLine = require('dbjs-ext/string/string-line') , defineUInteger = require('dbjs-ext/number/integer/u-integer') , defineUrl = require('dbjs-ext/string/string-line/url') , _ = require('mano').i18n.bind("Model: Business Process") , defineBusinessProcessBase = require('../lib/business-process-base') , defineNestedMap = require('../lib/nested-map') , defineStatusLog = require('../lib/status-log'); module.exports = memoize(function (db/*, options*/) { var StringLine = defineStringLine(db) , Url = defineUrl(db) , UInteger = defineUInteger(db) , StatusLog = defineStatusLog(db) , BusinessProcessBase = defineBusinessProcessBase(db) , BusinessProcess , options = Object(arguments[1]); defineNestedMap(db); BusinessProcess = BusinessProcessBase.extend(options.className || 'BusinessProcess', { // General label of business process type // It's not specific per business process, but should provide general info as: // "Merchant registration", "Company registration" etc. label: { type: StringLine }, // Name of businessProcess // Usually computed from other properties businessName: { type: StringLine }, // URL at which archive of files related to given business process // is accessible filesArchiveUrl: { type: Url }, submissionNumber: { type: db.Object, nested: true }, // Whether registration is made online // It may be overriden to false in case we import businessProces // which not processed electronically. // It has its use in "business update" applications where we allow updates // of old registrations done at the counter isFromEregistrations: { type: db.Boolean, value: true, label: _("Has registration been made online?") }, // String over which business processes can be searched // through interface panel (computed value is later indexed by persistence engine) // Below implementation just provides businessName, but it also shows // how many properties can be reliably grouped into one result string for search searchString: { type: db.String, value: function () { var arr = []; if (this.businessName) arr.push(this.businessName.toLowerCase()); return arr.join('\x02'); } } }); BusinessProcess.prototype.submissionNumber.defineProperties({ value: { type: StringLine, value: function () { return this.number; } }, number: { type: UInteger, value: 0 }, toString: { value: function (opts) { return this.value; } } }); BusinessProcess.prototype.defineNestedMap('statusLog', { itemType: StatusLog, cardinalPropertyKey: 'label' }); return BusinessProcess; }, { normalizer: require('memoizee/normalizers/get-1')() });
JavaScript
0
@@ -2055,163 +2055,8 @@ ne)%0A -%09%09// Below implementation just provides businessName, but it also shows%0A%09%09// how many properties can be reliably grouped into one result string for search%0A %09%09se @@ -2122,16 +2122,66 @@ arr = %5B%5D +, submissionNumber = String(this.submissionNumber) ;%0A%09%09%09if @@ -2243,16 +2243,88 @@ ase());%0A +%09%09%09if (submissionNumber) arr.push(this.submissionNumber.toLowerCase());%0A %09%09%09retur @@ -2467,20 +2467,17 @@ ion () %7B -%0A%09%09%09 + return t @@ -2487,19 +2487,17 @@ .number; -%0A%09%09 + %7D %7D,%0A%09%09n @@ -2571,20 +2571,17 @@ (opts) %7B -%0A%09%09%09 + return t @@ -2590,19 +2590,17 @@ s.value; -%0A%09%09 + %7D %7D%0A%09%7D);
30f6d93725bc472bf8cc35741182e3819a6886b9
Add catch() to download chain
assets/main.js
assets/main.js
$(function() { 'use strict'; var client = ZAFClient.init(), attachments = [], // attachments is "global" so we don't have to get the list repeatedly COMMENT_PATH = "ticket.comments", $container = $('#container'), $download = $('#download'), $list = $('#list'), $message = $('#message'), $status = $('#status'), $progress = $('#progress'), $interface = $('#interface'), $expand = $('#expand') ; client.on('app.registered', function(event) { $progress.hide(); findAttachments() .then(function() { attachments.sort(defaultSort); displayAttachments(); $download.show(); }) .catch(function(err) { message(err); $download.hide(); }) .then(function() { $container.show(); }); }); client.on('ticket.comments.changed', function(event) { // console.log(event); }); $download.on("click", function() { hide($interface); show($status); status("Fetching attachments..."); downloadAttachments() .then(function() { status("ZIP done!"); setTimeout(function() { hide($status); hide($progress); $progress.percent = 0; show($interface); }, 2000); }); }); $message.on("click", function() { $list.toggle(0, function() { // expand the list, and... client.invoke('resize', { height: $container.css("height") }); // ...expand the app so you can see the list }); }); function defaultSort(a, b) { return a.filename > b.filename ? 1 : a.filename < b.filename ? -1 : 0; } function findAttachments() { return client.get(COMMENT_PATH) .then(function(response) { attachments = getAllAttachments(response); return new Promise(function(resolve, reject) { var attachmentsFound = $.isArray(attachments) && attachments.length > 0; layout({attachmentsFound: attachmentsFound}); if (!attachmentsFound) { reject("No attachments found in this ticket."); } else { resolve(); } }); }); } function getAllAttachments(response) { var comments = $.makeArray(response[COMMENT_PATH]); var allAttachments = $.map(comments, function(comment) { return [] .concat(comment.imageAttachments) .concat(comment.nonImageAttachments); }); return deduplicate(allAttachments); } function layout(prefs) { var attachmentsFound = prefs.attachmentsFound; var height = attachmentsFound ? "4rem" : "2rem"; client.invoke('resize', { height: height }); } function displayAttachments() { var html = $.map(attachments, function(attachment) { return (tmpl("attachment-link", attachment)); }); $list .append(html) .toggle(); message(tmpl("attachment-message", attachments.length)); } function makeZip() { var zip = new JSZip(); $.each(attachments, function(index, attachment) { zip.file( attachment.filename, urlToPromise(attachment.contentUrl), { binary:true } ); }); return zip; } function downloadAttachments() { var first = true; return makeZip() .generateAsync({type:"blob"}, function updateCallback(metadata) { if (first) { $progress.show(); first = false; } var percent = metadata.percent; $progress.percent = percent; status("Making ZIP: " + percent.toFixed(2) + "%"); }) .then(function (blob) { client.context().then(function(context) { var date = new Date(); var o = { id: context.ticketId, year: date.getFullYear(), month: zeroPad(date.getMonth()+1), day: zeroPad(date.getDate()), hour: zeroPad(date.getHours()), minute: zeroPad(date.getMinutes()), second: zeroPad(date.getSeconds()), millis: date.getMilliseconds() } var filename = tmpl("attachment-filename", o); saveAs(blob, filename); }) }); } function zeroPad(n) { return ("0" + n).slice(-2); } function message(message) { display($message, message); } function status(message) { display($status, message); } function display($element, message) { $element.html(message); } function show($element) { $element.show(600); } function hide($element) { $element.hide(600); } /** * Set the width of the colored part of the progress bar. */ Object.defineProperty($progress, "percent", { set: function(percent) { this .find("#progress-bar") .attr('aria-valuenow', percent) .width(percent+"%"); } }); /** * Fetch the content and return the associated promise. * @param {String} url the url of the content to fetch. * @return {Promise} the promise containing the data. */ function urlToPromise(url) { return new Promise(function(resolve, reject) { JSZipUtils.getBinaryContent(url, function (err, data) { if(err) { reject(err); } else { resolve(data); } }); }); } /** Append a string to filename before the extension. */ function appendStringToFilename(filename, string) { var dotIndex = filename.lastIndexOf("."); if (dotIndex == -1) { return filename + string; } else { return filename.substring(0, dotIndex) + string + filename.substring(dotIndex); } } // Modified from // https://stackoverflow.com/a/34972148/1110820 // Takes an array of attachments and appends numbers // to the filenames to get rid of duplicates. // (Like Windows filenames.) function deduplicate(attachments) { var c = {}, t = function(x, n) { return appendStringToFilename(x, "(" + n + ")"); }; return attachments.map(function(attachment) { var n = c[attachment.filename] || 0; c[attachment.filename] = n + 1; if (!n) { return attachment; } while (c[t(attachment.filename, n)]) { n++; } c[t(attachment.filename, n)] = 1; attachment.filename = t(attachment.filename, n); return attachment; }); } });
JavaScript
0
@@ -1183,33 +1183,104 @@ %09%7D, 2000);%0D%0A%09%09%7D) -; +%0D%0A%09%09.catch(function(err) %7B%0D%0A%09%09%09message(err);%0D%0A%09%09%09show($interface);%0D%0A%09%09%7D) %0D%0A%09%7D);%0D%0A%09%0D%0A%09$mes
29d91d171aa10a9859b9ece4589285245a67c1d5
Handle errors, and turn off after delay
pi-alarm.js
pi-alarm.js
var http = require('http'); var gpio = require('pi-gpio'); var currentState = false; var actuator = function(outputValue) { console.log('Switching relay: '+outputValue); currentState = outputValue; gpio.open(11, "output", function(err) { gpio.write(11, outputValue, function(err) { gpio.close(11); }); }); }; var doPollingReq = function() { console.log('Starting request...'); var pollingReqOpts = { host: process.env.SERVER_HOSTNAME || 'localhost', port: process.env.SERVER_PORT || 3000, path: '/alarm', method: 'GET' }; var pollingReq = http.request(pollingReqOpts, function(res) { console.log('Request being created...'); res.on('data', function(data) { console.log('Got data: '+data); var objData = JSON.parse(data); if (objData && objData.value !== undefined) { actuator(objData.value); } }); res.on('close', doPollingReq); res.on('end', doPollingReq); }); pollingReq.end(); }; setImmediate(doPollingReq);
JavaScript
0
@@ -322,16 +322,127 @@ ;%0A %7D);%0A + if (outputValue) %7B%0A // Turn off after 5sec%0A setTimeout(actuator, proces.env.DELAY %7C%7C 5000, false);%0A %7D%0A %7D;%0A%0Avar @@ -1062,16 +1062,51 @@ ngReq);%0A + res.on('error', doPollingReq);%0A %7D);%0A
9ceab2c3f51e1fcf97627fb2e32f4a416d048bd6
load `node-webkit` binary module
node_modules/mongodb/node_modules/bson/ext/index.js
node_modules/mongodb/node_modules/bson/ext/index.js
var bson = null; // Load the precompiled win32 binary if(process.platform == "win32" && process.arch == "x64") { bson = require('./win32/x64/bson'); } else if(process.platform == "win32" && process.arch == "ia32") { bson = require('./win32/ia32/bson'); } else { bson = require('../build/Release/bson'); } exports.BSON = bson.BSON; exports.Long = require('../lib/bson/long').Long; exports.ObjectID = require('../lib/bson/objectid').ObjectID; exports.DBRef = require('../lib/bson/db_ref').DBRef; exports.Code = require('../lib/bson/code').Code; exports.Timestamp = require('../lib/bson/timestamp').Timestamp; exports.Binary = require('../lib/bson/binary').Binary; exports.Double = require('../lib/bson/double').Double; exports.MaxKey = require('../lib/bson/max_key').MaxKey; exports.MinKey = require('../lib/bson/min_key').MinKey; exports.Symbol = require('../lib/bson/symbol').Symbol; // Just add constants tot he Native BSON parser exports.BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; exports.BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; exports.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; exports.BSON.BSON_BINARY_SUBTYPE_UUID = 3; exports.BSON.BSON_BINARY_SUBTYPE_MD5 = 4; exports.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
JavaScript
0.000002
@@ -223,32 +223,37 @@ bson = require( +%0A './win32/ia32/bs @@ -250,25 +250,88 @@ 32/ia32/ -bson'); +' +%0A (process.versions%5B'node-webkit'%5D ? 'nw/' : '') +%0A 'bson'%0A ); %0A%7D else
0965a042a587c716048af96f59d20c62c6c2a569
Update Content.js
src/components/Content.js
src/components/Content.js
/** * The description / explanation of the chart and table, explains * data source, data aggregation, trend calculation, ... * Compiles markdown into html, content.md -> html * @author Fabian Beuke <mail@beuke.org> * @license AGPL-3.0 */ export default function Content() { return ( <div style={{ margin: "auto", marginTop: "40px", marginBottom: "40px", maxWidth: 760, textAlign: "justify", fontSize: 13, }} > <h4 id="githut-2-0">GITHUT 2.0</h4> <p class="responsivity-mobile-modif"> GitHut 2.0 is an attempt to continue the{" "} <a href="http://githut.info">githut.info</a> project. GitHub is the largest code host in the world, with 40 million users and more than 190 million repositories as of January 2020. By analyzing how languages are used in GitHub it&#39;s possible to understand the popularity of programming languages among developers and to discover the unique characteristics of each language. GitHub provides a public{" "} <a href="//developer.github.com/v3/">API</a> to interact with its huge dataset of events and interaction with the hosted repositories. The{" "} <a href="//githubarchive.org/">GitHub Archive</a> project goes one step further by aggregating and storing the API data over time. The quantitative data used in GitHut 2.0 is collected from the GitHub Archive dataset via{" "} <a href="//developers.google.com/bigquery/">Google BigQuery</a>. </p> <p class="responsivity-mobile-modif"> The language percentage distribution in the line chart shows the top 10 (or manually selected) languages since 2012/Q2. The ranking table shows the top 50 languages of the last quarter. The percentage values are the actual fractions of pull requests, pushes, stars or issues in relation to the top 50 languages in the table. The YoY change shows the difference in percentage compared to the same time period last year. The YoY trend arrows indicate the change in ranking. Two arrows up/down stands for more than three ranks up/down within one year. No arrow indicates that nothing has changed and one arrow fills the gap. Please note that it is possible that the ranking shown in the table does not match the chart ranking, since they are calculated over a different time period (quarter vs. full history). Please also note that there is not enough data available in the GitHub Archive dataset to calculate a statistical accurate ranking table or chart for any time period before 2012/Q2. </p> <h4 id="related-work">Related Work</h4> <ul> <li class="responsivity-mobile-modif"> <a href="//tiobe.com/tiobe-index/"> TIOBE Programming Community Index </a>{" "} is a measure of popularity of programming languages, created and maintained by the TIOBE Company based in Eindhoven, the Netherlands. </li> <li class="responsivity-mobile-modif"> <a href="//redmonk.com/sogrady/2016/07/20/language-rankings-6-16/"> The RedMonk Programming Language Rankings </a>{" "} are derived from a correlation of programming traction on GitHub and Stack Overflow. </li> <li class="responsivity-mobile-modif"> <a href="//pypl.github.io/PYPL.html"> The PYPL PopularitY of Programming Language Index </a>{" "} is created by analyzing how often language tutorials are searched on Google. </li> <li class="responsivity-mobile-modif"> <a href="//langpop.corger.nl"> Programming Language Popularity Chart </a>{" "} shows GitHub (lines changed) and StackOverflow (tags) ratio for programming languages. </li> </ul> </div> ) }
JavaScript
0.000001
@@ -610,32 +610,36 @@ %3Cp class +Name =%22responsivity-m @@ -644,32 +644,32 @@ -mobile-modif%22%3E%0A - @@ -1829,24 +1829,28 @@ %3Cp class +Name =%22responsivi @@ -3231,32 +3231,36 @@ %3Cli class +Name =%22responsivity-m @@ -3650,32 +3650,36 @@ %3Cli class +Name =%22responsivity-m @@ -4040,32 +4040,36 @@ %3Cli class +Name =%22responsivity-m @@ -4375,32 +4375,32 @@ %3C/li%3E%0A - @@ -4408,16 +4408,20 @@ li class +Name =%22respon
46ee014d135ecdf27cf81ca07342562ff46fa0e5
update resume with material-ui
src/components/Landing.js
src/components/Landing.js
import React, { Component } from 'react'; import About from './About'; import Projects from './Projects'; import Skills from './Skills'; class Landing extends Component { render() { return ( <div className="container"> <div className="banner-text"> <h1>CARLO FRANCISCO</h1> <h6>FULL STACK DEVELOPER</h6> </div> <div className="row icon-list"> <div className="col s6 m3 l3"> <figure className="icon"> <a className="modal-trigger" href="#modal1"> <img src={require('../images/about.svg')} alt="about" width="40%" /> <figcaption>about</figcaption> </a> </figure> <About /> </div> <div className="col s6 m3 l3"> <figure className="icon"> <a className="modal-trigger" href="#modal2"> <img src={require('../images/projects.svg')} alt="projects" width="40%" /> <figcaption>projects</figcaption> </a> </figure> <Projects /> </div> <div className="col s6 m3 l3"> <figure className="icon"> <a className="modal-trigger" href="#modal3"> <img src={require('../images/skills.svg')} alt="skills" width="40%" /> <figcaption>skills</figcaption> </a> </figure> <Skills /> </div> <div className="col s6 m3 l3"> <figure className="icon"> <a href="https://drive.google.com/file/d/1piQYkvEQLyMP-RQ0ajbD3CD5P8CZK8d3/view?usp=sharing" rel="noopener noreferrer" target="_blank" > <img src={require('../images/resume.svg')} alt="resume" width="40%" /> <figcaption>resume</figcaption> </a> </figure> </div> </div> <div className="row social-links"> <div className="col s4 m3 l4"> <a href="https://www.linkedin.com/in/cfrancisco726" rel="noopener noreferrer" target="_blank" > <i className="fab fa-linkedin icon" aria-hidden="true" /> </a> </div> <div className="col s4 m4 l4"> <a href="https://github.com/cfrancisco726" rel="noopener noreferrer" target="_blank" > <i className="fab fa-github-square icon" aria-hidden="true" /> </a> </div> <div className="col s4 m4 l4"> <a href="mailto:cfrancisco726@gmail.com" rel="noopener noreferrer" target="_top" > <i className="fas fa-envelope icon" aria-hidden="true" /> </a> </div> </div> </div> ); } } export default Landing;
JavaScript
0
@@ -1491,40 +1491,40 @@ /d/1 -piQYkvEQLyMP-RQ0ajbD3CD5P8CZK8d3 +K9Mid4L1DPGrLJSvyj_1bOX9VvHOfDgz /vie
8d671f59658e368a2c117d839866e843bf72f7fe
Improve logging on mongoose
app/src/app.js
app/src/app.js
const config = require('config'); const logger = require('logger'); const Koa = require('koa'); const koaLogger = require('koa-logger'); const koaQs = require('koa-qs'); const koaBody = require('koa-body'); const loader = require('loader'); const koaSimpleHealthCheck = require('koa-simple-healthcheck'); const koaValidate = require('koa-validate'); const ErrorSerializer = require('serializers/errorSerializer'); const sleep = require('sleep'); const mongoose = require('mongoose'); const ctRegisterMicroservice = require('ct-register-microservice-node'); const cronLoader = require('cronLoader'); const mongooseOptions = require('../../config/mongoose'); const mongoUri = process.env.MONGO_URI || `mongodb://${config.get('mongodb.host')}:${config.get('mongodb.port')}/${config.get('mongodb.database')}`; let retries = 10; if (config.get('logger.level') === 'debug') { mongoose.set('debug', true); } async function init() { return new Promise((resolve, reject) => { async function onDbReady(mongoConnectionError) { if (mongoConnectionError) { if (retries >= 0) { retries--; logger.error(`Failed to connect to MongoDB uri ${mongoUri}, retrying...`); sleep.sleep(5); mongoose.connect(mongoUri, mongooseOptions, onDbReady); } else { logger.error('MongoURI', mongoUri); logger.error(mongoConnectionError); reject(new Error(mongoConnectionError)); } return; } // instance of koa const app = new Koa(); // if environment is dev then load koa-logger if (process.env.NODE_ENV === 'dev') { logger.debug('Use logger'); app.use(koaLogger()); } koaQs(app, 'extended'); app.use(koaBody({ multipart: true, jsonLimit: '50mb', formLimit: '50mb', textLimit: '50mb' })); app.use(koaSimpleHealthCheck()); // catch errors and send in jsonapi standard. Always return vnd.api+json app.use(async (ctx, next) => { try { await next(); } catch (inErr) { let error = inErr; try { error = JSON.parse(inErr); } catch (e) { logger.debug('Could not parse error message - is it JSON?: ', inErr); error = inErr; } ctx.status = error.status || ctx.status || 500; if (ctx.status >= 500) { logger.error(error); } else { logger.info(error); } ctx.body = ErrorSerializer.serializeError(ctx.status, error.message); if (process.env.NODE_ENV === 'prod' && ctx.status === 500) { ctx.body = 'Unexpected error'; } ctx.response.type = 'application/vnd.api+json'; } }); // load custom validator koaValidate(app); // load API routes loader.loadRoutes(app); // load queues loader.loadQueues(app); // Instance of http module // const server = require('http').Server(app.callback()); // get port of environment, if not exist obtain of the config. // In production environment, the port must be declared in environment variable const port = process.env.PORT || config.get('service.port'); const server = app.listen(port, () => { ctRegisterMicroservice.register({ info: require('../microservice/register.json'), swagger: require('../microservice/public-swagger.json'), mode: (process.env.CT_REGISTER_MODE && process.env.CT_REGISTER_MODE === 'auto') ? ctRegisterMicroservice.MODE_AUTOREGISTER : ctRegisterMicroservice.MODE_NORMAL, framework: ctRegisterMicroservice.KOA2, app, logger, name: config.get('service.name'), ctUrl: process.env.CT_URL, url: process.env.LOCAL_URL, token: process.env.CT_TOKEN, active: true, }).then(() => { }, (err) => { logger.error(err); process.exit(1); }); if (config.get('settings.loadCron') && config.get('settings.loadCron') !== 'false') { cronLoader.load(); logger.info('[app] Cron tasks loaded'); } else { logger.info('[app] Skipping cron loading per configuration'); } }); logger.info('Server started in ', process.env.PORT); resolve({ app, server }); } logger.info(`Connecting to MongoDB URL ${mongoUri}`); mongoose.connection.on('connecting', () => { logger.debug('Mongoose attempting to connect'); }); mongoose.connection.on('connected', () => { logger.debug('Mongoose connected to the initial server'); }); mongoose.connection.on('fullsetup', () => { logger.debug('Mongoose connected to the primary server and at least a secondary server'); }); mongoose.connection.on('all', () => { logger.debug('Mongoose connected to all servers'); }); mongoose.connect(mongoUri, mongooseOptions, onDbReady); }); } module.exports = init;
JavaScript
0.000003
@@ -874,38 +874,544 @@ -mongoose.set('debug', true);%0A%7D +logger.debug('Setting mongoose debug logging on');%0A mongoose.set('debug', true);%0A%7D%0A%0Amongoose.connection.on('connecting', () =%3E %7B%0A logger.debug('Mongoose attempting to connect');%0A%7D);%0Amongoose.connection.on('connected', () =%3E %7B%0A logger.debug('Mongoose connected to the initial server');%0A%7D);%0Amongoose.connection.on('fullsetup', () =%3E %7B%0A logger.debug('Mongoose connected to the primary server and at least a secondary server');%0A%7D);%0Amongoose.connection.on('all', () =%3E %7B%0A logger.debug('Mongoose connected to all servers');%0A%7D); %0A%0Aas @@ -1737,16 +1737,72 @@ g...%60);%0A + logger.debug(mongoConnectionError);%0A @@ -5836,556 +5836,8 @@ );%0A%0A - mongoose.connection.on('connecting', () =%3E %7B%0A logger.debug('Mongoose attempting to connect');%0A %7D);%0A mongoose.connection.on('connected', () =%3E %7B%0A logger.debug('Mongoose connected to the initial server');%0A %7D);%0A mongoose.connection.on('fullsetup', () =%3E %7B%0A logger.debug('Mongoose connected to the primary server and at least a secondary server');%0A %7D);%0A mongoose.connection.on('all', () =%3E %7B%0A logger.debug('Mongoose connected to all servers');%0A %7D);%0A%0A%0A
43b0b66ada6378bc00c8661bd9b54739bda4ace4
Fix coding style and improve comment in settings.js
web/settings.js
web/settings.js
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* Copyright 2012 Mozilla Foundation * * 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. */ /* globals PDFJS, SETTINGS_MEMORY */ 'use strict'; // Settings Manager - This is a utility for saving settings // First we see if localStorage is available // If not, we use FUEL in FF // Use asyncStorage for B2G var Settings = (function SettingsClosure() { //#if !(FIREFOX || MOZCENTRAL || B2G) var isLocalStorageEnabled = (function localStorageEnabledTest() { // Feature test as per http://diveintohtml5.info/storage.html // The additional localStorage call is to get around a FF quirk, see // bug #495747 in bugzilla try { return 'localStorage' in window && window['localStorage'] !== null && localStorage; } catch (e) { return false; } })(); //#endif function Settings(fingerprint) { this.fingerprint = fingerprint; this.initializedPromise = new PDFJS.Promise(); var resolvePromise = (function settingsResolvePromise(db) { this.initialize(db || '{}'); this.initializedPromise.resolve(); }).bind(this); //#if B2G // asyncStorage.getItem('database', resolvePromise); //#endif //#if FIREFOX || MOZCENTRAL // resolvePromise(FirefoxCom.requestSync('getDatabase', null)); //#endif //#if !(FIREFOX || MOZCENTRAL || B2G) if (isLocalStorageEnabled) resolvePromise(localStorage.getItem('database')); //#endif } Settings.prototype = { initialize: function settingsInitialize(database) { database = JSON.parse(database); if (!('files' in database)) database.files = []; if (database.files.length >= SETTINGS_MEMORY) database.files.shift(); var index; for (var i = 0, length = database.files.length; i < length; i++) { var branch = database.files[i]; if (branch.fingerprint == this.fingerprint) { index = i; break; } } if (typeof index != 'number') index = database.files.push({fingerprint: this.fingerprint}) - 1; this.file = database.files[index]; this.database = database; }, set: function settingsSet(name, val) { if (!this.initializedPromise.isResolved) return; var file = this.file; file[name] = val; var database = JSON.stringify(this.database); //#if B2G // asyncStorage.setItem('database', database); //#endif //#if FIREFOX || MOZCENTRAL // FirefoxCom.requestSync('setDatabase', database); //#endif //#if !(FIREFOX || MOZCENTRAL || B2G) if (isLocalStorageEnabled) localStorage.setItem('database', database); //#endif }, get: function settingsGet(name, defaultValue) { if (!this.initializedPromise.isResolved) return defaultValue; return this.file[name] || defaultValue; } }; return Settings; })();
JavaScript
0.000001
@@ -795,17 +795,21 @@ ict';%0A%0A/ -/ +**%0A * Setting @@ -861,89 +861,217 @@ ings -%0A// First we see if localStorage is available%0A// If not, we use FUEL in FF%0A// U +.%0A *%0A * The way that settings are stored depends on how PDF.js is built,%0A * for 'node make %3Cflag%3E' the following cases exist:%0A * - FIREFOX or MOZCENTRAL - uses about:config.%0A * - B2G - u se +s asy @@ -1083,16 +1083,82 @@ rage - for B2G +.%0A * - GENERIC or CHROME - uses localStorage, if it is available.%0A */ %0Avar @@ -1498,16 +1498,17 @@ return +( 'localSt @@ -1564,32 +1564,36 @@ ll &&%0A + localStorage;%0A @@ -1588,16 +1588,17 @@ lStorage +) ;%0A %7D @@ -2177,24 +2177,26 @@ rageEnabled) + %7B %0A resol @@ -2236,24 +2236,30 @@ atabase'));%0A + %7D%0A //#endif%0A %7D @@ -2413,16 +2413,18 @@ tabase)) + %7B %0A @@ -2445,16 +2445,24 @@ s = %5B%5D;%0A + %7D%0A if @@ -2504,16 +2504,18 @@ _MEMORY) + %7B %0A @@ -2535,24 +2535,32 @@ es.shift();%0A + %7D%0A var in @@ -2710,16 +2710,17 @@ print == += this.fi @@ -2813,16 +2813,17 @@ index != += 'number @@ -2824,16 +2824,18 @@ number') + %7B %0A @@ -2901,16 +2901,24 @@ %7D) - 1;%0A + %7D%0A th @@ -3071,32 +3071,34 @@ mise.isResolved) + %7B %0A return; @@ -3098,16 +3098,23 @@ return;%0A + %7D %0A v @@ -3444,16 +3444,18 @@ Enabled) + %7B %0A @@ -3491,32 +3491,40 @@ se', database);%0A + %7D%0A //#endif%0A %7D,%0A @@ -3622,16 +3622,18 @@ esolved) + %7B %0A @@ -3654,16 +3654,23 @@ tValue;%0A + %7D %0A r
1aed61e11290ab0c8653d84ecced94a5183374a3
fix left nav link for events in all communities
src/components/LeftNav.js
src/components/LeftNav.js
import React from 'react' import { A, IndexA } from './A' import Icon from './Icon' import { VelocityTransitionGroup } from 'velocity-react' import { isEmpty, filter } from 'lodash' // this value is dupicated in CSS export const leftNavWidth = 208 export const leftNavEasing = [70, 25] const animations = { enter: { animation: {translateX: [0, '-100%']}, easing: leftNavEasing }, leave: { animation: {translateX: '-100%'}, easing: leftNavEasing } } export const MenuButton = ({ onClick, label }) => <a className='menu-button' onClick={onClick}> <div className='hamburger'> <div className='bar'></div> <div className='bar'></div> <div className='bar'></div> </div> <span>{label || 'Menu'}</span> </a> export const TopicList = ({ tags, slug }) => { let followedTags = filter(tags, t => t.followed && !t.created) let createdTags = filter(tags, t => t.created) const TagLink = ({ name }) => { var allTopics = name === 'all-topics' var AComponent = allTopics ? IndexA : A return <li> <AComponent to={allTopics ? `/c/${slug}` : `/c/${slug}/tag/${name}`}> <span className='bullet'>•</span>&nbsp;&nbsp;# {name} </AComponent> </li> } return <ul className='topic-list'> {!isEmpty(followedTags) && <li className='subheading'><a>TOPICS ({followedTags.length})</a></li>} {!isEmpty(followedTags) && <TagLink name='all-topics'/>} {!isEmpty(followedTags) && followedTags.map(tag => <TagLink name={tag.name} key={tag.name} />)} {!isEmpty(createdTags) && <li className='subheading'><a>TOPICS CREATED ({createdTags.length})</a></li>} {!isEmpty(createdTags) && createdTags.map(tag => <TagLink name={tag.name} key={tag.name} />)} </ul> } export const LeftNav = ({ opened, community, tags, close, canModerate, canInvite }) => { let { slug } = community || {} return <VelocityTransitionGroup {...animations}> {opened && <nav id='leftNav'> <MenuButton onClick={close}/> <ul> <li> <IndexA to={slug ? `/c/${slug}` : '/'}> <Icon name='th-list'/> Conversations </IndexA> </li> <li> <A to={`/c/${slug}/events`}> <Icon name='calendar'/> Events </A> </li> <li> <A to={slug ? `/c/${slug}/projects` : '/projects'}> <Icon name='road'/> Projects </A> </li> {community && <li> <A to={`/c/${slug}/members`}> <Icon name='user'/> Members </A> </li>} {community && <li> <A to={`/c/${slug}/about`}> <Icon name='question-sign'/> About </A> </li>} {canInvite && <li> <A to={`/c/${slug}/invite`}> <Icon name='sunglasses'/> Invite </A> </li>} {canModerate && <li> <A to={`/c/${slug}/settings`}> <Icon name='cog'/> Settings </A> </li>} </ul> {!isEmpty(tags) && <TopicList tags={tags} slug={slug} />} </nav>} </VelocityTransitionGroup> } export default LeftNav
JavaScript
0
@@ -2168,32 +2168,39 @@ %3CA to=%7B +slug ? %60/c/$%7Bslug%7D/even @@ -2202,16 +2202,28 @@ /events%60 + : '/events' %7D%3E%0A
3841d565b7ef957ddedc297abed7a12429c66ff8
Fix 'column filled' error
application.js
application.js
$(document).ready(function() { turn = 1 columnSelector(); unsaturated(); }) var unsaturated = function(){ $( ".standardcolumn").hover( function(){ var open_cell = find_open_cell(this.id); if (turn % 2 == 0) { $(open_cell).addClass("unsaturatedred"); } else { $(open_cell).addClass("unsaturatedblack"); } }, function(){ var open_cell = find_open_cell(this.id); $(open_cell).removeClass("unsaturatedblack"); $(open_cell).removeClass("unsaturatedred"); }); }; var columnSelector = function(){ $(".standardcolumn").on("click", function(event){ event.preventDefault(); var column_id = this.id; var open_cell = find_open_cell(column_id); if (open_cell) { change_cell_color(open_cell); checkForWin(open_cell); }; }); }; var find_open_cell = function(column) { string = column.split(' ')[0].toString(); var cells_in_column = $( '#' + column + ' li div' ); for (i = 5; i>=0; i--) { if ($(cells_in_column[i]).attr("class").includes("nopiece")) { return $(cells_in_column[i]); } } alert("This column is full! Try a different column."); return false; }; var change_cell_color = function(cell) { cell.removeClass("nopiece"); if (turn % 2 == 0) { cell.removeClass("unsaturatedred") cell.addClass("redpiece"); } else { cell.removeClass("unsaturatedblack") cell.addClass("blackpiece"); } turn++ }; var checkForWin = function(cell) { var solved = false; if (checkVertical(cell) == true) { solved = true; } else if (checkHorizontal(cell) == true) { solved = true; } else if (checkDiag1(cell) == true) { solved = true; } else if (checkDiag2(cell) == true) { solved = true; } if (solved == true) { alert("CONNECT FOUR! YOU WIN!"); $( '.standardcell.blackpiece' ).removeClass('blackpiece'); $( '.standardcell.redpiece' ).removeClass('redpiece'); $( '.standardcell' ).addClass('nopiece'); } }; var checkPieces = function(pieces_array) { for (i=0; i<4; i++) { if (pieces_array[i] != "nopiece" && (pieces_array.length >= 4)) { if (pieces_array[i] == pieces_array[i + 1] && pieces_array[i] == pieces_array[i + 2] && pieces_array[i] == pieces_array[i + 3]) { return true; }; }; }; }; var checkVertical = function(cell){ var current_column = $(cell).attr("class").split(' ')[0]; var cells_in_column = $( '#' + current_column + ' li div' ); var pieces_array = [] for (i=0; i<6; i++) { pieces_array.push($(cells_in_column[i]).attr("class").split(' ')[3]); }; if (checkPieces(pieces_array) == true) { return true; } }; var checkHorizontal = function(cell) { var current_row = $(cell).attr("class").split(' ')[1]; var cells_in_row = $( 'ul li .' + current_row); var pieces_array = [] for (i=0; i<7; i++) { pieces_array.push($(cells_in_row[i]).attr("class").split(' ')[3]); } if (checkPieces(pieces_array) == true) { return true; } }; var cellClassSelect = function(columnNum, rowNum){ return ($('ul li .column' + (columnNum).toString() + ".row" +(rowNum).toString()).attr("class")); }; var checkDiag1 = function(cell) { var current_column = $(cell).attr("class").split(' ')[0]; var current_row = $(cell).attr("class").split(' ')[1]; var column_num = Number(current_column.replace("column", "")); var row_num = Number(current_row.replace("row", "")); var pieces_array = [] for(i=0; i <= (6-row_num); i++){ var cellClass = cellClassSelect(column_num +i, row_num +i); if (cellClass){ pieces_array.push(cellClass.split(' ')[3]); } } for(i=1; i <= (7-row_num); i++){ var cellClass = cellClassSelect(column_num -i, row_num -i); if (cellClass){ pieces_array.unshift(cellClass.split(' ')[3]); } } if (checkPieces(pieces_array) == true) { return true; } }; var checkDiag2 = function(cell) { var current_column = $(cell).attr("class").split(' ')[0]; var current_row = $(cell).attr("class").split(' ')[1]; var column_num = Number(current_column.replace("column", "")); var row_num = Number(current_row.replace("row", "")); var pieces_array = [] for(i=0; i <= (6-row_num); i++){ var cellClass = cellClassSelect(column_num -i, row_num +i); if (cellClass){ pieces_array.unshift(cellClass.split(' ')[3]) } } for(i=1; i <= (7-row_num); i++){ var cellClass = cellClassSelect(column_num +i, row_num -i); if (cellClass){ pieces_array.push(cellClass.split(' ')[3]) } } if (checkPieces(pieces_array) == true) { return true; } };
JavaScript
0.000232
@@ -161,32 +161,38 @@ var open_cell = +small_ find_open_cell(t @@ -176,37 +176,32 @@ small_find_open -_cell (this.id);%0A i @@ -362,32 +362,38 @@ var open_cell = +small_ find_open_cell(t @@ -385,21 +385,16 @@ ind_open -_cell (this.id @@ -788,24 +788,24 @@ %0A %7D;%0A - %7D);%0A%7D; %0A%0Avar fi @@ -792,24 +792,307 @@ %7D;%0A %7D);%0A%7D; +%0Avar small_find_open = function(column) %7B%0A string = column.split(' ')%5B0%5D.toString();%0A var cells_in_column = $( '#' + column + ' li div' );%0A for (i = 5; i%3E=0; i--) %7B%0A if ($(cells_in_column%5Bi%5D).attr(%22class%22).includes(%22nopiece%22)) %7B%0A return $(cells_in_column%5Bi%5D);%0A %7D%0A %7D%0A%7D; %0A%0Avar find_o
187dad25a03800a4138b1638b1a4f8e65489037a
Remove blank line
webpack.prod.js
webpack.prod.js
const path = require("path"); const webpack = require("webpack"); const merge = require("webpack-merge"); const common = require("./webpack.common.js"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = merge(common, { mode: "production", output: { filename: "app.[hash:6].js", chunkFilename: "[name].[chunkhash:6].js", }, module: { rules: [ { test: /\.less$/, use: [ "classnames-loader", MiniCssExtractPlugin.loader, { loader: "css-loader", options: { modules: true, }, }, "less-loader", ], include: path.resolve(__dirname, "src"), }, { test: /\.less$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { modules: "global", }, }, "less-loader", ], include: /retail-ui/, }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { modules: "global", }, }, ], }, ], }, devtool: "cheap-source-map", plugins: [ new MiniCssExtractPlugin({ filename: "app.[hash:6].css", chunkFilename: "[name].[chunkhash:6].css", }), ], });
JavaScript
0.999999
@@ -1866,17 +1866,16 @@ %5D.css%22,%0A -%0A
bfc8b866b49aec490948c1a7894f1be543d61b80
Set editor read-only if no session (all tabs closed)
app/js/services/editor.js
app/js/services/editor.js
TD.factory('EditSession', function() { return ace.require("ace/edit_session").EditSession; }); // TODO(vojta): lazy load handlers TD.factory('VimHandler', function() { return ace.require("ace/keyboard/vim").handler; }); TD.factory('EmacsHandler', function() { return ace.require("ace/keyboard/emacs").handler; }); TD.factory('ace', function() { return ace.edit('editor'); }); TD.factory('AceRange', function() { return ace.require('ace/range').Range; }); TD.factory('HiddingFolding', function(AceRange) { return function(regexp) { var cache = []; this.getFoldWidget = function(session, foldStyle, row) { var previousMatch = cache[row - 1]; var line = session.getLine(row); var currentMatch = cache[row] = regexp.test(line); if (row === 0) { return currentMatch ? '' : 'start'; } else { if (!previousMatch) { return ''; } else { return currentMatch ? '' : 'start'; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var start = {row: row, column: 0}; var end = {}; while (!cache[row]) { if (typeof cache[row] === 'undefined') { if (row >= session.getLength()) break; this.getFoldWidget(session, foldStyle, row); if (cache[row]) break; } row++; } end.row = row - 1; end.column = session.getLine(end.row).length; return AceRange.fromPoints(start, end); }; }; }); TD.factory('editor', function(EditSession, HiddingFolding, settings, ace) { // default configs ace.setShowPrintMargin(false); var updateSoftWrapSettings = function(wrap, session) { switch (wrap) { case -1: session.setUseWrapMode(false); break; case 0: session.setUseWrapMode(true); session.setWrapLimitRange(null, null); break; default: session.setUseWrapMode(true); session.setWrapLimitRange(wrap, wrap); } }; // listen on settings changes settings.on('theme', function(theme) { ace.setTheme(theme.id); }); settings.on('keyMode', function(mode) { ace.setKeyboardHandler(mode.handler); }); settings.on('useSoftTabs', function(use) { ace.getSession().setUseSoftTabs(use); }); settings.on('tabSize', function(size) { ace.getSession().setTabSize(size); }); settings.on('softWrap', function(wrap) { updateSoftWrapSettings(wrap, ace.getSession()); }); var isFiltered = false; return { focus: function() { setTimeout(function() { ace.focus(); }, 0); }, setSession: function(session) { session.setFoldStyle('markbegin'); // apply current settings session.setUseSoftTabs(settings.useSoftTabs); session.setTabSize(settings.tabSize); updateSoftWrapSettings(settings.softWrap, session); ace.setSession(session); }, clearSession: function() { ace.setSession(new EditSession('')); }, goToLine: function(lineNumber) { ace.gotoLine(lineNumber) }, filter: function(regexp) { var session = ace.getSession(); session.unfold(); session.$setFolding(new HiddingFolding(regexp)); session.foldAll(); isFiltered = true; }, clearFilter: function() { if (!isFiltered) { return; } var session = ace.getSession(); session.unfold(); session.$setFolding(null); isFiltered = false; }, goToFirstFiltered: function() { var session = ace.getSession(); var firstFilteredRow = session.getNextFoldLine(0).end.row + 2; this.goToLine(firstFilteredRow); }, _editor: ace }; });
JavaScript
0
@@ -2923,16 +2923,46 @@ ssion);%0A + ace.setReadOnly(false);%0A %7D,%0A%0A @@ -3031,24 +3031,53 @@ ssion(''));%0A + ace.setReadOnly(true);%0A %7D,%0A%0A
e175d130570bbea10bd56cf98266404e9a66b1ab
Add missing pipeline index relay query data
app/lib/RelayPreloader.js
app/lib/RelayPreloader.js
import Relay from 'react-relay/classic'; import fromGraphQL from 'react-relay/lib/fromGraphQL'; const QUERIES = { "build_header/build": Relay.QL` query BuildsShowBuild($build: ID!) { build(slug: $build) { id createdBy { __typename ...on UnregisteredUser { name email avatar { url } } ...on User { id name email avatar { url } } } } } `, "build_header/viewer": Relay.QL` query BuildsShowViewer { viewer { emails(first: 50) { edges { node { id address verified } } } } } `, "organization_show/organization": Relay.QL` query PipelinesList($organization: ID!, $team: TeamSelector, $pageSize: Int, $pipelineFilter: String) { organization(slug: $organization) { id slug name permissions { pipelineCreate { code allowed message } } teams(first: 500) { edges { node { id name slug description } cursor } pageInfo { hasNextPage hasPreviousPage } } pipelines(first: $pageSize, search: $pipelineFilter, team: $team, order: NAME_WITH_FAVORITES_FIRST) { edges { node { id name slug description url favorite defaultBranch permissions { pipelineFavorite { allowed } } metrics(first: 6) { edges { node { label value url id } cursor } pageInfo { hasNextPage hasPreviousPage } } builds(first: 1, branch: "%default", state: [ RUNNING, CANCELING, PASSED, FAILED, CANCELED, BLOCKED ]) { edges { node { id message url commit state startedAt finishedAt canceledAt scheduledAt createdBy { __typename ... on User { id name avatar { url } } ...on UnregisteredUser { name avatar { url } } } } cursor } pageInfo { hasNextPage hasPreviousPage } } } cursor } pageInfo { hasNextPage hasPreviousPage } } } } `, "navigation/organization": Relay.QL` query NavigationOrganization($organization: ID!) { organization(slug: $organization) { name id slug agents { count } permissions { organizationUpdate { allowed } organizationInvitationCreate { allowed } notificationServiceUpdate { allowed } organizationBillingUpdate { allowed } teamAdmin { allowed } } } } `, "navigation/viewer": Relay.QL` query NavigationViewer { viewer { id user { name, avatar { url } id } } } `, "settings_navigation/organization": Relay.QL` query GetOrganization($organization: ID!) { organization(slug: $organization) { id name slug invitations(state: PENDING) { count } permissions { organizationUpdate { allowed } organizationInvitationCreate { allowed } notificationServiceUpdate { allowed } organizationBillingUpdate { allowed } teamAdmin { allowed } teamCreate { allowed } agentTokenView { allowed } } } } `, "agents/index": Relay.QL` query AgentIndex($organization: ID!) { organization(slug: $organization) { id permissions { agentTokenView { allowed } } agentTokens(first:50, revoked:false) { edges { node { id description token } cursor }, pageInfo { hasNextPage hasPreviousPage } } } } `, "agents/show": Relay.QL` query($slug: ID!) { agent(slug: $slug) { id name organization { id name slug } connectedAt connectionState disconnectedAt hostname id ipAddress job { __typename ... on JobTypeCommand { id label command url build { number pipeline { name id } id } } } lostAt metaData operatingSystem { name } permissions { agentStop { allowed code message } } pid pingedAt stoppedAt stoppedBy { name id } userAgent uuid version } } `, "teams/index": Relay.QL` query($organization: ID!) { organization(slug: $organization) { id name slug permissions { teamCreate { allowed } } } } `, "sso/index": Relay.QL` query($organization: ID!) { organization(slug: $organization) { id name slug permissions { organizationUpdate { allowed } } } } `, "pipeline/header": Relay.QL` query($pipeline: ID!) { pipeline(slug: $pipeline) { id name description url slug defaultBranch repository { url provider { url } } organization { slug id } builds { count } scheduledBuilds: builds(state: SCHEDULED) { count } runningBuilds: builds(state: RUNNING) { count } permissions { pipelineUpdate { allowed code message } buildCreate { allowed code message } } } } `, "pipeline/settings": Relay.QL` query($pipeline: ID!) { pipeline(slug: $pipeline) { id repository { provider { name __typename } } teams { count } schedules { count } } } `, "pipeline/teams_settings": Relay.QL` query($pipeline: ID!) { pipeline(slug: $pipeline) { id slug name organization { id slug } teams(first: 500) { count edges { node { id accessLevel team { id name description slug members { count } pipelines { count } } permissions { teamPipelineUpdate { allowed } teamPipelineDelete { allowed } } } } } } } `, "build_show/annotations": Relay.QL` query BuildAnnotations($build: ID!) { build(slug: $build) { id annotations(first: 10) { edges { node { id style body { html } } cursor } pageInfo { hasNextPage hasPreviousPage } } } } ` }; class RelayPreloader { preload(id, payload, variables) { // Get the concrete query const concrete = QUERIES[id]; if (!concrete) { throw new Error(`No concrete query defined for \`${id}\``); } // Create a Relay-readable GraphQL query with the variables loaded in const query = fromGraphQL.Query(concrete); query.__variables__ = variables; // Load it with the payload into the Relay store Relay.Store.getStoreData().handleQueryPayload(query, payload); } } export default new RelayPreloader();
JavaScript
0.000003
@@ -1200,33 +1200,33 @@ teams(first: -5 +1 00) %7B%0A @@ -1325,32 +1325,151 @@ description%0A + permissions %7B%0A pipelineView %7B%0A allowed%0A %7D%0A %7D%0A %7D%0A
2649dc25a78f6750bf752e9072368056c124e1a9
fix - plopfile bug
plopfile.js
plopfile.js
'use strict' // Plop: https://github.com/amwmedia/plop // inquirer prompts: https://github.com/SBoudrias/Inquirer.js/#objects module.exports = function (plop) { plop.setGenerator('js', { prompts: [{ type: 'input', name: 'filename', message: 'Enter a relative filename/path:', filter: function (filename) { console.log('entered:', filename) // create folder with index.js // e.g. 'server/' -> 'server/index.js' if (filename.endsWith('/')) return filename + '/index' if (!filename.endsWith('.js')) filename += '.js' return filename }, }], actions: [{ type: 'add', path: '{{filename}}', templateFile: 'plop/js.templ', }], }) }
JavaScript
0
@@ -466,30 +466,34 @@ ('/'))%0A%09%09%09%09%09 -return +filename = filename +
75053145e91762bd71ce1a330d097f8fa4cfe7b2
add entries to the ignore patterns
src/config/jest.config.js
src/config/jest.config.js
const path = require('path') const {ifAnyDep, hasFile, hasPkgProp, fromRoot} = require('../utils') const here = p => path.join(__dirname, p) const useBuiltInBabelConfig = !hasFile('.babelrc') && !hasPkgProp('babel') const ignores = [ '/node_modules/', '/fixtures/', '/__tests__/helpers/', '__mocks__', ] const jestConfig = { roots: [fromRoot('src')], testEnvironment: ifAnyDep(['webpack', 'rollup', 'react'], 'jsdom', 'node'), collectCoverageFrom: ['src/**/*.js'], testMatch: ['**/__tests__/**/*.js'], testPathIgnorePatterns: ignores, coveragePathIgnorePatterns: ignores, transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'], coverageThreshold: { global: { branches: 100, functions: 100, lines: 100, statements: 100, }, }, } if (useBuiltInBabelConfig) { jestConfig.transform = {'^.+\\.js$': here('./babel-transform')} } module.exports = jestConfig
JavaScript
0
@@ -537,31 +537,36 @@ rePatterns: +%5B... ignores +%5D ,%0A coverage @@ -589,16 +589,20 @@ ns: +%5B... ignores, %0A t @@ -597,16 +597,48 @@ ignores, + 'src/(umd%7Ccjs%7Cesm)-entry.js$'%5D, %0A trans
245e9d4067be60c82b081b79a820641896724389
USE double quotes .
src/controller/pokemon.js
src/controller/pokemon.js
'use strict'; const path = require('path'); const dao = require(path.resolve('src/dao/pokemon')); const pagarMeProvider = require(path.resolve('src/provider/pagarme')); const request = require('request-promise'); const controller = { getAll: function(req, res) { dao.findAll().then(function(results) { res.status(200).json(results); }).catch(function(error) { res.status(500).json(error); }); }, buy: function(req, res) { const _filter = { name: req.body.pokemon.name }, _pokemon = req.body.pokemon || {}, _creditCard = req.body.credit_card || {}; dao.findOne(_filter) .then(function(pokemon) { if (!pokemon) { res.status(400).send({ statusText: 'Bad Request', validations: [{ property: 'name', messages: ['Pokémon not registered!'] }] }); } else if (pokemon.stock < _pokemon.quantity) { res.status(400).send({ statusText: 'Bad Request', validations: [{ property: 'quantity', messages: ['Not enought ' + pokemon.name + ' in stock: ' + pokemon.stock] }] }); } else { var _data = { pokemon: pokemon, creditCard: _creditCard }; _data.pokemon.quantity = _pokemon.quantity; pagarMeProvider.buyPokemon(_data) .then(function (body){ if (body.status === 'paid') { pokemon.stock = pokemon.stock - _pokemon.quantity; pokemon.save() .then(function() { res.send(body); }) } else { res.status(400).send({ statusText: 'Bad Request', validations: [{ property: 'body', messages: ['Buy operation error'] }] }); } }) .catch(function (err){ res.status(err.response.statusCode).send(err.response.body); }) } }); }, create: function(req, res) { const pokemon = req.body; dao.create(pokemon).then(function(createdPokemon) { res.status(200).json(createdPokemon); }).catch(function(error) { res.status(500).json(error); }); } }; module.exports = controller;
JavaScript
0
@@ -1,9 +1,9 @@ -' +%22 use stri @@ -4,17 +4,17 @@ e strict -' +%22 ;%0A%0Aconst @@ -33,14 +33,14 @@ ire( -' +%22 path -' +%22 );%0Ac @@ -67,25 +67,25 @@ ath.resolve( -' +%22 src/dao/poke @@ -87,17 +87,17 @@ /pokemon -' +%22 ));%0Acons @@ -137,17 +137,17 @@ resolve( -' +%22 src/prov @@ -158,17 +158,17 @@ /pagarme -' +%22 ));%0Acons @@ -187,17 +187,17 @@ require( -' +%22 request- @@ -203,17 +203,17 @@ -promise -' +%22 );%0A%0Acons @@ -683,33 +683,33 @@ %09%09%09%09statusText: -' +%22 Bad Request',%0A%09%09 @@ -695,33 +695,33 @@ xt: %22Bad Request -' +%22 ,%0A%09%09%09%09%09validatio @@ -747,14 +747,14 @@ ty: -' +%22 name -' +%22 ,%0A%09%09 @@ -768,17 +768,17 @@ sages: %5B -' +%22 Pok%C3%A9mon @@ -792,17 +792,17 @@ istered! -' +%22 %5D%0A%09%09%09%09%09%7D @@ -900,33 +900,33 @@ %09%09%09%09statusText: -' +%22 Bad Request',%0A%09%09 @@ -916,25 +916,25 @@ %22Bad Request -' +%22 ,%0A%09%09%09%09%09valid @@ -964,17 +964,17 @@ ty: -' +%22 quantity ',%0A%09 @@ -969,17 +969,17 @@ quantity -' +%22 ,%0A%09%09%09%09%09%09 @@ -989,17 +989,17 @@ sages: %5B -' +%22 Not enou @@ -1002,17 +1002,17 @@ enought -' +%22 + pokem @@ -1021,17 +1021,17 @@ .name + -' +%22 in stoc @@ -1033,17 +1033,17 @@ stock: -' +%22 + pokem @@ -1305,14 +1305,14 @@ === -' +%22 paid -' +%22 ) %7B%0A @@ -1520,17 +1520,17 @@ usText: -' +%22 Bad Requ @@ -1532,17 +1532,17 @@ Request -' +%22 ,%0A%09%09%09%09%09%09 @@ -1582,14 +1582,14 @@ ty: -' +%22 body -' +%22 ,%0A%09%09 @@ -1606,17 +1606,17 @@ sages: %5B -' +%22 Buy oper @@ -1630,9 +1630,9 @@ rror -' +%22 %5D%0A%09%09
a8d70158a28988b94bdd2426a9f53377f5ebbfd4
change results array to array of objects named url
src/controllers/Scrape.js
src/controllers/Scrape.js
var _ = require('underscore'); var models = require('../models'); var Scrape = models.Scrape; var makerPage = function(req, res) { Scrape.ScrapeModel.findByOwner(req.session.account._id, function(err, docs) { if(err) { console.log(err); return res.status(400).json({error:'An error occurred'}); } res.render('app', {scrapes: docs}); }); }; var makeScrape = function(req, res) { if(!req.body.name || !req.body.age) { return res.status(400).json({error: "Both URL and Query are required"}); } var ScrapeData = { url: req.body.url, query: req.body.query, results: ['result 1','result 2'], owner: req.session.account._id }; var newScrape = new Scrape.ScrapeModel(scrapeData); newScrape.save(function(err) { if(err) { console.log(err); return res.status(400).json({error:'An error occurred'}); } res.json({redirect: '/maker'}); }); }; module.exports.makerPage = makerPage; module.exports.make = makeScrape;
JavaScript
0.000005
@@ -684,29 +684,33 @@ s: %5B -'result 1','result 2' +%7Burl: 'one'%7D,%7Burl: 'two'%7D %5D,%0A
7b85031a8ae32f8d9d53113b0782f7816ae92ead
fix issue with nonprofit show views not loading
server/boot/nonprofits.js
server/boot/nonprofits.js
var Rx = require('rx'); var debug = require('debug')('freecc:nonprofits'); var observeMethod = require('../utils/rx').observeMethod; var unDasherize = require('../utils').unDasherize; var dasherize = require('../utils').dasherize; module.exports = function(app) { var router = app.loopback.Router(); var Nonprofit = app.models.Nonprofit; var findNonprofits = observeMethod(Nonprofit, 'find'); var findOneNonprofit = observeMethod(Nonprofit, 'findOne'); router.get('/nonprofits/directory', nonprofitsDirectory); router.get('/nonprofits/:nonprofitName', returnIndividualNonprofit); app.use(router); function nonprofitsDirectory(req, res, next) { findNonprofits({ order: 'moneySaved DESC' }) .flatMap( (nonprofits = []) => { // turn array of nonprofits into observable array return Rx.Observable.from(nonprofits) .pluck('moneySaved') .reduce((sum, moneySaved = 0) => sum + moneySaved, 0); }, (nonprofits = [], totalSavings) => ({ nonprofits, totalSavings }) ) .subscribe(({ nonprofits, totalSavings }) => { res.render('nonprofits/directory', { title: 'Nonprofits we help', nonprofits: nonprofits, totalSavings: totalSavings.toString().replace(/000$/, ',000') }); }, next ); } function returnIndividualNonprofit(req, res, next) { var dashedName = req.params.nonprofitName; var nonprofitName = unDasherize(dashedName); var query = { where: { name: { like: nonprofitName, options: 'i' } } }; debug('looking for %s', nonprofitName); debug('query', query); findOneNonprofit(query).subscribe( function(nonprofit) { if (!nonprofit) { req.flash('errors', { msg: "404: We couldn't find a nonprofit with that name. " + 'Please double check the name.' }); return res.redirect('/nonprofits'); } var dashedNameFull = dasherize(nonprofit.name); if (dashedNameFull !== dashedName) { return res.redirect('../nonprofit/' + dashedNameFull); } var buttonActive = false; if ( req.user && req.user.uncompletedBonfires.length === 0 && req.user.completedCoursewares.length > 63 ) { var hasShownInterest = nonprofit.interestedCampers.filter(function(user) { return user.username === req.user.username; }); if (hasShownInterest.length === 0) { buttonActive = true; } } res.render('nonprofits/show', { dashedName: dashedNameFull, title: nonprofit.name, logoUrl: nonprofit.logoUrl, estimatedHours: nonprofit.estimatedHours, projectDescription: nonprofit.projectDescription, approvedOther: nonprofit.approvedDeliverables.indexOf('other') > -1, approvedWebsite: nonprofit.approvedDeliverables.indexOf('website') > -1, approvedDonor: nonprofit.approvedDeliverables.indexOf('donor') > -1, approvedInventory: nonprofit.approvedDeliverables.indexOf('inventory') > -1, approvedVolunteer: nonprofit.approvedDeliverables.indexOf('volunteer') > -1, approvedForm: nonprofit.approvedDeliverables.indexOf('form') > -1, approvedCommunity: nonprofit.approvedDeliverables.indexOf('community') > -1, approvedELearning: nonprofit.approvedDeliverables.indexOf('eLearning') > -1, websiteLink: nonprofit.websiteLink, imageUrl: nonprofit.imageUrl, whatDoesNonprofitDo: nonprofit.whatDoesNonprofitDo, interestedCampers: nonprofit.interestedCampers, assignedCampers: nonprofit.assignedCampers, buttonActive: buttonActive, moneySaved: nonprofit.moneySaved, currentStatus: nonprofit.currentStatus }); }, next ); } };
JavaScript
0
@@ -2161,24 +2161,115 @@ %7D%0A%0A +//We need to create logic that verifies completion. Defaulting to false for now.%0A // var buttonAc @@ -2286,24 +2286,26 @@ se;%0A +// if (%0A @@ -2297,32 +2297,34 @@ //if (%0A +// req.user &&%0A @@ -2333,63 +2333,10 @@ - - req.user.uncompletedBonfires.length === 0 &&%0A +// re @@ -2383,16 +2383,18 @@ +// ) %7B%0A @@ -2393,24 +2393,26 @@ ) %7B%0A +// var hasSho @@ -2424,32 +2424,34 @@ erest =%0A +// nonprofit.in @@ -2494,24 +2494,26 @@ ) %7B%0A +// return @@ -2558,24 +2558,26 @@ +// %7D);%0A %0A @@ -2568,16 +2568,26 @@ %7D);%0A + // %0A @@ -2583,24 +2583,26 @@ //%0A +// if (hasSho @@ -2632,24 +2632,26 @@ ) %7B%0A +// buttonAc @@ -2667,24 +2667,26 @@ ue;%0A +// %7D%0A @@ -2677,32 +2677,34 @@ // %7D%0A +// %7D%0A%0A res.r @@ -4002,27 +4002,20 @@ Active: -buttonActiv +fals e,%0A
cd711a05eda48d7a34716fb0f7dfa001e2a9123a
Remove TURN server from config
app/scripts/cyclondemo.js
app/scripts/cyclondemo.js
'use strict'; var cyclon = require("cyclon.p2p"); var rtc = require("cyclon.p2p-rtc-client"); var rtcComms = require("cyclon.p2p-rtc-comms"); var StorageService = require("./services/StorageService"); /** * RTC Module */ rtc.buildAngularModule(angular) .factory("StorageService", StorageService) .value("IceServers", [ // The Google STUN server {urls: ['stun:stun.l.google.com:19302']}, // Turn over TCP on port 80 for networks with totalitarian security regimes {urls: ['turn:54.187.115.223:80?transport=tcp'], username: 'cyclonjsuser', credential: 'sP4zBGasNVKI'} ]) .value("SignallingServers", JSON.parse('/* @echo SIGNALLING_SERVERS */')); /** * RTC Comms Module */ rtcComms.buildAngularModule(angular); /** * Demo app module */ var LocalSimulationService = require("./services/LocalSimulationService"); var OverlayService = require("./services/OverlayService"); var FrontendVersionService = require("./services/FrontendVersionService"); var LocationProviderService = require("./services/LocationProviderService"); var PlatformDetectionService = require("./services/PlatformDetectionService"); var ClientInfoService = require("./services/ClientInfoService"); var ShuffleStatsService = require("./services/ShuffleStatsService"); var VersionCheckService = require("./services/VersionCheckService"); var RTCService = require("./services/RTCService"); var SessionInformationService = require("./services/SessionInformationService"); var RankingService = require("./services/RankingService"); var DemoPageController = require("./controllers/DemoPageController"); var LocalSimulationController = require("./controllers/LocalSimulationController"); var ConnectivityTestController = require("./controllers/ConnectivityTestController"); var CacheContentsTable = require("./directives/CacheContentsTable"); var NodeInfo = require("./directives/NodeInfo"); var TopNodesTable = require("./directives/TopNodesTable"); var LocalNodePointerPanel = require("./directives/LocalNodePointerPanel"); var RemoteNodePointerPanel = require("./directives/RemoteNodePointerPanel"); var OutgoingSuccessRateFilter = require("./filters/OutgoingSuccessRateFilter"); var IncomingSuccessRateFilter = require("./filters/IncomingSuccessRateFilter"); var IdOrInfoFilter = require("./filters/IdOrInfoFilter"); var RunningTimeFilter = require("./filters/RunningTimeFilter"); var appModule = angular.module("cyclon-demo", ["ui.bootstrap", "cyclon-rtc-comms"]); appModule.filter("incomingSuccessRate", IncomingSuccessRateFilter); appModule.filter("outgoingSuccessRate", OutgoingSuccessRateFilter); appModule.filter("idOrInfo", IdOrInfoFilter); appModule.filter("runningTime", ["SessionInformationService", RunningTimeFilter]); appModule.factory("ShuffleStatsService", ["$rootScope", ShuffleStatsService]); appModule.factory("SessionInformationService", ["StorageService", SessionInformationService]); appModule.factory("RankingService", ["$rootScope", "$interval", "OverlayService", "SessionInformationService", RankingService]); appModule.factory("FrontendVersionService", FrontendVersionService); appModule.factory("OverlayService", ["$log", "$rootScope", "FrontendVersionService", "LocationProviderService", "PlatformDetectionService", "ClientInfoService", "ShuffleStatsService", "SessionInformationService", "StorageService", "Comms", "Bootstrap", "AsyncExecService", OverlayService]); appModule.factory("LocalSimulationService", ['$rootScope', '$log', '$interval', LocalSimulationService]); appModule.factory("LocationProviderService", ["$log", "$http", LocationProviderService]); appModule.factory("PlatformDetectionService", PlatformDetectionService); appModule.factory("ClientInfoService", ["StorageService", ClientInfoService]); appModule.factory("VersionCheckService", ["$rootScope", "$interval", "$http", "$log", "FrontendVersionService", VersionCheckService]); appModule.factory("RTCService", ["RTC", "$log", "$rootScope", RTCService]); appModule.directive("cacheContentsTable", CacheContentsTable); appModule.directive("nodeInfo", NodeInfo); appModule.directive("topNodesTable", TopNodesTable); appModule.directive("localNodePointerPanel", LocalNodePointerPanel); appModule.directive("remoteNodePointerPanel", RemoteNodePointerPanel); appModule.controller("DemoPageController", ['$http', '$interval', '$log', '$scope', "OverlayService", "ClientInfoService", "VersionCheckService", "RankingService", "StorageService", DemoPageController]); appModule.controller("LocalSimulationController", ['$scope', 'LocalSimulationService', LocalSimulationController]); appModule.controller("ConnectivityTestController", ["$timeout", "$scope", "RTCService", ConnectivityTestController]); // Disable debug, its very noisy appModule.config(["$logProvider", function ($logProvider) { $logProvider.debugEnabled(false); }]); angular.element(document).ready(function () { angular.bootstrap(document, ['cyclon-demo']); });
JavaScript
0.000001
@@ -410,204 +410,8 @@ 2'%5D%7D -,%0A // Turn over TCP on port 80 for networks with totalitarian security regimes%0A %7Burls: %5B'turn:54.187.115.223:80?transport=tcp'%5D, username: 'cyclonjsuser', credential: 'sP4zBGasNVKI'%7D %0A
e024243bd4824c3d964b452858830c5c84c1aac2
allow reset user. need this here otherwise the page doesn't load when not logged in for some reason
app/services/user-auth.js
app/services/user-auth.js
import Ember from 'ember'; import config from '../config/environment'; export default Ember.Service.extend({ tokenHandler: Ember.inject.service("token-handler"), store: Ember.inject.service('store'), authRequest: Ember.inject.service(), isAuthenticated: true, getCurrentUserFromServer:function () { let self = this; let url = config.apiUrl + '/user/me'; return this.get('authRequest').send(url) .then(userJS => { if ((userJS == null) || (userJS === "") || (userJS==="null")) { // console.log("User is null in api call"); return null; } else { let userRec = self.get('store').createRecord('user', userJS); //BUG: this call returns an empty object // console.log("User not is null in api call"); localStorage.currentUserID = userJS._id; // store logged in user locally return userRec; } }) .catch(e => { // console.log(e); return null; }); }, getCurrentUser() { var userID = localStorage.currentUserID; if ((userID === "null") || (userID == null) || (userID === "") || (userID === "undefined")) { return null; } return this.get('store').find('user', userID); }, getCurrentUserID() { return localStorage.currentUserID; }, logoutCurrentUser() { let self = this; let url = config.apiUrl + '/token/session'; let options = { method: 'DELETE' }; this.get('authRequest').send(url, options) .then(() => { self.get('tokenHandler').releaseWholeTaleCookie(); localStorage.currentUserID = null; }) .catch(() => { //alert("Could not log out!"); }); } });
JavaScript
0.000004
@@ -1058,32 +1058,102 @@ %7D);%0A %7D,%0A%0A + resetCurrentUser() %7B%0A localStorage.currentUserID = null;%0A %7D,%0A%0A getCurrentUser
c0895628b82e652b082b59f83667efd9593ca827
change sortie pill color
src/embeds/SortieEmbed.js
src/embeds/SortieEmbed.js
'use strict'; const BaseEmbed = require('./BaseEmbed.js'); /** * Generates sortie embeds */ class SortieEmbed extends BaseEmbed { /** * @param {Genesis} bot - An instance of Genesis * @param {Sortie} sortie - The sortie to be included in the embed */ constructor(bot, sortie) { super(); this.color = 0x00ff00; if (typeof sortie !== 'undefined' && sortie) { this.fields = sortie.variants.map(v => ({ name: `${v.node} - ${v.missionType}`, value: v.modifier, })); this.description = `Currently in-progress sortie: **${sortie.getBoss()}**`; this.footer.text = `${sortie.getETAString()} remaining | ${new Date().toLocaleString()}`; } this.title = 'Worldstate - Sortie'; this.thumbnail = { url: 'http://i.imgur.com/wWBRhaB.png', }; } } module.exports = SortieEmbed;
JavaScript
0.000001
@@ -325,12 +325,12 @@ = 0x -00ff +a843 00;%0A
9b5ea813f033618dec473b3dd044b4a4ffae192a
Use lowercase
app/static/script/myjs.js
app/static/script/myjs.js
// Use '[[' and ']]' tags since Django using Mustache's default template tags. Mustache.tags = ['[[', ']]']; $(function(){ var swiper = new Swiper('.swiper-container', { loop : true, pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', slidesPerView: 'auto', centeredSlides: true, paginationClickable: true, spaceBetween: 30 }); $('#top-tabs').tabs({ selected: 0 }); }); (function (window) { var $ = window.jQuery; var moment = window.moment; $('.dropdown-toggle').dropdown(); $(function () { webshim.activeLang('ja'); $.webshims.setOptions('extendNative', true); $.webshims.polyfill('forms'); }); moment.locale('ja', {week: {dow: 1}}); var DateFormat = 'YYYY-MM-DD'; $(function () { $('#searchform-date').datetimepicker({ inline: true, locale: moment.locale('ja'), format: DateFormat }); $('#result-number').change(function() { var Url = window.location.href; var num = this.value; var regex = /\b(numperpage=)[^&]*/; var newUrl; if (regex.test(Url)) { newUrl = Url.replace(regex, '$1' + num); } else { newUrl = Url + "&numperpage=" + num; } window.location.replace(newUrl); }); }); })(this); /** * bootstrap-confirmation2 */ (function (global) { global.jQuery(function ($) { $('[data-toggle=confirmation]').confirmation({ rootSelector: '[data-toggle=confirmation]', title: '本当によろしいですか?', btnOkLabel: 'はい', btnCancelLabel: 'いいえ' }); }); })(this); /** * croppie-upload - use croppie.js to crop uploaded images */ (function (global) { var $ = global.jQuery; var Blob = global.Blob; var alert = global.alert; var FileReader = global.FileReader; var FormData = global.FormData; var base64ToBlob = function (src) { var chunkSize = 1024; var srcList = src.split(/[:;,]/); var mime = srcList[1]; var byteChars = global.atob(srcList[3]); var byteArrays = []; for (var c = 0, len = byteChars.length; c < len; c += chunkSize) { var slice = byteChars.slice(c, c + chunkSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, {type: mime}); }; $.fn.extend({ croppieUpload: function (opt) { var self = this; var div; // read file self.on('change', function () { $('.croppie-upload-ready').remove(); div = $('<div>') .addClass('croppie-upload-ready') .croppie( $.extend({ enableExif: true, viewport: { width: 200, height: 200, type: 'square' }, boundary: { width: 300, height: 300 } }, opt) ); if (!this.files || !this.files[0]) { alert("Sorry - your browser doesn't support the FileReader API"); return false; } var reader = new FileReader(); reader.onload = function (e) { div.croppie('bind', { url: e.target.result }); }; reader.readAsDataURL(this.files[0]); self.after(div); }); self.closest('form').submit(function () { var form = $(this); var formData = new FormData(form.get(0)); var name = self.attr('name'); div .croppie('result', { type: 'canvas', size: 'viewport' }) .then(function (resp) { formData.append(name, base64ToBlob(resp), 'cropped'); $.ajax({ cache: true, async: false, url: form.attr('action'), type: form.attr('method'), cache: false, processData: false, contentType: false, data: formData, }) .done(function () { global.location.reload(); }); }); return false; }); } }); })(this);
JavaScript
0.988331
@@ -992,17 +992,17 @@ var -U +u rl = win @@ -1129,17 +1129,17 @@ ex.test( -U +u rl)) %7B%0A @@ -1154,17 +1154,17 @@ ewUrl = -U +u rl.repla @@ -1218,17 +1218,17 @@ ewUrl = -U +u rl + %22&n
9a15e7b11003a9e4e052b8b3f1f3cd965e77db76
Fix bug with gulp.spritesmith being required incorrectly
app/templates/gulpfile.js
app/templates/gulpfile.js
/* global $:true */ 'use strict'; var gulp = require('gulp'); var browserSync = require('browser-sync'); <% if (includeJekyll) { %>var cp = require('child_process');<% } %> var $ = require('gulp-load-plugins')(); <% if (includeSprites) { %>var spritesmith = require('spritesmith');<% } %> gulp.task('styles', function () { return gulp.src('app/styles/main.scss') .pipe($.plumber({ errorHandler: $.notify.onError('Error: <%%= error.message %>') })) .pipe($.rubySass({ style: 'expanded', precision: 10, bundleExec: true })) .pipe($.autoprefixer('last 3 versions', 'ie >= 9')) .pipe(gulp.dest('.tmp/styles')) .pipe($.size()); }); gulp.task('scripts', function () { return gulp.src('app/scripts/**/*.js') .pipe($.jshint()) .pipe($.jshint.reporter(require('jshint-stylish'))) .pipe($.size()); }); gulp.task('html', ['styles', 'scripts'<% if (includeJekyll) { %>, 'templates'<% } %><% if (includeIcons) { %>, 'icons'<% } %><% if (includeSprites) { %>, 'sprites'<% } %>], function () { var jsFilter = $.filter('**/*.js'); var cssFilter = $.filter('**/*.css'); return gulp.src('<% if (includeJekyll) { %>.jekyll<% } else { %>app<% } %>/**/*.html') .pipe($.useref.assets({ searchPath: '{.tmp,app}' })) .pipe(jsFilter) .pipe($.uglify()) .pipe(jsFilter.restore()) .pipe(cssFilter) .pipe($.csso()) .pipe(cssFilter.restore()) .pipe($.rev()) .pipe($.useref.restore()) .pipe($.useref()) .pipe($.revReplace()) .pipe($.if('*.html', $.minifyHtml({ comments: true, conditional: true, quotes: true, cdata: true, empty: true }))) .pipe(gulp.dest('dist')) .pipe($.size()); }); gulp.task('images', function () { return gulp.src('app/images/**/*') .pipe($.imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })) .pipe(gulp.dest('dist/images')) .pipe($.size()); }); gulp.task('fonts', function () { return gulp.src('app/fonts/**/*') .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}')) .pipe($.flatten()) .pipe(gulp.dest('dist/fonts')) .pipe($.size()); }); gulp.task('extras', function () { return gulp.src(['app/*.*', '!app/*.html'], { dot: true }) .pipe(gulp.dest('dist')); }); gulp.task('clean', function () { return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean()); }); gulp.task('build', function (cb) { var runSequence = require('run-sequence'); runSequence('clean', ['html', 'images', 'fonts', 'extras'], cb); }); gulp.task('default', ['build']); gulp.task('serve', ['watch', 'scripts', 'styles'<% if (includeJekyll) { %>, 'templates'<% } %>], function () { var files = [ '.tmp/styles/**/*.css', 'app/scripts/**/*.js', 'app/images/*' ]; browserSync.instance = browserSync.init(files, { startPath: '/index.html', server: { baseDir: ['app', '.tmp'<% if (includeJekyll) { %>, '.jekyll'<% } %>], routes: { '/bower_components': 'bower_components' } }, }); }); gulp.task('serve:dist', ['build'], function () { browserSync.instance = browserSync.init(['dist/**/*'], { startPath: '/index.html', server: { baseDir: ['dist'] }, }); }); gulp.task('watch', function () { <% if (includeJekyll) { %> gulp.watch('app/pages/**', ['templates:rebuild']);<% } %> gulp.watch('app/styles/**/*.scss', ['styles']); gulp.watch('app/scripts/**/*.js', ['scripts']); gulp.watch('app/images/**/*', ['images']); }); <% if (includeJekyll) { %> gulp.task('templates', function (done) { browserSync.notify('<span style="color: grey">Running:</span> $ jekyll build'); return cp.spawn('bundle', ['exec', 'jekyll', 'build'], { stdio: 'inherit' }) .on('close', done); }); gulp.task('templates:rebuild', ['templates'], function () { browserSync.reload(); }); <% } %> gulp.task('wiredep', function () { var wiredep = require('wiredep').stream; gulp.src('app/styles/*.scss') .pipe(wiredep({ directory: 'app/bower_components' })) .pipe(gulp.dest('app/styles')); gulp.src('app/**/*.html') .pipe(wiredep({ directory: 'app/bower_components', ignorePath: /^(\.\.\/\.\.)+/, exclude: ['bower_components/modernizr/modernizr.js'] })) .pipe(gulp.dest('app')); }); gulp.task('deploy', ['build'], function () { var rsync = require('rsyncwrapper').rsync; return rsync({ ssh: true, src: './dist/*', dest: 'user@server.tld:/path/to/site/', recursive: true, syncDest: true, args: ['-avz', '--delete'] }, function (error, stdout, stderr, cmd) { $.util.log('Command used was: ' + cmd); $.util.log(stdout); }); }); <% if (includeIcons) { %> gulp.task('icons', function () { gulp.src(['app/images/icons/*.svg']) .pipe($.iconfont({ fontName: 'icons', appendCodepoints: true, fontHeight: 500, normalize: true, centerHorizontally: true, })) .on('codepoints', function (codepoints) { gulp.src('templates/_iconfont.scss') .pipe($.consolidate('lodash', { glyphs: codepoints, fontName: 'icons', fontPath: '/fonts/', className: 'icon' })) .pipe(gulp.dest('app/styles/')); }) .pipe(gulp.dest('app/fonts')); }); <% } %><% if (includeSprites) { %> gulp.task('sprites', function () { var spriteData = gulp.src('app/images/sprites/*.png').pipe(spritesmith({ imgName: 'sprites.png', cssName: '_sprites.scss', algorithm: 'binary-tree', cssFormat: 'css', cssTemplate: 'gulp/spritesheet.mustache' })); spriteData.img.pipe(gulp.dest('app/images/')); spriteData.css.pipe(gulp.dest('app/styles/')); });<% } %>
JavaScript
0
@@ -261,16 +261,21 @@ equire(' +gulp. spritesm
519d6615ab0a8d3ccfe59875bfa7d42cf7c4ddf0
Update felixge/node-mysql benchmarking code, disable reconnectAsyncBenchmark
src/felixge-node-mysql.js
src/felixge-node-mysql.js
/* Copyright (C) 2010, Oleg Efimov <efimovov@gmail.com> See license text in LICENSE file */ // Require modules var sys = require('sys'), Mysql = require('../deps/felixge-node-mysql/lib/mysql').Client, conn, rows; function selectAsyncBenchmark(callback, cfg) { var start_time, total_time; start_time = new Date(); conn.query("SELECT * FROM " + cfg.test_table + ";", function (err, results, fields) { total_time = ((new Date()) - start_time) / 1000; sys.puts("**** " + cfg.insert_rows_count + " rows async selected in " + total_time + "s (" + Math.round(cfg.insert_rows_count / total_time) + "/s)"); // Finish benchmark conn.end(); callback.apply(); }); } function insertAsyncBenchmark(callback, cfg) { var start_time, total_time, i = 0; start_time = new Date(); function insertAsync() { i += 1; if (i <= cfg.insert_rows_count) { conn.query(cfg.insert_query, function (err, result) { insertAsync(); }); } else { total_time = ((new Date()) - start_time) / 1000; sys.puts("**** " + cfg.insert_rows_count + " async insertions in " + total_time + "s (" + Math.round(cfg.insert_rows_count / total_time) + "/s)"); setTimeout(function () { selectAsyncBenchmark(callback, cfg); }, cfg.delay_before_select); } } insertAsync(); } function reconnectAsyncBenchmark(callback, cfg) { var start_time, total_time, i = 0; start_time = new Date(); function reconnectAsync() { i += 1; if (i <= cfg.reconnect_count) { conn.end(); conn.connect(function (err, result) { reconnectAsync(); }); } else { total_time = ((new Date()) - start_time) / 1000; sys.puts("**** " + cfg.reconnect_count + " async reconnects in " + total_time + "s (" + Math.round(cfg.reconnect_count / total_time) + "/s)"); insertAsyncBenchmark(callback, cfg); } } reconnectAsync(); } function escapeBenchmark(callback, cfg) { var start_time, total_time, i = 0, escaped_string; start_time = new Date(); for (i = 0; i < cfg.escape_count; i += 1) { escaped_string = conn.escape(cfg.string_to_escape); } total_time = ((new Date()) - start_time) / 1000; sys.puts("**** " + cfg.escape_count + " escapes in " + total_time + "s (" + Math.round(cfg.escape_count / total_time) + "/s)"); reconnectAsyncBenchmark(callback, cfg); } function startBenchmark(callback, cfg) { var start_time, total_time; start_time = new Date(); conn = new Mysql(); conn.host = cfg.host; conn.user = cfg.user; conn.password = cfg.password; conn.database = cfg.database; conn.connect(function (err, result) { conn.query("DROP TABLE IF EXISTS " + cfg.test_table + ";", function () { conn.query(cfg.create_table_query, function () { total_time = ((new Date()) - start_time) / 1000; sys.puts("**** Benchmark initialization time is " + total_time + "s"); escapeBenchmark(callback, cfg); }); }); }); } exports.run = function (callback, cfg) { startBenchmark(callback, cfg); };
JavaScript
0
@@ -1471,32 +1471,34 @@ ,%0A i = 0;%0A %0A + start_time = n @@ -1502,35 +1502,39 @@ = new Date();%0A -%0A + %0A + function reconne @@ -1541,32 +1541,34 @@ ctAsync() %7B%0A + i += 1;%0A if ( @@ -1555,32 +1555,34 @@ i += 1;%0A + + if (i %3C= cfg.rec @@ -1599,24 +1599,26 @@ nt) %7B%0A + conn.end();%0A @@ -1610,27 +1610,42 @@ conn.end( -);%0A +function () %7B%0A conn.c @@ -1684,16 +1684,20 @@ + reconnec @@ -1704,36 +1704,54 @@ tAsync();%0A + + %7D);%0A + %7D);%0A %7D else %7B%0A @@ -1745,32 +1745,34 @@ %7D else %7B%0A + total_time = ((n @@ -1796,32 +1796,34 @@ t_time) / 1000;%0A + sys.puts(%22 @@ -1957,25 +1957,29 @@ s)%22);%0A -%0A + %0A insert @@ -2013,25 +2013,33 @@ g);%0A -%7D%0A + %7D%0A %7D%0A -%0A + %0A reconn @@ -2492,16 +2492,18 @@ );%0A %0A +// reconnec @@ -2534,16 +2534,55 @@ , cfg);%0A + insertAsyncBenchmark(callback, cfg);%0A %7D%0A%0Afunct
8e291a91fed804597409c9dd02c44a6c2be79eab
Send button submitting as form value after beautifying
public/js/client.js
public/js/client.js
// INITIALIZE SOCKET var socket = io(); // BIND BROWSER EVENTS TO SOCKET EVENT EMITTERS function afterReady() { var regPopup = new $.Popup(); console.log(regPopup.options); // regPopup.open('views/register.html'); $('.popup').popup({ width: 500, heigth: 150, afterOpen: function() { $('#join-room').click(function() { var roomName = $('#roomName').val(); joinRoom(roomName); }); $('#create-room').click(function() { var roomName = $('#roomName').val(); createRoom(roomName); }); } }); $('#send-message').click(function() { console.log("clicking send") var msg = $('#message').val(); sendMsg(msg, socket.id); receiveMsg(msg); $('#message').val(''); }); } // SOCKET EVENT LISTENERS socket.on('register', function() { // call popup to register }); socket.on('message', function(data) { receiveMsg(data.msg, data.id); }); socket.on('room-error', function(errMsg) { // reveal alert message $('.alert-danger').append(errMsg); $('.alert-danger').show(); }); socket.on('success', function(msg, data) { $('.popup_close').click(); $('#messages').append('<li class="admin">' + msg); $('.room p').text('Room name: ' + data.name); }); // SOCKET EVENT EMITTERS function createRoom(roomName) { socket.emit('create-room', roomName); } function joinRoom(roomName) { socket.emit('join-room', roomName); } function sendMsg(msg, id) { socket.emit('message', msg, id); } // HELPER function receiveMsg(msg, sender) { console.log('from others') $('#messages').append("<li>" + sender + ": " + msg); } function receiveMsg(msg) { console.log('from yourself') $('#messages').append("<li>you: " + msg); } // Init $(document).ready(afterReady);
JavaScript
0
@@ -678,32 +678,33 @@ .click(function( +e ) %7B%0A cons @@ -728,16 +728,44 @@ send%22)%0A + e.preventDefault();%0A
75368c636192b93ae0870037249934f9c281c65b
Update config.js
public/js/config.js
public/js/config.js
var Config = (function(){ "use strict"; /* -------- DO NOT BEAUTIFY ---------*/ var initialContent = [ { name: "index.html", fileId: "welcome", content: `<html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Welcome to MultiHack!</h1> <ul> <li>Collaborate in real-time.</li> <li>Syntax highlighting for every web language.</li> <li>Voice chat with up to 10 people! (WebRTC only)</li> <li>Instantly deploy your website via HyperHost (WebRTC only)</li> <li>Import files, ZIP archives and GitHub repos.</li> <li>Save your project for working offline.</li> <li>MultiHack is the ONLY multi-file, multi-user code editor on the web.</li> <!-- Try deploying this file! --> <a href="http://github.com/RationalCoding/multihack" target="_blank">Source Code</a> </ul> </body> </html>` }, { name: "style.css", fileId: "welcome2", content: `body { background: lightgray; font-family: Arial; } h1 { color: darkgreen; }` }, { name: "script.js", fileId: "welcome3", content: `var a = 1; for (var i=0; i < 10; i++){ //A meaningless loop! }` } ]; /*-------------------------------*/ return { FileSystem : { initialContent : initialContent }, UI : { }, Sockets : { HOSTNAME : "/", //Points at a Multihack server PeerJS : { host: "/", //Points at a slightly modified PeerJS server port: 443, path: "/server", secure: true } }, } }());
JavaScript
0.000002
@@ -874,16 +874,20 @@ ultihack +-web %22 target @@ -1809,8 +1809,9 @@ %7D%0A%7D()); +%0A
02809f995ed85a2e3262d0ac68ea8ff92b2b70ed
clean up
Resources/ui/common/FirstView.js
Resources/ui/common/FirstView.js
//FirstView Component Constructor var _ = require("/lib/underscore"); function FirstView() { var self = Ti.UI.createScrollView({backgroundColor: '#666'}); var SpriteCore = require('/sprite/SpriteCore'); var SpriteConfig = require('/sprite/SpriteConfig'); //roller1 var sprite = new SpriteCore(SpriteConfig.Slots); self.add(sprite.createSprite({ spriteStartFrame:0 })); sprite.spriteView.top=0; sprite.spriteView.left=0; //roller 2 spin in reverse var config = JSON.parse(JSON.stringify(SpriteConfig.Slots));//deep copy obj to prevent changes from interfering with any other references to the object later in code config.reverseLoop=true; var sprite2 = new SpriteCore(config); self.add(sprite2.createSprite({ spriteStartFrame:0 })); sprite2.spriteView.top=0; sprite2.spriteView.left=100; //roller 3 var sprite3 = new SpriteCore(SpriteConfig.Slots); self.add(sprite3.createSprite({ spriteStartFrame:0 })); sprite3.spriteView.top=0; sprite3.spriteView.left=200; var initSpin = true; var spinButton = Titanium.UI.createButton({ title: 'Spin', top: 100, width: 100, height: 50 }); self.add(spinButton); var timer; spinButton.addEventListener('click',function(e) { spinButton.setEnabled(false); lblWinner.text=''; if(initSpin) { sprite.start({ start:0, end:5, time:1000 }); sprite2.start({ start:0, end:5, time:900 }); sprite3.start({ start:0, end:5, time:800 }); initSpin=false; } else{ sprite.resume(); sprite2.resume(); sprite3.resume(); } var spinFor = Math.random() * 2000+2000; timer = setInterval(function(){ clearInterval(timer); sprite.stop(); sprite2.stop(); sprite3.stop(); spinButton.setEnabled(true); if(sprite.spriteCurrentFrame === sprite2.spriteCurrentFrame && sprite.spriteCurrentFrame === sprite3.spriteCurrentFrame) lblWinner.text='WINNER!'; }, spinFor); }); var lblWinner = Ti.UI.createLabel({ color: '#F00', font: { fontSize:'25sp' }, text: '', textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER, top: 200, width: Ti.UI.SIZE, height: Ti.UI.SIZE }); self.add(lblWinner); /* //Sample implementation 4 var config = JSON.parse(JSON.stringify(SpriteConfig.Mega));//deep copy obj to prevent changes from interfering with any other references to the object later in code config.loops=1; var spriteMega = new SpriteCore(config); self.add(spriteMega.createSprite({ spriteStartCustomFrame:{x:0,y:225,h:48,w:80}, })); spriteMega.spriteView.top=75; spriteMega.spriteView.left=20; var arr=[//sprite scaling handled in the functions for you, use 1:1 locations {x:0,y:416,h:76,w:58}, {x:58,y:416,h:76,w:66}, {x:124,y:416,h:76,w:112}, {x:236,y:416,h:76,w:112}, {x:348,y:416,h:76,w:116}, {x:464,y:416,h:76,w:116}, {x:580,y:416,h:76,w:88}, {x:668,y:416,h:76,w:72}, ]; spriteMega.start({ animationCustomArray:arr, time:1000 }); var spriteMega = new SpriteCore(SpriteConfig.Mega); self.add(spriteMega.createSprite({ spriteStartCustomFrame:{x:8,y:80,h:72,w:52}, })); spriteMega.spriteView.top=175; spriteMega.spriteView.left=20; var arr=[//sprite scaling handled in the functions for you, use 1:1 locations {x:8,y:80,h:72,w:50}, {x:58,y:80,h:72,w:50}, {x:108,y:80,h:72,w:50}, {x:158,y:80,h:72,w:50}, ]; spriteMega.start({ animationCustomArray:arr, time:1000 }); */ return self; } module.exports = FirstView;
JavaScript
0.000001
@@ -1785,37 +1785,9 @@ -spinButton.setEnabled(true); %0A + %09%09 @@ -1909,16 +1909,16 @@ tFrame)%0A - %09%09 %09l @@ -1942,16 +1942,241 @@ NNER!';%0A +%09%09 else if(sprite.spriteCurrentFrame === 5 %7C%7C sprite2.spriteCurrentFrame === 5 %7C%7C sprite3.spriteCurrentFrame==5)%0A%09%09 %09lblWinner.text='well you got a cherry, %5Cnguess that is something';%0A%09%09 spinButton.setEnabled(true);%0A %09%09%7D, spi
60fd91845b5a0cf967258cf04bc4c090da0f900a
change menu item height
application/views/Menu.js
application/views/Menu.js
import React from 'react'; import { VrButton, Text, View } from 'react-vr'; const DEG_IN_RAD = 57.2958; class MenuItem extends React.Component { constructor(props) { super(props); this.state = { isHovered: false, } } render = () => ( <VrButton onClick={this.props.onClick} onEnter={() => {this.setState({isHovered: true})}} onExit={() => {this.setState({isHovered: false})}} style={{ margin: 0.1, height: 0.3, backgroundColor: this.props.color, borderColor: this.state.isHovered ? 'yellow' : null, borderWidth: this.state.isHovered ? 0.005 : null, }} > <Text style={{fontSize: 0.2, textAlign: 'center'}}>{this.props.caption}</Text> </VrButton> ) } MenuItem.propTypes = { caption: React.PropTypes.string.isRequired, color: React.PropTypes.string, onClick: React.PropTypes.func, }; const Menu = ({head, items}) => ( <View style={{ flex: 1, flexDirection: 'column', width: 2, alignItems: 'stretch', transform: [ {rotateY: head.rot.Y}, {rotateX: head.rot.X}, {translate: [-1, 1, -3]}, ] }} > {(items || []).map((item, ix) => <MenuItem caption={item.caption} color={item.color} onClick={ item.action ? () => item.action(...(item.args || [])) : null } key={`${ix}-${item.caption}`} />)} </View> ); Menu.propTypes = { head: React.PropTypes.shape({ rot: React.PropTypes.shape({ X: React.PropTypes.number.isRequired, Y: React.PropTypes.number.isRequired, Z: React.PropTypes.number.isRequired, }) }).isRequired, items: React.PropTypes.arrayOf( React.PropTypes.shape({ caption: React.PropTypes.string.isRequired, color: React.PropTypes.string, onClick: React.PropTypes.func, }) ).isRequired, }; export default Menu;
JavaScript
0.000001
@@ -541,17 +541,17 @@ ight: 0. -3 +4 ,%0A
8b49d385a01955f1cd366fa16289f2a1a7b236e3
improve test robustness for slow Safari
history/test/browser/xstream.js
history/test/browser/xstream.js
import * as assert from 'assert'; import xs from 'xstream'; import Cycle from '@cycle/xstream-run'; import XSAdapter from '@cycle/xstream-adapter'; import {makeDOMDriver, h} from '@cycle/dom'; import {createHistory} from 'history'; import { makeHistoryDriver, createServerHistory, createLocation, supportsHistory } from '../../lib/index'; const locationDefaults = { pathname: '/', action: 'POP', hash: '', search: '', state: null, key: null, query: null, }; function createRenderTarget(id = null) { let element = document.createElement(`div`); element.className = `cycletest`; if (id) { element.id = id; } document.body.appendChild(element); return element; }; describe('History - XStream', () => { describe('createLocation', () => { it(`should return a full location with no parameter`, () => { assert.deepEqual(createLocation(), locationDefaults); }); it(`should accept just a string as the pathname`, () => { assert.deepEqual(createLocation(`/`), locationDefaults); }); it(`should accept an object of location parameters`, () => { const location = createLocation({pathname: `/some/path`, state: {the: `state`}}); const refLocattion = Object.assign(locationDefaults, { pathname: `/some/path`, state: {the: `state`}, }); assert.deepEqual(location, refLocattion); }); }); describe(`supportsHistory`, () => { it(`should return true if the browser supports history API`, () => { assert.strictEqual(supportsHistory(), true); }); }); describe('createServerHistory', () => { it(`should be an object`, () => { const history = createServerHistory(); assert.strictEqual(typeof history, `object`); assert.strictEqual(typeof history.push, `function`); assert.strictEqual(typeof history.listen, `function`); assert.strictEqual(typeof history.replace, `function`); }); it(`should return a function when .listen() is called`, () => { const history = createServerHistory(); const unlisten = history.listen(() => { return void 0; }); assert.strictEqual(typeof unlisten, `function`); unlisten(); }); it(`should allow pushing locations`, (done) => { const history = createServerHistory(); history.listen(location => { assert.strictEqual(typeof location, `object`); assert.strictEqual(location.pathname, `/some/path`); done(); }); history.push(`/some/path`); }); it(`should create an href`, () => { const history = createServerHistory(); assert.strictEqual(history.createHref(`/some/path`), `/some/path`); }); it(`should create a location`, () => { const history = createServerHistory(); const location = history.createLocation(`/some/path`); assert.strictEqual(typeof location, `object`); assert.strictEqual(location.pathname, `/some/path`); assert.strictEqual(location.state, undefined); assert.strictEqual(location.query, null); }); }); describe(`historyDriver`, () => { it(`should throw if not given a valid history object`, () => { assert.throws(() => { makeHistoryDriver(); }, TypeError); }); it(`should capture link clicks when capture === true`, done => { const pathname = window.location.pathname const app = () => ({DOM: xs.of( h(`div`, [ h(`a.link`, {props: {href: pathname + `/hello`}}, `Hello`), ]) )}) const {sources, run} = Cycle(app, { DOM: makeDOMDriver(createRenderTarget()), history: makeHistoryDriver(createHistory(), {capture: true}), }) let dispose; sources.history .filter(({action}) => action === `PUSH`) .addListener({ next: location => { assert.strictEqual(typeof location, `object`); assert.strictEqual(location.pathname, pathname + `/hello`); setTimeout(() => { dispose(); done(); }); }, error: () => {}, complete: () => {} }); sources.DOM.elements().drop(1).take(1).addListener({ next: (root) => { const element = root.querySelector(`.link`); assert.strictEqual(element.tagName, `A`); setTimeout(() => { element.click(); }, 1000) }, error: () => {}, complete: () => {} }); dispose = run(); }) it(`should return a stream with createHref() and createLocation() methods`, () => { const history = createServerHistory(); const history$ = makeHistoryDriver(history)(xs.of(`/`), XSAdapter); assert.strictEqual(history$ instanceof xs, true); assert.strictEqual(typeof history$.createHref, `function`); assert.strictEqual(typeof history$.createLocation, `function`); }); it('should allow pushing to a history object', (done) => { const history = createHistory(); const app = () => ({}) const {sources, run} = Cycle(app, { history: makeHistoryDriver(history) }) let dispose; sources.history.filter(({action}) => action === 'PUSH').addListener({ next(location) { assert.strictEqual(location.pathname, '/test'); setTimeout(() => { dispose(); done(); }) }, error: () => {}, complete: () => {} }) setTimeout(() => { dispose = run(); history.push('/test') }) }) it(`should return a location to application`, (done) => { const app = () => ({history: xs.of(`/`)}); const {sources, run} = Cycle(app, { history: makeHistoryDriver(createHistory()), }); let dispose; sources.history.drop(1).take(1).addListener({ next: (location) => { assert.strictEqual(typeof location, `object`); assert.strictEqual(location.pathname, `/`); assert.strictEqual(location.state, undefined); setTimeout(() => { dispose(); done(); }); }, error() { return void 0; }, complete() { return void 0; }, }); dispose = run(); }); it(`should allow replacing a location`, (done) => { const app = () => ({ history: xs.of({ type: `replace`, pathname: `/`, }), }); const {sources, run} = Cycle(app, { history: makeHistoryDriver(createHistory()), }); let dispose; sources.history.drop(1).take(1).addListener({ next(location) { assert.strictEqual(typeof location, `object`); assert.strictEqual(location.pathname, `/`); assert.strictEqual(location.state, undefined); setTimeout(() => { dispose(); done(); }); }, error() { return void 0; }, complete() { return void 0; }, }); dispose = run(); }); }); });
JavaScript
0.000019
@@ -3307,24 +3307,50 @@ , done =%3E %7B%0A + this.timeout(4000);%0A const @@ -4522,17 +4522,16 @@ run();%0A -%0A %7D)%0A%0A
6a7c1f02e35ffc67b70b5514016b3ece48c36a47
fix invalid 'activityTypes/clear' action
src/activities/datastore/activityTypes.js
src/activities/datastore/activityTypes.js
import activityTypes from '@/activities/api/activityTypes' import { createMetaModule, indexById, metaStatuses, metaStatusesWithId, withMeta } from '@/utils/datastore/helpers' import i18n from '@/base/i18n' function initialState () { return { entries: {}, } } export default { namespaced: true, modules: { meta: createMetaModule() }, state: initialState(), getters: { get: (state, getters) => activityTypeId => { return getters.enrich(state.entries[activityTypeId]) }, all: (state, getters) => Object.values(state.entries).map(getters.enrich), enrich: (state, getters) => activityType => { if (!activityType) return const { id, icon, feedbackIcon, name, nameIsTranslatable } = activityType // this corresponds to the name used by the activity type stylesheet plugin const colorName = `activity-type-${id}` const translatedName = nameIsTranslatable ? i18n.t(`ACTIVITY_TYPE_NAMES.${name}`) : name return { ...activityType, translatedName, colorName, iconProps: { name: icon, color: colorName, title: translatedName, }, feedbackIconProps: { name: feedbackIcon, color: colorName, title: translatedName, }, ...metaStatusesWithId(getters, ['save'], activityType.id), } }, byCurrentGroup: (state, getters, rootState, rootGetters) => { return getters.all.filter(({ group }) => group === rootGetters['currentGroup/id']) }, activeByCurrentGroup: (state, getters) => { return getters.byCurrentGroup.filter(activityType => activityType.status === 'active') }, ...metaStatuses(['create']), }, actions: { ...withMeta({ async fetch ({ commit }) { commit('update', await activityTypes.list()) }, async save ({ commit, dispatch }, activityType) { const data = await activityTypes.save(activityType) commit('update', [data]) dispatch('toasts/show', { message: 'NOTIFICATIONS.CHANGES_SAVED', config: { timeout: 2000, icon: 'thumb_up', }, }, { root: true }) }, async create ({ commit, dispatch, rootGetters }, data) { await activityTypes.create({ group: rootGetters['currentGroup/id'], ...data }) dispatch('refresh') }, }), refresh ({ dispatch }) { dispatch('fetch') }, }, mutations: { clear (state) { Object.assign(state, initialState()) }, update (state, activityTypes) { state.entries = Object.freeze({ ...state.entries, ...indexById(activityTypes) }) }, delete (state, activityTypeId) { if (!state.entries[activityTypeId]) return const { [activityTypeId]: _, ...rest } = state.entries Object.freeze(rest) state.entries = rest }, }, } export function plugin (datastore) { datastore.watch((state, getters) => getters['auth/isLoggedIn'], isLoggedIn => { if (isLoggedIn) { datastore.dispatch('activityTypes/fetch') } else { datastore.dispatch('activityTypes/clear') } }) }
JavaScript
0.000331
@@ -3109,32 +3109,30 @@ datastore. -dispatch +commit ('activityTy
e5c2e7d1feb465495e3f706f5dc5f2ba0f65d587
Make default code more sensible (on instead of off)
public/js/editor.js
public/js/editor.js
define(['codemirror', 'matchbrackets', 'continuecomment', 'javascripthint', 'javascriptmode'], function() { function initEditor($e) { return CodeMirror($e.get(0), { value: "function effect(cube) {\n cube().off();\n}", mode: 'javascript', indentUnit: 4, lineWrapping: true, lineNumbers: true, matchBrackets: true }); } return initEditor; });
JavaScript
0
@@ -227,18 +227,17 @@ cube().o -ff +n ();%5Cn%7D%22,
4d3acfb14c054cde866905309acc478be5ebc6d0
fix error message
src/administrative-sdk/profile/profile.js
src/administrative-sdk/profile/profile.js
/** * Profile domain model. A profile is part of a {@link User} and stores general information about the user. */ export default class Profile { /** * Create a Profile. * * @param {string} firstName - The first name of the {@link User}. * @param {string} lastName - The last name of the {@link User}. * @param {?string} [infix] - The infix of the {@link User}'s name. * @param {string} gender - The gender of the {@link User}. * @param {Date} birthDate - The birth date of the {@link User}. * @throws {Error} firstName parameter of type "string" is required. * @throws {Error} lastName parameter of type "string" is required. * @throws {Error} gender parameter of type "string" is required. * @throws {Error} birthDate parameter of type "Date" is required. */ constructor(firstName, lastName, infix = null, gender, birthDate) { if (typeof firstName !== 'string') { throw new Error('firstName parameter of type "string" is required'); } /** * The first name of the {@link User}. * @type {string} */ this.firstName = firstName; if (typeof lastName !== 'string') { throw new Error('lastName parameter of type "string" is required'); } /** * The last name of the {@link User}. * @type {string} */ this.lastName = lastName; if (infix !== null && typeof infix !== 'string') { throw new Error('infix parameter of type "string|null" is required'); } /** * @type {string} The infix of the {@link User}'s name. */ this.infix = infix; if (typeof gender !== 'string') { throw new Error('gender parameter of type "string" is required'); } /** * The gender of the {@link User}. * @type {string} */ this.gender = gender; if (!(birthDate instanceof Date)) { throw new Error('birthDate parameter of type "string" is required'); } /** * The birth date of the {@link User}. * @type {Date} */ this.birthDate = birthDate; } }
JavaScript
0
@@ -1876,38 +1876,36 @@ ameter of type %22 -string +Date %22 is required');
9cff9b00e468c05fd38744eac4ae3833a38d7898
Update person.js
public/js/person.js
public/js/person.js
var Persons = { hatids : 0, bodyids : 0, faceids : 0, personids : 0, //last persons arrive time lpersonarrtime : 0, hatscount : 6, facescount : 6, bodiescount : 3, allPersons : [], Hats : [], Bodies : [], Faces : [], update : function() { if(Date.now() - this.lpersonarrtime > 4000 && this.allPersons.length < 10){ this.addPersonToLine(); } }, addAllHatTextures : function() { var test = 1; var count = 0; for(count = 0; count < this.hatscount; count++) { test = Texture.addTexture("hat" + count, "assets/img/hat" + count + ".png"); this.Hats.push(new Hat("hat" + count, "assets/img/hat" + count + ".png")); } }, addAllFaceTextures : function() { var test = 1; var count = 0; for(count = 0; count < this.facescount; count++) { test = Texture.addTexture("head" + count, "assets/img/head" + count + ".png"); this.Faces.push(new Face("head" + count, "assets/img/head" + count + ".png")); } }, addAllBodyTextures : function() { var test = 1; var count = 0; for(count = 0; count < this.bodiescount; count++) { test = Texture.addTexture("body" + count, "assets/img/body" + count + ".png"); this.Bodies.push(new Body("body" + count, "assets/img/body" + count + ".png")); } }, addTexture : function(name,source) { var img = new Image(); img.onload = function() { Texture.textureLoaded(img, name); img.src = source; }; img.onerror = function() { console.log("Failed to load texture " + name + " from "+ source); }; img.src = source; return 1; }, initPersons : function() { this.addAllHatTextures(); this.addAllBodyTextures(); this.addAllFaceTextures(); }, getRandomHat : function() { var item = this.Hats[Math.floor(Math.random()*this.Hats.length)]; return item; }, getRandomBody : function() { var item = this.Bodies[Math.floor(Math.random()*this.Bodies.length)]; return item; }, getRandomFace : function() { var item = this.Faces[Math.floor(Math.random()*this.Faces.length)]; return item; }, addPersonToLine : function() { var p = new Person(); this.allPersons.push(p); Engine.addObject(p); this.lpersonarrtime = Date.now(); }, renderAllPersons : function() { for(var i = 0; i < this.allPersons.length; i++) { } } } function Hat(img){this.id = Persons.hatids++; this.name = img;}; function Body(img){this.id = Persons.bodyids++; this.name = img;}; function Face(img){this.id = Persons.faceids++; this.name = img;}; function Person() { GameObject.call(this); //TODO: find positions for the parts this.hatoffset = new Vector2(0, -30); this.bodyoffset = new Vector2(0, 0); this.faceoffset = new Vector2(30, 0); this.position = new Vector2(window.innerWidth, -100); this.size = new Vector2(160, 300); this.checkForInput = true; this.sizehat = new Vector2(180, 170); this.sizeface = new Vector2(130, 170); this.sizebody = new Vector2(200, 300); this.drawOffset = Context.drawOffset["behindDesk"]; this.depth = -30; this.targetpos = new Vector2(1000 + Persons.allPersons.length * 100, -100); this.entering = true; this.a = 0; this.update = function() { //TODO: only update in right context if(this.entering) { this.a += 0.1; this.position = new Vector2(this.position.x - 1, -100 + 10 * Math.sin(this.a)); if(this.position.x <= this.targetpos.x){ this.entering = false; } } } this.hat = Persons.getRandomHat(); this.face = Persons.getRandomFace(); this.body = Persons.getRandomBody(); this.id = Persons.personids++; this.draw = function() { //TODO: persons in line are rendered in wrong order. context.drawImage(Texture.map[this.body.name], this.position.x + this.bodyoffset.x, this.position.y + this.bodyoffset.y, this.sizebody.x, this.sizebody.y); context.drawImage(Texture.map[this.face.name], this.position.x + this.faceoffset.x, this.position.y + this.faceoffset.y, this.sizeface.x, this.sizeface.y); context.drawImage(Texture.map[this.hat.name], this.position.x + this.hatoffset.x, this.position.y + this.hatoffset.y, this.sizehat.x, this.sizehat.y); } }; Person.prototype = new GameObject(); Person.constructor = Person.Object;
JavaScript
0.000001
@@ -144,17 +144,17 @@ count : -6 +7 ,%0A%09faces
f15c3287f4a4180830087f046a0b7b71901d1c6d
Update status.js
public/js/status.js
public/js/status.js
/*global angular, localStorage*/ angular .module('IsTheDungeonPrinterDown', []) .controller('StatusController', StatusController); function StatusController($http) { // Ah, arrow functions, please come soon. var self = this; // Shamelessly ripped from stack overflow because that's the // spirit of weekend hacking and this isn't node.js so I // don't have that swanky crypto module. function randomString(length, chars) { var result = ''; for (var i = length; i > 0; --i) { result += chars[Math.round(Math.random() * (chars.length - 1))]; } return result; } this.localAuth = function() { var tokenLength = 128; var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; if (!localStorage.authToken || localStorage.authToken.length < tokenLength) { // Yup, you could totally just set this thing to something // else and fuck my day up. localStorage.authToken = randomString( tokenLength, characters ); } }; this.reportStatus = function(status) { self.localAuth(); self.report = {}; self.report.status = status; self.report.authtoken = localStorage.authToken; $http.post('/report', self.report).then(function(res) { self.getStatus(); }, function(err) { console.err('Something went horribly wrong.'); }); }; this.getStatus = function() { $http.get('/status').then(function(res) { self.status = res.data.status; if (self.status == 'down') { self.bgClass = 'red-bg'; self.emojiClass = 'twa twa-scream'; self.footerClass = 'footer-red'; self.saying = 'PROBS.'; } else { self.bgClass = 'green-bg'; self.emojiClass = 'twa twa-sunglasses'; self.footerClass = 'footer-green'; self.saying = 'NAH.'; } }, function(err) { console.err('Something went horribly wrong.'); }); }; }; StatusController.$inject = ['$http'];
JavaScript
0.000002
@@ -1209,19 +1209,21 @@ = %7B -%7D;%0A +%0A self @@ -1222,36 +1222,23 @@ -self.report. status - = +: status -; +, %0A @@ -1246,31 +1246,22 @@ -self.report. + auth -t +T oken - = +: loc @@ -1279,16 +1279,26 @@ uthToken +%0A %7D ;%0A
c9509d66ecf27a18e4eb114e0811e4ec20b73884
update restTest for profile
src/backend/rest/profile/test/restTest.js
src/backend/rest/profile/test/restTest.js
var orm = require('../../../dbbs'); var Profile = orm.model("switch_profile"); var request = require('request'); var assert = require('assert'); var fs = require('fs'); //orm.setup() var token, sessKey; // ---------------------------------------------------------------------------- // Testing create profile describe('Testing create profile requests:',function() { // Register, verify, then login a subscriber before(function(done) { this.timeout(5000); request( { // register subscriber url: 'http://localhost:3000/api/subscriber/register', body: '{ \"email\": \"flowgrammablemailer@gmail.com\", \"password\": \"my password\"}', headers: { 'Content-Type': 'application/json' }, method: 'POST' }, function (error, response, body) { console.log(body); assert(JSON.parse(body)['value'],'Unable to register user'); fs.readFile(process.cwd()+'/temp','utf8',function (err,data) { if (err) console.log('Unable to read token in file for restTest'); else { var array = data.toString().split("\n"); token = JSON.parse(array[0]).ver_token; request( { // verify subscriber url: 'http://localhost:3000/api/subscriber/verify/', body: '{ \"token\": \"'+token+'\"}', headers: { 'Content-Type': 'application/json' }, method: 'POST' }, function (error, response, body) { assert(JSON.parse(body)['value'],'Unable to verify user'); request( { // login subscriber url: 'http://localhost:3000/api/subscriber/login', body: '{ \"email\": \"flowgrammablemailer@gmail.com\", \"password\": \"my password\"}', headers: { 'Content-Type': 'application/json' }, method: 'POST' }, function (error, response, body) { assert(JSON.parse(body)['value'],'Unable to login user'); sessKey = JSON.parse(body)['value']; done(); }); }); } }); }); }); it('A request that is successful should return msg.success()', function(done) { request( { url: 'http://localhost:3000/api/profile/create', body: '{ \"name\": \"test profile\"}', headers: { 'Content-Type':'application/json', 'x-access-token': sessKey }, method: 'POST' }, function (error, response, body) { assert(JSON.parse(body)['value'],'Unable to create profile'); console.log('\tResponse received : ', body); done(); }); }); it('A request with a missing name should return msg.missingName()', function(done) { request( { url: 'http://localhost:3000/api/profile/create', body: '{ \"name\": \"\"}', headers: { 'Content-Type':'application/json', 'x-access-token': sessKey }, method: 'POST' }, function (error, response, body) { assert.equal(JSON.parse(body)['error']['type'],'missingName'); console.log('\tResponse received : ', body); done(); }); }); }); // -------------------------------------------------------------------------- // Testing update profile describe('Testing update profile request: ', function() { it('Test: PUT to /api/profile/update without an id in the body should return msg.missingId()', function(done) { request( { url: 'http://localhost:3000/api/profile/update', body: '{ \"name\": \"test profile\"}', headers: { 'Content-Type':'application/json', 'x-access-token': sessKey }, method: 'PUT' }, function (error, response, body) { assert.equal(JSON.parse(body)['error']['type'],'missingId'); console.log('\tResponse received : ', body); done(); }); }); });
JavaScript
0
@@ -3191,16 +3191,641 @@ ion() %7B%0A +%0A%09it('Test: Successful update of profile PUT /api/profile/update %7Bid: id, name: name%7D should return msg.success()', %0A%09function(done) %7B%0A%09%09request( %7B%0A%09%09%09url: 'http://localhost:3000/api/profile/update',%0A%09%09%09body: '%7B%5C%22id%5C%22: %5C%221%5C%22, %5C%22name%5C%22: %5C%22test profile%5C%22%7D',%0A%09%09%09headers: %7B 'Content-Type':'application/json', 'x-access-token': sessKey %7D,%0A method: 'PUT'%0A %7D, function (error, response, body) %7B%0A assert(JSON.parse(body)%5B'value'%5D,'Unable to update profile');%0A console.log('%5CtResponse received : ', body);%0A done();%0A%09%09%7D);%0A%09%7D);%0A%0A %09it('Tes @@ -4322,17 +4322,19 @@ %09%7D);%0A %09%7D);%0A +%09%0A %7D);%0A%0A
6ff3120a8ae7d1ef504c65e8e17be5c127b12f13
Fix codebox.io api url
bin/codebox.js
bin/codebox.js
#!/usr/bin/env node var _ = require('underscore'); var cli = require('commander'); var open = require("open"); var pkg = require('../package.json'); var codebox = require("../index.js"); // Options cli.option('-p, --port [http port]', 'Port to run the IDE'); cli.option('-t, --title [project title]', 'Title for the project.'); cli.option('-o, --open', 'Open the IDE in your favorite browser') // Command 'run' cli.command('run [folder]') .description('Run a Codebox into a specific folder.') .action(function(projectDirectory) { var that = this; // Codebox.io settings this.box = process.env.CODEBOXIO_BOXID; this.key = process.env.CODEBOXIO_TOKEN; this.codeboxio = process.env.CODEBOXIO_HOST || "https://api.codenow.io"; // Default options this.directory = projectDirectory || process.env.WORKSPACE_DIR || "./"; this.title = this.title || process.env.WORKSPACE_NAME; this.port = this.port || process.env.PORT || 5000; var config = { 'root': this.directory, 'title': this.title, 'server': { 'port': parseInt(this.port) } }; // Use Codebox if (this.box && this.codeboxio && this.key) { _.extend(config, { 'workspace': { 'id': this.box }, 'hooks': { 'auth': this.codeboxio+"/api/box/"+this.box+"/auth", 'events': this.codeboxio+"/api/box/"+this.box+"/events", 'settings': this.codeboxio+"/api/account/settings" }, 'webhook': { 'authToken': this.key }, 'proc': { 'urlPattern': 'http://web-%d.' + this.box + '.vm1.dynobox.io' } }); } // Start Codebox codebox.start(config).then(function() { var url = "http://localhost:"+that.port; console.log("\nCodebox is running at",url); if (that.open) { open(url); } }, function(err) { console.error('Error initializing CodeBox'); console.error(err); console.error(err.stack); // Kill process process.exit(1); }); }); cli.on('--help', function(){ console.log(' Examples:'); console.log(''); console.log(' $ codebox run'); console.log(' $ codebox run ./myProject'); console.log(''); console.log(' Use option --open to directly open the IDE in your browser:'); console.log(' $ codebox run ./myProject --open'); console.log(''); }); cli.version(pkg.version).parse(process.argv); if (!cli.args.length) cli.help();
JavaScript
0.000245
@@ -736,11 +736,11 @@ code -now +box .io%22 @@ -1129,24 +1129,27 @@ Use Codebox +.io %0A if (thi
86c8b82a3d90f26869f478de44a383aec0446d4a
remove debug log statement
bin/compile.js
bin/compile.js
import fs from 'fs-extra' import _debug from 'debug' import webpackCompiler from '../build/webpack-compiler' import webpackConfig from '../build/webpack.config' import config from '../config' const debug = _debug('app:bin:compile') const paths = config.utils_paths ;(async function () { try { debug('Run compiler') const stats = await webpackCompiler(webpackConfig) console.log('stats', stats) if (stats.warnings.length && config.compiler_fail_on_warning) { debug('Config set to fail on warning, exiting with status code "1".') process.exit(1) } debug('Copy static assets to dist folder.') fs.copySync(paths.client('static'), paths.dist()) } catch (e) { debug('Compiler encountered an error.', e) process.exit(1) } })()
JavaScript
0.000027
@@ -375,40 +375,8 @@ ig)%0A - console.log('stats', stats)%0A
96ad185833fe66057a5d599a0c6bcc87a92f1024
fix harvester
role.harvester.js
role.harvester.js
/** * Created by truthlighting on 9/14/2016. */ var roleHarvester = { /** @param {Creep} creep **/ run: function(creep) { if(creep.memory.transporting && creep.carry.energy == 0) { creep.memory.transporting = false; creep.say("Harvesting"); } if (!creep.memory.transporting && creep.carry.energy == creep.carryCapacity || ((!creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE)) && creep.carry.energy > 0)) { creep.memory.transporting = true; creep.say("Xporting"); } if(!creep.memory.transporting) { //var sources = creep.room.find(FIND_SOURCES); var activeSource = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE); /*, { filter: (source) => { source.energy > 0 } })*/ //creep.say("H-"+target); //creep.say("H - " + target.energy); if(creep.harvest(activeSource) == ERR_NOT_IN_RANGE) { creep.moveTo(activeSource); //if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { // creep.moveTo(sources[0]); } } else { var energyStorageStructures = creep.room.find(FIND_STRUCTURES, { filter: (structure) => { return (structure.structureType == STRUCTURE_EXTENSION || // structure.structureType == STRUCTURE_CONTAINER || structure.structureType == STRUCTURE_SPAWN || structure.structureType == STRUCTURE_TOWER) && (structure.energy < structure.energyCapacity || _.sum(structure.store) < structure.storeCapacity); } }) if(energyStorageStructures.length > 0) { var energyStorageStructure = creep.pos.findClosestByPath(energyStorageStructures); if(creep.transfer(energyStorageStructure, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) { creep.moveTo(energyStorageStructure); } } else { var structuresToRepair = creep.room.find(FIND_STRUCTURES, { filter: function(object){ return (object.structureType == STRUCTURE_ROAD || object.structureType == STRUCTURE_CONTAINER ) && (object.hits < object.hitsMax); } }); if (structuresToRepair.length > 0){ var structureToRepair = creep.pos.findClosestByPath(structuresToRepair); if (creep.repair(structureToRepair) === ERR_NOT_IN_RANGE) { creep.moveTo(structureToRepair); creep.say("Mvg to Repair"); } // perhaps check the results again? } else { // nothing to repair creep.moveTo(Game.flags.Flag1); } } } } }; module.exports = roleHarvester;
JavaScript
0.000002
@@ -1383,26 +1383,24 @@ -//
8648ff96338edf73d31b8a6940e1e9355f882cd0
send data in response
routes/geocode.js
routes/geocode.js
var express = require('express'); var debug = require('debug')('geocode'); var fb = require('fb'); var moment = require('moment'); var g_API_key = ['AIzaSyD4C_0grHO3gWxgCLGbndJy_ejDXbKNDXk', ]; var g_API_key_offset = 0; var hat = require('hat'); var request = require('request'); var THRESHOLD = 15; var router = express.Router(); router.get('/', function(req, res) { res.render('index'); }); router.get('/fb_events', function(req, res) { var FB = require('fb'); FB.setAccessToken('CAAJlnCaKfaEBAGqSUnt7uXlTBMx8PHwfBzHsnv8zStSXAj7Q8mVAa1ZC11wARDZBka3446X4GdQGSyc10C43cqGCDT5lYqOrfBy8huDd4PeENYQDiXTIdW0okPtYqHpoUZBaOo75oNWZAB9Kp3aaKBn7QVhtdl4SLTDdLsM2DOtcdyA6hfPcSrXo2tgGzOO4TfGOYWmQHJFGwYc9eqfwnwwyWdD3s0TMpgmT6ZAsOOQZDZD' || req.body.authToken); FB.api('me/events', function(events) { if (!events || events.error) { console.log(!events ? 'error occurred' : events.error); res.send(events.error); } console.log(events); }); }); router.post('/insight', function(req, res) { // require the google places module inside the route handler to change the config key var googleplaces = require('googleplaces')(g_API_key[g_API_key_offset], 'json'); // start a RadarSearch via the Google Places API // use default radius as 500m // default seach category is 'restaurants' googleplaces.radarSearch({ location: [Number(req.body.latitude), Number(req.body.longitude)], radius: req.body.radius || '500', types: ['restaurant'] }, function(error, response) { if (error) { // if there's an error, send back the error res.send(error); } else { // for every place reference in the response, gather meta-info var placeDetails = []; // only gather info for the first <THRESHOLD> references var resultCount = THRESHOLD; console.log('found ' + response.results.length + ' results'); console.log('Extracting information for the top: ' + THRESHOLD) if (response.results.length > 0) { for (var i = 0; i < THRESHOLD; i++) { // using the reference field, make individual PlaceDetails requests via the Places API googleplaces.placeDetailsRequest({ reference: response.results[i].reference }, function(detailsErr, details) { // must have lat/long geometry for insight if (details.result.geometry) { // push only relevent API response information placeDetails.push({ name: details.result.name, location: details.result.geometry.location, icon: details.result.icon, place_id: details.result.place_id, address: details.result.formatted_address, website: details.result.website }); // IMPORTANT: do not modify // async check counter (only sends response when all meta-inf has been retrieved) if (placeDetails.length == resultCount) { res.send(placeDetails); } } else { // decrement check counter if result does not have geometry resultCount -= 1; } }); } } else { res.send([]); } } }); }); module.exports = router;
JavaScript
0
@@ -915,27 +915,24 @@ ;%0A%09%09%7D%0A%09%09 -console.log +res.send (events)
c6a46f159bf5b68ad76fbdf5092174ed535fe524
fix chrome context menu error, closes #629
shells/chrome/src/background.js
shells/chrome/src/background.js
// the background script runs all the time and serves as a central message // hub for each vue devtools (panel + proxy + backend) instance. const ports = {} chrome.runtime.onConnect.addListener(port => { let tab let name if (isNumeric(port.name)) { tab = port.name name = 'devtools' installProxy(+port.name) } else { tab = port.sender.tab.id name = 'backend' } if (!ports[tab]) { ports[tab] = { devtools: null, backend: null } } ports[tab][name] = port if (ports[tab].devtools && ports[tab].backend) { doublePipe(tab, ports[tab].devtools, ports[tab].backend) } }) function isNumeric (str) { return +str + '' === str } function installProxy (tabId) { chrome.tabs.executeScript(tabId, { file: '/build/proxy.js' }, function (res) { if (!res) { ports[tabId].devtools.postMessage('proxy-fail') } else { console.log('injected proxy to tab ' + tabId) } }) } function doublePipe (id, one, two) { one.onMessage.addListener(lOne) function lOne (message) { if (message.event === 'log') { return console.log('tab ' + id, message.payload) } console.log('devtools -> backend', message) two.postMessage(message) } two.onMessage.addListener(lTwo) function lTwo (message) { if (message.event === 'log') { return console.log('tab ' + id, message.payload) } console.log('backend -> devtools', message) one.postMessage(message) } function shutdown () { console.log('tab ' + id + ' disconnected.') one.onMessage.removeListener(lOne) two.onMessage.removeListener(lTwo) one.disconnect() two.disconnect() ports[id] = null updateContextMenuItem() } one.onDisconnect.addListener(shutdown) two.onDisconnect.addListener(shutdown) console.log('tab ' + id + ' connected.') updateContextMenuItem() } chrome.runtime.onMessage.addListener((req, sender) => { if (sender.tab && req.vueDetected) { const suffix = req.nuxtDetected ? '.nuxt' : '' chrome.browserAction.setIcon({ tabId: sender.tab.id, path: { 16: `icons/16${suffix}.png`, 48: `icons/48${suffix}.png`, 128: `icons/128${suffix}.png` } }) chrome.browserAction.setPopup({ tabId: sender.tab.id, popup: req.devtoolsEnabled ? `popups/enabled${suffix}.html` : `popups/disabled${suffix}.html` }) } }) // Right-click inspect context menu entry let activeTabId chrome.tabs.onActivated.addListener(({ tabId }) => { activeTabId = tabId updateContextMenuItem() }) function updateContextMenuItem () { if (ports[activeTabId]) { chrome.contextMenus.create({ id: 'vue-inspect-instance', title: 'Inspect Vue component', contexts: ['all'] }) } else { chrome.contextMenus.remove('vue-inspect-instance') } } chrome.contextMenus.onClicked.addListener((info, tab) => { chrome.runtime.sendMessage({ vueContextMenu: { id: info.menuItemId } }) })
JavaScript
0.000001
@@ -2595,16 +2595,58 @@ em () %7B%0A + chrome.contextMenus.removeAll(() =%3E %7B%0A if (po @@ -2665,24 +2665,26 @@ bId%5D) %7B%0A + + chrome.conte @@ -2702,24 +2702,26 @@ ate(%7B%0A + id: 'vue-ins @@ -2742,16 +2742,18 @@ ,%0A + + title: ' @@ -2776,16 +2776,18 @@ onent',%0A + co @@ -2810,80 +2810,23 @@ -%7D)%0A %7D else %7B%0A chrome.contextMenus.remove('vue-inspect-instance') + %7D)%0A %7D %0A %7D +) %0A%7D%0A%0A
76cc8939d961d4696d74408b01e9e4040141acc6
Update to Tag Manager
components/GoogleAnalytics/GoogleAnalytics.js
components/GoogleAnalytics/GoogleAnalytics.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React from 'react'; import { googleAnalyticsId } from '../../config'; const trackingCode = { __html: `(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=` + `function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;` + `e=o.createElement(i);r=o.getElementsByTagName(i)[0];` + `e.src='https://www.google-analytics.com/analytics.js';` + `r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));` + `ga('create','${googleAnalyticsId}','auto');`, }; function GoogleAnalytics() { return <script dangerouslySetInnerHTML={trackingCode} />; } export default GoogleAnalytics;
JavaScript
0
@@ -254,18 +254,16 @@ __html:%0A - %60(functi @@ -269,163 +269,106 @@ ion( -b,o,i,l,e,r)%7Bb.GoogleAnalyticsObject=l;b%5Bl%5D%7C%7C(b%5Bl%5D=%60 +%0A %60function()%7B(b%5Bl%5D.q=b%5Bl%5D.q%7C%7C%5B%5D).push(arguments)%7D);b%5Bl%5D.l=+new Date;%60 +%0A %60e=o.createElement(i);r=o +w,d,s,l,i)%7Bw%5Bl%5D=w%5Bl%5D%7C%7C%5B%5D;w%5Bl%5D.push(%7B'gtm.start':%60 +%0A%60new Date().getTime(),event:'gtm.js'%7D);var f=d .get @@ -389,83 +389,139 @@ ame( -i +s )%5B0%5D -; +, %60 +%0A - %60e.src='https://www.google-analytics.com/analytics.js';%60 +%0A %60r +%60j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=%60 +%0A%60'//www.googletagmanager.com/gtm.js?id='+i+dl;f .par @@ -545,13 +545,20 @@ ore( -e,r)%7D +j,f);%60 +%0A%60%7D) (win @@ -584,31 +584,17 @@ t',' -ga'));%60 +%0A %60ga('create +dataLayer ','$ @@ -617,15 +617,8 @@ Id%7D' -,'auto' );%60,
b4c1085d6c915926a5315c3a358e2aa9469decb5
FIX - File Path
routes/route-family.js
routes/route-family.js
var express = require('express') var router = express.Router() const family_file = "family.json" const fs = require('fs') // define the home page route router.get('/', function (req, res) { res.json(readFamily()) }) // define the about route router.get('/about', function (req, res) { res.send('About Page') }) function readFamily() { fs.readFile(('../data/' + family_file), 'utf8', function readFileCallback(err, data){ if (err){ console.log(err) } else { obj = JSON.parse(data) //now it an object return obj } }); return null } module.exports = router
JavaScript
0
@@ -56,16 +56,118 @@ outer()%0A +var fs = require('fs')%0Avar path = require('path');%0Avar appDir = path.dirname(require.main.filename);%0A%0A const fa @@ -195,33 +195,8 @@ son%22 -%0Aconst fs = require('fs') %0A%0A// @@ -434,11 +434,18 @@ le(( -'.. +appDir + ' /dat
1a383458113e447e821cc2df708b66aa8ba8acf6
remove unnecessary code
src/game/ui/HealthView.js
src/game/ui/HealthView.js
let debug = require('debug')('game:game/ui/HealthView'); import View from '../../engine/views/View'; class HealthView extends View { constructor () { super(); this._healthScale = 1; } init () { let material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); this.geometry = new THREE.PlaneGeometry(200, 20); // Change originX to left side this.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(100, 0, 0)); this.mesh = new THREE.Mesh(this.geometry, material); this._initialized = true; } set healthScale (value) { if (value !== this._healthScale) { this._healthScale = value; if (value <= 0) { this.mesh.visible = false; } else { if (!this.mesh.visible) { this.mesh.visible = true; } let oldX = this.mesh.position.x; this.mesh.scale.set(value, 1, 1); this.mesh.position.x = oldX; this.geometry.verticesNee = true; this.geometry.dynamic = true; } } } update (delta) { super.update(delta); } } export default HealthView;
JavaScript
0.00242
@@ -1061,104 +1061,8 @@ dX;%0A - this.geometry.verticesNee = true;%0A this.geometry.dynamic = true;%0A
d30236af0c6482a5806a80214cc3ed4c89aa95d0
Add runtime metamodel to Callable
runtime-js/callable.js
runtime-js/callable.js
function initType(a,b,c,d,e,f){}//IGNORE function String$(x){}//IGNORE function ArraySequence(x){}//IGNORE var exports;//IGNORE function Callable(wat) { return wat; } initType(Callable, 'ceylon.language::Callable'); exports.Callable=Callable; function $JsCallable(callable,targs) { callable.getT$all=Callable.getT$all; if (targs !== undefined) { callable.$$targs$$=targs; } return callable; } initExistingTypeProto($JsCallable, Function, 'ceylon.language::JsCallable', Callable); function noop() { return null; } //This is used for plain method references function JsCallable(o,f) { return (o !== null) ? function() { return f.apply(o, arguments); } : noop; } //This is used for spread method references function JsCallableList(value) { return function() { var rval = Array(value.length); for (var i = 0; i < value.length; i++) { var c = value[i]; rval[i] = c.f.apply(c.o, arguments); } return ArraySequence(rval); }; } exports.JsCallableList=JsCallableList; exports.JsCallable=JsCallable; exports.$JsCallable=$JsCallable;
JavaScript
0.000001
@@ -161,24 +161,116 @@ turn wat;%0A%7D%0A +Callable.$$metamodel$$=%7B$nm:'Callable',$tp:%7BReturn:%7B'var':'out'%7D, Arguments:%7B'var':'in'%7D%7D%7D;%0A initType(Cal @@ -798,16 +798,110 @@ noop;%0A%7D +%0AJsCallable.$$metamodel$$=%7B$nm:'Callable',$tp:%7BReturn:%7B'var':'out'%7D, Arguments:%7B'var':'in'%7D%7D%7D; %0A%0A//This @@ -1216,17 +1216,115 @@ %0A %7D;%0A - %7D +%0AJsCallableList.$$metamodel$$=%7B$nm:'Callable',$tp:%7BReturn:%7B'var':'out'%7D, Arguments:%7B'var':'in'%7D%7D%7D; %0A%0Aexport
0a572a7b1931f2e8d88034844e8bfb5693c59a0f
add missing reference to global scope for emailjs
src/components/pages/contact/sendEmail.js
src/components/pages/contact/sendEmail.js
const templateKey = "portfolio"; const serviceKey = "gmail"; const handleSuccess = function(response) { console.log("SUCCESS. status=%d, text=%s", response.status, response.text); }; const handleError = function(err) { console.log("FAILED. error=", err); }; const sendEmail = function(form) { return emailjs .send(serviceKey, templateKey, form) .then(handleSuccess, handleError); }; export default sendEmail;
JavaScript
0
@@ -302,16 +302,23 @@ return +window. emailjs%0A
e03ed8c3742e790b7a6e13e0923aad435464207f
fix build
bin/package.js
bin/package.js
#!/usr/bin/env node /** * Builds app binaries for OS X, Linux, and Windows. */ var config = require('../config') var cp = require('child_process') var electronPackager = require('electron-packager') var fs = require('fs') var path = require('path') var pkg = require('../package.json') var all = { // Build 64 bit binaries only. arch: 'x64', // The application source directory. dir: path.join(__dirname, '..'), // The release version of the application. Maps to the `ProductVersion` metadata // property on Windows, and `CFBundleShortVersionString` on OS X. 'app-version': pkg.version, // Package the application's source code into an archive, using Electron's archive // format. Mitigates issues around long path names on Windows and slightly speeds up // require(). asar: true, // The build version of the application. Maps to the FileVersion metadata property on // Windows, and CFBundleVersion on OS X. We're using the short git hash (e.g. 'e7d837e') 'build-version': cp.execSync('git rev-parse --short HEAD').toString().replace('\n', ''), // Pattern which specifies which files to ignore when copying files to create the // package(s). ignore: /^\/dist|\/(appveyor.yml|AUTHORS|CONTRIBUTORS|bench|benchmark|benchmark\.js|bin|bower\.json|component\.json|coverage|doc|docs|docs\.mli|dragdrop\.min\.js|example|examples|example\.html|example\.js|externs|ipaddr\.min\.js|Makefile|min|minimist|perf|rusha|simplepeer\.min\.js|simplewebsocket\.min\.js|static\/screenshot\.png|test|tests|test\.js|tests\.js|webtorrent\.min\.js|ws|\.[^\/]*|.*\.md|.*\.markdown)$/, // The application name. name: config.APP_NAME, // The base directory where the finished package(s) are created. out: path.join(__dirname, '..', 'dist'), // Replace an already existing output directory. overwrite: true, // Runs `npm prune --production` which remove the packages specified in // "devDependencies" before starting to package the app. prune: true, // The Electron version with which the app is built (without the leading 'v') version: pkg.devDependencies['electron-prebuilt'] } var darwin = { platform: 'darwin', // The bundle identifier to use in the application's plist (OS X only). 'app-bundle-id': 'io.webtorrent.app', // The application category type, as shown in the Finder via "View" -> "Arrange by // Application Category" when viewing the Applications directory (OS X only). 'app-category-type': 'public.app-category.utilities', // The bundle identifier to use in the application helper's plist (OS X only). 'helper-bundle-id': 'io.webtorrent.app.helper', // Application icon. icon: path.join(__dirname, '..', 'static', 'WebTorrent.icns') } var win32 = { platform: 'win32', // Object hash of application metadata to embed into the executable (Windows only) 'version-string': { // Company that produced the file. CompanyName: config.APP_NAME, // Copyright notices that apply to the file. This should include the full text of all // notices, legal symbols, copyright dates, and so on. LegalCopyright: fs.readFileSync(path.join(__dirname, '..', 'LICENSE'), 'utf8'), // File description to be presented to users. FileDescription: 'Streaming torrent client', // Original name of the file, not including a path. This information enables an // application to determine whether a file has been renamed by a user. The format of // the name depends on the file system for which the file was created. OriginalFilename: 'WebTorrent.exe', // Name of the product with which the file is distributed. ProductName: config.APP_NAME, // Internal name of the file, if one exists, for example, a module name if the file // is a dynamic-link library. If the file has no internal name, this string should be // the original filename, without extension. This string is required. InternalName: config.APP_NAME }, // Application icon. icon: path.join(__dirname, '..', 'static', 'WebTorrent.ico') } var linux = { platform: 'linux' // Note: Application icon for Linux is specified via the BrowserWindow `icon` option. } var platform = process.argv[2] if (platform === '--darwin') { buildDarwin() } else if (platform === '--win32') { buildWin32() } else if (platform === '--linux') { buildLinux() } else { // Build all buildDarwin(() => buildWin32(() => buildLinux())) } function buildDarwin (cb) { electronPackager(Object.assign({}, all, darwin), done.bind(null, cb)) } function buildWin32 (cb) { electronPackager(Object.assign({}, all, win32), done.bind(null, cb)) } function buildLinux (cb) { electronPackager(Object.assign({}, all, linux), done.bind(null, cb)) } function done (cb, err, appPath) { if (err) console.error(err.message || err) else console.log('Built ' + appPath) if (cb) cb() }
JavaScript
0.000001
@@ -1564,11 +1564,8 @@ .js%7C -ws%7C %5C.%5B%5E
279b8afad0454abc8012a0e43b51b07eaa857efa
Add fallback to blob-builder on low-end devices (#3937)
core/templates/dev/head/services/AssetsBackendApiService.js
core/templates/dev/head/services/AssetsBackendApiService.js
// Copyright 2017 The Oppia 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. /** * @fileoverview Service to serve as the interface for fetching and uploading * assets from Google Cloud Storage. */ oppia.factory('AssetsBackendApiService', [ '$http', '$q', 'UrlInterpolationService', function( $http, $q, UrlInterpolationService) { // List of filenames that have had been requested for but have // yet to return a response. var _filesCurrentlyBeingRequested = []; var AUDIO_DOWNLOAD_URL_TEMPLATE = ( GLOBALS.GCS_RESOURCE_BUCKET_NAME ? ('https://storage.googleapis.com/' + GLOBALS.GCS_RESOURCE_BUCKET_NAME + '/<exploration_id>/assets/audio/<filename>') : '/audiohandler/<exploration_id>/audio/<filename>'); var AUDIO_UPLOAD_URL_TEMPLATE = '/createhandler/audioupload/<exploration_id>'; // Map from asset filename to asset blob. var assetsCache = {}; var _fetchAudio = function( explorationId, filename, successCallback, errorCallback) { _filesCurrentlyBeingRequested.push(filename); $http({ method: 'GET', responseType: 'blob', url: _getAudioDownloadUrl(explorationId, filename), }).success(function(data) { var audioBlob = new Blob([data]); assetsCache[filename] = audioBlob; successCallback(audioBlob); }).error(function() { errorCallback(); })['finally'](function() { _removeFromFilesCurrentlyBeingRequested(filename); }); }; var _removeFromFilesCurrentlyBeingRequested = function(filename) { if (_isCurrentlyBeingRequested(filename)) { var fileToRemoveIndex = _filesCurrentlyBeingRequested.indexOf(filename); _filesCurrentlyBeingRequested.splice(fileToRemoveIndex, 1); } }; var _saveAudio = function( explorationId, filename, rawAssetData, successCallback, errorCallback) { var form = new FormData(); form.append('raw_audio_file', rawAssetData); form.append('payload', JSON.stringify({ filename: filename })); form.append('csrf_token', GLOBALS.csrf_token); $.ajax({ url: _getAudioUploadUrl(explorationId), data: form, processData: false, contentType: false, type: 'POST', dataType: 'text', dataFilter: function(data) { // Remove the XSSI prefix. var transformedData = data.substring(5); return JSON.parse(transformedData); }, }).done(function(response) { if (successCallback) { successCallback(response); } }).fail(function(data) { // Remove the XSSI prefix. var transformedData = data.responseText.substring(5); var parsedResponse = angular.fromJson(transformedData); console.error(parsedResponse); if (errorCallback) { errorCallback(parsedResponse); } }); }; var _getAudioDownloadUrl = function(explorationId, filename) { return UrlInterpolationService.interpolateUrl( AUDIO_DOWNLOAD_URL_TEMPLATE, { exploration_id: explorationId, filename: filename }); }; var _getAudioUploadUrl = function(explorationId) { return UrlInterpolationService.interpolateUrl(AUDIO_UPLOAD_URL_TEMPLATE, { exploration_id: explorationId }); }; var _isCurrentlyBeingRequested = function(filename) { return _filesCurrentlyBeingRequested.indexOf(filename) !== -1; }; var _isCached = function(filename) { return assetsCache.hasOwnProperty(filename); }; return { loadAudio: function(explorationId, filename) { return $q(function(resolve, reject) { if (_isCached(filename)) { resolve(assetsCache[filename]); } else if (!_isCurrentlyBeingRequested(filename)) { _fetchAudio(explorationId, filename, resolve, reject); } }); }, saveAudio: function(explorationId, filename, rawAssetData) { return $q(function(resolve, reject) { _saveAudio(explorationId, filename, rawAssetData, resolve, reject); }); }, isCached: function(filename) { return _isCached(filename); }, getAudioDownloadUrl: function(explorationId, filename) { return _getAudioDownloadUrl(explorationId, filename); } }; } ]);
JavaScript
0
@@ -1760,32 +1760,48 @@ unction(data) %7B%0A + try %7B%0A var audi @@ -1822,24 +1822,543 @@ ob(%5Bdata%5D);%0A + %7D catch (exception) %7B%0A window.BlobBuilder = window.BlobBuilder %7C%7C%0A window.WebKitBlobBuilder %7C%7C%0A window.MozBlobBuilder %7C%7C%0A window.MSBlobBuilder;%0A if (exception.name == 'TypeError' && window.BlobBuilder) %7B%0A var blobBuilder = new BlobBuilder();%0A blobBuilder.append(data);%0A var audioBlob = blobBuilder.getBlob('audio/*');%0A %7D else %7B%0A throw exception;%0A %7D%0A %7D%0A asse
a4632eaa4df7b109d66a1e33fb1044ae56973501
Make utils.startWorker accept onInit, onMessage, and onShutdown callbacks
nodeWorkerUtils.js
nodeWorkerUtils.js
var JSONStreamParser = require('./lib/JSONStreamParser'); var Q = require('q'); var util = require('util'); function respondWithError(err) { if (util.isError(err)) { err = err.stack; } console.log(JSON.stringify({error: err}, null, 2)); } function respondWithResult(result) { console.log(JSON.stringify({response: result}, null, 2)); } function startWorker(onMessageReceived, onShutdown) { process.stdin.resume(); process.stdin.setEncoding('utf8'); var inputData = ''; var inputStreamParser = new JSONStreamParser(); var initialized = false; var initData = null; process.stdin.on('data', function(data) { inputData += data; var rcvdMsg = inputStreamParser.parse(inputData); if (rcvdMsg.length === 1) { try { if (initialized === false) { initData = rcvdMsg[0].initData; initialized = true; console.log(JSON.stringify({initSuccess: true})); } else { var message = rcvdMsg[0].message; onMessageReceived(message, initData).then(function(response) { if (!response || typeof response !== 'object') { throw new Error( 'Invalid response returned by worker function: ' + JSON.stringify(response, null, 2) ); } return response; }).done(respondWithResult, respondWithError); } } catch (e) { respondWithError(e.stack || e.message); } } else if (rcvdMsg.length > 1) { throw new Error( 'Received multiple messages at once! Not sure what to do, so bailing ' + 'out!' ); } }); onShutdown && process.stdin.on('end', onShutdown); } exports.respondWithError = respondWithError; exports.respondWithResult = respondWithResult; exports.startWorker = startWorker;
JavaScript
0.000001
@@ -365,16 +365,30 @@ tWorker( +onInitialize, onMessag @@ -756,22 +756,8 @@ ) %7B%0A - try %7B%0A @@ -799,21 +799,37 @@ - initData = +try %7B%0A onInitialize( rcvd @@ -843,16 +843,17 @@ initData +) ;%0A @@ -946,20 +946,157 @@ %7D -else +catch (e) %7B%0A console.log(JSON.stringify(%7BinitError: e.stack %7C%7C e.message%7D));%0A throw e;%0A %7D%0A %7D else %7B%0A try %7B%0A @@ -1173,18 +1173,8 @@ sage -, initData ).th @@ -1531,24 +1531,16 @@ %7D -%0A %7D catch ( @@ -1536,32 +1536,34 @@ %7D catch (e) %7B%0A + respondW @@ -1594,16 +1594,26 @@ ssage);%0A + %7D%0A %7D%0A
d63e274c4a5670b51a644cab2bf2bea05ae6c6a1
Handle undefined variables in underscore templates
core/lib/pattern_engines/engine_underscore.js
core/lib/pattern_engines/engine_underscore.js
/* * underscore pattern engine for patternlab-node - v0.15.1 - 2015 * * Geoffrey Pursell, Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. * * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. * */ /* * ENGINE SUPPORT LEVEL: * * Basic. We can't call partials from inside underscore templates yet, but we * can render templates with backing JSON. * */ (function () { "use strict"; var _ = require('underscore'); // extend underscore with partial-ing methods // HANDLESCORE! UNDERBARS! _.mixin({ renderPartial: function (partial, data) { var data = data || {}; var compiled = _.template(partial); return compiled(data); }, assignContext: function (viewModel, data) { return viewModel(data); } }); var engine_underscore = { engine: _, engineName: 'underscore', engineFileExtension: '.html', // partial expansion is only necessary for Mustache templates that have // style modifiers or pattern parameters (I think) expandPartials: false, // regexes, stored here so they're only compiled once findPartialsRE: /<%= _.renderPartial\((.*?)\).*?%>/g, // TODO, findPartialsWithStyleModifiersRE: /<%= _.renderPartial\((.*?)\).*?%>/g, // TODO findPartialsWithPatternParametersRE: /<%= _.renderPartial\((.*?)\).*?%>/g, // TODO findListItemsRE: /({{#( )?)(list(I|i)tems.)(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)( )?}}/g, // render it renderPattern: function renderPattern(template, data, partials) { var compiled = _.template(template); return compiled(_.extend(data, { _allData: data, _partials: partials })); }, // registerPartial: function (oPattern) { // debugger; // _.registerPartial(oPattern.key, oPattern.template); // }, // find and return any {{> template-name }} within pattern findPartials: function findPartials(pattern) { var matches = pattern.template.match(this.findPartialsRE); return matches; }, findPartialsWithStyleModifiers: function () { return []; }, // returns any patterns that match {{> value(foo:"bar") }} or {{> // value:mod(foo:"bar") }} within the pattern findPartialsWithPatternParameters: function () { return []; }, findListItems: function (pattern) { var matches = pattern.template.match(this.findListItemsRE); return matches; }, // given a pattern, and a partial string, tease out the "pattern key" and // return it. findPartialKey: function (partialString) { var partialKey = partialString.replace(this.findPartialsRE, '$1'); return partialKey; } }; module.exports = engine_underscore; })();
JavaScript
0.000001
@@ -1705,38 +1705,363 @@ emplate);%0A -return +var renderedHTML;%0A%0A // This try-catch is necessary because references to undefined variables%0A // in underscore templates are eval()ed directly as javascript, and as%0A // such will throw very real exceptions that will shatter the whole build%0A // process if we don't handle them.%0A try %7B%0A renderedHTML = compiled(_.exte @@ -2071,12 +2071,20 @@ data + %7C%7C %7B%7D , %7B%0A + @@ -2111,16 +2111,18 @@ + + _partial @@ -2143,13 +2143,400 @@ + %7D));%0A + %7D catch (e) %7B%0A var errorMessage = %22WARNING: the underscore template %22 + template.fileName + %22 threw an exception; it probably just tried to reference an undefined variable. Is this pattern maybe missing a .json file?%22;%0A console.log(errorMessage, e);%0A renderedHTML = %22%3Ch1%3EError in underscore template%3C/h1%3E%22 + errorMessage;%0A %7D%0A%0A return renderedHTML;%0A
2e812a3ab6b11902165adc329130585e3a01fa62
fix bug
src/js/CapturePlayback.js
src/js/CapturePlayback.js
/** * CapturePlayback * * @author VinhLH */ "use strict"; var app = angular.module('CapturePlayback', ['Jira', 'ngPrism']); app.controller('MainController', ['$scope', 'JiraAPIs', function ($scope, JiraAPIs) { $scope.projects = null; $scope.issues = null; $scope.scripts = null; $scope.scriptKeys = null; $scope.selected = { 'project': null }; $scope.loading = 'Fetching project list..'; JiraAPIs.getProjects(function (resp) { $scope.projects = resp; $scope.loading = null; if ($scope.projects.length) { $scope.selected['project'] = $scope.projects[0].id; $scope.getIssues(); } }); $scope.getIssues = function () { $scope.loading = 'Fetching issue list..'; $scope.issues = null; JiraAPIs.getIssues($scope.selected['project'], function (resp) { $scope.issues = resp.issues; $scope.loading = null; if ($scope.issues.length) { $scope.selected['issue'] = '10130'; // $scope.selected['issue'] = $scope.issues[0].id; $scope.getScripts(); } }); }; $scope.getScripts = function () { $scope.loading = 'Fetching script list..'; $scope.scripts = null; $scope.scriptKeys = null; JiraAPIs.getScripts($scope.selected['issue'], function (resp) { $scope.scripts = resp; $scope.loading = null; $scope.scriptKeys = Object.keys($scope.scripts); if ($scope.scriptKeys.length) { $scope.selected['script'] = $scope.scripts[$scope.scriptKeys[0]].id; $scope.getScriptDetail(); } }); }; $scope.getScriptDetail = function () { if (!$scope.selected['script']) { return; } $scope.loading = 'Fetching script detail..'; $scope.startUrl = null; JiraAPIs.getJsonFromUrl($scope.scripts[$scope.selected['script']].content, function (resp) { $scope.loading = null; $scope.actions = resp.script.join("\n").trim(); $scope.startUrl = resp.startUrl; }); }; }]);
JavaScript
0.000001
@@ -61,19 +61,24 @@ %22;%0A%0Avar -app +playback = angul @@ -133,11 +133,16 @@ );%0A%0A -app +playback .con @@ -1010,32 +1010,35 @@ %0A + // $scope.selected @@ -1065,35 +1065,32 @@ %0A - // $scope.selected
396bddd03f48450eeb1753d6459afd53f334af2a
Return initials; profiles
schema/partner.js
schema/partner.js
import gravity from '../lib/loaders/gravity'; import { GraphQLString, GraphQLObjectType, GraphQLNonNull, GraphQLInt } from 'graphql'; let PartnerType = new GraphQLObjectType({ name: 'Partner', fields: () => ({ cached: { type: GraphQLInt, resolve: ({ cached }) => new Date().getTime() - cached }, id: { type: GraphQLString }, name: { type: GraphQLString }, type: { type: GraphQLString }, default_profile_id: { type: GraphQLString } }) }); let Partner = { type: PartnerType, description: 'A Partner', args: { id: { type: new GraphQLNonNull(GraphQLString), description: 'The slug or ID of the Partner' } }, resolve: (root, { id }) => gravity(`partner/${id}`) }; export default Partner;
JavaScript
0.000049
@@ -1,12 +1,36 @@ +import _ from 'lodash';%0A import gravi @@ -63,16 +63,87 @@ avity';%0A +import cached from './fields/cached';%0Aimport Profile from './profile';%0A import %7B @@ -201,22 +201,8 @@ Null -,%0A GraphQLInt %0A%7D f @@ -313,100 +313,14 @@ ed: -%7B%0A type: GraphQLInt,%0A resolve: (%7B cached %7D) =%3E new Date().getTime() - cached%0A %7D +cached ,%0A @@ -458,26 +458,142 @@ -default_ +initials: %7B%0A type: GraphQLString,%0A resolve: (%7B name %7D) =%3E _.take(name.replace(/%5B%5EA-Z%5D/g, ''), 3).join('')%0A %7D,%0A profile -_id : %7B%0A @@ -600,37 +600,121 @@ type: -GraphQLString +Profile.type,%0A resolve: (%7B default_profile_id %7D) =%3E gravity(%60profile/$%7Bdefault_profile_id%7D%60) %0A %7D%0A %7D)%0A
c8a2c87faabe8db2f2fdc8036a76491b13c26723
extend instead of overwriting cluster
client/app/modules/events-map/services/map-service.js
client/app/modules/events-map/services/map-service.js
'use strict'; angular.module('genie.eventsMap') .factory('mapService', ['ZoomLevel', '$http', function(ZoomLevel, $http) { function findZoomLevel(options) { return ZoomLevel.find({ filter: { where: { zoom_level: options.zoom_level, minutes_ago: options.minutes_ago } } }) .$promise; } function getClusterSources(params) { return $http.post('/sourcedataaccess/sourcedata', {events: params}) .then(function(res) { return res.data; }); } function getZoomLevel(options) { return findZoomLevel(options) .then(function(zoomLevels) { var zoomLevel = zoomLevels[0]; if (zoomLevel) { var clusters = _.sortByOrder(zoomLevel.clusters, 'weight', 'desc'); zoomLevel.clusters = mapifyClusters(clusters); return zoomLevel; } else { zoomLevel = new ZoomLevel(); zoomLevel.clusters = [] return zoomLevel; // no record found for zoom or time } }); function mapifyClusters(clusters) { return _.map(clusters, function(cluster) { return { // artificial id for UI convenience id: cluster.lat.toString() + '-' + cluster.lng.toString(), location: new google.maps.LatLng(cluster.lat, cluster.lng), weight: cluster.weight, events: cluster.events, start_time: moment(cluster.start_time).format('MM-DD hh:mm a'), end_time: moment(cluster.end_time).format('MM-DD hh:mm a') }; }) } } return { getZoomLevel: getZoomLevel, getClusterSources: getClusterSources }; }]);
JavaScript
0.000001
@@ -1096,22 +1096,32 @@ -return +var uiFriendly = %7B%0A @@ -1310,80 +1310,8 @@ g),%0A - weight: cluster.weight,%0A events: cluster.events,%0A @@ -1453,16 +1453,16 @@ :mm a')%0A - @@ -1466,16 +1466,70 @@ %7D;%0A + return angular.extend(cluster, uiFriendly);%0A
43cd6b0f868ca3cd0d47887727966c2aec65a0b8
Fix typo
client/src/connectionAccesses/ConnectionAccessList.js
client/src/connectionAccesses/ConnectionAccessList.js
import React, { useEffect, useState } from 'react'; import { connect } from 'unistore/react'; import humanizeDuration from 'humanize-duration'; import Button from '../common/Button'; import DeleteConfirmButton from '../common/DeleteConfirmButton'; import ListItem from '../common/ListItem'; import Text from '../common/Text'; import fetchJson from '../utilities/fetch-json'; import message from '../common/message'; import ConnectionAccessCreateDrawer from './ConnectionAccessCreateDrawer'; function ConnectionAccessList({ currentUser }) { const [connectionAccesses, setConnectionAccesses] = useState([]); const [showInactives, setShowInactives] = useState(false); const [expiredConnectionAccessId, setExpiredConnectionAccessId] = useState( null ); const [newConnectionAccessId, setNewConnectionAccessId] = useState(null); const [showAccessCreate, setShowAccessCreate] = useState(false); useEffect(() => { async function getConnectionAccesses() { let url = `/api/connection-accesses`; if (showInactives) { url = url + '?includeInactives=true'; } const json = await fetchJson('GET', url); if (json.error) { message.error(json.error); } else { setConnectionAccesses(json.connectionAccesses); } } getConnectionAccesses(); }, [showInactives, newConnectionAccessId, expiredConnectionAccessId]); const toggleShowInactives = () => { setShowInactives(!showInactives); }; const newConnectionAccess = () => { setShowAccessCreate(true); }; const expireConnectionAccess = async connectionAccessId => { const json = await fetchJson( 'PUT', `/api/connection-accesses/${connectionAccessId}/expire` ); if (json.error) { return message.error('Expire Failed: ' + json.error.toString()); } setExpiredConnectionAccessId(connectionAccessId); }; const handleCreateDrawerClose = () => { setShowAccessCreate(false); }; const handleConnectionAccessSaved = connectionAccess => { setShowAccessCreate(false); setNewConnectionAccessId(connectionAccess._id); }; return ( <> <div style={{ display: 'flex', justifyContent: 'flex-end' }}> <Button style={{ marginRight: 8 }} onClick={toggleShowInactives}> {showInactives ? 'Hide Expired' : 'Show Expired'} </Button> <Button style={{ width: 135 }} variant="primary" onClick={newConnectionAccess} > Create Access </Button> </div> {connectionAccesses.map(item => { const actions = []; const timeToExpire = new Date(item.expiryDate) - new Date(); const expired = timeToExpire < 0; if (currentUser.role === 'admin' && !expired) { actions.push( <DeleteConfirmButton key="expire" confirmMessage="Expire connection access?" onConfirm={e => expireConnectionAccess(item._id)} style={{ marginLeft: 8 }} > Expire </DeleteConfirmButton> ); } return ( <ListItem key={item._id}> <div style={{ flexGrow: 1, padding: 8 }}> <b>Connection:</b> {item.connectionName} <br /> <b>User:</b> {item.userEmail} <br /> <Text type="secondary"> Duration: {item.duration || 'Indefinete'}{' '} {!item.duration || 'seconds'} &nbsp;&nbsp; - &nbsp;&nbsp; Expiry Date:{' '} {new Date(item.expiryDate).toLocaleString()} </Text> <br /> {!expired ? ( <Text type="secondary"> Time to Expire:{' '} {humanizeDuration(timeToExpire, { units: ['d', 'h', 'm'], round: true })} </Text> ) : ( <Text type="danger">Expired</Text> )} </div> {actions} </ListItem> ); })} <ConnectionAccessCreateDrawer visible={showAccessCreate} onClose={handleCreateDrawerClose} onConnectionAccessSaved={handleConnectionAccessSaved} placement="left" /> </> ); } export default connect(['currentUser'])(ConnectionAccessList);
JavaScript
0.999999
@@ -3443,17 +3443,17 @@ 'Indefin -e +i te'%7D%7B' '
7eeda1afa3132809026fbd8c94f1a8baa20d9779
Update reflect script to use built sdk
script/reflect.js
script/reflect.js
/* global Promise */ var fs = require('fs'); var path = require('path'); var auth = require('../plugins/api-key'); var request = require('../request')(auth(process.env.FLICKR_API_KEY)); /** * Get the destination filename for `method` * @param {String} method * @returns {String} */ function filename(method) { return path.join('src', method + '.json'); } /** * Returns a JSON representation of `obj`. * @param {Object} obj * @returns {String} */ function stringify(obj) { return JSON.stringify(obj, null, 2) + '\n'; } /** * Get the method info for `method` and write it to disk * @param {Object} method * @returns {Promise} */ function info(method) { return request('GET', 'flickr.reflection.getMethodInfo') .query('method_name=' + method._content) .then(function (res) { fs.writeFileSync(filename(method._content), stringify(res.body)); }); } /** * Get info for every method and write them all to disk */ request('GET', 'flickr.reflection.getMethods').then(function (res) { return res.body.methods.method; }).then(function (methods) { return Promise.all(methods.map(info)); }).catch(function (err) { // eslint-disable-next-line no-console console.error(err); process.exit(err.code || 1); });
JavaScript
0
@@ -75,86 +75,30 @@ var -auth = require('../plugins/api-key');%0Avar request = require('../request')(auth +flickr = require('..') (pro @@ -121,17 +121,16 @@ API_KEY) -) ;%0A%0A/**%0A @@ -616,32 +616,16 @@ %09return -request('GET', ' flickr.r @@ -651,21 +651,13 @@ Info -') +(%7B %0A%09%09 -.query(' meth @@ -667,12 +667,9 @@ name -=' + +: met @@ -684,12 +684,12 @@ tent -) %0A%09 -%09 +%7D) .the @@ -707,17 +707,16 @@ (res) %7B%0A -%09 %09%09fs.wri @@ -775,17 +775,16 @@ body));%0A -%09 %09%7D);%0A%7D%0A%0A @@ -852,24 +852,8 @@ */%0A%0A -request('GET', ' flic @@ -876,17 +876,17 @@ tMethods -' +( ).then(f
b6d8320b648c5ab6b1070b33d72dc126a6666459
Send message to Iframe
sdk/src/Application.js
sdk/src/Application.js
import Style from './style.css'; import ChatHeaderTemplate from './chat-header.html'; import ChatFooterTemplate from './chat-footer.html'; export default class Application { constructor() { //Default options this.options = { title: 'Estamos online', onEnter: () => { }, onLeave: () => { }, } this.IFRAMEURL_HMG = 'https://hmg-sdkcommon.blip.ai/'; this.IFRAMEURL_LOCAL = 'http://localhost:3000/'; this.IFRAMEURL_PRD = 'https://sdkcommon.blip.ai/' this.IFRAMEURL = this.IFRAMEURL_LOCAL; if (process.env.NODE_ENV === 'homolog') { this.IFRAMEURL = this.IFRAMEURL_HMG; } else if (process.env.NODE_ENV === 'production') { this.IFRAMEURL = this.IFRAMEURL_PRD; } //Div container for SDK let chatEl = document.createElement('div'); //Div ID chatEl.id = 'take-chat'; this.chatEl = chatEl; } /* Init chat and set values and styles*/ openBlipThread(options) { let chatOpts = { ...this.options, ...options }; this.options = chatOpts; //Chat HTML element this.buildChat(chatOpts); } /* Build chat HTML element */ buildChat(opts) { let params = 'apikey=' + this._apiKey; //Chat iframe this.chatIframe = document.createElement('iframe'); this.chatIframe.src = this.IFRAMEURL + '?' + params; if (opts.target === undefined) { this.chatEl.innerHTML = ChatHeaderTemplate; this.chatEl.innerHTML += ChatFooterTemplate; this.chatEl.appendChild(this.chatIframe); this.chatEl.className = 'blip-hidden-chat'; this.chatEl.className += ' fixed-window'; this.chatIframe.width = 300; this.chatIframe.height = 460; //Set chat title this._setChatTitle(opts.title); let body = document.getElementsByTagName('body')[0]; body.appendChild(this.chatEl); let closeBtn = document.getElementById('blip-close-btn'); closeBtn.addEventListener('click', () => { if (this.chatEl.getAttribute('class').indexOf('blip-hidden-chat') == ! -1) { this.chatEl.setAttribute('class', 'blip-show-chat fixed-window'); //Enter chat callback setTimeout(() => { opts.onEnter(); }, 500); } else { this.chatEl.setAttribute('class', 'blip-hidden-chat fixed-window'); //Leave chat callback setTimeout(() => { opts.onLeave(); }, 500); } }); } else { this.chatEl.className = 'target-window'; this.chatEl.appendChild(this.chatIframe); this.chatIframe.className += ' target-window'; let chatTarget = document.getElementById(opts.target); chatTarget.appendChild(this.chatEl); } } destroy() { if (this.options.target !== undefined) { let element = document.getElementById(this.options.target); element.removeChild(this.chatEl); } else { let body = document.getElementsByTagName('body')[0]; body.removeChild(this.chatEl); } } _setChatTitle(title) { let chatTitle = title ? title : 'Estamos online'; this.chatEl.querySelector('#chat-header-text').innerHTML = chatTitle; } _sendMessage(message) { this.chatEl.querySelector('iframe').contentWindow.postMessage(message, '*'); } }
JavaScript
0
@@ -950,20 +950,16 @@ ions) %7B%0A - %0A let @@ -1287,43 +1287,276 @@ ame. -src = this.IFRAMEURL + '?' + params +id = 'iframe-chat';%0A this.chatIframe.src = this.IFRAMEURL + '?' + params;%0A this.chatIframe.onload = function () %7B%0A var iframe = document.getElementById('iframe-chat');%0A iframe.contentWindow.postMessage('Os dados ser%C3%A3o enviados aqui', iframe.src);%0A %7D ;%0A%0A @@ -2958,24 +2958,27 @@ atEl);%0A %7D + %0A%0A %7D%0A%0A des
0902473b516b2932735ca5daf85f81b117a0c33b
Add update job handler
server/handlers/job.js
server/handlers/job.js
import {badRequest, notFound} from 'boom' import Joi from 'joi' import Logger from '@modulus/logger' import Job from '../models/job' let logger = Logger('handlers/job') export default { /////////// Job.create \\\\\\\\\\ create: { validate: { payload: { employer: Joi.string().required(), location: { city: Joi.string(), state: Joi.string() }, dates: { start: Joi.string().required(), end: Joi.string() }, title: Joi.string().required(), tasks: Joi.array() } }, handler: function (request, reply) { let {employer, location, dates, tasks, title} = request.payload let newJob = { employer: employer, location: { city: location.city, state: location.state }, dates: { start: dates.start, end: dates.end }, title: title, tasks: tasks } new Job(newJob).save((err, created) => { if (err) { logger.error(`Job.create error: ${err}`) return reply(badRequest(err.message)) } logger.debug(`Job.create saved ${JSON.stringify(created)}`) reply(created) }) } }, ////////// Job.get \\\\\\\\\\ get: { validate: { params: { id: Joi.string().required() } }, handler: function (request, reply) { Job.findOne({ id: request.params.id }, (err, job) => { if (err) { logger.error(`Job.findOne error: ${err}`) return reply(badRequest(err.message)) } logger.debug(`Job.findOne found ${JSON.stringify(job)}`) reply(job) }) } }, ////////// Job.getAll \\\\\\\\\\ getAll: { handler: function (request, reply) { Job.find({}, (err, jobs) => { if (err) { logger.error(`Job.find error: ${err}`) return reply(badRequest(err.message)) } logger.debug(`Job.find found ${JSON.stringify(jobs)}`) reply(jobs) }) } }, ////////// Job.remove \\\\\\\\\\ remove: { validate: { params: { id: Joi.string().required() } }, handler: function (request, reply) { Job.remove({ id: request.params.id }, (err) => { if (err) { logger.error(`Job.remove error: ${err}`) return reply(badRequest(err.message)) } logger.debug(`Job.remove removed ${request.params.id}`) reply() }) } } }
JavaScript
0.000001
@@ -2523,14 +2523,803 @@ )%0A %7D%0A + %7D,%0A%0A ////////// Job.update %5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%0A update: %7B%0A validate: %7B%0A params: %7B%0A id: Joi.string().required()%0A %7D,%0A payload: %7B%0A employer: Joi.string(),%0A location: %7B%0A city: Joi.string(),%0A state: Joi.string()%0A %7D,%0A dates: %7B%0A start: Joi.string(),%0A end: Joi.string()%0A %7D,%0A title: Joi.string(),%0A tasks: Joi.array()%0A %7D%0A %7D,%0A handler: function (request, reply) %7B%0A let %7Bparams, payload%7D = request%0A%0A Job.update(%7B id: params.id %7D, payload, (err) =%3E %7B%0A if (err) %7B%0A logger.error(%60Job.update error: $%7Berr%7D%60)%0A return reply(badRequest(err.message))%0A %7D%0A%0A logger.debug(%60Job.update updated $%7Bparams.id%7D%60)%0A reply(params.id)%0A %7D)%0A %7D%0A %7D%0A%7D%0A
8587dac06565fa5e4c356fc26d5dff8c5998faab
Set PhantomJS exit code properly on failures
build/ci/phantom.js
build/ci/phantom.js
/* * Qt+WebKit powered headless test runner using Phantomjs * * Phantomjs installation: http://code.google.com/p/phantomjs/wiki/BuildInstructions * * Run with: * phantomjs runner.js [url-of-your-qunit-testsuite] * * E.g. * phantomjs runner.js http://localhost/qunit/test */ var url = phantom.args[0]; var page = require('webpage').create(); // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") page.onConsoleMessage = function(msg) { console.log(msg); }; page.open(url, function(status){ if (status !== "success") { console.log("Unable to access network: " + status); phantom.exit(1); } else { // page.evaluate(addLogging); var interval = setInterval(function() { if (finished()) { clearInterval(interval); onfinishedTests(); } }, 500); } }); page.onResourceReceived = function(data) { page.evaluate(function(addLogging) { // Only add setZeroTimeout to the window object, and hide everything // else in a closure. (function() { var timeouts = []; var messageName = "zero-timeout-message"; // Like setTimeout, but only takes a function argument. There's // no time argument (always zero) and no arguments (you have to // use a closure). function setZeroTimeout(fn) { timeouts.push(fn); window.postMessage(messageName, "*"); } function handleMessage(event) { if (event.source == window && event.data == messageName) { event.stopPropagation(); if (timeouts.length > 0) { var fn = timeouts.shift(); fn(); } } } window.addEventListener("message", handleMessage, true); // Add the one thing we want added to the window object. window.setZeroTimeout = setZeroTimeout; })(); setZeroTimeout(function() { if(window.QUnit && !window.QUnit.__logging) { console.log('Adding logging'); addLogging(); window.QUnit.__logging = true; } }); }, addLogging); } function finished() { return page.evaluate(function(){ return !!window.qunitDone; }); } function onfinishedTests() { var output = page.evaluate(function() { return JSON.stringify(window.qunitDone); }); phantom.exit(JSON.parse(output).failed > 0 ? 1 : 0); } function addLogging() { var print = function(msg) { console.log(msg); }; QUnit.begin(function() { print("Starting ..."); }); QUnit.log(function(o){ var result = o.result, message = o.message || 'okay'; // Testdox layout if(result) { print(' [x] ' + message); } else { print(' [ ] ' + message); if(o.expected) { print(' Actual: ' + o.actual); print(' Expected: ' + o.expected); } } }); QUnit.testStart(function(o){ print(' ' + o.name); }); QUnit.moduleStart(function(o){ print("\n" + o.name); }); QUnit.done(function(o) { if(o.failed > 0) { print("\n" + 'FAILURES!'); print('Tests: ' + o.total + ', Passed: ' + o.passed, + ', Failures: ' + o.failed); } else { print("\n" + 'SUCESS!'); print('Tests: ' + o.total); } print('Took: ' + o.runtime + 'ms'); window.qunitDone = true; }); }
JavaScript
0.000001
@@ -503,20 +503,17 @@ (msg) %7B%0A - +%09 console. @@ -2085,22 +2085,23 @@ %7B%0A%09var -output +success = page. @@ -2128,31 +2128,15 @@ %7B%0A%09%09 -%09 return -JSON.stringify( wind @@ -2147,13 +2147,15 @@ unit -Done) +Success ;%0A%09%7D @@ -2175,45 +2175,23 @@ xit( -JSON.parse(output).failed %3E 0 ? 1 : 0 +success ? 0 : 1 );%0A%7D @@ -3076,15 +3076,55 @@ = true;%0A +%09%09window.qunitSuccess = o.failed === 0;%0A %09%7D);%0A%7D%0A
9046c1550356c26a458e3728582e6a285625a84a
call super
public/js/views/database_function_list_view.js
public/js/views/database_function_list_view.js
(function($, ns) { ns.views.DatabaseFunctionList = ns.views.DatabaseList.extend({ className : "database_function_list", useLoadingSection: true, events: { "click .context a": "contextClicked" }, setup: function() { this.sandbox = this.options.sandbox; this.schemas = this.sandbox.database().schemas(); this.schemas.fetch(); this.setSchema(this.sandbox.schema()); }, additionalContext: function() { return { schemaLink: ns.helpers.linkTo("#", this.schema.get('name')) }; }, schemaMenuContent: function() { var content = $("<ul></ul>"); this.schemas.each(function(schema) { var a = "<a href='#' class='schema' data-id='" + schema.get("id") + "'>" + schema.get("name") + "</a>" var li = $("<li></li>").html(a); content.append(li); }); return content.outerHtml() }, postRender: function() { chorus.search({ input: this.$('input.search'), list: this.$('ul') }); chorus.menu(this.$(".context a"), { content: this.schemaMenuContent(), contentEvents: { 'a.schema': _.bind(this.schemaSelected, this) } }); }, setSchema: function(schema) { this.resource = this.collection = this.functions = schema.functions(); this.bindings.add(this.resource, "change reset add remove", this.render); this.functions.fetch(); this.schema = schema; this.render(); }, schemaSelected: function(e) { var schemaId = $(e.target).data("id") var schema = this.schemas.get(schemaId) this.setSchema(schema); }, contextClicked: function(e) { e.preventDefault(); } }); })(jQuery, chorus);
JavaScript
0.000015
@@ -1089,122 +1089,34 @@ -chorus.search(%7B%0A input: this.$('input.search'),%0A list: this.$('ul')%0A %7D);%0A +this._super('postRender'); %0A
ea187f4ab4fe3ec4dbcb0b050fdc73200bc31fb4
Fix stamen subdomain list
source/js/map/VCO.StamenMaps.js
source/js/map/VCO.StamenMaps.js
/* VCO.StamenMaps Makes Stamen Map tiles available http://maps.stamen.com/ ================================================== */ (function(exports) { /* tile.stamen.js v1.2.3 ================================================== */ var SUBDOMAINS = " a b c d".split(" "), MAKE_PROVIDER = function(layer, type, minZoom, maxZoom) { return { "url": ["//stamen-tiles-{S}.a.ssl.fastly.net/", layer, "/{Z}/{X}/{Y}.", type].join(""), "type": type, "subdomains": SUBDOMAINS.slice(), "minZoom": minZoom, "maxZoom": maxZoom, "attribution": [ 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, ', 'under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. ', 'Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, ', 'under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.' ].join("") }; }, PROVIDERS = { "toner": MAKE_PROVIDER("toner", "png", 0, 20), "terrain": MAKE_PROVIDER("terrain", "jpg", 4, 18), "watercolor": MAKE_PROVIDER("watercolor", "jpg", 1, 16), "trees-cabs-crime": { "url": "http://{S}.tiles.mapbox.com/v3/stamen.trees-cabs-crime/{Z}/{X}/{Y}.png", "type": "png", "subdomains": "a b c d".split(" "), "minZoom": 11, "maxZoom": 18, "extent": [ {"lat": 37.853, "lon": -122.577}, {"lat": 37.684, "lon": -122.313} ], "attribution": [ 'Design by Shawn Allen at <a href="http://stamen.com">Stamen</a>.', 'Data courtesy of <a href="http://fuf.net">FuF</a>,', '<a href="http://www.yellowcabsf.com">Yellow Cab</a>', '&amp; <a href="http://sf-police.org">SFPD</a>.' ].join(" ") } }; // set up toner and terrain flavors setupFlavors("toner", ["hybrid", "labels", "lines", "background", "lite"]); // toner 2010 setupFlavors("toner", ["2010"]); // toner 2011 flavors setupFlavors("toner", ["2011", "2011-lines", "2011-labels", "2011-lite"]); setupFlavors("terrain", ["background"]); setupFlavors("terrain", ["labels", "lines"], "png"); /* Export stamen.tile to the provided namespace. ================================================== */ exports.stamen = exports.stamen || {}; exports.stamen.tile = exports.stamen.tile || {}; exports.stamen.tile.providers = PROVIDERS; exports.stamen.tile.getProvider = getProvider; /* A shortcut for specifying "flavors" of a style, which are assumed to have the same type and zoom range. ================================================== */ function setupFlavors(base, flavors, type) { var provider = getProvider(base); for (var i = 0; i < flavors.length; i++) { var flavor = [base, flavors[i]].join("-"); PROVIDERS[flavor] = MAKE_PROVIDER(flavor, type || provider.type, provider.minZoom, provider.maxZoom); } } /* Get the named provider, or throw an exception if it doesn't exist. ================================================== */ function getProvider(name) { if (name in PROVIDERS) { return PROVIDERS[name]; } else { throw 'No such provider (' + name + ')'; } } /* StamenTileLayer for modestmaps-js <https://github.com/modestmaps/modestmaps-js/> Works with both 1.x and 2.x by checking for the existence of MM.Template. ================================================== */ if (typeof MM === "object") { var ModestTemplate = (typeof MM.Template === "function") ? MM.Template : MM.TemplatedMapProvider; MM.StamenTileLayer = function(name) { var provider = getProvider(name); this._provider = provider; MM.Layer.call(this, new ModestTemplate(provider.url, provider.subdomains)); this.provider.setZoomRange(provider.minZoom, provider.maxZoom); this.attribution = provider.attribution; }; MM.StamenTileLayer.prototype = { setCoordLimits: function(map) { var provider = this._provider; if (provider.extent) { map.coordLimits = [ map.locationCoordinate(provider.extent[0]).zoomTo(provider.minZoom), map.locationCoordinate(provider.extent[1]).zoomTo(provider.maxZoom) ]; return true; } else { return false; } } }; MM.extend(MM.StamenTileLayer, MM.Layer); } /* StamenTileLayer for Leaflet <http://leaflet.cloudmade.com/> Tested with version 0.3 and 0.4, but should work on all 0.x releases. ================================================== */ if (typeof L === "object") { L.StamenTileLayer = L.TileLayer.extend({ initialize: function(name) { var provider = getProvider(name), url = provider.url.replace(/({[A-Z]})/g, function(s) { return s.toLowerCase(); }); L.TileLayer.prototype.initialize.call(this, url, { "minZoom": provider.minZoom, "maxZoom": provider.maxZoom, "subdomains": provider.subdomains, "scheme": "xyz", "attribution": provider.attribution }); } }); } /* StamenMapType for Google Maps API V3 <https://developers.google.com/maps/documentation/javascript/> ================================================== */ if (typeof google === "object" && typeof google.maps === "object") { google.maps.StamenMapType = function(name) { var provider = getProvider(name), subdomains = provider.subdomains; return google.maps.ImageMapType.call(this, { "getTileUrl": function(coord, zoom) { var numTiles = 1 << zoom, wx = coord.x % numTiles, x = (wx < 0) ? wx + numTiles : wx, y = coord.y, index = (zoom + x + y) % subdomains.length; return provider.url .replace("{S}", subdomains[index]) .replace("{Z}", zoom) .replace("{X}", x) .replace("{Y}", y); }, "tileSize": new google.maps.Size(256, 256), "name": name, "minZoom": provider.minZoom, "maxZoom": provider.maxZoom }); }; // FIXME: is there a better way to extend classes in Google land? google.maps.StamenMapType.prototype = new google.maps.ImageMapType("_"); } })(typeof exports === "undefined" ? this : exports);
JavaScript
0.000012
@@ -247,17 +247,16 @@ AINS = %22 - a b c d%22
ece9ec6a2c40f309d37fb6c35b6661ec82f3977b
Make sure the requirejs binaries wont get uglified since they are breaking the ulgification
Build/Grunt-Options/uglify.js
Build/Grunt-Options/uglify.js
/** * Grunt-Contrib-Uglify * @description Minify files with UglifyJS. * @docs https://github.com/gruntjs/grunt-contrib-uglify */ var config = require("../Config"); module.exports = { js: { options: { banner: config.bannerComment() }, files: [{ expand: true, cwd: config.JavaScripts.paths.devDir, src: [ "**/*.js", "!Vendor/almond/**/*.js", "!Vendor/modernizr/**/*.js" ], dest: config.JavaScripts.paths.distDir }] } };
JavaScript
0
@@ -328,32 +328,69 @@ %0A%09%09%09%09%22**/*.js%22,%0A +%09%09%09%09%22!Vendor/requirejs/bin/**/*.js%22,%0A %09%09%09%09%22!Vendor/alm
ef301f3fa271aa2481d1d434966f4071f1ca82f5
fix auto refresh public feed when tab clicked if pending updates
modules/page/html/render/public.js
modules/page/html/render/public.js
var nest = require('depnest') var { h, send, when, computed, map } = require('mutant') var extend = require('xtend') var pull = require('pull-stream') exports.gives = nest({ 'page.html.render': true }) exports.needs = nest({ sbot: { pull: { log: 'first', feed: 'first', userFeed: 'first' }, async: { publish: 'first' }, obs: { connectedPeers: 'first', localPeers: 'first' } }, 'about.html.image': 'first', 'about.obs.name': 'first', 'message.html.compose': 'first', 'feed.html.rollup': 'first', 'profile.obs.recentlyUpdated': 'first', 'contact.obs.following': 'first', 'channel.obs': { subscribed: 'first', recent: 'first' }, 'keys.sync.id': 'first' }) exports.create = function (api) { return nest('page.html.render', page) function page (path) { if (path !== '/public') return // "/" is a sigil for "page" var id = api.keys.sync.id() var following = api.contact.obs.following(id) var subscribedChannels = api.channel.obs.subscribed(id) var loading = computed(subscribedChannels.sync, x => !x) var channels = computed(api.channel.obs.recent(), items => items.slice(0, 8), {comparer: arrayEq}) var connectedPeers = api.sbot.obs.connectedPeers() var localPeers = api.sbot.obs.localPeers() var connectedPubs = computed([connectedPeers, localPeers], (c, l) => c.filter(x => !l.includes(x))) var oldest = Date.now() - (2 * 24 * 60 * 60e3) getFirstMessage(id, (_, msg) => { if (msg) { // fall back to timestamp stream before this, give 48 hrs for feeds to stabilize if (msg.value.timestamp > oldest) { oldest = Date.now() } } }) var prepend = [ api.message.html.compose({ meta: { type: 'post' }, placeholder: 'Write a public message' }) ] var feedView = api.feed.html.rollup(getFeed, { prepend, waitUntil: computed([ following.sync, subscribedChannels.sync ], (...x) => x.every(Boolean)), windowSize: 500, filter: (item) => { return !item.boxed && ( id === item.author || following().has(item.author) || subscribedChannels().has(item.channel) || (item.repliesFrom && item.repliesFrom.has(id)) || item.digs && item.digs.has(id) ) }, bumpFilter: (msg, group) => { if (!group.message) { return ( isMentioned(id, msg.value.content.mentions) || msg.value.author === id || ( fromDay(msg, group.fromTime) && ( following().has(msg.value.author) || group.repliesFrom.has(id) ) ) ) } return true } }) var result = h('div.SplitView', [ h('div.side', [ getSidebar() ]), h('div.main', feedView) ]) result.pendingUpdates = feedView.pendingUpdates return result function getSidebar () { var whoToFollow = computed([following, api.profile.obs.recentlyUpdated(200)], (following, recent) => { return Array.from(recent).filter(x => x !== id && !following.has(x)).slice(0, 10) }) return [ h('h2', 'Active Channels'), when(loading, [ h('Loading') ]), h('div', { classList: 'ChannelList', hidden: loading }, [ map(channels, (channel) => { var subscribed = subscribedChannels.has(channel.id) return h('a.channel', { href: `#${channel.id}`, classList: [ when(subscribed, '-subscribed') ] }, [ h('span.name', '#' + channel.id), when(subscribed, h('a.-unsubscribe', { 'ev-click': send(unsubscribe, channel.id) }, 'Unsubscribe'), h('a.-subscribe', { 'ev-click': send(subscribe, channel.id) }, 'Subscribe') ) ]) }, {maxTime: 5}) ]), when(computed(localPeers, x => x.length), h('h2', 'Local')), h('div', { classList: 'ProfileList' }, [ map(localPeers, (id) => { return h('a.profile', { classList: [ when(computed([connectedPeers, id], (p, id) => p.includes(id)), '-connected') ], href: id }, [ h('div.avatar', [api.about.html.image(id)]), h('div.main', [ h('div.name', [ '@', api.about.obs.name(id) ]) ]) ]) }) ]), when(computed(whoToFollow, x => x.length), h('h2', 'Who to follow')), when(following.sync, h('div', { classList: 'ProfileList' }, [ map(whoToFollow, (id) => { return h('a.profile', { href: id }, [ h('div.avatar', [api.about.html.image(id)]), h('div.main', [ h('div.name', [ '@', api.about.obs.name(id) ]) ]) ]) }) ]), h('div', {classList: 'Loading'}) ), when(computed(connectedPubs, x => x.length), h('h2', 'Connected Pubs')), h('div', { classList: 'ProfileList' }, [ map(connectedPubs, (id) => { return h('a.profile', { classList: [ '-connected' ], href: id }, [ h('div.avatar', [api.about.html.image(id)]), h('div.main', [ h('div.name', [ '@', api.about.obs.name(id) ]) ]) ]) }) ]) ] } function getFeed (opts) { if (opts.lt && opts.lt < oldest) { opts = extend(opts, {lt: parseInt(opts.lt, 10)}) return pull( api.sbot.pull.feed(opts), pull.map((msg) => { if (msg.sync) { return msg } else { return {key: msg.key, value: msg.value, timestamp: msg.value.timestamp} } }) ) } else { return api.sbot.pull.log(opts) } } function getFirstMessage (feedId, cb) { api.sbot.pull.userFeed({id: feedId, gte: 0, limit: 1})(null, cb) } function subscribe (id) { api.sbot.async.publish({ type: 'channel', channel: id, subscribed: true }) } function unsubscribe (id) { api.sbot.async.publish({ type: 'channel', channel: id, subscribed: false }) } } } function isMentioned (id, list) { if (Array.isArray(list)) { return list.includes(id) } else { return false } } function fromDay (msg, fromTime) { return (fromTime - msg.timestamp) < (24 * 60 * 60e3) } function arrayEq (a, b) { if (Array.isArray(a) && Array.isArray(b) && a.length === b.length && a !== b) { return a.every((value, i) => value === b[i]) } }
JavaScript
0
@@ -2951,16 +2951,52 @@ gUpdates +%0A result.reload = feedView.reload %0A%0A re
2fe9c06695ba01b1aa1f451177c0bc2939574677
Update numberIterators.js
numberIterators.js
numberIterators.js
Number.iterator(function(){ var up=this.valueOf(); for(var i=0;i<up;i++){ this.yield({n:i}); } return null; },"times"); /** * Ruby-style times iterator for Number s. * */
JavaScript
0
@@ -125,16 +125,306 @@ imes%22);%0A +Number.iterator(function(upTo)%7B%0A var low=this.valueOf();%0A for(var i=low;i%3C=upTo;i++)%7B%0A this.yield(%7Bn:i%7D);%0A %7D%0A return null;%0A%7D,%22upto%22);%0ANumber.iterator(function(downTo)%7B%0A var high=this.valueOf();%0A for(var i=high;i%3E=downTo;i--)%7B%0A this.yield(%7Bn:i%7D);%0A %7D%0A return null;%0A%7D,%22downto%22);%0A /**%0A * R
17b8157145507a8c9d3eb457b9fa2eea5433f6a4
change update interval
web3/static/js/sites/info.js
web3/static/js/sites/info.js
jQuery.fn.selectText = function(){ var doc = document; var element = this[0]; if (doc.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); } }; function updateStatus() { var s = $("#process-status").text(); if (s.includes("STARTING")) { setTimeout(function() { $.get(status_refresh_endpoint, function(data) { $("#process-status").text(data); updateStatus(); }); }, 2000); } } $(document).ready(function() { if (window.location.hash) { var ele = $("a[href='" + window.location.hash + "']"); if (ele.length && ele.hasClass("nav-link")) { ele.click(); } } $("#git-pull").click(function() { $(this).html("<i class='fa fa-cog fa-spin'></i> Pulling...").prop("disabled", true); $.get(git_pull_endpoint, function(data) { $("#git-output").text("Process exited with return code " + data.ret + (data.out ? "\n\n" + data.out : "") + (data.err ? "\n\n" + data.err : "")).slideDown("fast"); }).fail(function(xhr, textStatus, err) { $("#git-output").text("Failed to contact server!\n\n" + xhr + "\n" + textStatus + "\n" + err).slideDown("fast"); }).always(function() { $("#git-pull").html("<i class='fa fa-github'></i> Git Pull").prop("disabled", false); }); }); $("#generate-database-password").click(function(e) { if (!confirm("Are you sure you want to regenerate passwords for this database?")) { e.preventDefault(); } }); $("#generate-key").click(function(e) { if ($(this).text().indexOf("Regenerate") > -1) { if (!confirm("Are you sure you want to regenerate keys for this site?")) { e.preventDefault(); } } }); $("#database-url").click(function() { $("#database-pass").removeClass("hide"); }).dblclick(function() { $(this).selectText(); }).on("blur",function() { $("#database-pass").addClass("hide"); }); updateStatus(); }); var select = function(el) { var range = document.createRange(); range.selectNodeContents(el); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); }
JavaScript
0.000001
@@ -780,9 +780,9 @@ %7D, -2 +1 000)
bce9ee3adf2d14dc884bdef53f56ded377c50dc1
Remove debug trace
core/app/assets/javascripts/admin/orders/edit_form.js
core/app/assets/javascripts/admin/orders/edit_form.js
$(document).ready(function() { $.each($('td.qty input'), function(i, input) { $(input).on('change', function() { var id = "#" + $(this).attr('id').replace("_quantity", "_id"); console.log($(this)) console.log($(id)) jQuery.post("/admin/orders/" + $('input#order_number').val() + "/line_items/" + $(id).val(), { _method: "put", "line_item[quantity]": $(this).val()}, function(resp) { $('#order-form-wrapper').html(resp.responseText); }) }) }) });
JavaScript
0.000005
@@ -186,60 +186,8 @@ d%22); -%0A console.log($(this))%0A console.log($(id)) %0A%0A
267dfa831b3d635b171103aa7c1c2fee66e86e2a
fix locations => location.js
corehq/apps/locations/static/locations/js/location.js
corehq/apps/locations/static/locations/js/location.js
// for product and user per location selection hqDefine("locations/js/location", [ 'jquery', 'knockout', 'underscore', 'hqwebapp/js/initial_page_data', 'hqwebapp/js/alert_user', 'analytix/js/google', 'locations/js/location_drilldown', 'hqwebapp/js/select_2_ajax_widget', 'hqwebapp/js/widgets', // custom data fields use a .hqwebapp-select2 'locations/js/widgets', ], function ( $, ko, _, initialPageData, alertUser, googleAnalytics, locationModels ) { var insert_new_user = function (user) { var $select = $('#id_users-selected_ids'); // Add the newly created user to the users that are already at the location. var currentUsers = $select.select2('data'); currentUsers.push({ "text": user.text, "id": user.user_id }); // Push the updated list of currentUsers to the ui $select.select2("data", currentUsers); }; var TEMPLATE_STRINGS = { new_user_success: _.template(gettext("User <%= name %> added successfully. " + "A validation message has been sent to the phone number provided.")), }; $(function () { var form_node = $('#add_commcare_account_form'); var url = form_node.prop('action'); $('#new_user').on('show.bs.modal', function () { form_node.html('<i class="fa fa-refresh fa-spin"></i>'); $.get(url, function (data) { form_node.html(data.form_html); }); }); form_node.submit(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: url, data: form_node.serialize(), success: function (data) { if (data.status === 'success') { insert_new_user(data.user); alertUser.alert_user( TEMPLATE_STRINGS.new_user_success({name: data.user.text}), 'success' ); $('#new_user').modal('hide'); } else { form_node.html(data.form_html); } }, error: function () { alertUser.alert_user(gettext('Error saving user', 'danger')); }, }); }); }); $(function () { var location_url = initialPageData.get('api_root'); var loc_id = initialPageData.get('location_id'); var loc_type = initialPageData.get('location_type'); var hierarchy = initialPageData.get('hierarchy'); var model = locationModels.locationSelectViewModel({ "hierarchy": hierarchy, "default_caption": "\u2026", "auto_drill": false, "loc_filter": function (loc) { return loc.uuid() !== loc_id && loc.can_have_children(); }, "loc_url": location_url, }); model.editing = ko.observable(false); model.allowed_child_types = ko.computed(function () { var active_loc = (this.selected_location() || this.root()); return (active_loc ? active_loc.allowed_child_types() : []); }, model); model.loc_type = ko.observable(loc_type); var locs = initialPageData.get('locations'); var selected_parent = initialPageData.get('location_parent_get_id'); model.load(locs, selected_parent); model.orig_parent_id = model.selected_locid(); $("#loc_form :button[type='submit']").click(function () { if (this.name === 'update-loc') { googleAnalytics.track.event('Organization Structure', 'Edit', 'Update Location'); } else { googleAnalytics.track.event('Organization Structure', 'Edit', 'Create Child Location'); } }); googleAnalytics.track.click($("#edit_users :button[type='submit']"), 'Organization Structure', 'Edit', 'Update Users at this Location'); $('#loc_form').koApplyBindings(model); }); });
JavaScript
0.000013
@@ -1016,17 +1016,17 @@ %22User %3C%25 -= +- name %25%3E
44955a12a723c94b93ae2c67814ef48cd9fac7f7
Update index.js
www/js/index.js
www/js/index.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); document.getElementById('scan').addEventListener('click', this.scan, false); document.getElementById('encode').addEventListener('click', this.encode, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); }, scan: function() { console.log('scanning'); var scanner = cordova.require("cordova/plugin/BarcodeScanner"); scanner.scan( function (result) { alert("We got a barcode\n" + "Result: " + result.text + "\n" + "Format: " + result.format + "\n" + "Cancelled: " + result.cancelled); console.log("Scanner result: \n" + "text: " + result.text + "\n" + "format: " + result.format + "\n" + "cancelled: " + result.cancelled + "\n"); document.getElementById("info").innerHTML = result.text; console.log(result); /* if (args.format == "QR_CODE") { window.plugins.childBrowser.showWebPage(args.text, { showLocationBar: false }); } */ }, function (error) { console.log("Scanning failed: ", error); } ); } };
JavaScript
0.000002
@@ -1609,24 +1609,94 @@ iceready');%0A + navigator.geolocation.getCurrentPosition(onSuccess, onError);%0A %0A %7D,%0A @@ -3115,16 +3115,1155 @@ %7D );%0A + %7D,%0A onSuccess: function(position) %7B%0A var element = document.getElementById('geolocation');%0A element.innerHTML = 'Latitude: ' + position.coords.latitude + '%3Cbr /%3E' +%0A 'Longitude: ' + position.coords.longitude + '%3Cbr /%3E' +%0A 'Altitude: ' + position.coords.altitude + '%3Cbr /%3E' +%0A 'Accuracy: ' + position.coords.accuracy + '%3Cbr /%3E' +%0A 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '%3Cbr /%3E' +%0A 'Heading: ' + position.coords.heading + '%3Cbr /%3E' +%0A 'Speed: ' + position.coords.speed + '%3Cbr /%3E' +%0A 'Timestamp: ' + position.timestamp + '%3Cbr /%3E';%0A %7D%0A%0A // onError Callback receives a PositionError object%0A //%0A onError: function(error) %7B%0A alert('code: ' + error.code + '%5Cn' +%0A 'message: ' + error.message + '%5Cn');%0A %7D%0A%7D;
77e71c9c6a748f62e54f7864ccaf2c8e02af8a27
Add alert on Blrb/Me
www/js/index.js
www/js/index.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicity call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); var ref = window.open('http://blrbrdev.azurewebsites.net', '_blank', 'location=no'); //ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); }); ref.addEventListener('loadstart', function(event) { //alert('stop: ' + event.url); if(event.url.indexOf('Blrb/Create') != -1) { ref.close(); window.location="create.html"; } } ); ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); }); ref.addEventListener('exit', function(event) { }); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } };
JavaScript
0
@@ -1730,16 +1730,213 @@ .url); %0A + %0A %09if(event.url.indexOf('Blrb/Me') != -1)%0A %09%7B%0A %09%09debugger;%0A %09%09alert(%22ME%22);%0A %09%09alert(event.url);%0A %09%09alert(event);%0A %09%7D%0A %0A @@ -1984,32 +1984,52 @@ -1)%0A %09%7B%0A + %09%09debugger;%0A %09%09ref.cl
78327eac44243e0fe8cbc64392a9ebeae2f05083
Update vstarcam.js
www/vstarcam.js
www/vstarcam.js
var exec = require('cordova/exec'); module.exports = { videostream: function(cameraId, user, pass, onSuccess, onError){ exec(onSuccess, onError, "Vstarcam", "videostream", [cameraId, user, pass]); } };
JavaScript
0.000001
@@ -115,16 +115,86 @@ Error)%7B%0A +%09%09console.log('videostream-params:'+cameraId+','+ user + ',' + pass);%0A %09%09exec(o
b92aa8004dfde13fc12fa514ce76a427bda8de5e
Add decimal point feature. Needs adjusting to compensate for accuracy errors w/ precision problems of non-integers.
assets/javascript/main.js
assets/javascript/main.js
//Function to run when window is loaded in browser Sets variables, event handlers, and contains event listener definitions. var init = function () { //Declare local variables var equalsButton; //for querySelector var clearButton; //for querySelector var toggleSignButton; // for querySelector var displayNumber; //for querySelector var decimalButton; //for querySelector var calculation = []; //Current calculation var numberPressedLast = false; var decimalPressedLast = false; // Variable pointing to equals-button HTML element equalsButton = document.querySelector("#button-equal"); // Variable pointing to AC-button HTML element clearButton = document.querySelector("#button-clear"); // Variable pointing to display-digits HTML element displayNumber = document.querySelector(".display-digits"); // Variable pointing to button-toggle-sign HTML element toggleSignButton = document.querySelector("#button-toggle-sign"); // Variable pointing to button-toggle-sign HTML element decimalButton = document.querySelector("#button-decimal"); //Event handler that adds the value of the clicked number button to the calculation var numberPressed = function(event) { var button = event.target; var text = button.textContent; var lastValueEntered; if (decimalPressedLast) { lastValueEntered = calculation[calculation.length - 1]; calculation[calculation.length-1] = lastValueEntered + text; //displayNumber.innerText += calculation[calculation.length-2] + calculation[calculation.length-1]; } else if (numberPressedLast) { calculation[calculation.length - 1] += text; //displayNumber.innerText = calculation[calculation.length - 1]; } else { calculation.push(text); //displayNumber.innerText = text; } numberPressedLast = true; console.log(text + " CLICKED"); console.log(calculation); }; //Event handler that adds the value of the clicked operator button to the calculation var operatorPressed = function(event) { var button = event.target; var text = button.textContent; if (numberPressedLast) { calculation.push(text); } else { calculation[calculation.length - 1] = text; } numberPressedLast = false; console.log(text + " CLICKED"); console.log(calculation); }; //Event handler that joins the calculation array into a string, calls eval() to generate an answer, and displays the answer to the screen var equalPressed = function(event) { var button = event.target; var text = button.textContent; var answer; calculation = calculation.join(''); answer = eval(calculation); //displayNumber.innerText = answer; console.log(text + " CLICKED"); console.log(calculation); console.log("answer is: " + answer); }; //Event handler that resets the calculation and calculator display to zero var clearPressed = function(event) { var button = event.target; var text = button.textContent; calculation = []; //displayNumber.innerText = "0"; numberPressedLast = false; decimalPressedLast = false; console.log(text + " CLICKED"); console.log(calculation); }; //Event handler that toggles the sign of the last pressed number button value var toggleSignPressed = function(event) { var button = event.target; var lastValueEntered; lastValueEntered = calculation[calculation.length - 1]; calculation[calculation.length - 1] = ( lastValueEntered * -1); //displayNumber.innerText = calculation[calculation.length - 1]; console.log("Toggle sign pressed"); console.log(calculation); }; //Event handler that toggles the sign of the last pressed number button value var decimalPressed = function(event) { var button = event.target; var text = button.textContent; var lastValueEntered; if (decimalPressedLast===false) { lastValueEntered = calculation[calculation.length - 1]; lastValueEntered += lastValueEntered + "."; calculation += calculation.splice((calculation.length-1), lastValueEntered); //displayNumber.innerText += "."; decimalPressedLast = true; numberPressedLast = false; console.log("Decimal pressed"); console.log(calculation); } }; // Loop over every element in document. Finds every element w. matching CSS class and binds event listener to 'click' event on that button. When element is clicked, function alertButtonValue is called. [].forEach.call(document.querySelectorAll('.button-number'), function(element){ element.addEventListener('click', numberPressed); }, false); [].forEach.call(document.querySelectorAll('.button-operator'), function(element){ element.addEventListener('click', operatorPressed);}, false); // Bind event listener to equals button equalsButton.addEventListener('click', equalPressed, false); // Bind event listener to AC button clearButton.addEventListener('click', clearPressed, false); // Bind event listener to toggle-sign button toggleSignButton.addEventListener('click', toggleSignPressed, false); // Bind event listener to decimal button decimalButton.addEventListener('click', decimalPressed, false); }; window.onload = init;
JavaScript
0.000001
@@ -1289,34 +1289,8 @@ ent; -%0A var lastValueEntered; %0A%0A @@ -1317,73 +1317,32 @@ Last -) %7B%0A lastValueEntered = calculation%5Bcalculation.length - 1%5D; + %7C%7C numberPressedLast) %7B %0A @@ -1378,36 +1378,18 @@ ngth-1%5D -= lastValueEntered + += text;%0A @@ -1498,172 +1498,8 @@ 1%5D;%0A - %7D%0A else if (numberPressedLast) %7B%0A calculation%5Bcalculation.length - 1%5D += text;%0A //displayNumber.innerText = calculation%5Bcalculation.length - 1%5D;%0A @@ -1618,18 +1618,16 @@ = true;%0A -%0A%0A cons @@ -2043,32 +2043,64 @@ edLast = false;%0A + decimalPressedLast = false;%0A console.log( @@ -3735,35 +3735,16 @@ %7B%0A - lastValueEntered = calcula @@ -3775,142 +3775,17 @@ - 1%5D -;%0A lastValueEntered += lastValueEntered + %22.%22;%0A calculation += calculation.splice((calculation.length-1), lastValueEntered); + += %22.%22;%0A %0A
a08a58d5c36a2016d36a358e6ac7c11d7ea4e713
Fix collapsible
assets/js/admin-global.js
assets/js/admin-global.js
(function ($) { var constants = { notification: { show: { duration: 'slow', delay: 500 }, hide: { duration: 'slow', delay: 5000 } } }, properties = { }, methods = { init: function () { $(window).load(methods.loaded); $('.table').dataTable(); $('.modal').on('hide.bs.modal', methods.hideModal); $('[data-toggle="collapse"]').on('click', methods.collapse).each(methods.prepareCollapse); $('.alert-notifications .alert').each(methods.showNotification); }, loaded: function () { $('body').addClass('loaded'); }, prepareCollapse: function() { var $this = $(this), target = $($this.attr('data-target')); if (target.hasClass('in')) { $this.data('originalTitle', $this.html()); $this.html('<span class="glyphicon glyphicon-minus" aria-hidden="true" /> Hide'); } }, collapse: function () { var $this = $(this), target = $($this.attr('data-target')); if (target.hasClass('collapsing')) { return; } var originalTitle = $this.data('originalTitle'); if (originalTitle && target.hasClass('in')) { $this.html(originalTitle); $this.data('originalTitle', null); return; } if (!originalTitle) { $this.data('originalTitle', $this.html()); $this.html('<span class="glyphicon glyphicon-minus" aria-hidden="true" /> Hide'); } }, hideModal: function () { var href = $('.btn-cancel', this).attr('data-href'); if (href) { window.location.href = href; } }, showNotification: function () { $(this).delay(constants.notification.show.delay).fadeIn( constants.notification.show.duration, methods.hideNotification ).hover( methods.hoverNotification, methods.hideNotification ); }, hideNotification: function () { $(this).delay(constants.notification.hide.delay).fadeOut( constants.notification.hide.duration ); }, hoverNotification: function () { $(this).stop(true).show(); } }; $(document).ready(methods.init); })(jQuery);
JavaScript
0.000002
@@ -1863,63 +1863,14 @@ - return;%0D%0A %7D%0D%0A +%7D else if
fecec2910e6b390248b2b514131e0b175fc131f1
Fix settings page filter function
components/Settings/Settings.js
components/Settings/Settings.js
import React, { Component, PropTypes } from 'react' import bem from 'js-kit/dom/bem' import SettingsLink from '../SettingsLink/SettingsLink' class Settings extends Component { static propTypes = { services: PropTypes.array.isRequired, updateServiceSubscription: PropTypes.func.isRequired }; constructor (props) { super(props) this.state = { filterText: '' } this.handleChange = this.handleChange.bind(this) } handleChange (event) { this.setState({filterText: event.target.value}) } matchesFilter (str) { if (!this.state.filterText) return true const filterText = this.state.filterText return str.toLowerCase().indexOf(filterText.toLowerCase()) === -1 } render () { const c = bem('Settings') const { services, updateServiceSubscription } = this.props const servicesHtml = services.map((s, i) => ( this.matchesFilter(s.name + s.id) ? ( <div className={c('&__option')} key={i}> <label className={c('&__field')}> <span className={c('&__toggle')}> <input type='checkbox' checked={s.subscribed} onChange={(e) => { updateServiceSubscription({ id: s.id, subscribed: e.target.checked }) }} /> <b /> </span> <span className={c('&__optionTitle')}>{ s.parent }</span> — { s.name } </label> </div> ) : null )) return ( <div className='Settings'> <div className='Settings__filterContainer'> <input className='Settings__filter' placeholder='Type to filter Services...' type='text' value={this.state.filterText} onChange={this.handleChange} /> </div> <div className='Settings__options'> { servicesHtml } </div> <SettingsLink to='/' /> </div> ) } } export default Settings
JavaScript
0.000001
@@ -701,17 +701,17 @@ Case()) -= +! == -1%0A
3f5ee974d2e2bd30b38c3235c13089c302c27f78
add playedDate to scoreboard
client/app/scripts/services/GameService.js
client/app/scripts/services/GameService.js
'use strict'; angular.module('meanRecipieApp') .factory('GameService', function(localStorageService, ScoreResource) { var game = { scoreBoard: {} }; var cardIndex = 0; var saveScoreboardLocal = function() { localStorageService.add(game.deck.name, angular.toJson(game.scoreBoard)); }; return { initScoreBoard: function() { cardIndex = 0; game.scoreBoard.score = 0; game.scoreBoard.incorrectCards = []; game.scoreBoard.correctCards = []; if (game.deck) { game.scoreBoard.outOf = game.deck.cards.length; } }, getGame: function() { this.initScoreBoard(); return game; }, setGame: function(deck) { game.deck = deck; this.initScoreBoard(); }, getNextCard: function() { if (cardIndex < game.deck.cards.length) { var nextCard = game.deck.cards[cardIndex]; cardIndex = cardIndex + 1; return nextCard; } return null; }, checkGuess: function(card, guess) { if (card.translated === guess) { return true; } else { return false; } }, updateScoreBoard: function(guessResult, card) { if (guessResult) { game.scoreBoard.score += 1; game.scoreBoard.correctCards.push(card); } else { game.scoreBoard.incorrectCards.push(card); } saveScoreboardLocal(); return game.scoreBoard; }, getScoreBoard: function() { return game.scoreBoard; }, saveScoreBoard: function() { ScoreResource.save(game.scoreBoard); }, buildFeedback: function(result, card) { if (result) { return 'Correct'; } else { return 'Incorrect, answer is: ' + card.translated; } } }; });
JavaScript
0.000001
@@ -357,24 +357,69 @@ dIndex = 0;%0A +%09%09%09%09game.scoreBoard.playedDate = new Date();%0A %09%09%09%09game.sco
3f6faa5371b73bbda8eb5d1c6fb3b39b9f6cf554
Use segment for tracking
client/app/scripts/utils/tracking-utils.js
client/app/scripts/utils/tracking-utils.js
import debug from 'debug'; const log = debug('service:tracking'); // Track mixpanel events only if Scope is running inside of Weave Cloud. export function trackMixpanelEvent(name, props) { if (window.mixpanel && process.env.WEAVE_CLOUD) { window.mixpanel.track(name, props); } else { log('trackMixpanelEvent', name, props); } }
JavaScript
0
@@ -197,24 +197,25 @@ (window. -mixpanel +analytics && proc @@ -248,24 +248,25 @@ window. -mixpanel +analytics .track(n
db68279aa1a8581a574a41bba86481f93c8c04a3
Update main.js
blocks/main.js
blocks/main.js
export default(request) =>{ // Required modules const db = require("kvstore"); // Database module const xhr = require("xhr"); // xmlHttprequest module const pubnub = require("pubnub"); var date_const = new Date(); // Date constructor var message_dict = {}; var url_fetched_data = null; var fetched_message_body = null; var database_value = null; var TimeLimit = 15; var weather_state = null; var minute = 60*60*24; // In minutes var diff_inminutes = null; var username = '88e9ca57-09f6-471d-be6e-a75d9c3c8700'; var password = 'qTxtbhhxqA'; var joincommand = "join"; var leavecommand = "leave"; var messagecommand = "message"; // Air Traffic Control Station Location's Lattitude and Longitude var Location_data = {"Anchorage":{"lattitude":"49.3789762","longitude":"-130.5870698"}, "Vancouver":{"lattitude":"49.2577142","longitude":"-123.1941156"}, "Seattle":{"lattitude":"47.5536626","longitude":"-122.4378361"}, "Portland":{"lattitude":"45.4363626","longitude":"-122.7286843"}}; // Pubnub Publish channel on which we will broadcast the messages. var pubchannel = "chat_receive"; /* Name - broadcastMessage Description - Function used to send message to users via pubnub Parameters - pubchannel : Channel for braodcasting the message message : Message to be sent to users */ function broadcastMessage(pubchannel,message){ // Broadcasting the Message to all the Users. pubnub.publish({ channel : pubchannel, message : message, callback : function(e) { console.log( "SUCCESS!", e ); }, error : function(e) { console.log( "FAILED! RETRY PUBLISH!", e ); } }); } /* Name - fetchLocationWeather Description - Function used to execute the external api call to fetch the wether state from the IBM weather company data. Parameters - location : The ATC Location Name. */ function fetchLocationWeather(location){ console.log("RECEIVED ATC LOCATION",location); var lattitude = Location_data[location]["lattitude"]; //Extract Lattitude from the locally stored Object var longitude = Location_data[location]["longitude"]; //Extract Longitude from the locally stored Object. // URL for the weather API const url = ('https://'+username+':'+password+'@twcservice.mybluemix.net:443/api/weather/v1/geocode/'+lattitude+'/'+longitude+'/observations.json?units=m&language=en-US'); // Making an external api call for the weather data xhr.fetch(url).then((url_fetched_data) =>{ var fetched_message_body = JSON.parse(url_fetched_data.body); var weather_state = fetched_message_body.observation.wx_phrase; console.log("FETCHED WEATHER_DATA FOR RECEIVED ATC LOCATION --> ",weather_state); // Preparing Object with the Current Time and Weather State message_dict = {"lastupdatedTime":date_const.getTime(),"lastweatherUpdate":weather_state}; // Inserting the Prepared Object with to the Database with location as key. db.set(location,message_dict); }).catch((err) => { // handle request failure console.log("THE API CALL ERROR --> ",err); }); } /* First condition Command - Join Description - Handles the Messages of type Join. */ if (request.message.command == joincommand){ console.log("RECEIVED JOIN COMMAND"); db.get(request.message.ATClocation).then((database_value)=>{ console.log("FETCHED DATABASE VALUE",database_value); if (!database_value) { var location = request.message.ATClocation; // Extract the location from the incoming Message. fetchLocationWeather(location); console.log(request.message); } broadcastMessage(pubchannel,request.message); });// db call ending } // First condition Ending /* Second Condition Command - message Description - Handles the Messages of type message */ if (request.message.command == messagecommand){ console.log("RECEIVED MESSAGE COMMAND"); db.get(request.message.ATClocation).then((database_value) =>{ console.log("FETCHED DATABASE VALUE -->",database_value); var currentTime = date_const.getTime(); // Getting the Current time var lastupdatedTime = database_value.lastupdatedTime; // Extracting the Lastupdate time from the Database. diff_inminutes = Math.round((currentTime - lastupdatedTime)/minute); // Calculating Time difference console.log("TIME DIFFERENCE IN MINUTES --> ",diff_inminutes); // Checking for 15 min interval if (diff_inminutes>=TimeLimit) { var location = request.message.ATClocation; fetchLocationWeather(location); db.get(location).then((database_value) => { request.message.weatherStatus = database_value.lastweatherUpdate; console.log("BROADCASTING MESSAGE WITH NOT AVAILABLE DATA -->",request.message); broadcastMessage(pubchannel,request.message); }); } else { db.get(request.message.ATClocation).then((database_value) => { request.message.weatherStatus = database_value.lastweatherUpdate; console.log("BROADCASTING MESSAGE WITH AVAILABLE DATA -->",request.message); broadcastMessage(pubchannel,request.message); }); } }); // db call ending } // Second command ending /* Third condition Command - Leave Description - Handles the Messages of type Leave */ if (request.message.command == leavecommand){ console.log("RECEIVED LEAVE COMMAND"); console.log("BROADCASTING MESSAGE -->",request.message); broadcastMessage(pubchannel,request.message); } // Third condition ending return request.ok(); };
JavaScript
0.000001
@@ -5521,21 +5521,23 @@ econd co -mmand +ndition ending%0A
67b4aa7543ecd25a78ee81170ab8355e2ec183a2
Add pull-down class
src/js/pull-to-refresh.js
src/js/pull-to-refresh.js
/*====================================================== ************ Pull To Refresh ************ ======================================================*/ app.initPullToRefresh = function (pageContainer) { var eventsTarget = $(pageContainer); if (!eventsTarget.hasClass('pull-to-refresh-content')) { eventsTarget = eventsTarget.find('.pull-to-refresh-content'); } if (eventsTarget.length === 0) return; var isTouched, isMoved, touchesStart = {}, isScrolling, touchesDiff, touchStartTime, container, refresh = false, useTranslate = false, startTranslate = 0, translate, scrollTop; container = eventsTarget; function handleTouchStart(e) { if (isTouched) { if (app.device.os === 'android') { if ('targetTouches' in e && e.targetTouches.length > 1) return; } else return; } isMoved = false; isTouched = true; isScrolling = undefined; touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX; touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY; touchStartTime = (new Date()).getTime(); /*jshint validthis:true */ container = $(this); } function handleTouchMove(e) { if (!isTouched) return; var pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX; var pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY; if (typeof isScrolling === 'undefined') { isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x)); } if (!isScrolling) { isTouched = false; return; } scrollTop = container[0].scrollTop; if (!isMoved) { /*jshint validthis:true */ container.removeClass('transitioning'); if (scrollTop > container[0].offsetHeight) { isTouched = false; return; } startTranslate = container.hasClass('refreshing') ? 44 : 0; if (container[0].scrollHeight === container[0].offsetHeight || app.device.os !== 'ios') { useTranslate = true; } else { useTranslate = false; } } isMoved = true; touchesDiff = pageY - touchesStart.y; if (touchesDiff > 0 && scrollTop <= 0 || scrollTop < 0) { if (useTranslate) { e.preventDefault(); translate = (Math.pow(touchesDiff, 0.85) + startTranslate); container.transform('translate3d(0,' + translate + 'px,0)'); } if ((useTranslate && Math.pow(touchesDiff, 0.85) > 44) || (!useTranslate && touchesDiff >= 88)) { refresh = true; container.addClass('pull-up'); } else { refresh = false; container.removeClass('pull-up'); } } else { container.removeClass('pull-up'); refresh = false; return; } } function handleTouchEnd(e) { if (!isTouched || !isMoved) { isTouched = false; isMoved = false; return; } if (translate) { container.addClass('transitioning'); translate = 0; } container.transform(''); if (refresh) { container.addClass('refreshing'); container.trigger('refresh', { done: function () { app.pullToRefreshDone(container); } }); } isTouched = false; isMoved = false; } // Attach Events eventsTarget.on(app.touchEvents.start, handleTouchStart); eventsTarget.on(app.touchEvents.move, handleTouchMove); eventsTarget.on(app.touchEvents.end, handleTouchEnd); // Detach Events on page remove var page = eventsTarget.hasClass('page') ? eventsTarget : eventsTarget.parents('.page'); if (page.length === 0) return; function detachEvents() { eventsTarget.off(app.touchEvents.start, handleTouchStart); eventsTarget.off(app.touchEvents.move, handleTouchMove); eventsTarget.off(app.touchEvents.end, handleTouchEnd); page.off('pageBeforeRemove', detachEvents); } page.on('pageBeforeRemove', detachEvents); }; app.pullToRefreshDone = function (container) { container = $(container); if (container.length === 0) container = $('.pull-to-refresh-content.refreshing'); container.removeClass('refreshing').addClass('transitioning'); container.transitionEnd(function () { container.removeClass('transitioning pull-up'); }); }; app.pullToRefreshTrigger = function (container) { container = $(container); if (container.length === 0) container = $('.pull-to-refresh-content'); if (container.hasClass('refreshing')) return; container.addClass('transitioning refreshing'); container.trigger('refresh', { done: function () { app.pullToRefreshDone(container); } }); };
JavaScript
0
@@ -2904,32 +2904,57 @@ Class('pull-up') +.removeClass('pull-down') ;%0A %7D%0A @@ -3045,32 +3045,54 @@ Class('pull-up') +.addClass('pull-down') ;%0A %7D%0A @@ -3167,24 +3167,34 @@ ass('pull-up + pull-down ');%0A @@ -3793,32 +3793,105 @@ %7D);%0A %7D%0A + else %7B%0A container.removeClass('pull-down');%0A %7D%0A isTouche @@ -4959,16 +4959,26 @@ pull-up + pull-down ');%0A
483cf30801069d24122a130dfcb9d85fd55474c2
Support environments without ReadableStream (#23032)
src/loaders/FileLoader.js
src/loaders/FileLoader.js
import { Cache } from './Cache.js'; import { Loader } from './Loader.js'; const loading = {}; class FileLoader extends Loader { constructor( manager ) { super( manager ); } load( url, onLoad, onProgress, onError ) { if ( url === undefined ) url = ''; if ( this.path !== undefined ) url = this.path + url; url = this.manager.resolveURL( url ); const cached = Cache.get( url ); if ( cached !== undefined ) { this.manager.itemStart( url ); setTimeout( () => { if ( onLoad ) onLoad( cached ); this.manager.itemEnd( url ); }, 0 ); return cached; } // Check if request is duplicate if ( loading[ url ] !== undefined ) { loading[ url ].push( { onLoad: onLoad, onProgress: onProgress, onError: onError } ); return; } // Initialise array for duplicate requests loading[ url ] = []; loading[ url ].push( { onLoad: onLoad, onProgress: onProgress, onError: onError, } ); // create request const req = new Request( url, { headers: new Headers( this.requestHeader ), credentials: this.withCredentials ? 'include' : 'same-origin', // An abort controller could be added within a future PR } ); // start the fetch fetch( req ) .then( response => { if ( response.status === 200 || response.status === 0 ) { // Some browsers return HTTP Status 0 when using non-http protocol // e.g. 'file://' or 'data://'. Handle as success. if ( response.status === 0 ) { console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); } const callbacks = loading[ url ]; const reader = response.body.getReader(); const contentLength = response.headers.get( 'Content-Length' ); const total = contentLength ? parseInt( contentLength ) : 0; const lengthComputable = total !== 0; let loaded = 0; // periodically read data into the new stream tracking while download progress return new ReadableStream( { start( controller ) { readData(); function readData() { reader.read().then( ( { done, value } ) => { if ( done ) { controller.close(); } else { loaded += value.byteLength; const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } ); for ( let i = 0, il = callbacks.length; i < il; i ++ ) { const callback = callbacks[ i ]; if ( callback.onProgress ) callback.onProgress( event ); } controller.enqueue( value ); readData(); } } ); } } } ); } else { throw Error( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}` ); } } ) .then( stream => { const response = new Response( stream ); switch ( this.responseType ) { case 'arraybuffer': return response.arrayBuffer(); case 'blob': return response.blob(); case 'document': return response.text() .then( text => { const parser = new DOMParser(); return parser.parseFromString( text, this.mimeType ); } ); case 'json': return response.json(); default: return response.text(); } } ) .then( data => { // Add to cache only on HTTP success, so that we do not cache // error response bodies as proper responses to requests. Cache.add( url, data ); const callbacks = loading[ url ]; delete loading[ url ]; for ( let i = 0, il = callbacks.length; i < il; i ++ ) { const callback = callbacks[ i ]; if ( callback.onLoad ) callback.onLoad( data ); } } ) .catch( err => { // Abort errors and other errors are handled the same const callbacks = loading[ url ]; if ( callbacks === undefined ) { // When onLoad was called and url was deleted in `loading` this.manager.itemError( url ); throw err; } delete loading[ url ]; for ( let i = 0, il = callbacks.length; i < il; i ++ ) { const callback = callbacks[ i ]; if ( callback.onError ) callback.onError( err ); } this.manager.itemError( url ); } ) .finally( () => { this.manager.itemEnd( url ); } ); this.manager.itemStart( url ); } setResponseType( value ) { this.responseType = value; return this; } setMimeType( value ) { this.mimeType = value; return this; } } export { FileLoader };
JavaScript
0
@@ -1558,24 +1558,150 @@ );%0A%0A%09%09%09%09%09%7D%0A%0A +%09%09%09%09%09if ( typeof ReadableStream === 'undefined' %7C%7C response.body.getReader === undefined ) %7B%0A%0A%09%09%09%09%09%09return response;%0A%0A%09%09%09%09%09%7D%0A%0A %09%09%09%09%09const c @@ -1723,24 +1723,24 @@ ing%5B url %5D;%0A - %09%09%09%09%09const r @@ -2063,22 +2063,30 @@ ss%0A%09%09%09%09%09 -return +const stream = new Rea @@ -2748,24 +2748,61 @@ %0A%09%09%09%09%09%7D );%0A%0A +%09%09%09%09%09return new Response( stream );%0A%0A %09%09%09%09%7D else %7B @@ -2941,65 +2941,21 @@ en( -stream =%3E %7B%0A%0A%09%09%09%09const response = new Response( stream ); +response =%3E %7B %0A%0A%09%09
b5a4cc7f2f11eba10d0f4605594f11b76cd12afa
Remove https for daum
examples/tms-tiled/script.js
examples/tms-tiled/script.js
var crs = new L.Proj.CRS('EPSG:5181', '+proj=tmerc +lat_0=38 +lon_0=127 +k=1 +x_0=200000 +y_0=500000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs', { resolutions: [2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5, 0.25], origin: [-30000, -60000], bounds: L.bounds([-30000, -60000], [494288, 464288]) }), map = L.map('map', { crs: crs, continuousWorld: true, worldCopyJump: false, }); new L.TileLayer('https://i{s}.maps.daum-img.net/map/image/G03/i/1.20/L{z}/{y}/{x}.png', { maxZoom: 14, minZoom: 0, zoomReverse: true, subdomains: '0123', continuousWorld: true, attribution: 'ⓒ Daum', tms: true }).addTo(map); //Gunsan Airport new L.marker([35.925937, 126.615810]).addTo(map); map.setView([36.0, 127.0], 0);
JavaScript
0
@@ -440,17 +440,16 @@ er('http -s ://i%7Bs%7D.
71e712dd24883286cb43e5f571a03604a60f06df
Fix alanning:roles code
security-rules.js
security-rules.js
/* * This file defines built-in restriction methods */ /* * No one */ Security.defineMethod("never", { fetch: [], transform: null, deny: function () { return true; } }); /* * Logged In */ Security.defineMethod("ifLoggedIn", { fetch: [], transform: null, deny: function (type, arg, userId) { return !userId; } }); /* * Specific User ID */ Security.defineMethod("ifHasUserId", { fetch: [], transform: null, deny: function (type, arg, userId) { return userId !== arg; } }); /* * Specific Roles */ /* * alanning:roles support */ if (Package && Package["alanning:roles"]) { var Roles = Package["alanning:roles"].Roles; Security.defineMethod("ifHasRole", { fetch: [], transform: null, deny: function (type, arg, userId) { if (!arg) { throw new Error('ifHasRole security rule method requires an argument'); } if (arg.role) { return !Roles.userIsInRole(userId, arg.role, arg.group); } else { return !Roles.userHasRole(userId, arg); } } }); } /* * nicolaslopezj:roles support * Note: doesn't support groups */ if (Package && Package["nicolaslopezj:roles"]) { var Roles = Package["nicolaslopezj:roles"].Roles; Security.defineMethod("ifHasRole", { fetch: [], transform: null, deny: function (type, arg, userId) { if (!arg) { throw new Error('ifHasRole security rule method requires an argument'); } return !Roles.userHasRole(userId, arg); } }); } /* * Specific Properties */ Security.defineMethod("onlyProps", { fetch: [], transform: null, deny: function (type, arg, userId, doc, fieldNames) { if (!_.isArray(arg)) { arg = [arg]; } fieldNames = fieldNames || _.keys(doc); return !_.every(fieldNames, function (fieldName) { return _.contains(arg, fieldName); }); } }); Security.defineMethod("exceptProps", { fetch: [], transform: null, deny: function (type, arg, userId, doc, fieldNames) { if (!_.isArray(arg)) { arg = [arg]; } fieldNames = fieldNames || _.keys(doc); return _.any(fieldNames, function (fieldName) { return _.contains(arg, fieldName); }); } });
JavaScript
0.001083
@@ -1009,35 +1009,36 @@ turn !Roles.user -Has +IsIn Role(userId, arg
2365d644e5db39b2942dfdd3b98a3ecab374dfa8
fix indentation and start using compact obj literal
src/main/LocationTrack.js
src/main/LocationTrack.js
/** * A track which shows the location of the base in the middle of the view. * @flow */ 'use strict'; var React = require('./react-shim'), _ = require('underscore'), d3 = require('d3'), shallowEquals = require('shallow-equals'), types = require('./react-types'), d3utils = require('./d3utils'); class LocationTrack extends React.Component { constructor(props: Object) { super(props); this.state = { labelSize: {height: 0, width: 0} }; } getScale() { return d3utils.getTrackScale(this.props.range, this.props.width); } render(): any { return <div ref='container'></div>; } componentDidMount() { var div = this.getDOMNode(), svg = d3.select(div).append('svg'); svg.append('line').attr('class', 'location-hline'); svg.append('line').attr('class', 'location-vline'); var label = svg.append('text').attr('class', 'location-label'); var {height, width} = label.text("0").node().getBBox(); // Save the size information for precise calculation this.setState({ labelSize: {height: height, width: width} }); this.updateVisualization(); } componentDidUpdate(prevProps: any, prevState: any) { this.updateVisualization(); } getDOMNode(): any { return this.refs.container.getDOMNode(); } updateVisualization() { var div = this.getDOMNode(), range = this.props.range, width = this.props.width, height = this.props.height, labelSize = this.state.labelSize, svg = d3.select(div).select('svg'); svg.attr('width', width).attr('height', height); var scale = this.getScale(); var midPoint = (range.stop + range.start) / 2; var midX = width / 2, midY = height / 2; var midLabelFormat = d3.format(',d'); var midLabel = svg.select('.location-label'); var labelHeight = labelSize.height; var labelPadding = 10; midLabel .attr('x', midX + labelPadding + (labelSize.width / 2)) .attr('y', midY + (labelHeight / 3)) .text(midLabelFormat(Math.floor(midPoint)) + ' bp'); var midLine = svg.select('.location-vline'); midLine .attr('x1', midX) .attr('y1', 0) .attr('x2', midX) .attr('y2', height); var hLine = svg.select('.location-hline'); hLine .attr('x1', midX) .attr('y1', midY) .attr('x2', midX + labelPadding) .attr('y2', midY); } } LocationTrack.propTypes = { range: types.GenomeRange.isRequired, onRangeChange: React.PropTypes.func.isRequired, }; LocationTrack.displayName = 'location'; module.exports = LocationTrack;
JavaScript
0.000003
@@ -1056,26 +1056,24 @@ e(%7B%0A - labelSize: %7B @@ -1082,24 +1082,9 @@ ight -: height, width: +, wid
eb111efe859d7c48088e066aab4f435db170ac86
Use non-breaking space to separate emoji and reaction count.
src/webview/html/messageReactionAsHtml.js
src/webview/html/messageReactionAsHtml.js
/* @flow */ import type { AggregatedReaction, RealmEmojiState, RealmEmojiType } from '../../types'; import emojiMap from '../../emoji/emojiMap'; import template from './template'; const getRealmEmojiHtml = (realmEmoji: RealmEmojiType): string => template`<img class="realm-reaction" src="${realmEmoji.source_url}"/> `; export default ( messageId: number, reaction: AggregatedReaction, realmEmoji: RealmEmojiState, ): string => template`<span onClick="" class="reaction${reaction.selfReacted ? ' self-voted' : ''}" data-name="${reaction.name}" data-code="${reaction.code}" data-type="${reaction.type}">$!${ realmEmoji[reaction.name] ? getRealmEmojiHtml(realmEmoji[reaction.name]) : emojiMap[reaction.name] } ${reaction.count} </span>`;
JavaScript
0.000001
@@ -755,17 +755,22 @@ ame%5D%0A %7D - +&nbsp; $%7Breacti
5d41ef7d0f37e0ea242467546ee41c602151d287
update compiled coffeescript
labs/architecture-examples/serenadejs/js/app.js
labs/architecture-examples/serenadejs/js/app.js
// Generated by CoffeeScript 1.6.2 (function() { var App, AppController, Todo, TodoController, app, router, _ref, _ref1, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Todo = (function(_super) { __extends(Todo, _super); function Todo() { _ref = Todo.__super__.constructor.apply(this, arguments); return _ref; } Todo.belongsTo('app', { inverseOf: 'all', as: function() { return App; } }); Todo.property('title', { serialize: true }); Todo.property('completed', { serialize: true }); Todo.property('incomplete', { get: function() { return !this.completed; } }); Todo.property('edit'); Todo.prototype.remove = function() { return this.app.all["delete"](this); }; return Todo; })(Serenade.Model); App = (function(_super) { __extends(App, _super); function App() { _ref1 = App.__super__.constructor.apply(this, arguments); return _ref1; } App.hasMany('all', { inverseOf: 'app', serialize: true, as: function() { return Todo; } }); App.selection('active', { from: 'all', filter: 'incomplete' }); App.selection('completed', { from: 'all', filter: 'completed' }); App.property('label', { get: function() { if (this.activeCount === 1) { return 'item left'; } else { return 'items left'; } } }); App.property('allCompleted', { get: function() { return this.activeCount === 0; }, set: function(value) { var todo, _i, _len, _ref2, _results; _ref2 = this.all; _results = []; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { todo = _ref2[_i]; _results.push(todo.completed = value); } return _results; } }); App.property('newTitle'); App.property('filter', { value: 'all' }); App.property('filtered', { get: function() { return this[this.filter]; } }); App.property('filterAll', { get: function() { return this.filter === 'all'; } }); App.property('filterActive', { get: function() { return this.filter === 'active'; } }); App.property('filterCompleted', { get: function() { return this.filter === 'completed'; } }); return App; })(Serenade.Model); AppController = (function() { function AppController(app) { this.app = app; } AppController.prototype.newTodo = function() { var title; title = this.app.newTitle.trim(); if (title) { this.app.all.push({ title: title }); } return this.app.newTitle = ''; }; AppController.prototype.clearCompleted = function() { return this.app.all = this.app.active; }; return AppController; })(); TodoController = (function() { function TodoController(todo) { this.todo = todo; } TodoController.prototype.removeTodo = function() { return this.todo.remove(); }; TodoController.prototype.edit = function() { this.todo.edit = true; return this.field.select(); }; TodoController.prototype.edited = function() { if (this.todo.title.trim()) { if (this.todo.edit) { this.todo.edit = false; } } else { this.todo.remove(); } return this.todo.app.changed.trigger(); }; TodoController.prototype.loadField = function(field) { this.field = field; }; return TodoController; })(); app = new App(JSON.parse(localStorage.getItem('todos-serenade'))); app.changed.bind(function() { return localStorage.setItem('todos-serenade', app); }); router = Router({ '/': function() { return app.filter = 'all'; }, '/active': function() { return app.filter = 'active'; }, '/completed': function() { return app.filter = 'completed'; } }); router.init(); Serenade.view('app', document.getElementById('app').innerHTML); Serenade.view('todo', document.getElementById('todo').innerHTML); Serenade.controller('app', AppController); Serenade.controller('todo', TodoController); document.body.insertBefore(Serenade.render('app', app), document.body.children[0]); }).call(this);
JavaScript
0
@@ -26,17 +26,17 @@ ipt 1.6. -2 +3 %0A(functi @@ -1970,17 +1970,16 @@ esults;%0A -%0A @@ -2957,17 +2957,16 @@ title;%0A -%0A ti @@ -3678,24 +3678,74 @@ e.trim()) %7B%0A + this.todo.title = this.todo.title.trim();%0A if (
7c6f36d6370442f75117cdd6699827ba4aacdb19
Use jsfiledownload for save.
devilry/apps/i18n/static/extjs_classes/i18n/TranslateGui.js
devilry/apps/i18n/static/extjs_classes/i18n/TranslateGui.js
Ext.define('devilry.i18n.TranslateGui', { extend: 'Ext.panel.Panel', alias: 'widget.i18n-translategui', requires: [ 'devilry.i18n.TranslateGuiModel', 'devilry.i18n.TranslateGuiGrid' ], initComponent: function() { this.store = Ext.create('Ext.data.Store', { model: 'devilry.i18n.TranslateGuiModel', autoSync: false, proxy: 'memory' }); Ext.apply(this, { layout: 'fit', items: [{ xtype: 'translategui-grid', store: this.store, listeners: { scope: this, itemdblclick: this._onDblClick } }], tbar: [{ xtype: 'button', iconCls: 'icon-save-16', text: 'Save', listeners: { scope: this, click: this._onSave } }] }); this.callParent(arguments); this._loadDefaults(); }, _onDblClick: function(view, record) { var editform = Ext.widget('form', { title: 'Translation', bodyPadding: 5, layout: 'fit', flex: 1, items: [{ xtype: 'textarea', name: 'translation' }], buttons: [{ text: 'Cancel', handler: function() { var form = this.up('form').getForm(); var translation = form.getValues().translation; if(translation === record.get('translation')) { this.up('window').close(); } else { Ext.MessageBox.confirm('Close without saving?', 'This will loose any changes you have made to the translation.', function(btn) { if(btn === 'yes') { this.up('window').close(); } }, this); } } }, { text: 'Save', handler: function() { var form = this.up('form').getForm(); form.updateRecord(record); this.up('window').close(); } }] }); editform.loadRecord(record); Ext.widget('window', { modal: true, title: 'Edit - ' + record.get('key'), width: 600, height: 400, layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'panel', title: 'Default value', bodyPadding: 5, flex: 1, html: record.get('defaultvalue') }, editform] }).show(); }, _loadDefaults: function() { Ext.Ajax.request({ url: Ext.String.format('{0}/i18n/messages.json', DevilrySettings.DEVILRY_STATIC_URL), scope: this, success: this._onLoadDefaults }); }, _onLoadDefaults: function(response) { var defaults = Ext.JSON.decode(response.responseText); Ext.Object.each(defaults, function(key, value) { this.store.add({ key: key, defaultvalue: value }); }, this); }, _onSave: function() { var result = this._exportJson(); console.log(result); }, _exportJson: function() { var result = new Object(); Ext.each(this.store.data.items, function(record, index) { var translation = Ext.String.trim(record.get('translation')); if(translation) { var key = record.get('key'); result[key] = translation; } }, this); return Ext.JSON.encode(result); } });
JavaScript
0
@@ -202,16 +202,65 @@ GuiGrid' +,%0A 'devilry.jsfiledownload.JsFileDownload' %0A %5D,%0A @@ -3609,24 +3609,100 @@ og(result);%0A + devilry.jsfiledownload.JsFileDownload.saveas('trans.json', result);%0A %7D,%0A%0A
1b5ea8ff2a062acdb207f9b79befba84401ce54a
Add early return statement in when calling `res.err` in api handlers
server/app/api.js
server/app/api.js
import express from 'express'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import multer from 'multer'; import crypto from 'crypto'; import Program from './model/Program'; import Post from './model/Post'; import Broadcast from './model/Broadcast'; const {ObjectId} = mongoose.Types; const router = express.Router(); const jsonParser = bodyParser.json(); const IMAGE_UPLOAD_FOLDER = 'uploads/'; const upload = multer({ storage: multer.diskStorage({ destination: IMAGE_UPLOAD_FOLDER, filename(req, file, cb) { crypto.pseudoRandomBytes(10, (err, raw) => { const hex = raw.toString('hex'); const [name, ext] = file.originalname.split('.'); cb(err, err ? undefined : `${name}-${hex}.${ext}`); }); } }) }); router.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }) router.get('/program', async (req, res) => { const programs = await Program.find({}); res.json(programs); }); router.get('/program/:program_id', async (req, res) => { const program = await Program.findById(req.params.program_id); const posts = await Post.find({ program: program.id }); res.json({ program, posts: posts }); }); router.post('/program', jsonParser, (req, res) => { const program = new Program(req.body); program.save((err) => { if (err) res.send(err); res.json({message: 'Program added.', data: program}); }); }); router.put('/program/:program_id', jsonParser, async (req, res) => { const program = await Program.findById(req.params.program_id); program.update( req.body, (err, raw) => { if (err) res.send(err); res.json({message: 'Program updated.'}); }); }); router.get('/post', async (req, res) => { res.json(await Post.find({})); }); router.get('/post/:post_id', async (req, res) => { const post = await Post.findById(req.params.post_id); res.json(post); }); router.post('/post', jsonParser, (req, res) => { const post = new Post(req.body); post.save((err) => { if (err) res.send(err); res.json({message: 'Post added.', data: post}); }); }); router.put('/post/:post_id', jsonParser, async (req, res) => { const post = await Post.findById(req.params.post_id); post.update( req.body, (err, raw) => { if (err) res.send(err); res.json({message: 'Post updated.'}); }); }); router.get('/broadcast', async (req, res) => { try { res.json(await Broadcast.find({}).sort('-date')); } catch (e) { console.log("error"); } }); router.get('/broadcast/:broadcast_id', async (req, res) => { const broadcast = await Broadcast.findById(req.params.broadcast_id); res.json(broadcast); }); router.post('/broadcast', jsonParser, (req, res) => { const broadcast = new Broadcast(req.body); broadcast.save((err) => { if (err) res.send(err); res.json({message: 'Broadcast added.', data: broadcast}); }); }); router.put('/broadcast/:broadcast_id', jsonParser, async (req, res) => { const broadcast = await Broadcast.findById(req.params.broadcast_id); broadcast.update( req.body, (err, raw) => { if (err) res.send(err); res.json({message: 'Broadcast updated.'}); }); }); router.post('/image', upload.single('attachment[file]'), (req, res) => { res.json({ file: { url: req.file.path } }); }); export default router;
JavaScript
0.000001
@@ -1457,32 +1457,39 @@ if (err)%0A +return res.send(err);%0A @@ -1479,32 +1479,32 @@ res.send(err);%0A - res.json(%7Bme @@ -1749,32 +1749,39 @@ if (err)%0A +return res.send(err);%0A @@ -2163,32 +2163,39 @@ if (err)%0A +return res.send(err);%0A @@ -2431,32 +2431,39 @@ if (err)%0A +return res.send(err);%0A @@ -2975,32 +2975,39 @@ if (err)%0A +return res.send(err);%0A @@ -3285,22 +3285,29 @@ f (err)%0A - +return res.send
b277a963f0d90747cc45080ca84bfe2cde32ac9a
eslint fail
components/_util/__tests__/easings.test.js
components/_util/__tests__/easings.test.js
import { easeInOutCubic } from '../easings'; describe('Test easings', () => { it('easeInOutCubic return value', () => { const nums = []; for (let index = 0; index < 5; index++) { nums.push(easeInOutCubic(index, 1, 5, 4)); } expect(nums).toEqual([1, 1.25, 3, 4.75, 5]); }); });
JavaScript
0.998854
@@ -137,16 +137,60 @@ s = %5B%5D;%0A + // eslint-disable-next-line no-plusplus%0A for
6000059a64cade7a7e81f99cb719a7a0eaec5f24
Update build version
extension/build-variables.js
extension/build-variables.js
module.exports = { storeURL: { chrome: 'https://chrome.google.com/webstore/detail/gene-info/jggendahejbhkghnachhlomkkheomchp', edge: 'https://microsoftedge.microsoft.com/addons/detail/gene-info/hegihjieeonojcnhfmhmedmoobggamka', firefox: 'https://addons.mozilla.org/firefox/addon/gene-info/', safari: 'https://apps.apple.com/us/app/gix-for-safari/id1543199063', }, version: '1.7.0', };
JavaScript
0
@@ -394,15 +394,15 @@ n: '1.7. -0 +1 ',%0A%7D;%0A
05c7587ca93f4d04982900afc60ac71ec70e7114
Move story based tests order
components/story-based-tests.js
components/story-based-tests.js
/* * STORY-BASED SNAPSHOT TESTING * * Please add stories below to use Storybook Stories (http://localhost:9001) * as the basis for DOM and image snapshots to allow markup and visual regression * testing. All new components should be added below to enable DOM and image * snapshots. With enough Storybook story examples, these two methods should be * significant to fully test components with the exception of callback testing. * Pleaes test callback props with the Mocha framework (http://localhost:8001). * `tests/story-based-tests.snapshot-test.js` looks at this file and uses the * following stories to create snapshots. * * This library is transitioning to story-based testing, but not all components * are able to be tested without a DOM. This file should eventually go away and * `storybook-stories.js` used for the basis of snapshot creation. */ export Blank from '../tests/initial-blank-stories'; export Accordion from '../components/accordion/__docs__/storybook-stories'; export Alert from '../components/alert/__docs__/storybook-stories'; export Avatar from '../components/avatar/__docs__/storybook-stories'; export BrandBand from '../components/brand-band/__docs__/storybook-stories'; export Breadcrumb from '../components/breadcrumb/__docs__/storybook-stories'; export Button from '../components/button/__docs__/storybook-stories'; export ButtonGroup from '../components/button-group/__docs__/storybook-stories'; export ButtonStateful from '../components/button-stateful/__docs__/storybook-stories'; export Card from '../components/card/__docs__/storybook-stories'; export Checkbox from '../components/checkbox/__docs__/storybook-stories'; // export Combobox from '../components/combobox/__docs__/storybook-stories'; // export Filter from '../components/filter/__docs__/storybook-stories'; export DataTable from '../components/data-table/__docs__/storybook-stories'; // export Dropdown from '../components/menu-dropdown/__docs__/storybook-stories'; export Input from '../components/input/__docs__/storybook-stories'; // export Textarea from '../components/textarea/__docs__/storybook-stories'; // export Search from '../components/input/__docs__/search/storybook-stories'; export Icon from '../components/icon/__docs__/storybook-stories'; export Illustration from '../components/illustration/__docs__/storybook-stories'; // export Lookup from '../components/lookup/__docs__/storybook-stories'; // export MediaObject from '../components/media-object/__docs__/storybook-stories'; // export PageHeader from '../components/page-header/__docs__/storybook-stories'; // export Pill from '../components/pill/__docs__/storybook-stories'; // export ProgressRing from '../components/progress-ring/__docs__/storybook-stories'; // export RadioGroup from '../components/radio-group/__docs__/storybook-stories'; // export RadioButtonGroup from '../components/radio-button-group/__docs__/storybook-stories'; // export Slider from '../components/slider/__docs__/storybook-stories'; // export SplitView from '../components/split-view/__docs__/storybook-stories'; // export Tabs from '../components/tabs/__docs__/storybook-stories'; // export Toast from '../components/toast/__docs__/storybook-stories'; // export Tooltip from '../components/tooltip/__docs__/storybook-stories'; export Tree from '../components/tree/__docs__/storybook-stories'; // export VerticalNavigation from '../components/vertical-navigation/__docs__/storybook-stories'; /* * The following components are not compatible Jest testing because * need a real DOM. These components should be updated to allow testing * with Jest. This is typically done by gaurding references to `document`. */ // export AppLauncher from '../components/app-launcher/__docs__/storybook-stories'; // export GlobalNavigationBar from '../components/global-navigation-bar/__docs__/storybook-stories'; // export DatePicker from '../components/date-picker/__docs__/storybook-stories'; // export IconSettings from '../components/icon-settings/__docs__/storybook-stories'; export GlobalHeader from '../components/global-header/__docs__/storybook-stories'; // export Modal from '../components/modal/__docs__/storybook-stories'; // export Panel from '../components/panel/__docs__/storybook-stories'; // export Popover from '../components/popover/__docs__/storybook-stories'; export ProgressIndicator from '../components/progress-indicator/__docs__/storybook-stories'; // export Spinner from '../components/spinner/__docs__/storybook-stories'; // export TimePicker from '../components/time-picker/__docs__/storybook-stories'; // DEPRECATED // export Notification from '../components/notification/__docs__/storybook-stories'; // export Picklist from '../components/menu-picklist/__docs__/storybook-stories';
JavaScript
0
@@ -1981,87 +1981,20 @@ ort -Input from '../components/input/__docs__/storybook-stories';%0A// export Textarea +GlobalHeader fro @@ -2014,16 +2014,21 @@ nts/ -textarea +global-header /__d @@ -2057,24 +2057,20 @@ s';%0A -// export -Search +Input fro @@ -2105,15 +2105,8 @@ s__/ -search/ stor @@ -2273,81 +2273,8 @@ s';%0A -// export Lookup from '../components/lookup/__docs__/storybook-stories';%0A // e @@ -2496,32 +2496,125 @@ ybook-stories';%0A +export ProgressIndicator from '../components/progress-indicator/__docs__/storybook-stories';%0A // export Progre @@ -2852,32 +2852,111 @@ ybook-stories';%0A +// export Search from '../components/input/__docs__/search/storybook-stories';%0A // export Slider @@ -3153,32 +3153,109 @@ ybook-stories';%0A +// export Textarea from '../components/textarea/__docs__/storybook-stories';%0A // export Toast @@ -4129,91 +4129,8 @@ s';%0A -export GlobalHeader from '../components/global-header/__docs__/storybook-stories';%0A // e @@ -4346,101 +4346,8 @@ s';%0A -export ProgressIndicator from '../components/progress-indicator/__docs__/storybook-stories';%0A // e @@ -4500,16 +4500,16 @@ ries';%0A%0A - // DEPRE @@ -4514,16 +4514,89 @@ RECATED%0A +// export Lookup from '../components/lookup/__docs__/storybook-stories';%0A // expor
3d48d7932136defa459766940ebe3cd153a8cf98
change interface selection to device
applications/luci-app-watchcat/htdocs/luci-static/resources/view/watchcat.js
applications/luci-app-watchcat/htdocs/luci-static/resources/view/watchcat.js
'use strict'; 'require view'; 'require form'; 'require tools.widgets as widgets'; return view.extend({ render: function () { var m, s, o; m = new form.Map('watchcat', _('Watchcat'), _("Here you can set up several checks and actions to take in the event that a host becomes unreachable. \ Click the <b>Add</b> button at the bottom to set up more than one action.")); s = m.section(form.TypedSection, 'watchcat', _('Watchcat'), _('These rules will govern how this device reacts to network events.')); s.anonymous = true; s.addremove = true; s.tab('general', _('General Settings')); o = s.taboption('general', form.ListValue, 'mode', _('Mode'), _("Ping Reboot: Reboot this device if a ping to a specified host fails for a specified duration of time. <br /> \ Periodic Reboot: Reboot this device after a specified interval of time. <br /> \ Restart Interface: Restart a network interface if a ping to a specified host fails for a specified duration of time.")); o.value('ping_reboot', _('Ping Reboot')); o.value('periodic_reboot', _('Periodic Reboot')); o.value('restart_iface', _('Restart Interface')); o = s.taboption('general', form.Value, 'period', _('Period'), _("In Periodic Reboot mode, it defines how often to reboot. <br /> \ In Ping Reboot mode, it defines the longest period of \ time without a reply from the Host To Check before a reboot is engaged. <br /> \ In Network Restart mode, it defines the longest period of \ time without a reply from the Host to Check before the interface is restarted. \ <br /><br />The default unit is seconds, without a suffix, but you can use the \ suffix <b>m</b> for minutes, <b>h</b> for hours or <b>d</b> \ for days. <br /><br />Examples:<ul><li>10 seconds would be: <b>10</b> or <b>10s</b></li><li>5 minutes would be: <b>5m</b></li><li> \ 1 hour would be: <b>1h</b></li><li>1 week would be: <b>7d</b></li><ul>")); o.default = '6h'; o = s.taboption('general', form.Value, 'pinghosts', _('Host To Check'), _(`IPv4 address or hostname to ping.`)); o.datatype = 'host(1)'; o.default = '8.8.8.8'; o.depends({ mode: "ping_reboot" }); o.depends({ mode: "restart_iface" }); o = s.taboption('general', form.Value, 'pingperiod', _('Check Interval'), _("How often to ping the host specified above. \ <br /><br />The default unit is seconds, without a suffix, but you can use the suffix <b>m</b> for minutes, <b>h</b> for hours or <b>d</b> for days. <br /><br /> \ Examples:<ul><li>10 seconds would be: <b>10</b> or <b>10s</b></li><li>5 minutes would be: <b>5m</b></li><li>1 hour would be: <b>1h</b></li><li>1 week would be: <b>7d</b></li><ul>")); o.default = '30s'; o.depends({ mode: "ping_reboot" }); o.depends({ mode: "restart_iface" }); o = s.taboption('general', form.ListValue, 'pingsize', _('Ping Packet Size')); o.value('small', _('Small: 1 byte')); o.value('windows', _('Windows: 32 bytes')); o.value('standard', _('Standard: 56 bytes')); o.value('big', _('Big: 248 bytes')); o.value('huge', _('Huge: 1492 bytes')); o.value('jumbo', _('Jumbo: 9000 bytes')); o.default = 'standard'; o.depends({ mode: 'ping_reboot' }); o.depends({ mode: 'restart_iface' }); o = s.taboption('general', form.Value, 'forcedelay', _('Force Reboot Delay'), _("Applies to Ping Reboot and Periodic Reboot modes</i> <br /> When rebooting the router, the service will trigger a soft reboot. \ Entering a non-zero value here will trigger a delayed hard reboot if the soft reboot were to fail. \ Enter the number of seconds to wait for the soft reboot to fail or use 0 to disable the forced reboot delay.")); o.default = '1m'; o.depends({ mode: 'ping_reboot' }); o.depends({ mode: 'periodic_reboot' }); o = s.taboption('general', widgets.NetworkSelect, 'interface', _('Interface'), _('Interface to monitor and/or restart'), _('<i>Applies to Ping Reboot and Restart Interface modes</i> <br /> Specify the interface to monitor and restart if a ping over it fails.')); o.depends({ mode: 'ping_reboot' }); o.depends({ mode: 'restart_iface' }); o = s.taboption('general', widgets.NetworkSelect, 'mmifacename', _('Name of ModemManager Interface'), _("Applies to Ping Reboot and Restart Interface modes</i> <br /> If using ModemManager, \ you can have Watchcat restart your ModemManger interface by specifying its name.")); o.depends({ mode: 'restart_iface' }); o.optional = true; o = s.taboption('general', form.Flag, 'unlockbands', _('Unlock Modem Bands'), _('If using ModemManager, then before restarting the interface, set the modem to be allowed to use any band.')); o.default = '0'; o.depends({ mode: 'restart_iface' }); return m.render(); } });
JavaScript
0
@@ -3820,39 +3820,38 @@ neral', widgets. -Network +Device Select, 'interfa
d8b713769a664033185db57a3852c91a156d35f5
switch to shallow merge
Utils/computeProps.js
Utils/computeProps.js
'use_strict'; import _ from 'lodash'; import ReactNativePropRegistry from 'react/lib/ReactNativePropRegistry'; // For compatibility with RN 0.25 // import ReactNativePropRegistry from "react-native/Libraries/ReactNative/ReactNativePropRegistry"; module.exports = function(incomingProps, defaultProps) { // External props has a higher precedence var computedProps = {}; incomingProps = _.clone(incomingProps); delete incomingProps.children; var incomingPropsStyle = incomingProps.style; delete incomingProps.style; // console.log(defaultProps, incomingProps); if(incomingProps) { try { _.merge(computedProps, defaultProps, incomingProps); } catch (exception) { console.log('Warning: Call stack size exceeded when merging props, falling back to shallow merge.'); _.assign(computedProps, defaultProps, incomingProps); } } else computedProps = defaultProps; // Pass the merged Style Object instead if(incomingPropsStyle) { var computedPropsStyle = {}; computedProps.style = {}; if (Array.isArray(incomingPropsStyle)) { _.forEach(incomingPropsStyle, (style)=>{ if(typeof style == 'number') { _.merge(computedPropsStyle, ReactNativePropRegistry.getByID(style)); } else { _.merge(computedPropsStyle, style); } }) } else { if(typeof incomingPropsStyle == 'number') { computedPropsStyle = ReactNativePropRegistry.getByID(incomingPropsStyle); } else { computedPropsStyle = incomingPropsStyle; } } _.merge(computedProps.style, defaultProps.style, computedPropsStyle); } // console.log("computedProps ", computedProps); return computedProps; }
JavaScript
0.000002
@@ -611,236 +611,8 @@ ) %7B%0A - try %7B%0A _.merge(computedProps, defaultProps, incomingProps);%0A %7D catch (exception) %7B%0A console.log('Warning: Call stack size exceeded when merging props, falling back to shallow merge.');%0A @@ -667,26 +667,16 @@ Props);%0A - %7D%0A %7D el
348ea27dd4a418b60315f3f8d14bb09f4891862b
add note about click handlers
solution/js/ttt-widget.js
solution/js/ttt-widget.js
(function () { if (typeof TTT === "undefined") { window.TTT = {}; } var Widget = TTT.Widget = function (game, $el) { this.game = game; this.$el = $el; }; Widget.prototype.bindEvents = function () { var widget = this; // install a handler on the `li` elements inside the board. this.$el.on('click', 'li', function (event) { var $square = $(event.currentTarget); widget.makeMove($square); }); }; Widget.prototype.makeMove = function ($square) { var pos = $square.data("pos"); var currentPlayer = this.game.currentPlayer; try { this.game.playMove(pos); } catch (e) { alert('Invalid move! Try again.'); return; } $square.addClass(currentPlayer); if (this.game.isOver()) { this.$el.off('click'); var winner = this.game.winner(); if (winner) { this.$el.addClass('winner-' + winner); } else { this.$el.addClass('over'); } } }; Widget.prototype.play = function () { this.setupBoard(); this.bindEvents(); }; Widget.prototype.setupBoard = function () { for (var rowIdx = 0; rowIdx < 3; rowIdx++) { for (var colIdx = 0; colIdx < 3; colIdx++) { var $li = $("<li>"); $li.data("pos", [rowIdx, colIdx]); this.$el.append($li); } } }; })();
JavaScript
0
@@ -764,24 +764,57 @@ isOver()) %7B%0A + // cleanup click handlers.%0A this.$