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
adda1e261b87633559d9165e13dcafbd6f709ac7
correct error with submission hooks.
src/services/submissions/hooks/index.js
src/services/submissions/hooks/index.js
'use strict'; const globalHooks = require('../../../hooks'); const hooks = require('feathers-hooks'); const auth = require('feathers-authentication').hooks; exports.before = { all: [ // auth.verifyToken(), // auth.populateUser(), // auth.restrictToAuthenticated() ], find: [], get: [], create: [], update: [], patch: [], remove: [] }; exports.after = { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] };
JavaScript
0
@@ -179,27 +179,24 @@ all: %5B%0A - // auth.verify @@ -203,27 +203,24 @@ Token(),%0A - // auth.popula @@ -236,11 +236,8 @@ %0A - // aut
fe899e38f4f19ba914f568af0232d52fbfda3003
add S3 copy object example
javascriptv3/example_code/s3/src/s3_copyobject.js
javascriptv3/example_code/s3/src/s3_copyobject.js
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html. Purpose: s3_copyobject.js demonstrates how to copy an object from one Amazon Simple Storage Solution (Amazon S3) bucket to another. Inputs (replace in code): - BUCKET_NAME Running the code: node s3_copyobject.js */ // snippet-start:[s3.JavaScript.buckets.copyObjectV3] // Get service clients module and commands using ES6 syntax. import { CopyObjectCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Set the bucket parameters. export const params = { Bucket: "brmurbucket", CopySource: "/apigatewaystack-mybucket160f8132-1dysc21xykp8d/index.js", Key: "index.js" }; // Create the Amazon S3 bucket. export const run = async () => { try { const data = await s3Client.send(new CopyObjectCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run(); // snippet-end:[s3.JavaScript.buckets.copyObjectV3] // For unit tests only. // module.exports ={run, bucketParams};
JavaScript
0
@@ -586,13 +586,60 @@ :%0A- -BUCKE +DESTINATION_BUCKET_NAME%0A- SOURCE_BUCKET_NAME%0A- OBJEC T_NA @@ -976,95 +976,82 @@ t: %22 -brmurbucket%22,%0A CopySource: %22/apigatewaystack-mybucket160f8132-1dysc21xykp8d/index.js +DESTINATION_BUCKET_NAME%22,%0A CopySource: %22/SOURCE_BUCKET_NAME/OBJECT_NAME %22,%0A @@ -1063,16 +1063,19 @@ y: %22 -index.js +OBJECT_NAME %22%0A%7D;
b805b78b03d58efb353c725390cef10562652021
Update checks
Source/Core/FeatureDetection.js
Source/Core/FeatureDetection.js
/*global define*/ define([ './defaultValue', './defined', './Fullscreen' ], function( defaultValue, defined, Fullscreen) { 'use strict'; var theNavigator; if (typeof navigator !== 'undefined') { theNavigator = navigator; } else { theNavigator = {}; } function extractVersion(versionString) { var parts = versionString.split('.'); for (var i = 0, len = parts.length; i < len; ++i) { parts[i] = parseInt(parts[i], 10); } return parts; } var isChromeResult; var chromeVersionResult; function isChrome() { if (!defined(isChromeResult)) { isChromeResult = false; if (/Google Inc/.test(theNavigator.vendor)) { var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent); if (fields !== null) { isChromeResult = true; chromeVersionResult = extractVersion(fields[1]); } } } return isChromeResult; } function chromeVersion() { return isChrome() && chromeVersionResult; } var isSafariResult; var safariVersionResult; function isSafari() { if (!defined(isSafariResult)) { isSafariResult = false; // Chrome contains Safari in the user agent too if (!isChrome() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) { var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent); if (fields !== null) { isSafariResult = true; safariVersionResult = extractVersion(fields[1]); } } } return isSafariResult; } function safariVersion() { return isSafari() && safariVersionResult; } var isWebkitResult; var webkitVersionResult; function isWebkit() { if (!defined(isWebkitResult)) { isWebkitResult = false; var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent); if (fields !== null) { isWebkitResult = true; webkitVersionResult = extractVersion(fields[1]); webkitVersionResult.isNightly = !!fields[2]; } } return isWebkitResult; } function webkitVersion() { return isWebkit() && webkitVersionResult; } var isInternetExplorerResult; var internetExplorerVersionResult; function isInternetExplorer() { if (!defined(isInternetExplorerResult)) { isInternetExplorerResult = false; var fields; if (theNavigator.appName === 'Microsoft Internet Explorer') { fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent); if (fields !== null) { isInternetExplorerResult = true; internetExplorerVersionResult = extractVersion(fields[1]); } } else if (theNavigator.appName === 'Netscape') { fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent); if (fields !== null) { isInternetExplorerResult = true; internetExplorerVersionResult = extractVersion(fields[1]); } } } return isInternetExplorerResult; } function internetExplorerVersion() { return isInternetExplorer() && internetExplorerVersionResult; } var isEdgeResult; var edgeVersionResult; function isEdge() { if (!defined(isEdgeResult)) { isEdgeResult = false; var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent); if (fields !== null) { isEdgeResult = true; edgeVersionResult = extractVersion(fields[1]); } } return isEdgeResult; } function edgeVersion() { return isEdge() && edgeVersionResult; } var isFirefoxResult; var firefoxVersionResult; function isFirefox() { if (!defined(isFirefoxResult)) { isFirefoxResult = false; var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent); if (fields !== null) { isFirefoxResult = true; firefoxVersionResult = extractVersion(fields[1]); } } return isFirefoxResult; } var isWindowsResult; function isWindows() { if (!defined(isWindowsResult)) { isWindowsResult = /Windows/i.test(theNavigator.appVersion); } return isWindowsResult; } function firefoxVersion() { return isFirefox() && firefoxVersionResult; } var hasPointerEvents; function supportsPointerEvents() { if (!defined(hasPointerEvents)) { //While navigator.pointerEnabled is deprecated in the W3C specification //we still need to use it if it exists in order to support browsers //that rely on it, such as the Windows WebBrowser control which defines //PointerEvent but sets navigator.pointerEnabled to false. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled); } return hasPointerEvents; } var imageRenderingValueResult; var supportsImageRenderingPixelatedResult; function supportsImageRenderingPixelated() { if (!defined(supportsImageRenderingPixelatedResult)) { var canvas = document.createElement('canvas'); canvas.setAttribute('style', 'image-rendering: -moz-crisp-edges;' + 'image-rendering: pixelated;'); //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers. var tmp = canvas.style.imageRendering; supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== ''; if (supportsImageRenderingPixelatedResult) { imageRenderingValueResult = tmp; } } return supportsImageRenderingPixelatedResult; } function imageRenderingValue() { return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined; } /** * A set of functions to detect whether the current browser supports * various features. * * @exports FeatureDetection */ var FeatureDetection = { isChrome : isChrome, chromeVersion : chromeVersion, isSafari : isSafari, safariVersion : safariVersion, isWebkit : isWebkit, webkitVersion : webkitVersion, isInternetExplorer : isInternetExplorer, internetExplorerVersion : internetExplorerVersion, isEdge : isEdge, edgeVersion : edgeVersion, isFirefox : isFirefox, firefoxVersion : firefoxVersion, isWindows : isWindows, hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3), supportsPointerEvents : supportsPointerEvents, supportsImageRenderingPixelated: supportsImageRenderingPixelated, imageRenderingValue: imageRenderingValue }; /** * Detects whether the current browser supports the full screen standard. * * @returns {Boolean} true if the browser supports the full screen standard, false if not. * * @see Fullscreen * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification} */ FeatureDetection.supportsFullscreen = function() { return Fullscreen.supportsFullscreen(); }; /** * Detects whether the current browser supports typed arrays. * * @returns {Boolean} true if the browser supports typed arrays, false if not. * * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification} */ FeatureDetection.supportsTypedArrays = function() { return typeof ArrayBuffer !== 'undefined'; }; /** * Detects whether the current browser supports Web Workers. * * @returns {Boolean} true if the browsers supports Web Workers, false if not. * * @see {@link http://www.w3.org/TR/workers/} */ FeatureDetection.supportsWebWorkers = function() { return typeof Worker !== 'undefined'; }; return FeatureDetection; });
JavaScript
0.000001
@@ -742,49 +742,78 @@ -if (/Google Inc/.test(theNavigator.vendor +// Edge contains Chrome in the user agent too%0A if (!isEdge( )) %7B @@ -1394,24 +1394,32 @@ Chrome +and Edge contain -s Safari @@ -1470,16 +1470,29 @@ ome() && + !isEdge() && (/ Safa
9daee0f6354a660f6ec6e33aeb9669a11b8a7c89
add ts and tsx to extension config
.storybook/main.js
.storybook/main.js
const path = require("path"); const glob = require("glob"); const projectRoot = path.resolve(__dirname, "../"); const ignoreTests = process.env.IGNORE_TESTS === "true"; const isChromatic = !ignoreTests; const getStories = () => glob.sync(`${projectRoot}/src/**/*.stories.@(js|mdx)`, { ...(ignoreTests && { ignore: `${projectRoot}/src/**/*-test.stories.@(js|mdx)`, }), }); module.exports = { stories: (list) => [ ...list, "./welcome-page/welcome.stories.js", "../docs/*.stories.mdx", ...getStories(), ], addons: [ "@storybook/addon-actions", "@storybook/addon-docs", "@storybook/addon-controls", "@storybook/addon-viewport", "@storybook/addon-a11y", "@storybook/addon-google-analytics", "@storybook/addon-links", "@storybook/addon-toolbars", "./theme-selector/register", ], webpackFinal: async (config, { configType }) => { config.resolve = { alias: { helpers: path.resolve(__dirname, "__helpers__/"), }, extensions: [".js"], }; // Workaround to stop hashes being added to font filenames, so we can pre-load them config.module.rules.find((rule) => rule.test.toString().includes("woff2") ).options.name = "static/media/[name].[ext]"; return config; }, ...(isChromatic && { previewHead: (head) => ` ${head} <meta name="robots" content="noindex"> `, managerHead: (head) => ` ${head} <meta name="robots" content="noindex"> `, }), };
JavaScript
0
@@ -1027,16 +1027,31 @@ : %5B%22.js%22 +, %22.tsx%22, %22.ts%22 %5D,%0A %7D
678c011c7125fb12e22d86678cc0d05794db8135
Add default response to search
controllers/people/index.js
controllers/people/index.js
'use strict'; var _ = require('underscore'), ccb = require('../../lib/ccb'), peopleModel = require('../../models/people'), Promise = require('bluebird'); module.exports = function (router) { router.get('/', function (req, res) { if(process.env.NODE_ENV === 'production' && req.query.token !== process.env.slack_token) { //make this an express middleware res.send('An Error Occurred: invalid token'); } if(!req.query.text) { res.send('An Error Occurred: invalid input'); } var obj = {}, names = decodeURI(req.query.text).split(' '), individuals = []; obj.first_name = names[0]; obj.last_name = names[1]; peopleModel.search({ first_name: names[0], last_name: names[1] }).then(function(first) { individuals = individuals.concat(ccb.parseIndividuals(first)); if (individuals.length === 0) { return peopleModel.search({ last_name: names[0] //if no first names found, search the name as a last name }); } else { return Promise.resolve(null); } }).then(function(last) { individuals = individuals.concat(ccb.parseIndividuals(last)); console.log(ccb.parseIndividuals(last)); var output = _.map(individuals, function(individual) { return ccb.individualToString(individual); }).join(', '); res.send(output); }) }); };
JavaScript
0.000001
@@ -39,20 +39,17 @@ core'),%0A - +%09 ccb = re @@ -72,20 +72,17 @@ /ccb'),%0A - +%09 peopleMo @@ -119,20 +119,17 @@ ople'),%0A - +%09 Promise @@ -189,20 +189,17 @@ uter) %7B%0A - +%09 router.g @@ -228,24 +228,18 @@ res) %7B%0A - +%09%09 if(proce @@ -355,28 +355,19 @@ dleware%0A - +%09%09%09 res.send @@ -404,35 +404,23 @@ oken');%0A - %7D%0A%0A +%09%09%7D%0A%0A%09%09 if(!req. @@ -433,28 +433,19 @@ text) %7B%0A - +%09%09%09 res.send @@ -486,27 +486,15 @@ ');%0A - %7D%0A%0A +%09%09%7D%0A%0A%09%09 var @@ -503,28 +503,19 @@ j = %7B%7D,%0A - +%09%09%09 names = @@ -552,28 +552,19 @@ t(' '),%0A - +%09%09%09 individu @@ -574,24 +574,18 @@ = %5B%5D;%0A%0A - +%09%09 obj.firs @@ -603,24 +603,18 @@ mes%5B0%5D;%0A - +%09%09 obj.last @@ -632,24 +632,18 @@ es%5B1%5D;%0A%0A - +%09%09 peopleMo @@ -655,28 +655,19 @@ earch(%7B%0A - +%09%09%09 first_na @@ -680,28 +680,19 @@ mes%5B0%5D,%0A - +%09%09%09 last_nam @@ -703,24 +703,18 @@ ames%5B1%5D%0A - +%09%09 %7D).then( @@ -727,36 +727,27 @@ on(first) %7B%0A - +%09%09%09 individuals @@ -797,28 +797,19 @@ irst));%0A - +%09%09%09 if (indi @@ -832,32 +832,20 @@ == 0) %7B%0A - +%09%09%09%09 return p @@ -868,28 +868,13 @@ h(%7B%0A - +%09%09%09%09%09 last @@ -951,65 +951,32 @@ ame%0A - %7D);%0A %7D else %7B%0A +%09%09%09%09%7D);%0A%09%09%09%7D else %7B%0A%09%09%09%09 retu @@ -1005,30 +1005,15 @@ l);%0A - %7D%0A +%09%09%09%7D%0A%09%09 %7D).t @@ -1033,28 +1033,19 @@ last) %7B%0A - +%09%09%09 individu @@ -1102,73 +1102,11 @@ ));%0A - console.log(ccb.parseIndividuals(last));%0A +%09%09%09 var @@ -1160,24 +1160,12 @@ ) %7B%0A - +%09%09%09%09 retu @@ -1203,28 +1203,19 @@ idual);%0A - +%09%09%09 %7D).join( @@ -1225,20 +1225,11 @@ ');%0A - +%09%09%09 res. @@ -1243,26 +1243,56 @@ tput -);%0A %7D)%0A + %7C%7C %22Couldn't find anyone by that name%22);%0A%09%09%7D)%0A%09 %7D);%0A
dbdad7ffd14a30ccfe0553721ca7d46a9d257a6d
remove full browser width from web components wrapper
src/BookReaderComponent/BookReaderComponent.js
src/BookReaderComponent/BookReaderComponent.js
/** * BookReaderTemplate to load BookNavigator components */ import { LitElement, html, css } from 'lit-element'; import '../ItemNavigator/ItemNavigator.js' import '../BookNavigator/BookNavigator.js' export class BookReader extends LitElement { static get properties() { return { base64Json: { type: String }, baseHost: { type: String }, }; } constructor() { super(); this.base64Json = ''; this.baseHost = 'https://archive.org'; } firstUpdated() { this.fetchData(); } /** * Fetch metadata response from public metadata API * convert response to base64 data * set base64 data to props */ async fetchData() { const ocaid = new URLSearchParams(location.search).get('ocaid'); const response = await fetch(`${this.baseHost}/metadata/${ocaid}`); const bookMetadata = await response.json(); const jsonBtoa = btoa(JSON.stringify(bookMetadata)); this.setBaseJSON(jsonBtoa); } /** * Set base64 data to prop * @param {string} value - base64 string format */ setBaseJSON(value) { this.base64Json = value; } render() { return html` <div class="ia-bookreader"> <item-navigator itemType="bookreader" basehost=${this.baseHost} item=${this.base64Json}> <div slot="bookreader"> <slot name="bookreader"></slot> </div> </item-navigator> </div> `; } static get styles() { return css` :host { display: block; --primaryBGColor: var(--black, #000); --secondaryBGColor: #222; --tertiaryBGColor: #333; --primaryTextColor: var(--white, #fff); --primaryCTAFill: #194880; --primaryCTABorder: #c5d1df; --secondaryCTAFill: #333; --secondaryCTABorder: #999; --primaryErrorCTAFill: #e51c26; --primaryErrorCTABorder: #f8c6c8; } .ia-bookreader { background-color: var(--primaryBGColor); position: relative; width: 100vw; height: auto; } item-navigator { display: block; width: 100%; color: var(--primaryTextColor); --menuButtonLabelDisplay: block; --menuWidth: 320px; --menuSliderBg: var(--secondaryBGColor); --activeButtonBg: var(--tertiaryBGColor); --animationTiming: 100ms; --iconFillColor: var(--primaryTextColor); --iconStrokeColor: var(--primaryTextColor); --menuSliderHeaderIconHeight: 2rem; --menuSliderHeaderIconWidth: 2rem; --iconWidth: 2.4rem; --iconHeight: 2.4rem; --shareLinkColor: var(--primaryTextColor); --shareIconBorder: var(--primaryTextColor); --shareIconBg: var(--secondaryBGColor); --activityIndicatorLoadingDotColor: var(--primaryTextColor); --activityIndicatorLoadingRingColor: var(--primaryTextColor); } `; } } window.customElements.define("ia-bookreader", BookReader);
JavaScript
0
@@ -2016,30 +2016,8 @@ ve;%0A - width: 100vw;%0A
0814008f10a5317bc7d60044d2e449134c19c740
use yarn publish
scripts/publish-to-npm.js
scripts/publish-to-npm.js
'use strict'; const yargs = require('yargs'); const execa = require('execa'); const util = require('util'); const glob = util.promisify(require('glob')); const fs = require('fs-extra'); const path = require('path'); const rootDir = process.cwd(); let argv = yargs .usage( '$0 [-t|--tag]' ) .command({ command: '*', builder: yargs => { return yargs .option('t', { alias: 'tag', describe: 'the npm dist-tag', default: 'latest', type: 'string', }); }, handler: async argv => { const packageJsonData = JSON.parse( await fs.readFile(path.join(rootDir, 'package.json')) ); const packageDirs = ( await Promise.all(packageJsonData.workspaces.map((item) => glob(item))) ).flat(); await Promise.all(packageDirs.map((item) => { const publishCmd = `npm publish --tag ${argv.tag}`; return execa(publishCmd, { stdio: 'inherit', cwd: path.join(rootDir, item) }); })) }, }) .help().argv;
JavaScript
0
@@ -850,19 +850,20 @@ hCmd = %60 -npm +yarn publish
978d2a42b5ff4d5edcf58e621030253d60d5c2b0
Fix host computation in Hacker News Answer Generator
src/answer_generators/hacker_news/generator.js
src/answer_generators/hacker_news/generator.js
/*jslint continue: true, devel: true, evil: true, indent: 2, nomen: true, plusplus: true, regexp: true, rhino: true, sloppy: true, sub: true, unparam: true, vars: true, white: true */ /*global _, HostAdapter, hostAdapter */ var ICON_URL = 'https://news.ycombinator.com/favicon.ico'; var BASE_RELEVANCE = 0.4; function hostForUrl(url) { var startIndex = url.indexOf('//') + 2; var endIndex = url.indexOf('/', startIndex); return url.substring(startIndex, endIndex); } function makeResponseHandler(q, context) { 'use strict'; return function (responseText, response) { 'use strict'; console.log('Got response'); if (response.statusCode !== 200) { console.error('Got bad status code ' + response.statusCode); return null; } var resultObject = JSON.parse(responseText); var hits = resultObject.hits; console.log('Got ' + hits.length + ' hits'); if (hits.length === 0) { return []; } var outputLinks = false; if (!context.isSuggestionQuery || (context.settings.outputLinks !== 'true')) { var xml = <s><![CDATA[ <!doctype html> <html> <title>Hacker News Search Results</title> <body> <h3>Hacker News search results for &quot;<%= q %>&quot;:</h3> <ul> <% _(hits).each(function (hit) { if (hit.url) { %> <li> <a href="<%= hit.url %>" target="_top"><%= hit.title || '(No title)' %></a> <% if (hit.story_text) { %> : <%= _(hit.story_text).prune(100) %> <% } %> &nbsp;<small>(<%= hostForUrl(hit.url) %>)</small> </li> <% } }); %> </ul> <p> <small>Search results provided by <a href="https://www.algolia.com/" target="_top">Algolia</a>.</small> </p> </body> </html> ]]></s>; var template = xml.toString(); var model = { q: q, hits: hits, hostForUrl: hostForUrl }; var content = ejs.render(template, model); return [{ label: 'Hacker News Search', uri: 'https://hn.algolia.com/#!/story/forever/0/' + encodeURIComponent(q), tooltip: 'Hacker News Search results for "' + _(q).escapeHTML() + '"', iconUrl: ICON_URL, relevance: BASE_RELEVANCE, content: content, serverSideSanitized: true, categories: [{value: 'programming', weight: 1.0}, {value: 'business', weight: 0.5}] }]; } else { return _(hits).chain().filter(function (hit) { return !!hit.url; }).map(function (hit) { console.log('got hit url = ' + hit.url); return { label : hit.title || '', iconUrl: ICON_URL, uri : hit.url, // embeddable: false, let solveforall guess summaryHtml: _(hit.story_text || '').escapeHTML(), relevance: BASE_RELEVANCE * (1.0 - Math.pow(2.0, -Math.max((hit.points || 0), 1) * 0.01)) }; }).value(); } }; } function generateResults(recognitionResults, q, context) { 'use strict'; if (context.isSuggestionQuery) { return []; } var url = 'https://hn.algolia.com/api/v1/search'; var request = hostAdapter.makeWebRequest(url, { data: { query: q } }); request.send('makeResponseHandler(' + JSON.stringify(q) + ',' + JSON.stringify(context) + ')'); return HostAdapter.SUSPEND; }
JavaScript
0.00014
@@ -419,16 +419,208 @@ tIndex); + %0A var endIndex2 = url.indexOf('?', startIndex);%0A %0A if (endIndex %3C 0) %7B%0A endIndex = endIndex2; %0A %0A if (endIndex %3C 0) %7B%0A return url.substring(startIndex);%0A %7D %0A %7D %0A %0A retur
55524174ef76c23b1e1917e57cbe863fee3acd8e
Resolve #67: Add channelOptions option to ChannelPool constructor
lib/ChannelPool.js
lib/ChannelPool.js
/*jslint node: true, indent: 2, unused: true, maxlen: 80, camelcase: true */ /* * stompit.ChannelPool * Copyright (c) 2014 Graham Daws <graham.daws@gmail.com> * MIT licensed */ var Channel = require('./Channel'); var assign = require('object-assign'); function ChannelPool(connectFailover, options) { if (!(this instanceof ChannelPool)) { var object = Object.create(ChannelPool.prototype); ChannelPool.apply(object, arguments); return object; } options = assign({ minChannels: 1, minFreeChannels: 1, maxChannels: Infinity, freeExcessTimeout: null, requestChannelTimeout: null }, options || {}); this._connectFailover = connectFailover; this._minChannels = options.minChannels; this._minFreeChannels = Math.min(options.minFreeChannels, this._minChannels); this._maxChannels = options.maxChannels; this._channels = []; this._freeChannels = []; this._freeExcessTimeout = options.freeExcessTimeout; this._freeExcessTimeouts = []; this._requestChannelTimeout = options.requestChannelTimeout; this._closed = false; if (this._requestChannelTimeout !== null){ this._channelRequests = []; } for (var i = 0; i < this._minChannels; i++) { this._allocateFreeChannel(); } } ChannelPool.prototype._createChannel = function() { return new Channel(this._connectFailover, { alwaysConnected: true }); }; ChannelPool.prototype._allocateFreeChannel = function() { if (this._channels.length >= this._maxChannels) { return; } var channel = this._createChannel(); this._channels.push(channel); this._freeChannels.push(channel); return channel; }; ChannelPool.prototype._deallocateChannel = function(channel) { channel.close(); var index = this._channels.indexOf(channel); if (index !== -1) { this._channels.splice(index, 1); } }; ChannelPool.prototype._addExcessTimeout = function() { if (this._freeChannels.length <= this._minChannels) { return; } var self = this; var close = function() { var channel = self._freeChannels.shift(); if (!channel.isEmpty()) { self._startIdleListen(channel); return; } self._deallocateChannel(channel); }; if (this._freeExcessTimeout === null) { close(); return; } this._freeExcessTimeouts.push(setTimeout(function() { self._freeExcessTimeouts.shift(); if (self._freeChannels.length > self._minChannels) { close(); } }, this._freeExcessTimeout)); }; ChannelPool.prototype._hasChannelRequestTimeout = function() { return typeof this._requestChannelTimeout == 'number'; }; ChannelPool.prototype._startIdleListen = function(channel) { var self = this; channel.once('idle', function(){ if (self._closed) { self._deallocateChannel(channel); return; } if (self._hasChannelRequestTimeout() && self._channelRequests.length > 0) { var channelRequest = self._channelRequests.shift(); clearTimeout(channelRequest.timeout); self._startIdleListen(channel); channelRequest.callback(null, channel); return; } self._freeChannels.push(channel); self._addExcessTimeout(); }); }; ChannelPool.prototype._timeoutChannelRequest = function(callback) { this._channelRequests.shift(); callback(new Error('failed to allocate channel')); }; ChannelPool.prototype.channel = function(callback) { if (this._closed) { process.nextTick(function() { callback(new Error('channel pool closed')); }); return; } if (this._freeChannels.length === 0 && !this._allocateFreeChannel()) { if (this._hasChannelRequestTimeout()) { var timeout = setTimeout( this._timeoutChannelRequest.bind(this, callback), this._requestChannelTimeout ); this._channelRequests.push({ timeout: timeout, callback: callback }); } else { process.nextTick(function() { callback(new Error('failed to allocate channel')); }); } return; } var channel = this._freeChannels.shift(); if (this._freeExcessTimeouts.length > 0) { clearTimeout(this._freeExcessTimeouts.shift()); } if (this._freeChannels.length < this._minFreeChannels) { this._allocateFreeChannel(); } this._startIdleListen(channel); process.nextTick(function() { callback(null, channel); }); }; ChannelPool.prototype.close = function() { this._closed = true; this._channels.forEach(function(channel) { channel.close(); }); this._channels = []; this._freeChannels = []; if (this._channelRequests) { this._channelRequests.forEach(function(request) { clearTimeout(request.timeout); request.callback(new Error('channel pool closed')); }); this._channelRequests = []; } }; module.exports = ChannelPool;
JavaScript
0
@@ -661,16 +661,41 @@ ut: null +,%0A%0A channelOptions: %7B%7D %0A %0A @@ -949,32 +949,119 @@ annels = %5B%5D;%0A %0A + this._channelOptions = assign(%7B%7D, options.channelOptions, %7BalwaysConnected: true%7D);%0A%0A this._freeChan @@ -1477,18 +1477,16 @@ ion() %7B%0A - %0A retur @@ -1526,39 +1526,28 @@ er, -%7B%0A alwaysConnected: true%0A %7D +this._channelOptions );%0A%7D
709f9ae84a27cca1e4b4c540237a7c75cddd5383
fix line endings and update build 2
Jakefile.js
Jakefile.js
var build = require('./build/build.js'), lint = require('./build/hint.js'); var COPYRIGHT = "/*\r\n Copyright (c) 2010-2011, CloudMade, Vladimir Agafonkin\n" + " Leaflet is a modern open-source JavaScript library for interactive maps.\n" + " http://leaflet.cloudmade.com\r\n*/\r\n"; desc('Check Leaflet source for errors with JSHint'); task('lint', function () { var files = build.getFiles(); console.log('Checking for JS errors...'); var errorsFound = lint.jshint(files); if (errorsFound > 0) { console.log(errorsFound + ' error(s) found.\n'); fail(); } else { console.log('\tCheck passed'); } }); desc('Combine and compress Leaflet source files'); task('build', ['lint'], function (compsBase32, buildName) { var name = buildName || 'custom', path = 'dist/leaflet' + (compsBase32 ? '-' + name : ''); var files = build.getFiles(compsBase32); console.log('Concatenating ' + files.length + ' files...'); var content = build.combineFiles(files); console.log('\tUncompressed size: ' + content.length); build.save(path + '-src.js', COPYRIGHT + content); console.log('\tSaved to ' + path); console.log('Compressing...'); var compressed = COPYRIGHT + build.uglify(content); console.log('\tCompressed size: ' + compressed.length); build.save(path + '.js', compressed); console.log('\tSaved to ' + path); }); task('default', ['build']);
JavaScript
0
@@ -150,16 +150,18 @@ afonkin%5C +r%5C n%22 +%0A
1c4a59f86ac4e1e062ad061b5850f0175184958e
Make sure we're only adding labels to lis on the top level
github.com.js
github.com.js
var dotjs_github = {}; dotjs_github.init = function() { dotjs_github.$issues = $('.issues'); var style = '<style>' + '.filter-exclude { margin-top: 10px; }' + '.filter-exclude input {' + ' box-sizing: border-box;' + ' padding: 3px 4px;' + ' width: 100%;' + '}' + '.filter-exclude .minibutton {' + ' display: block;' + ' text-align: center;' + '}' + '.filter-list li {' + ' position: relative;' + '}' + '.filter-list .hide-it {' + ' font-size: 20px;' + ' line-height: 20px;' + ' left: -45px;' + ' position: absolute;' + ' top: 0px;' + '}' + '.filter-list .hide-it.clicked {' + ' color: #ccc;' + '}' + '.filter-list .custom-hidden a:nth-child(2) {' + ' text-decoration: line-through;' + ' opacity: 0.3;' + '}' + '.filter-list .hide-it:hover {' + ' text-decoration: none;' + '}' + '.issues .item.hidden {' + ' display: none;' + '}' + '</style>'; $('body').append( style ); $('.sidebar .filter-item').live('click.dotjs_github', function( e ) { e.preventDefault(); setTimeout( function() { dotjs_github.$issues = $('.issues'); dotjs_github.add_hide_links(); }, 500 ); }); dotjs_github.add_hide_links(); }; dotjs_github.add_hide_links = function() { var $labels = $('.js-color-label-list'); $labels.find('li').prepend('<a href="#" class="hide-it minibutton">☠</a>'); $labels.find('.hide-it').bind('click', function( e ) { e.preventDefault(); e.stopPropagation(); var $el = $(this); var val = $el.next().data('label'); var $issues = dotjs_github.$issues.find('.list-browser-item .label[data-name="' + $.trim( val ) + '"]').closest('tr'); if ( ! $el.hasClass('clicked') ) { $el.addClass('clicked').closest('li').addClass('custom-hidden'); $issues.addClass('hidden'); } else { $el.removeClass('clicked').closest('li').removeClass('custom-hidden'); $issues.removeClass('hidden'); }//end else var count = $('.issues-list').find('.list-browser-item:not(.hidden)').length; var $selected = $('.list-browser-filter-tabs .selected'); $selected.html( parseInt( count, 10 ) + ' ' + $selected.data('filter') + ' issues' ); }); }; dotjs_github.init();
JavaScript
0
@@ -1296,20 +1296,24 @@ $labels. -find +children ('li').p
5f9703e389ba0ab7471ef4d3f41b9f07b9198f71
Update throbber test time to avoid test inaccuracies
test/__playground/throbber.formatted.js
test/__playground/throbber.formatted.js
#!/usr/bin/env node 'use strict'; var throbber = require('../../lib/throbber') , interval = require('clock/lib/interval') , format = require('../../lib/index').red; var i = interval(100, true); throbber(i, format); process.stdout.write('START'); setTimeout(i.stop.bind(i), 500);
JavaScript
0
@@ -278,13 +278,13 @@ nd(i), 5 -0 +5 0);%0A
17b95e4b726a9c59096fe56c20cda3b05bb3acd3
add new test spec for models
server/spec/modelSpec.js
server/spec/modelSpec.js
import jasmine from 'jasmine'; import Sequelize from 'sequelize'; import expect from 'expect'; import Users from '../models/users'; import Group from '../models/group'; // import GroupMembers from '../models/groupMembers'; // import Messages from '../models/messages'; import db from '../config/db_url.json'; describe('Model test suite', () => { beforeEach((done) => { const sequelize = new Sequelize(db.url); sequelize.authenticate().then(() => { console.log('Connection established'); }) .catch((err) => { console.log('Error occured', err); }); done(); }, 10000); it('I should be able to create a new user with this model', (done) => { Users.sync({ force: true }).then(() => { Users.create({ name: 'Peter', username: 'Ike', email: 'alobam@gmail.com', password: 'show' }) .then((user) => { if (user) { expect('Ike').toBe(user.dataValues.username); } done(); }).catch((err) => { console.log('Failed', err); done(); }); }); }, 10000); it('I should be able to create a new group with this model', (done) => { Group.sync({ force: true }).then(() => { Group.create({ groupName: 'Zikites', groupCategory: 'Class of 2014', userId: 1 }) .then((group) => { if (group) { expect('Zikites').toNotBe('Zike'); expect('Class of 2014').toBe(group.dataValues.groupCategory); } done(); }); }).catch((err) => { console.log('Failed', err); }); }, 10000); /* it('I should be able to add users to group I created', (done) => { GroupMembers.sync({ force: true }).then(() => { GroupMembers.create({ userId: 1, admin: 1, groupId: 1 }) .then((members) => { if (members) { expect(1).toBe(members.dataValues.userId); } done(); }); }).catch((err) => { console.log('Failed', err); }); }, 10000);*/ }); /* describe('Models test suite', () => { describe('Establish connection to the database', () => { beforeAll((done) => { const sequelize = new Sequelize(db.url); sequelize.authenticate().then(() => { console.log('Connected'); // 'Connected'; }).catch((err) => { if (err) { return 'Unable to connect'; } }); done(); }); }); describe('Users model', () => { beforeEach((done) => { const User = Users.sync({ force: true }).then(() => { Users.create({ name: 'Ebuka', username: 'Bonachristi', email: 'bona@gmail.com', password: 'samodu' }) .then((result) => { if (result) { return 'Registered'; } }).catch((err) => { if (err) { return 'Failed'; } }); }); it('should be able to create a new account', () => { expect(User).to.be.a('Registered'); done(); }); }); }); describe('Create a new group', () => { beforeEach((done) => { const CreateGroup = Group.sync({ force: true }).then(() => { Group.create({}).then((group) => { if (group) { return 'Group Created'; } }).catch((err) => { if (err) { return 'Error occured, group not created'; } }); }); it('Registered users should be able to create a group', () => { expect(CreateGroup).to.be.a('Group Created'); done(); }); }); }); describe('Add registered users to group', () => { beforeEach((done) => { const AddMembers = GroupMembers.sync({ force: true }).then(() => { GroupMembers.create({}).then((users) => { if (users) { return 'Added'; } }).catch((err) => { if (err) { return 'Failed'; } }); }); it('Users should be added by groups by registered user', () => { expect(AddMembers).to.be.a('Added'); done(); }); }); }); describe('A user should be able to post messages to groups he created', () => { beforeEach((done) => { const post = Messages.sync({ force: true }).then(() => { Messages.create({}).then((message) => { if (message) { return 'Posted'; } }).catch((err) => { if (err) { return 'Failed'; } }); }); it('Should be able to post message to group', () => { expect(post).to.be.a('Posted'); done(); }); }); }); });*/
JavaScript
0
@@ -1904,2664 +1904,4 @@ );%0A%0A -%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A/* describe('Models test suite', () =%3E %7B%0A describe('Establish connection to the database', () =%3E %7B%0A beforeAll((done) =%3E %7B%0A const sequelize = new Sequelize(db.url);%0A sequelize.authenticate().then(() =%3E %7B%0A console.log('Connected');%0A // 'Connected';%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Unable to connect';%0A %7D%0A %7D);%0A done();%0A %7D);%0A %7D);%0A describe('Users model', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const User = Users.sync(%7B force: true %7D).then(() =%3E %7B%0A Users.create(%7B name: 'Ebuka', username: 'Bonachristi', email:%0A 'bona@gmail.com', password: 'samodu' %7D)%0A .then((result) =%3E %7B%0A if (result) %7B%0A return 'Registered';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('should be able to create a new account', () =%3E %7B%0A expect(User).to.be.a('Registered');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('Create a new group', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const CreateGroup = Group.sync(%7B force: true %7D).then(() =%3E %7B%0A Group.create(%7B%7D).then((group) =%3E %7B%0A if (group) %7B%0A return 'Group Created';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Error occured, group not created';%0A %7D%0A %7D);%0A %7D);%0A it('Registered users should be able to create a group', () =%3E %7B%0A expect(CreateGroup).to.be.a('Group Created');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('Add registered users to group', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const AddMembers = GroupMembers.sync(%7B force: true %7D).then(() =%3E %7B%0A GroupMembers.create(%7B%7D).then((users) =%3E %7B%0A if (users) %7B%0A return 'Added';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('Users should be added by groups by registered user', () =%3E %7B%0A expect(AddMembers).to.be.a('Added');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('A user should be able to post messages to groups he created', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const post = Messages.sync(%7B force: true %7D).then(() =%3E %7B%0A Messages.create(%7B%7D).then((message) =%3E %7B%0A if (message) %7B%0A return 'Posted';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('Should be able to post message to group', () =%3E %7B%0A expect(post).to.be.a('Posted');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%7D);*/%0A
aa10cda61021ef3d32c301755e594faecbf24f2e
Add tests to <Text>
src/Text/__tests__/Text.test.js
src/Text/__tests__/Text.test.js
import React from 'react'; import ReactDOM from 'react-dom'; import Text from '../Text'; it('renders without crashing', () => { const div = document.createElement('div'); const element = ( <Text align="right" basic="Basic text" aside="Aside text" tag="Tag" /> ); ReactDOM.render(element, div); });
JavaScript
0
@@ -65,26 +65,138 @@ ort -Text from '../Text +%7B shallow %7D from 'enzyme';%0A%0Aimport StatusIcon from 'src/StatusIcon';%0Aimport Text from '../Text';%0Aimport BasicRow from '../BasicRow ';%0A%0A @@ -474,12 +474,1709 @@ div);%0A%7D);%0A%0A +it('renders using %3CBasicRow%3E with BEM className', () =%3E %7B%0A const wrapper = shallow(%3CText basic=%22text%22 /%3E);%0A const rowWrapper = wrapper.find(BasicRow);%0A%0A expect(wrapper.children()).toHaveLength(1);%0A expect(rowWrapper.exists()).toBeTruthy();%0A expect(rowWrapper.hasClass('ic-text__row')).toBeTruthy();%0A expect(rowWrapper.hasClass('ic-text__basic')).toBeTruthy();%0A%7D);%0A%0Ait('passing %22basic%22, %22tag%22 and %22stateIcon%22 to %3CBasicRow%3E', () =%3E %7B%0A const icon = %3CStatusIcon status=%22loading%22 /%3E;%0A const wrapper = shallow(%0A %3CText%0A basic=%22Basic text%22%0A tag=%22Tag%22%0A stateIcon=%7Bicon%7D /%3E%0A );%0A const rowWrapper = wrapper.find(BasicRow);%0A%0A expect(rowWrapper.prop('basic')).toBe('Basic text');%0A expect(rowWrapper.prop('tag')).toBe('Tag');%0A expect(rowWrapper.prop('stateIcon')).toEqual(icon);%0A%7D);%0A%0Ait('takes custom %3CBasicRow%3E and passes the same props to it', () =%3E %7B%0A const FooRow = () =%3E %3Cdiv /%3E;%0A%0A const customRow = %3CFooRow /%3E;%0A const icon = %3CStatusIcon status=%22loading%22 /%3E;%0A%0A const wrapper = shallow(%0A %3CText%0A basic=%22Basic text%22%0A tag=%22Tag%22%0A stateIcon=%7Bicon%7D%0A basicRow=%7BcustomRow%7D /%3E%0A );%0A const rowWrapper = wrapper.find(FooRow);%0A%0A expect(rowWrapper.prop('basic')).toBe('Basic text');%0A expect(rowWrapper.prop('tag')).toBe('Tag');%0A expect(rowWrapper.prop('stateIcon')).toEqual(icon);%0A%7D);%0A%0Ait('renders aside text', () =%3E %7B%0A const wrapper = shallow(%3CText basic=%22Basic%22 aside=%22Aside%22 /%3E);%0A%0A expect(wrapper.children()).toHaveLength(2);%0A expect(wrapper.childAt(1).hasClass('ic-text__aside')).toBeTruthy();%0A expect(wrapper.childAt(1).text()).toBe('Aside');%0A%7D);%0A
63c03ef48a1fc0dbeec02943909bc9bc26ad7a2c
Mark TODO
lib/api/register_user.js
lib/api/register_user.js
var data = require(__dirname+'/../data/'); var sql = require(__dirname +'/../data/sequelize.js'); var config = require(__dirname+'/../../config/environment.js'); var validator = require(__dirname+'/../validator.js'); var RippleRestClient = require('ripple-rest-client'); var uuid = require('node-uuid'); /** * Register a User * - creates external account named "default" * - creates ripple address as provided * @require data, sql, config * @param {string} name * @param {string} rippleAddress * @param {string} password * @returns {User}, {ExternalAccount}, {RippleAddress} */ function registerUser(opts, fn) { var userOpts = { name: opts.name, password: opts.password, address: opts.ripple_address, secret: opts.secret, currency: opts.currency, amount: opts.amount }; if (!validator.isRippleAddress(opts.ripple_address)) { fn({ ripple_address: 'invalid ripple address' }); return; } sql.transaction(function(sqlTransaction){ data.users.create(userOpts, function(err, user) { if (err) { sqlTransaction.rollback(); fn(err, null); return; } var addressOpts = { user_id: user.id, address: opts.ripple_address, managed: false, type: 'independent' }; data.rippleAddresses.create(addressOpts, function(err, ripple_address) { if (err) { sqlTransaction.rollback(); fn(err, null); return; } data.externalAccounts.create({ name: 'default', user_id: user.id, address:addressOpts.address, type:addressOpts.type }, function(err, account){ if (err) { fn(err, null); return; } var addressOpts = { user_id: user.id, address: config.get('COLD_WALLET'), managed: true, type: 'hosted', tag: account.id }; // We might be missing the cold wallet if (addressOpts.address) { // CS Fund user account with XRP var rippleRootRestClient = new RippleRestClient({ api: config.get('RIPPLE_REST_API'), account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' }); var options = { secret: 'masterpassphrase', client_resource_id: uuid.v4(), payment: { destination_account: userOpts.address, source_account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', destination_amount: { value: '60', currency: 'XRP', issuer: '' } } }; rippleRootRestClient.sendAndConfirmPayment(options, function(error, response){ if (error || (response.success != true)) { logger.error('rippleRestClient.sendAndConfirmPayment', error); return fn(error, null); } // CS Set trust line from user account to cold wallet. We should let users to this manually. var coldWallet = config.get('COLD_WALLET'); var rippleRestClient = new RippleRestClient({ api: config.get('RIPPLE_REST_API'), account:userOpts.address }); rippleRestClient.setTrustLines({ account: userOpts.address, secret: userOpts.secret, limit: userOpts.amount, currency: userOpts.currency, counterparty: coldWallet, account_allows_rippling: true }, fn); }); // CS Create in DB data.rippleAddresses.create(addressOpts, function(err, hosted_address) { if (err) { sqlTransaction.rollback(); fn(err, null); return; } var response = user.toJSON(); response.ripple_address = ripple_address; response.external_account = account; response.hosted_address = hosted_address; sqlTransaction.commit(); fn(err, response); }); } }); }); }); }); } module.exports = registerUser;
JavaScript
0.000004
@@ -3682,16 +3682,83 @@ e in DB%0A + // TODO the server.js process is restarted here - why?%0A
847544231b0819913f22e2fe437f5cf475542962
fix code identity
server/streak/service.js
server/streak/service.js
const rp = require('request-promise'); const cheerio = require('cheerio'); const getStreakBody = (userName) => { var options = { uri: `https://github.com/users/${userName}/contributions`, transform: function (body) { return cheerio.load(body); } }; return rp(options) .then(function ($) { const currentDateStreak = []; let currentStreak = []; $('.day').filter(function (i, el) { return $(this).prop('data-count') !== '0'; }).each(function (index) { const date = new Date($(this).prop('data-date')); date.setHours(0, 0, 0, 0); if (currentDateStreak[index - 1]) { const tempDate = currentDateStreak[index - 1].date; tempDate.setDate(tempDate.getDate() + 1); tempDate.setHours(0, 0, 0, 0); if (date.getTime() === tempDate.getTime()) { if ($(this).prop('fill') != '#ebedf0') { currentStreak.push({ date: date, commit: $(this).prop('data-count') }); } } else { currentStreak = []; } } currentDateStreak.push({ date: date }); }); return currentStreak; }) .catch( (err) => { console.log('errror', err); }); }; module.exports = { getStreakBody };
JavaScript
0.000717
@@ -799,56 +799,8 @@ ) %7B%0A -%09%09%09%09%09%09if ($(this).prop('fill') != '#ebedf0') %7B%0A%09 %09%09%09%09 @@ -818,25 +818,24 @@ reak.push(%7B%0A -%09 %09%09%09%09%09%09%09date: @@ -848,17 +848,16 @@ %0A%09%09%09%09%09%09%09 -%09 commit: @@ -893,21 +893,12 @@ %09%09%09%09 -%09 %7D);%0A -%09%09%09%09%09%09%7D%0A %09%09%09%09 @@ -1046,17 +1046,16 @@ %09.catch( - (err) =%3E @@ -1076,17 +1076,16 @@ log('err -r or', err @@ -1097,13 +1097,12 @@ %7D);%0A + %7D;%0A%0A -%0A modu
5418e50f4d56f3f700c9ecc745c3d1d3e25bbfc9
Add extra named-chunks test cases for variations with require.ensure error callback present.
test/cases/chunks/named-chunks/index.js
test/cases/chunks/named-chunks/index.js
it("should handle named chunks", function(done) { var sync = false; require.ensure([], function(require) { require("./empty?a"); require("./empty?b"); testLoad(); sync = true; process.nextTick(function() { sync = false; }); }, "named-chunk"); function testLoad() { require.ensure([], function(require) { require("./empty?c"); require("./empty?d"); sync.should.be.ok(); done(); }, "named-chunk"); } }); it("should handle empty named chunks", function(done) { var sync = false; require.ensure([], function(require) { sync.should.be.ok(); }, "empty-named-chunk"); require.ensure([], function(require) { sync.should.be.ok(); done(); }, "empty-named-chunk"); sync = true; setImmediate(function() { sync = false; }); });
JavaScript
0
@@ -757,12 +757,977 @@ e;%0A%09%7D);%0A%7D);%0A +%0Ait(%22should handle named chunks when there is an error callback%22, function(done) %7B%0A var sync = false;%0A require.ensure(%5B%5D, function(require) %7B%0A require(%22./empty?a%22);%0A require(%22./empty?b%22);%0A testLoad();%0A sync = true;%0A process.nextTick(function() %7B%0A sync = false;%0A %7D);%0A %7D, function(error) %7B%7D, %22named-chunk%22);%0A function testLoad() %7B%0A require.ensure(%5B%5D, function(require) %7B%0A require(%22./empty?c%22);%0A require(%22./empty?d%22);%0A sync.should.be.ok();%0A done();%0A %7D, function(error) %7B%7D, %22named-chunk%22);%0A %7D%0A%7D);%0A%0Ait(%22should handle empty named chunks when there is an error callback%22, function(done) %7B%0A var sync = false;%0A require.ensure(%5B%5D, function(require) %7B%0A sync.should.be.ok();%0A %7D, function(error) %7B%7D, %22empty-named-chunk%22);%0A require.ensure(%5B%5D, function(require) %7B%0A sync.should.be.ok();%0A done();%0A %7D, function(error) %7B%7D, %22empty-named-chunk%22);%0A sync = true;%0A setImmediate(function() %7B%0A sync = false;%0A %7D);%0A%7D);%0A
4acca781206921d81fb4dd1b05df11920951621c
Fix formatting
cla_public/static-src/javascripts/modules/form-errors.js
cla_public/static-src/javascripts/modules/form-errors.js
(function() { 'use strict'; moj.Modules.FormErrors = { init: function() { _.bindAll(this, 'postToFormErrors', 'onAjaxSuccess', 'onAjaxError'); this.bindEvents(); this.loadTemplates(); }, bindEvents: function() { $('form') .on('submit', this.postToFormErrors) // Focus back on summary if field-error is focused and escape key is pressed .on('keyup', function(e) { var $target = $(e.target); if(e.keyCode === 27 && $target.is('.form-error')) { $target.closest('form').find('> .alert').focus(); } }) .on('blur', '.form-group', function(e) { $(e.target).removeAttr('tabindex'); }); //// Add role=alert on error message when fieldset is focused //.on('focus', 'fieldset.m-error', function(e) { // $(e.target).find('.field-error').attr('role', 'alert'); //}) //// Remove role=alert from error message when fieldset is blurred //.on('blur', 'fieldset.m-error', function(e) { // $(e.target).find('.field-error').removeAttr('role'); //}); $('[type=submit]').on('click', function(e) { var $target = $(e.target); $target.closest('form').attr('submit-name', $target.attr('name')); }); // Focus on field with error $('#content').on('click', '.error-summary a', function(e) { e.preventDefault(); var targetId = e.target.href.replace(/.*#/, '#'); if(targetId.length < 2) { return; } var $target = $(targetId); $('html, body').animate({ scrollTop: $target.offset().top - 20 }, 300, function() { $target.attr('tabindex', -1).focus(); }); }); }, postToFormErrors: function(e) { this.$form = $(e.target); // Return if button has a name, which is attached as form attribute on click // (assuming secondary buttons) if(this.$form.attr('submit-name') || this.$form.attr('method') && this.$form.attr('method').toLowerCase() === 'get') { return; } if (this.$form.length) { e.preventDefault(); e.stopPropagation(); $.ajax({ type: 'OPTIONS', url: '', contentType: 'application/x-www-form-urlencoded', data: this.$form.serialize() }) .done(this.onAjaxSuccess) .fail(this.onAjaxError); } }, onAjaxSuccess: function(errors) { if (!$.isEmptyObject(errors)) { this.loadErrors(errors); var errorBanner = $('.alert-error:visible:first'); if(!errorBanner.length) { return; } $('html, body').animate({ scrollTop: errorBanner.offset().top - 20 }, 300, function() { errorBanner.attr({'tabindex': -1}).focus(); }); } else { this.$form.off('submit'); this.$form.submit(); } }, onAjaxError: function() { this.$form.off('submit'); this.$form.submit(); }, formatErrors: function(errors) { var errorFields = {}; (function fieldName (errorsObj, prefix) { prefix = (typeof prefix === 'undefined')? '': prefix + '-'; for (var key in errorsObj) { var field = prefix + key; if ($.isArray(errorsObj[key])) { errorFields[field] = errorsObj[key]; } else { fieldName(errorsObj[key], field); } } })(errors); return errorFields; }, createErrorSummary: function() { var errorSummary = []; // Loop through errors on the page to retain the fields order $('.form-error').map(function() { var $this = $(this); if(!this.id || $this.hasClass('s-hidden') || $this.parent().hasClass('s-hidden')) { return; } var name = this.id.replace(/^field-/, ''); errorSummary.push({ label: $this.find('> legend, > .form-group-label').text(), name: name, errors: $this.find('> .field-error p').map(function() { return $(this).text(); }) }); }); return errorSummary; }, loadErrors: function(errors) { var errorFields = this.formatErrors(errors); var self = this; this.clearErrors(); function addErrors(errors, fieldName) { if (_.isString(errors[0])) { $('#field-' + fieldName) .addClass('form-error') .attr({ 'aria-invalid': true, 'aria-describedby': 'error-' + fieldName }); var label = $('#field-label-' + fieldName); label.after(self.fieldError({ errors: errors, fieldName: fieldName })); } else if(_.isObject(errors[0]) && !_.isArray(errors[0])) { // Multiple forms (e.g. properties) _.each(errors, function(errors, i) { _.each(errors, function(subformErrors, subformFieldName) { addErrors(subformErrors, fieldName + '-' + i + '-' + subformFieldName); }); }); } else { _.each(errors, function(subformErrors) { addErrors(subformErrors[1], fieldName + '-' + subformErrors[0]); }); } } _.each(errorFields, addErrors); if(this.$form.data('error-banner') !== false) { this.$form.prepend(this.mainFormError({ errors: this.createErrorSummary()})); } }, loadTemplates: function() { this.mainFormError = _.template($('#mainFormError').html()); this.fieldError = _.template($('#fieldError').html()); }, clearErrors: function() { $('.form-row.field-error').remove(); $('.alert.alert-error').remove(); $('.form-error') .removeClass('form-error') .removeAttr('aria-invalid'); } }; }());
JavaScript
0.000029
@@ -3240,12 +3240,14 @@ ed') + ? '' + : pr
ce9b5866133de731e00202a8faa19f7de1ecbd38
Fix in category filter popup
cityproblems/site/static/site/js/index.js
cityproblems/site/static/site/js/index.js
var mainPageViewCtrl = function ($scope, $http, $route) { "use strict"; $scope.showMenu = false; $scope.alerts=[]; $scope.$on('$routeChangeSuccess', function(next, current) { if((current.params.reportBy != $scope.reportBy || current.params.category != $scope.category) && (typeof current.params.reportBy != "undefined" && typeof current.params.category != "undefined")) { $scope.reportBy = current.params.reportBy; $scope.category = current.params.category; loadMarkers(); } }); $scope.init=function(categories) { $scope.categories = angular.fromJson(categories); $scope.tmpCategory = "all"; } $scope.$watch("category", function(category, oldValue) { if(category != oldValue) for(var i=0;i<$scope.categories.length;++i) if($scope.categories[i]["url_name"] == category) { $scope.categoryTitle = $scope.categories[i].title; break; } } ) function clearMap() { if(!$scope.markers) { $scope.markers=[]; return; } for(var i=0;i<$scope.markers.length;++i) $scope.markers[i].setMap(null); $scope.markers=[]; } $scope.map_init=function() { var zoom = parseInt($scope.zoom); if(zoom!=zoom) $scope.zoom=11; var latitude = parseFloat($scope.latitude.replace(",", ".")); var longitude = parseFloat($scope.longitude.replace(",", ".")); if(latitude!=latitude || longitude!=longitude) { alert("Wrong map config. Please fix it in site parameters"); return; } var latLng = new google.maps.LatLng(latitude, longitude); var mapOptions = { zoom: zoom, center: latLng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false } $scope.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); } function loadMarkers() { $http.post($scope.loadDataURL, {reportBy: $scope.reportBy, category: $scope.category}) .success(function(data) { if ("error" in data) $scope.alerts.push({type: 'danger', msg: data["error"]}); else { clearMap(); var objList = data["problems"]; var infowindow = new google.maps.InfoWindow(); $scope.infowindow=infowindow; for(var i=0;i<objList.length;++i) { var myLatlng = new google.maps.LatLng(parseFloat(objList[i].latitude), parseFloat(objList[i].longitude)); var marker = new google.maps.Marker({ position: myLatlng, map: $scope.map, html: '<a href="'+$scope.problemViewURL+objList[i].id+'/" target="_blank">'+objList[i].title+'</a>' }); google.maps.event.addListener(marker, 'click', function () { infowindow.setContent(this.html); infowindow.open($scope.map, this); }); $scope.markers.push(marker); } } }) .error(function(data) { //document.write(data); $scope.alerts.push({type: 'danger', msg: "Error while load data"}); }); } $scope.closeAlert = function(index) { $scope.alerts.splice(index, 1); }; }; mainPageViewCtrl.$inject = ["$scope", "$http", "$route"];
JavaScript
0.000001
@@ -539,24 +539,82 @@ dMarkers();%0A + $('#popup-filter-category').trigger('close');%0A %7D%0A
0e8964f2cca4493045814fb74fb4ea7de53d9242
Fix paths on Windows
lib/asset_types/html5.js
lib/asset_types/html5.js
var loader = require("@loader"); var nodeRequire = loader._nodeRequire; var path = nodeRequire("path"); // Register the html5-upgrade asset type module.exports = function(register){ var shivPath = path.join(__dirname, "/../../scripts/html5shiv.min.js"); var loaderBasePath = loader.baseURL.replace("file:", ""); var shivUrl = path.relative(loaderBasePath, shivPath); register("html5shiv", function(){ var elements = Object.keys(loader.global.can.view.callbacks._tags) .filter(function(tagName) { return tagName.indexOf("-") > 0; }); var comment = document.createComment( "[if lt IE 9]>\n" + "\t<script src=\""+ shivUrl + "\"></script>" + "\t<script>\n\t\thtml5.elements = \"" + elements.join(" ") + "\";\nhtml5.shivDocument();\n\t</script>" + "<![endif]" ); return comment; }); };
JavaScript
0
@@ -362,16 +362,36 @@ hivPath) +.replace(/%5C%5C/g, %22/%22) ;%0A%0A%09regi
0f6506374ddfed2969454b081e5494f0cda811de
Update cred.js
server/routes/cred.js
server/routes/cred.js
var User = require('../models/users.js'); var express = require('express'); var router = express.Router(); var nodemailer = require('nodemailer'); var wellknown = require('nodemailer-wellknown'); module.exports = router; router.post('/sendEmail', function(req,res){ var email = req.body.email; console.log('email in send', email) User.getByEmail(email) .then(user => { console.log('user in sendEmail:', user); if(user[0]){ var config = wellknown('GandiMail'); config.auth = { user: 'info@fairshare.cloud', pass: 'AeK6yxhT' }; var transporter = nodemailer.createTransport(config); var mailOptions = { from: '"Info" <info@fairshare.cloud>', to: '<'+ email +'>', subject: "Click the following link to reset your Fairshare password", html: '<a href=' + 'http://localhost:3000/resetPassword>Reset Password</a>' }; transporter.sendMail(mailOptions, function(err, info){ if(err){ return console.log(err); }else{ res.status(200).send(info); } }); }else{ res.status(401).send('Email is not registered') } }) .catch(err => console.warn(err)) })
JavaScript
0.000001
@@ -910,25 +910,31 @@ http +s :// -localhost:3000 +www.fairshare.cloud /res @@ -1303,8 +1303,9 @@ err))%0A%7D) +%0A
b03df04b45b069a4bea75bed5a8428eb7b1275c2
reformulate as recursion
WordSmushing/smushing.js
WordSmushing/smushing.js
"use strict"; var assert = require('assert'); var smush = function(w1,w2) { return w1 + w2; }; describe('word smushing', function() { it('should join words with no overlap', function() { assert.equal('thecat', smush('the', 'cat')); }); it('should do single character overlaps', function() { assert.equal('henot', smush('hen', 'not')); }); });
JavaScript
0.999976
@@ -79,22 +79,77 @@ -return w1 + +if (w1 === '') return w2;%0A%0A return w1%5B0%5D + smush(w1.substr(1), w2 +) ;%0A%7D; @@ -191,24 +191,29 @@ n() %7B%0A it +.only ('should joi
c4b6024abd81b33562c78c343ecb99e0210ecfb5
Add test that child nodes are rendered.
src/components/with-drag-and-drop/draggable-context/__spec__.js
src/components/with-drag-and-drop/draggable-context/__spec__.js
import React from 'react'; import { DragDropContext } from 'react-dnd'; import DraggableContext from './draggable-context'; fdescribe('DraggableContext', () => { it('is wrapped in a DragDropContextContainer', () => { expect(DraggableContext.name).toBe('DragDropContextContainer'); }); it('has a DecoratedComponent pointing to the original component', () => { expect(DraggableContext.DecoratedComponent.name).toBe('DraggableContext'); }); });
JavaScript
0
@@ -121,10 +121,41 @@ t';%0A +import %7B mount %7D from 'enzyme';%0A %0A -f desc @@ -480,13 +480,378 @@ );%0A %7D); +%0A%0A describe('render', () =%3E %7B%0A it('renders this.props.children', () =%3E %7B%0A let wrapper = mount(%0A %3CDraggableContext%3E%0A %3Cdiv%3E%0A %3Cp%3EOne%3C/p%3E%0A %3Cp%3ETwo%3C/p%3E%0A %3C/div%3E%0A %3C/DraggableContext%3E%0A );%0A%0A expect(wrapper.find('div').length).toEqual(1);%0A expect(wrapper.find('p').length).toEqual(2);%0A %7D);%0A %7D); %0A%7D);%0A
eafcb68040b44a73e6c2d3605e75f75847d2dfef
update TableHeader
src/_TableHeader/TableHeader.js
src/_TableHeader/TableHeader.js
/** * @file TableHeader component * @author liangxiaojun(liangxiaojun@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import TableHeaderSortIcon from '../_TableHeaderSortIcon'; class TableHeader extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); } headerRenderer = () => { const {header, colIndex} = this.props; switch (typeof header) { case 'function': return header(colIndex); default: return header; } }; clickHandler = e => { e.preventDefault(); const {sortable, onSort} = this.props; sortable && onSort && onSort(); }; render() { const { className, style, header, hidden, sortable, sortProp, sort, sortAscIconCls, sortDescIconCls } = this.props, finalHeader = this.headerRenderer(), tableHeaderClassName = classNames('table-header', { sortable: sortable, hidden: hidden, [className]: className }); return ( <th className={tableHeaderClassName} style={style} title={typeof header === 'string' ? header : null} onClick={this.clickHandler}> <div className="table-header-inner"> {finalHeader} { sortable ? <TableHeaderSortIcon sort={sort} sortProp={sortProp} sortAscIconCls={sortAscIconCls} sortDescIconCls={sortDescIconCls}/> : null } </div> </th> ); } } TableHeader.propTypes = { className: PropTypes.string, style: PropTypes.object, header: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), colIndex: PropTypes.number, sortable: PropTypes.bool, sortProp: PropTypes.string, sort: PropTypes.object, sortAscIconCls: PropTypes.string, sortDescIconCls: PropTypes.string, hidden: PropTypes.bool, onSort: PropTypes.func }; TableHeader.defaultProps = { colIndex: 0, sortable: false, hidden: false }; export default TableHeader;
JavaScript
0
@@ -653,43 +653,16 @@ r = -e +() =%3E %7B%0A - e.preventDefault();%0A
539dde3653d78ccf4bbf2a67c109167c28f260e6
version up
vendor/ember-simple-token/register-version.js
vendor/ember-simple-token/register-version.js
Ember.libraries.register('Ember Simple Token', '1.1.2');
JavaScript
0
@@ -49,9 +49,9 @@ 1.1. -2 +3 ');%0A
69ee5277e50328bf2daa3ef21686dd96a2c58470
Fix error "Cannot read property 'min' of undefined"
src/models/axis.js
src/models/axis.js
/*! * VIZABI Axis Model (hook) */ (function () { "use strict"; var root = this; var Vizabi = root.Vizabi; var utils = Vizabi.utils; //warn client if d3 is not defined if (!Vizabi._require('d3')) { return; } //constant time formats var time_formats = { "year": d3.time.format("%Y"), "month": d3.time.format("%Y-%m"), "week": d3.time.format("%Y-W%W"), "day": d3.time.format("%Y-%m-%d"), "hour": d3.time.format("%Y-%m-%d %H"), "minute": d3.time.format("%Y-%m-%d %H:%M"), "second": d3.time.format("%Y-%m-%d %H:%M:%S") }; Vizabi.Model.extend('axis', { /** * Initializes the color hook * @param {Object} values The initial values of this model * @param parent A reference to the parent model * @param {Object} bind Initial events to bind */ init: function (values, parent, bind) { this._type = "axis"; values = utils.extend({ use: "value", unit: "", which: undefined, min: null, max: null }, values); this._super(values, parent, bind); }, /** * Validates a color hook */ validate: function () { var possibleScales = ["log", "linear", "time", "pow"]; if (!this.scaleType || (this.use === "indicator" && possibleScales.indexOf(this.scaleType) === -1)) { this.scaleType = 'linear'; } if (this.use !== "indicator" && this.scaleType !== "ordinal") { this.scaleType = "ordinal"; } //TODO a hack that kills the scale, it will be rebuild upon getScale request in model.js if (this.which_1 != this.which || this.scaleType_1 != this.scaleType) this.scale = null; this.which_1 = this.which; this.scaleType_1 = this.scaleType; if(this.scale && this._readyOnce && this.use=="indicator"){ if(this.min==null) this.min = this.scale.domain()[0]; if(this.max==null) this.max = this.scale.domain()[1]; if(this.min<=0 && this.scaleType=="log") this.min = 0.01; if(this.max<=0 && this.scaleType=="log") this.max = 10; // Max may be less than min // if(this.min>=this.max) this.min = this.max/2; if(this.min!=this.scale.domain()[0] || this.max!=this.scale.domain()[1]) this.scale.domain([this.min, this.max]); } }, /** * Gets the domain for this hook * @returns {Array} domain */ buildScale: function (margins) { var domain; var scaleType = this.scaleType || "linear"; if (typeof margins === 'boolean') { var res = margins; margins = {}; margins.min = res; margins.max = res; } if (this.scaleType == "time") { var limits = this.getLimits(this.which); this.scale = d3.time.scale().domain([limits.min, limits.max]); return; } switch (this.use) { case "indicator": var limits = this.getLimits(this.which), margin = (limits.max - limits.min) / 20; domain = [(limits.min - (margins.min ? margin : 0)), (limits.max + (margins.max ? margin : 0))]; if (scaleType == "log") { domain = [(limits.min - limits.min / 4), (limits.max + limits.max / 4)]; } break; case "property": domain = this.getUnique(this.which); break; case "value": default: domain = [this.which]; break; } if (this.min!=null && this.max!=null && scaleType !== 'ordinal') { domain = [this.min, this.max]; this.min = domain[0]; this.max = domain[1]; } this.scale = d3.scale[scaleType]().domain(domain); } }); }).call(this);
JavaScript
0
@@ -2530,16 +2530,73 @@ linear%22; +%0A if (margins === undefined)%0A margins = true; %0A%0A @@ -3130,16 +3130,26 @@ ins.min +&& margin ? margin @@ -3183,16 +3183,26 @@ ins.max +&& margin ? margin
b97fac279648ce2216a4f01cf6f1ec44e244ef08
Refresh the whole scrollbar when adapting to size
Source/Widget/Scrollbar.js
Source/Widget/Scrollbar.js
/* --- script: Scrollbar.js description: Scrollbars for everything license: MIT-style license. authors: Yaroslaff Fedin requires: - ART.Widget.Paint - ART.Widget.Section - ART.Widget.Button - Base/Widget.Trait.Slider provides: [ART.Widget.Scrollbar] ... */ ART.Widget.Scrollbar = new Class({ Includes: [ ART.Widget.Paint, Widget.Trait.Slider ], name: 'scrollbar', position: 'absolute', layout: { 'scrollbar-track#track': { 'scrollbar-thumb#thumb': {}, }, 'scrollbar-button#decrement': {}, 'scrollbar-button#increment': {} }, layered: { stroke: ['stroke'], background: ['fill', ['backgroundColor']], reflection: ['fill', ['reflectionColor']] }, options: { slider: { wheel: true } }, initialize: function() { this.parent.apply(this, arguments); this.setState(this.options.mode); }, adaptSize: function(size, old){ if (!size || $chk(size.height)) size = this.parentNode.size; var isVertical = (this.options.mode == 'vertical'); var other = isVertical ? 'horizontal' : 'vertical'; var prop = isVertical ? 'height' : 'width'; var Prop = prop.capitalize(); var setter = 'set' + Prop; var getter = 'getClient' + Prop; var value = size[prop]; if (isNaN(value) || !value) return; var invert = this.parentNode[other]; var scrolled = this.getScrolled(); $(scrolled).setStyle(prop, size[prop]) var ratio = size[prop] / $(scrolled)['scroll' + Prop] var delta = (!invert || invert.hidden ? 0 : invert.getStyle(prop)); this[setter](size[prop] - delta); var offset = 0; if (isVertical) { offset += this.track.offset.padding.top + this.track.offset.padding.bottom } else { offset += this.track.offset.padding.left + this.track.offset.padding.right } var track = size[prop] - this.increment[getter]() - this.decrement[getter]() - delta - ((this.style.current.strokeWidth || 0) * 2) - offset * 2 this.track[setter](track); this.track.thumb[setter](Math.ceil(track * ratio)) this.refresh(); this.parent.apply(this, arguments); }, inject: Macro.onion(function(widget) { this.adaptToSize(widget.size); }), onSet: function(value) { var prop = (this.options.mode == 'vertical') ? 'height' : 'width'; var direction = (this.options.mode == 'vertical') ? 'top' : 'left'; var result = (value / 100) * this.parentNode.element['scroll' + prop.capitalize()]; $(this.getScrolled())['scroll' + direction.capitalize()] = result; }, getScrolled: function() { if (!this.scrolled) { var parent = this; while ((parent = parent.parentNode) && !parent.getScrolled); this.scrolled = parent.getScrolled ? parent.getScrolled() : this.parentNode.element; } return this.scrolled; }, getTrack: function() { return $(this.track) }, getTrackThumb: function() { return $(this.track.thumb); }, hide: Macro.onion(function() { this.element.setStyle('display', 'none'); }), show: Macro.onion(function() { this.element.setStyle('display', 'block'); }) }) ART.Widget.Scrollbar.Track = new Class({ Extends: ART.Widget.Section, layered: { innerShadow: ['inner-shadow'] }, name: 'track', position: 'absolute' }); ART.Widget.Scrollbar.Thumb = new Class({ Extends: ART.Widget.Button, name: 'thumb' }); ART.Widget.Scrollbar.Button = new Class({ Extends: ART.Widget.Button, position: 'absolute' });
JavaScript
0
@@ -2090,16 +2090,20 @@ refresh( +true );%0A t
0e4adfa855d599636c70622af81d9475165a3515
Undo workaround for offline testing.
client/components/widget/query/data-view-service_test.js
client/components/widget/query/data-view-service_test.js
/** * @copyright Copyright 2014 Google Inc. 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 Tests for the dataViewService service. * @author joemu@google.com (Joe Allan Muharsky) */ goog.require('p3rf.perfkit.explorer.application.module'); goog.require('p3rf.perfkit.explorer.components.widget.data_viz.gviz.getGvizDataTable'); goog.require('p3rf.perfkit.explorer.components.widget.query.DataViewService'); goog.require('p3rf.perfkit.explorer.models.DataViewModel'); var _describe = function() {}; _describe('dataViewService', function() { var DataViewModel = p3rf.perfkit.explorer.models.DataViewModel; var svc, gvizDataViewMock, gvizDataTable; beforeEach(module('explorer')); beforeEach(inject(function(dataViewService, GvizDataTable) { svc = dataViewService; gvizDataTable = GvizDataTable; })); describe('create', function() { var dataTable; beforeEach(function() { var data = { cols: [ {id: 'date', label: 'Date', type: 'date'}, {id: 'value', label: 'Fake values 1', type: 'number'}, {id: 'value', label: 'Fake values 2', type: 'number'} ], rows: [ {c: [ {v: '2013/03/03 00:48:04'}, {v: 0.5}, {v: 3} ]}, {c: [ {v: '2013/03/04 00:50:04'}, {v: 0.1}, {v: 5} ]}, {c: [ {v: '2013/03/05 00:59:04'}, {v: 0.3}, {v: 1} ]}, {c: [ {v: '2013/03/06 00:50:04'}, {v: 0.7}, {v: 2} ]}, {c: [ {v: '2013/03/07 00:59:04'}, {v: 0.2}, {v: 6} ]} ] }; dataTable = new gvizDataTable(data); }); it('should return the correct dataViewJson.', function() { var model = new DataViewModel(); model.columns = [0, 2]; model.filter = [ { column: 1, minValue: 0, maxValue: 0.2 } ]; model.sort = [ { column: 2, desc: true } ]; var dataViewJson = svc.create(dataTable, model); var expectedDataViewJson = [ { columns: [0, 2], rows: [1, 4] }, { rows: [1, 0] } ]; expect(dataViewJson).toEqual(expectedDataViewJson); }); it('should return an error when an error occurred on columns property.', function() { var model = new DataViewModel(); model.columns = [-1]; var dataViewJson = svc.create(dataTable, model); expect(dataViewJson.error).toBeDefined(); expect(dataViewJson.error.property).toEqual('columns'); } ); it('should return an error when an error occurred on filter property.', function() { var model = new DataViewModel(); model.filter = [-1]; var dataViewJson = svc.create(dataTable, model); expect(dataViewJson.error).toBeDefined(); expect(dataViewJson.error.property).toEqual('filter'); } ); it('should return an error when an error occurred on sort property.', function() { var model = new DataViewModel(); model.sort = [-1]; var dataViewJson = svc.create(dataTable, model); expect(dataViewJson.error).toBeDefined(); expect(dataViewJson.error.property).toEqual('sort'); } ); }); });
JavaScript
0
@@ -1020,41 +1020,8 @@ );%0A%0A -var _describe = function() %7B%7D;%0A%0A_ desc
def49f76b0b9a0259aa3cb3e8bca5242f50d65be
Update LoadCSSJS.min.js
LoadCSSJS.min.js
LoadCSSJS.min.js
/*! Simple CSS JS loader asynchronously for all browsers by cara-tm.com, MIT Licence */ function LoadCSSJS(e,t,r){"use strict";var els="";-1==els.indexOf("["+e+"]")?(Loader(e,t,r),els+="["+e+"]"):alert("File "+e+" already added!")}function Loader(e,t,r){if("css"==t){var s=document.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute("href",e),r?"":r="all",s.setAttribute("media",r),s.setAttribute("type","text/css")}else if("js"==t){var s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",e)}if("undefined"!=typeof s){var a=document.getElementsByTagName("head");a=a[a.length-1],a.appendChild(s)}}
JavaScript
0
@@ -128,19 +128,17 @@ var -els +a =%22%22;-1== els. @@ -133,19 +133,17 @@ =%22%22;-1== -els +a .indexOf @@ -169,19 +169,17 @@ (e,t,r), -els +a +=%22%5B%22+e+
b5c5d531d169f974651b08d3000b541062f71390
Fix for unhandled promise on fresh db startup
core/server/data/migration/index.js
core/server/data/migration/index.js
var _ = require('underscore'), when = require('when'), series = require('when/sequence'), errors = require('../../errorHandling'), knex = require('../../models/base').Knex, defaultSettings = require('../default-settings'), Settings = require('../../models/settings').Settings, fixtures = require('../fixtures'), initialVersion = '000', defaultDatabaseVersion; // Default Database Version // The migration version number according to the hardcoded default settings // This is the version the database should be at or migrated to function getDefaultDatabaseVersion() { if (!defaultDatabaseVersion) { // This be the current version according to the software defaultDatabaseVersion = _.find(defaultSettings.core, function (setting) { return setting.key === 'databaseVersion'; }).defaultValue; } return defaultDatabaseVersion; } // Database Current Version // The migration version number according to the database // This is what the database is currently at and may need to be updated function getDatabaseVersion() { return knex.Schema.hasTable('settings').then(function (exists) { // Check for the current version from the settings table if (exists) { // Temporary code to deal with old databases with currentVersion settings return knex('settings') .where('key', 'databaseVersion') .orWhere('key', 'currentVersion') .select('value') .then(function (versions) { var databaseVersion = _.reduce(versions, function (memo, version) { if (isNaN(version.value)) { errors.throwError('Database version is not recognised'); } return parseInt(version.value, 10) > parseInt(memo, 10) ? version.value : memo; }, initialVersion); if (!databaseVersion || databaseVersion.length === 0) { // we didn't get a response we understood, assume initialVersion databaseVersion = initialVersion; } return databaseVersion; }); } return when.reject('Settings table does not exist'); }); } function setDatabaseVersion() { return knex('settings') .where('key', 'databaseVersion') .update({ 'value': defaultDatabaseVersion }); } module.exports = { getDatabaseVersion: getDatabaseVersion, // Check for whether data is needed to be bootstrapped or not init: function () { var self = this; // There are 4 possibilities: // 1. The database exists and is up-to-date // 2. The database exists but is out of date // 3. The database exists but the currentVersion setting does not or cannot be understood // 4. The database has not yet been created return getDatabaseVersion().then(function (databaseVersion) { var defaultVersion = getDefaultDatabaseVersion(); if (databaseVersion === defaultVersion) { // 1. The database exists and is up-to-date return when.resolve(); } if (databaseVersion < defaultVersion) { // 2. The database exists but is out of date return self.migrateUpFromVersion(databaseVersion); } if (databaseVersion > defaultVersion) { // 3. The database exists but the currentVersion setting does not or cannot be understood // In this case we don't understand the version because it is too high errors.logErrorAndExit( 'Your database is not compatible with this version of Ghost', 'You will need to create a new database' ); } }, function (err) { if (err === 'Settings table does not exist') { // 4. The database has not yet been created // Bring everything up from initial version. return self.migrateUpFreshDb(); } // 3. The database exists but the currentVersion setting does not or cannot be understood // In this case the setting was missing or there was some other problem errors.logErrorAndExit('There is a problem with the database', err.message || err); }); }, // ### Reset // Migrate from where we are down to nothing. reset: function () { var self = this; return getDatabaseVersion().then(function (databaseVersion) { // bring everything down from the current version return self.migrateDownFromVersion(databaseVersion); }, function () { // If the settings table doesn't exist, bring everything down from initial version. return self.migrateDownFromVersion(initialVersion); }); }, // Only do this if we have no database at all migrateUpFreshDb: function () { var migration = require('./' + initialVersion); return migration.up().then(function () { // Load the fixtures return fixtures.populateFixtures(); }).then(function () { // Initialise the default settings return Settings.populateDefaults(); }); }, // Migrate from a specific version to the latest migrateUpFromVersion: function (version, max) { var versions = [], maxVersion = max || this.getVersionAfter(getDefaultDatabaseVersion()), currVersion = version, tasks = []; // Aggregate all the versions we need to do migrations for while (currVersion !== maxVersion) { versions.push(currVersion); currVersion = this.getVersionAfter(currVersion); } // Aggregate all the individual up calls to use in the series(...) below tasks = _.map(versions, function (taskVersion) { return function () { try { var migration = require('./' + taskVersion); return migration.up(); } catch (e) { errors.logError(e); return when.reject(e); } }; }); // Run each migration in series return series(tasks).then(function () { // Finally update the databases current version return setDatabaseVersion(); }); }, migrateDownFromVersion: function (version) { var self = this, versions = [], minVersion = this.getVersionBefore(initialVersion), currVersion = version, tasks = []; // Aggregate all the versions we need to do migrations for while (currVersion !== minVersion) { versions.push(currVersion); currVersion = this.getVersionBefore(currVersion); } // Aggregate all the individual up calls to use in the series(...) below tasks = _.map(versions, function (taskVersion) { return function () { try { var migration = require('./' + taskVersion); return migration.down(); } catch (e) { errors.logError(e); return self.migrateDownFromVersion(initialVersion); } }; }); // Run each migration in series return series(tasks); }, // Get the following version based on the current getVersionAfter: function (currVersion) { var currVersionNum = parseInt(currVersion, 10), nextVersion; // Default to initialVersion if not parsed if (isNaN(currVersionNum)) { currVersionNum = parseInt(initialVersion, 10); } currVersionNum += 1; nextVersion = String(currVersionNum); // Pad with 0's until 3 digits while (nextVersion.length < 3) { nextVersion = "0" + nextVersion; } return nextVersion; }, getVersionBefore: function (currVersion) { var currVersionNum = parseInt(currVersion, 10), prevVersion; if (isNaN(currVersionNum)) { currVersionNum = parseInt(initialVersion, 10); } currVersionNum -= 1; prevVersion = String(currVersionNum); // Pad with 0's until 3 digits while (prevVersion.length < 3) { prevVersion = "0" + prevVersion; } return prevVersion; } };
JavaScript
0
@@ -2344,34 +2344,31 @@ -return when.reject +throw new Error ('Settin @@ -4041,16 +4041,31 @@ if (err +.message %7C%7C err === 'Se
cd3aa58988d8bdadfae7449052eeaa410bd385a6
Fix import bug in make-html command.
lib/cli/cmd/make-html.js
lib/cli/cmd/make-html.js
/* dendry * http://github.com/idmillington/dendry * * MIT License */ /*jshint indent:2 */ (function() { "use strict"; var path = require('path'); var fs = require('fs'); var handlebars = require('handlebars'); var async = require('async'); var browserify = require('browserify'); var uglify = require('uglify-js'); var utils = require('../utils'); var cmdCompile = require('./compile').cmd; var loadGameAndSource = function(data, callback) { utils.loadCompiledGame(data.compiledPath, function(err, game, json) { if (err) return callback(err); data.gameFile = json; data.game = game; callback(null, data); }); }; var browserifyUI = function(data, callback) { var b = browserify(); b.add(path.resolve(__dirname, "../../ui/browser.js")); b.bundle(function(err, buffer) { if (err) return callback(err); var str = buffer.toString(); data.browserify = str; return callback(null, data); }); }; var uglifyBundle = function(data, callback) { var gameFile = data.gameFile.toString(); var wrappedGameFile = JSON.stringify({compiled:gameFile}); var content = ["window.game="+wrappedGameFile+";", data.browserify]; var result = uglify.minify(content, {fromString: true, compress:{}}); data.code = content.join("");//result.code; return callback(null, data); }; var getTemplateDir = function(data, callback) { utils.getTemplatePath( data.template, "html", function(err, templateDir, name) { if (err) return callback(err); data.templateDir = templateDir; data.template = name; return callback(null, data); }); }; var getDestDir = function(data, callback) { data.destDir = path.join(data.projectDir, "out", "html"); callback(null, data); }; var notifyUser = function(data, callback) { console.log(("Creating HTML build in: "+data.destDir).grey); console.log(("Using template: "+data.template).grey); callback(null, data); }; var createHTML = function(data, callback) { fs.exists(data.destDir, function(exists) { if (exists) { console.log("Warning: Overwriting existing HTML content.".red); } utils.copyTemplate( data.templateDir, data.destDir, data, function(err) { if (err) return callback(err); else return(null, data); }); }); }; // ---------------------------------------------------------------------- // Make-HTML: Creates a playable HTML version of the game. // ---------------------------------------------------------------------- var cmdMakeHTML = new utils.Command("make-html"); cmdMakeHTML.createArgumentParser = function(subparsers) { var parser = subparsers.addParser(this.name, { help: "Make a project into a playable HTML page.", description: "Builds a HTML version of a game, compiling it first "+ "if it is out of date. The compilation uses a template which "+ "can be a predefined template, or the path to a directory. "+ "Templates use the handlebars templating system. The default "+ "HTML template (called 'default') compresses the browser interface "+ "and your game content and embeds it in a single HTML file, for the "+ "most portable game possible." }); parser.addArgument(['project'], { nargs: "?", help: "The project to compile (default: the current directory)." }); parser.addArgument(['-t', '--template'], { help: "A theme template to use (default: the 'default' theme). "+ "Can be the name of a built-in theme, or the path to a theme." }); parser.addArgument(['-f', '--force'], { action: "storeTrue", default: false, help: "Always recompiles, even if the compiled game is up to date." }); }; cmdMakeHTML.run = function(args, callback) { var getData = function(callback) { cmdCompile.run(args, callback); }; async.waterfall([getData, loadGameAndSource, browserifyUI, uglifyBundle, getTemplateDir, getDestDir, notifyUser, createHTML], callback); }; module.exports = { cmd: cmdMakeHTML }; }());
JavaScript
0
@@ -359,24 +359,76 @@ ../utils');%0A + var compiler = require('../../parsers/compiler');%0A var cmdCom @@ -518,21 +518,24 @@ ) %7B%0A -utils +compiler .loadCom @@ -1382,22 +1382,8 @@ %22%22); -//result.code; %0A
7ef05101fafd008f7886571b2595bc810025f4aa
Fix floatbar behaviour on "More threads/posts" clicks.
client/common/system/floatbar/floatbar.js
client/common/system/floatbar/floatbar.js
'use strict'; var _ = require('lodash'); N.wire.on('navigate.done', function () { var $window = $(window) , $floatbar = $('#floatbar') , isFixed = false , navTop; // Remove previous floatbar handlers if any. $window.off('scroll.floatbar'); if (0 === $floatbar.length) { // Do nothing if there's no floatbar. return; } navTop = $floatbar.offset().top; isFixed = false; function updateFloatbarState() { var scrollTop = $window.scrollTop(); if (scrollTop >= navTop && !isFixed) { isFixed = true; $floatbar.addClass('floatbar-fixed'); } else if (scrollTop <= navTop && isFixed) { isFixed = false; $floatbar.removeClass('floatbar-fixed'); } } updateFloatbarState(); $window.on('scroll.floatbar', _.throttle(updateFloatbarState, 100)); });
JavaScript
0
@@ -183,90 +183,8 @@ p;%0A%0A - // Remove previous floatbar handlers if any.%0A $window.off('scroll.floatbar');%0A%0A if @@ -744,8 +744,317 @@ ));%0A%7D);%0A +%0A%0AN.wire.on('navigate.exit', function () %7B%0A // Remove floatbar event handler.%0A $(window).off('scroll.floatbar');%0A%0A // Get floatbar back to the initial position to ensure next %60navigate.done%60%0A // handler will obtain correct floatbar offset on next call.%0A $('#floatbar').removeClass('floatbar-fixed');%0A%7D);%0A
b9dcce9939f2bcaeec8d4dbc4d8607e3b6ba856a
remove console statement
client/components/projects/ProjectItem.js
client/components/projects/ProjectItem.js
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { formatTime } from '../../helpers'; class ProjectItem extends React.Component { constructor(props) { super(props); this.state = { showInput: false, newName: '', }; this.handleNewName = this.handleNewName.bind(this); this.handleRenaming = this.handleRenaming.bind(this); this.handleShowInput = this.handleShowInput.bind(this); this.handleEnterButton = this.handleEnterButton.bind(this); } handleNewName(e) { this.setState({ newName: e.target.value }); } handleShowInput(name) { this.setState({ showInput: !this.state.showInput, newName: name, }); } handleRenaming(id, name) { this.props.renameMe(id, name); this.setState({ showInput: false, }); } handleEnterButton(event) { if (event.charCode === 13) { this.renameLink.click(); } } render() { const { project, onDelete } = this.props; const { newName, showInput } = this.state; const hideTaskName = this.state.showInput ? 'none' : ''; console.log(project); return ( <li style={{ paddingLeft: `${this.props.padding}px` }} className="projects__item" > <Link className="projects__item-title" style={{ display: `${hideTaskName}` }} to={`/projects/${project._id}`} > <span>{project.name}</span> <span className="pretty-time">{formatTime(project.timeSpent)}</span> </Link> {showInput ? ( <input type="text" value={newName} className="name-input" onKeyPress={this.handleEnterButton} onChange={this.handleNewName} /> ) : null} <div className="buttons-group"> {showInput ? ( <button onClick={() => this.handleRenaming(project._id, this.state.newName) } ref={link => { this.renameLink = link; }} className="button--info" > Ok </button> ) : null} <button onClick={() => this.handleShowInput(project.name)} className="button--info" > Edit </button> <button onClick={() => onDelete(project._id)} className="button--info button--danger" > Delete </button> </div> </li> ); } } ProjectItem.propTypes = { project: PropTypes.object.isRequired, onDelete: PropTypes.func.isRequired, renameMe: PropTypes.func.isRequired, padding: PropTypes.number.isRequired, }; export default ProjectItem;
JavaScript
0.000032
@@ -1129,34 +1129,8 @@ '';%0A - console.log(project);%0A
bd57d8643a445faf8777c4d2961821cfa8e56288
connect relevancy feature flag to experiment
share/spice/news/news.js
share/spice/news/news.js
(function (env) { "use strict"; env.ddg_spice_news = function (api_result) { if (!api_result || !api_result.results) { return Spice.failed('news'); } var useRelevancy = false, entityWords = [], goodStories = [], searchTerm = DDG.get_query().replace(/(?: news|news ?)/i, '').trim(), // Some sources need to be set by us. setSourceOnStory = function(story) { switch(story.syndicate) { case "Topsy": story.source = story.author || "Topsy"; break; case "NewsCred": if(story.source) { if(story.author) { story.source = story.source + " by " + story.author; } } else { story.source = "NewsCred"; } break; } }; if (useRelevancy) { // Words that we have to skip in DDG.isRelevant. var skip = [ "news", "headline", "headlines", "latest", "breaking", "update", "s:d", "sort:date" ]; if (Spice.news && Spice.news.entities && Spice.news.entities.length) { for (var j = 0, entity; entity = Spice.news.entities[j]; j++) { var tmpEntityWords = entity.split(" "); for (var k = 0, entityWord; entityWord = tmpEntityWords[k]; k++) { if (entityWord.length > 3) { entityWords.push(entityWord); } } } } } // Check if the title is relevant to the query. for(var i = 0, story; story = api_result.results[i]; i++) { if (!useRelevancy || DDG.isRelevant(story.title, skip)) { setSourceOnStory(story); story.sortableDate = parseInt(story.date || 0); goodStories.push(story); // additional news relevancy for entities. story need only // contain one word from one entity to be good. strict indexof // check though. } else if (entityWords.length > 0) { var storyOk = 0; var tmpStoryTitle = story.title.toLowerCase(); for (var k = 0, entityWord; entityWord = entityWords[k]; k++) { if (tmpStoryTitle.indexOf(entityWord) !== -1) { storyOk = 1; break; } } if (storyOk) { setSourceOnStory(story); goodStories.push(story); } } } if (useRelevancy && goodStories < 3) { return Spice.failed('news'); } Spice.add({ id: 'news', name: 'News', data: goodStories, ads: api_result.ads, meta: { idField: 'url', count: goodStories.length, searchTerm: searchTerm, itemType: 'Recent News', rerender: [ 'image' ] }, templates: { item: 'news_item' }, onItemShown: function(item) { if (!item.fetch_image || item.image || item.fetched_image) { return; } // set flag so we don't try to fetch more than once: item.fetched_image = 1; // try to fetch the image and set it on the model // which will trigger the tile to re-render with the image: $.getJSON('/f.js?o=json&i=1&u=' + item.url, function(meta) { if (meta && meta.image) { item.set('image', meta.image); } }); }, sort_fields: { date: function(a, b) { return b.sortableDate - a.sortableDate; } }, sort_default: 'date' }); } }(this));
JavaScript
0
@@ -212,13 +212,104 @@ y = -false +DDG.opensearch.installed.experiment === %22organic_ux%22 && DDG.opensearch.installed.variant === 'b' ,%0A
4bb1faa246cff960a7a28ea85d000bd69cd30b23
Fix bug with incorrect 'auto storage' calculation when more than 3
src/app/components/player/player.controller.js
src/app/components/player/player.controller.js
export default class PlayerController { constructor($rootScope, $scope, $log, $uibModal, _, toastr, playersApi, playerModel, websocket) { 'ngInject'; this.$rootScope = $rootScope; this.$scope = $scope; this.$log = $log.getInstance(this.constructor.name); this.$uibModal = $uibModal; this._ = _; this.toastr = toastr; this.playerModel = playerModel; // Used in template this.playersApi = playersApi; this.ws = websocket; this.$log.debug('constructor()', this); } $onInit() { this.$log.debug('$onInit()', this); this.$rootScope.$on('deck:action:winter', () => { this.$log.debug('deck:action:winter'); if (this.player.id === this.playerModel.model.player.id) { this.playerModel.showSpecialCards(); } }); } $onDestroy() { this.$log.debug('$onDestroy()', this); } canStoreCards(cardsSelected) { if (this.game.actionCard || !cardsSelected || cardsSelected.length !== 3) { return false; } let cardsMatch = this._.reduce(cardsSelected, (prev, current, index, array) => { let len = array.length, sameCard = prev.amount === current.amount; if (!prev) { // If the previous object is 'false', then cards don't match return false; } else if (sameCard && index === len - 1) { // Reached the end of the array and all values matched return true; } return sameCard ? current : false; }); return cardsMatch; } getCurrentPlayer() { return this.playerModel.model.player; } onStorageClick(evt) { let cardsSelected = this.player.cardsSelected; this.$log.debug('onStorageClick()', evt, cardsSelected, this); evt.preventDefault(); if (this.player.isActive && this.player.hasDrawnCard && this.canStoreCards(cardsSelected)) { this.storeCards(cardsSelected); } else { this.showStorage(this.player); } } onStorageAutoClick(evt) { evt.preventDefault(); if (this.player.isActive && !this.player.isFirstTurn) { // Filter out sets of 3 that have the same 'amount' this.playerModel.getCards() .then(res => { let cards = this._.filter(res.data, (o) => { return o.cardType === 'number'; }), numberCards = this._.groupBy(cards, (o) => { return o.amount; }), isStored = false; this.$log.info('numberCards -> ', numberCards); this._.forEach(numberCards, (cardsGroup) => { if (cardsGroup.length % 3 === 0) { this.storeCards(cardsGroup); isStored = true; } }); if (!isStored) { this.toastr.warning('No matching cards to store!'); } }, (err) => { this.$log.error(err); }); } } storeCards(cardsSelected) { let cardsInStorage = this.player.cardsInStorage, cardsInHand = this.player.cardsInHand, onSuccess = (res => { if (res.status == 200) { this.$log.debug(res); } }), onError = (err => { this.$log.error(err); }), cardIds = this._.map(cardsSelected, (obj) => { return obj.id; }); cardsInStorage.push(cardIds[0]); this._.pullAll(cardsInHand, cardIds); let plData = { cardsInHand: cardsInHand, cardsInStorage: cardsInStorage, score: this.player.score + cardsSelected[0].amount }; this.playersApi .update(this.player.id, plData) .then(onSuccess, onError); this.player.cardsSelected = []; } showStorage(pl) { let onClose = (data => { this.$log.debug('onClose()', data, this); }), onError = (err => { if (err !== 'backdrop click') { this.$log.error(err); } }); this.$log.debug('showStorage()', pl, this); let modal = this.$uibModal.open({ appendTo: angular.element(document).find('players'), component: 'storageModal', resolve: { player: () => { return this.player; } } }); modal.result.then(onClose, onError); } }
JavaScript
0.000001
@@ -2254,12 +2254,13 @@ log. -info +debug ('nu @@ -2347,19 +2347,42 @@ %7B%0A%09%09%09%09%09%09 -if +let numGroups = Math.floor (cardsGr @@ -2396,20 +2396,200 @@ gth -%25 3 === 0) %7B +/ 3),%0A%09%09%09%09%09%09%09numToStore = numGroups * 3;%0A%0A%09%09%09%09%09%09if (numToStore) %7B%0A%09%09%09%09%09%09%09let cardsToStore = this._.sampleSize(cardsGroup, numToStore);%0A%09%09%09%09%09%09%09this.$log.debug('cardsToStore -%3E ', cardsToStore); %0A%09%09%09 @@ -2613,21 +2613,23 @@ ds(cards -Group +ToStore );%0A%09%09%09%09%09
75aa9ab5476e62adbb5abbbaaf8cbfbf5933ea94
stop serving bower_components separately. bower_components are now inside the app directory (ionic/www) and hence get served along with the app directory.
server/boot/dev-assets.js
server/boot/dev-assets.js
var path = require('path'); module.exports = function(app) { if (!app.get('isDevEnv')) return; var serveDir = app.loopback.static; app.use(serveDir(projectPath('.tmp'))); app.use('/bower_components', serveDir(projectPath('client/bower_components'))); // app.use('/bower_components', serveDir(projectPath('bower_components'))); app.use('/lbclient', serveDir(projectPath('client/lbclient'))); }; function projectPath(relative) { return path.resolve(__dirname, '../..', relative); }
JavaScript
0
@@ -169,24 +169,26 @@ ('.tmp')));%0A +// app.use('/
7b3e3cbad51dfa66fa7aa81bb74a93419c3a19c9
add fn assertion to app.use(). Closes #337
lib/application.js
lib/application.js
/** * Module dependencies. */ var debug = require('debug')('koa:application'); var Emitter = require('events').EventEmitter; var compose = require('koa-compose'); var isJSON = require('koa-is-json'); var response = require('./response'); var context = require('./context'); var request = require('./request'); var onFinished = require('on-finished'); var Cookies = require('cookies'); var accepts = require('accepts'); var status = require('statuses'); var assert = require('assert'); var Stream = require('stream'); var http = require('http'); var only = require('only'); var co = require('co'); /** * Application prototype. */ var app = Application.prototype; /** * Expose `Application`. */ exports = module.exports = Application; /** * Initialize a new `Application`. * * @api public */ function Application() { if (!(this instanceof Application)) return new Application; this.env = process.env.NODE_ENV || 'development'; this.subdomainOffset = 2; this.poweredBy = true; this.middleware = []; this.context = Object.create(context); this.request = Object.create(request); this.response = Object.create(response); } /** * Inherit from `Emitter.prototype`. */ Application.prototype.__proto__ = Emitter.prototype; /** * Shorthand for: * * http.createServer(app.callback()).listen(...) * * @param {Mixed} ... * @return {Server} * @api public */ app.listen = function(){ debug('listen'); var server = http.createServer(this.callback()); return server.listen.apply(server, arguments); }; /** * Return JSON representation. * We only bother showing settings. * * @return {Object} * @api public */ app.inspect = app.toJSON = function(){ return only(this, [ 'subdomainOffset', 'poweredBy', 'env' ]); }; /** * Use the given middleware `fn`. * * @param {GeneratorFunction} fn * @return {Application} self * @api public */ app.use = function(fn){ assert('GeneratorFunction' == fn.constructor.name, 'app.use() requires a generator function'); debug('use %s', fn._name || fn.name || '-'); this.middleware.push(fn); return this; }; /** * Return a request handler callback * for node's native http server. * * @return {Function} * @api public */ app.callback = function(){ var mw = [respond].concat(this.middleware); var gen = compose(mw); var fn = co(gen); var self = this; if (!this.listeners('error').length) this.on('error', this.onerror); return function(req, res){ res.statusCode = 404; var ctx = self.createContext(req, res); onFinished(res, ctx.onerror); fn.call(ctx, ctx.onerror); } }; /** * Initialize a new context. * * @api private */ app.createContext = function(req, res){ var context = Object.create(this.context); var request = context.request = Object.create(this.request); var response = context.response = Object.create(this.response); context.app = request.app = response.app = this; context.req = request.req = response.req = req; context.res = request.res = response.res = res; request.ctx = response.ctx = context; request.response = response; response.request = request; context.onerror = context.onerror.bind(context); context.originalUrl = request.originalUrl = req.url; context.cookies = new Cookies(req, res, this.keys); context.accept = request.accept = accepts(req); return context; }; /** * Default error handler. * * @param {Error} err * @api private */ app.onerror = function(err){ assert(err instanceof Error, 'non-error thrown: ' + err); if (404 == err.status) return; if ('test' == this.env) return; var msg = err.stack || err.toString(); console.error(); console.error(msg.replace(/^/gm, ' ')); console.error(); }; /** * Response middleware. */ function *respond(next) { if (this.app.poweredBy) this.set('X-Powered-By', 'koa'); yield *next; // allow bypassing koa if (false === this.respond) return; var res = this.res; if (res.headersSent || !this.writable) return; var body = this.body; var code = this.status; // ignore body if (status.empty[code]) { // strip headers this.body = null; return res.end(); } if ('HEAD' == this.method) { if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body)); return res.end(); } // status body if (null == body) { this.type = 'text'; body = status[code]; if (body) this.length = Buffer.byteLength(body); return res.end(body); } // responses if (Buffer.isBuffer(body)) return res.end(body); if ('string' == typeof body) return res.end(body); if (body instanceof Stream) return body.pipe(res); // body: json body = JSON.stringify(body); this.length = Buffer.byteLength(body); res.end(body); }
JavaScript
0.000001
@@ -1926,16 +1926,22 @@ assert( +fn && 'Generat
ba0731679463757c03975f43fdbe63ed22675aff
Improve copy Grunt task structure
grunt/copy.js
grunt/copy.js
'use strict'; module.exports = { fonts: { files: [ { expand: true, cwd: '<%= paths.src %>/fonts/', src: ['**/*'], dest: '<%= paths.dist %>/fonts/', }, { expand: true, cwd: '<%= paths.bower %>/bootstrap/fonts/', src: ['**/*'], dest: '<%= paths.dist %>/fonts/', }, { expand: true, cwd: '<%= paths.bower %>/', src: ['ckeditor/**/*'], dest: '<%= paths.dist %>/vendor/', }, ], }, };
JavaScript
0.000033
@@ -344,32 +344,53 @@ nts/',%0A %7D,%0A + %5D,%0A vendor: %5B%0A %7B%0A
b2b4408b2401fba7d7ad971b69c40b5d47720ee4
optimize DraggableGridGroup
src/_DraggableGridGroup/DraggableGridGroup.js
src/_DraggableGridGroup/DraggableGridGroup.js
/** * @file DraggableGridGroup component * @author liangxiaojun(liangxiaojun@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {DragSource, DropTarget} from 'react-dnd'; import DraggableGridItem from '../_DraggableGridItem'; import Theme from '../Theme'; import DragDrop from '../_vendors/DragDrop'; const DRAG_GRID_GROUP_SYMBOL = Symbol('DRAG_GRID_GROUP'); @DropTarget(DRAG_GRID_GROUP_SYMBOL, DragDrop.getVerticalTarget(), connect => ({ connectDropTarget: connect.dropTarget() })) @DragSource(DRAG_GRID_GROUP_SYMBOL, DragDrop.getSource(), (connect, monitor) => ({ connectDragPreview: connect.dragPreview(), connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() })) export default class DraggableGridGroup extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); } render() { const { connectDragPreview, connectDragSource, connectDropTarget, isDragging, children, className, style, theme, text, iconCls, rightIconCls, anchorIconCls, isDraggableAnyWhere, disabled, isLoading, onMouseEnter, onMouseLeave } = this.props, listGroupClassName = (theme ? ` theme-${theme}` : '') + (isDragging ? ' dragging' : '') + (isDraggableAnyWhere ? ' draggable' : '') + (className ? ' ' + className : ''), anchorEl = <i className={'draggable-grid-group-anchor' + (anchorIconCls ? ' ' + anchorIconCls : '')} aria-hidden="true"></i>, el = connectDropTarget( <div className={'draggable-grid-group' + listGroupClassName} style={style} disabled={disabled || isLoading} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}> <DraggableGridItem className="draggable-grid-group-name" text={text} iconCls={iconCls} rightIconCls={rightIconCls} disabled={disabled} isLoading={isLoading} isGroupTitle={true} anchorIconCls={anchorIconCls} isDraggableAnyWhere={isDraggableAnyWhere}/> <div className="draggable-grid-group-item-wrapper"> {children} </div> { isDraggableAnyWhere ? anchorEl : connectDragSource(anchorEl) } </div> ); return isDraggableAnyWhere ? connectDragSource(el) : connectDragPreview(el); } }; DraggableGridGroup.propTypes = { connectDragPreview: PropTypes.func, connectDragSource: PropTypes.func, connectDropTarget: PropTypes.func, isDragging: PropTypes.bool, /** * The CSS class name of the grid button. */ className: PropTypes.string, /** * Override the styles of the grid button. */ style: PropTypes.object, /** * The theme of the grid button. */ theme: PropTypes.oneOf(Object.keys(Theme).map(key => Theme[key])), /** * The text value of the grid button. Type can be string or number. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The grid item's display text. Type can be string, number or bool. */ text: PropTypes.any, /** * If true, the grid button will be disabled. */ disabled: PropTypes.bool, /** * If true,the button will be have loading effect. */ isLoading: PropTypes.bool, /** * Use this property to display an icon. It will display on the left. */ iconCls: PropTypes.string, /** * Use this property to display an icon. It will display on the right. */ rightIconCls: PropTypes.string, /** * */ anchorIconCls: PropTypes.string, /** * */ isDraggableAnyWhere: PropTypes.bool, /** * */ onMouseEnter: PropTypes.func, /** * */ onMouseLeave: PropTypes.func }; DraggableGridGroup.defaultProps = { className: '', style: null, theme: Theme.DEFAULT, value: '', text: '', disabled: false, isLoading: false, iconCls: '', rightIconCls: '', anchorIconCls: 'fa fa-bars', isDraggableAnyWhere: false };
JavaScript
0.000002
@@ -811,24 +811,51 @@ omponent %7B%0A%0A + static Theme = Theme;%0A%0A construc
43b7930247c46cfa454f4ceed1f1e777235ea895
clear action
src/astroprint/static/js/app/views/terminal.js
src/astroprint/static/js/app/views/terminal.js
var TerminalView = Backbone.View.extend({ el: '#terminal-view', outputView: null, sourceId: null, events: { 'submit form': 'onSend', 'show': 'onShow', 'hide': 'onHide' }, initialize: function() { this.outputView = new OutputView(); this.sourceId = Math.floor((Math.random() * 100000)); //Generate a random sourceId app.eventManager.on("astrobox:PrinterResponse", _.bind(function(data) { if (data.sourceId == this.sourceId) { this.outputView.add('received', data.response); } }, this)); }, onClear: function(e) { e.preventDefault(); this.outputView.clear(); }, onSend: function(e) { e.preventDefault(); var sendField = this.$('input'); var command = sendField.val(); if (this.sourceId && command) { var loadingBtn = this.$('button.send').closest('.loading-button'); loadingBtn.addClass('loading'); $.ajax({ url: API_BASEURL + 'printer/comm/send', method: 'POST', data: { sourceId: this.sourceId, command: command } }) .done(_.bind(function(){ this.outputView.add('sent', command); }, this)) .fail(function(){ loadingBtn.addClass('error'); setTimeout(function(){ loadingBtn.removeClass('error'); }, 3000); }) .always(function(){ loadingBtn.removeClass('loading'); sendField.val(''); }); } return false; }, onShow: function() { this.$('input').focus(); $.ajax({ url: API_BASEURL + 'printer/comm/listen', method: 'POST' }) }, onHide: function() { $.ajax({ url: API_BASEURL + 'printer/comm/listen', method: 'DELETE' }); } }); var OutputView = Backbone.View.extend({ el: '#terminal-view .output-container', add: function(type, text) { switch(type) { case 'sent': text = '<div class="sent bold"><i class="icon-angle-right"></i>'+text+'</div>'; break; case 'received': text = '<div class="received"><i class="icon-angle-left"></i>'+text+'</div>'; break; } this.$el.append(text); this.$el.scrollTop(this.$el[0].scrollHeight); }, clear: function() { this.$el.empty(); } });
JavaScript
0.000001
@@ -180,16 +180,53 @@ 'onHide' +,%0A 'click button.clear': 'onClear' %0A %7D,%0A @@ -2325,14 +2325,15 @@ $el. -empty( +html('' );%0A
3e496394541b46fe822903c9b180419979fbd608
Remove dragStart event from example
examples/events/main.js
examples/events/main.js
import { default as React, Component } from 'react'; var ReactDOM = require('react-dom'); import { ReactiveBase } from '@appbaseio/reactivebase'; import { ReactiveMap } from '../../app/app.js'; class Main extends Component { constructor(props) { super(props); this.eventLists = [ 'onDragstart', 'onClick', 'onDblclick', 'onDrag', 'onDragstart', 'onDragend', 'onMousemove', 'onMouseout', 'onMouseover', 'onResize', 'onRightclick', 'onTilesloaded', 'onBoundsChanged', 'onCenterChanged', 'onProjectionChanged', 'onTiltChanged', 'onZoomChanged' ]; this.onIdle = this.onIdle.bind(this); this.onMouseover = this.onMouseover.bind(this); this.onMouseout = this.onMouseout.bind(this); this.onClick = this.onClick.bind(this); this.onDblclick = this.onDblclick.bind(this); this.onDrag = this.onDrag.bind(this); this.onDragstart = this.onDragstart.bind(this); this.onDragend = this.onDragend.bind(this); this.onMousemove = this.onMousemove.bind(this); this.onMouseout = this.onMouseout.bind(this); this.onMouseover = this.onMouseover.bind(this); this.onResize = this.onResize.bind(this); this.onRightclick = this.onRightclick.bind(this); this.onTilesloaded = this.onTilesloaded.bind(this); this.onBoundsChanged = this.onBoundsChanged.bind(this); this.onCenterChanged = this.onCenterChanged.bind(this); this.onProjectionChanged = this.onProjectionChanged.bind(this); this.onTiltChanged = this.onTiltChanged.bind(this); this.onZoomChanged = this.onZoomChanged.bind(this); } renderEventName() { return this.eventLists.map((eventName, index) => { return (<li key={index} ref={"event-"+eventName}>{eventName}</li>); }); } onIdle(mapRef) { this.eventActive('event-onIdle'); } onMouseover(mapRef) { this.eventActive('event-onMouseover'); } onMouseout(mapRef) { this.eventActive('event-onMouseout'); } onClick(mapRef) { this.eventActive('event-onClick'); } onDblclick(mapRef) { this.eventActive('event-onDblclick'); } onDrag(mapRef) { this.eventActive('event-onDrag'); } onDragstart(mapRef) { this.eventActive('event-onDragstart'); } onDragend(mapRef) { this.eventActive('event-onDragend'); } onMousemove(mapRef) { this.eventActive('event-onMousemove'); } onMouseout(mapRef) { this.eventActive('event-onMouseout'); } onMouseover(mapRef) { this.eventActive('event-onMouseover'); } onResize(mapRef) { this.eventActive('event-onResize'); } onRightclick(mapRef) { this.eventActive('event-onRightclick'); } onTilesloaded(mapRef) { this.eventActive('event-onTilesloaded'); } onBoundsChanged(mapRef) { this.eventActive('event-onBoundsChanged'); } onCenterChanged(mapRef) { this.eventActive('event-onCenterChanged'); } onProjectionChanged(mapRef) { this.eventActive('event-onProjectionChanged'); } onTiltChanged(mapRef) { this.eventActive('event-onTiltChanged'); } onZoomChanged(mapRef) { this.eventActive('event-onZoomChanged'); } onClick(mapRef) { this.eventActive('event-onClick'); } eventActive(eventRef) { $(this.refs[eventRef]).addClass('active'); setTimeout(() => { $(this.refs[eventRef]).removeClass('active'); }, 1500); } render() { return ( <div className="row m-0 h-100"> <ReactiveBase appname={this.props.config.appbase.appname} username={this.props.config.appbase.username} password={this.props.config.appbase.password} type={this.props.config.appbase.type} > <div className="col s12 m9 h-100"> <ReactiveMap appbaseField={this.props.mapping.location} defaultZoom={13} defaultCenter={{ lat: 37.74, lng: -122.45 }} historicalData={true} markerCluster={false} searchComponent="appbase" searchField={this.props.mapping.venue} mapStyle={this.props.mapStyle} autoCenter={true} searchAsMoveComponent={true} title="Events Example" MapStylesComponent={true} onIdle={this.onIdle} onMouseover={this.onMouseover} onMouseout={this.onMouseout} onClick={this.onClick} onDblclick={this.onDblclick} onDrag={this.onDrag} onDragstart={this.onDragstart} onDragend={this.onDragend} onMousemove={this.onMousemove} onMouseout={this.onMouseout} onMouseover={this.onMouseover} onResize={this.onResize} onRightclick={this.onRightclick} onBoundsChanged={this.onBoundsChanged} onCenterChanged={this.onCenterChanged} onProjectionChanged={this.onProjectionChanged} onTiltChanged={this.onTiltChanged} onZoomChanged={this.onZoomChanged} /> </div> <div className="col s12 m3"> <ul> {this.renderEventName()} </ul> </div> </ReactiveBase> </div> ); } } Main.defaultProps = { mapStyle: "Light Monochrome", mapping: { location: 'location' }, config: { "appbase": { "appname": "checkin", "username": "6PdfXag4h", "password": "b614d8fa-03d8-4005-b6f1-f2ff31cd0f91", "type": "city" } } }; ReactDOM.render(<Main />, document.getElementById('map'));
JavaScript
0
@@ -280,34 +280,16 @@ sts = %5B%0A -%09%09%09'onDragstart',%0A %09%09%09'onCl
615a2718f0d62205869b72e347cf909c8c43c4de
Add docstrings to the popover view
web_client/views/popover/AnnotationPopover.js
web_client/views/popover/AnnotationPopover.js
import _ from 'underscore'; import View from '../View'; import { restRequest } from 'girder/rest'; import ElementCollection from 'girder_plugins/large_image/collections/ElementCollection'; import annotationPopover from '../../templates/popover/annotationPopover.pug'; import '../../stylesheets/popover/annotationPopover.styl'; var AnnotationPopover = View.extend({ initialize(settings) { if (settings.debounce) { this.position = _.debounce(this.position, settings.debounce); } $('body').on('mousemove', '.h-image-view-body', (evt) => this.position(evt)); $('body').on('mouseout', '.h-image-view-body', () => this._hide()); $('body').on('mouseover', '.h-image-view-body', () => this._show()); this._hidden = !settings.visible; this._users = {}; this.collection = new ElementCollection(); this.listenTo(this.collection, 'add', this._getUser); this.listenTo(this.collection, 'all', this.render); }, render() { this.$el.html( annotationPopover({ annotations: _.uniq( this.collection.pluck('annotation'), _.property('id')), formatDate: this._formatDate, users: this._users }) ); this._show(); if (!this._visible()) { this._hide(); } this._height = this.$('.h-annotation-popover').height(); }, _getUser(model) { var id = model.get('annotation').get('creatorId'); if (!_.has(this._users, id)) { restRequest({ path: 'user/' + id }).then((user) => { this._users[id] = user; this.render(); }); } }, _formatDate(s) { var d = new Date(s); return d.toLocaleString(); }, _show() { if (this._visible()) { this.$el.removeClass('hidden'); } }, _hide() { this.$el.addClass('hidden'); }, _visible() { return !this._hidden && this.collection.length > 0; }, position(evt) { if (this._visible()) { this.$el.css({ left: evt.pageX + 5, top: evt.pageY - this._height / 2 }); } }, toggle(show) { this._hidden = !show; this.render(); } }); export default AnnotationPopover;
JavaScript
0
@@ -323,16 +323,336 @@ styl';%0A%0A +/**%0A * This view behaves like a bootstrap %22popover%22 that follows the mouse pointer%0A * over the image canvas and dynamically updates according to the features%0A * under the pointer.%0A *%0A * @param %7Bobject%7D %5Bsettings%5D%0A * @param %7Bnumber%7D %5Bsettings.debounce%5D%0A * Debounce time in ms for rerendering due to mouse movements%0A */%0A var Anno @@ -754,24 +754,25 @@ this. +_ position = _ @@ -782,24 +782,25 @@ bounce(this. +_ position, se @@ -898,16 +898,17 @@ =%3E this. +_ position @@ -1787,24 +1787,798 @@ ();%0A %7D,%0A%0A + /**%0A * Set the popover visibility state.%0A *%0A * @param %7Bboolean%7D %5Bshow%5D%0A * if true: show the popover%0A * if false: hide the popover%0A * if undefined: toggle the popover state%0A */%0A toggle(show) %7B%0A if (show === undefined) %7B%0A show = this._hidden;%0A %7D%0A this._hidden = !show;%0A this.render();%0A return this;%0A %7D,%0A%0A /**%0A * Check the local cache for the given creator. If it has not already been%0A * fetched, then send a rest request to get the user information and%0A * rerender the popover.%0A *%0A * As a consequence to avoid always rendering asyncronously, the user name%0A * will not be shown on the first render. In practice, this isn't usually%0A * noticeable.%0A */%0A _getUser @@ -2879,24 +2879,91 @@ %7D%0A %7D,%0A%0A + /**%0A * Format a Date object as a localized string.%0A */%0A _formatD @@ -3039,24 +3039,134 @@ ();%0A %7D,%0A%0A + /**%0A * Remove the hidden class on the popover element if this._visible()%0A * returns true.%0A */%0A _show() @@ -3256,24 +3256,77 @@ %7D%0A %7D,%0A%0A + /**%0A * Unconditionally hide popover.%0A */%0A _hide() @@ -3380,93 +3380,380 @@ -_visible() %7B%0A return !this._hidden && this.collection.length %3E 0;%0A %7D,%0A%0A +/**%0A * Determine if the popover should be visible. Returns true%0A * if there are active annotations under the mouse pointer and%0A * the label option is enabled.%0A */%0A _visible() %7B%0A return !this._hidden && this.collection.length %3E 0;%0A %7D,%0A%0A /**%0A * Reset the position of the popover to the position of the%0A * mouse pointer.%0A */%0A _ posi @@ -3939,88 +3939,8 @@ %7D%0A - %7D,%0A%0A toggle(show) %7B%0A this._hidden = !show;%0A this.render();%0A
828032d625d4246a1d4a86333e962d00e04bcfb6
test åäö
src/main/resources/client/components/SiteWrapper/SiteWrapper.js
src/main/resources/client/components/SiteWrapper/SiteWrapper.js
'use strict'; // Vendor var _assign = require('lodash/object/assign'); var Vue = require('vue'); var $ = require('jquery'); // Components var TechInfoWindow = require('components/TechInfoWindow/TechInfoWindow.js'); // Utils var AuthenticationUtil = require('utils/AuthenticationUtil/AuthenticationUtil.js'); var TechnicalInfoUtil = require('utils/TechnicalInfoUtil/TechnicalInfoUtil.js'); // CSS modules var styles = _assign( require('./SiteWrapper.css'), require('css/modules/Colors.less') ); /** * Site Wrapper Component */ var SiteWrapperMixin = { props: ['activity'], template: require('./SiteWrapper.html'), data: function() { return { authenticated: false, userModel: {}, _styles: styles, } }, components: { 'tech-info-window': TechInfoWindow }, events: { /* 'authenticate': function() { if(this.authenticated) { this.$broadcast('logged-in', this.userModel); } }, */ 'setTextTitle': function() { } }, ready: function() { /* // Authenticate Authenticationutil.authenticate(function(authenticated, userModel) { if(authenticated) { this.$set('authenticated', true); this.$set('userModel', userModel); this.$broadcast('logged-in', userModel); } }.bind(this)); */ AuthenticationUtil.authenticate(function(authenticated) { if (authenticated.isLoggedIn) { this.$set('authenticated', true); this.$set('userModel', authenticated); } }.bind(this)); // Set GitHub-image this.$els.githubImage1.src = this.$els.githubImage2.src = require('octicons/svg/mark-github.svg'); }, methods: { init: function() { }, checkLoggedInStatus: function() { AuthenticationUtil.authenticate(function(authenticated) { if (!authenticated.isLoggedIn) { var url = '/secure?return='; $(location).attr('href', url + window.location.href); } }); } } }; module.exports = SiteWrapperMixin;
JavaScript
0.000001
@@ -1424,16 +1424,48 @@ cated);%0A +%09%09%09%09console.log(authenticated);%0A %09%09%09%7D%09%0A%09%09
362901bbe5c73ac8c534675f84aab9e5a62aebd5
fix unknown error when showing details of expense from /expenses page
src/apps/expenses/components/PayExpenseBtn.js
src/apps/expenses/components/PayExpenseBtn.js
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, FormattedMessage } from 'react-intl'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; import { get } from 'lodash'; import withIntl from '../../../lib/withIntl'; import { isValidEmail } from '../../../lib/utils'; import SmallButton from '../../../components/SmallButton'; class PayExpenseBtn extends React.Component { static propTypes = { expense: PropTypes.object.isRequired, collective: PropTypes.object.isRequired, host: PropTypes.object, disabled: PropTypes.bool, paymentProcessorFeeInCollectiveCurrency: PropTypes.number, hostFeeInCollectiveCurrency: PropTypes.number, platformFeeInCollectiveCurrency: PropTypes.number, lock: PropTypes.func, unlock: PropTypes.func, }; constructor(props) { super(props); this.state = { loading: false, paymentProcessorFeeInCollectiveCurrency: 0, }; this.onClick = this.onClick.bind(this); this.messages = defineMessages({ 'paypal.missing': { id: 'expense.payoutMethod.paypal.missing', defaultMessage: 'Please provide a valid paypal email address', }, }); } async onClick() { const { expense, lock, unlock } = this.props; if (this.props.disabled) { return; } lock(); this.setState({ loading: true }); try { await this.props.payExpense( expense.id, this.props.paymentProcessorFeeInCollectiveCurrency, this.props.hostFeeInCollectiveCurrency, this.props.platformFeeInCollectiveCurrency, ); this.setState({ loading: false }); unlock(); } catch (e) { console.log('>>> payExpense error: ', e); const error = e.message && e.message.replace(/GraphQL error:/, ''); this.setState({ error, loading: false }); unlock(); } } render() { const { collective, expense, intl, host } = this.props; let disabled = this.state.loading, selectedPayoutMethod = expense.payoutMethod, title = '', error = this.state.error; if (expense.payoutMethod === 'paypal') { if (!isValidEmail(get(expense, 'user.paypalEmail')) && !isValidEmail(get(expense, 'user.email'))) { disabled = true; title = intl.formatMessage(this.messages['paypal.missing']); } else { const paypalPaymentMethod = host.paymentMethods && host.paymentMethods.find(pm => pm.service === 'paypal'); if (get(expense, 'user.paypalEmail') === get(paypalPaymentMethod, 'name')) { selectedPayoutMethod = 'other'; } } } if (get(collective, 'stats.balance') < expense.amount) { disabled = true; error = <FormattedMessage id="expense.pay.error.insufficientBalance" defaultMessage="Insufficient balance" />; } return ( <div className="PayExpenseBtn"> <style jsx> {` .PayExpenseBtn { align-items: flex-end; display: flex; flex-wrap: wrap; } .error { display: flex; align-items: center; color: red; font-size: 1.3rem; padding-left: 1rem; } .processorFee { margin-right: 1rem; max-width: 16rem; } .processorFee label { margin: 0; } `} </style> <style global jsx> {` .processorFee .inputField, .processorFee .form-group { margin: 0; } .processorFee .inputField { margin-top: 0.5rem; } `} </style> <SmallButton className="pay" onClick={this.onClick} disabled={this.props.disabled || disabled} title={title}> {selectedPayoutMethod === 'other' && ( <FormattedMessage id="expense.pay.manual.btn" defaultMessage="record as paid" /> )} {selectedPayoutMethod !== 'other' && ( <FormattedMessage id="expense.pay.btn" defaultMessage="pay with {paymentMethod}" values={{ paymentMethod: expense.payoutMethod }} /> )} </SmallButton> <div className="error">{error}</div> </div> ); } } const payExpenseQuery = gql` mutation payExpense( $id: Int! $paymentProcessorFeeInCollectiveCurrency: Int $hostFeeInCollectiveCurrency: Int $platformFeeInCollectiveCurrency: Int ) { payExpense( id: $id paymentProcessorFeeInCollectiveCurrency: $paymentProcessorFeeInCollectiveCurrency hostFeeInCollectiveCurrency: $hostFeeInCollectiveCurrency platformFeeInCollectiveCurrency: $platformFeeInCollectiveCurrency ) { id status collective { id stats { id balance } } } } `; const addMutation = graphql(payExpenseQuery, { props: ({ mutate }) => ({ payExpense: async ( id, paymentProcessorFeeInCollectiveCurrency, hostFeeInCollectiveCurrency, platformFeeInCollectiveCurrency, ) => { return await mutate({ variables: { id, paymentProcessorFeeInCollectiveCurrency, hostFeeInCollectiveCurrency, platformFeeInCollectiveCurrency, }, }); }, }), }); export default addMutation(withIntl(PayExpenseBtn));
JavaScript
0
@@ -2398,22 +2398,38 @@ Method = - +%0A get( host -. +, ' paymentM @@ -2434,16 +2434,18 @@ tMethods +') && host
ae543be4b0ce6807cbb6b70b09d28bd390290fad
add default export (#48)
leveldown.js
leveldown.js
const util = require('util') , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN , binding = require('bindings')('leveldown').leveldown , ChainedBatch = require('./chained-batch') , Iterator = require('./iterator') , fs = require('fs') function LevelDOWN (location) { if (!(this instanceof LevelDOWN)) return new LevelDOWN(location) AbstractLevelDOWN.call(this, location) this.binding = binding(location) } util.inherits(LevelDOWN, AbstractLevelDOWN) LevelDOWN.prototype._open = function (options, callback) { this.binding.open(options, callback) } LevelDOWN.prototype._close = function (callback) { this.binding.close(callback) } LevelDOWN.prototype._put = function (key, value, options, callback) { this.binding.put(key, value, options, callback) } LevelDOWN.prototype._get = function (key, options, callback) { this.binding.get(key, options, callback) } LevelDOWN.prototype._del = function (key, options, callback) { this.binding.del(key, options, callback) } LevelDOWN.prototype._chainedBatch = function () { return new ChainedBatch(this) } LevelDOWN.prototype._batch = function (operations, options, callback) { return this.binding.batch(operations, options, callback) } LevelDOWN.prototype.approximateSize = function (start, end, callback) { if (start == null || end == null || typeof start === 'function' || typeof end === 'function') { throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') } if (typeof callback !== 'function') { throw new Error('approximateSize() requires a callback argument') } start = this._serializeKey(start) end = this._serializeKey(end) this.binding.approximateSize(start, end, callback) } LevelDOWN.prototype.compactRange = function (start, end, callback) { this.binding.compactRange(start, end, callback) } LevelDOWN.prototype.getProperty = function (property) { if (typeof property != 'string') throw new Error('getProperty() requires a valid `property` argument') return this.binding.getProperty(property) } LevelDOWN.prototype._iterator = function (options) { return new Iterator(this, options) } LevelDOWN.destroy = function (location, callback) { if (arguments.length < 2) throw new Error('destroy() requires `location` and `callback` arguments') if (typeof location != 'string') throw new Error('destroy() requires a location string argument') if (typeof callback != 'function') throw new Error('destroy() requires a callback function argument') binding.destroy(location, function (err) { if (err) return callback(err) // On Windows, RocksDB silently fails to remove the directory because its // Logger, which is instantiated on destroy(), has an open file handle on a // LOG file. Destroy() removes this file but Windows won't actually delete // it until the handle is released. This happens when destroy() goes out of // scope, which disposes the Logger. So back in JS-land, we can again // attempt to remove the directory. This is merely a workaround because // arguably RocksDB should not instantiate a Logger or open a file at all. fs.rmdir(location, function (err) { if (err) { // Ignore this error in case there are non-RocksDB files left. if (err.code === 'ENOTEMPTY') return callback() if (err.code === 'ENOENT') return callback() return callback(err) } callback() }) }) } LevelDOWN.repair = function (location, callback) { if (arguments.length < 2) throw new Error('repair() requires `location` and `callback` arguments') if (typeof location != 'string') throw new Error('repair() requires a location string argument') if (typeof callback != 'function') throw new Error('repair() requires a callback function argument') binding.repair(location, callback) } module.exports = LevelDOWN
JavaScript
0
@@ -3997,16 +3997,36 @@ xports = + LevelDOWN.default = LevelDO
5b3a17e24efcf7603f0fd73d8eabd8fb516ee536
fix wrong this context (#4352)
lib/workers/repository/process/lookup/rollback.js
lib/workers/repository/process/lookup/rollback.js
const { logger } = require('../../../../logger'); const versioning = require('../../../../versioning'); module.exports = { getRollbackUpdate, }; function getRollbackUpdate(config, versions) { const { packageFile, versionScheme, depName, currentValue } = config; const version = versioning.get(versionScheme); // istanbul ignore if if (!version.isLessThanRange) { logger.info( { versionScheme }, 'Current version scheme does not support isLessThanRange()' ); return null; } const lessThanVersions = versions.filter(v => version.isLessThanRange(v, currentValue) ); // istanbul ignore if if (!lessThanVersions.length) { logger.info( { packageFile, depName, currentValue }, 'Missing version has nothing to roll back to' ); return null; } logger.info( { packageFile, depName, currentValue }, `Current version not found - rolling back` ); logger.debug( { dependency: depName, versions }, 'Versions found before rolling back' ); lessThanVersions.sort(version.sortVersions); const toVersion = lessThanVersions.pop(); // istanbul ignore if if (!toVersion) { logger.info('No toVersion to roll back to'); return null; } let fromVersion; const newValue = version.getNewValue( currentValue, 'replace', fromVersion, toVersion ); return { updateType: 'rollback', branchName: '{{{branchPrefix}}}rollback-{{{depNameSanitized}}}-{{{newMajor}}}.x', commitMessageAction: 'Roll back', isRollback: true, newValue, newMajor: version.getMajor(toVersion), semanticCommitType: 'fix', }; }
JavaScript
0.000011
@@ -1039,16 +1039,26 @@ ns.sort( +(a, b) =%3E version. @@ -1069,16 +1069,22 @@ Versions +(a, b) );%0A con
c2e3d2b8ca5ebe76fc12a08038bf9251c43bdbac
Fix time differences (add 1 second)
src/client/rest/RequestHandlers/Sequential.js
src/client/rest/RequestHandlers/Sequential.js
const RequestHandler = require('./RequestHandler'); /** * Handles API Requests sequentially, i.e. we wait until the current request is finished before moving onto * the next. This plays a _lot_ nicer in terms of avoiding 429's when there is more than one session of the account, * but it can be slower. * @extends {RequestHandler} */ module.exports = class SequentialRequestHandler extends RequestHandler { constructor(restManager) { super(restManager); /** * Whether this rate limiter is waiting for a response from a request * @type {Boolean} */ this.waiting = false; /** * The time difference between Discord's Dates and the local computer's Dates. A positive number means the local * computer's time is ahead of Discord's. * @type {Number} */ this.timeDifference = 0; } push(request) { super.push(request); this.handle(); } /** * Performs a request then resolves a promise to indicate its readiness for a new request * @param {APIRequest} item the item to execute * @returns {Promise<Object, Error>} */ execute(item) { return new Promise((resolve, reject) => { item.request.gen().end((err, res) => { if (res && res.headers) { this.requestLimit = res.headers['x-ratelimit-limit']; this.requestResetTime = Number(res.headers['x-ratelimit-reset']) * 1000; this.requestRemaining = Number(res.headers['x-ratelimit-remaining']); this.timeDifference = Date.now() - new Date(res.headers.date).getTime(); } if (err) { if (err.status === 429) { setTimeout(() => { this.waiting = false; resolve(); }, res.headers['retry-after']); } else { this.queue.shift(); this.waiting = false; item.reject(err); resolve(err); } } else { this.queue.shift(); const data = res && res.body ? res.body : {}; item.resolve(data); if (this.requestRemaining === 0) { setTimeout(() => { this.waiting = false; resolve(data); }, (this.requestResetTime - Date.now()) + this.timeDifference - 1000); } else { this.waiting = false; resolve(data); } } }); }); } handle() { super.handle(); if (this.waiting || this.queue.length === 0) { return; } this.waiting = true; const item = this.queue[0]; this.execute(item).then(() => this.handle()); } };
JavaScript
0.000059
@@ -2251,17 +2251,17 @@ ference -- ++ 1000);%0A
c0d9881a621bd39be404fb0905fd11843d0ff4c9
add memoryUsageHeap value
src/node/server.js
src/node/server.js
#!/usr/bin/env node 'use strict'; /** * This module is started with bin/run.sh. It sets up a Express HTTP and a Socket.IO Server. * Static file Requests are answered directly from this module, Socket.IO messages are passed * to MessageHandler and minfied requests are passed to minified. */ /* * 2011 Peter 'Pita' Martischka (Primary Technology Ltd) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const log4js = require('log4js'); log4js.replaceConsole(); /* * early check for version compatibility before calling * any modules that require newer versions of NodeJS */ const NodeVersion = require('./utils/NodeVersion'); NodeVersion.enforceMinNodeVersion('10.13.0'); NodeVersion.checkDeprecationStatus('10.13.0', '1.8.3'); const UpdateCheck = require('./utils/UpdateCheck'); const db = require('./db/DB'); const express = require('./hooks/express'); const hooks = require('../static/js/pluginfw/hooks'); const npm = require('npm/lib/npm.js'); const plugins = require('../static/js/pluginfw/plugins'); const settings = require('./utils/Settings'); const util = require('util'); let started = false; let stopped = false; exports.start = async () => { if (started) return express.server; started = true; if (stopped) throw new Error('restart not supported'); // Check if Etherpad version is up-to-date UpdateCheck.check(); // start up stats counting system const stats = require('./stats'); stats.gauge('memoryUsage', () => process.memoryUsage().rss); await util.promisify(npm.load)(); try { await db.init(); await plugins.update(); console.info(`Installed plugins: ${plugins.formatPluginsWithVersion()}`); console.debug(`Installed parts:\n${plugins.formatParts()}`); console.debug(`Installed hooks:\n${plugins.formatHooks()}`); await hooks.aCallAll('loadSettings', {settings}); await hooks.aCallAll('createServer'); } catch (e) { console.error(`exception thrown: ${e.message}`); if (e.stack) console.log(e.stack); process.exit(1); } process.on('uncaughtException', exports.exit); /* * Connect graceful shutdown with sigint and uncaught exception * * Until Etherpad 1.7.5, process.on('SIGTERM') and process.on('SIGINT') were * not hooked up under Windows, because old nodejs versions did not support * them. * * According to nodejs 6.x documentation, it is now safe to do so. This * allows to gracefully close the DB connection when hitting CTRL+C under * Windows, for example. * * Source: https://nodejs.org/docs/latest-v6.x/api/process.html#process_signal_events * * - SIGTERM is not supported on Windows, it can be listened on. * - SIGINT from the terminal is supported on all platforms, and can usually * be generated with <Ctrl>+C (though this may be configurable). It is not * generated when terminal raw mode is enabled. */ process.on('SIGINT', exports.exit); // When running as PID1 (e.g. in docker container) allow graceful shutdown on SIGTERM c.f. #3265. // Pass undefined to exports.exit because this is not an abnormal termination. process.on('SIGTERM', () => exports.exit()); // Return the HTTP server to make it easier to write tests. return express.server; }; exports.stop = async () => { if (stopped) return; stopped = true; console.log('Stopping Etherpad...'); await new Promise(async (resolve, reject) => { const id = setTimeout(() => reject(new Error('Timed out waiting for shutdown tasks')), 3000); await hooks.aCallAll('shutdown'); clearTimeout(id); resolve(); }); }; exports.exit = async (err) => { let exitCode = 0; if (err) { exitCode = 1; console.error(err.stack ? err.stack : err); } try { await exports.stop(); } catch (err) { exitCode = 1; console.error(err.stack ? err.stack : err); } process.exit(exitCode); }; if (require.main === module) exports.start();
JavaScript
0
@@ -1991,16 +1991,88 @@ ().rss); +%0A stats.gauge('memoryUsageHeap', () =%3E process.memoryUsage().heapUsed); %0A%0A awai
928ce8b8f980c89e9419f2174f7efa6dabf14334
update delete user JSON message
lib/controllers/users.js
lib/controllers/users.js
const express = require('express'); const router = express.Router(); // eslint-disable-line new-cap const async = require('async'); const UserModel = require('../models/user'); const authenticate = require('../middlewares/authenticate'); const authorise = require('../middlewares/authorise'); router.use('/users', authenticate); // Create user router.post('/users', authorise('admin')); router.post('/users', (req, res) => { UserModel.create(req.body, (err, user) => { if (err) { res.json({ status: 'fail', meta: { message: 'The user could not be created. Check validation.', validation: err.errors, }, data: null, }); } else { const userObj = user.toObject(); delete userObj.password; res.json({ status: 'success', meta: { message: 'The user was created.', }, data: userObj, }); } }); }); // List users router.get('/users', authorise('admin')); router.get('/users', (req, res) => { const page = req.query.page || 1; const limit = 20; async.parallel({ total: function total(cb) { UserModel.count(cb); }, users: function users(cb) { UserModel .find() .select('name username') .skip(limit * (page - 1)) .limit(limit) .lean() .exec(cb); }, }, (err, result) => { if (err) { res.status(500).json({ status: 'fail', meta: { message: 'The query could not be executed.', }, data: null, }); } else { res.json({ status: 'success', meta: { paginate: { total: result.total, previous: ((page > 1) ? page - 1 : null), next: (((limit * page) < result.total) ? page + 1 : null), }, }, data: result.users, }); } }); }); // Get current user router.get('/users/me', (req, res) => { UserModel.findById(req.jwt.id, (err, user) => { if (err) { res.json({ status: 'error', meta: { message: 'User information could not be found.', }, data: null, }); } else if (user === null) { res.json({ status: 'fail', meta: { message: 'User information could not be found.', }, data: null, }); } else { const userObj = user.toObject(); delete userObj.password; res.json({ status: 'success', meta: { message: 'The user was found.', }, data: userObj, }); } }); }); // Get user router.get('/users/:user', (req, res) => { if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) { return res.json({ status: 'fail', meta: { message: 'You are not authorised.', }, data: null, }); } UserModel.findById(req.params.user, (err, user) => { if (err) { res.json({ status: 'error', meta: { message: 'User information could not be found.', }, data: null, }); } else if (user === null) { res.json({ status: 'fail', meta: { message: 'User information could not be found.', }, data: null, }); } else { const userObj = user.toObject(); delete userObj.password; res.json({ status: 'success', meta: { message: 'The user was found.', }, data: userObj, }); } }); }); // Update user router.put('/users/:user', (req, res) => { if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) { return res.json({ status: 'fail', meta: { message: 'You are not authorised.', }, data: null, }); } UserModel.findById(req.params.user, (err, user) => { if (err) { res.json({ status: 'fail', meta: { message: 'The user could not be updated.', }, data: null, }); } else if (user === null) { res.json({ status: 'fail', meta: { message: 'The user was not found and could not be updated.', }, data: null, }); } else { user.set(req.body).save((saveErr, updatedUser) => { if (saveErr) { res.json({ status: 'fail', meta: { message: 'The user could not be updated. Check validation.', validation: saveErr.errors, }, data: null, }); } else { const userObj = updatedUser.toObject(); delete userObj.password; res.json({ status: 'success', meta: { message: 'The user was updated.', }, data: userObj, }); } }); } }); }); // Delete user router.delete('/users/:user', (req, res) => { if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) { return res.json({ status: 'fail', meta: { message: 'You are not authorised.', }, data: null, }); } UserModel.findByIdAndRemove(req.params.user, err => { if (err) { res.json({ status: 'error', meta: { message: 'The user could not be updated.', }, data: null, }); } else { res.json({ status: 'success', meta: { message: 'The user was deleted', }, data: null, }); } }); }); module.exports = router;
JavaScript
0.000001
@@ -5333,36 +5333,36 @@ er could not be -upda +dele ted.',%0A %7D
1eeee314affb486acc249d670452063b78e42e49
refactor the Index module for readability and testability
lib/Index.js
lib/Index.js
'use strict'; const path = require('path'); const defaults = require('defa'); const Sequelize = require('sequelize'); class Index { constructor(options) { defaults(options, { 'filename': () => path.join(process.cwd(), '.index') }); this.prepareDb(options.filename); } sync() { if (!this.ready) this.ready = this.Result.sync(); return this.ready; } log() { // do nothing // TODO log it somewhere } /** * Prepare the database and insert models and stuff * @param {String} filename * @returns {Promise} */ prepareDb(filename) { const sequelize = new Sequelize('cachething', 'carrier', null, { 'dialect': 'sqlite', 'storage': filename, 'logging': msg => this.log(msg) }); this.db = sequelize; this.Result = sequelize.define('Result', { action: Sequelize.STRING, fileHash: Sequelize.STRING, outputHash: Sequelize.STRING, created: Sequelize.BIGINT, expires: Sequelize.BIGINT, fileName: Sequelize.STRING, compressed: Sequelize.BOOLEAN, fileSize: Sequelize.BIGINT, runtime: Sequelize.BIGINT }); } } module.exports = Index;
JavaScript
0.000004
@@ -18,14 +18,24 @@ nst -path +%7Bnoop, defaults%7D @@ -45,19 +45,21 @@ equire(' -pat +lodas h');%0Acon @@ -61,24 +61,34 @@ ;%0Aconst -defaults +path = requ @@ -92,20 +92,20 @@ equire(' -defa +path ');%0Acons @@ -116,16 +116,26 @@ quelize + = requir @@ -162,24 +162,62 @@ ss Index %7B%0A%0A + /**%0A * @param options%0A */%0A construc @@ -239,16 +239,26 @@ %0A + options = default @@ -286,17 +286,16 @@ -' filename ': ( @@ -294,16 +294,9 @@ name -' : - () =%3E pat @@ -330,34 +330,85 @@ ex') -%0A %7D);%0A%0A this +,%0A log: noop,%0A %7D);%0A%0A const %7Bdb, Result%7D = Index .pre @@ -425,152 +425,185 @@ ions -.filename );%0A +%0A -%7D%0A%0A -sync() %7B%0A if (!this.ready) +this.db = db;%0A this.Result = Result; %0A +%7D%0A%0A - this.ready = this.Result.sync();%0A +/**%0A * Prepare the %22Result%22 collection for mutations %0A +*%0A + * @ return - this.ready; +s %7BPromise%7D %0A -%7D%0A + */ %0A -log +sync () %7B @@ -615,54 +615,84 @@ -// do nothing%0A // TODO log it somewhere +if (!this.ready) this.ready = this.Result.sync();%0A return this.ready; %0A @@ -734,36 +734,15 @@ base - and insert models and stuff +%0A * %0A @@ -761,16 +761,24 @@ String%7D +options. filename @@ -786,32 +786,99 @@ * @ -returns %7BPromise +param %7BFunction%7D options.log%0A *%0A * @returns %7B%7Bdb: Sequelize, result: Model%7D %7D%0A * @@ -883,16 +883,23 @@ */%0A +static prepareD @@ -900,24 +900,23 @@ epareDb( -filename +options ) %7B%0A%0A @@ -926,25 +926,18 @@ const -sequelize +db = new S @@ -1034,16 +1034,24 @@ orage': +options. filename @@ -1079,28 +1079,20 @@ g': -msg =%3E this.log(msg) +options.log, %0A @@ -1113,61 +1113,273 @@ -this.db = sequelize;%0A%0A this.Result = sequelize +const Result = Index.defineResultModel(db);%0A%0A return %7Bdb, Result%7D;%0A %7D%0A%0A /**%0A * Define the %22Result%22 model on the given database instance%0A * @param db%0A * @returns %7B*%7Cvoid%7CModel%7C%7B%7D%7D%0A */%0A static defineResultModel(db) %7B%0A%0A return db .def
551054d702cd378e598dbbdee9731e540b9acf42
Remove comment
lib/core/shared/store.js
lib/core/shared/store.js
/* * Kuzzle, a backend software, self-hostable and ready to use * to power modern apps * * Copyright 2015-2020 Kuzzle * mailto: support AT kuzzle.io * website: http://kuzzle.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const { Mutex } = require('../../util/mutex'); const { promiseAllN } = require('../../util/async'); const kerror = require('../../kerror'); const { getESIndexDynamicSettings } = require('../../util/esRequest'); /** * Wrapper around the document store. * Once instantiated, this class can only access the index passed in the * constructor */ class Store { /** * @param {Kuzzle} kuzzle * @param {String} index * @param {storeScopeEnum} scope */ constructor (index, scope) { this.index = index; this.scope = scope; const methodsMapping = { count: `core:storage:${scope}:document:count`, create: `core:storage:${scope}:document:create`, createCollection: `core:storage:${scope}:collection:create`, createOrReplace: `core:storage:${scope}:document:createOrReplace`, delete: `core:storage:${scope}:document:delete`, deleteByQuery: `core:storage:${scope}:document:deleteByQuery`, deleteCollection: `core:storage:${scope}:collection:delete`, deleteFields: `core:storage:${scope}:document:deleteFields`, deleteIndex: `core:storage:${scope}:index:delete`, exists: `core:storage:${scope}:document:exist`, get: `core:storage:${scope}:document:get`, getMapping: `core:storage:${scope}:mappings:get`, getSettings: `core:storage:${scope}:collection:settings:get`, mExecute: `core:storage:${scope}:document:mExecute`, mGet: `core:storage:${scope}:document:mGet`, refreshCollection: `core:storage:${scope}:collection:refresh`, replace: `core:storage:${scope}:document:replace`, search: `core:storage:${scope}:document:search`, truncateCollection: `core:storage:${scope}:collection:truncate`, update: `core:storage:${scope}:document:update`, updateByQuery: `core:storage:${scope}:document:updateByQuery`, updateCollection: `core:storage:${scope}:collection:update`, updateMapping: `core:storage:${scope}:mappings:update`, }; for (const [method, event] of Object.entries(methodsMapping)) { this[method] = (...args) => global.kuzzle.ask(event, this.index, ...args); } // the scroll and multiSearch method are special: they doesn't need an index parameter // we keep them for ease of use this.scroll = (scrollId, opts) => global.kuzzle.ask( `core:storage:${scope}:document:scroll`, scrollId, opts); this.multiSearch = (targets, searchBody, opts) => global.kuzzle.ask( `core:storage:${scope}:document:multiSearch`, targets, searchBody, opts ); } /** * Initialize the index, and creates provided collections * * @param {Object} collections - List of collections with mappings to create * * @returns {Promise} */ async init (collections = {}) { const creatingMutex = new Mutex(`Store.init(${this.index})`, { timeout: 0, ttl: 30000, }); const creatingLocked = await creatingMutex.lock(); if (creatingLocked) { try { await this.createCollections(collections, { indexCacheOnly: false }); } finally { await creatingMutex.unlock(); } } else { // Ensure that cached collection are used after being properly // created by a kuzzle cluster const cachingMutex = new Mutex(`Store.init(${this.index})`, { timeout: -1, ttl: 30000, }); await cachingMutex.lock(); cachingMutex.unlock(); await this.createCollections(collections, { indexCacheOnly: true }); } } /** * Creates collections with the provided mappings * * @param {Object} collections - collections with mappings * * @returns {Promise} */ createCollections ( collections, { indexCacheOnly = false } = {} ) { return promiseAllN( Object.entries(collections).map( ([collection, config]) => async () => { // @deprecated if (config.mappings !== undefined && config.settings !== undefined) { // @deprecated const isConfigDeprecated = config.settings.number_of_shards === undefined && config.settings.number_of_replicas === undefined; if (indexCacheOnly) { return global.kuzzle.ask( `core:storage:${this.scope}:collection:create`, this.index, collection, // @deprecated isConfigDeprecated ? { mappings: config.mappings } : config, { indexCacheOnly }); } const exist = await global.kuzzle.ask( `core:storage:${this.scope}:collection:exist`, this.index, collection); if (exist) { // @deprecated const dynamicSettings = (isConfigDeprecated) ? null : getESIndexDynamicSettings(config.settings); const existingSettings = await global.kuzzle.ask( `core:storage:${this.scope}:collection:settings:get`, this.index, collection); if (! isConfigDeprecated && parseInt(existingSettings.number_of_shards) !== config.settings.number_of_shards ) { if (global.NODE_ENV === 'development') { throw kerror.get( 'storage', 'wrong_collection_number_of_shards', collection, this.index, this.scope, 'number_of_shards', config.settings.number_of_shards, existingSettings.number_of_shards); } global.kuzzle.log.warn([ 'Attempt to recreate', `an existing collection ${collection}`, `of index ${this.index} of scope ${this.scope}`, 'with non matching', 'static setting : number_of_shards', `at ${config.settings.number_of_shards} while existing one`, `is at ${existingSettings.number_of_shards}`, ].join('\n')); } // Create call will update collection and cache it internally return global.kuzzle.ask( `core:storage:${this.scope}:collection:create`, this.index, collection, // @deprecated (isConfigDeprecated) ? { mappings: config.mappings } : { mappings: config.mappings, settings: dynamicSettings }, ); } return global.kuzzle.ask( `core:storage:${this.scope}:collection:create`, this.index, collection, // @deprecated isConfigDeprecated ? { mappings: config.mappings } : config, { indexCacheOnly }); } // @deprecated return global.kuzzle.ask( `core:storage:${this.scope}:collection:create`, this.index, collection, { mappings: config }, { indexCacheOnly }); } ), 10 ); } } module.exports = Store;
JavaScript
0
@@ -6963,84 +6963,8 @@ %7D%0A%0A - // Create call will update collection and cache it internally%0A @@ -7311,24 +7311,65 @@ Settings %7D,%0A + %7B indexCacheOnly: true %7D%0A
be75c469b7d90952e89a9ee7c87ea7ad017cd104
Allow alias exploding
plugins/aliases.js
plugins/aliases.js
// This is the aliases plugin // One must not run this plugin with the queue/smtp_proxy plugin. var Address = require('address-rfc2821').Address; exports.register = function () { this.inherits('queue/discard'); this.register_hook('rcpt','aliases'); }; exports.aliases = function (next, connection, params) { var plugin = this; var config = this.config.get('aliases', 'json') || {}; var rcpt = params[0].address(); var user = params[0].user; var host = params[0].host; var match = user.split("-", 1); var action = "<missing>"; if (config[rcpt]) { action = config[rcpt].action || action; match = rcpt; switch (action.toLowerCase()) { case 'drop': _drop(plugin, connection, rcpt); break; case 'alias': _alias(plugin, connection, match, config[match], host); break; default: connection.loginfo(plugin, "unknown action: " + action); } } if (config['@'+host]) { action = config['@'+host].action || action; match = '@'+host; switch (action.toLowerCase()) { case 'drop': _drop(plugin, connection, '@'+host); break; case 'alias': _alias(plugin, connection, match, config[match], host); break; default: connection.loginfo(plugin, "unknown action: " + action); } } if (config[user] || config[match[0]]) { if (config[user]) { action = config[user].action || action; match = user; } else { action = config[match[0]].action || action; match = match[0]; } switch (action.toLowerCase()) { case 'drop': _drop(plugin, connection, rcpt); break; case 'alias': _alias(plugin, connection, match, config[match], host); break; default: connection.loginfo(plugin, "unknown action: " + action); } } next(); }; function _drop(plugin, connection, rcpt) { connection.logdebug(plugin, "marking " + rcpt + " for drop"); connection.transaction.notes.discard = true; } function _alias(plugin, connection, key, config, host) { var to; var toAddress; if (config.to) { if (config.to.search("@") !== -1) { to = config.to; } else { to = config.to + '@' + host; } connection.logdebug(plugin, "aliasing " + connection.transaction.rcpt_to + " to " + to); toAddress = new Address('<' + to + '>'); connection.transaction.rcpt_to.pop(); connection.transaction.rcpt_to.push(toAddress); } else { connection.loginfo(plugin, 'alias failed for ' + key + ', no "to" field in alias config'); } }
JavaScript
0.000005
@@ -2422,16 +2422,20 @@ ddress;%0A + %0A if @@ -2444,24 +2444,444 @@ onfig.to) %7B%0A + if (Array.isArray(config.to)) %7B%0A connection.logdebug(plugin, %22aliasing %22 + connection.transaction.rcpt_to + %22 to %22 + config.to);%0A connection.transaction.rcpt_to.pop();%0A for (var i = 0, len = config.to.length; i %3C len; i++) %7B%0A toAddress = new Address('%3C' + config.to%5Bi%5D + '%3E');%0A connection.transaction.rcpt_to.push(toAddress);%0A %7D%0A %7D else %7B%0A if ( @@ -2908,24 +2908,28 @@ ) !== -1) %7B%0A + @@ -2951,34 +2951,30 @@ %0A - %7D%0A - +%7D else %7B%0A @@ -2957,32 +2957,36 @@ %7D else %7B%0A + to = @@ -3010,35 +3010,55 @@ + host;%0A -%7D%0A%0A + %7D%0A %0A connecti @@ -3091,16 +3091,20 @@ ing %22 +%0A + @@ -3154,25 +3154,40 @@ + to);%0A -%0A + %0A toAddres @@ -3170,32 +3170,33 @@ %0A + toAddress = new @@ -3220,32 +3220,36 @@ + '%3E');%0A + connection.trans @@ -3270,32 +3270,36 @@ .pop();%0A + + connection.trans @@ -3326,24 +3326,28 @@ toAddress);%0A + %7D%0A el @@ -3343,16 +3343,18 @@ %7D%0A + %7D else %7B%0A
70fc4295de4e9123f90bbf9e18749d990e2da403
Fix indentation
simplePagination.spec.js
simplePagination.spec.js
'use strict'; describe('Simple Pagination', function() { var pagination; // load the app beforeEach(module('SimplePagination')); // get service beforeEach(inject(function(Pagination) { pagination = Pagination.getNew(); })); it('should paginate', function() { pagination.numPages = 2; expect(pagination.page).toBe(0); pagination.nextPage(); expect(pagination.page).toBe(1); pagination.prevPage(); expect(pagination.page).toBe(0); }); it('should not paginate outside min and max page', function() { pagination.numPages = 2; pagination.page = 0; pagination.prevPage(); expect(pagination.page).toBe(0); pagination.page = 1; pagination.nextPage(); expect(pagination.page).toBe(1); }); it('should jump to a given page id', function() { pagination.numPages = 3; expect(pagination.page).toBe(0); pagination.toPageId(2); expect(pagination.page).toBe(2); }); });
JavaScript
0.017244
@@ -52,17 +52,18 @@ on() %7B%0A%0A -%09 + var pagi @@ -71,17 +71,18 @@ ation;%0A%0A -%09 + // load @@ -89,17 +89,18 @@ the app%0A -%09 + beforeEa @@ -132,17 +132,18 @@ on'));%0A%0A -%09 + // get s @@ -150,17 +150,18 @@ ervice %0A -%09 + beforeEa @@ -189,26 +189,28 @@ gination) %7B%0A -%09%09 + pagination = @@ -235,16 +235,18 @@ ();%0A -%09 + %7D));%0A%0A -%09 + it(' @@ -268,34 +268,36 @@ ', function() %7B%0A -%09%09 + pagination.numPa @@ -306,18 +306,20 @@ s = 2;%0A%0A -%09%09 + expect(p @@ -336,34 +336,36 @@ page).toBe(0);%0A%0A -%09%09 + pagination.nextP @@ -363,34 +363,36 @@ ion.nextPage();%0A -%09%09 + expect(paginatio @@ -412,18 +412,20 @@ 1); %0A%0A -%09%09 + paginati @@ -440,18 +440,20 @@ age(); %0A -%09%09 + expect(p @@ -477,23 +477,25 @@ oBe(0);%0A -%09 + %7D);%0A%0A -%09 + it('shou @@ -542,34 +542,36 @@ ', function() %7B%0A -%09%09 + pagination.numPa @@ -580,18 +580,20 @@ s = 2;%0A%0A -%09%09 + paginati @@ -605,18 +605,20 @@ ge = 0;%0A -%09%09 + paginati @@ -624,34 +624,36 @@ ion.prevPage();%0A -%09%09 + expect(paginatio @@ -662,34 +662,36 @@ page).toBe(0);%0A%0A -%09%09 + pagination.page @@ -695,18 +695,20 @@ ge = 1;%0A -%09%09 + paginati @@ -722,18 +722,20 @@ Page();%0A -%09%09 + expect(p @@ -763,15 +763,17 @@ 1);%0A -%09 + %7D);%0A%0A -%09 + it(' @@ -818,18 +818,20 @@ ion() %7B%0A -%09%09 + paginati @@ -848,18 +848,20 @@ s = 3;%0A%0A -%09%09 + expect(p @@ -886,18 +886,20 @@ Be(0);%0A%0A -%09%09 + paginati @@ -918,10 +918,12 @@ 2);%0A -%09%09 + expe @@ -955,9 +955,10 @@ 2);%0A -%09 + %7D);%0A
f6faa3bc938bb92cbe7497b228eeeba0ca256020
Edit comment
core/tests/protractor/cacheSlugs.js
core/tests/protractor/cacheSlugs.js
// Copyright 2016 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 End-to-end tests for cache slugs. */ var general = require('../protractor_utils/general.js'); var ERROR_PAGE_URL_SUFFIX = '/console_errors'; var getUniqueLogMessages = function(logs) { // Returns unique log messages. var logsDict = {}; for (var i = 0; i < logs.length; i++) { if (!logsDict.hasOwnProperty(logs[i].message)) { logsDict[logs[i].message] = true; } } return Object.keys(logsDict); }; var checkConsoleErrorsExist = function(expectedErrors) { // Checks that browser logs match entries in expectedErrors array. browser.manage().logs().get('browser').then(function(browserLogs) { // Some browsers such as chrome raise two errors for a missing resource. // To keep consistent behaviour across browsers, we keep only the logs // that have a unique value for their message attribute. var uniqueLogMessages = getUniqueLogMessages(browserLogs); expect(uniqueLogMessages.length).toBe(expectedErrors.length); for (var i = 0; i < expectedErrors.length; i++) { var errorPresent = false; for (var j = 0; j < uniqueLogMessages.length; j++) { if (uniqueLogMessages[j].match(expectedErrors[i])) { errorPresent = true; } } expect(errorPresent).toBe(true); } }); }; describe('Cache Slugs', function() { it('should check that errors get logged for missing resources', function() { browser.get(ERROR_PAGE_URL_SUFFIX); var expectedErrors = [ 'http://localhost:9001/build/fail/logo/288x128_logo_white.png', // Warning fired by synchronous AJAX request in // core/templates/dev/head/pages/header_js_libs.html this warning is // expected and it's needed for constants loading. 'Synchronous XMLHttpRequest on the main thread' ]; checkConsoleErrorsExist(expectedErrors); }); });
JavaScript
0
@@ -2271,18 +2271,28 @@ ibs.html - t +.%0A // T his warn @@ -2297,25 +2297,16 @@ rning is -%0A // expecte
7a8f39067376f44c30b688e960d980b1cafe2337
Add 'add' to projectDeploy provided interface
core/cb.project.deploy/main.js
core/cb.project.deploy/main.js
// Requires var _ = require('underscore'); var DeploymentSolution = require("./solution").DeploymentSolution; // List of all deployment solution var SUPPORTED = []; function setup(options, imports, register) { // Import var logger = imports.logger.namespace("deployment"); var events = imports.events; var workspace = imports.workspace; // Return a specific solution var getSolution = function(solutionId) { return _.find(SOLUTIONS, function(solution) { return solution.id == solutionId; }); }; // Add a solution var addSolution = function(solution) { if (!_.isArray(solution)) solution = [solution]; _.each(solution, function(_sol) { SUPPORTED.push(new DeploymentSolution(workspace, events, logger, _sol)); }); } // Add basic solutions addSolution([ require("./ghpages") ]) // Register register(null, { 'projectDeploy': { 'SUPPORTED': SUPPORTED, 'get': getSolution } }); } // Exports module.exports = setup;
JavaScript
0.000001
@@ -814,16 +814,17 @@ );%0A %7D +; %0A%0A%0A / @@ -1026,24 +1026,56 @@ getSolution +,%0A 'add': addSolution %0A %7D%0A
66d067a35ed2fcaf9decaad683ebeb2f563b2117
Add styling clases to fix buttons appearing white on iOS
src/main/web/js/app/mobile-table.js
src/main/web/js/app/mobile-table.js
$(function() { var markdownTable = $('.markdown-table-wrap'); if (markdownTable.length) { $('<button class="btn btn--mobile-table-show">View table</button>').insertAfter(markdownTable); $('<button class="btn btn--mobile-table-hide">Close table</button>').insertAfter(markdownTable.find('table')); $('.btn--mobile-table-show').click(function () { $(this).closest('.markdown-table-container').find('.markdown-table-wrap').show(); }); $('.btn--mobile-table-hide').click(function () { $(this).closest('.markdown-table-wrap').css('display', ''); }); } });
JavaScript
0
@@ -114,32 +114,47 @@ tton class=%22btn +btn--secondary btn--mobile-tabl @@ -237,24 +237,39 @@ class=%22btn +btn--secondary btn--mobile-
285bdf6c56f70fb2fd0a8fc7e881d244bf8a6cd0
Remove odd html tags
src/components/NavigationBar/NavigationBar.js
src/components/NavigationBar/NavigationBar.js
import React from 'react' import { Link } from 'react-router-dom'; import './navigation-bar.css'; import { isAuthenticated } from '../../helper/auth'; import * as firebase from 'firebase'; class NavigationBar extends React.Component { signout() { firebase.auth().signOut(); } authenticated() { return ( <div className="navigation-bar__wrapper"> <div className="navigation-bar__placeholder"></div> <nav className="navigation-bar"> <div className="navigation-bar__item--flex"> <Link className="navigation-bar__link" to="/">Home</Link> </div> <div className="navigation-bar__item"> <Link className="navigation-bar__link" to="/admin">Admin</Link> <a className="navigation-bar__link" onClick={this.signout} >Sign Out</a> </div> </nav> </div> ) } unauthenticated() { return ( <div className="navigation-bar__wrapper"> <div className="navigation-bar__placeholder"></div> <nav className="navigation-bar"> <div className="navigation-bar__item--flex"> <Link className="navigation-bar__link" to="/">Home</Link> </div> <div className="navigation-bar__item"> <Link className="navigation-bar__link" to="/signin">Sign In</Link> </div> </nav> </div> ) } render() { if (isAuthenticated()) { return this.authenticated(); } else { return this.unauthenticated(); } } } export { NavigationBar }
JavaScript
0.999801
@@ -344,170 +344,46 @@ - %3Cdiv className=%22navigation-bar__wrapper%22%3E%0A %3Cdiv className=%22navigation-bar__placeholder%22%3E%3C/div%3E%0A %3Cnav className=%22navigation-bar%22%3E%0A +%3Cnav className=%22navigation-bar glow%22%3E%0A @@ -451,36 +451,32 @@ - %3CLink className= @@ -497,36 +497,41 @@ r__link%22 to=%22/%22%3E -Home +Biografia %3C/Link%3E%0A @@ -530,36 +530,32 @@ - %3C/div%3E%0A @@ -553,36 +553,32 @@ - - %3Cdiv className=%22 @@ -592,36 +592,32 @@ ion-bar__item%22%3E%0A - @@ -704,20 +704,16 @@ - - %3Ca class @@ -789,39 +789,31 @@ - - %3C/div%3E%0A - %3C @@ -818,34 +818,16 @@ %3C/nav%3E%0A - %3C/div%3E%0A @@ -891,170 +891,41 @@ - %3Cdiv className=%22navigation-bar__wrapper%22%3E%0A %3Cdiv className=%22navigation-bar__placeholder%22%3E%3C/div%3E%0A %3Cnav className=%22navigation-bar%22%3E%0A +%3Cnav className=%22navigation-bar%22%3E%0A @@ -973,36 +973,32 @@ r__item--flex%22%3E%0A - @@ -1051,12 +1051,17 @@ %22/%22%3E -Home +Biografia %3C/Li @@ -1072,36 +1072,32 @@ - %3C/div%3E%0A @@ -1095,36 +1095,32 @@ - - %3Cdiv className=%22 @@ -1134,36 +1134,32 @@ ion-bar__item%22%3E%0A - @@ -1221,36 +1221,32 @@ %3ESign In%3C/Link%3E%0A - @@ -1267,34 +1267,12 @@ - %3C/nav%3E%0A %3C/di +%3C/na v%3E%0A
207f9e63434b1c191b8d3296e17e1bb881c580c0
reset board on start
lib/board/index.js
lib/board/index.js
import bus from 'component/bus' import Board from 'kvnneff/bloxparty-board@1.0.3-alpha' export default function plugin () { return function (app) { var board = new Board() app.set('board', board.json()) board.on('change', function () { app.set('board', board.json()) }) bus.on('player:move', function (direction) { board.move(direction) }) bus.on('game:begin', function () { board.start() }) bus.on('client', function (data) { board.sync(data.board) }) bus.on('game:stop', function () { board.stop() }) } }
JavaScript
0.000001
@@ -404,32 +404,52 @@ , function () %7B%0A + board.reset()%0A board.star
965716143e75bb52d4979986fd35e9b4bbc1acde
use 1 for env instead of true, since it becomes a string
lib/boilerplate.js
lib/boilerplate.js
"use strict"; var mocha = require('gulp-mocha'), Q = require('q'), Transpiler = require('../index').Transpiler, jshint = require('gulp-jshint'), jscs = require('gulp-jscs'), vinylPaths = require('vinyl-paths'), del = require('del'), _ = require('lodash'); var DEFAULT_OPTS = { files: ["*.js", "lib/**/*.js", "test/**/*.js", "!gulpfile.js"], transpile: true, transpileOut: "build", babelOpts: {}, linkBabelRuntime: true, jscs: true, jshint: true, watch: true, test: true, testFiles: null, testReporter: 'nyan', testTimeout: 8000, buildName: null }; var boilerplate = function (gulp, opts) { var spawnWatcher = require('../index').spawnWatcher.use(gulp); var runSequence = Q.denodeify(require('run-sequence').use(gulp)); var defOpts = _.clone(DEFAULT_OPTS); _.extend(defOpts, opts); opts = defOpts; process.env.APPIUM_NOTIF_BUILD_NAME = opts.buildName; gulp.task('clean', function () { if (opts.transpile) { return gulp.src(opts.transpileOut, {read: false}) .pipe(vinylPaths(del)); } }); if (opts.test) { var testDeps = []; var testDir = 'test'; if (opts.transpile) { testDeps.push('transpile'); testDir = opts.transpileOut + '/test'; } var testFiles = opts.testFiles ? opts.testFiles : testDir + '/**/*-specs.js'; gulp.task('test', testDeps, function () { var mochaOpts = { reporter: opts.testReporter, timeout: opts.testTimeout }; // set env so our code knows when it's being run in a test env process.env._TESTING = true; var testProc = gulp .src(testFiles, {read: false}) .pipe(mocha(mochaOpts)) .on('error', spawnWatcher.handleError); process.env._TESTING = false; return testProc; }); } if (opts.transpile) { gulp.task('transpile', function () { var transpiler = new Transpiler(opts.babelOpts); return gulp.src(opts.files, {base: './'}) .pipe(transpiler.stream()) .on('error', spawnWatcher.handleError) .pipe(gulp.dest(opts.transpileOut)); }); gulp.task('prepublish', function () { return runSequence('clean', 'transpile'); }); } var lintTasks = []; if (opts.jscs) { gulp.task('jscs', function () { return gulp .src(opts.files) .pipe(jscs()) .on('error', spawnWatcher.handleError); }); lintTasks.push('jscs'); } if (opts.jshint) { gulp.task('jshint', function () { return gulp .src(opts.files) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')) .on('error', spawnWatcher.handleError); }); lintTasks.push('jshint'); } if (opts.jscs || opts.jshint) { opts.lint = true; gulp.task('lint', lintTasks); } var defaultSequence = []; if (opts.transpile) defaultSequence.push('clean'); if (opts.lint) defaultSequence.push('lint'); if (opts.transpile) defaultSequence.push('transpile'); if (opts.test) defaultSequence.push('test'); if (opts.watch) { spawnWatcher.clear(false); spawnWatcher.configure('watch', opts.files, function () { return runSequence.apply(null, defaultSequence); }); } gulp.task('once', function () { return runSequence.apply(null, defaultSequence); }); gulp.task('default', [opts.watch ? 'watch' : 'once']); }; module.exports = { use: function (gulp) { return function (opts) { boilerplate(gulp, opts); }; } };
JavaScript
0.000011
@@ -1633,20 +1633,17 @@ STING = -true +1 ;%0A @@ -1782,44 +1782,8 @@ r);%0A - process.env._TESTING = false;%0A
95fb0e2af62acc4b3ea4d88e1832325807467143
Put initialization in a separate callable function.
www/googleplayservices.js
www/googleplayservices.js
var argscheck = require ('cordova/argscheck') var exec = require ('cordova/exec') module.exports = function () { var exports = {} exports.getPlayerId = function (init) { var success = (typeof init.success != "undefined") ? init.success : function () {} var error = (typeof init.error != "undefined") ? init.error : function () {} cordova.exec (success, error, "GooglePlayServices", "getPlayerId", []) } return exports } ()
JavaScript
0
@@ -421,16 +421,303 @@ %5D)%0A %7D%0A %0A + exports.initialize = function (init) %7B%0A var success = (typeof init.success != %22undefined%22) ? init.success : function () %7B%7D%0A var error = (typeof init.error != %22undefined%22) ? init.error : function () %7B%7D%0A cordova.exec (success, error, %22GooglePlayServices%22, %22initialize%22, %5B%5D)%0A %7D%0A %0A return @@ -728,8 +728,9 @@ rts%0A%7D () +%0A
eab5c2896ea862ce2023e317b65d483d592d1792
Fix to check for zero s value in sign function
lib/browser/Key.js
lib/browser/Key.js
var ECKey = require('../../browser/vendor-bundle.js').ECKey; var SecureRandom = require('../SecureRandom'); var Curve = require('../Curve'); var bignum = require('bignum'); var Key = function() { this._pub = null; this._compressed = true; // default }; var bufferToArray = Key.bufferToArray = function(buffer) { var ret = []; var l = buffer.length; for(var i =0; i<l; i++) { ret.push(buffer.readUInt8(i)); } return ret; } Object.defineProperty(Key.prototype, 'public', { set: function(p){ if (!Buffer.isBuffer(p) ) { throw new Error('Arg should be a buffer'); } var type = p[0]; this._compressed = type!==0x04; this._pub = p; }, get: function(){ return this._pub; } }); Object.defineProperty(Key.prototype, 'compressed', { set: function(c) { var oldc = this._compressed; this._compressed = !!c; if (oldc == this._compressed) return; var oldp = this._pub; if (this._pub) { var eckey = new ECKey(); eckey.setPub(bufferToArray(this.public)); eckey.setCompressed(this._compressed); this._pub = new Buffer(eckey.getPub()); } if (!this._compressed) { //bug in eckey //oldp.slice(1).copy(this._pub, 1); } }, get: function() { return this._compressed; } }); Key.generateSync = function() { var privbuf; while(true) { privbuf = SecureRandom.getRandomBuffer(32); if ((bignum.fromBuffer(privbuf, {size: 32})).cmp(Curve.getN()) < 0) break; } var privhex = privbuf.toString('hex'); var eck = new ECKey(privhex); eck.setCompressed(true); var pub = eck.getPub(); ret = new Key(); ret.private = privbuf; ret._compressed = true; ret.public = new Buffer(eck.getPub()); return ret; }; Key.prototype.regenerateSync = function() { if (!this.private) { throw new Error('Key does not have a private key set'); } var eck = new ECKey(this.private.toString('hex')); eck.setCompressed(this._compressed); this._pub = new Buffer(eck.getPub()); return this; }; Key.prototype.signSync = function(hash) { var getSECCurveByName = require('../../browser/vendor-bundle.js').getSECCurveByName; var BigInteger = require('../../browser/vendor-bundle.js').BigInteger; var rng = new SecureRandom(); var ecparams = getSECCurveByName('secp256k1'); var rng = {}; rng.nextBytes = function(array) { var buf = SecureRandom.getRandomBuffer(array.length); var a = bufferToArray(SecureRandom.getRandomBuffer(array.length)); for (var i in a) { array[i] = a[i]; } }; var getBigRandom = function (limit) { return new BigInteger(limit.bitLength(), rng) .mod(limit.subtract(BigInteger.ONE)) .add(BigInteger.ONE); }; var sign = function (hash, priv) { var d = priv; var n = ecparams.getN(); var e = BigInteger.fromByteArrayUnsigned(hash); do { var k = getBigRandom(n); var G = ecparams.getG(); var Q = G.multiply(k); var r = Q.getX().toBigInteger().mod(n); } while (r.compareTo(BigInteger.ZERO) <= 0); var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); return serializeSig(r, s); }; var serializeSig = function (r, s) { var rBa = r.toByteArraySigned(); var sBa = s.toByteArraySigned(); var sequence = []; sequence.push(0x02); // INTEGER sequence.push(rBa.length); sequence = sequence.concat(rBa); sequence.push(0x02); // INTEGER sequence.push(sBa.length); sequence = sequence.concat(sBa); sequence.unshift(sequence.length); sequence.unshift(0x30); // SEQUENCE return sequence; }; if (!this.private) { throw new Error('Key does not have a private key set'); } if (!Buffer.isBuffer(hash) || hash.length !== 32) { throw new Error('Arg should be a 32 bytes hash buffer'); } var privhex = this.private.toString('hex'); var privnum = new BigInteger(privhex, 16); var signature = sign(bufferToArray(hash), privnum); return new Buffer(signature); }; Key.prototype.verifySignature = function(hash, sig, callback) { try { var result = this.verifySignatureSync(hash, sig); callback(null, result); } catch (e) { callback(e); } }; Key.prototype.verifySignatureSync = function(hash, sig) { var self = this; if (!Buffer.isBuffer(hash) || hash.length !== 32) { throw new Error('Arg 1 should be a 32 bytes hash buffer'); } if (!Buffer.isBuffer(sig)) { throw new Error('Arg 2 should be a buffer'); } if (!self.public) { throw new Error('Key does not have a public key set'); } var eck = new ECKey(); eck.setPub(bufferToArray(self.public)); eck.setCompressed(self._compressed); var sigA = bufferToArray(sig); var ret = eck.verify(bufferToArray(hash),sigA); return ret; }; module.exports = Key;
JavaScript
0
@@ -3015,56 +3015,8 @@ ;%0A - %7D while (r.compareTo(BigInteger.ZERO) %3C= 0);%0A%0A @@ -3077,16 +3077,102 @@ .mod(n); +%0A %7D while (r.compareTo(BigInteger.ZERO) %3C= 0 %7C%7C s.compareTo(BigInteger.ZERO) %3C= 0); %0A%0A re
e291726e5fe2c2cfe858c3ace02c7c1fb14eefa9
Update build-state.js
lib/build-state.js
lib/build-state.js
/** @babel */ import path from 'path' import { isTexFile, isKnitrFile } from './werkzeug' function toArray (value) { return (typeof value === 'string') ? value.split(',').map(item => item.trim()) : Array.from(value) } function toBoolean (value) { return (typeof value === 'string') ? !!value.match(/^(true|yes)$/i) : !!value } class JobState { constructor (parent, jobName) { this.parent = parent this.jobName = jobName } getOutputFilePath () { return this.outputFilePath } setOutputFilePath (value) { this.outputFilePath = value } getFileDatabase () { return this.fileDatabase } setFileDatabase (value) { this.fileDatabase = value } getLogMessages () { return this.logMessages } setLogMessages (value) { this.logMessages = value } getJobName () { return this.jobName } getFilePath () { return this.parent.getFilePath() } getProjectPath () { return this.parent.getProjectPath() } getTexFilePath () { return this.parent.getTexFilePath() } setTexFilePath (value) { this.parent.setTexFilePath(value) } getKnitrFilePath () { return this.parent.getKnitrFilePath() } setKnitrFilePath (value) { this.parent.setKnitrFilePath(value) } getCleanPatterns () { return this.parent.getCleanPatterns() } getEnableSynctex () { return this.parent.getEnableSynctex() } getEnableShellEscape () { return this.parent.getEnableShellEscape() } getEnableExtendedBuildMode () { return this.parent.getEnableExtendedBuildMode() } getEngine () { return this.parent.getEngine() } getMoveResultToSourceDirectory () { return this.parent.getMoveResultToSourceDirectory() } getOutputDirectory () { return this.parent.getOutputDirectory() } getOutputFormat () { return this.parent.getOutputFormat() } getProducer () { return this.parent.getProducer() } getShouldRebuild () { return this.parent.getShouldRebuild() } } export default class BuildState { constructor (filePath, jobNames = [null], shouldRebuild = false) { this.setFilePath(filePath) this.setJobNames(jobNames) this.setShouldRebuild(shouldRebuild) this.setEnableSynctex(false) this.setEnableShellEscape(false) this.setEnableExtendedBuildMode(false) this.subfiles = new Set() } getKnitrFilePath () { return this.knitrFilePath } setKnitrFilePath (value) { this.knitrFilePath = value } getTexFilePath () { return this.texFilePath } setTexFilePath (value) { this.texFilePath = value } getProjectPath () { return this.projectPath } setProjectPath (value) { this.projectPath = value } getCleanPatterns () { return this.cleanPatterns } setCleanPatterns (value) { this.cleanPatterns = toArray(value) } getEnableSynctex () { return this.enableSynctex } setEnableSynctex (value) { this.enableSynctex = toBoolean(value) } getEnableShellEscape () { return this.enableShellEscape } setEnableShellEscape (value) { this.enableShellEscape = toBoolean(value) } getEnableExtendedBuildMode () { return this.enableExtendedBuildMode } setEnableExtendedBuildMode (value) { this.enableExtendedBuildMode = toBoolean(value) } getEngine () { return this.engine } setEngine (value) { this.engine = value } getJobStates () { return this.jobStates } setJobStates (value) { this.jobStates = value } getMoveResultToSourceDirectory () { return this.moveResultToSourceDirectory } setMoveResultToSourceDirectory (value) { this.moveResultToSourceDirectory = toBoolean(value) } getOutputFormat () { return this.outputFormat } setOutputFormat (value) { this.outputFormat = value } getOutputDirectory () { return this.outputDirectory } setOutputDirectory (value) { this.outputDirectory = value } getProducer () { return this.producer } setProducer (value) { this.producer = value } getSubfiles () { return Array.from(this.subfiles.values()) } addSubfile (value) { this.subfiles.add(value) } hasSubfile (value) { return this.subfiles.has(value) } getShouldRebuild () { return this.shouldRebuild } setShouldRebuild (value) { this.shouldRebuild = toBoolean(value) } getFilePath () { return this.filePath } setFilePath (value) { this.filePath = value this.texFilePath = isTexFile(value) ? value : undefined this.knitrFilePath = isKnitrFile(value) ? value : undefined this.projectPath = path.dirname(value) } getJobNames () { return this.jobStates.map(jobState => jobState.getJobName()) } setJobNames (value) { this.jobStates = toArray(value).map(jobName => new JobState(this, jobName)) } }
JavaScript
0.000001
@@ -1565,24 +1565,109 @@ Mode()%0A %7D%0A%0A + getOpenResultAfterBuild () %7B%0A return this.parent.getOpenResultAfterBuild()%0A %7D%0A%0A getEngine @@ -1663,32 +1663,32 @@ getEngine () %7B%0A - return this. @@ -2399,32 +2399,72 @@ uildMode(false)%0A + this.setOpenResultAfterBuild(false)%0A this.subfile @@ -3367,32 +3367,32 @@ dMode (value) %7B%0A - this.enableE @@ -3428,24 +3428,187 @@ value)%0A %7D%0A%0A + getOpenResultAfterBuild () %7B%0A return this.openResultAfterBuild%0A %7D%0A%0A setOpenResultAfterBuild (value) %7B%0A this.openResultAfterBuild = toBoolean(value)%0A %7D%0A%0A getEngine
d39a9a0f189f3a2ce13e230ecd76ee4d9fd6e575
bring back select-all-on-click
src/components/views/elements/EditableText.js
src/components/views/elements/EditableText.js
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require('react'); const KEY_TAB = 9; const KEY_SHIFT = 16; const KEY_WINDOWS = 91; module.exports = React.createClass({ displayName: 'EditableText', propTypes: { onValueChanged: React.PropTypes.func, initialValue: React.PropTypes.string, label: React.PropTypes.string, placeholder: React.PropTypes.string, className: React.PropTypes.string, labelClassName: React.PropTypes.string, placeholderClassName: React.PropTypes.string, blurToCancel: React.PropTypes.bool, }, Phases: { Display: "display", Edit: "edit", }, value: '', placeholder: false, getDefaultProps: function() { return { onValueChanged: function() {}, initialValue: '', label: '', placeholder: '', }; }, getInitialState: function() { return { phase: this.Phases.Display, } }, componentWillReceiveProps: function(nextProps) { this.value = nextProps.initialValue; }, componentDidMount: function() { this.value = this.props.initialValue; if (this.refs.editable_div) { this.showPlaceholder(!this.value); } }, showPlaceholder: function(show) { if (show) { this.refs.editable_div.textContent = this.props.placeholder; this.refs.editable_div.setAttribute("class", this.props.className + " " + this.props.placeholderClassName); this.placeholder = true; this.value = ''; } else { this.refs.editable_div.textContent = this.value; this.refs.editable_div.setAttribute("class", this.props.className); this.placeholder = false; } }, getValue: function() { return this.value; }, edit: function() { this.setState({ phase: this.Phases.Edit, }); }, cancelEdit: function() { this.setState({ phase: this.Phases.Display, }); this.onValueChanged(false); }, onValueChanged: function(shouldSubmit) { this.props.onValueChanged(this.value, shouldSubmit); }, onKeyDown: function(ev) { // console.log("keyDown: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder); if (this.placeholder) { if (ev.keyCode !== KEY_SHIFT && !ev.metaKey && !ev.ctrlKey && !ev.altKey && ev.keyCode !== KEY_WINDOWS && ev.keyCode !== KEY_TAB) { this.showPlaceholder(false); } } if (ev.key == "Enter") { ev.stopPropagation(); ev.preventDefault(); } // console.log("keyDown: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder); }, onKeyUp: function(ev) { // console.log("keyUp: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder); if (!ev.target.textContent) { this.showPlaceholder(true); } else if (!this.placeholder) { this.value = ev.target.textContent; } if (ev.key == "Enter") { this.onFinish(ev); } else if (ev.key == "Escape") { this.cancelEdit(); } // console.log("keyUp: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder); }, onClickDiv: function(ev) { this.setState({ phase: this.Phases.Edit, }) }, onFocus: function(ev) { //ev.target.setSelectionRange(0, ev.target.textContent.length); }, onFinish: function(ev) { var self = this; this.setState({ phase: this.Phases.Display, }, function() { self.onValueChanged(ev.key === "Enter"); }); }, onBlur: function(ev) { if (this.props.blurToCancel) this.cancelEdit(); else this.onFinish(ev) }, render: function() { var editable_el; if (this.state.phase == this.Phases.Display && (this.props.label || this.props.labelClassName) && !this.value) { // show the label editable_el = <div className={this.props.className + " " + this.props.labelClassName} onClick={this.onClickDiv}>{this.props.label}</div>; } else { // show the content editable div, but manually manage its contents as react and contentEditable don't play nice together editable_el = <div ref="editable_div" contentEditable="true" className={this.props.className} onKeyDown={this.onKeyDown} onKeyUp={this.onKeyUp} onFocus={this.onFocus} onBlur={this.onBlur}></div>; } return editable_el; } });
JavaScript
0.000001
@@ -4347,16 +4347,289 @@ length); +%0A%0A var node = ev.target.childNodes%5B0%5D;%0A var range = document.createRange();%0A range.setStart(node, 0);%0A range.setEnd(node, node.length);%0A %0A var sel = window.getSelection();%0A sel.removeAllRanges();%0A sel.addRange(range); %0A %7D,%0A
384f50609d92ed9e525f261ea6bf4a64d97b401c
Allow searching by partial prefix (/w or /wo '+')
src/components/views/login/CountryDropdown.js
src/components/views/login/CountryDropdown.js
/* Copyright 2017 Vector Creations Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import sdk from '../../../index'; import { COUNTRIES } from '../../../phonenumber'; const COUNTRIES_BY_ISO2 = new Object(null); for (const c of COUNTRIES) { COUNTRIES_BY_ISO2[c.iso2] = c; } function countryMatchesSearchQuery(query, country) { if (country.name.toUpperCase().indexOf(query.toUpperCase()) == 0) return true; if (country.iso2 == query.toUpperCase()) return true; if (country.prefix == query) return true; return false; } export default class CountryDropdown extends React.Component { constructor(props) { super(props); this._onSearchChange = this._onSearchChange.bind(this); this._onOptionChange = this._onOptionChange.bind(this); this._getShortOption = this._getShortOption.bind(this); this.state = { searchQuery: '', }; } componentWillMount() { if (!this.props.value) { // If no value is given, we start with the first // country selected, but our parent component // doesn't know this, therefore we do this. this.props.onOptionChange(COUNTRIES[0]); } } _onSearchChange(search) { this.setState({ searchQuery: search, }); } _onOptionChange(iso2) { this.props.onOptionChange(COUNTRIES_BY_ISO2[iso2]); } _flagImgForIso2(iso2) { return <img src={`flags/${iso2}.png`}/>; } _getShortOption(iso2) { if (!this.props.isSmall) { return undefined; } let countryPrefix; if (this.props.showPrefix) { countryPrefix = '+' + COUNTRIES_BY_ISO2[iso2].prefix; } return <span> { this._flagImgForIso2(iso2) } { countryPrefix } </span>; } render() { const Dropdown = sdk.getComponent('elements.Dropdown'); let displayedCountries; if (this.state.searchQuery) { displayedCountries = COUNTRIES.filter( countryMatchesSearchQuery.bind(this, this.state.searchQuery), ); if ( this.state.searchQuery.length == 2 && COUNTRIES_BY_ISO2[this.state.searchQuery.toUpperCase()] ) { // exact ISO2 country name match: make the first result the matches ISO2 const matched = COUNTRIES_BY_ISO2[this.state.searchQuery.toUpperCase()]; displayedCountries = displayedCountries.filter((c) => { return c.iso2 != matched.iso2; }); displayedCountries.unshift(matched); } } else { displayedCountries = COUNTRIES; } const options = displayedCountries.map((country) => { return <div key={country.iso2}> {this._flagImgForIso2(country.iso2)} {country.name} </div>; }); // default value here too, otherwise we need to handle null / undefined // values between mounting and the initial value propgating const value = this.props.value || COUNTRIES[0].iso2; return <Dropdown className={this.props.className + " left_aligned"} onOptionChange={this._onOptionChange} onSearchChange={this._onSearchChange} menuWidth={298} getShortOption={this._getShortOption} value={value} searchEnabled={true} > {options} </Dropdown>; } } CountryDropdown.propTypes = { className: React.PropTypes.string, isSmall: React.PropTypes.bool, // if isSmall, show +44 in the selected value showPrefix: React.PropTypes.bool, onOptionChange: React.PropTypes.func.isRequired, value: React.PropTypes.string, };
JavaScript
0.000001
@@ -835,24 +835,150 @@ country) %7B%0A + // Remove '+' if present (when searching for a prefix)%0A if (query%5B0%5D === '+') %7B%0A query = query.slice(1);%0A %7D%0A%0A if (coun @@ -1128,25 +1128,38 @@ y.prefix - == query +.indexOf(query) !== -1 ) return
f69efdf8441ba4ec5e8abf9af4fa04b29f15130d
Add args as a parameter for cmdRunner.runHadoopJar
cosmos-tidoop-api/src/cmd_runner.js
cosmos-tidoop-api/src/cmd_runner.js
/** * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-cosmos (FI-WARE project). * * fiware-cosmos is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * fiware-cosmos is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License along with fiware-cosmos. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with * francisco dot romerobueno at telefonica dot com */ /** * Command runner. * * Author: frb */ // Module dependencies var spawn = require('child_process').spawn; function runHadoopJar(userId, jarName, jarInHDFS, className, libJarsName, libJarsInHDFS, input, output, callback) { // Copy the jar from the HDFS user space var params = ['-u', userId, 'hadoop', 'fs', '-copyToLocal', jarInHDFS, '/home/' + userId + '/' + jarName]; var command = spawn('sudo', params); command.on('close', function(code) { // Copy the libjar from the HDFS user space var params = ['-u', userId, 'hadoop', 'fs', '-copyToLocal', libJarsInHDFS, '/home/' + userId + '/' + libJarsName]; var command = spawn('sudo', params); command.on('close', function(code) { // Run the MR job var params = ['-u', userId, 'hadoop', 'jar', '/home/' + userId + '/' + jarName, className, '-libjars', '/home/' + userId + '/' + libJarsName, input, output]; var command = spawn('sudo', params); var jobId = null; // This function catches the stderr as it is being produced (console logs are printed in the stderr). At the // moment of receiving the line containing the job ID, get it and return with no error (no error means the // job could be run, independently of the final result of the job) command.stderr.on('data', function (data) { var dataStr = data.toString(); var magicString = 'Submitting tokens for job: '; var indexOfJobId = dataStr.indexOf(magicString); if(indexOfJobId >= 0) { jobId = dataStr.substring(indexOfJobId + magicString.length, indexOfJobId + magicString.length + 22); var params = ['-u', userId, 'rm', '/home/' + userId + '/' + jarName]; var command = spawn('sudo', params); var params = ['-u', userId, 'rm', '/home/' + userId + '/' + libJarsName]; var command = spawn('sudo', params); return callback(null, jobId); } // if }); // This function catches the moment the command finishes. Return the error code if the job ID was never got command.on('close', function (code) { if (jobId === null) { return callback(code, null); } // if }); }); }); } // runHadoopJar function runHadoopJobList(userId, callback) { var params = ['job', '-list', 'all']; var command = spawn('hadoop', params); var jobInfos = null; command.stdout.on('data', function (data) { var dataStr = data.toString(); jobInfos = '['; var firstJobInfo = true; var lines = dataStr.split("\n"); for (i in lines) { if(i > 1) { var fields = lines[i].split("\t"); if (fields.length > 3 && fields[3].replace(/ /g,'') === userId) { var jobInfo = '{'; for (j in fields) { if (fields[j].length > 0) { var value = fields[j].replace(/ /g,''); if (j == 0) { jobInfo += '"job_id":"' + value + '"'; } else if (j == 1) { jobInfo += ',"state":"' + value + '"'; } else if (j == 2) { jobInfo += ',"start_time":"' + value + '"'; } else if (j == 3) { jobInfo += ',"user_id":"' + value + '"'; } // if else } // if } // for jobInfo += '}'; if (firstJobInfo) { jobInfos += jobInfo; firstJobInfo = false; } else { jobInfos += ',' + jobInfo; } // if else } // if } // if } // for jobInfos += ']'; return callback(null, jobInfos); }); // This function catches the moment the command finishes. Return the error code if the jobs information was never // got command.on('close', function (code) { if (jobInfos === null) { return callback(code, null); } // if }); } // runHadoopJobList function runHadoopJobKill(jobId, callback) { var params = ['job', '-kill', jobId]; var command = spawn('hadoop', params); command.stderr.on('data', function (data) { var dataStr = data.toString(); var magicString = 'Application with id'; if(dataStr.indexOf(magicString) >= 0) { return callback('Application does not exist'); } // if }); command.stdout.on('data', function (data) { var dataStr = data.toString(); var magicString = 'Killed job'; if (dataStr.indexOf(magicString) >= 0) { return callback(null); } // if }); } // runHadoopJobKill module.exports = { runHadoopJar: runHadoopJar, runHadoopJobList: runHadoopJobList, runHadoopJobKill: runHadoopJobKill } // module.exports
JavaScript
0
@@ -1134,16 +1134,22 @@ sInHDFS, + args, input, @@ -1805,16 +1805,22 @@ assName, + args, '-libja
8a0df6aefa71fb2e34bc891b59791d8c8d5c963c
Fix build target selection
lib/admin.js
lib/admin.js
var async = require('async'), campfire = require('./campfire'), config = require('./config'), express = require('express'), log = require('./log'); module.exports = function(app, repo) { var branches = [], currentBranch; campfire.init(repo); app.get('/ms_admin', function(req, res, next) { async.parallel([ function(callback) { repo.remoteBranches(function(err, data) { branches = data; callback(err); }); }, function(callback) { repo.currentBranch(function(err, data) { currentBranch = data; callback(err); }); } ], function(err) { res.render('index', { gitPath: config.appDir, mocksEnabled: !!config.mocksEnabled, buildTarget: config.buildTarget || {}, buildTargets: config.projectConfig['build-targets'] || [], servers: config.projectConfig.servers || [], proxyServer: config.proxyServer, branches: branches || [], currentBranch: currentBranch, log: log.logs, error: log.errors }); }); }); app.all('/ms_admin/proxy-server', express.bodyParser(), function(req, res, next) { log.reset(); // Filter the user input var proxy = req.param('proxy'); if ((config.projectConfig.servers || []).indexOf(proxy) < 0) { res.redirect('/ms_admin'); return; } config.proxyServer = proxy; campfire.speak('proxy changed to ' + config.proxyServer); res.redirect('/ms_admin'); }); app.all('/ms_admin/mocks', express.bodyParser(), function(req, res, next) { log.reset(); config.mocksEnabled = req.param('enable-mocks'); if (config.mocksEnabled === 'false') { config.mocksEnabled = false; } config.mocksEnabled = !!config.mocksEnabled; campfire.speak('mocksEnabled changed to ' + config.mocksEnabled); res.redirect('/ms_admin'); }); app.all('/ms_admin/build-target', express.bodyParser(), function(req, res, next) { log.reset(); // Filter the input var target = req.param('target'); if ((config.projectConfig['build-targets'] || []).indexOf(target) < 0) { res.redirect('/ms_admin'); return; } config.buildTarget = target; repo.build(function() { campfire.speak('build target changed to ' + config.buildTarget.name); res.redirect('/ms_admin'); }); }); app.all('/ms_admin/branch', express.bodyParser(), function(req, res, next) { log.reset(); // Filter the input var branch = req.param('branch'), sameBranch = currentBranch === branch; console.log('branch', branch, branches, branches.indexOf(branch)); if (branches.indexOf(branch) < 0) { res.redirect('/ms_admin'); return; } console.log('Switching to branch', branch); async.series([ function(callback) { // Skip checkout if we are already on this branch if (sameBranch) { callback(); } else { repo.checkout(branch, callback); } }, function(callback) { repo.pull(!sameBranch, function(err) { callback(err); }); }, function(callback) { repo.build(callback); } ], function(err) { err || campfire.speak('branch changed to ' + branch); res.redirect('/ms_admin'); }); }); app.all('/ms_admin/pull', express.bodyParser(), function(req, res, next) { log.reset(); module.exports.pull(repo, currentBranch, function(err) { res.redirect('/ms_admin'); }); }); }; module.exports.pull = function(repo, currentBranch, callback) { log.reset(); async.series([ function(callback) { repo.pull(callback); }, function(callback) { repo.build(callback); } ], function(err) { if (err) { log.exception(err); } err || process.env.CAMPFIRE_QUIET || campfire.speak('pulled from ' + currentBranch); callback && callback(err); }); };
JavaScript
0
@@ -2066,16 +2066,25 @@ arget = +parseInt( req.para @@ -2094,16 +2094,17 @@ target') +) ;%0A if @@ -2097,32 +2097,46 @@ get'));%0A if ( +target %3C 0 %7C%7C (config.projectC @@ -2169,28 +2169,25 @@ %5B%5D). -indexOf( +length %3C= target) - %3C 0) %7B%0A
27df63964a1fc93b2fd909c17db766ebf460d292
Fix "no-unused-styles" suite name
tests/lib/rules/no-unused-styles.js
tests/lib/rules/no-unused-styles.js
/** * @fileoverview No unused styles defined in javascript files * @author Tom Hastjarjanto */ 'use strict'; // ------------------------------------------------------------------------------ // Requirements // ------------------------------------------------------------------------------ const rule = require('../../../lib/rules/no-unused-styles'); const RuleTester = require('eslint').RuleTester; require('babel-eslint'); // ------------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------------ const ruleTester = new RuleTester(); const tests = { valid: [{ code: [ 'const styles = StyleSheet.create({', ' name: {}', '});', 'const Hello = React.createClass({', ' render: function() {', ' return <Text textStyle={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), }, { code: [ 'const Hello = React.createClass({', ' render: function() {', ' return <Text textStyle={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', 'const styles = StyleSheet.create({', ' name: {}', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' name: {}', '});', 'const Hello = React.createClass({', ' render: function() {', ' return <Text style={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' name: {},', ' welcome: {}', '});', 'const Hello = React.createClass({', ' render: function() {', ' return <Text style={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', 'const Welcome = React.createClass({', ' render: function() {', ' return <Text style={styles.welcome}>Welcome</Text>;', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {}', '})', 'const Hello = React.createClass({', ' propTypes: {', ' textStyle: Text.propTypes.style,', ' },', ' render: function() {', ' return <Text style={[styles.text, textStyle]}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {}', '})', 'const styles2 = StyleSheet.create({', ' text: {}', '})', 'const Hello = React.createClass({', ' propTypes: {', ' textStyle: Text.propTypes.style,', ' },', ' render: function() {', ' return (', ' <Text style={[styles.text, styles2.text, textStyle]}>', ' Hello {this.props.name}', ' </Text>', ' );', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {}', '});', 'const Hello = React.createClass({', ' getInitialState: function() {', ' return { condition: true, condition2: true }; ', ' },', ' render: function() {', ' return (', ' <Text', ' style={[', ' this.state.condition &&', ' this.state.condition2 &&', ' styles.text]}>', ' Hello {this.props.name}', ' </Text>', ' );', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {},', ' text2: {},', '});', 'const Hello = React.createClass({', ' getInitialState: function() {', ' return { condition: true }; ', ' },', ' render: function() {', ' return (', ' <Text style={[this.state.condition ? styles.text : styles.text2]}>', ' Hello {this.props.name}', ' </Text>', ' );', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' style1: {', ' color: \'red\',', ' },', ' style2: {', ' color: \'blue\',', ' }', '});', 'export default class MyComponent extends Component {', ' static propTypes = {', ' isDanger: PropTypes.bool', ' };', ' render() {', ' return <View style={this.props.isDanger ? styles.style1 : styles.style2} />;', ' }', '}', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {}', '})', ].join('\n'), }, { code: [ 'const Hello = React.createClass({', ' getInitialState: function() {', ' return { condition: true }; ', ' },', ' render: function() {', ' const myStyle = this.state.condition ? styles.text : styles.text2;', ' return (', ' <Text style={myStyle}>', ' Hello {this.props.name}', ' </Text>', ' );', ' }', '});', 'const styles = StyleSheet.create({', ' text: {},', ' text2: {},', '});', ].join('\n'), }, { code: [ 'const additionalStyles = {};', 'const styles = StyleSheet.create({', ' name: {},', ' ...additionalStyles', '});', 'const Hello = React.createClass({', ' render: function() {', ' return <Text textStyle={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), }], invalid: [{ code: [ 'const styles = StyleSheet.create({', ' text: {}', '})', 'const Hello = React.createClass({', ' render: function() {', ' return <Text style={styles.b}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), errors: [{ message: 'Unused style detected: styles.text', }], }], }; const config = { parser: 'babel-eslint', parserOptions: { ecmaFeatures: { classes: true, jsx: true, }, }, }; tests.valid.forEach(t => Object.assign(t, config)); tests.invalid.forEach(t => Object.assign(t, config)); ruleTester.run('split-platform-components', rule, tests);
JavaScript
0
@@ -6314,32 +6314,23 @@ un(' -split-platform-component +no-unused-style s',
ded1e02da7a42aaa5ea0a4414d9ebac7d986995f
move buildHelpers require down a slot
packages/build-runtime.js
packages/build-runtime.js
"use strict"; var buildHelpers = require("../lib/babel/build-helpers"); var transform = require("../lib/babel/transformation"); var util = require("../lib/babel/util"); var fs = require("fs"); var t = require("../lib/babel/types"); var _ = require("lodash"); var relative = function (filename) { return __dirname + "/babel-runtime/" + filename; }; var writeFile = function (filename, content) { filename = relative(filename); console.log(filename); fs.writeFileSync(filename, content); }; var readFile = function (filename, defaultify) { var file = fs.readFileSync(require.resolve(filename), "utf8"); if (defaultify) { file += '\nmodule.exports = { "default": module.exports, __esModule: true };\n'; } return file; }; var updatePackage = function () { var pkgLoc = relative("package.json"); var pkg = require(pkgLoc); var mainPkg = require("../package.json"); pkg.version = mainPkg.version; writeFile("package.json", JSON.stringify(pkg, null, 2)); }; var selfContainify = function (code) { return transform(code, { optional: ["selfContained"] }).code; }; var buildHelpers2 = function () { var body = util.template("self-contained-helpers-head"); var tree = t.program(body); buildHelpers(body, t.identifier("helpers")); return transform.fromAst(tree, null, { optional: ["selfContained"] }).code; }; writeFile("helpers.js", buildHelpers2()); writeFile("core-js.js", readFile("core-js/library", true)); writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true)); writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime"))); updatePackage();
JavaScript
0
@@ -12,28 +12,28 @@ %22;%0A%0Avar -buildHelpers +transform = requi @@ -53,41 +53,42 @@ bel/ -build-helpers%22);%0Avar transform +transformation%22);%0Avar buildHelpers = r @@ -104,38 +104,37 @@ ./lib/babel/ -transformation +build-helpers %22);%0Avar util
62a0f429264c4d63006e455690d02496674d3a2f
Fix chart symbol
src/botPage/view/blockly/blocks/trade/index.js
src/botPage/view/blockly/blocks/trade/index.js
import { observer as globalObserver } from 'binary-common-utils/lib/observer'; import { translate } from '../../../../../common/i18n'; import config from '../../../../common/const'; import { setBlockTextColor, findTopParentBlock, deleteBlockIfExists } from '../../utils'; import { defineContract } from '../images'; import { updatePurchaseChoices } from '../shared'; import { marketDefPlaceHolders } from './tools'; import backwardCompatibility from './backwardCompatibility'; import tradeOptions from './tradeOptions'; const bcMoveAboveInitializationsDown = block => { Blockly.Events.recordUndo = false; Blockly.Events.setGroup('BackwardCompatibility'); const parent = block.getParent(); if (parent) { const initializations = block.getInput('INITIALIZATION').connection; const ancestor = findTopParentBlock(parent); parent.nextConnection.disconnect(); initializations.connect((ancestor || parent).previousConnection); } block.setPreviousStatement(false); Blockly.Events.setGroup(false); Blockly.Events.recordUndo = true; }; const decorateTrade = ev => { const trade = Blockly.mainWorkspace.getBlockById(ev.blockId); if (!trade || trade.type !== 'trade') { return; } if ([Blockly.Events.CHANGE, Blockly.Events.MOVE, Blockly.Events.CREATE].includes(ev.type)) { const symbol = trade.getFieldValue('SYMBOL_LIST'); const submarket = trade.getInput('SUBMARKET').connection.targetConnection; // eslint-disable-next-line no-underscore-dangle const needsMutation = submarket && submarket.sourceBlock_.type !== 'tradeOptions'; if (symbol && !needsMutation) { globalObserver.emit('bot.init', symbol); } const type = trade.getFieldValue('TRADETYPE_LIST'); if (type) { const oppositesName = type.toUpperCase(); const contractType = trade.getFieldValue('TYPE_LIST'); if (oppositesName && contractType) { updatePurchaseChoices(contractType, oppositesName); } } } }; const replaceInitializationBlocks = (trade, ev) => { if (ev.type === Blockly.Events.CREATE) { ev.ids.forEach(blockId => { const block = Blockly.mainWorkspace.getBlockById(blockId); if (block && block.type === 'trade' && !deleteBlockIfExists(block)) { bcMoveAboveInitializationsDown(block); } }); } }; const resetTradeFields = (trade, ev) => { if (ev.blockId === trade.id) { if (ev.element === 'field') { if (ev.name === 'MARKET_LIST') { trade.setFieldValue('', 'SUBMARKET_LIST'); } if (ev.name === 'SUBMARKET_LIST') { trade.setFieldValue('', 'SYMBOL_LIST'); } if (ev.name === 'SYMBOL_LIST') { trade.setFieldValue('', 'TRADETYPECAT_LIST'); } if (ev.name === 'TRADETYPECAT_LIST') { trade.setFieldValue('', 'TRADETYPE_LIST'); } if (ev.name === 'TRADETYPE_LIST') { if (ev.newValue) { trade.setFieldValue('both', 'TYPE_LIST'); } else { trade.setFieldValue('', 'TYPE_LIST'); } } } } }; Blockly.Blocks.trade = { init: function init() { this.appendDummyInput() .appendField(new Blockly.FieldImage(defineContract, 15, 15, 'T')) .appendField(translate('(1) Define your trade contract')); marketDefPlaceHolders(this); this.appendStatementInput('INITIALIZATION').setCheck(null).appendField(`${translate('Run Once at Start')}:`); this.appendStatementInput('SUBMARKET').setCheck(null).appendField(`${translate('Define Trade Options')}:`); this.setPreviousStatement(true, null); this.setColour('#2a3052'); this.setTooltip( translate('Define your trade contract and start the trade, add initializations here. (Runs on start)') ); this.setHelpUrl('https://github.com/binary-com/binary-bot/wiki'); }, onchange: function onchange(ev) { setBlockTextColor(this); if (ev.group !== 'BackwardCompatibility') { replaceInitializationBlocks(this, ev); resetTradeFields(this, ev); } decorateTrade(ev); }, }; Blockly.JavaScript.trade = block => { const account = $('.account-id').first().attr('value'); if (!account) { throw Error('Please login'); } const initialization = Blockly.JavaScript.statementToCode(block, 'INITIALIZATION'); const tradeOptionsStatement = Blockly.JavaScript.statementToCode(block, 'SUBMARKET'); const candleIntervalValue = block.getFieldValue('CANDLEINTERVAL_LIST'); const contractTypeSelector = block.getFieldValue('TYPE_LIST'); const oppositesName = block.getFieldValue('TRADETYPE_LIST').toUpperCase(); const contractTypeList = contractTypeSelector === 'both' ? config.opposites[oppositesName].map(k => Object.keys(k)[0]) : [contractTypeSelector]; const timeMachineEnabled = block.getFieldValue('TIME_MACHINE_ENABLED') === 'TRUE'; const shouldRestartOnError = block.getFieldValue('RESTARTONERROR') === 'TRUE'; const code = ` init = function init() { Bot.init('${account}', { symbol: '${block.getFieldValue('SYMBOL_LIST')}', contractTypes: ${JSON.stringify(contractTypeList)}, candleInterval: '${candleIntervalValue}', shouldRestartOnError: ${shouldRestartOnError}, timeMachineEnabled: ${timeMachineEnabled}, }); ${initialization.trim()} }; start = function start() { ${tradeOptionsStatement.trim()} }; `; return code; }; export default () => { backwardCompatibility(); tradeOptions(); };
JavaScript
0.000002
@@ -1405,239 +1405,8 @@ T'); -%0A const submarket = trade.getInput('SUBMARKET').connection.targetConnection;%0A // eslint-disable-next-line no-underscore-dangle%0A const needsMutation = submarket && submarket.sourceBlock_.type !== 'tradeOptions'; %0A%0A @@ -1425,26 +1425,8 @@ mbol - && !needsMutation ) %7B%0A
4982d4029e48a8d89f70ba01a9fc69b959f212fc
Fix #8
WebContent/static/games/Tanks/displayScript.js
WebContent/static/games/Tanks/displayScript.js
/** * The display script for Tanks. This code displays sprites in a grid based canvas. */ var images = {}; var idList = null; //Called on page load function onLoad(gameID) { displayMessage("Loading Sprites"); let sprites = { bullet: "../static/games/Tanks/bullet.png", }; loadSprites(sprites, gameID); } function loadSprites(sprites, gameID) { let numImages = 0; // get num of sources for(name in sprites) { numImages++; } for(name in sprites) { images[name] = new Image(); images[name].onload = function() { if(--numImages <= 0) { connectWebSocket(gameID); } }; images[name].src = sprites[name]; } } /* * 4: Player ID list * 0: Bulk update * 1: Delta update * * 2: Update game table * 3: Update player table */ function onMessage(message) { let dataView = new DataView(message.data); let header = dataView.getUint8(0); switch(header) { case 1: //delta handleDeltaData(dataView); break; case 0: //bulk handleBulkData(dataView); break; case 2: updateGameTable(); break; case 4: updateIDMap(dataView); break; case 3: updatePlayerList(); default: canvasError(); } } function updateIDMap(dataView) { idList = []; let length = dataView.getUint8(1); for(index = 0; index < length; index++) { let id = dataView.getUint32(index * 4 + 2).toString(); idList.push(id); if(id == "0") { images[id] = null; } else { images[id] = new Image(); images[id].src = "/playericon/" + id; } } } function handleBulkData(dataView) { canvas.clearRect(0, 0, pixelSize, pixelSize); width = dataView.getUint8(1); height = dataView.getUint8(2); for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { let c = dataView.getUint16(3 + (x + y * width) * 2); paintItem(x, y, c); } } } function paintItem(x, y, c) { switch(c) { case 0: //space clear(x, y); break; case 1: //wall wall(x, y); break; case 2: //bullet shot(x, y); break; default: tank(x, y, c - 3); } } function handleDeltaData(dataView) { let offset = 1; while(offset <= dataView.byteLength - 4) { let c = dataView.getUint16(offset); let x = dataView.getUint8(offset + 2); let y = dataView.getUint8(offset + 3); paintItem(x, y, c); offset = offset + 4; } } function tank(x, y, index) { if(idList == null) return; if(idList.length <= index) { return; //we haven't been sent that ID yet } let image = images[idList[index]]; if(image != null && image.complete) { canvas.drawImage(image, x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height); } } function wall(x, y) { canvas.fillStyle = 'black'; canvas.fillRect(x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height); } function clear(x, y) { canvas.clearRect(x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height); } function shot(x, y) { clear(x, y); canvas.drawImage(images.bullet, x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height); }
JavaScript
0.000001
@@ -2290,16 +2290,32 @@ ndex) %7B%0A +%09clear(x, y);%0A%09%0A %09if(idLi
1f4875527d1e2f9a0f3812eca958ece9377595d4
Change language on counts block from Events to Performances.
imports/api/counts/server/publications.js
imports/api/counts/server/publications.js
/* eslint-disable prefer-arrow-callback */ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; import { _ } from 'meteor/underscore'; // API import { Counts } from '../../counts/counts.js'; import { Profiles } from '../../profiles/profiles.js'; import { Shows } from '../../shows/shows.js'; import { Events } from '../../events/events.js'; Meteor.publish('counts.collections', function countsCollections() { const self = this; let countTheatremakers = 0; let countOrganizations = 0; let countShows = 0; let countEvents = 0; let countLocations = 0; let initializing = true; // observeChanges only returns after the initial `added` callbacks // have run. Until then, we don't want to send a lot of // `self.changed()` messages - hence tracking the // `initializing` state. const handleTheatremakers = Profiles.find({"profileType": "Individual"}).observeChanges({ added: function() { countTheatremakers++; if (!initializing) { self.changed('Counts', 'Theatremakers', { count: countTheatremakers }); } }, removed: function() { countTheatremakers--; self.changed('Counts', 'Theatremakers', { count: countTheatremakers }); }, // don't care about changed }); const handleOrganizations = Profiles.find({"profileType": "Organization"}).observeChanges({ added: function() { countOrganizations++; if (!initializing) { self.changed('Counts', 'Organizations', { count: countOrganizations }); } }, removed: function() { countOrganizations--; self.changed('Counts', 'Organizations', { count: countOrganizations }); }, // don't care about changed }); const handleShows = Shows.find({}).observeChanges({ added: function() { countShows++; if (!initializing) { self.changed('Counts', 'Shows', { count: countShows }); } }, removed: function() { countShows--; self.changed('Counts', 'Shows', { count: countShows }); }, // don't care about changed }); const handleEvents = Events.find({}).observeChanges({ added: function() { countEvents++; if (!initializing) { self.changed('Counts', 'Events', { count: countEvents }); } }, removed: function() { countEvents--; self.changed('Counts', 'Events', { count: countEvents }); }, // don't care about changed }); const handleEventLocations = Events.find({"lat": { $gt: ""}}).observeChanges({ added: function() { countLocations++; if (!initializing) { self.changed('Counts', 'Locations', { count: countLocations }); } }, removed: function() { countLocations--; self.changed('Counts', 'Locations', { count: countLocations }); }, // don't care about changed }); const handleProfileLocations = Profiles.find({"lat": { $gt: ""}}).observeChanges({ added: function() { countLocations++; if (!initializing) { self.changed('Counts', 'Locations', { count: countLocations }); } }, removed: function() { countLocations--; self.changed('Counts', 'Locations', { count: countLocations }); }, // don't care about changed }); // Instead, we'll send one `self.added()` message right after // observeChanges has returned, and mark the subscription as // ready. initializing = false; self.added('Counts', 'Theatremakers', { count: countTheatremakers }); self.added('Counts', 'Organizations', { count: countOrganizations }); self.added('Counts', 'Shows', { count: countShows }); self.added('Counts', 'Events', { count: countEvents }); self.added('Counts', 'Locations', { count: countLocations }); self.ready(); // Stop observing the cursor when client unsubs. // Stopping a subscription automatically takes // care of sending the client any removed messages. self.onStop(() => { handleTheatremakers.stop(); handleOrganizations.stop(); handleShows.stop(); handleEvents.stop(); handleEventLocations.stop(); handleProfileLocations.stop(); }); });
JavaScript
0
@@ -2216,37 +2216,43 @@ nged('Counts', ' -Event +Performance s', %7B count: cou @@ -2348,37 +2348,43 @@ nged('Counts', ' -Event +Performance s', %7B count: cou @@ -3648,21 +3648,27 @@ unts', ' -Event +Performance s', %7B co
cb9bc30842fdededbb25f7e627e8f3f84eb151a4
Fix failing test
tests/pages/jobs/JobsOverview-cy.js
tests/pages/jobs/JobsOverview-cy.js
describe('Jobs Overview', function () { context('Jobs page loads correctly', function () { beforeEach(function () { cy.configureCluster({ mesos: '1-for-each-health', nodeHealth: true }); cy.visitUrl({url: '/jobs'}); }); it('has the right active navigation entry', function () { cy.get('.page-header-navigation .tab-item.active') .should('to.have.text', 'Jobs'); }); it('displays empty jobs overview page', function () { cy.get('.page-content .panel-content h3') .should('to.have.text', 'No Jobs Found'); }); }); });
JavaScript
0.000209
@@ -578,12 +578,14 @@ obs -Foun +Create d');
8bf416778ad35f9c96c76de2db451fc3924de8f9
Fix little typo
plugins/weather.js
plugins/weather.js
/** Created on May 6, 2014 * author: MrPoxipol */ var http = require('http'); var util = require('util'); // Templates module var Mustache = require('mustache'); var debug = require('../nibo/debug'); const COMMAND_NAME = 'weather'; // pattern for util.format() const API_URL_PATTERN = 'http://api.openweathermap.org/data/2.5/weather?q=%s&lang=eng'; exports.meta = { name: 'weather', commandName: COMMAND_NAME, description: 'Fetches actual weather conditions from openweathermap.org at specific place on the Earth' }; function kelvinsToCelcius(temperature) { return Math.round(temperature - 273.15); } function calcWindChill(temperature, windSpeed) { if (temperature < 10 && (windSpeed / 3.6) >= 1.8) { var windChill = (13.12 + 0.6215 * temperature - 11.37 * Math.pow(windSpeed, 0.16) + 0.3965 * temperature * Math.pow(windSpeed, 0.16)); windChill = Math.round(windChill); } return null; } function getWeatherFromJson(data) { var parsedJson; try { parsedJson = JSON.parse(data); } catch (e) { debug.debug('JSON parsing error'); return; } var weather = { city: parsedJson.name }; if (!weather.city) { return; } weather.country = parsedJson.sys.country; weather.temp = kelvinsToCelcius(parsedJson.main.temp); weather.description = parsedJson.weather[0].description; weather.windSpeed = parsedJson.wind.speed; weather.pressure = Math.round(parsedJson.main.pressure); weather.windChill = calcWindChill(weather.temp, weather.windSpeed); var pattern; if (weather.windChill !== null) pattern = '[{{&city}}, {{&country}}]: {{&temp}}°C (felt as {{&windChill}}°C) - {{&description}}, {{&pressure}} hPa'; else pattern = '[{{&city}}, {{&country}}]: {{&temp}}°C - {{&description}}, {{&pressure}} hPa'; var output = Mustache.render(pattern, weather); return output; } function sendResponse(bot, args, message) { bot.sayToUser(args.channel, args.user.nick, message); } function fetchWeather(bot, args) { args.place = encodeURIComponent(args.place); var url = util.format(API_URL_PATTERN, args.place); http.get(url, function (response) { var responseParts = []; response.setEncoding('utf8'); response.on('data', function (chunk) { responseParts.push(chunk); }); response.on('end', function () { var data = responseParts.join(''); var message = getWeatherFromJson(data); if (message) { sendResponse(bot, args, message); } else { sendResponse(bot, args, util.format('[%s] Could not find weather information.', decodeURIComponent(args.place)) ); } }); }).on('error', function (e) { debug.error('HTTP ' + e.message); sendResponse(bot, args, '[] Weather is not avaiable at the moment.'); }); } exports.onCommand = function (bot, user, channel, command) { if (command.name !== COMMAND_NAME) return; if (command.args.length < 1) return; var args = { user: user, channel: channel, place: command.args.join(' '), }; fetchWeather(bot, args); };
JavaScript
0.999968
@@ -2660,16 +2660,17 @@ not avai +l able at
f258286c431b46f944ecaffb319bf44b749f04f4
Fix #149 TextCell should trigger error and high light the text box if the formatter returns undefined
src/extensions/text-cell/backgrid-text-cell.js
src/extensions/text-cell/backgrid-text-cell.js
/* backgrid-text-cell http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT @license. */ (function (window, $, _, Backbone, Backgrid) { /** Renders a form with a text area and a save button in a modal dialog. @class Backgrid.Extension.TextareaEditor @extends Backgrid.CellEditor */ var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({ /** @property */ tagName: "div", /** @property */ className: "modal hide fade", /** @property {function(Object, ?Object=): string} template */ template: _.template('<form><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h3><%- column.get("label") %></h3></div><div class="modal-body"><textarea cols="<%= cols %>" rows="<%= rows %>"><%- content %></textarea></div><div class="modal-footer"><input class="btn" type="submit" value="Save"/></div></form>'), /** @property */ cols: 80, /** @property */ rows: 10, /** @property */ events: { "keydown textarea": "clearError", "submit": "saveOrCancel", "hide": "saveOrCancel", "hidden": "close", "shown": "focus" }, /** @property {Object} modalOptions The options passed to Bootstrap's modal plugin. */ modalOptions: { backdrop: false }, /** Renders a modal form dialog with a textarea, submit button and a close button. */ render: function () { this.$el.html($(this.template({ column: this.column, cols: this.cols, rows: this.rows, content: this.formatter.fromRaw(this.model.get(this.column.get("name"))) }))); this.delegateEvents(); this.$el.modal(this.modalOptions); return this; }, /** Event handler. Saves the text in the text area to the model when submitting. When cancelling, if the text area is dirty, a confirmation dialog will pop up. If the user clicks confirm, the text will be saved to the model. Triggers a Backbone `backgrid:error` event from the model along with the model, column and the existing value as the parameters if the value cannot be converted. @param {Event} e */ saveOrCancel: function (e) { if (e && e.type == "submit") { e.preventDefault(); e.stopPropagation(); } var model = this.model; var column = this.column; var val = this.$el.find("textarea").val(); var newValue = this.formatter.toRaw(val); if (_.isUndefined(newValue)) { model.trigger("backgrid:error", model, column, val); if (e) { e.preventDefault(); e.stopPropagation(); } } else if (!e || e.type == "submit" || (e.type == "hide" && newValue !== (this.model.get(this.column.get("name")) || '').replace(/\r/g, '') && window.confirm("Would you like to save your changes?"))) { model.set(column.get("name"), newValue); this.$el.modal("hide"); } else if (e.type != "hide") this.$el.modal("hide"); }, clearError: _.debounce(function () { if (this.formatter.toRaw(this.$el.find("textarea").val())) { this.$el.parent().removeClass("error"); } }, 150), /** Triggers a `backgrid:edited` event along with the cell editor as the parameter after the modal is hidden. @param {Event} e */ close: function (e) { var model = this.model; model.trigger("backgrid:edited", model, this.column, new Backgrid.Command(e)); }, /** Focuses the textarea when the modal is shown. */ focus: function () { this.$el.find("textarea").focus(); } }); /** TextCell is a string cell type that renders a form with a text area in a modal dialog instead of an input box editor. It is best suited for entering a large body of text. @class Backgrid.Extension.TextCell @extends Backgrid.StringCell */ var TextCell = Backgrid.Extension.TextCell = Backgrid.StringCell.extend({ /** @property */ className: "text-cell", /** @property */ editor: TextareaEditor }); }(window, jQuery, _, Backbone, Backgrid));
JavaScript
0
@@ -3215,24 +3215,90 @@ %22);%0A %7D,%0A%0A + /**%0A Clears the error class on the parent cell.%0A */%0A clearErr @@ -3335,16 +3335,31 @@ if +(!_.isUndefined (this.fo @@ -3405,16 +3405,17 @@ .val())) +) %7B%0A
f9451d9339839e32fab7c6c27e6fcc32dfe75037
make composition cache work
lib/composition.js
lib/composition.js
var File = require('./file'); var Cache = require('./cache'); var Module = require('./module'); var utils = require('./client/utils'); var composition_cache = Cache('compositions'); /** * Get module instance composition. */ module.exports = function (name, role, callback) { // get composition from cache var composition = composition_cache.get(name); switch (composition) { // handle invalid composition configuration case 'INVALID': return callback(new Error('Invalid composition "' + name + '".')); // handle cache hit case !undefined: // check access for cached item if (!utils.roleAccess(composition, role)) { return callback(new Error('Access denied for composition "' + name + '"')); } // return if composition is complete if (!composition.LOAD) { return callback(null, composition); } } // read the composition json File.json(engine.paths.app_composition + name + '.json', function (err, config) { // handle error if ((err = err || checkComposition(name, role, config))) { return callback(err); } // create mandatory package infos to custom module if (typeof config.module === 'object') { config.module.name = name; config.module.version = 'custom'; config.module._id = name + '@custom'; module._base = engine.repo; } Module(config.module, function (err, modulePackage) { // handle module package error if (err) { return callback(err); } // prepare instance components if (config.client && (config.client.styles || config.client.markup)) { // send module id and module base var components = { base: modulePackage._base, module: modulePackage._id, styles: config.client.styles, markup: config.client.markup }; File.prepare(components, function (err, files) { // update file paths in module package if (files.styles) { config.client.styles = files.styles; } if (files.markup) { config.client.markup = files.markup; } finish(name, modulePackage, config, callback); }); return; } finish(name, modulePackage, config, callback); }); }); }; function finish (name, modulePackage, config, callback) { // merge package data into config if (modulePackage.composition) { config = mergePackage(modulePackage.version, modulePackage.composition, config); } // save composition in cache composition_cache.set(name, config); // return composition config callback(null, config); } /** * Check composition config. */ function checkComposition (name, role, config) { // handle not found if (!config) { return new Error('composition "' + name +'" not found.'); } // check if composition has a module if (!config.module) { // save as invalid in cache composition_cache.set(name, 'INVALID'); return new Error('No module info in composition "' + name + '".'); } // check access if (!utils.roleAccess(config, role)) { // save access information in cache, to check access without loading the hole file again composition_cache.set(name, {roles: config.roles, LOAD: true}); return new Error('Access denied: Role "' + role + '", Composition "' + name + '".'); } // set composition name as custom module name if (typeof config.module === 'object' && !config.module.name) { config.module.name = config.name; } } /** * Merge package config into composition config. */ function mergePackage (version, package_instance, config) { // merge client related options if (package_instance.client) { // ensure client config object config.client = config.client || {}; config.client.name = config.name; config.client.version = version; // set client module scripts if (package_instance.client.module) { config.client.module = package_instance.client.module; } // config if (package_instance.client.config) { for (var key in package_instance.client.config) { if (typeof config.client.config[key] === 'undefined') { config.client.config[key] = package_instance.client.config[key]; } } } // flow if (package_instance.client.flow) { config.client.flow = (config.client.flow || []).concat(package_instance.client.flow); } // markup if (package_instance.client.markup) { config.client.markup = (config.client.markup || []).concat(package_instance.client.markup); } // styles if (package_instance.client.styles) { config.client.styles = (config.client.styles || []).concat(package_instance.client.styles); } } // server flow if (package_instance.flow) { config.flow = (config.flow || []).concat(package_instance.flow); } // merge server config if (package_instance.config) { for (var prop in package_instance.config) { if (typeof config.config[prop] === 'undefined') { config.config[prop] = package_instance.config[prop]; } } } return config; }
JavaScript
0
@@ -368,14 +368,10 @@ -switch +if (co @@ -383,22 +383,16 @@ tion) %7B%0A - %0A @@ -396,64 +396,27 @@ -// handle invalid composition configuration%0A case +if (composition === 'IN @@ -421,17 +421,19 @@ INVALID' -: +) %7B %0A @@ -516,79 +516,11 @@ -%0A // handle cache hit%0A case !undefined:%0A %0A +%7D%0A%0A @@ -554,28 +554,24 @@ hed item %0A - if ( @@ -606,28 +606,24 @@ n, role)) %7B%0A - @@ -706,39 +706,19 @@ - %7D%0A %0A +%7D%0A%0A @@ -758,28 +758,24 @@ ete%0A - - if (!composi @@ -783,28 +783,24 @@ ion.LOAD) %7B%0A - @@ -835,20 +835,16 @@ ition);%0A - @@ -851,18 +851,16 @@ %7D%0A %7D%0A - %0A //
2533551dcd46caa844436ec5f9b1aa83912291c4
Implement signup email handler and email state * Re-order state object to reflect order of inputs
client/mobile/components/shared/signup.js
client/mobile/components/shared/signup.js
var React = require('react-native'); var Login = require('./login'); var JoinClassView = require('./../student/joinClassView'); var StartClassView = require('./../teacher/startClassView'); var api = require('./../../utils/api'); var { View, Text, StyleSheet, TextInput, TouchableHighlight, Picker, ActivityIndicatorIOS, Navigator } = React; class Signup extends React.Component { constructor(props) { super(props); this.state = { username: '', password: '', confirmedPassword: '', firstName: '', lastName: '', accountType: 'student', isLoading: false, error: false, passwordError: false }; } handleFirstNameChange(event) { this.setState({ firstName: event.nativeEvent.text }); } handleLastNameChange(event) { this.setState({ lastName: event.nativeEvent.text }); } handleUsernameChange(event) { this.setState({ username: event.nativeEvent.text }); } handlePasswordChange(event) { this.setState({ password: event.nativeEvent.text }); } handleConfirmedPasswordChange(event) { this.setState({ confirmedPassword: event.nativeEvent.text }); } handleSubmit() { if (this.state.password === this.state.confirmedPassword) { this.setState({ isLoading: true, passwordError: false }); api.signup(this.state.username, this.state.password, this.state.firstName, this.state.lastName, this.state.accountType) .then((response) => { if(response.status === 500){ this.setState({ error: 'User already exists', password: '', confirmedPassword: '', isLoading: false }); } else if(response.status === 200) { //keychain stuff? var body = JSON.parse(response._bodyText); if(body.teacher) { this.props.navigator.push({ component: StartClassView, classes: body.teacher.classes, userId: body.teacher.uid, sceneConfig: { ...Navigator.SceneConfigs.FloatFromBottom, gestures: {} } }); } else if (body.student) { this.props.navigator.push({ component: JoinClassView, classes: body.student.classes, userId: body.student.uid, sceneConfig: { ...Navigator.SceneConfigs.FloatFromBottom, gestures: {} } }); } } }) .catch((err) => { this.setState({ error: 'User already exists' + err, isLoading: false }); }); } else { this.setState({ isLoading: false, password: '', confirmedPassword: '', passwordError: 'passwords do not match' }); } } handleRedirect() { this.props.navigator.pop(); } render() { var showErr = ( this.state.error ? <Text style={styles.err}> {this.state.error} </Text> : <View></View> ); var showPasswordErr = ( this.state.passwordError ? <Text style={styles.err}> {this.state.passwordError} </Text> : <View></View> ); return ( <View style={{flex: 1, backgroundColor: 'white'}}> <View style={styles.mainContainer}> <Text style={styles.fieldTitle}> Username </Text> <TextInput autoCapitalize={'none'} autoCorrect={false} maxLength={16} style={styles.userInput} value={this.state.username} returnKeyType={'next'} onChange={this.handleUsernameChange.bind(this)} onSubmitEditing={(event) => { this.refs.SecondInput.focus(); }} /> <Text style={styles.fieldTitle}> Password </Text> <TextInput ref='SecondInput' autoCapitalize={'none'} autoCorrect={false} maxLength={16} secureTextEntry={true} style={styles.userInput} value={this.state.password} returnKeyType={'next'} onChange={this.handlePasswordChange.bind(this)} onSubmitEditing={(event) => { this.refs.ThirdInput.focus(); }} /> <Text style={styles.fieldTitle}> Confirm Password </Text> <TextInput ref='ThirdInput' autoCapitalize={'none'} autoCorrect={false} maxLength={16} secureTextEntry={true} style={styles.userInput} value={this.state.confirmedPassword} returnKeyType={'go'} onSubmitEditing={this.handleSubmit.bind(this)} onChange={this.handleConfirmedPasswordChange.bind(this)} /> <Text style={styles.fieldTitle}> Account Type </Text> <Picker style={styles.picker} selectedValue={this.state.accountType} onValueChange={(type) => this.setState({accountType: type})}> <Picker.Item label="Student" value="student" /> <Picker.Item label="Teacher" value="teacher" /> </Picker> <TouchableHighlight style={styles.button} onPress={this.handleSubmit.bind(this)} underlayColor='#e66365' > <Text style={styles.buttonText}> Sign Up </Text> </TouchableHighlight> <TouchableHighlight onPress={this.handleRedirect.bind(this)} underlayColor='#ededed' > <Text style={styles.signin}> Already have an account? Sign in! </Text> </TouchableHighlight> <ActivityIndicatorIOS animating= {this.state.isLoading} size='large' style={styles.loading} /> {showErr} {showPasswordErr} </View> </View> ); } } var styles = StyleSheet.create({ mainContainer: { flex: 1, padding: 30, flexDirection: 'column', justifyContent: 'center', }, fieldTitle: { marginTop: 10, marginBottom: 15, fontSize: 18, textAlign: 'center', color: '#616161' }, userInput: { height: 50, padding: 4, fontSize: 18, borderWidth: 1, borderColor: '#616161', borderRadius: 4, color: '#616161' }, picker: { bottom: 70, height: 70 }, buttonText: { fontSize: 18, color: 'white', alignSelf: 'center' }, button: { height: 45, flexDirection: 'row', backgroundColor: '#FF5A5F', borderColor: 'transparent', borderWidth: 1, borderRadius: 4, marginBottom: 10, marginTop: 30, alignSelf: 'stretch', justifyContent: 'center' }, signin: { marginTop: 20, fontSize: 14, textAlign: 'center' }, loading: { marginTop: 20 }, err: { fontSize: 14, textAlign: 'center' }, }); module.exports = Signup;
JavaScript
0
@@ -453,29 +453,30 @@ e = %7B%0A -usern +firstN ame: '',%0A @@ -474,32 +474,32 @@ : '',%0A -password +lastName : '',%0A @@ -498,33 +498,24 @@ ,%0A -confirmedPassword +username : '',%0A @@ -514,33 +514,29 @@ : '',%0A -firstName +email : '',%0A @@ -531,32 +531,61 @@ : '',%0A -lastName +password: '',%0A confirmedPassword : '',%0A @@ -997,32 +997,130 @@ xt%0A %7D);%0A %7D%0A%0A + handleEmailChange(event) %7B%0A this.setState(%7B%0A email: event.nativeEvent.text%0A %7D);%0A %7D%0A%0A handlePassword
b7a634649f273aff78eef8fda8cf5f1a3075016e
Implement signup email handler and email state * Re-order state object to reflect order of inputs
client/mobile/components/shared/signup.js
client/mobile/components/shared/signup.js
var React = require('react-native'); var Login = require('./login'); var JoinClassView = require('./../student/joinClassView'); var StartClassView = require('./../teacher/startClassView'); var api = require('./../../utils/api'); var { View, Text, StyleSheet, TextInput, TouchableHighlight, Picker, ActivityIndicatorIOS, Navigator } = React; class Signup extends React.Component { constructor(props) { super(props); this.state = { username: '', password: '', confirmedPassword: '', firstName: '', lastName: '', accountType: 'student', isLoading: false, error: false, passwordError: false }; } handleFirstNameChange(event) { this.setState({ firstName: event.nativeEvent.text }); } handleLastNameChange(event) { this.setState({ lastName: event.nativeEvent.text }); } handleUsernameChange(event) { this.setState({ username: event.nativeEvent.text }); } handlePasswordChange(event) { this.setState({ password: event.nativeEvent.text }); } handleConfirmedPasswordChange(event) { this.setState({ confirmedPassword: event.nativeEvent.text }); } handleSubmit() { if (this.state.password === this.state.confirmedPassword) { this.setState({ isLoading: true, passwordError: false }); api.signup(this.state.username, this.state.password, this.state.firstName, this.state.lastName, this.state.accountType) .then((response) => { if(response.status === 500){ this.setState({ error: 'User already exists', password: '', confirmedPassword: '', isLoading: false }); } else if(response.status === 200) { //keychain stuff? var body = JSON.parse(response._bodyText); if(body.teacher) { this.props.navigator.push({ component: StartClassView, classes: body.teacher.classes, userId: body.teacher.uid, sceneConfig: { ...Navigator.SceneConfigs.FloatFromBottom, gestures: {} } }); } else if (body.student) { this.props.navigator.push({ component: JoinClassView, classes: body.student.classes, userId: body.student.uid, sceneConfig: { ...Navigator.SceneConfigs.FloatFromBottom, gestures: {} } }); } } }) .catch((err) => { this.setState({ error: 'User already exists' + err, isLoading: false }); }); } else { this.setState({ isLoading: false, password: '', confirmedPassword: '', passwordError: 'passwords do not match' }); } } handleRedirect() { this.props.navigator.pop(); } render() { var showErr = ( this.state.error ? <Text style={styles.err}> {this.state.error} </Text> : <View></View> ); var showPasswordErr = ( this.state.passwordError ? <Text style={styles.err}> {this.state.passwordError} </Text> : <View></View> ); return ( <View style={{flex: 1, backgroundColor: 'white'}}> <View style={styles.mainContainer}> <Text style={styles.fieldTitle}> Username </Text> <TextInput autoCapitalize={'none'} autoCorrect={false} maxLength={16} style={styles.userInput} value={this.state.username} returnKeyType={'next'} onChange={this.handleUsernameChange.bind(this)} onSubmitEditing={(event) => { this.refs.SecondInput.focus(); }} /> <Text style={styles.fieldTitle}> Password </Text> <TextInput ref='SecondInput' autoCapitalize={'none'} autoCorrect={false} maxLength={16} secureTextEntry={true} style={styles.userInput} value={this.state.password} returnKeyType={'next'} onChange={this.handlePasswordChange.bind(this)} onSubmitEditing={(event) => { this.refs.ThirdInput.focus(); }} /> <Text style={styles.fieldTitle}> Confirm Password </Text> <TextInput ref='ThirdInput' autoCapitalize={'none'} autoCorrect={false} maxLength={16} secureTextEntry={true} style={styles.userInput} value={this.state.confirmedPassword} returnKeyType={'go'} onSubmitEditing={this.handleSubmit.bind(this)} onChange={this.handleConfirmedPasswordChange.bind(this)} /> <Text style={styles.fieldTitle}> Account Type </Text> <Picker style={styles.picker} selectedValue={this.state.accountType} onValueChange={(type) => this.setState({accountType: type})}> <Picker.Item label="Student" value="student" /> <Picker.Item label="Teacher" value="teacher" /> </Picker> <TouchableHighlight style={styles.button} onPress={this.handleSubmit.bind(this)} underlayColor='#e66365' > <Text style={styles.buttonText}> Sign Up </Text> </TouchableHighlight> <TouchableHighlight onPress={this.handleRedirect.bind(this)} underlayColor='#ededed' > <Text style={styles.signin}> Already have an account? Sign in! </Text> </TouchableHighlight> <ActivityIndicatorIOS animating= {this.state.isLoading} size='large' style={styles.loading} /> {showErr} {showPasswordErr} </View> </View> ); } } var styles = StyleSheet.create({ mainContainer: { flex: 1, padding: 30, flexDirection: 'column', justifyContent: 'center', }, fieldTitle: { marginTop: 10, marginBottom: 15, fontSize: 18, textAlign: 'center', color: '#616161' }, userInput: { height: 50, padding: 4, fontSize: 18, borderWidth: 1, borderColor: '#616161', borderRadius: 4, color: '#616161' }, picker: { bottom: 70, height: 70 }, buttonText: { fontSize: 18, color: 'white', alignSelf: 'center' }, button: { height: 45, flexDirection: 'row', backgroundColor: '#FF5A5F', borderColor: 'transparent', borderWidth: 1, borderRadius: 4, marginBottom: 10, marginTop: 30, alignSelf: 'stretch', justifyContent: 'center' }, signin: { marginTop: 20, fontSize: 14, textAlign: 'center' }, loading: { marginTop: 20 }, err: { fontSize: 14, textAlign: 'center' }, }); module.exports = Signup;
JavaScript
0
@@ -453,29 +453,30 @@ e = %7B%0A -usern +firstN ame: '',%0A @@ -474,32 +474,32 @@ : '',%0A -password +lastName : '',%0A @@ -498,33 +498,24 @@ ,%0A -confirmedPassword +username : '',%0A @@ -514,33 +514,29 @@ : '',%0A -firstName +email : '',%0A @@ -531,32 +531,61 @@ : '',%0A -lastName +password: '',%0A confirmedPassword : '',%0A @@ -997,32 +997,130 @@ xt%0A %7D);%0A %7D%0A%0A + handleEmailChange(event) %7B%0A this.setState(%7B%0A email: event.nativeEvent.text%0A %7D);%0A %7D%0A%0A handlePassword
93a63d4371249b1d3d8f0c934153804261d6e072
add promise rejection error reporting
client/scripts/arcademode/actions/test.js
client/scripts/arcademode/actions/test.js
'use strict'; export const OUTPUT_CHANGED = 'OUTPUT_CHANGED'; export const TESTS_STARTED = 'TESTS_STARTED'; export const TESTS_FINISHED = 'TESTS_FINISHED'; export function onOutputChange(newOutput) { return { type: OUTPUT_CHANGED, userOutput: newOutput }; } /* Thunk action which runs the test cases against user code. */ export function runTests(userCode, currChallenge) { return dispatch => { dispatch(actionTestsStarted()); // Eval user code inside worker // http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766 function createWorker () { return new Promise((resolve, reject) => { const wk = new Worker('../../public/js/worker.bundle.js'); wk.postMessage([userCode, currChallenge.toJS()]); // postMessage mangles the Immutable object, so it needs to be transformed into regular JS before sending over to worker. wk.onmessage = e => { // console.log(`worker onmessage result: ${e.data}`); resolve(e.data); }; }); } return createWorker() .then(workerData => { dispatch(onOutputChange(workerData[0].output)); if (workerData.length > 1) { dispatch(actionTestsFinished(workerData.slice(1))); } }); }; } /* Dispatched when a user starts running the tests.*/ export function actionTestsStarted () { return { type: TESTS_STARTED }; } /* Dispatched when the tests finish. */ export function actionTestsFinished (testResults) { return { type: TESTS_FINISHED, testResults }; }
JavaScript
0
@@ -610,16 +610,17 @@ 6255766%0A +%0A func @@ -1309,24 +1309,91 @@ %7D%0A %7D) +%0A .catch(err =%3E %7B console.log(%60Promise rejected: $%7Berr%7D.%60); %7D) ;%0A %7D;%0A%7D%0A%0A/*
31e94b683dbe349bd19c1c0d9f279b0b6c2f46e5
Update to new redis port to reduce potential collisions
lib/core/config.js
lib/core/config.js
'use strict'; var path = require('path'); var fs = require('fs'); var env = require('./env.js'); var deps = require('./deps.js'); // Constants var CONFIG_FILENAME = 'kalabox.json'; exports.CONFIG_FILENAME = CONFIG_FILENAME; var DEFAULT_GLOBAL_CONFIG = { domain: 'kbox', kboxRoot: ':home:/kalabox', kalaboxRoot: ':kboxRoot:', appsRoot: ':kboxRoot:/apps', sysConfRoot: ':home:/.kalabox', globalPluginRoot: ':kboxRoot:/plugins', globalPlugins: [ 'hipache', 'kalabox_core', 'kalabox_install', 'kalabox_app', 'kalabox_b2d' ], redis: { // @todo: Dynamically set this. host: '1.3.3.7', port: 6379 }, // @this needs to be set dynamically once we merge in config.js dockerHost: '1.3.3.7', startupServicePrefix: 'kalabox_', startupServices: { kalaboxDebian: { name: 'kalabox/debian', containers : { kalaboxSkydns: { name: 'kalabox/skydns', createOpts : { name: 'skydns', HostConfig : { NetworkMode: 'bridge', PortBindings: { '53/udp' : [{'HostIp' : '172.17.42.1', 'HostPort' : '53'}], } } }, startOpts : {} }, kalaboxSkydock: { name: 'kalabox/skydock', createOpts : { name: 'skydock', HostConfig : { NetworkMode: 'bridge', Binds : ['/var/run/docker.sock:/docker.sock', '/skydock.js:/skydock.js'] } }, startOpts : {} }, kalaboxHipache: { name: 'kalabox/hipache', createOpts : { name: 'hipache', HostConfig : { NetworkMode: 'bridge', PortBindings: { '80/tcp' : [{'HostIp' : '', 'HostPort' : '80'}], '6379/tcp' : [{'HostIp' : '', 'HostPort' : '6379'}], } } }, startOpts : {} }, kalaboxDnsmasq: { name: 'kalabox/dnsmasq', createOpts : { name: 'dnsmasq', Env: ['KALABOX_IP=1.3.3.7'], ExposedPorts: { '53/tcp': {}, '53/udp': {} }, HostConfig : { NetworkMode: 'bridge', PortBindings: { '53/udp' : [{'HostIp' : '1.3.3.7', 'HostPort' : '53'}] } } }, startOpts : {} } } } } }; // @todo: implement //var KEYS_TO_CONCAT = {}; function normalizeValue(key, config) { var rawValue = config[key]; if (typeof rawValue === 'string') { var params = rawValue.match(/:[a-zA-Z0-9-_]*:/g); if (params !== null) { for (var index in params) { var param = params[index]; var paramKey = param.substr(1, param.length - 2); var paramValue = config[paramKey]; if (paramValue !== undefined) { config[key] = rawValue.replace(param, paramValue); } } } } } exports.normalizeValue = normalizeValue; function normalize(config) { for (var key in config) { normalizeValue(key, config); } return config; } exports.normalize = normalize; function mixIn(a, b/*, keysToConcat*/) { /*if (!keysToConcat) { keysToConcat = KEYS_TO_CONCAT; }*/ for (var key in b) { //var shouldConcat = keysToConcat[key] !== undefined; var shouldConcat = false; if (shouldConcat) { // Concat. if (a[key] === undefined) { a[key] = b[key]; } else { a[key] = a[key].concat(b[key]); } } else { // Override. a[key] = b[key]; } } return normalize(a); } exports.mixIn = mixIn; exports.getEnvConfig = function() { return { home: env.getHomeDir(), srcRoot: env.getSourceRoot() }; }; exports.getDefaultConfig = function() { return mixIn(this.getEnvConfig(), DEFAULT_GLOBAL_CONFIG); }; var getGlobalConfigFilepath = function() { return path.join(env.getKalaboxRoot(), CONFIG_FILENAME); }; var loadConfigFile = function(configFilepath) { return require(configFilepath); }; exports.getGlobalConfig = function() { var defaultConfig = this.getDefaultConfig(); var globalConfigFilepath = getGlobalConfigFilepath(); if (fs.existsSync(globalConfigFilepath)) { var globalConfigFile = loadConfigFile(globalConfigFilepath); return mixIn(defaultConfig, globalConfigFile); } else { return defaultConfig; } }; exports.getAppConfigFilepath = function(app, config) { return path.join(config.appsRoot, app.name, CONFIG_FILENAME); }; exports.getAppConfig = function(app) { var globalConfig = this.getGlobalConfig(); var appRoot = path.join(globalConfig.appsRoot, app.name); var appConfigFilepath = path.join(appRoot, CONFIG_FILENAME); var appConfigFile = require(appConfigFilepath); appConfigFile.appRoot = appRoot; appConfigFile.appCidsRoot = ':appRoot:/.cids'; return mixIn(globalConfig, appConfigFile); };
JavaScript
0
@@ -631,20 +631,20 @@ port: -6379 +8160 %0A %7D,%0A @@ -1842,20 +1842,20 @@ ' -6379 +8160 /tcp' : @@ -1889,12 +1889,12 @@ : ' -6379 +8160 '%7D%5D,
2fd85899d20ad2d15555c6975f16e095dfc348f3
add exception handling for cloudflare error.
lib/courier/jnt.js
lib/courier/jnt.js
'use strict' var request = require('request') var moment = require('moment') var tracker = require('../') var trackingInfo = function (number) { return { method: 'POST', url: 'https://www.jtexpress.ph/index/router/index.html', json: true, body: { method: 'app.findTrack', data: { billcode: number, lang: 'en', source: 3 } } } } var parser = { trace: function (data) { var courier = { code: tracker.COURIER.JNT.CODE, name: tracker.COURIER.JNT.NAME } var result = { courier: courier, number: data.billcode, status: tracker.STATUS.PENDING } var checkpoints = [] for (var i = 0; i < data.details.length; i++) { var item = data.details[i] var message = [ item.desc ].join(' - ') var checkpoint = { courier: courier, location: item.city || item.siteName, message: message, status: tracker.STATUS.IN_TRANSIT, time: moment(item.scantime + 'T+0800', 'YYYY-MM-DD HH:mm:ssZ').utc().format('YYYY-MM-DDTHH:mmZ') } if (item.scantype === 'Delivered') { checkpoint.status = tracker.STATUS.DELIVERED } checkpoints.push(checkpoint) } result.checkpoints = checkpoints result.status = tracker.normalizeStatus(result.checkpoints) return result } } module.exports = function () { return { trackingInfo: trackingInfo, trace: function (number, cb) { var tracking = trackingInfo(number) request(tracking, function (err, res, body) { if (err) { return cb(err) } try { var result = parser.trace(JSON.parse(body.data)) cb(result ? null : tracker.error(tracker.ERROR.INVALID_NUMBER), result) } catch (e) { cb(tracker.error(e.message)) } }) } } }
JavaScript
0
@@ -1645,16 +1645,124 @@ try %7B%0A + if (res.statusCode !== 200) %7B%0A return cb(tracker.error(res.statusMessage))%0A %7D%0A
3d5f46d4917d6eadf46a8e1d772ff7f9f410a29e
Prepare new Info to be in modal
client/src/components/shared/Info/Info.js
client/src/components/shared/Info/Info.js
// @flow import React, {Fragment} from 'react' import Circle from 'react-icons/lib/fa/circle-o' import {Container} from 'reactstrap' import {Link} from 'react-router-dom' import type {Node} from 'react' import { getNewFinancialData, icoUrl, ShowNumberCurrency, showDate, } from '../../../services/utilities' import {compose, withHandlers} from 'recompose' import {connect} from 'react-redux' import {zoomToLocation} from '../../../actions/verejneActions' import {ENTITY_CLOSE_ZOOM} from '../../../constants' import Contracts from './Contracts' import Notices from './Notices' import Eurofunds from './Eurofunds' import Relations from './Relations' import Trend from './Trend' import ExternalLink from '../ExternalLink' import mapIcon from '../../../assets/mapIcon.svg' import type {NewEntityDetail} from '../../../state' import type {FinancialData} from '../../../services/utilities' import './Info.css' type InfoProps = { data: NewEntityDetail, canClose?: boolean, onClose?: () => void, } type ItemProps = { children?: Node, label?: string, url?: string, linkText?: Node, } const Item = ({children, label, url, linkText}: ItemProps) => ( <li className="info-item"> {label && <strong className="info-item-label">{label}</strong>} {url && ( <ExternalLink isMapView={false} url={url}> {linkText} </ExternalLink> )} {children} </li> ) const Findata = ({data}: {data: FinancialData}) => { const finances = data.finances[0] || {} // possible feature: display finances also for older years return ( <Fragment> <Item label="IČO" url={`http://www.orsr.sk/hladaj_ico.asp?ICO=${data.ico}&SID=0`} // TODO link to zrsr when there is a way to tell companies and persons apart linkText={data.ico} > &nbsp;(<ExternalLink isMapView={false} url={icoUrl(data.ico)}> Detaily o firme </ExternalLink>) </Item> {data.established_on && <Item label="Založená">{showDate(data.established_on)}</Item>} {data.terminated_on && <Item label="Zaniknutá">{showDate(data.terminated_on)}</Item>} {finances.employees && ( <Item label={`Zamestnanci v ${finances.year}`}>{finances.employees}</Item> )} {finances.profit ? ( <Item label={`Zisk v ${finances.year}`} url={icoUrl(data.ico)} linkText={<ShowNumberCurrency num={finances.profit} />} > {finances.profitTrend ? <Trend trend={finances.profitTrend} /> : null} </Item> ) : null} {finances.revenue ? ( <Item label={`Tržby v ${finances.year}`} url={icoUrl(data.ico)} linkText={<ShowNumberCurrency num={finances.revenue} />} > {finances.revenueTrend ? <Trend trend={finances.revenueTrend} /> : null} </Item> ) : null} </Fragment> ) } const Info = ({data, canClose, onClose, showOnMap}: InfoProps) => ( <Container className={canClose ? 'info closable' : 'info'}> <div className="info-header"> <h3 onClick={onClose}> <Circle aria-hidden="true" />&nbsp;{data.name}&nbsp; </h3> <Link to={`/verejne?lat=${data.lat}&lng=${data.lng}&zoom=${ENTITY_CLOSE_ZOOM}`} title="Zobraz na mape" onClick={showOnMap} > <img src={mapIcon} alt="MapMarker" style={{width: '16px', height: '25px'}} /> </Link> {canClose && ( <span className="info-close-button" onClick={onClose}> &times; </span> )} </div> <div className="info-main"> <ul className="info-list"> <Item>{data.address}</Item> {data.companyinfo && <Findata data={getNewFinancialData(data)} />} {data.contracts && data.contracts.price_amount_sum > 0 && ( <Item label="Verejné zákazky" url={`http://www.otvorenezmluvy.sk/documents/search?utf8=%E2%9C%93&q=${data.name}`} linkText={<ShowNumberCurrency num={data.contracts.price_amount_sum} />} /> )} </ul> {data.contracts && data.contracts.count > 0 && <Contracts data={data.contracts} />} {data.notices && data.notices.count > 0 && <Notices data={data.notices} />} {data.eufunds && data.eufunds.eufunds_count > 0 && <Eurofunds data={data.eufunds} />} {data.related.length > 0 && <Relations data={data.related} useNewApi />} </div> </Container> ) export default compose( connect(null, {zoomToLocation}), withHandlers({ showOnMap: ({data, zoomToLocation}) => () => { data.toggleModalOpen && data.toggleModalOpen() zoomToLocation(data, ENTITY_CLOSE_ZOOM) }, }) )(Info)
JavaScript
0
@@ -416,16 +416,33 @@ Location +, toggleModalOpen %7D from ' @@ -968,16 +968,37 @@ Detail,%0A + inModal?: boolean,%0A canClo @@ -4535,16 +4535,33 @@ Location +, toggleModalOpen %7D),%0A wi @@ -4595,16 +4595,25 @@ (%7Bdata, + inModal, zoomToL @@ -4619,16 +4619,33 @@ Location +, toggleModalOpen %7D) =%3E () @@ -4660,37 +4660,19 @@ -data.toggleModalOpen && data. +inModal && togg
138ad3b71603f2f1ce7a05954c2e065b41d339cb
Update to ES6 syntax
client/webpack.production.config.babel.js
client/webpack.production.config.babel.js
/* global module, __dirname */ import path from "path"; import webpack from "webpack"; import HTMLPlugin from "html-webpack-plugin"; import CleanPlugin from "clean-webpack-plugin"; import ExtractTextPlugin from "extract-text-webpack-plugin"; import UglifyJSPlugin from "uglifyjs-webpack-plugin"; module.exports = { entry: ["babel-polyfill", "./src/js/index.js"], module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: [ "babel-loader", { loader: "eslint-loader", options: { configFile: path.resolve(__dirname, "./.eslintrc") } } ] }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.less$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: [ {loader: "css-loader"}, {loader: "less-loader"} ] }) }, { test: /\.woff$/, use: { loader: "url-loader?limit=100000" } } ] }, node: { fs: "empty" }, mode: "production", output: { path: path.resolve(__dirname, "./dist"), filename: "app.[hash:8].js", sourceMapFilename: "[name].js.map", publicPath: "/static/" }, plugins: [ new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }), new ExtractTextPlugin("style.[hash:8].css"), new HTMLPlugin({ filename: "index.html", title: "Virtool", favicon: "./src/images/favicon.ico", template: "./src/index.html", inject: "body" }), new CleanPlugin(["dist"], { verbose: true }), new UglifyJSPlugin({ sourceMap: true }) ] };
JavaScript
0
@@ -6,16 +6,8 @@ obal - module, __d @@ -286,24 +286,22 @@ %22;%0A%0A -module.exports = +export default %7B%0A%0A
37d3d04f0ec20f4145fcb9d90b805e706e948a41
Clean mediatag integration code
www/common/diffMarked.js
www/common/diffMarked.js
define([ 'jquery', '/bower_components/marked/marked.min.js', '/common/cryptpad-common.js', '/common/media-tag.js', '/bower_components/diff-dom/diffDOM.js', '/bower_components/tweetnacl/nacl-fast.min.js', ],function ($, Marked, Cryptpad, MediaTag) { var DiffMd = {}; var DiffDOM = window.diffDOM; var renderer = new Marked.Renderer(); Marked.setOptions({ renderer: renderer }); DiffMd.render = function (md) { return Marked(md); }; // Tasks list var checkedTaskItemPtn = /^\s*\[x\]\s*/; var uncheckedTaskItemPtn = /^\s*\[ \]\s*/; renderer.listitem = function (text) { var isCheckedTaskItem = checkedTaskItemPtn.test(text); var isUncheckedTaskItem = uncheckedTaskItemPtn.test(text); if (isCheckedTaskItem) { text = text.replace(checkedTaskItemPtn, '<i class="fa fa-check-square" aria-hidden="true"></i>&nbsp;') + '\n'; } if (isUncheckedTaskItem) { text = text.replace(uncheckedTaskItemPtn, '<i class="fa fa-square-o" aria-hidden="true"></i>&nbsp;') + '\n'; } var cls = (isCheckedTaskItem || isUncheckedTaskItem) ? ' class="todo-list-item"' : ''; return '<li'+ cls + '>' + text + '</li>\n'; }; renderer.image = function (href, title, text) { if (href.slice(0,6) === '/file/') { var parsed = Cryptpad.parsePadUrl(href); var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel); var mt = '<media-tag src="/blob/' + hexFileName.slice(0,2) + '/' + hexFileName + '" data-crypto-key="cryptpad:' + parsed.hashData.key + '"></media-tag>'; return mt; } var out = '<img src="' + href + '" alt="' + text + '"'; if (title) { out += ' title="' + title + '"'; } out += this.options.xhtml ? '/>' : '>'; return out; }; var forbiddenTags = [ 'SCRIPT', 'IFRAME', 'OBJECT', 'APPLET', 'VIDEO', 'AUDIO', ]; var unsafeTag = function (info) { if (info.node && $(info.node).parents('media-tag').length) { // Do not remove elements inside a media-tag return true; } if (['addAttribute', 'modifyAttribute'].indexOf(info.diff.action) !== -1) { if (/^on/.test(info.diff.name)) { console.log("Rejecting forbidden element attribute with name", info.diff.name); return true; } } if (['addElement', 'replaceElement'].indexOf(info.diff.action) !== -1) { var msg = "Rejecting forbidden tag of type (%s)"; if (info.diff.element && forbiddenTags.indexOf(info.diff.element.nodeName) !== -1) { console.log(msg, info.diff.element.nodeName); return true; } else if (info.diff.newValue && forbiddenTags.indexOf(info.diff.newValue.nodeName) !== -1) { console.log("Replacing restricted element type (%s) with PRE", info.diff.newValue.nodeName); info.diff.newValue.nodeName = 'PRE'; } } }; var getSubMediaTag = function (element) { var result = []; console.log(element); if (element.nodeName === "MEDIA-TAG") { result.push(element); return result; } if (element.childNodes) { element.childNodes.forEach(function (el) { result = result.concat(getSubMediaTag(el, result)); }); } console.log(result); return result; }; var mediaTag = function (info) { if (info.diff.action === 'addElement') { return getSubMediaTag(info.diff.element); //MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes); //MediaTag($mt[0]); } return; }; var slice = function (coll) { return Array.prototype.slice.call(coll); }; /* remove listeners from the DOM */ var removeListeners = function (root) { slice(root.attributes).map(function (attr) { if (/^on/.test(attr.name)) { root.attributes.removeNamedItem(attr.name); } }); // all the way down slice(root.children).forEach(removeListeners); }; var domFromHTML = function (html) { var Dom = new DOMParser().parseFromString(html, "text/html"); removeListeners(Dom.body); return Dom; }; //var toTransform = []; var DD = new DiffDOM({ preDiffApply: function (info) { if (unsafeTag(info)) { return true; } }, }); var makeDiff = function (A, B, id) { var Err; var Els = [A, B].map(function (frag) { if (typeof(frag) === 'object') { if (!frag || (frag && !frag.body)) { Err = "No body"; return; } var els = frag.body.querySelectorAll('#'+id); if (els.length) { return els[0]; } } Err = 'No candidate found'; }); if (Err) { return Err; } var patch = DD.diff(Els[0], Els[1]); return patch; }; DiffMd.apply = function (newHtml, $content) { var id = $content.attr('id'); if (!id) { throw new Error("The element must have a valid id"); } var $div = $('<div>', {id: id}).append(newHtml); var Dom = domFromHTML($('<div>').append($div).html()); var oldDom = domFromHTML($content[0].outerHTML); var patch = makeDiff(oldDom, Dom, id); if (typeof(patch) === 'string') { throw new Error(patch); } else { DD.apply($content[0], patch); var $mts = $content.find('media-tag:not(:has(*))'); $mts.each(function (i, el) { MediaTag(el); }); } }; $(window.document).on('decryption', function (e) { var decrypted = e.originalEvent; if (decrypted.callback) { decrypted.callback(); } }); return DiffMd; });
JavaScript
0
@@ -3189,752 +3189,8 @@ %7D;%0A%0A - var getSubMediaTag = function (element) %7B%0A var result = %5B%5D;%0A console.log(element);%0A if (element.nodeName === %22MEDIA-TAG%22) %7B%0A result.push(element);%0A return result;%0A %7D%0A if (element.childNodes) %7B%0A element.childNodes.forEach(function (el) %7B%0A result = result.concat(getSubMediaTag(el, result));%0A %7D);%0A %7D%0A console.log(result);%0A return result;%0A %7D;%0A var mediaTag = function (info) %7B%0A if (info.diff.action === 'addElement') %7B%0A return getSubMediaTag(info.diff.element);%0A //MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes);%0A //MediaTag($mt%5B0%5D);%0A %7D%0A return;%0A %7D;%0A %0A @@ -3810,36 +3810,8 @@ %7D;%0A%0A - //var toTransform = %5B%5D;%0A
7b2b3e9dfbf805da61b1e957e71bdd3bad0352dc
Fix typo
server/lib/client-info.js
server/lib/client-info.js
/** * Client info keyed on client id. Mainly used for logging. * Getting full details about a client is a multi-part process * since we get partial info when they request a token, and more * when they finally connect/authenticate over the web socket. */ var useragent = require('useragent'); var log = require('./logger.js'); function ClientInfo(id, userAgentString) { this.id = id; // User isn't yet known, we'll update this in update() later this.username = 'unauthenticated'; // Try to extract useful browser/device info try { var agent = useragent.parse(userAgentString); this.agent = agent.toString(); this.device = agent.device.toString(); } catch(err) { log.error({err: err}, 'Error parsing user agent string: `%s`', userAgentString); this.agent = "Unknown"; this.device = "Unknown"; } this.born = Date.now(); // How many times this client has sync'ed during this connection. this.downstreamSyncs = 0; this.upstreamSyncs = 0; // Web Socket data usage for this client this.bytesSent = 0; this.bytesRecevied = 0; } // How long this client has been connected in MS ClientInfo.prototype.connectedInMS = function() { return Date.now() - this.born; }; /** * Keep track of client info objects while they are still connected. */ var clients = {}; function remove(id) { delete clients[id]; } function find(client) { return clients[client.id]; } /** * Step 1: create a partial ClientInfo object when the client requests a token */ function init(id, userAgentString) { clients[id] = new ClientInfo(id, userAgentString); } /** * Step 2: update the ClientInfo object with all the client info when * web socket connection is completed. */ function update(client) { var id = client.id; // Auto-remove when this client is closed. client.once('closed', function() { remove(id); }); var info = find(client); if(!info) { log.warn('No ClientInfo object found for client.id=%s', id); return; } info.username = client.username; } module.exports = { init: init, update: update, remove: remove, find: find };
JavaScript
0.999999
@@ -1064,18 +1064,18 @@ ytesRece -v i +v ed = 0;%0A
205dba7e0e4a828ae27a4b08af3c67186e162a7a
Improve variable names
server/lib/userSession.js
server/lib/userSession.js
// // Copyright 2014 Ilkka Oksanen <iao@iki.fi> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // 'use strict'; const user = require('../models/user'); exports.auth = function *auth(next) { const cookie = this.cookies.get('auth') || ''; const ts = new Date(); this.mas = this.mas || {}; this.mas.user = null; const [ userId, secret ] = cookie.split('-'); if (userId && secret) { const userRecord = yield user.fetch(parseInt(userId)); if (userRecord && userRecord.get('secretExpires') > ts && userRecord.get('secret') === secret) { this.mas.user = userRecord; } } yield next; };
JavaScript
0.998747
@@ -643,17 +643,17 @@ %0A%0Aconst -u +U ser = re @@ -950,22 +950,16 @@ nst user -Record = yield @@ -959,17 +959,17 @@ = yield -u +U ser.fetc @@ -1010,22 +1010,16 @@ user -Record && user Reco @@ -1010,30 +1010,24 @@ user && user -Record .get('secret @@ -1047,31 +1047,13 @@ s && -%0A userRecord + user .get @@ -1113,14 +1113,8 @@ user -Record ;%0A
55be56e6a4d27d717954a93e4043a04705ad06af
use https for transifex download
tools/downloadLanguages.js
tools/downloadLanguages.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Environment Variables USERNAME - valid Transifex user name with read privileges PASSWORD - password for above username LANG [optional] - single language code to retrieve in xx-XX format (I.e. en-US) */ 'use strict' const path = require('path') const fs = require('fs') const request = require('request') // The names of the directories in the locales folder are used as a list of languages to retrieve var languages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales')).filter(function (language) { return language !== 'en-US' }).map(function (language) { return language.replace('-', '_') }) // Support retrieving a single language if (process.env.LANG_CODE) { languages = [process.env.LANG_CODE] } if (process.env.META) { var localLanguages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales')) console.log(` <meta name="availableLanguages" content="${localLanguages.join(', ')}">`) console.log(localLanguages.map(function (l) { return `'${l}'` }).join(',\n ')) process.exit(0) } // Setup the credentials const username = process.env.USERNAME const password = process.env.PASSWORD if (!(username && password)) { throw new Error('The USERNAME and PASSWORD environment variables must be set to the Transifex credentials') } // URI and resource list const TEMPLATE = 'http://www.transifex.com/api/2/project/brave-laptop/resource/RESOURCE_SLUG/translation/LANG_CODE/?file' // Retrieve resource names dynamically var resources = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', 'en-US')).map(function (language) { return language.split(/\./)[0] }) // For each language / resource combination languages.forEach(function (languageCode) { resources.forEach(function (resource) { // Build the URI var URI = TEMPLATE.replace('RESOURCE_SLUG', resource + 'properties') URI = URI.replace('LANG_CODE', languageCode) // Authorize and request the translation file request.get(URI, { 'auth': { 'user': username, 'pass': password, 'sendImmediately': true } }, function (error, response, body) { if (error) { // Report errors (often timeouts) console.log(error.toString()) } else { if (response.statusCode === 401) { throw new Error('Unauthorized - Are the USERNAME and PASSWORD env vars set correctly?') } // Check to see if the directory exists, if not create it var directory = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-')) if (!fs.existsSync(directory)) { console.log(`${languageCode} does not exist - creating directory`) if (!process.env.TEST) { fs.mkdirSync(directory) } else { console.log(`${languageCode} would have been created`) } } else { // Directory exists - continue } // Build the filename and store the translation file var filename = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-'), resource + '.properties') console.log('[*] ' + filename) if (process.env.TEST) { console.log(body) } else { fs.writeFileSync(filename, body) } } }) }) })
JavaScript
0
@@ -1594,16 +1594,17 @@ = 'http +s ://www.t
d6ae29f4d18462b2b150fba0e12d3b42960fca20
Test cases for default code version
tests/unit/services/rollbar-test.js
tests/unit/services/rollbar-test.js
import { moduleFor, test } from 'ember-qunit'; import Ember from 'ember'; import Rollbar from 'rollbar'; moduleFor('service:rollbar', 'Unit | Service | rollbar', { needs: ['config:environment'] }); test('it exists', function(assert) { let service = this.subject(); assert.ok(service); }); test('notifier', function(assert) { let service = this.subject(); assert.ok(service.get('notifier') instanceof Rollbar); }); test('critical', function(assert) { let service = this.subject(); let uuid = service.critical('My error message').uuid; assert.ok(uuid); }); test('error', function(assert) { let service = this.subject(); let uuid = service.error('My error message').uuid; assert.ok(uuid); }); test('warning', function(assert) { let service = this.subject(); let uuid = service.warning('My error message').uuid; assert.ok(uuid); }); test('info', function(assert) { let service = this.subject(); let uuid = service.info('My error message').uuid; assert.ok(uuid); }); test('debug', function(assert) { let service = this.subject(); let uuid = service.debug('My error message').uuid; assert.ok(uuid); }); test('registerLogger: register error handler for Ember errors if enabled', function(assert) { assert.expect(2); let service = this.subject({ config: { enabled: true }, error(message) { assert.ok(true, 'error handler is called'); assert.equal(message, 'foo', 'error is passed to error handler as argument'); } }); service.registerLogger(); Ember.onerror('foo'); }); test('registerLogger: does not override previous hook', function(assert) { assert.expect(4); let service = this.subject({ config: { enabled: true }, error(message) { assert.ok(true, 'rollbar error handler is called'); assert.equal(message, 'foo', 'error is passed to rollbar error handler as argument'); } }); Ember.onerror = function(message) { assert.ok(true, 'previous hook is called'); assert.equal(message, 'foo', 'error is passed to previous hook as argument'); }; service.registerLogger(); Ember.onerror('foo'); }); test('registerLogger: does not register logger if disabled', function(assert) { assert.expect(1); let service = this.subject({ config: { enabled: false }, error() { assert.notOk(true); } }); Ember.onerror = function() { assert.ok(true); }; service.registerLogger(); Ember.onerror(); })
JavaScript
0
@@ -1131,32 +1131,520 @@ .ok(uuid);%0A%7D);%0A%0A +test('config with default value for code version', function(assert) %7B%0A let service = this.subject();%0A let currentVersion = Ember.getOwner(this).resolveRegistration('config:environment').APP.version%0A assert.equal(service.get('config').code_version, currentVersion);%0A%7D);%0A%0Atest('config custom value for code version', function(assert) %7B%0A let service = this.subject(%7B%0A config: %7B%0A code_version: '1.2.3'%0A %7D%0A %7D);%0A assert.equal(service.get('config').code_version, '1.2.3');%0A%7D);%0A%0A test('registerLo
8ceb8c074327ecd4be630018c7643f84e26f1b08
Include the extra secrets.js.
server/config/secrets.js
server/config/secrets.js
JavaScript
0
@@ -0,0 +1,362 @@ +/** Important **/%0A/** You should not be committing this file to GitHub **/%0A%0Amodule.exports = %7B%0A // Find the appropriate database to connect to, default to localhost if not found.%0A db: process.env.MONGOHQ_URL %7C%7C process.env.MONGOLAB_URI %7C%7C 'mongodb://localhost/ReactWebpackNode',%0A sessionSecret: process.env.SESSION_SECRET %7C%7C 'Your Session Secret goes here'%0A%7D;
ede80b3f5a07d3cc11ba94f9ea40e52e0bb3a8a1
add endGame method in game menu
src/common/directives/diGameMenu/diGameMenu.js
src/common/directives/diGameMenu/diGameMenu.js
/** * directive.diGameMenu Module * * Description */ angular.module('directive.diGameMenu', [ 'service.GameManager' ]) .controller('GameMenuCtrl', [ '$scope', 'GameManager', function ( $scope, GameManager ){ $scope.continueGame = function continueGame() { GameManager.setPause(); $scope.closeModal(); return this; }; $scope.restartGame = function restartGame() { GameManager.newGame(); $scope.closeModal(); GameManager.setGameStart(); return this; }; this.isPause = function isPause() { return GameManager.isPause(); }; this.isGameStart = function isGameStart() { return GameManager.isGameStart(); }; }]) .directive('diGameMenu', [ function( ){ var GameMenu = {}; GameMenu.controller = 'GameMenuCtrl'; GameMenu.templateUrl = 'directives/diGameMenu/diGameMenu.tpl.html'; GameMenu.restrict = 'A'; GameMenu.replace = true; GameMenu.scope = true; GameMenu.link = function link(scope, element, attrs, controller) { scope.$on('app.pause', function() { if (!controller.isPause() && controller.isGameStart()) { $(element).modal({ backdrop: 'static' }); } else { scope.closeModal(); } }); scope.closeModal = function closeModal() { $(element).modal('hide'); }; }; return GameMenu; }]);
JavaScript
0
@@ -334,37 +334,16 @@ odal();%0A - return this;%0A %7D;%0A%0A @@ -496,23 +496,113 @@ - return this +%7D;%0A%0A $scope.endGame = function endGame() %7B%0A GameManager.gameOver();%0A $scope.closeModal() ;%0A
0313147b8cc69c0eb8fe76642922be9b121eadcd
Fix closure loader path in legacy example
examples/legacy-closure-lib/webpack.config.js
examples/legacy-closure-lib/webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin'), webpack = require('webpack'), pathUtil = require('path'); module.exports = { entry: { app: './src/app.js', }, output: { path: './build', filename: '[name].js', }, resolve: { modulesDirectories: ['node_modules'], root: [ __dirname, ], alias: { 'npm': __dirname + '/node_modules', } }, resolveLoader: { root: pathUtil.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /google-closure-library\/closure\/goog\/base/, loaders: [ 'imports?this=>{goog:{}}&goog=>this.goog', 'exports?goog', ], }, // Loader for closure library { test: /google-closure-library\/closure\/goog\/.*\.js/, loaders: [ require.resolve('../../index'), ], exclude: [/base\.js$/], }, // Loader for project js files { test: /\/src\/.*\.js/, loaders: [ 'closure', ], exclude: [/node_modules/, /test/], }, ], }, plugins: [ // This will copy the index.html to the build directory and insert script tags new HtmlWebpackPlugin({ template: 'src/index.html', }), new webpack.ProvidePlugin({ goog: 'google-closure-library/closure/goog/base', }), ], closureLoader: { paths: [ __dirname + '/node_modules/google-closure-library/closure/goog', ], es6mode: false, watch: false, }, devServer: { contentBase: './build', noInfo: true, inline: true, historyApiFallback: true, }, devtool: 'source-map', };
JavaScript
0
@@ -1241,17 +1241,38 @@ -'closure' +require.resolve('../../index') ,%0A
70f855f1a8accf94641c71e48e8544676085fa20
Rewrite LogoutButton to hooks
src/components/SettingsManager/LogoutButton.js
src/components/SettingsManager/LogoutButton.js
import React from 'react'; import PropTypes from 'prop-types'; import { translate } from '@u-wave/react-translate'; import Button from '@mui/material/Button'; import LogoutIcon from '@mui/icons-material/PowerSettingsNew'; import ConfirmDialog from '../Dialogs/ConfirmDialog'; import FormGroup from '../Form/Group'; const enhance = translate(); class LogoutButton extends React.Component { static propTypes = { t: PropTypes.func.isRequired, onLogout: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { showDialog: false, }; } handleOpen = () => { this.setState({ showDialog: true }); }; handleClose = () => { this.closeDialog(); }; handleConfirm = () => { const { onLogout } = this.props; onLogout(); this.closeDialog(); }; closeDialog() { this.setState({ showDialog: false }); } render() { const { t } = this.props; const { showDialog } = this.state; return ( <> <Button color="inherit" className="LogoutButton" onClick={this.handleOpen}> <LogoutIcon className="LogoutButton-icon" /> {t('settings.logout')} </Button> {showDialog && ( <ConfirmDialog title="" confirmLabel={t('dialogs.logout.action')} onConfirm={this.handleConfirm} onCancel={this.handleClose} > <FormGroup>{t('dialogs.logout.confirm')}</FormGroup> </ConfirmDialog> )} </> ); } } export default enhance(LogoutButton);
JavaScript
0
@@ -65,25 +65,29 @@ mport %7B -t +useT ranslat -e +or %7D from @@ -323,279 +323,165 @@ nst -enhance = translate();%0A%0Aclass LogoutButton extends React.Component %7B%0A static propTypes = %7B%0A t: PropTypes.func.isRequired,%0A onLogout: PropTypes.func.isRequired,%0A %7D;%0A%0A constructor(props) %7B%0A super(props);%0A this.state = %7B%0A showDialog: false,%0A %7D;%0A %7D%0A%0A +%7B useState %7D = React;%0A%0Afunction LogoutButton(%7B onLogout %7D) %7B%0A const %7B t %7D = useTranslator();%0A const %5BshowDialog, setShowDialog%5D = useState(false);%0A%0A const han @@ -502,33 +502,20 @@ %3E %7B%0A -this.setState(%7B s +setS howDialo @@ -519,16 +519,13 @@ alog -: +( true - %7D );%0A @@ -527,24 +527,30 @@ e);%0A %7D;%0A%0A +const handleClose @@ -563,33 +563,35 @@ %3E %7B%0A -this.close +setShow Dialog( +false );%0A %7D;%0A @@ -593,16 +593,22 @@ %7D;%0A%0A +const handleCo @@ -631,127 +631,28 @@ -const %7B onLogout %7D = this.props;%0A%0A onLogout();%0A this.closeDialog();%0A %7D;%0A%0A closeDialog() %7B%0A this.setState(%7B s +onLogout();%0A setS howD @@ -660,110 +660,23 @@ alog -: +( false - %7D );%0A %7D +; %0A%0A - render() %7B%0A const %7B t %7D = this.props;%0A const %7B showDialog %7D = this.state;%0A%0A re @@ -686,18 +686,16 @@ n (%0A - %3C%3E%0A @@ -695,18 +695,16 @@ %3E%0A - - %3CButton @@ -753,21 +753,16 @@ nClick=%7B -this. handleOp @@ -766,18 +766,16 @@ eOpen%7D%3E%0A - @@ -827,18 +827,16 @@ - - %7Bt('sett @@ -856,18 +856,16 @@ %7D%0A - %3C/Button @@ -866,18 +866,16 @@ Button%3E%0A - %7Bs @@ -897,18 +897,16 @@ - %3CConfirm @@ -922,18 +922,16 @@ - title=%22%22 @@ -941,18 +941,16 @@ - - confirmL @@ -993,18 +993,16 @@ - onConfir @@ -1004,21 +1004,16 @@ onfirm=%7B -this. handleCo @@ -1029,18 +1029,16 @@ - - onCancel @@ -1043,13 +1043,8 @@ el=%7B -this. hand @@ -1064,14 +1064,10 @@ - %3E%0A +%3E%0A @@ -1133,18 +1133,16 @@ - %3C/Confir @@ -1160,15 +1160,11 @@ - )%7D%0A - @@ -1173,18 +1173,82 @@ %3E%0A - );%0A %7D +);%0A%7D%0A%0ALogoutButton.propTypes = %7B%0A onLogout: PropTypes.func.isRequired, %0A%7D +; %0A%0Aex @@ -1264,16 +1264,8 @@ ult -enhance( Logo @@ -1272,11 +1272,10 @@ utButton -) ;%0A
89ab12e6324f4d6fc32280f244bb91cea81482dd
Use correct path in examples when using handlers nested in subdirs
examples/serverless-offline/webpack.config.js
examples/serverless-offline/webpack.config.js
const path = require('path'); const nodeExternals = require('webpack-node-externals'); module.exports = { entry: './src/handler.js', target: 'node', externals: [nodeExternals()], module: { loaders: [{ test: /\.js$/, loaders: ['babel-loader'], include: __dirname, exclude: /node_modules/, }], }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: 'handler.js' }, };
JavaScript
0
@@ -433,16 +433,20 @@ ename: ' +src/ handler.
cde39cdfb33867d32c9b9b8e4b19a27592ff00e8
Stop ending the test twice\!
features-support/step_definitions/features.js
features-support/step_definitions/features.js
'use strict'; var should = require('should'); var By = require('selenium-webdriver').By; // Test helper. function getProjectFromUrl(callback) { var world = this; var projectRetrievalUrl = 'http://localhost:' + world.appPort + '/?repo_url=' + encodeURIComponent(world.repoUrl); world.browser.get(projectRetrievalUrl) .then(world.browser.getPageSource.bind(world.browser)) .then(function (body) { world.body = body; callback(); }); } // The returned function is passed as a callback to getProjectFromUrl. function getScenarioFromProject(callback, world) { return function(error) { if (error) { callback(error); return; } world.browser.findElements(By.css('.spec-link')) .then(function (specLinks) { var featureLink = specLinks[specLinks.length - 1]; return world.browser.get(featureLink.getAttribute('href')); }) .then(world.browser.getPageSource.bind(world.browser)) .then(function (body) { world.body = body; callback(); }); }; } module.exports = function () { this.Given(/^a URL representing a remote Git repo "([^"]*)"$/, function (repoUrl, callback) { this.repoUrl = repoUrl; callback(); }); this.When(/^an interested party wants to view the features in that repo\.?$/, getProjectFromUrl); this.When(/^they request the features for the same repository again\.?$/, getProjectFromUrl); this.When(/^an interested party wants to view the scenarios within a feature\.?$/, function (callback) { var world = this; getProjectFromUrl.bind(world)(getScenarioFromProject(callback, world)); }); this.When(/^they decide to change which branch is being displayed$/, function (callback) { var world = this; var burgerMenuId = "expand-collapse-repository-controls"; var repositoryCongtrolsId = "repository-controls"; var projectShaElId = "project-commit"; var changeBranchSelectElId = "change-branch-control"; var testingBranchOptionValue = "refs%2Fremotes%2Forigin%2Ftest%2FdoNotDelete"; var burgerMenuEl; var repoControlsEl; // Get the burger menu element. world.browser.findElement(By.id(burgerMenuId)) .then(function(_burgerMenuEl) { burgerMenuEl = _burgerMenuEl; return world.browser.findElement(By.id(repositoryCongtrolsId)); // Get the repo controls element. }).then(function(_repoControlsEl) { repoControlsEl = _repoControlsEl; return repoControlsEl.getAttribute('class'); // Open the repo controls. }).then(function(repoControlsClass) { var isClosed = repoControlsClass.indexOf("collapse") !== -1; if (isClosed) { return burgerMenuEl.click(); } return; // Grab the current SHA }).then(function() { return world.browser.findElement(By.id(projectShaElId)); }).then(function(_projectShaEl) { return _projectShaEl.getText(); }).then(function(originalSha) { world.oringalSha = originalSha; // Grab the branch selecting control. return world.browser.findElement(By.id(changeBranchSelectElId)); // Request to change branch. }).then(function(_changeBranchSelectEl) { return _changeBranchSelectEl.findElement(By.xpath('option[@value=\'' + testingBranchOptionValue + '\']')); }).then(function(_testBranchOptionEl) { return _testBranchOptionEl.click(); }).then(function() { callback(); }); }); this.Then(/^the list of features will be visible\.?$/, function (callback) { should.equal( /\.feature/i.test(this.body) && /\.md/i.test(this.body), true, 'The returned document body does not contain the strings \'.feature\' and \'.md\'' + this.body); callback(); }); this.Then(/^the scenarios will be visible\.?$/, function (callback) { should.equal(/feature-title/i.test(this.body), true, 'The returned document body does not contain a feature title'); callback(); }); this.Then(/^the files from the selected branch are displayed\.$/, function (callback) { var world = this; var projectShaElId = "project-commit"; // Get the new SHA. return world.browser.findElement(By.id(projectShaElId)) .then(function(_projectShaEl) { return _projectShaEl.getText(); }).then(function(newSha) { should.notEqual(newSha, world.oringalSha, 'The SHA did not change on changing branch.'); callback(); }); }); };
JavaScript
0.000001
@@ -4186,31 +4186,24 @@ ew SHA.%0A -return world.browse
9c3003410adceb851ea3cb2ae16ef37d55046ae4
add genotype colors constants (#337)
src/genome-browser/genome-browser-constants.js
src/genome-browser/genome-browser-constants.js
// Global constants for GenomeBrowser export default class GenomeBrowserConstants { // CellBase constants static CELLBASE_HOST = "https://ws.zettagenomics.com/cellbase"; static CELLBASE_VERSION = "v5"; // OpenCGA Constants static OPENCGA_HOST = "https://ws.opencb.org/opencga-test"; static OPENCGA_VERSION = "v2"; // Cytobands static CYTOBANDS_COLORS = { gneg: "white", stalk: "#666666", gvar: "#CCCCCC", gpos25: "silver", gpos33: "lightgrey", gpos50: "gray", gpos66: "dimgray", gpos75: "darkgray", gpos100: "black", gpos: "gray", acen: "blue", }; // Sequence colors static SEQUENCE_COLORS = { A: "#009900", C: "#0000FF", G: "#857A00", T: "#aa0000", N: "#555555", }; // Gene biotype colors static GENE_BIOTYPE_COLORS = { "3prime_overlapping_ncrna": "Orange", "ambiguous_orf": "SlateBlue", "antisense": "SteelBlue", "disrupted_domain": "YellowGreen", "IG_C_gene": "#FF7F50", "IG_D_gene": "#FF7F50", "IG_J_gene": "#FF7F50", "IG_V_gene": "#FF7F50", "lincRNA": "#8b668b", "miRNA": "#8b668b", "misc_RNA": "#8b668b", "Mt_rRNA": "#8b668b", "Mt_tRNA": "#8b668b", "ncrna_host": "Fuchsia", "nonsense_mediated_decay": "seagreen", "non_coding": "orangered", "non_stop_decay": "aqua", "polymorphic_pseudogene": "#666666", "processed_pseudogene": "#666666", "processed_transcript": "#0000ff", "protein_coding": "#a00000", "pseudogene": "#666666", "retained_intron": "goldenrod", "retrotransposed": "lightsalmon", "rRNA": "indianred", "sense_intronic": "#20B2AA", "sense_overlapping": "#20B2AA", "snoRNA": "#8b668b", "snRNA": "#8b668b", "transcribed_processed_pseudogene": "#666666", "transcribed_unprocessed_pseudogene": "#666666", "unitary_pseudogene": "#666666", "unprocessed_pseudogene": "#666666", // "": "orangered", "other": "#000000" }; // Codon configuration static CODON_CONFIG = { "": {text: "", color: "transparent"}, "R": {text: "Arg", color: "#BBBFE0"}, "H": {text: "His", color: "#BBBFE0"}, "K": {text: "Lys", color: "#BBBFE0"}, "D": {text: "Asp", color: "#F8B7D3"}, "E": {text: "Glu", color: "#F8B7D3"}, "F": {text: "Phe", color: "#FFE75F"}, "L": {text: "Leu", color: "#FFE75F"}, "I": {text: "Ile", color: "#FFE75F"}, "M": {text: "Met", color: "#FFE75F"}, "V": {text: "Val", color: "#FFE75F"}, "P": {text: "Pro", color: "#FFE75F"}, "A": {text: "Ala", color: "#FFE75F"}, "W": {text: "Trp", color: "#FFE75F"}, "G": {text: "Gly", color: "#FFE75F"}, "T": {text: "Thr", color: "#B3DEC0"}, "S": {text: "Ser", color: "#B3DEC0"}, "Y": {text: "Tyr", color: "#B3DEC0"}, "Q": {text: "Gln", color: "#B3DEC0"}, "N": {text: "Asn", color: "#B3DEC0"}, "C": {text: "Cys", color: "#B3DEC0"}, "X": {text: " X ", color: "#f0f0f0"}, "*": {text: " * ", color: "#DDDDDD"} }; // SNP Biotype colors configuration static SNP_BIOTYPE_COLORS = { "2KB_upstream_variant": "#a2b5cd", "5KB_upstream_variant": "#a2b5cd", "500B_downstream_variant": "#a2b5cd", "5KB_downstream_variant": "#a2b5cd", "3_prime_UTR_variant": "#7ac5cd", "5_prime_UTR_variant": "#7ac5cd", "coding_sequence_variant": "#458b00", "complex_change_in_transcript": "#00fa9a", "frameshift_variant": "#ff69b4", "incomplete_terminal_codon_variant": "#ff00ff", "inframe_codon_gain": "#ffd700", "inframe_codon_loss": "#ffd700", "initiator_codon_change": "#ffd700", "non_synonymous_codon": "#ffd700", "missense_variant": "#ffd700", "intergenic_variant": "#636363", "intron_variant": "#02599c", "mature_miRNA_variant": "#458b00", "nc_transcript_variant": "#32cd32", "splice_acceptor_variant": "#ff7f50", "splice_donor_variant": "#ff7f50", "splice_region_variant": "#ff7f50", "stop_gained": "#ff0000", "stop_lost": "#ff0000", "stop_retained_variant": "#76ee00", "synonymous_codon": "#76ee00", "other": "#000000" }; }
JavaScript
0
@@ -4541,10 +4541,169 @@ %7D;%0A%0A + // Genotypes colors%0A static GENOTYPES_COLORS = %7B%0A %22heterozygous%22: %22darkblue%22,%0A %22homozygous%22: %22cyan%22,%0A %22reference%22: %22gray%22,%0A %7D;%0A%0A %7D%0A
4453bf5e68f1fd41cebe9e3dc2833d2df7fdfd0f
Update moonpay api
server/lib/v1/moonpay.js
server/lib/v1/moonpay.js
'use strict'; var axios = require('axios'); var db = require('./db'); var PRIORITY_SYMBOLS = ['BTC', 'BCH', 'ETH', 'USDT', 'LTC', 'XRP', 'XLM', 'EOS', 'DOGE', 'DASH']; var fiatSigns = { usd: '$', eur: '€', gbp: '£' }; function save(_id, data) { var collection = db().collection('moonpay'); return collection.updateOne({_id: _id}, {$set: {data: data}}, {upsert: true}); } function getCurrenciesFromAPI() { return axios.get('https://api.moonpay.io/v3/currencies').then(function(response) { var data = response.data; if (!data || !data.length) throw new Error('Bad moonpay response'); var coins = {}; var coinsUSA = {}; PRIORITY_SYMBOLS.forEach(function(symbol) { var coin = data.find(function(item) { return item.code === symbol.toLowerCase(); }); if (coin) { coins[coin.id] = { symbol: symbol, isSupported: !coin.isSuspended } coinsUSA[coin.id] = { symbol: symbol, isSupported: !coin.isSuspended && coin.isSupportedInUS } } }); var fiat = {}; data.forEach(function(item) { if (item.type === 'fiat') { fiat[item.id] = { symbol: item.code.toUpperCase(), sign: fiatSigns[item.code] || '', precision: item.precision }; } }); return { coins: coins, coins_usa: coinsUSA, fiat: fiat }; }); } function getCountriesFromAPI() { return axios.get('https://api.moonpay.io/v3/countries').then(function(response) { var data = response.data; if (!data || !data.length) throw new Error('Bad moonpay response'); var document = data.filter(function(country) { return country.supportedDocuments && country.supportedDocuments.length > 0; }).map(function(country) { return { code: country.alpha3, name: country.name, supportedDocuments: country.supportedDocuments } }); var allowed = data.filter(function(country) { return country.isAllowed; }).map(function(country) { var item = {}; item.code = country.alpha3; item.name = country.name; if (country.states) { item.states = country.states.filter(function(state) { return state.isAllowed; }).map(function(state) { return { code: state.code, name: state.name }; }); } return item; }); return { document: document, allowed: allowed }; }); } function getFromCache(id) { var collection = db().collection('moonpay'); return collection .find({_id: id}) .limit(1) .next().then(function(item) { if (!item) return {}; delete item.id; return item.data; }); } module.exports = { save: save, getCurrenciesFromAPI: getCurrenciesFromAPI, getCountriesFromAPI: getCountriesFromAPI, getFromCache: getFromCache };
JavaScript
0
@@ -63,16 +63,59 @@ './db'); +%0Avar API_KEY = process.env.MOONPAY_API_KEY; %0A%0Avar PR @@ -508,24 +508,73 @@ /currencies' +, %7B%0A params: %7B%0A apiKey: API_KEY%0A %7D%0A %7D ).then(funct
94f350b9b01a1048f03c9c93bad0fda1f0b9041e
refactor serial writes
lib/board.js
lib/board.js
var events = require('events'), child = require('child_process'), util = require('util'), serial = require('serialport').SerialPort; /* * The main Arduino constructor * Connect to the serial port and bind */ var Board = function (options) { this.messageBuffer = ''; var self = this; this.detect(function (err, serial) { if (err) throw err; self.serial = serial; self.serial.on('data', function(data){ self.emit('data', data); self.messageBuffer += data; self.attemptParse(); }); self.emit('connected'); }); } /* * EventEmitter, I choose you! */ util.inherits(Board, events.EventEmitter); /* * Detect an Arduino board * Loop through all USB devices and try to connect * This should really message the device and wait for a correct response */ Board.prototype.detect = function (cb) { child.exec('ls /dev | grep usb', function(err, stdout, stderr){ var possible = stdout.slice(0, -1).split('\n'), found = false; for (var i in possible) { var tempSerial, err; try { tempSerial = new serial('/dev/' + possible[i]); } catch (e) { err = e; } if (!err) { found = tempSerial; break; } } if (found) cb(null, found); else cb(new Error('Could not find Arduino')); }); } /* * Attempt to parse the message buffer via delimiter * Called every time data bytes are received */ Board.prototype.attemptParse = function (data) { var b = this.messageBuffer.split('\r\n'); while (b.length > 1) { this.emit('message', b.shift()); } this.messageBuffer = b[0]; } /* * Low-level serial write */ Board.prototype.write = function (m) { this.serial.write(m); } /* * Set a pin's mode * val == out = 01 * val == in = 00 */ Board.prototype.pinMode = function (pin, val) { this.serial.write( '00' + pin + (val == 'out' ? '01' : '00') ); } /* * Tell the board to write to a digital pin */ Board.prototype.digitalWrite = function (pin, val) { this.serial.write('01' + pin + val + '\r'); } Board.prototype.digitalRead = function (pin, val) {} Board.prototype.analogWrite = function (pin, val) {} Board.prototype.analogWrite = function (pin, val) {} module.exports = Board;
JavaScript
0.000001
@@ -385,24 +385,52 @@ l = serial;%0A + self.serial.write('0');%0A self.ser @@ -1743,17 +1743,29 @@ l.write( -m +'!' + m + '.' );%0A%7D%0A%0A/* @@ -1881,53 +1881,20 @@ %7B%0A -this.serial.write(%0A '00' +%0A pin +%0A ( +val = (%0A val @@ -1907,24 +1907,102 @@ t' ? +%0A '01' : +%0A '00' -) %0A +);%0A // console.log('pm 00' + pin + val);%0A this.write('00' + pin + val );%0A%7D @@ -2105,35 +2105,66 @@ n, val) %7B%0A -this.serial +//console.log('dw 01' + pin + val);%0A this .write('01' @@ -2178,15 +2178,8 @@ val - + '%5Cr' );%0A%7D
41edd3fb3a1db6a4cfe3e728663595586f5c39e6
I never claimed to be a smart man. fix stupid bug
server/routes/download.js
server/routes/download.js
'use strict'; // We have three possible outcomes when someone requests `/download`, // 1. serve the compilled, static html file if in production // 2. serve a compiled handlebars template on each request, in development // 3. reply with a tar ball of a compiled version of Modernizr, if requested via bower // this module determines the right one depending the circumstances var Path = require('path'); var ETag = require('etag'); var Archiver = require('archiver'); var Modernizr = require('modernizr'); var modernizrMetadata = Modernizr.metadata(); var bowerJSON = require('../util/bowerJSON')(); var modernizrOptions = require('../util/modernizrOptions'); var _ = require(Path.join(__dirname, '..', '..', 'frontend', 'js', 'lodash.custom')); // the `builderContent` step is super heavy, as a result, do not load it if we // are in a production enviroment if (process.env.NODE_ENV !== 'production') { var builderContent = require('../buildSteps/download'); var downloaderConfig = { metadata: JSON.stringify(modernizrMetadata), options: JSON.stringify(modernizrOptions), builderContent: builderContent, scripts: [ '/js/lodash.custom.js', '/js/modernizr.custom.js', '/lib/zeroclipboard/dist/ZeroClipboard.js', '/lib/r.js/dist/r.js', '/lib/modernizr/lib/build.js', '/js/download/downloader.js', ], team: require('../util/footer') }; } var propToAMD = function(prop) { if (_.contains(prop, '_')) { prop = prop.split('_'); } return _.where(modernizrMetadata, {'property': prop})[0].amdPath; }; var optProp = function(prop) { return _.chain(modernizrOptions) .filter(function(opt) { return opt.property.toLowerCase() === prop; }) .map(function(opt) { return opt.property; }) .first() .value(); }; // takes a build hash/querystring that is updated automatically on `/download`, and // included by default inside of every custom build of modernizr, and converts it // into a valid Modernizr config var config = function(query) { var config = { 'minify': true, 'feature-detects': [], 'options': [] }; var queries = _.chain(query.replace(/^\?/, '').split('&')) .map(function(query) { return query.split('-'); }) .flatten() .value(); queries.forEach(function(query) { // `/download` has a search box that we track state with via the `q` param // since it defently won't match anything, we exit early when found var searchResult = query.match(/q=(.*)/); var cssclassprefix = query.match('cssclassprefix:(.*)'); if (searchResult) { return; } if (cssclassprefix) { // the classPrefix is tracked separately from other options, so just update // the config accordingly, and return false for every property we match against config.classPrefix = cssclassprefix[1]; return; } if (query.match('shiv$')) { // `html5shiv` and `html5printshiv` are configured as `shiv` and `printshiv` // for the sake of brevity, as well as to drive me insane query = 'html5' + query; } var matches = function(obj) { var prop = obj.property; if (_.isArray(prop)) { // some detects have an array of properties, which would strinigfy weirdly // without us doing it manually here prop = prop.join('_'); } if (query === 'dontmin' && prop === 'minify') { // we track the minify state on the `/download` side under the inverted // `dontmin` option, and on the server side with the (non standard) // `modernizr.options().minify` option config.minify = false; } return query === prop.toLowerCase(); }; if (_.some(modernizrOptions, matches)) { config.options.push(optProp(query)); } else if (_.some(modernizrMetadata, matches)) { config['feature-detects'].push(propToAMD(query)); } }); return config; }; var handler = function (request, reply) { // the download urls (that include the build settings) can be used inside of a bower.json // file to automatically download a custom version of the current version of Modernizr // Ironically, in order to support this, we have to do user agent sniffing var ua = request.headers['user-agent']; // http://bower.io/docs/config/#user-agent // NOTE this will obvs fail to match for custom bower user agents var isBower = !!ua.match(/^node\/v\d*\.\d*\.\d* (darwin|freebsd|linux|sunos|win32) (arm|ia32|x64)/); if (isBower) { // bower complains a bunch if we don't include proper metadata with the response. // in order to do so, we create a virtual tar file, and but the build and bower.json // file in it var archive = Archiver('tar'); var query = request.url.search.replace(/\.tar(\.gz)?|zip$/, ''); var buildConfig = config(query); Modernizr.build(buildConfig, function(build) { var module = archive .append(build, {name: bowerJSON.main}) .append(JSON.stringify(bowerJSON, 0, 2), {name: 'bower.json'}) .finalize(); reply(module) // bower bases how it handles the response on the name of the responded file. // we have to reply with a `.tar` file in order to be processed correctly .header('Content-disposition', 'attachment; filename=Modernizr.custom.tar') // bower will cache files downloaded via URLResolver (which is what it is // using here) via its ETag. This won't prevent us from building a new // version on each response, but it will prevent wasted bandwidth .etag(ETag(bowerJSON.version + JSON.stringify(buildConfig))); }); } else if (!!ua.match(/^npm\//)) { Modernizr.build(buildConfig, function(build) { var archive = Archiver('tar'); var query = request.url.search.replace(/\.tar(.gz)?$/, ''); var buildConfig = config(query); var module = archive .append(build, {name: 'modernizr/' + bowerJSON.main}) .append(JSON.stringify(bowerJSON, 0, 2), {name: 'modernizr/package.json'}) .finalize(); reply(module) .header('Content-disposition', 'attachment; filename=Modernizr.custom.tar') .etag(ETag(bowerJSON.version + JSON.stringify(buildConfig))); }); } else if (process.env.NODE_ENV !== 'production') { // if it was not requested by bower, and not in prod mode, we serve the // homepage via the Hapi handlebars renderer reply.view('pages/download', downloaderConfig); } else { // if all else fails, we are in prod/static mode, so serve the static index reply.file(Path.join(__dirname, '..', '..', 'dist', 'download', 'index.html')); } }; module.exports = handler;
JavaScript
0.158806
@@ -4502,16 +4502,118 @@ %7Cx64)/); +%0A var query = request.url.search.replace(/%5C.tar(%5C.gz)?%7Czip$/, '');%0A var buildConfig = config(query); %0A%0A if ( @@ -4854,114 +4854,8 @@ r'); -%0A var query = request.url.search.replace(/%5C.tar(%5C.gz)?%7Czip$/, '');%0A var buildConfig = config(query); %0A%0A @@ -5784,109 +5784,8 @@ ');%0A - var query = request.url.search.replace(/%5C.tar(.gz)?$/, '');%0A var buildConfig = config(query);%0A
e732a1170294e70fee3b6a30bedec6ddf981b6bd
refactor missions endpoint
server/routes/missions.js
server/routes/missions.js
var express = require('express'); var router = express.Router(); //console.log(__dirname); const bookshelf = require('../db/knex') // models const Mission = require('../Models/Mission'); const Casefile = require('../Models/Casefile'); const User = require('../Models/User'); // collections - TODO not used??? - when is it good to use? const Missions = require('../Collections/missions'); // check if user authorized function authorizedUser(req, res, next) { const userID = req.session.user; if (userID) { next(); } else { res.render('restricted'); } } // need to display user-specific missions + casefiles when user is logged in router.get('/api/missions', (req, res, next) => { let files = {}; // TODO where user_id === logged_in user (req.session.user) let user = 1; // temporary workaround Mission.forge().where({user_id: user}).query('orderBy', 'id', 'asc') .fetchAll({withRelated: ['casefile'], debug:true}) .then((mission) => { // convert data to JSON mission = mission.toJSON(); // loop over data to get mission and casefile names for (var i = 0; i < mission.length; i++) { // save to files object if (mission[i].casefile && mission[i].casefile.name) { files[mission[i].name] = mission[i].casefile.name; } else { files[mission[i].name] = "no casefile added"; } } // send files object res.send(files) }) }); // get mission by name / id router.get('/api/view-mission/:name', function(req, res, next) { let mission_name = req.params.name.split('_').join(' '); let missionJSON; Mission.forge().where({ name: mission_name }).fetch() .then((mission) => res.send(mission)) .catch((err) => console.log("mission fetching error", err)) }) // create a new mission router.post('/api/add-mission', (req, res, next) => { let username, new_url, next_id; // set the value of the next id in the mission table, avoiding duplicate key errors bookshelf.knex.raw('SELECT setval(\'missions_id_seq\', (SELECT MAX(id) FROM missions)+1)') // TODO I don't think this is the correct way to do this AT ALL // get last mission id // get user name from user id for mission url User.forge().where({id: req.body.user_id}).fetch() .then((user) => { user = user.toJSON() || 'testamdmin'; username = user.name; // strip punctuation, capitals, and spaces username = username.replace(/[.\-`'\s]/g,"").toLowerCase(); // create the url students will use to access the mission new_url = '/' + username + '/'; // TODO need to add the correct id to this somehow, here or elsewhere }) .then(() => { // change last_id to false for current last_id Mission.forge().where({last_id: true}) .save({last_id: false}, {patch: true}) }) .then(() => { // save mission name, user_id, url to mission table - casefile_id will be // updated in patch when selected Mission.forge({ name: req.body.name, user_id: req.body.user_id, url: new_url, last_id: true }) .save() .then((mission) => { res.sendStatus(200); }) .catch((err) => { next(err); }) }) .catch((err) => { next(err); }) }) // end post // update mission with casefile_id on saving router.patch('/api/update-mission', (req, res, next) => { console.log("patch route reached", req.body); Mission.forge().where({name: req.body.name}).fetch() .then((mission) => { // update mission table with selected casefile_id console.log("fetched mission to patch", mission); Mission.forge().where({id: mission.attributes.id}) //TODO get casefile_id a better way .save({casefile_id: req.body.casefile_id+1}, {patch: true}) .then((response) => { console.log("mission updated successfully", response); res.sendStatus(200); }) .catch((err) => { next(err); }) }) .catch((err) => { next(err); }) }) router.delete('/api/delete-mission/:name', (req, res, next) => { console.log("you are in the mission delete route and you are deleting mission: ", req.params.name); Mission.forge().where({name: req.params.name}) .fetch({require: true}) .then((mission) => { mission.destroy() .then(() => { console.log("mission", req.params.name, "successfully deleted"); res.sendStatus(200); }) .catch((err) => { console.log("nooo, error", err); }) }) .catch((err) => { console.log("delete error", err); }); }) module.exports = router;
JavaScript
0.000109
@@ -701,19 +701,28 @@ let -files = %7B%7D; +missionsArray = %5B%5D;%0A %0A / @@ -957,32 +957,33 @@ .then((mission +s ) =%3E %7B%0A // @@ -1016,16 +1016,17 @@ mission +s = missi @@ -1027,16 +1027,17 @@ mission +s .toJSON( @@ -1035,24 +1035,25 @@ s.toJSON();%0A +%0A // loo @@ -1097,16 +1097,22 @@ le names + & ids %0A f @@ -1137,16 +1137,17 @@ mission +s .length; @@ -1166,137 +1166,181 @@ -// save to files object%0A if ( +missionsArray%5Bi%5D = %7B%0A %22missionName%22: mission +s %5Bi%5D. -casefile && mission%5Bi%5D.casefile.name) %7B%0A files%5B +name %7C%7C %22%22,%0A %22missionId%22: missions%5Bi%5D.id %7C%7C null,%0A %22casefileName%22: mission +s %5Bi%5D. -name%5D = +casefile ? mission %5Bi%5D. @@ -1331,24 +1331,25 @@ le ? mission +s %5Bi%5D.casefile @@ -1357,82 +1357,110 @@ name -;%0A %7D else %7B%0A files%5B + : %22no casefile added%22,%0A %22casefileId%22: mission +s %5Bi%5D. -name%5D = %22no casefile added%22; +casefile ? missions%5Bi%5D.casefile.id : null, %0A @@ -1488,20 +1488,23 @@ // send -file +mission s object @@ -1519,21 +1519,29 @@ es.send( -files +missionsArray )%0A %7D)
09214e30538194174194130ccc2e85c70648915d
Change text view init
www/views/backup/text.js
www/views/backup/text.js
define([ 'jquery', 'underscore', 'backbone', 'shCore', 'shBrushAppleScript', 'shBrushAS3', 'shBrushBash', 'shBrushColdFusion', 'shBrushCpp', 'shBrushCSharp', 'shBrushCss', 'shBrushDelphi', 'shBrushDiff', 'shBrushErlang', 'shBrushGroovy', 'shBrushHaxe', 'shBrushJava', 'shBrushJavaFX', 'shBrushJScript', 'shBrushPerl', 'shBrushPhp', 'shBrushPlain', 'shBrushPowerShell', 'shBrushPython', 'shBrushRuby', 'shBrushSass', 'shBrushScala', 'shBrushSql', 'shBrushTypeScript', 'shBrushVb', 'shBrushXml', 'models/backup/text', 'text!templates/backup/text.html' ], function($, _, Backbone, SyntaxHighlighter, BrushAppleScript, BrushAS3, BrushBash, BrushColdFusion, BrushCpp, BrushCSharp, BrushCss, BrushDelphi, BrushDiff, BrushErlang, BrushGroovy, BrushHaxe, BrushJava, BrushJavaFX, BrushJScript, BrushPerl, BrushPhp, BrushPlain, BrushPowerShell, BrushPython, BrushRuby, BrushSass, BrushScala, BrushSql, BrushTypeScript, BrushVb, BrushXml, TextModel, textTemplate) { 'use strict'; var TextView = Backbone.View.extend({ className: 'text-viewer-box', events: { 'mouseover .close-viewer': 'addIconWhite', 'mouseout .close-viewer': 'removeIconWhite', 'click .close-viewer': 'onClickClose' }, template: _.template(textTemplate), initialize: function(options) { this.model = new TextModel({ id: options.id, volume: options.volume, snapshot: options.snapshot }); }, render: function() { this.$el.html(this.template(this.model.toJSON())); SyntaxHighlighter.highlight(null, this.$('pre')[0]); this.$el.fadeIn(400); return this; }, addIconWhite: function(evt) { this.$(evt.target).addClass('icon-white'); }, removeIconWhite: function(evt) { this.$(evt.target).removeClass('icon-white'); }, onClickClose: function() { this.$('.close-viewer').roll(400); this.$el.fadeOut(400, function() { this.remove(); }.bind(this)); } }); return TextView; });
JavaScript
0.000001
@@ -1402,108 +1402,15 @@ del( -%7B%0A id: options.id,%0A volume: options.volume,%0A snapshot: options.snapshot%0A %7D +options );%0A
0d63f0442e795ec0371e73050076ea3dd60c0725
Fix for undefined req.onErrorCallback
lib/express_validator.js
lib/express_validator.js
/* * This binds the node-validator library to the req object so that * the validation / sanitization methods can be called on parameter * names rather than the actual strings. * * 1. Be sure to include `req.mixinParams()` as middleware to merge * query string, body and named parameters into `req.params` * * 2. To validate parameters, use `req.check(param_name, [err_message])` * e.g. req.check('param1').len(1, 6).isInt(); * e.g. req.checkHeader('referer').contains('mydomain.com'); * * Each call to `check()` will throw an exception by default. To * specify a custom err handler, use `req.onValidationError(errback)` * where errback receives a parameter containing the error message * * 3. To sanitize parameters, use `req.sanitize(param_name)` * e.g. req.sanitize('large_text').xss(); * e.g. req.sanitize('param2').toInt(); * * 4. Done! Access your validated and sanitized paramaters through the * `req.params` object */ var Validator = require('validator').Validator, Filter = require('validator').Filter; var validator = new Validator(); var expressValidator = function(req, res, next) { req.updateParam = function(name, value) { // route params like /user/:id if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) { return this.params[name] = value; } // query string params if (undefined !== this.query[name]) { return this.query[name] = value; } // request body params via connect.bodyParser if (this.body && undefined !== this.body[name]) { return this.body[name] = value; } return false; }; req.check = function(param, fail_msg) { validator.error = function(msg) { var error = { param: param, msg: msg } if (req._validationErrors === undefined) { req._validationErrors = []; } req._validationErrors.push(error); req.onErrorCallback(msg); } return validator.check(this.param(param), fail_msg); }; req.checkHeader = function(param, fail_msg) { var to_check; if (header === 'referrer' || header === 'referer') { to_check = this.headers.referer; } else { to_check = this.headers[header]; } return validator.check(to_check || '', fail_msg); }; req.onValidationError = function(errback) { req.onErrorCallback = errback; }; req.validationErrors = function(mapped) { if (req._validationErrors === undefined) { return false; } if (mapped) { var errors = {}; req._validationErrors.map(function(err) { errors[err.param] = err.msg; }); return errors; } else { return req._validationErrors; } } req.filter = function(param) { var self = this; var filter = new Filter(); filter.modify = function(str) { this.str = str; self.updateParam(param, str); // Replace the param with the filtered version }; return filter.sanitize(this.param(param)); }; // Create some aliases - might help with code readability req.sanitize = req.filter; req.assert = req.check; return next(); }; module.exports = expressValidator; module.exports.Validator = Validator; module.exports.Filter = Filter;
JavaScript
0.00001
@@ -1946,16 +1946,51 @@ error);%0A +%0A if(req.onErrorCallback) %7B%0A re @@ -2013,16 +2013,24 @@ k(msg);%0A + %7D%0A %7D%0A