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
|
---|---|---|---|---|---|---|---|
28cda95346a1f5c8071feb9ed50b8255c6120c51 | Allow some kind of downloading to work on Safari | src/lib/download-blob.js | src/lib/download-blob.js | export default (filename, blob) => {
const downloadLink = document.createElement('a');
document.body.appendChild(downloadLink);
// Use special ms version if available to get it working on Edge.
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, filename);
return;
}
const url = window.URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = filename;
downloadLink.type = blob.type;
downloadLink.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(downloadLink);
};
| JavaScript | 0 | @@ -313,16 +313,73 @@
%0A %7D%0A%0A
+ if ('download' in HTMLAnchorElement.prototype) %7B%0A
cons
@@ -420,16 +420,20 @@
(blob);%0A
+
down
@@ -453,24 +453,28 @@
= url;%0A
+
+
downloadLink
@@ -495,16 +495,20 @@
lename;%0A
+
down
@@ -534,24 +534,28 @@
b.type;%0A
+
+
downloadLink
@@ -572,41 +572,8 @@
-window.URL.revokeObjectURL(url);%0A
@@ -612,12 +612,388 @@
adLink);
+%0A window.URL.revokeObjectURL(url);%0A %7D else %7B%0A // iOS Safari, open a new page and set href to data-uri%0A let popup = window.open('', '_blank');%0A const reader = new FileReader();%0A reader.onloadend = function () %7B%0A popup.location.href = reader.result;%0A popup = null;%0A %7D;%0A reader.readAsDataURL(blob);%0A %7D%0A
%0A%7D;%0A
|
3a611c403fe103a3f234c0d355e86a382492ca47 | Fix localeManager crashing on README | src/lib/localeManager.js | src/lib/localeManager.js | /*
* Clara - locale manager
*
* Contributed by Capuccino and Ovyerus
*/
const fs = require('fs');
const localeDir = `${__baseDir}/res/locales`;
/**
* Object for managing locales and translating strings
* @prop {String} fallbackLocale The locale to fallback if it can't translate the string for some reason.
* @prop {Object} locales Object of locales currently loaded.
* @prop {String} localeDir The directory where locales are stored.
*/
class localeManager {
/**
* Create the locale manager object.
*/
constructor() {
this.fallbackLocale = 'en-UK';
this.locales = {};
this.localeDir = localeDir;
}
/**
* Load all locales in the locale directory.
*
* @returns {Promise}
*/
loadLocales() {
return new Promise((resolve, reject) => {
fs.readdir(localeDir, (err, locales) => {
if (err) {
reject(err);
} else {
for (let locale of locales) {
let localeParsed = JSON.parse(fs.readFileSync(`${localeDir}/${locale}`));
this.locales[locale.substring(0, locale.indexOf('.js'))] = localeParsed;
}
fs.readdir(`${__baseDir}/commands`, (err, fldrs) => {
if (err) {
reject(err);
} else {
for (let fldr of fldrs) {
let owo = fs.readdirSync(`${__baseDir}/commands/${fldr}`);
if (owo.indexOf('locales') !== -1) {
let locales = fs.readdirSync(`${__baseDir}/commands/${fldr}/locales`);
for (let locale of locales) {
if (!locale.endsWith('.json')) continue;
let r = JSON.parse(fs.readFileSync(`${__baseDir}/commands/${fldr}/locales/${locale}`));
let l = locale.substring(0, locale.indexOf('.json'));
this.locales[l] = Object.assign({}, this.locales[l], r);
}
}
}
resolve();
}
});
}
});
});
}
/**
* Return's the value of 'key' in the locale specified, or fallback to the fallback language.
*
* @param {String} key The key whose value to translate
* @param {String} locale Name of locale to translate too.
* @param {Object=} replacers Object of values in string.
* @returns {String}
*/
t(key, locale = this.fallbackLocale, replacers = {}) {
if (typeof key !== 'string') {
throw new Error('key is not a string');
} else if (typeof locale !== 'string') {
throw new Error('locale is not a string');
} else if (!this.locales[locale]) {
throw new Error(`${locale} is not a valid locale`);
} else {
let res = this.locales[locale][key] || this.locales[this.fallbackLocale][key] || '';
if (/.*{{.+}}.*/g.test(res) && Object.keys(replacers).length !== 0) {
for (let rep of Object.keys(replacers)) {
res = res.replace(new RegExp(`{{${rep}}}`, 'g'), replacers[rep]);
}
}
return res;
}
}
}
module.exports = new localeManager(); | JavaScript | 0.000008 | @@ -1002,32 +1002,97 @@
e of locales) %7B%0A
+ if (!locale.endsWith('.json')) continue;%0A
|
0ed0461f0837231977d0c56253b83d2683de16cd | Fix program layout shift | ReactApp/src/Cards/Program/ProgramComponents.js | ReactApp/src/Cards/Program/ProgramComponents.js | import React, { Component } from 'react';
import {blue100, red100, cyan500, teal400, amber800, pink500, purple500} from 'material-ui/styles/colors';
import {CardText} from 'material-ui/Card';
import RaisedButton from 'material-ui/RaisedButton';
const programTableStyle = {
// border: '1px solid black',
borderCollapse: 'collapse',
width: '100%',
};
const programRowStyle = {
// border: '1px solid black',
borderCollapse: 'collapse',
};
const programHourStyle = {
borderRight: '1px solid black',
borderCollapse: 'collapse',
position: 'relative',
height: '40px',
top: '20px',
width: '60px',
};
const programCellStyle = {
border: '1px solid white',
borderCollapse: 'collapse',
width: '20%',
backgroundColor: blue100,
padding: '0.4em',
textAlign: 'center',
};
const eventColors = {
bal: cyan500,
concert: teal400,
theatre: amber800,
learn: pink500,
free: purple500,
};
class BandPlaying extends React.Component {
render() {
var kind = this.props.kind;
var cellStyle = Object.assign({}, programCellStyle, {
backgroundColor: eventColors[kind]
});
return (
<td style={cellStyle} rowSpan={this.props.duration}>
<a style={{color: 'white', textDecoration: 'none'}} href="#">{this.props.name}</a>
</td>
)
}
}
class HourRow extends React.Component {
render() {
var groups = this.props.groups;
return (
<tr>
<th style={programHourStyle}>{this.props.hour}</th>
{groups.map((group) => {
if (group === false)
return <td style={{}}></td>
else if (group === true)
return null
else
return (
<BandPlaying {...group} />
)
})}
</tr>
);
}
}
const i18n_strings = {
fr: {
all_details: 'Tous les détails sur les artistes',
},
en: {
all_details: 'All informations on the line-up',
},
nl: {
all_details: 'Alle informatie over de kunstenaars',
}
}
export class DayProgram extends React.Component {
render() {
var strings = i18n_strings[this.props.lang] || i18n_strings['fr'];
return(
<div>
<CardText>
<RaisedButton label={strings.all_details} secondary={true}
labelColor='white' linkButton={true}
style={{marginLeft: 'auto'}}
href="/static/all-details.html" />
</CardText>
<table style={programTableStyle}>
<tr style={programRowStyle}>
<th></th>
<th style={{}}>Salle</th>
<th style={{}}>Chapiteau 1</th>
<th style={{}}>Chapiteau 2</th>
<th style={{}}>Cour</th>
</tr>
{this.props.plan.map((hourPlan) =>
<HourRow hour={hourPlan.hour} groups={hourPlan.groups} />
)}
</table>
</div>
);
}
}
| JavaScript | 0 | @@ -584,16 +584,17 @@
top: '
+-
20px',%0A
|
ddd8eda064809a55f9c88cd4790061f0adf30a4f | Fix dest path | slush/tasks/staticOptimize/files/tools/tasks/optimizeStatic.js | slush/tasks/staticOptimize/files/tools/tasks/optimizeStatic.js | const gulp = require('gulp');
const imagemin = require('gulp-imagemin');
const pngquant = require('imagemin-pngquant');
/**
* Optimizes images.
*
* @task optimizeStatic
*/
gulp.task('optimizeStatic', (done) => {
return gulp.
src(env.DIR_SRC + '/assets/media/images/**/*')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest(env.DIR_DEST + '/dist/images'));
});
| JavaScript | 0.000055 | @@ -476,19 +476,28 @@
+ '/
-dist
+assets/media
/images
+/
'));
|
8ce7c18cd8163d36afde3f574cf4296e19190cd2 | fix bugs at inventory movement validator | src/inventory/inventory-movement-validator.js | src/inventory/inventory-movement-validator.js | require("should");
module.exports = function (data) {
data.should.not.equal(null);
data.should.instanceOf(Object);
data.should.have.property('referenceNo');
data.referenceNo.should.be.String();
data.should.have.property('referenceType');
data.referenceType.should.be.String();
data.should.have.property('date');
data.date.should.instanceof(Object);
data.should.have.property('productId');
data.productId.should.instanceof(Object);
data.should.have.property('productCode');
data.productCode.should.instanceof(String);
data.should.have.property('productName');
data.productName.should.be.String();
data.should.have.property('storageId');
data.storageId.should.instanceof(Object);
data.should.have.property('storageCode');
data.storageCode.should.instanceof(String);
data.should.have.property('storageName');
data.storageName.should.be.String();
data.should.have.property('before');
data.before.should.instanceOf(Number);
data.should.have.property('quantity');
data.quantity.should.instanceOf(Number);
data.should.have.property('after');
data.after.should.instanceOf(Number);
data.should.have.property('secondBefore');
data.secondBefore.should.instanceOf(Number);
data.should.have.property('secondQuantity');
data.secondQuantity.should.instanceOf(Number);
data.should.have.property('secondAfter');
data.secondAfter.should.instanceOf(Number);
data.should.have.property('thirdBefore');
data.secondAfter.should.instanceOf(Number);
data.should.have.property('thirdQuantity');
data.secondAfter.should.instanceOf(Number);
data.should.have.property('thirdAfter');
data.secondAfter.should.instanceOf(Number);
data.should.have.property('uomId');
data.uomId.should.instanceof(Object);
data.should.have.property('uom');
data.uom.should.be.String();
data.should.have.property('secondUomId');
data.secondUomId.should.instanceof(Object);
data.should.have.property('secondUom');
data.secondUom.should.be.String();
data.should.have.property('thirdUomId');
data.thirdUomId.should.instanceof(Object);
data.should.have.property('thirdUom');
data.thirdUom.should.be.String();
data.should.have.property('remark');
data.remark.should.be.String();
data.should.have.property('type');
data.type.should.be.String();
}; | JavaScript | 0 | @@ -1153,24 +1153,32 @@
data.after
+Quantity
.should.inst
|
2a677fd0532d1633d4a4d4f6328d1656febbf6bb | Drop Markdown text box | orion/ui/helpers/misc.js | orion/ui/helpers/misc.js | import React from "react";
import {Div} from "./div";
import classNames from "classnames/bind";
// Loading Icon
export const LoadingDiv = (props) => {
let text = props.text || "Loading ...";
return (
<div centerText><span className="l-spinner"></span>
<div>{text}</div>
</div>
)
};
export const LoadingDivLarge = (props) => {
let text = props.text || "Loading ...";
return (
<Div centerText className="l-row-gut-2" style={{"fontSize": '3rem', "marginTop": '2em'}}>
<span style={{width: '100px', height: '100px'}} className="l-spinner"></span>
<div>{text}</div>
</Div>);
};
// Regular Icon
export const Icon = (props) => {
let {onClick, type, color, ...others} = props;
let iconclasses = classNames({
'l-secondary--light' : color == "neutral",
'l-primary-color' : color == "fancy",
});
if ( onClick ) {
return <a href="" onClick={onClick}><span className={`l-col-gut-sm icon-${props.type} ${iconclasses}`} {...others}/></a>
}
else {
return <span className={`l-col-gut-sm icon-${props.type} ${iconclasses}`} {...others}/>
}
};
// Horizontal Spacer
export const Spacer = (props) => <div className={`l-clear l-row-gut-${props.size ? props.size : 'half'}`}></div>;
/// Paragraphs ///
// Markdown paragraph
export const MarkDown = (props) => (
<div dangerouslySetInnerHTML={{__html: props.children} }></div>
);
/**
* Creator: Sam Herbert (@sherb), for everyone. More @ http://goo.gl/7AJzbL
* @licence MIT
* @param size
* @return XML
*/
export const ProgressIcon = ({size = 15}) => (
<svg width={size} height={size} viewBox="0 0 57 57" xmlns="http://www.w3.org/2000/svg" stroke="#fff">
<g fill="none" fillRule="evenodd">
<g transform="translate(1 1)" stroke-width="2">
<circle cx="5" cy="50" r="5">
<animate attributeName="cy"
begin="0s" dur="2.2s"
values="50;5;50;50"
calcMode="linear"
repeatCount="indefinite"/>
<animate attributeName="cx"
begin="0s" dur="2.2s"
values="5;27;49;5"
calcMode="linear"
repeatCount="indefinite"/>
</circle>
<circle cx="27" cy="5" r="5">
<animate attributeName="cy"
begin="0s" dur="2.2s"
from="5" to="5"
values="5;50;50;5"
calcMode="linear"
repeatCount="indefinite"/>
<animate attributeName="cx"
begin="0s" dur="2.2s"
from="27" to="27"
values="27;49;5;27"
calcMode="linear"
repeatCount="indefinite"/>
</circle>
<circle cx="49" cy="50" r="5">
<animate attributeName="cy"
begin="0s" dur="2.2s"
values="50;50;5;50"
calcMode="linear"
repeatCount="indefinite"/>
<animate attributeName="cx"
from="49" to="49"
begin="0s" dur="2.2s"
values="49;5;27;49"
calcMode="linear"
repeatCount="indefinite"/>
</circle>
</g>
</g>
</svg>
);
| JavaScript | 0.000001 | @@ -1312,159 +1312,8 @@
%3E;%0A%0A
-%0A/// Paragraphs ///%0A%0A// Markdown paragraph%0Aexport const MarkDown = (props) =%3E (%0A %3Cdiv dangerouslySetInnerHTML=%7B%7B__html: props.children%7D %7D%3E%3C/div%3E%0A);%0A%0A%0A
/**%0A
|
46922a5f2aff8a470cd417fdd8684154ac290563 | Deploy defaults. | webpack/webpack.config.js | webpack/webpack.config.js | const path = require("path");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
module.exports = (websomServer) => {
let gatherViews = () => {
let files = [];
for (let [i, mod] of websomServer.module.modules.entries()) {
let resources = websomServer.resource.compile(mod.name, mod.root, mod.baseConfig.resources);
for (let resource of resources) {
if (resource.type == "view") {
files.push({
file: resource.file,
type: "view",
package: mod.name
});
}
}
}
for (let [i, theme] of websomServer.theme.themes.entries()) {
let resources = websomServer.resource.compile(theme.name, theme.root, theme.config.resources);
for (let resource of resources) {
if (resource.type == "view") {
files.push({
file: resource.file,
type: "view",
package: theme.name
});
}
}
}
return files;
};
return {
entry: "./entry.js",
mode: "development",
module: {
rules: [
{
test: /\.view$/,
oneOf: [
{
resourceQuery: /vue/,
use: [
{
loader: "vue-loader"
},
{
loader: path.resolve(__dirname, "./view-loader/loader.js")
}
]
},
{
use: [
{
loader: path.resolve(__dirname, "./view-loader/loader.js")
}
]
}
]
},
{
test: /\.vue$/,
use: [
{
loader: "vue-loader"
},
{
loader: path.resolve(__dirname, "./view-loader/loader.js")
}
]
},
{
test: /\.websom-packages$/,
use: [
{
loader: path.resolve(__dirname, "./websom-loader/loader.js"),
options: {
type: "components",
files: gatherViews
}
}
]
},
{
test: /\.websom-effects$/,
use: [
{
loader: path.resolve(__dirname, "./websom-loader/loader.js"),
options: {
type: "effects",
files: gatherViews
}
}
]
},
{
test: /\.websom-state$/,
use: [
{
loader: path.resolve(__dirname, "./websom-loader/loader.js"),
options: {
type: "state",
files: gatherViews
}
}
]
},
{
test: /\.websom-scripts$/,
use: [
{
loader: path.resolve(__dirname, "./websom-loader/loader.js"),
options: {
type: "script",
files: gatherViews
}
}
]
},
{
test: /\.websom-styles$/,
use: [
"vue-style-loader",
"css-loader",
"less-loader",
{
loader: path.resolve(__dirname, "./websom-loader/loader.js"),
options: {
type: "styles",
files: gatherViews
}
}
]
},
{
test: /\.css$/,
use: [
"vue-style-loader",
"css-loader",
"less-loader"
]
},
{
test: /\.less$/,
use: [
"vue-style-loader",
"css-loader",
"less-loader"
]
},
{
test: /\.js$/,
loader: "babel-loader",
options: {
plugins: [
require.resolve("@babel/plugin-syntax-dynamic-import")
]
}
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=20000&mimetype=application/font-woff"
},
{
test: /\.(ttf|eot|png|svg|jpg|gif|jpeg|webp|webm)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader"
}
]
},
output: {
path: websomServer.config.javascriptOutput,
filename: websomServer.config.jsBundle,
publicPath: "/"
},
plugins: [
new VueLoaderPlugin()
],
context: path.resolve(__dirname),
resolve: {
modules: [
path.resolve(__dirname, "../node_modules")
],
alias: {
Util: path.resolve(__dirname, './')
}
}
};
}; | JavaScript | 0 | @@ -112,22 +112,80 @@
omServer
-) =%3E %7B
+, deployBundle) =%3E %7B%0A%09deployBundle = deployBundle %7C%7C %22default%22;%0A
%0A%09let ga
@@ -1792,32 +1792,62 @@
les: gatherViews
+,%0A%09%09%09%09%09%09%09%09bundle: deployBundle
%0A%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09
@@ -2501,32 +2501,62 @@
les: gatherViews
+,%0A%09%09%09%09%09%09%09%09bundle: deployBundle
%0A%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09
@@ -2824,32 +2824,62 @@
les: gatherViews
+,%0A%09%09%09%09%09%09%09%09bundle: deployBundle
%0A%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09
|
3818bd28aec81317ca88c2944fc984dda4cbf8e6 | Add sourcemaps to examples build | website/build-examples.js | website/build-examples.js | /**
* build-examples.js
* --------
* Searches for each example's `js/app.es6` file.
* Creates a new watchify instance for each `app.es6`.
* Changes to Uppy's source will trigger rebundling.
*
* Run as:
*
* build-examples.js # to build all examples one-off
* build-examples.js watch # to keep rebuilding examples with an internal watchify
* build-examples.js <path> # to build just one example app.es6
* build-examples.js <path> <path> # to build just one example app.es6 to a specific location
*
* Note:
* Since each example is dependent on Uppy's source,
* changing one source file causes the 'file changed'
* notification to fire multiple times. To stop this,
* files are added to a 'muted' array that is checked
* before announcing a changed file. It's removed from
* the array when it has been bundled.
*/
var createStream = require('fs').createWriteStream
var glob = require('multi-glob').glob
var chalk = require('chalk')
var path = require('path')
var mkdirp = require('mkdirp')
var notifier = require('node-notifier')
var babelify = require('babelify')
var browserify = require('browserify')
var watchify = require('watchify')
var webRoot = __dirname
var uppyRoot = path.dirname(webRoot)
var srcPattern = webRoot + '/src/examples/**/app.es6'
var dstPattern = webRoot + '/public/examples/**/app.js'
var watchifyEnabled = process.argv[2] === 'watch'
var browserifyPlugins = []
if (watchifyEnabled) {
browserifyPlugins.push(watchify)
}
// Instead of 'watch', build-examples.js can also take a path as cli argument.
// In this case we'll only bundle the specified path/pattern
if (!watchifyEnabled && process.argv[2]) {
srcPattern = process.argv[2]
if (process.argv[3]) {
dstPattern = process.argv[3]
}
}
// Find each app.es6 file with glob.
glob(srcPattern, function (err, files) {
if (err) throw new Error(err)
if (watchifyEnabled) {
console.log('--> Watching examples..')
}
var muted = []
// Create a new watchify instance for each file.
files.forEach(function (file) {
var browseFy = browserify(file, {
cache: {},
packageCache: {},
plugin: browserifyPlugins
})
// Aliasing for using `require('uppy')`, etc.
browseFy
.require(uppyRoot + '/src/index.js', { expose: 'uppy' })
.require(uppyRoot + '/src/core/index.js', { expose: 'uppy/core' })
.require(uppyRoot + '/src/plugins/index.js', { expose: 'uppy/plugins' })
.require(uppyRoot + '/src/locales/index.js', { expose: 'uppy/locales' })
.transform(babelify)
// Listeners for changes, errors, and completion.
browseFy
.on('update', bundle)
.on('error', onError)
.on('file', function (file, id, parent) {
// When file completes, unmute it.
muted = muted.filter(function (mutedId) {
return id !== mutedId
})
})
// Call bundle() manually to start watch processes.
bundle()
/**
* Creates bundle and writes it to static and public folders.
* Changes to
* @param {[type]} ids [description]
* @return {[type]} [description]
*/
function bundle (ids) {
ids = ids || []
ids.forEach(function (id) {
if (!isMuted(id, muted)) {
console.info(chalk.cyan('change:'), id)
muted.push(id)
}
})
var exampleName = path.basename(path.dirname(file))
var output = dstPattern.replace('**', exampleName)
var parentDir = path.dirname(output)
mkdirp.sync(parentDir)
console.info(chalk.green('✓ building:'), chalk.green(path.relative(process.cwd(), file)))
var bundle = browseFy.bundle()
.on('error', onError)
bundle.pipe(createStream(output))
}
})
})
/**
* Logs to console and shows desktop notification on error.
* Calls `this.emit(end)` to stop bundling.
* @param {object} err Error object
*/
function onError (err) {
console.error(chalk.red('✗ error:'), chalk.red(err.message))
notifier.notify({
'title': 'Build failed:',
'message': err.message
})
this.emit('end')
// When running without watch, process.exit(1) on error
if (!watchifyEnabled) {
process.exit(1)
}
}
/**
* Checks if a file has been added to muted list.
* This stops single changes from logging multiple times.
* @param {string} id Name of changed file
* @param {Array<string>} list Muted files array
* @return {Boolean} True if file is muted
*/
function isMuted (id, list) {
return list.reduce(function (prev, curr) {
return prev || (curr === id)
}, false)
}
| JavaScript | 0 | @@ -2132,24 +2132,43 @@
eCache: %7B%7D,%0A
+ debug: true,%0A
plugin
|
3206327a9e465437be5205be45906fa49136107d | Set 500ms | static/main.js | static/main.js | var app = angular.module('jesuis', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/init', {
templateUrl: 'partials/init.html',
controller: 'InitController'
})
.when('/event', {
templateUrl: 'partials/event.html',
controller: 'EventController',
reloadOnSearch: false
})
.otherwise({
redirectTo: '/init'
})
}])
.filter("trustUrl", ['$sce', function ($sce) {
return function (recordingUrl) {
return $sce.trustAsResourceUrl(recordingUrl);
};
}])
.controller('InitController', ['$scope', '$location', function($scope, $location) {
console.log("init-controller");
$scope.start = function() {
var elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
$location.path('/event');
};
}])
.controller('EventController', ['$scope', '$location', '$anchorScroll', "$interval", function($scope, $location, $anchorScroll, $interval) {
console.log("event-controller");
$scope.selected_content = 0;
$scope.content = window.content;
$scope.content_top = window.content.filter(function(element, index) { return index % 2 == 1; });
$scope.content_bottom = window.content.filter(function(element, index) { return index % 2 == 0; });
$scope.next = function(id) {
var selectedVideo = document.getElementById("video-"+id);
window.content.forEach(function(elem, index) {
var video = document.getElementById("video-"+index);
video.pause();
});
selectedVideo.play();
$scope.selected_content = id;
$location.hash("event-"+$scope.selected_content);
$anchorScroll();
};
var loaded = $interval(function() {
try { $scope.next(0); $interval.cancel(loaded); }
catch (e) { console.log("waiting..."); }
});
}])
;
| JavaScript | 0.000002 | @@ -2078,24 +2078,28 @@
.%22); %7D%0A %7D
+,500
);%0A %7D%5D)%0A;%0A%0A
|
f18874c549a360415ecd765103b31c3c75d55cd4 | Add singleton pattern test | test/new-tests.js | test/new-tests.js | 'use strict';
// 2017-06-23 | It's been almost 18 months since I first wrote Dolza and its test suite. I think my JavaScript skills
// have come a long way since then. I'm going to rewrite some of the original test suite to make sure that Dolza
// functions as it should. I may update its functionality, too, if that seems warranted.
import chai, { expect } from 'chai';
import dirtyChai from 'dirty-chai';
import _ from 'lodash';
import dolzaFactory from '../index';
chai.use( dirtyChai );
// Test fixtures adapted from _Node.js Design Patterns, Second Ed._, Ch. 7
const dbFactory = function dbFactoryFunction( name, server, port ) {
return {
getId() {
return this.getUrl();
},
getUrl() {
return `${server}:${port}/${name}`;
}
};
};
const userRoutesFactory = function userRoutesFactoryFunction( userService, uuid ) {
return {
getId() {
return `routes ${uuid} :: ${userService.getId()}`;
}
};
};
const userServiceFactory = function userServiceFactoryFunction( db, salt ) {
return {
getId() {
return `${db.getId()}$${salt}`;
}
};
};
describe( 'Dolza (a lightweight dependency injection container)', function() {
let dolza;
beforeEach( function() {
dolza = dolzaFactory();
} );
it( 'passes a canary test', function() {
expect( true ).to.be.true();
expect( 1 + 1 ).to.equal( 2 );
} );
context( 'has a function `register` for registering a factory function that', function() {
it( 'returns an object literal describing the factory function', function() {
let expectedResult = {
key: 'db',
dependencies: [ 'dbServer', 'dbPort', 'dbName' ]
// dependencies: [ 'chumley', 99, 'smart' ]
};
expect( dolza.register( 'db', dbFactory, [ 'dbServer', 'dbPort', 'dbName' ] ) )
.to.deep.equal( expectedResult );
} );
it( 'throws an error if the first argument is not a string' );
it( 'throws an error if the second argument is not a function' );
it( 'throws an error if the optional third argument is not a string or an array of strings' );
} );
context( 'has a function `store` for storing data that', function() {
it( 'returns the key and type of data stored', function() {
let expectedResult = {
key: 'dbServer',
type: 'string'
};
expect( dolza.store( 'dbServer', 'chumley' ) ).to.deep.equal( expectedResult );
expectedResult = {
key: 'dbPort',
type: 'number'
};
expect( dolza.store( 'dbPort', 99 ) ).to.deep.equal( expectedResult );
} );
it( 'throws an error if the first argument is not a string', function () {
expect( function storeFirstArg() {
dolza.store( 99, 'agent' )
} ).to.throw( Error, dolzaFactory.messages.fnStoreFirstArg );
} );
it( 'throws an error if the second argument is null or undefined', function () {
expect( function storeSecondArgNull() {
dolza.store( 'null', null )
} ).to.throw( Error, dolzaFactory.messages.fnStoreSecondArg );
expect( function storeSecondArgUndef() {
dolza.store( 'undef', undefined )
} ).to.throw( Error, dolzaFactory.messages.fnStoreSecondArg );
} );
it( 'accepts null or undefined for the second argument if the optional third argument is `true`' );
} );
context( 'has a function `get` that accepts a key and', function() {
const data = {
dbServer: 'chumley',
dbPort: 99,
dbName: 'smart',
salt: 'a19b27c36d48e50',
uuid: 'jfe354356VDAasdnceqKNNFDOI4TNVM'
};
const factories = {
db: {
factory: dbFactory,
args: [ 'dbName', 'dbServer', 'dbPort' ]
},
userRoutes: {
factory: userRoutesFactory,
args: [ 'userService', 'uuid' ]
},
userService: {
factory: userServiceFactory,
args: [ 'db', 'salt' ]
}
};
beforeEach( function () {
_.forEach( data, (value, key) => dolza.store( key, value ) );
_.forEach( factories, (value, key) => dolza.register( key, value.factory, value.args ) );
} );
it( 'returns stored data when given a key for stored data', function () {
expect( dolza.get( 'dbServer' ) ).to.equal( 'chumley' );
expect( dolza.get( 'dbPort' ) ).to.equal( 99 );
expect( dolza.get( 'dbName' ) ).to.equal( 'smart' );
} );
it( 'returns an object created from a factory when given a key for a factory function', function () {
const db = dolza.get( 'db' );
const expectedDbUrl = `${data.dbServer}:${data.dbPort}/${data.dbName}`;
expect( db.getId() ).to.equal( expectedDbUrl );
} );
it( 'correctly instantiates a dependency graph as needed' );
it( 'correctly waits for asynchronously dependencies to be instantiated' );
it( 'throws an error if the key is not a string', function () {
expect( function() {
dolza.get( 99 );
} ).to.throw( Error, dolzaFactory.messages.fnGetKeyNotString( 99 ) );
} );
it( 'throws an error if the key is not registered', function () {
expect( function() {
dolza.get( 'no-such-key' )
} ).to.throw( Error, dolzaFactory.messages.fnGetNotValidKey( 'no-such-key' ) );
} );
} );
// TODO Maybe? context( 'when listing registered modules', function() {} );
} );
| JavaScript | 0.000007 | @@ -5173,32 +5173,297 @@
;%0A %7D );%0A%0A
+ it( 'implements the singleton pattern for each key', function() %7B%0A const db1 = dolza.get( 'db' );%0A const db2 = dolza.get( 'db' );%0A expect( db1 === db2 ).to.be.true();%0A expect( db1 ).to.equal( db2 );%0A %7D );%0A%0A
it( 'cor
|
d80eb4f8a1f54431cd5d4bb3db531c09ce3584a7 | add missing return; remove console.log | src/redux/actions.js | src/redux/actions.js | 'use strict';
import crypto from 'crypto';
import db from './db';
export function setGreeting(greeting) {
return {
type: 'SET_GREETING',
greeting
};
};
export function togglePeopleModal() {
return {
type: 'TOGGLE_PEOPLE_MODAL'
};
};
export function fetchPeople() {
return db.allDocs({
include_docs: true
}).then(people => {
return {
type: 'FETCH_PEOPLE',
people: mapDocsFromPouch(people)
};
}).catch(err => {
throw err;
});
};
export function deletePerson() {
return {
type: 'DELETE_PERSON'
};
}
export function deletePeople() {
db.allDocs({
include_docs: true
}).then(records => {
return Promise.all(
records.rows.map(row => row.doc)
.map(doc => db.remove(doc))
).then(() => {
return {
type: 'DELETE_PEOPLE'
};
});
}).catch(err => {
throw err;
});
}
export function upsertPerson(name) {
console.log('upsertPerson: ', name);
return db.put({
_id: generateId(),
name: name
}).then(person => {
return {
type: 'UPSERT_PERSON'
};
}).catch(err => {
throw err;
});
}
function mapDocsFromPouch(records) {
if (!!!records) {
return {};
}
return records.rows.map(record => record.doc);
}
function generateId() {
return crypto.randomBytes(16).toString('hex');
}
| JavaScript | 0.000004 | @@ -594,16 +594,23 @@
e() %7B%0A
+return
db.allDo
@@ -925,47 +925,8 @@
) %7B%0A
- console.log('upsertPerson: ', name);%0A
re
|
0302e794af7206a63d63e6ae94b7c443e35baf2a | Update set currency header | src/javascript/app/pages/user/set_currency.js | src/javascript/app/pages/user/set_currency.js | const BinaryPjax = require('../../base/binary_pjax');
const Client = require('../../base/client');
const Header = require('../../base/header');
const BinarySocket = require('../../base/socket');
const getCurrencyName = require('../../common/currency').getCurrencyName;
const isCryptocurrency = require('../../common/currency').isCryptocurrency;
const localize = require('../../../_common/localize').localize;
const State = require('../../../_common/storage').State;
const Url = require('../../../_common/url');
const SetCurrency = (() => {
let is_new_account;
const onLoad = () => {
is_new_account = localStorage.getItem('is_new_account');
localStorage.removeItem('is_new_account');
const el = is_new_account ? 'show' : 'hide';
$(`#${el}_new_account`).setVisibility(1);
if (Client.get('currency')) {
if (is_new_account) {
$('#set_currency_loading').remove();
$('#has_currency, #set_currency').setVisibility(1);
} else {
BinaryPjax.loadPreviousUrl();
}
return;
}
BinarySocket.wait('payout_currencies').then((response) => {
const payout_currencies = response.payout_currencies;
const $fiat_currencies = $('<div/>');
const $cryptocurrencies = $('<div/>');
payout_currencies.forEach((c) => {
(isCryptocurrency(c) ? $cryptocurrencies : $fiat_currencies)
.append($('<div/>', { class: 'gr-3 currency_wrapper', id: c })
.append($('<div/>').append($('<img/>', { src: Url.urlForStatic(`images/pages/set_currency/${c.toLowerCase()}.svg`) })))
.append($('<div/>', { class: 'currency-name', html: (isCryptocurrency(c) ? `${getCurrencyName(c)}<br />(${c})` : c) })));
});
const fiat_currencies = $fiat_currencies.html();
if (fiat_currencies) {
$('#fiat_currencies').setVisibility(1);
$('#fiat_currency_list').html(fiat_currencies);
}
const crytpo_currencies = $cryptocurrencies.html();
if (crytpo_currencies) {
$('#crypto_currencies').setVisibility(1);
$('#crypto_currency_list').html(crytpo_currencies);
}
$('#set_currency_loading').remove();
$('#set_currency, .select_currency').setVisibility(1);
const $currency_list = $('.currency_list');
$('.currency_wrapper').on('click', function () {
$currency_list.find('> div').removeClass('selected');
$(this).addClass('selected');
});
const $form = $('#frm_set_currency');
const $error = $form.find('.error-msg');
$form.on('submit', (evt) => {
evt.preventDefault();
$error.setVisibility(0);
const $selected_currency = $currency_list.find('.selected');
if ($selected_currency.length) {
BinarySocket.send({ set_account_currency: $selected_currency.attr('id') }).then((response_c) => {
if (response_c.error) {
$error.text(response_c.error.message).setVisibility(1);
} else {
Client.set('currency', response_c.echo_req.set_account_currency);
BinarySocket.send({ balance: 1 });
BinarySocket.send({ payout_currencies: 1 }, { forced: true });
Header.displayAccountStatus();
let redirect_url;
if (is_new_account) {
if (Client.isAccountOfType('financial')) {
const get_account_status = State.getResponse('get_account_status');
if (!/authenticated/.test(get_account_status.status)) {
redirect_url = Url.urlFor('user/authenticate');
}
}
// Do not redirect MX clients to cashier, because they need to set max limit before making deposit
if (!redirect_url && !/^(iom)$/i.test(Client.get('landing_company_shortcode'))) {
redirect_url = Url.urlFor('cashier');
}
} else {
redirect_url = BinaryPjax.getPreviousUrl();
}
if (redirect_url) {
window.location.href = redirect_url; // load without pjax
} else {
Header.populateAccountsList(); // update account title
$('.select_currency').setVisibility(0);
$('#has_currency').setVisibility(1);
}
}
});
} else {
$error.text(localize('Please choose a currency')).setVisibility(1);
}
});
});
};
return {
onLoad,
};
})();
module.exports = SetCurrency;
| JavaScript | 0 | @@ -5053,32 +5053,178 @@
tVisibility(0);%0A
+ $('#hide_new_account').setVisibility(0);%0A $('#show_new_account').setVisibility(1);%0A
|
89897d26bccf637d85e494ae4d664c24343ea2f4 | Change position of all the food | games/hungrydog.js | games/hungrydog.js | var puppy = {
x: 550,
y: 490,
alive: true,
won: false,
canMove: true,
};
var bone1 = {
x: 750,
y: 200,
alive: true,
};
var bone2 = {
x: 1100,
y: 400,
alive: true,
};
var bacon = {
x: 1150,
y: 190,
alive: true,
};
document.getElementById("up").onclick = function() {move(38);};
document.getElementById("down").onclick = function() {move(40);};
document.getElementById("right").onclick = function() {move(39);};
document.getElementById("left").onclick = function() {move(37);};
var puppyImg = document.getElementById("puppy");
var boneImg1 = document.getElementById("bone1");
var boneImg2 = document.getElementById("bone2");
var baconImg = document.getElementById("bacon");
var foodCount = 3;
function move(direction){
if (puppy.canMove){
food_move(bone1, boneImg1);
food_move(bone2, boneImg2);
food_move(bacon, baconImg);
if (puppy.canMove){
if (direction.keyCode === 38 || direction === 38){ // move up
if (puppy.y > 50){
puppy.y = (puppy.y - 10);
puppyImg.style.top = (puppy.y + "px");
}
}else if (direction.keyCode === 40 || direction === 40){ // move down
if (puppy.y < 490){
puppy.y = (puppy.y + 10);
puppyImg.style.top = (puppy.y + "px");
}
}else if (direction.keyCode === 39 || direction == 39){ // move right
if (puppy.x < 1160){
puppy.x = (puppy.x + 10);
puppyImg.style.left = (puppy.x + "px");
}
}else if (direction.keyCode === 37 || direction == 37){ // move left
if (puppy.x > 550){
puppy.x = (puppy.x - 10);
puppyImg.style.left = (puppy.x + "px");
}
}
status(bone1, boneImg1);
status(bone2, boneImg2);
status(bacon, baconImg);
setTimeout(function(){
puppy.canMove = true;
}, 200)
puppy.canMove = false;
}
}
}
function food_move(food, foodImg){
var random = Math.floor((Math.random() * 4) + 1);
if (random === 1){
if (food.y > 50){
food.y = (food.y - 20);
foodImg.style.top = (food.y + "px");
}
}else if (random === 2){
if (food.y < 490){
food.y = (food.y + 20);
foodImg.style.top = (food.y + "px");
}
}else if (random === 3){
if (food.x < 1200){
food.x = (food.x + 20);
foodImg.style.left = (food.x + "px");
}
}else{
if (food.x > 550){
food.x = (food.x - 20);
foodImg.style.left = (food.x + "px");
}
}
}
function eat(food, foodImg){
if (puppy.x === food.x && puppy.y === food.y && food.alive){
foodCount -= 1;
food.alive = false;
setTimeout(function(){
foodImg.style.opacity = "0";
foodImg.style.transform = 'rotate(360deg) scale(5)';
if (foodCount < 1){
alert("Pepper is full! Thanks for feeding her!! YOU WIN!!!");
} else {
alert("Yummy!");
}
}, 400);
}
}
document.onkeydown = move; | JavaScript | 0.000106 | @@ -1641,30 +1641,27 @@
%7D%0A %7D%0A
-status
+eat
(bone1, bone
@@ -1671,22 +1671,19 @@
1);%0A
-status
+eat
(bone2,
@@ -1701,14 +1701,11 @@
-status
+eat
(bac
|
a711d88878394e54c67087646586f8c2f71bdf70 | Switch order to allow for modal updates in callback | src/google-places-autocomplete.js | src/google-places-autocomplete.js | /*
* angular-google-places-autocomplete
*
* Copyright (c) 2014 "kuhnza" David Kuhn
* Licensed under the MIT license.
* https://github.com/kuhnza/angular-google-places-autocomplete/blob/master/LICENSE
*/
'use strict';
angular.module('google.places', [])
/**
* DI wrapper around global google places library.
*
* Note: requires the Google Places API to already be loaded on the page.
*/
.factory('googlePlacesApi', ['$window', function ($window) {
return $window.google;
}])
/**
* Autocomplete directive. Use like this:
*
* <input type="text" g-places-autocomplete ng-model="myScopeVar" />
*/
.directive('gPlacesAutocomplete', [ '$parse', 'googlePlacesApi', function ($parse, google) {
function link($scope, element, attrs, ngModelController) {
var keymap = {
tab: 9,
enter: 13,
downArrow: 40
},
input = element[0],
options, validLocationTypes, autocomplete, onPlaceChanged;
(function init() {
initOptions();
initAutocomplete();
initValidation();
}());
function initOptions() {
options = {
types: ($scope.restrictType) ? [ $scope.restrictType ] : [],
componentRestrictions: ($scope.restrictCountry) ? { country: $scope.restrictCountry } : undefined
};
validLocationTypes = ($scope.validLocationTypes) ? $scope.validLocationTypes.replace(/\s/g, '').split(',') : [],
onPlaceChanged = (attrs.onPlaceChanged) ? $parse(attrs.onPlaceChanged) : angular.noop;
}
function initAutocomplete() {
autocomplete = new google.maps.places.Autocomplete(input, options);
element.bind('keydown', function (event) {
if (event.which == keymap.enter) {
event.preventDefault();
}
});
if ($scope.forceSelection) {
initForceSelection();
}
google.maps.event.addListener(autocomplete, 'place_changed', function () {
$scope.$apply(function () {
onPlaceChanged($scope.$parent, { $autocomplete: autocomplete });
ngModelController.$setViewValue(element.val());
});
});
}
function initValidation() {
ngModelController.$formatters.push(function (modelValue) {
var viewValue = "";
if (_.isString(modelValue)) {
viewValue = modelValue;
} else if (_.isObject(modelValue)) {
if (_.has(modelValue, 'formatted_address')) {
viewValue = modelValue.formatted_address;
} else if (_.has(modelValue, 'name')) {
viewValue = modelValue.name;
}
}
return viewValue;
});
ngModelController.$parsers.push(function (viewValue) {
var place = autocomplete.getPlace();
validate(viewValue, place);
return place;
});
ngModelController.$render = function () {
element.val(ngModelController.$viewValue);
};
}
function initForceSelection() {
var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent; // store the original event binding function
// Event listener wrapper that simulates a 'down arrow' keypress on hitting 'return' or 'tab' when no pac suggestion is selected,
// and then trigger the original listener.
function addEventListenerWrapper(type, listener) {
var originalListener;
if (type == "keydown") {
originalListener = listener;
listener = function (event) {
var suggestionSelected = $('.pac-item-selected').length > 0;
if ((event.which == keymap.enter || event.which == keymap.tab) && !suggestionSelected) {
var keydownEvent = angular.element.Event("keydown", {keyCode: keymap.downArrow, which: keymap.downArrow});
originalListener.apply(input, [keydownEvent]);
}
originalListener.apply(input, [event]);
};
}
// add the modified listener
_addEventListener.apply(input, [type, listener]);
}
if (input.addEventListener)
input.addEventListener = addEventListenerWrapper;
else if (input.attachEvent)
input.attachEvent = addEventListenerWrapper;
}
function validate(viewValue, place) {
ngModelController.$setValidity('address', isValidAddressSelection(viewValue, place));
ngModelController.$setValidity('locationType', isValidLocationType(place));
}
function isValidAddressSelection(viewValue, place) {
if ($scope.forceSelection) { // force user to choose from drop down.
if (place == null) return false;
if (_.isString(place)) return false;
if (!_.has(place, 'formatted_address')) return false;
}
return true;
}
function isValidLocationType(place) {
var valid = true;
if (!_.isEmpty(validLocationTypes)) {
valid = (place) ? containsAny(place.types, validLocationTypes) : false;
}
return valid;
}
function containsAny(array1, array2) {
var i;
for (i = 0; i < array2.length; i++) {
if (_.contains(array1, array2[i])) {
return true;
}
}
return false;
}
}
return {
restrict: 'A',
require: 'ngModel',
scope: {
forceSelection: '=?',
restrictType: '=?',
restrictCountry: '=?',
validLocationTypes: '@?'
},
link: link
}
}]);
| JavaScript | 0 | @@ -1877,24 +1877,78 @@
nction () %7B%0A
+%09%09%09%09%09%09ngModelController.$setViewValue(element.val());%0A
%09%09%09%09%09%09onPlac
@@ -2010,62 +2010,8 @@
%7D);%0A
-%09%09%09%09%09%09ngModelController.$setViewValue(element.val());%0A
%09%09%09%09
|
9bdd62ac1cb35c7ee3fdca293ead74dbcaa1403b | disable focus-on-click for homepage action buttons | agir/front/components/app/ActionButtons/ActionButton.js | agir/front/components/app/ActionButtons/ActionButton.js | import PropTypes from "prop-types";
import React from "react";
import styled from "styled-components";
import Link from "@agir/front/app/Link";
import { Hide } from "@agir/front/genericComponents/grid";
import { RawFeatherIcon } from "@agir/front/genericComponents/FeatherIcon";
const StyledButton = styled(Link)`
display: inline-flex;
flex-flow: column nowrap;
align-items: center;
gap: 8px;
width: 75px;
font-size: 12px;
line-height: 1.5;
font-weight: 400;
text-align: center;
color: ${(props) => props.theme.black700};
@media (min-width: ${(props) => props.theme.collapse}px) {
width: 100%;
flex-flow: row nowrap;
gap: 0;
font-size: 0.875rem;
height: 2rem;
}
&,
&:hover,
&:focus {
text-decoration: none;
}
&[disabled],
&[disabled]:hover,
&[disabled]:focus {
opacity: 0.5;
cursor: default;
color: ${(props) => props.theme.green500};
text-decoration: line-through;
}
& > ${RawFeatherIcon} {
background-color: ${(props) => props.$color};
}
& > span {
flex: 0 0 50px;
width: 50px;
height: 50px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 100%;
color: white;
@media (min-width: ${(props) => props.theme.collapse}px) {
transform-origin: left center;
transform: scale(0.64);
margin-right: -10px;
}
}
& > strong {
font-weight: inherit;
white-space: nowrap;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
`;
const ActionButton = (props) => {
const { route, label, icon, color, className, disabled = false } = props;
return (
<StyledButton
$color={color}
disabled={disabled}
onClick={disabled ? (e) => e.preventDefault() : undefined}
className={className}
route={route}
>
{typeof icon === "string" ? <RawFeatherIcon name={icon} /> : icon}
{Array.isArray(label) ? (
<strong>
<Hide as="span" title={label[1]} over>
{label[0]}
</Hide>
<Hide as="span" title={label[1]} under>
{label[1]}
</Hide>
</strong>
) : (
<strong title={label}>{label}</strong>
)}
</StyledButton>
);
};
ActionButton.propTypes = {
route: PropTypes.string,
label: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]),
icon: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
color: PropTypes.string,
className: PropTypes.string,
disabled: PropTypes.bool,
};
export default ActionButton;
| JavaScript | 0.000001 | @@ -1781,24 +1781,70 @@
undefined%7D%0A
+ onMouseDown=%7B(e) =%3E e.preventDefault()%7D%0A
classN
|
b71602d2ec812a144452f800b684acdd96c0f439 | Update ui-grid-header-cell.js | src/js/core/directives/ui-grid-header-cell.js | src/js/core/directives/ui-grid-header-cell.js | (function(){
'use strict';
angular.module('ui.grid').directive('uiGridHeaderCell', ['$log', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', function ($log, $timeout, $window, $document, gridUtil, uiGridConstants) {
// Do stuff after mouse has been down this many ms on the header cell
var mousedownTimeout = 500;
var uiGridHeaderCell = {
priority: 0,
scope: {
col: '=',
row: '=',
renderIndex: '='
},
require: '?^uiGrid',
templateUrl: 'ui-grid/uiGridHeaderCell',
replace: true,
link: function ($scope, $elm, $attrs, uiGridCtrl) {
$scope.grid = uiGridCtrl.grid;
$elm.addClass($scope.col.getColClass(false));
// shane - No need for watch now that we trackby col name
// $scope.$watch('col.index', function (newValue, oldValue) {
// if (newValue === oldValue) { return; }
// var className = $elm.attr('class');
// className = className.replace(uiGridConstants.COL_CLASS_PREFIX + oldValue, uiGridConstants.COL_CLASS_PREFIX + newValue);
// $elm.attr('class', className);
// });
// Hide the menu by default
$scope.menuShown = false;
// Put asc and desc sort directions in scope
$scope.asc = uiGridConstants.ASC;
$scope.desc = uiGridConstants.DESC;
// Store a reference to menu element
var $colMenu = angular.element( $elm[0].querySelectorAll('.ui-grid-header-cell-menu') );
var $contentsElm = angular.element( $elm[0].querySelectorAll('.ui-grid-cell-contents') );
// Figure out whether this column is sortable or not
if (uiGridCtrl.grid.options.enableSorting && $scope.col.enableSorting) {
$scope.sortable = true;
}
else {
$scope.sortable = false;
}
if (uiGridCtrl.grid.options.enableFiltering && $scope.col.enableFiltering) {
$scope.filterable = true;
}
else {
$scope.filterable = false;
}
function handleClick(evt) {
// If the shift key is being held down, add this column to the sort
var add = false;
if (evt.shiftKey) {
add = true;
}
// Sort this column then rebuild the grid's rows
uiGridCtrl.grid.sortColumn($scope.col, add)
.then(function () {
uiGridCtrl.columnMenuCtrl.hideMenu();
uiGridCtrl.grid.refresh();
});
}
// Long-click (for mobile)
var cancelMousedownTimeout;
var mousedownStartTime = 0;
$contentsElm.on('mousedown', function(event) {
if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) {
event = event.originalEvent;
}
// Don't show the menu if it's not the left button
if (event.button && event.button !== 0) {
return;
}
mousedownStartTime = (new Date()).getTime();
cancelMousedownTimeout = $timeout(function() { }, mousedownTimeout);
cancelMousedownTimeout.then(function () {
uiGridCtrl.columnMenuCtrl.showMenu($scope.col, $elm);
});
});
$contentsElm.on('mouseup', function () {
$timeout.cancel(cancelMousedownTimeout);
});
$scope.toggleMenu = function($event) {
$event.stopPropagation();
// If the menu is already showing...
if (uiGridCtrl.columnMenuCtrl.shown) {
// ... and we're the column the menu is on...
if (uiGridCtrl.columnMenuCtrl.col === $scope.col) {
// ... hide it
uiGridCtrl.columnMenuCtrl.hideMenu();
}
// ... and we're NOT the column the menu is on
else {
// ... move the menu to our column
uiGridCtrl.columnMenuCtrl.showMenu($scope.col, $elm);
}
}
// If the menu is NOT showing
else {
// ... show it on our column
uiGridCtrl.columnMenuCtrl.showMenu($scope.col, $elm);
}
};
// If this column is sortable, add a click event handler
if ($scope.sortable) {
$contentsElm.on('click', function(evt) {
evt.stopPropagation();
$timeout.cancel(cancelMousedownTimeout);
var mousedownEndTime = (new Date()).getTime();
var mousedownTime = mousedownEndTime - mousedownStartTime;
if (mousedownTime > mousedownTimeout) {
// long click, handled above with mousedown
}
else {
// short click
handleClick(evt);
}
});
$scope.$on('$destroy', function () {
// Cancel any pending long-click timeout
$timeout.cancel(cancelMousedownTimeout);
});
}
if ($scope.filterable) {
$scope.$on('$destroy', $scope.$watch('col.filter.term', function(n, o) {
uiGridCtrl.refresh()
.then(function () {
if (uiGridCtrl.prevScrollArgs && uiGridCtrl.prevScrollArgs.y && uiGridCtrl.prevScrollArgs.y.percentage) {
uiGridCtrl.fireScrollingEvent({ y: { percentage: uiGridCtrl.prevScrollArgs.y.percentage } });
}
// uiGridCtrl.fireEvent('force-vertical-scroll');
});
}));
}
}
};
return uiGridHeaderCell;
}]);
})();
| JavaScript | 0 | @@ -5081,16 +5081,21 @@
ridCtrl.
+grid.
refresh(
|
0d3babb2b755a7e07936e830891031db7fc79d34 | Use reserved identifiers for domain and email | test/provision.js | test/provision.js | const assert = require('assert');
const jwcrypto = require('jwcrypto');
const request = require('request');
const sideshow = require('../server');
const mockid = require('./lib/mockid');
const BASE_URL = 'http://localhost:3033';
const TEST_EMAIL = 'test.does.not.exist.for.sure@gmail.com';
/* globals describe, before, after, it */
describe('server', function() {
var server;
sideshow.setOpenIDRP(mockid({
url: 'http://does.not.exist',
result: {
authenticated: true,
email: TEST_EMAIL
}
}));
var pubkey;
before(function(done) {
jwcrypto.generateKeypair({
algorithm: 'RS',
keysize: 64
}, function(err, pair) {
pubkey = pair.publicKey.serialize();
server = sideshow.listen(3033, done);
});
});
describe('provisioning', function() {
it('should forward to auth url', function(done) {
request.get({
url: BASE_URL + '/authenticate/forward?email=' + TEST_EMAIL,
followRedirect: false
}, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 302);
assert.equal(res.headers.location, 'http://does.not.exist');
done();
});
});
it('should verify on return', function(done) {
request.get(BASE_URL + '/authenticate/verify', function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
done();
});
});
var csrf;
it('should get a csrf token', function(done) {
request.get(BASE_URL + '/provision', function(err, res, body) {
// please forgive me Cthulu
var re = /<input type="hidden" id="csrf" value="([^"]+)"\/>/;
csrf = body.match(re)[1];
assert(csrf);
done();
});
});
it('should sign a certificate', function(done) {
request.post({
url: BASE_URL + '/provision/certify',
headers: {
'X-CSRF-Token': csrf
},
json: {
email: TEST_EMAIL,
pubkey: pubkey,
duration: 1000 * 60 * 5
}
}, function(err, res, body) {
assert.ifError(err);
assert(body.cert);
assert.equal(body.cert.split('.').length, 3);
done();
});
});
});
after(function(done) {
server.close(done);
});
});
| JavaScript | 0 | @@ -249,36 +249,17 @@
= '
-test.does.not.exist.for.sure
+hikingfan
@gma
@@ -407,30 +407,30 @@
'http://
-does.not.exist
+openid.example
',%0A r
@@ -786,19 +786,17 @@
ion() %7B%0A
-
%0A
+
it('
@@ -1123,22 +1123,22 @@
p://
-does.not.exist
+openid.example
');%0A
@@ -2219,18 +2219,16 @@
%7D);%0A
-
%0A %7D);%0A%0A
|
8095a72bbc30af252080843bcd4c99d4321ad760 | Convert extended Form to native class, providing compatibility with ember-bootstrap 5.1+ | addon/components/bs-form.js | addon/components/bs-form.js | import { notEmpty } from '@ember/object/computed';
import { assert } from '@ember/debug';
import RSVP from 'rsvp';
import BsForm from 'ember-bootstrap/components/bs-form';
export default BsForm.extend({
'__ember-bootstrap_subclass': true,
hasValidator: notEmpty('model.validate'),
validate(model) {
let m = model;
assert(
'Model must be a Changeset instance',
m && typeof m.validate === 'function'
);
return new RSVP.Promise(function (resolve, reject) {
m.validate().then(() => {
model.get('isValid') ? resolve() : reject();
}, reject);
});
},
});
| JavaScript | 0 | @@ -1,55 +1,4 @@
-import %7B notEmpty %7D from '@ember/object/computed';%0A
impo
@@ -36,33 +36,8 @@
g';%0A
-import RSVP from 'rsvp';%0A
impo
@@ -109,22 +109,67 @@
ult
-BsForm.extend(
+class BsFormWithChangesetValidationsSupport extends BsForm
%7B%0A
@@ -200,19 +200,24 @@
ass'
-:
+ =
true
-,
+;
%0A%0A
+get
hasV
@@ -228,25 +228,42 @@
ator
-: notEmpty('
+() %7B%0A return typeof this.
model
+?
.val
@@ -271,14 +271,37 @@
date
-'),%0A%0A
+ === 'function';%0A %7D%0A%0A async
val
@@ -446,173 +446,96 @@
);%0A
+%0A
-return new RSVP.Promise(function (resolve, reject) %7B%0A m.validate().then(() =%3E %7B%0A model.get('isValid') ? resolve() : reject();%0A %7D, reject
+await m.validate();%0A if (!model.get('isValid')) %7B%0A throw new Error(
);%0A %7D
);%0A
@@ -534,16 +534,11 @@
%7D
-);
%0A %7D
-,
%0A%7D
-);
%0A
|
36117b40bed9406f0c61cdf232ac866cd0c5a40d | fix custom attributes inputs for new Topic | lib/admin/admin-topics-form/attrs/component.js | lib/admin/admin-topics-form/attrs/component.js | import React, { Component } from 'react'
export default ({ forum, topic }) => {
return (
<div className='attrs'>
{forum.topicsAttrs.map((attr) => {
const Form = forms[attr.kind]
const val = topic.attrs && topic.attrs[attr.name]
return <Form key={attr.name} {...attr} value={val} />
})}
</div>
)
}
const forms = {}
forms.Number = ({
name,
title,
mandatory,
min,
max,
value
}) => (
<div className='form-group kind-number'>
<label>{title}</label>
<input
className='form-control'
type='number'
name={`attrs.${name}`}
defaultValue={value}
min={min}
max={max}
required={mandatory}
validate={mandatory && 'required'} />
</div>
)
forms.String = ({
name,
title,
mandatory,
min,
max,
value
}) => (
<div className='form-group kind-string'>
<label>{title}</label>
<input
className='form-control'
type='text'
name={`attrs.${name}`}
defaultValue={value}
minLength={min}
maxLength={max}
required={mandatory}
validate={mandatory && 'required'} />
</div>
)
forms.Enum = ({
name,
title,
mandatory,
options,
value
}) => (
<div className='form-group kind-enum'>
<label>{title}</label>
<select
className='form-control'
name={`attrs.${name}`}
defaultValue={value}
required={mandatory}
validate={mandatory && 'required'}>
{options.map((opt) => (
<option key={opt.name} value={opt.name}>{opt.title}</option>
))}
</select>
</div>
)
forms.Boolean = class extends Component {
constructor (props) {
super(props)
this.state = {
checked: props.value
}
}
handleChange = (evt) => {
this.setState({
checked: !this.state.checked
})
}
render () {
const {
name,
title,
mandatory
} = this.props
return (
<div className='checkbox'>
<label>
{!this.state.checked && (
<input
type='hidden'
value='false'
name={`attrs.${name}`} />
)}
<input
type='checkbox'
onChange={this.handleChange}
defaultChecked={this.state.checked}
defaultValue={this.state.checked ? 'true' : undefined}
name={this.state.checked ? `attrs.${name}` : undefined}
required={mandatory}
validate={mandatory && 'required'} />
{title}
</label>
</div>
)
}
}
| JavaScript | 0 | @@ -172,16 +172,21 @@
nst Form
+Input
= forms
@@ -209,19 +209,37 @@
-cons
+le
t val
- =
+%0A%0A if (topic &&
top
@@ -249,16 +249,73 @@
attrs &&
+ topic.attrs.hasOwnProperty(attr.name)) %7B%0A val =
topic.a
@@ -330,16 +330,27 @@
r.name%5D%0A
+ %7D%0A%0A
@@ -361,16 +361,21 @@
rn %3CForm
+Input
key=%7Bat
|
085fc01e6029b0dea9b709ba3d6b95aa0f5c20f6 | update ember-cli-sass dependency to 4.0.1 | blueprints/ember-cli-foundation-sass/index.js | blueprints/ember-cli-foundation-sass/index.js | var fs = require('fs');
var path = require('path');
module.exports = {
normalizeEntityName: function() {
},
beforeInstall: function(options) {
return this.addBowerPackageToProject('foundation', '~5.5.0');
},
afterInstall: function(options) {
//copying over the foundation.scss and _settings.scss to make foundation customization easy
var foundationPath = path.join(process.cwd(), 'bower_components', 'foundation', 'scss');
var stylePath = path.join(process.cwd(), 'app', 'styles');
var settingsPath = path.join(foundationPath, 'foundation', '_settings.scss');
var mainPath = path.join(foundationPath, 'foundation.scss');
var _this = this;
fs.writeFileSync(path.join(stylePath, '_settings.scss'), fs.readFileSync(settingsPath));
fs.writeFileSync(path.join(stylePath, '_foundation.scss'), fs.readFileSync(mainPath));
return this.addPackagesToProject([
{ name: 'ember-cli-sass', target: '3.3.1'},
{ name: 'broccoli-clean-css', target: '~1.0.0' }
]);
}
};
| JavaScript | 0.000023 | @@ -958,11 +958,11 @@
t: '
-3.3
+4.0
.1'%7D
|
469c484f744434a7a1e143aad35c06459cd07f1d | Move notifyReady() call even though it probably doesn't matter. It will now get called before resolving in case that does any painting / layout updating. | src/lifecycle/created.js | src/lifecycle/created.js | import data from '../util/data';
import emit from '../api/emit';
import events from './events';
import patchAttributeMethods from './patch-attribute-methods';
import property from './property';
import propertiesCreated from './properties-created';
import propertiesReady from './properties-ready';
import prototype from './prototype';
import renderer from './renderer';
import resolve from './resolve';
// TODO Remove this when we no longer support the legacy definitions and only
// support a superset of a native property definition.
function ensurePropertyFunctions (opts) {
let props = opts.properties;
let names = Object.keys(props || {});
return names.reduce(function (descriptors, descriptorName) {
descriptors[descriptorName] = opts.properties[descriptorName];
if (typeof descriptors[descriptorName] !== 'function') {
descriptors[descriptorName] = property(descriptors[descriptorName]);
}
return descriptors;
}, {});
}
function ensurePropertyDefinitions (elem, propertyFunctions) {
return Object.keys(propertyFunctions || {}).reduce(function (descriptors, descriptorName) {
descriptors[descriptorName] = propertyFunctions[descriptorName](descriptorName);
return descriptors;
}, {});
}
function notifyReady (elem) {
emit(elem, 'skate.ready', {
bubbles: false,
cancelable: false
});
}
export default function (opts) {
let applyEvents = events(opts);
let applyPrototype = prototype(opts);
let applyRenderer = renderer(opts);
let propertyFunctions = ensurePropertyFunctions(opts);
return function () {
let info = data(this, `lifecycle/${opts.id}`);
let propertyDefinitions;
if (info.created) return;
info.created = true;
propertyDefinitions = ensurePropertyDefinitions(this, propertyFunctions);
patchAttributeMethods(this, opts);
applyPrototype(this);
propertiesCreated(this, propertyDefinitions);
applyEvents(this);
opts.created && opts.created(this);
applyRenderer(this);
propertiesReady(this, propertyDefinitions);
opts.ready && opts.ready(this);
resolve(this, opts);
notifyReady(this);
};
}
| JavaScript | 0 | @@ -2078,48 +2078,48 @@
-resolve(this, opts);%0A notifyReady(thi
+notifyReady(this);%0A resolve(this, opt
s);%0A
|
5acc197b26f5d75ef2596d4a49712ec309245674 | Assign the right variable | addon/components/data-table.js | addon/components/data-table.js | import Ember from 'ember';
import Table from 'ember-light-table';
import EmberDataTableMixin from 'ember-data-table-light/mixins/ember-data-table';
import TablePaginationMixin from 'ember-data-table-light/mixins/table-pagination';
import TableSortingMixin from 'ember-data-table-light/mixins/table-sorting';
import DataTableState from 'ember-data-table-light/services/data-table-state';
import layout from 'ember-data-table-light/templates/components/data-table';
import config from 'ember-data-table-light/configuration';
const { Component, assert, computed, inject, isEmpty } = Ember;
/**
* @class DataTable
* @extends Ember.Component
* @uses EmberDataTableMixin
* @uses TablePaginationMixin
* @uses TableSortingMixin
*/
const DataTable = Component.extend(EmberDataTableMixin, TablePaginationMixin, TableSortingMixin, {
layout,
/**
* Configures if the table should have a search field or not. The component
* that is used to create the search field can be configured with the
* {{#crossLink "DataTable/searchComponent:attribute"}}{{/crossLink}}
* attribute.
*
* @property search
* @type Boolean
* @default true
* @public
*/
search: true,
/**
* Component that is used to create the search field.
*
* @property searchComponent
* @type String
* @default 'data-table/search'
* @public
*/
searchComponent: 'data-table/search',
/**
* Configures if the table should have a dropdown menu to choose the visible
* columns. The component that is used can be configured with the
* {{#crossLink "DataTable/columnChooserComponent:attribute"}}{{/crossLink}}
*
* @property columnChooser
* @type Boolean
* @default true
* @public
*/
columnChooser: true,
/**
* Component that is used to render a column chooser. The default component
* requires the [ember-bootstrap](https://github.com/kaliber5/ember-bootstrap)
* addon.
*
* @property columnChooserComponent
* @type String
* @default 'data-table/column-chooser'
* @public
*/
columnChooserComponent: 'data-table/column-chooser',
/**
* Componente para ser exibido quando a tabela estiver vazia.
*
* @property emptyComponent
* @type String
* @default 'data-table/empty'
* @public
*/
emptyComponent: 'data-table/empty',
/**
* Component used to indicate that the table is loading.
*
* @property loadingComponent
* @type String
* @default 'data-table/loading'
* @public
*/
loadingComponent: 'data-table/loading',
/**
* Indicates if the table has one or more selected rows.
*
* @property hasSeletion
* @type Boolean
* @public
*/
hasSelection: computed.notEmpty('table.selectedRows'),
/**
* Configures if the table supports bulk actions for the selected records. If
* you set this to `true`, you must also set a value for
* {{#crossLink "DataTable/bulkActionsComponent:attribute"}}{{/crossLink}}.
*
* @property bulkActions
* @type Boolean
* @default false
* @public
*/
bulkActions: false,
/**
* Component used to render the bulk actions. It's visible only when there
* are rows selected in the table.
*
* @property bulkActionsComponent
* @type String
* @default null
* @public
*/
bulkActionsComponent: null,
/**
* Configures if the table should have a pagination component. The component
* used to show the pagination can be configured with the
* {{#crossLink "DataTable/paginationComponent:attribute"}}{{/crossLink}}
* option.
*
* @property pagination
* @type Boolean
* @default true
* @public
*/
pagination: true,
/**
* Component used to render the pagination for the table.
*
* @property paginationComponent
* @type String
* @default 'data-table/pagination'
* @public
*/
paginationComponent: 'data-table/pagination',
/**
* Configures if the table state must be saved. Currently, this saves only
* what columns are visible in the table, but this may be extended to save
* more properties.
*
* @property saveState
* @type Boolean
* @default true
* @public
*/
saveState: true,
/**
* Unique identifier for this table (must be constant across page refreshes),
* used to load and save the state. If this option is not specified, the
* model name is used instead.
*
* @property identifier
* @type String
* @public
*/
identifier: null,
/**
* Configures the service used to save the table state. Currently, the
* available options are `local-storage` and `simple-auth`, but you can also
* define yours.
*
* @property stateStorage
* @type String
* @public
*/
stateStorage: null,
/**
* Instance of the service used to save the table state. This is loaded based
* on the {{#crossLink "DataTable/stateStorage:attribute"}}{{/crossLink}}
* option.
*
* @property stateService
* @type DataTableState
* @protected
*/
stateService: null,
/**
* Table columns.
*
* @property columns
* @type Object[]
* @public
*/
columns: [],
/**
* Table object for ember-light-table.
*
* @property table
* @type Table
* @protected
*/
table: null,
init() {
this._super(...arguments);
assert(
'[ember-data-table-light] you must pass a model name to be used in this table',
!isEmpty(this.get('modelName'))
);
assert(
'[ember-data-table-light] you must configure the columns for this table',
!isEmpty(this.get('columns'))
);
this.table = new Table(this.get('columns'));
this._setupState();
this._fetchData();
},
_setupState() {
let identifier = this.get('identifier');
if (!identifier) {
identifier = this.get('modelName');
this.set('identifier', identifier);
}
if (!this.get('saveState')) {
return;
}
let stateStorage = this.get('stateStorage');
if (!stateStorage) {
stateStorage = config.stateStorage;
this.set('stateStorage', stateStorage);
}
let serviceName = 'data-table-state-' + stateStorage;
this.stateService = inject.service(serviceName);
assert(
`[ember-data-table-light] Storage ${stateStorage} is not supported: a service named ${serviceName} was not found`,
!isEmpty(this.get('stateService'))
);
assert(
`[ember-data-table-light] Storage ${stateStorage} is not supported: the service ${serviceName} must be an instance of DataTableState`,
this.get('stateService') instanceof DataTableState
);
let state = this.get('stateService').load(identifier, this.get('table'));
this.get('stateService').deserialize(this.get('table'), state);
},
actions: {
reloadTable() {
this._fetchData();
},
makeSearch(searchText) {
this.set('search', searchText);
this._fetchData();
},
onColumnClick(column) {
if (!column.sortable) {
return;
}
if (column.sorted) {
let columnName = column.get('valuePath');
let direction = column.get('ascending') ? 'asc' : 'desc';
this.sortColumn(columnName, direction);
}
else {
this.removeSorting();
}
this._fetchData();
},
columnVisibilityChanged(column) {
this.sendAction('columnVisibilityChanged', column);
let state = this.get('stateService').serialize(this.get('table'));
this.get('stateService').save(this.get('identifier'), state, this.get('table'));
}
}
});
DataTable.reopenClass({
positionalParams: ['modelName']
});
export default DataTable;
| JavaScript | 0.999998 | @@ -6837,16 +6837,20 @@
('search
+Text
', searc
|
51ab85fa27ae2a2a337aac6ceecf533dfd5a225a | Change the logic of checking piped files from boolean to sinon spy. | test/publisher.js | test/publisher.js | var es = require('event-stream');
var gulp = require('gulp');
var mox = require('./mock-knox');
describe('publisher', function () {
var publisher,
gulpS3,
mockedStream;
// replace all the required module with either mocked module or
// the exact same module so that istanbul would not include them in the coverage
beforeEach(function() {
mockedStream = es.mapSync( function (file) { return file;});
gulpS3 = sinon.stub().returns( mockedStream );
publisher = SandboxedModule.require('../publisher', {
requires: {
'gulp-s3': gulpS3,
'event-stream': es,
'knox': mox
}
});
});
describe ('Parameter', function () {
it('should throw with null options', function() {
expect(publisher).to.throw( 'Missing options' );
});
it('should throw with empty options', function() {
expect(function() {
publisher({});
}).to.throw( 'Missing app id' );
});
it('should throw with no credentials', function() {
var options = {
appID: 'some-ID',
devTag: 'some-tag'
}
expect(function() {
publisher(options);
}).to.throw( 'Missing credentials' );
});
it('should throw with no key', function() {
var options = {
appID: 'some-ID',
creds: {},
devTag: 'some-tag'
}
expect(function() {
publisher(options);
}).to.throw( 'Missing credential key' );
});
it('should throw with no secret', function() {
var options = {
appID: 'some-ID',
creds: {
key: 'some-key'
},
devTag: 'some-tag'
};
expect(function() {
publisher(options);
}).to.throw( 'Missing credential secret' );
});
it('should throw with no devTag', function() {
var options = {
appID: 'some-ID',
creds: {
key: 'some-key',
secret: 'some-secret'
}
};
expect(function() {
publisher(options);
}).to.throw( 'Missing devTag' );
});
it('should throw with no appID', function() {
var options = {
creds: {
key: 'some-key',
secret: 'some-secret'
},
devTag: 'some-tag'
};
expect(function() {
publisher(options);
}).to.throw( 'Missing app id' );
});
it ('should not throw even if there is extra info in the creds', function() {
var options = {
appID: 'some-ID',
creds: {
key: 'some-key',
secret: 'some-secret',
useless: 'testetetse'
},
devTag: 'some-tag'
};
expect(function() {
publisher(options);
}).to.not.throw();
});
});
describe('location', function () {
it('should return the proper address', function () {
var options = {
appID: 'some-ID',
creds: { key: 'some-key', secret: 'some-secret' },
devTag: 'some-tag'
};
expect(publisher( options ).location).to.equal('https://d2660orkic02xl.cloudfront.net/apps/some-ID/dev/some-tag/');
});
});
describe('stream', function () {
it('should pipe files into a s3-amazon bucket with existing contents but not overwrite contents', function (done) {
var options = {
appID: 'some-ID',
creds: { key: 'key-a', secret: 'some-secret' },
devTag: 'some-tag'
};
var passedData = false;
gulp.src('./test/dist/**')
.pipe( publisher(options) )
.on('data', function (data) {
passedData = true;
})
.on('end', function (err) {
expect(passedData).to.be.false;
done();
});
});
it('should pipe files into an empty s3-amazon bucket successfully', function (done) {
var options = {
appID: 'some-ID',
creds: { key: 'some-key', secret: 'some-secret' },
devTag: 'some-tag'
};
var passedData = false;
gulp.src('./test/dist/**')
.pipe( publisher(options) )
.on('data', function (data) {
passedData = true;
})
.on('end', function (err) {
expect(passedData).to.be.true;
done();
});
});
it('should expect an error when give a wrong key', function (done) {
var options = {
appID: 'some-ID',
creds: { key: 'wrong-key', secret: 'some-secret' },
devTag: 'some-tag'
};
var hasError;
gulp.src('./test/dist/**')
.pipe( publisher(options) )
.on('error', function (err) {
hasError = true;
expect(hasError).to.be.true;
done();
});
});
});
});
| JavaScript | 0 | @@ -3231,34 +3231,41 @@
%0A%09%09%09var
-passedData = false
+dataHandler = sinon.spy()
;%0D%0A%09%09%09gu
@@ -3343,77 +3343,19 @@
a',
-function (data) %7B%09%0D%0A%09%09%09%09%09%0D%0A%09%09%09%09%09passedData = true;%0D%0A%09%09%09%09%09%09%09%09%09%09%0D%0A%09%09%09%09%7D
+dataHandler
)%0D%0A%09
@@ -3404,31 +3404,37 @@
ect(
-passedData).to
+dataHandler).to.not
.be.
-false
+called
;%0D%0A%09
@@ -3696,26 +3696,33 @@
var
-passedData = false
+dataHandler = sinon.spy()
;%0D%0A%09
@@ -3804,79 +3804,19 @@
a',
-function (data) %7B%09%09%09%0D%0A%09%09%09%09%09%0D%0A%09%09%09%09%09passedData = true;%0D%0A%09%09%09%09%09%09%09%09%09%09%0D%0A%09%09%09%09%7D
+dataHandler
)%0D%0A%09
@@ -3863,26 +3863,27 @@
ect(
-passedData
+dataHandler
).to.be.
true
@@ -3870,36 +3870,38 @@
aHandler).to.be.
-true
+called
;%0D%0A%09%09%09%09%09done();%0D
|
cf52f314eed6afbb9901f6cfa40f245ca2964d55 | Return the super result | addon/utils/reopen-route.js | addon/utils/reopen-route.js | import Ember from 'ember';
import arraySwap from 'ember-redirect/utils/array-swap';
export default function(routeName, options, instance) {
var routeContainerKey = `route:${routeName}`;
var routeObject = instance.container.lookup(routeContainerKey);
if (!routeObject) {
routeObject = Ember.Route.extend({});
instance.registry.register(routeContainerKey, routeObject, { singleton: false });
}
Ember.assert(`Could not find a route named: ${routeName}`, routeObject);
routeObject.reopen({
beforeModel: function(transition) {
var newDynObject = {};
var thisRouteName = this.routeName;
var routeNames = this.router.router.recognizer.names;
var dynSegsOfNextRoute = routeNames[options.redirect].segments.filter(item => item.name).map(item => item.name);
var dynSegsOfThisRoute = routeNames[thisRouteName].segments.filter(item => item.name).map(item => item.name);
// Make sure we only try to make a redirect at the most nested
// route and not a parent resource.
if(this.routeName !== transition.targetName) {
return false;
}
// Make sure that the lengths are the same else we are trying to transition to a route that needs more
// segments then we can supply.
if(dynSegsOfNextRoute.length <= dynSegsOfThisRoute.length) {
dynSegsOfNextRoute.forEach(function(item, index) {
// This means that we have the same dynamic segment on both this and the next route so we will pair them together.
if(dynSegsOfThisRoute.indexOf(dynSegsOfNextRoute[index]) !== -1) {
newDynObject[dynSegsOfNextRoute[index]] = transition.params[thisRouteName][dynSegsOfNextRoute[index]];
dynSegsOfThisRoute = arraySwap(dynSegsOfThisRoute, index, dynSegsOfThisRoute.indexOf(dynSegsOfNextRoute[index]));
}
else {
newDynObject[dynSegsOfNextRoute[index]] = transition.params[thisRouteName][dynSegsOfThisRoute[index]];
}
});
this.replaceWith(transition.router.recognizer.generate(options.redirect, newDynObject));
}
this._super.apply(this, arguments);
}
});
return routeObject;
}
| JavaScript | 0.999992 | @@ -2124,24 +2124,31 @@
%7D%0A%0A
+return
this._super.
|
f9604c0b2093c08894faae2fc3bf628760d3ef44 | use Array.from | src/client/updaters/tag.js | src/client/updaters/tag.js | // borrow the slice method
const toArray = Function.prototype.call.bind(Array.prototype.slice)
/**
* Updates meta tags inside <head> and <body> on the client. Borrowed from `react-helmet`:
* https://github.com/nfl/react-helmet/blob/004d448f8de5f823d10f838b02317521180f34da/src/Helmet.js#L195-L245
*
* @param {('meta'|'base'|'link'|'style'|'script'|'noscript')} type - the name of the tag
* @param {(Array<Object>|Object)} tags - an array of tag objects or a single object in case of base
* @return {Object} - a representation of what tags changed
*/
export default function updateTag({ attribute, tagIDKeyName } = {}, type, tags, headTag, bodyTag) {
const oldHeadTags = toArray(headTag.querySelectorAll(`${type}[${attribute}]`))
const oldBodyTags = toArray(bodyTag.querySelectorAll(`${type}[${attribute}][data-body="true"]`))
const newTags = []
if (tags.length > 1) {
// remove duplicates that could have been found by merging tags
// which include a mixin with metaInfo and that mixin is used
// by multiple components on the same page
const found = []
tags = tags.filter((x) => {
const k = JSON.stringify(x)
const res = !found.includes(k)
found.push(k)
return res
})
}
if (tags && tags.length) {
tags.forEach((tag) => {
const newElement = document.createElement(type)
newElement.setAttribute(attribute, 'true')
const oldTags = tag.body !== true ? oldHeadTags : oldBodyTags
for (const attr in tag) {
if (tag.hasOwnProperty(attr)) {
if (attr === 'innerHTML') {
newElement.innerHTML = tag.innerHTML
} else if (attr === 'cssText') {
if (newElement.styleSheet) {
newElement.styleSheet.cssText = tag.cssText
} else {
newElement.appendChild(document.createTextNode(tag.cssText))
}
} else if ([tagIDKeyName, 'body'].includes(attr)) {
const _attr = `data-${attr}`
const value = (typeof tag[attr] === 'undefined') ? '' : tag[attr]
newElement.setAttribute(_attr, value)
} else {
const value = (typeof tag[attr] === 'undefined') ? '' : tag[attr]
newElement.setAttribute(attr, value)
}
}
}
// Remove a duplicate tag from domTagstoRemove, so it isn't cleared.
let indexToDelete
const hasEqualElement = oldTags.some((existingTag, index) => {
indexToDelete = index
return newElement.isEqualNode(existingTag)
})
if (hasEqualElement && (indexToDelete || indexToDelete === 0)) {
oldTags.splice(indexToDelete, 1)
} else {
newTags.push(newElement)
}
})
}
const oldTags = oldHeadTags.concat(oldBodyTags)
oldTags.forEach(tag => tag.parentNode.removeChild(tag))
newTags.forEach((tag) => {
if (tag.getAttribute('data-body') === 'true') {
bodyTag.appendChild(tag)
} else {
headTag.appendChild(tag)
}
})
return { oldTags, newTags }
}
| JavaScript | 0.000032 | @@ -1,100 +1,4 @@
-// borrow the slice method%0Aconst toArray = Function.prototype.call.bind(Array.prototype.slice)%0A%0A
/**%0A
@@ -579,23 +579,26 @@
dTags =
-to
Array
+.from
(headTag
@@ -667,15 +667,18 @@
s =
-to
Array
+.from
(bod
|
54dcc32f568f18cfa6d089009414b8c5a4ae3d11 | Remove unecessary parenthesis | lib/queryBuilder/operations/InsertOperation.js | lib/queryBuilder/operations/InsertOperation.js | 'use strict';
const { QueryBuilderOperation } = require('./QueryBuilderOperation');
const { StaticHookArguments } = require('../StaticHookArguments');
const { after, mapAfterAllReturn } = require('../../utils/promiseUtils');
const { isPostgres, isSqlite, isMySql, isMsSql } = require('../../utils/knexUtils');
const { isObject } = require('../../utils/objectUtils');
// Base class for all insert operations.
class InsertOperation extends QueryBuilderOperation {
constructor(name, opt) {
super(name, opt);
this.models = null;
this.isArray = false;
this.modelOptions = Object.assign({}, this.opt.modelOptions || {});
}
onAdd(builder, args) {
const json = args[0];
const modelClass = builder.modelClass();
this.isArray = Array.isArray(json);
this.models = modelClass.ensureModelArray(json, this.modelOptions);
return true;
}
async onBefore2(builder, result) {
if (this.models.length > 1 && (!isPostgres(builder.knex()) && !isMsSql(builder.knex()))) {
throw new Error('batch insert only works with Postgresql and SQL Server');
} else {
await callBeforeInsert(builder, this.models);
return result;
}
}
onBuildKnex(knexBuilder, builder) {
if (!isSqlite(builder.knex()) && !isMySql(builder.knex()) && !builder.has(/returning/)) {
// If the user hasn't specified a `returning` clause, we make sure
// that at least the identifier is returned.
knexBuilder.returning(builder.modelClass().getIdColumn());
}
knexBuilder.insert(this.models.map(model => model.$toDatabaseJson(builder)));
}
onAfter1(_, ret) {
if (!Array.isArray(ret) || !ret.length || ret === this.models) {
// Early exit if there is nothing to do.
return this.models;
}
if (isObject(ret[0])) {
// If the user specified a `returning` clause the result may be an array of objects.
// Merge all values of the objects to our models.
for (let i = 0, l = this.models.length; i < l; ++i) {
this.models[i].$set(ret[i]);
}
} else {
// If the return value is not an array of objects, we assume it is an array of identifiers.
for (let i = 0, l = this.models.length; i < l; ++i) {
const model = this.models[i];
// Don't set the id if the model already has one. MySQL and Sqlite don't return the correct
// primary key value if the id is not generated in db, but given explicitly.
if (!model.$id()) {
model.$id(ret[i]);
}
}
}
return this.models;
}
onAfter2(builder, models) {
const result = this.isArray ? models : models[0] || null;
return callAfterInsert(builder, this.models, result);
}
clone() {
const clone = super.clone();
clone.models = this.models;
clone.isArray = this.isArray;
return clone;
}
}
function callBeforeInsert(builder, models) {
const maybePromise = callInstanceBeforeInsert(builder, models);
return after(maybePromise, () => callStaticBeforeInsert(builder));
}
function callInstanceBeforeInsert(builder, models) {
return mapAfterAllReturn(models, model => model.$beforeInsert(builder.context()), models);
}
function callStaticBeforeInsert(builder) {
const args = StaticHookArguments.create({ builder });
return builder.modelClass().beforeInsert(args);
}
function callAfterInsert(builder, models, result) {
const maybePromise = callInstanceAfterInsert(builder, models);
return after(maybePromise, () => callStaticAfterInsert(builder, result));
}
function callInstanceAfterInsert(builder, models) {
return mapAfterAllReturn(models, model => model.$afterInsert(builder.context()), models);
}
function callStaticAfterInsert(builder, result) {
const args = StaticHookArguments.create({ builder, result });
const maybePromise = builder.modelClass().afterInsert(args);
return after(maybePromise, maybeResult => {
if (maybeResult === undefined) {
return result;
} else {
return maybeResult;
}
});
}
module.exports = {
InsertOperation
};
| JavaScript | 0.999999 | @@ -937,17 +937,16 @@
%3E 1 &&
-(
!isPostg
@@ -993,17 +993,16 @@
knex()))
-)
%7B%0A
|
51a6250bebf1200e2b38d21c5655333540543bb8 | add more size styles to icons | addon/components/paper-icon.js | addon/components/paper-icon.js | /**
* @module ember-paper
*/
import Ember from 'ember';
import layout from '../templates/components/paper-icon';
import ColorMixin from 'ember-paper/mixins/color-mixin';
const { Component, computed, String: Str } = Ember;
/**
* @class PaperIcon
* @extends Ember.Component
* @uses ColorMixin
*/
let PaperIconComponent = Component.extend(ColorMixin, {
layout,
tagName: 'md-icon',
classNames: ['paper-icon', 'md-font', 'material-icons', 'md-default-theme'],
classNameBindings: ['spinClass'],
attributeBindings: ['aria-label', 'title', 'sizeStyle:style', 'iconClass:md-font-icon'],
icon: '',
spin: false,
reverseSpin: false,
iconClass: computed('icon', 'positionalIcon', function() {
let icon = this.getWithDefault('positionalIcon', this.get('icon'));
return icon;
}),
'aria-label': computed.reads('iconClass'),
spinClass: computed('spin', 'reverseSpin', function() {
if (this.get('spin')) {
return 'md-spin';
} else if (this.get('reverseSpin')) {
return 'md-spin-reverse';
}
}),
sizeStyle: computed('size', function() {
let size = this.get('size');
if (size) {
return Str.htmlSafe(`height: ${size}px; font-size: ${size}px;`);
}
})
});
PaperIconComponent.reopenClass({
positionalParams: ['positionalIcon']
});
export default PaperIconComponent;
| JavaScript | 0 | @@ -1183,17 +1183,86 @@
px;
-font-size
+min-height: $%7Bsize%7Dpx; min-width: $%7Bsize%7Dpx; font-size: $%7Bsize%7Dpx; line-height
: $%7B
|
dbd2879eda90a6b750b8d28de65c9b6f7957aefb | use tokenAssert | lib/rules/require-spaces-in-call-expression.js | lib/rules/require-spaces-in-call-expression.js | /**
* Requires space before `()` in call expressions.
*
* Type: `Boolean`
*
* Values: `true`
*
* #### Example
*
* ```js
* "requireSpacesInCallExpression": true
* ```
*
* ##### Valid
*
* ```js
* var x = foobar ();
* ```
*
* ##### Invalid
*
* ```js
* var x = foobar();
* ```
*/
var assert = require('assert');
module.exports = function() {};
module.exports.prototype = {
configure: function(requireSpacesInCallExpression) {
assert(
requireSpacesInCallExpression === true,
'requireSpacesInCallExpression option requires true value or should be removed'
);
},
getOptionName: function() {
return 'requireSpacesInCallExpression';
},
check: function(file, errors) {
var tokens = file.getTokens();
file.iterateNodesByType('CallExpression', function(node) {
var nodeBeforeRoundBrace = node;
if (node.callee) {
nodeBeforeRoundBrace = node.callee;
}
var roundBraceToken = file.getTokenByRangeStart(nodeBeforeRoundBrace.range[0]);
do {
roundBraceToken = file.findNextToken(roundBraceToken, 'Punctuator', '(');
} while (roundBraceToken.range[0] < nodeBeforeRoundBrace.range[1]);
var functionEndToken = file.getPrevToken(roundBraceToken);
if (roundBraceToken.value === '(' && functionEndToken.range[1] === roundBraceToken.range[0]) {
errors.add(
'Missing space before opening round brace',
roundBraceToken.loc.start
);
}
});
}
};
| JavaScript | 0 | @@ -876,259 +876,77 @@
var
-nodeBeforeRoundBrace = node;%0A if (node.callee) %7B%0A nodeBeforeRoundBrace = node.callee;%0A %7D%0A%0A var roundBraceToken = file.getTokenByRangeStart(nodeBeforeRoundBrace.range%5B0%5D);%0A do %7B%0A
+lastCalleeToken = file.getLastNodeToken(node.callee);%0A var
rou
@@ -975,33 +975,33 @@
ndNextToken(
-roundBrac
+lastCalle
eToken, 'Pun
@@ -1016,16 +1016,17 @@
, '(');%0A
+%0A
@@ -1033,111 +1033,64 @@
-%7D while (roundBraceToken.range%5B0%5D %3C nodeBeforeRoundBrace.range%5B1%5D);%0A%0A var functionEndT
+errors.assert.whitespaceBetween(%7B%0A t
oken
- =
+:
fil
@@ -1120,18 +1120,17 @@
ceToken)
-;%0A
+,
%0A
@@ -1138,74 +1138,22 @@
-if (roundBraceToken.value === '(' && functionEndToken.range%5B1%5D ===
+ nextToken:
rou
@@ -1168,20 +1168,9 @@
oken
-.range%5B0%5D) %7B
+,
%0A
@@ -1186,39 +1186,16 @@
-errors.add(%0A
+message:
'Mi
@@ -1233,17 +1233,16 @@
d brace'
-,
%0A
@@ -1250,74 +1250,11 @@
- roundBraceToken.loc.start%0A );%0A %7D
+%7D);
%0A
|
00f592335860e21ede6df3bab11df3e7522b5cb3 | Replace null values with empty strings | src/js/cilantro/ui/charts/dist.js | src/js/cilantro/ui/charts/dist.js | /* global define */
define([
'jquery',
'underscore',
'../base',
'./core',
'./utils'
], function($, _, base, charts, utils) {
var ChartLoading = base.LoadView.extend({
message: 'Chart loading...'
});
var FieldChart = charts.Chart.extend({
template: 'charts/chart',
loadView: ChartLoading,
ui: {
chart: '.chart',
heading: '.heading',
status: '.heading .status'
},
initialize: function() {
_.bindAll(this, 'chartClick', 'setValue');
},
showLoadView: function () {
var view = new this.loadView();
view.render();
this.ui.chart.html(view.el);
},
chartClick: function(event) {
event.point.select(!event.point.selected, true);
this.change();
},
interactive: function(options) {
var type;
if (options.chart) {
type = options.chart.type;
}
if (type === 'pie' || (type === 'column' && options.xAxis.categories)) {
return true;
}
return false;
},
getChartOptions: function(resp) {
var options = utils.processResponse(resp, [this.model]);
if (options.clustered) {
this.ui.status.text('Clustered').show();
}
else {
this.ui.status.hide();
}
if (this.interactive(options)) {
this.setOptions('plotOptions.series.events.click', this.chartClick);
}
$.extend(true, options, this.chartOptions);
options.chart.renderTo = this.ui.chart[0];
return options;
},
getField: function() {
return this.model.id;
},
getValue: function() {
return _.pluck(this.chart.getSelectedPoints(), 'category');
},
getOperator: function() {
return 'in';
},
removeChart: function() {
charts.Chart.prototype.removeChart.apply(this, arguments);
if (this.node) {
this.node.destroy();
}
},
onRender: function() {
// Explicitly set the width of the chart so Highcharts knows
// how to fill out the space. Otherwise if this element is
// not in the DOM by the time the distribution request is finished,
// the chart will default to an arbitary size.
if (this.options.parentView) {
this.ui.chart.width(this.options.parentView.$el.width());
}
this.showLoadView();
var _this = this;
this.model.distribution(function(resp) {
if (_this.isClosed) return;
// Convert it into the structure the chart renderer expects
var data = _.map(resp, function(item) {
return {
count: item.count,
values: [{
label: item.label,
value: item.value
}]
};
});
data = _.sortBy(data, function(item) {
return item.values[0];
});
var options = _this.getChartOptions({
clustered: false,
data: data,
outliers: null,
size: data.length
});
if (data.length) {
_this.renderChart(options);
}
else {
_this.showEmptyView(options);
}
});
},
setValue: function(value) {
if (!_.isArray(value)) value = [];
if (this.chart !== null) {
var points = this.chart.series[0].points,
point,
select;
for (var i = 0; i < points.length; i++) {
point = points[i];
select = false;
if (point.name !== null || value.indexOf(point.category) !== -1) {
select = true;
}
point.select(select, true);
}
}
}
});
return {
FieldChart: FieldChart
};
});
| JavaScript | 0 | @@ -2924,16 +2924,223 @@
expects
+.%0A // Since highcharts has odd behavior when encountering nul%60%0A // we replace null values with empty strings to make the%0A // highcharts behavior more predictable.
%0A
@@ -3387,16 +3387,43 @@
em.value
+ === null ? '' : item.value
%0A
|
cf087c401e6fce81c8b5538cac3efc09acaa0348 | Replace accidental beans access with direct access of internal property. | src/color/GradientColor.js | src/color/GradientColor.js | /*
* Paper.js
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
* http://paperjs.org/
* http://scriptographer.org/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* All rights reserved.
*/
var GradientColor = this.GradientColor = Color.extend({
beans: true,
initialize: function(gradient, origin, destination, hilite) {
this.gradient = gradient || new Gradient();
this.setOrigin(origin);
this.setDestination(destination);
if (hilite)
this.setHilite(hilite);
},
getOrigin: function() {
return this._origin;
},
setOrigin: function(origin) {
// PORT: add clone to Scriptographer
origin = Point.read(arguments).clone();
this._origin = origin;
if (this._destination)
this._radius = this._destination.getDistance(this._origin);
return this;
},
getDestination: function() {
return this._destination;
},
setDestination: function(destination) {
// PORT: add clone to Scriptographer
destination = Point.read(arguments).clone();
this._destination = destination;
this._radius = this._destination.getDistance(this._origin);
return this;
},
getHilite: function() {
return this._hilite;
},
setHilite: function(hilite) {
// PORT: add clone to Scriptographer
hilite = Point.read(arguments).clone();
var vector = hilite.subtract(this._origin);
if (vector.getLength() > this._radius) {
this._hilite = this._origin.add(vector.normalize(
this._radius - 0.1));
} else {
this._hilite = hilite;
}
return this;
},
getCanvasStyle: function(ctx) {
var gradient;
if (this.gradient.type === 'linear') {
gradient = ctx.createLinearGradient(this._origin.x, this._origin.y,
this.destination.x, this.destination.y);
} else {
var origin = this._hilite || this._origin;
gradient = ctx.createRadialGradient(origin.x, origin.y,
0, this._origin.x, this._origin.y, this._radius);
}
for (var i = 0, l = this.gradient._stops.length; i < l; i++) {
var stop = this.gradient._stops[i];
gradient.addColorStop(stop._rampPoint, stop._color.toCssString());
}
return gradient;
},
/**
* Checks if the component color values of the color are the
* same as those of the supplied one.
*
* @param obj the GrayColor to compare with
* @return true if the GrayColor is the same, false otherwise.
*/
equals: function(color) {
return color == this || color && color._colorType === this._colorType
&& this.gradient.equals(color.gradient)
&& this._origin.equals(color._origin)
&& this._destination.equals(color._destination);
},
transform: function(matrix) {
matrix._transformPoint(this._origin, this._origin, true);
matrix._transformPoint(this._destination, this._destination, true);
if (this._hilite)
matrix._transformPoint(this._hilite, this._hilite, true);
this._radius = this._destination.getDistance(this._origin);
}
});
| JavaScript | 0 | @@ -1874,24 +1874,25 @@
,%0A%09%09%09%09%09this.
+_
destination.
@@ -1899,16 +1899,17 @@
x, this.
+_
destinat
|
11e13948867f777544fefecf94a466e231a9565b | update gesture conditional | src/platform.js | src/platform.js | require('enyo');
var utils = require('./utils');
/**
* Determines OS versions of platforms that need special treatment. Can have one of the following
* properties:
*
* * android
* * androidChrome (Chrome on Android, standard starting in 4.1)
* * androidFirefox
* * ie
* * edge
* * ios
* * webos
* * windowsPhone
* * blackberry
* * tizen
* * safari (desktop version)
* * chrome (desktop version)
* * firefox (desktop version)
* * firefoxOS
*
* If the property is defined, its value will be the major version number of the platform.
*
* Example:
* ```javascript
* // android 2 does not have 3d css
* if (enyo.platform.android < 3) {
* t = 'translate(30px, 50px)';
* } else {
* t = 'translate3d(30px, 50px, 0)';
* }
* this.applyStyle('-webkit-transform', t);
* ```
*
* @module enyo/platform
*/
exports = module.exports = {
/**
* `true` if the platform has native single-finger [events]{@glossary event}.
* @public
*/
touch: Boolean(('ontouchstart' in window) || window.navigator.msMaxTouchPoints || (window.navigator.msManipulationViewsEnabled && window.navigator.maxTouchPoints)),
/**
* `true` if the platform has native double-finger [events]{@glossary event}.
* @public
*/
gesture: Boolean(('ongesturestart' in window) || ('onmsgesturestart' in window && window.navigator.msMaxTouchPoints && window.navigator.msMaxTouchPoints > 1) || ('onmsgesturestart' in window && window.navigator.maxTouchPoints && window.navigator.maxTouchPoints > 1))
/**
* The name of the platform that was detected or `undefined` if the platform
* was unrecognized. This value is the key name for the major version of the
* platform on the exported object.
* @member {String} platformName
* @public
*/
};
var ua = navigator.userAgent;
var ep = exports;
var platforms = [
// Windows Phone 7 - 10
{platform: 'windowsPhone', regex: /Windows Phone (?:OS )?(\d+)[.\d]+/},
// Android 4+ using Chrome
{platform: 'androidChrome', regex: /Android .* Chrome\/(\d+)[.\d]+/},
// Android 2 - 4
{platform: 'android', regex: /Android(?:\s|\/)(\d+)/},
// Kindle Fire
// Force version to 2, (desktop mode does not list android version)
{platform: 'android', regex: /Silk\/1./, forceVersion: 2, extra: {silk: 1}},
// Kindle Fire HD (Silk versions 2 or 3)
// Force version to 4
{platform: 'android', regex: /Silk\/2./, forceVersion: 4, extra: {silk: 2}},
{platform: 'android', regex: /Silk\/3./, forceVersion: 4, extra: {silk: 3}},
// IE 8 - 10
{platform: 'ie', regex: /MSIE (\d+)/},
// IE 11
{platform: 'ie', regex: /Trident\/.*; rv:(\d+)/},
// Edge
{platform: 'edge', regex: /Edge\/(\d+)/},
// iOS 3 - 5
// Apple likes to make this complicated
{platform: 'ios', regex: /iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/},
// webOS 1 - 3
{platform: 'webos', regex: /(?:web|hpw)OS\/(\d+)/},
// webOS 4 / OpenWebOS
{platform: 'webos', regex: /WebAppManager|Isis|webOS\./, forceVersion: 4},
// Open webOS release LuneOS
{platform: 'webos', regex: /LuneOS/, forceVersion: 4, extra: {luneos: 1}},
// desktop Safari
{platform: 'safari', regex: /Version\/(\d+)[.\d]+\s+Safari/},
// desktop Chrome
{platform: 'chrome', regex: /Chrome\/(\d+)[.\d]+/},
// Firefox on Android
{platform: 'androidFirefox', regex: /Android;.*Firefox\/(\d+)/},
// FirefoxOS
{platform: 'firefoxOS', regex: /Mobile;.*Firefox\/(\d+)/},
// desktop Firefox
{platform: 'firefox', regex: /Firefox\/(\d+)/},
// Blackberry Playbook
{platform: 'blackberry', regex: /PlayBook/i, forceVersion: 2},
// Blackberry 10+
{platform: 'blackberry', regex: /BB1\d;.*Version\/(\d+\.\d+)/},
// Tizen
{platform: 'tizen', regex: /Tizen (\d+)/}
];
for (var i = 0, p, m, v; (p = platforms[i]); i++) {
m = p.regex.exec(ua);
if (m) {
if (p.forceVersion) {
v = p.forceVersion;
} else {
v = Number(m[1]);
}
ep[p.platform] = v;
if (p.extra) {
utils.mixin(ep, p.extra);
}
ep.platformName = p.platform;
break;
}
}
| JavaScript | 0.000001 | @@ -1266,45 +1266,9 @@
&&
-window.navigator.msMaxTouchPoints &&
+(
wind
@@ -1304,80 +1304,11 @@
%3E 1
-)
%7C%7C
- ('onmsgesturestart' in window && window.navigator.maxTouchPoints &&
win
@@ -1341,16 +1341,17 @@
ts %3E 1))
+)
%0A%0A%09/**%0A%09
|
2a8be28cdaf3f3deaa9868c191b864573a93ab1a | Refactor because <Score/> is now a pure function | test/scoreTest.js | test/scoreTest.js | require('./testdom')('<html><body></body></html>');
import { assert } from 'chai';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import Score from '../src/components/score.jsx';
describe('<Score />', function () {
let strength;
let dexterity;
beforeEach(function () {
strength = TestUtils.renderIntoDocument( React.createElement(Score, { score: 18 }, null) );
dexterity = TestUtils.renderIntoDocument( React.createElement(Score, { score: 8 }, null) );
});
it('should return a correct modifier', function () {
assert.strictEqual(' (+4)', strength.setModifier());
assert.strictEqual(' (-1)', dexterity.setModifier(8));
});
});
| JavaScript | 0 | @@ -318,65 +318,14 @@
h =
-TestUtils.renderIntoDocument( React.createElement(
Score
-,
+(
%7B sc
@@ -333,24 +333,16 @@
re: 18 %7D
-, null)
);%0A d
@@ -356,65 +356,14 @@
y =
-TestUtils.renderIntoDocument( React.createElement(
Score
-,
+(
%7B sc
@@ -374,16 +374,8 @@
8 %7D
-, null)
);%0A
@@ -450,110 +450,105 @@
ert.
-strictEqual(' (+4)', strength.setModifier());%0A assert.strictEqual(' (-1)', dexterity.setModifier(8)
+match(strength.props.children, /%5C(%5C+4%5C)$/);%0A assert.match(dexterity.props.children, /%5C(%5C-1%5C)$/
);%0A
@@ -552,13 +552,12 @@
;%0A %7D);%0A
-%0A
%7D);%0A
|
e969e005d03edba9fd74cc50d00e081a97499fef | fix trialsPerBlock bug | src/js/extensions/iat/sequence.js | src/js/extensions/iat/sequence.js | define(['./properties'],function(properties){
/**
* Takes a sequence array and pushes in a block according to the settings in blockObj:
* {
* block: 1,
* part: 1,
* twoRows: false,
* trials: 20
* }
*/
var addBlock = function addBlock(sequenceArr, blockObj){
// push instructions
sequenceArr.push({
data: {block:blockObj.block, part:blockObj.part, IATversion:properties.IATversion, blockStart:true},
inherit: {set:'instructions', type:'byData', data: {block:blockObj.block}}
});
// push block trials
sequenceArr.push({
mixer : 'repeat',
times : !blockObj.twoRows ? blockObj.trials : Math.floor(blockObj.trials/2),
data : !blockObj.twoRows ?
// if we have one row
[
{inherit : {type:'byData', data:{block:blockObj.block}, set:'IAT'}}
]
// if we have two rows
: [
{inherit : {type:'byData', data:{block:blockObj.block,row:1}, set:'IAT'}},
{inherit : {type:'byData', data:{block:blockObj.block,row:2}, set:'IAT'}}
]
});
};
function getTrials(block, defaultTrials){
return typeof properties.trialsPerBlock[block] == 'number' ? properties.trialsPerBlock[block] : defaultTrials;
}
function longIAT(){
var v1 = [], v2 = [];
// build version 1
addBlock(v1,{block:1,part:1,trials:getTrials(1,20),twoRows:false});
addBlock(v1,{block:2,part:2,trials:getTrials(2,20),twoRows:false});
addBlock(v1,{block:3,part:3,trials:getTrials(3,40),twoRows:true});
addBlock(v1,{block:4,part:4,trials:getTrials(4,40),twoRows:true});
addBlock(v1,{block:5,part:5,trials:getTrials(5,40),twoRows:false});
addBlock(v1,{block:6,part:6,trials:getTrials(6,40),twoRows:true});
addBlock(v1,{block:7,part:7,trials:getTrials(7,40),twoRows:true});
// build version 2
addBlock(v2,{block:5,part:1,trials:getTrials(5,20),twoRows:false});
addBlock(v2,{block:2,part:2,trials:getTrials(2,20),twoRows:false});
addBlock(v2,{block:6,part:3,trials:getTrials(6,40),twoRows:true});
addBlock(v2,{block:7,part:4,trials:getTrials(7,40),twoRows:true});
addBlock(v2,{block:1,part:5,trials:getTrials(1,40),twoRows:false});
addBlock(v2,{block:3,part:6,trials:getTrials(3,40),twoRows:true});
addBlock(v2,{block:4,part:7,trials:getTrials(4,40),twoRows:true});
return properties.randomize_order ?
v1
: [
{
mixer: 'choose',
data: [
{mixer:'wrapper',data:v1},
{mixer:'wrapper',data:v2}
]
}
];
}
function shortIAT(){
var v1 = [], v2 = [];
// build version 1
addBlock(v1,{block:1,part:1,trials:getTrials(1,20),twoRows:false});
addBlock(v1,{block:2,part:2,trials:getTrials(2,20),twoRows:false});
addBlock(v1,{block:3,part:3,trials:getTrials(3,50),twoRows:true});
addBlock(v1,{block:5,part:5,trials:getTrials(5,30),twoRows:false});
addBlock(v1,{block:6,part:6,trials:getTrials(6,50),twoRows:true});
// build version 2
addBlock(v2,{block:5,part:1,trials:getTrials(5,20),twoRows:false});
addBlock(v2,{block:2,part:2,trials:getTrials(2,20),twoRows:false});
addBlock(v2,{block:6,part:3,trials:getTrials(6,50),twoRows:true});
addBlock(v2,{block:1,part:5,trials:getTrials(1,30),twoRows:false});
addBlock(v2,{block:3,part:6,trials:getTrials(3,50),twoRows:true});
return properties.randomize_order ?
v1
: [
{
mixer: 'choose',
data: [
{mixer:'wrapper',data:v1},
{mixer:'wrapper',data:v2}
]
}
];
}
return function sequence(){
return properties.IATversion == 'short' ? shortIAT() : longIAT();
};
}); | JavaScript | 0 | @@ -1058,16 +1058,46 @@
%09return
+properties.trialsPerBlock && (
typeof p
@@ -1139,16 +1139,17 @@
'number'
+)
? prope
|
8dde0b388a9aff3101c22d3314199b8fa2221643 | rename layoutNotifications to LayoutNotifications | features/layouts/js/pl-layout-notifications.js | features/layouts/js/pl-layout-notifications.js | (function() {
'use strict';
window.Ractive.controller('pl-layout-notifications', function(component, data, el, config, done) {
data.title = typeof data['text-title'] == 'undefined' ? 'notifications' : data['text-title'];
data.nonotification = typeof data['text-nonotification'] == 'undefined' ? 'No new notification.' : data['text-nonotification'];
data.signoutlabel = typeof data['text-signoutlabel'] == 'undefined' ? 'signout' : data['text-signoutlabel'];
data.emailslabel = typeof data['text-emailslabel'] == 'undefined' ? 'emails' : data['text-emailslabel'];
var _$el = {
body: $('body')
},
layoutNotifications = component({
plName: 'pl-layout-notifications',
data: $.extend(true, {
opened: false,
notifications: [],
emailstoggle: function(event, isOn) {
event.original.stopPropagation();
var emailsToggleFunc = layoutNotifications.get('emails-toggle');
if (emailsToggleFunc) {
emailsToggleFunc(event, isOn);
}
}
}, data),
pushNotification: function(content, time, picture, args) {
var notifications = this.get('notifications');
notifications = notifications || [];
notifications.unshift({
picture: picture,
time: time,
content: content,
args: args || null
});
this.set('notifications', notifications);
},
toggle: function() {
this.set('opened', !this.get('opened'));
this.fire('toggle');
},
open: function() {
this.set('opened', true);
this.fire('toggle');
},
close: function() {
this.set('opened', false);
this.fire('toggle');
},
isToggled: function() {
return this.get('opened');
}
});
if (data.toggle) {
layoutNotifications.on('toggle', function(event) {
data.toggle(event, layoutNotifications.get('opened'));
});
}
if (data.signout) {
layoutNotifications.on('signout', function(event) {
data.signout(event);
event.original.stopPropagation();
});
}
if (data.openitem) {
layoutNotifications.on('openitem', function(event) {
data.openitem(event);
event.original.stopPropagation();
});
}
function _close() {
layoutNotifications.close();
}
layoutNotifications.on('teardown', function() {
_$el.body.unbind('click', _close);
});
_$el.body.click(_close);
layoutNotifications.require().then(done);
});
})();
| JavaScript | 0.000023 | @@ -637,25 +637,25 @@
%7D,%0A
-l
+L
ayoutNotific
@@ -947,17 +947,17 @@
eFunc =
-l
+L
ayoutNot
@@ -2022,33 +2022,33 @@
toggle) %7B%0A
-l
+L
ayoutNotificatio
@@ -2108,17 +2108,17 @@
(event,
-l
+L
ayoutNot
@@ -2183,33 +2183,33 @@
ignout) %7B%0A
-l
+L
ayoutNotificatio
@@ -2354,33 +2354,33 @@
enitem) %7B%0A
-l
+L
ayoutNotificatio
@@ -2530,25 +2530,25 @@
e() %7B%0A
-l
+L
ayoutNotific
@@ -2570,25 +2570,25 @@
%0A %7D%0A%0A
-l
+L
ayoutNotific
@@ -2706,17 +2706,17 @@
);%0A%0A
-l
+L
ayoutNot
|
195a1bdd969101ac14373101ac28e2c3caadb383 | see test fail with message: AssertionError: expected true to be false | server/02-palindrome/palindrome.spec.js | server/02-palindrome/palindrome.spec.js | describe('the palindrome canary spec', () => {
it('shows the infrastructure works', () => {
true.should.be.true();
});
let isPalindrome = () => true;
describe('palindrome should be', () => {
it('true for mom', () => {
isPalindrome('mom').should.be.true();
});
it('false for dude');
it('true for mom mom');
it('false for dad mom');
it('true for whitespaces');
it('error for empty string');
it('error for not a string');
});
});
| JavaScript | 0.999845 | @@ -305,18 +305,80 @@
or dude'
-);
+, () =%3E %7B%0A isPalindrome('dude').should.be.false();%0A %7D);%0A
%0A it(
|
f15096b4280e62b03b113fc71bf1312cddb97f38 | add missong string | src/js/services/onGoingProcess.js | src/js/services/onGoingProcess.js | 'use strict';
angular.module('copayApp.services').factory('ongoingProcess', function($log, $timeout, lodash, $ionicLoading, gettextCatalog, platformInfo) {
var root = {};
var isCordova = platformInfo.isCordova;
var ongoingProcess = {};
var processNames = {
'openingWallet': 'Updating Wallet...',
'updatingStatus': 'Updating Wallet...',
'updatingBalance': 'Updating Wallet...',
'updatingPendingTxps': 'Updating Wallet...',
'scanning': 'Scanning Wallet funds...',
'recreating': 'Recreating Wallet...',
'generatingCSV': 'Generating .csv file...',
'creatingTx': 'Creating transaction',
'sendingTx': 'Sending transaction',
'signingTx': 'Signing transaction',
'broadcastingTx': 'Broadcasting transaction',
'fetchingPayPro': 'Fetching Payment Information',
'calculatingFee': 'Calculating fee',
'joiningWallet': 'Joining Wallet...',
'retrivingInputs': 'Retrieving inputs information',
'creatingWallet': 'Creating Wallet...',
'validationWallet': 'Validating wallet integrity...',
'connectingledger': 'Waiting for Ledger...',
'connectingtrezor': 'Waiting for Trezor...',
'validatingWords': 'Validating recovery phrase...',
'connectingCoinbase': 'Connecting to Coinbase...',
'connectingGlidera': 'Connecting to Glidera...',
'importingWallet': 'Importing Wallet...',
'sweepingWallet': 'Sweeping Wallet...',
'deletingWallet': 'Deleting Wallet...',
};
lodash.each(processNames, function(k, v) {
processNames[k] = gettextCatalog.getString(v);
});
root.clear = function() {
ongoingProcess = {};
};
root.set = function(processName, isOn) {
$log.debug('ongoingProcess', processName, isOn);
root[processName] = isOn;
ongoingProcess[processName] = isOn;
var name;
root.any = lodash.any(ongoingProcess, function(isOn, processName) {
if (isOn)
name = name || processName;
return isOn;
});
// The first one
root.onGoingProcessName = name;
var showName = processNames[name] || gettextCatalog.getString(name);
if (root.onGoingProcessName) {
if (isCordova) {
window.plugins.spinnerDialog.show(null, showName, true);
} else {
$ionicLoading.show({
template: showName,
});
}
} else {
if (isCordova) {
window.plugins.spinnerDialog.hide();
} else {
$ionicLoading.hide();
}
}
};
return root;
});
| JavaScript | 0.999999 | @@ -998,18 +998,18 @@
validati
-o
n
+g
Wallet':
|
283e018334737c5586525f1209e8d23d3a5d985b | update tests | test/sort.spec.js | test/sort.spec.js | import sort from '../src/sort';
import chai from 'chai';
const expect = chai.expect;
const numberArray = [20, 3, 4, 10, -3, 1, 0, 5];
const stringArray = ['Blue', 'Humpback', 'Beluga'];
describe('immutable-sort', () => {
it('original array should stay untouched', () => {
const resultArray = sort(numberArray, (a, b) => a - b);
expect(numberArray).to.not.eql(resultArray);
});
it('sorts numeric array (ascending)', () => {
const resultArray = sort(numberArray, (a, b) => a - b);
expect(resultArray).to.eql([-3, 0, 1, 3, 4, 5, 10, 20]);
});
it('sorts numeric array (descending)', () => {
const resultArray = sort(numberArray, (a, b) => b - a);
expect(resultArray).to.eql([20, 10, 5, 4, 3, 1, 0, -3]);
});
it('sorts string array (without compareFunction) (ascending)', () => {
const resultArray = sort(stringArray);
expect(resultArray).to.eql(['Beluga', 'Blue', 'Humpback']);
});
it('sorts string array (with compareFunction) (descending)', () => {
const resultArray = sort(stringArray, (a, b) => a.toLowerCase() < b.toLowerCase());
expect(resultArray).to.eql(['Humpback', 'Blue', 'Beluga']);
});
});
| JavaScript | 0.000001 | @@ -928,238 +928,8 @@
%7D);
-%0A%0A it('sorts string array (with compareFunction) (descending)', () =%3E %7B%0A const resultArray = sort(stringArray, (a, b) =%3E a.toLowerCase() %3C b.toLowerCase());%0A expect(resultArray).to.eql(%5B'Humpback', 'Blue', 'Beluga'%5D);%0A %7D);
%0A%7D);
|
798f2a49d0ffc3594d90d8c4f43b35f40f33f157 | Upgrade YUI to 3.15.0 | config/yui.js | config/yui.js | 'use strict';
var isProduction = process.env.NODE_ENV === 'production';
exports.version = '3.15.0-rc-1';
exports.config = {
combine: isProduction,
filter : isProduction ? 'min' : 'raw',
root : exports.version + '/',
groups: {
'app': {
combine : isProduction,
comboBase: '/combo/' + require('../package').version + '?',
base : '/',
root : '/',
modules: {
'css-mediaquery': {
path: 'vendor/css-mediaquery.js'
},
'handlebars-runtime': {
path: 'vendor/handlebars.runtime.js'
},
'rework': {
path: 'vendor/rework.js'
},
'rework-pure-grids': {
path: 'vendor/rework-pure-grids.js'
},
'grid-model': {
path: 'js/models/grid-model.js',
requires: [
'model',
'mq-model',
'rework',
'rework-pure-grids',
'querystring'
]
},
'mq-model': {
path: 'js/models/mq-model.js',
requires: [
'model',
'model-list',
'css-mediaquery'
]
},
'grid-tab-view': {
path: 'js/views/grid-tab-view.js',
requires: [
'view',
'node'
]
},
'grid-input-view': {
path: 'js/views/grid-input-view.js',
requires: [
'grid-tab-view',
'event-focus'
]
},
'grid-output-view': {
path: 'js/views/grid-output-view.js',
requires: [
'grid-tab-view'
]
}
}
}
}
};
| JavaScript | 0.000001 | @@ -96,13 +96,8 @@
15.0
--rc-1
';%0A%0A
|
b030156cf3a94ca93c560a2e4b3fa317080ca7cb | Remove spinner before render | app/assets/javascripts/stories/views/StoriesListView.js | app/assets/javascripts/stories/views/StoriesListView.js | /**
* The StoriesKeep view.
*/
define([
'jquery',
'backbone',
'underscore',
'handlebars',
'simplePagination',
'text!stories/templates/storiesList.handlebars',
], function($,Backbone,underscore,Handlebars,simplePagination, storiesTPL) {
'use strict';
var StoriesListView = Backbone.View.extend({
el: '#storiesListView',
model: new (Backbone.Model.extend({
defaults: {
total: null,
perpage: null,
page: null
},
})),
collection: new (Backbone.Collection.extend({
url: '/stayinformed-stories.json',
parse: function(response) {
return _.map(response, function(story){
var img = (! story.media.length) ? null : story.media[story.media.length -1].preview_url;
var detail = (story.details.length > 295) ? story.details.substr(0, 295)+'...' : story.details;
return {
id: story.id,
title: story.title,
details: detail,
link: '/stories/'+story.id,
map: (img) ? 'http://gfw2stories.s3.amazonaws.com/uploads/' + img : 'https://maps.googleapis.com/maps/api/staticmap?center=' + story.lat + ',' + story.lng + '&zoom=2&size=80x80',
}
});
}
})),
template: Handlebars.compile(storiesTPL),
initialize: function() {
if (!this.$el.length) {
return
}
this.cache();
this.listeners();
/**
* Inits
*/
// Init model
this.model.set({
total: this.$storiesPagination.data('total'),
perpage: this.$storiesPagination.data('perpage'),
page: this.$storiesPagination.data('page')
}, { silent: true });
// Init pagination
this.pagination();
},
cache: function() {
this.$htmlbody = $('html, body');
this.$storiesList = $('#storiesList');
this.$storiesSpinner = $('#storiesSpinner');
this.$storiesPagination = $('#storiesPagination');
this.$storiesResetPosition = $('#storiesResetPosition');
},
listeners: function() {
this.model.on('change:page', this.changePage.bind(this));
},
render: function(){
this.$storiesList.html(this.template({ stories : this.collection.toJSON() }));
},
/**
* Listeners
*/
changePage: function() {
this.$htmlbody.animate({ scrollTop: this.$storiesResetPosition.offset().top }, 500);
this.$storiesSpinner.toggleClass('-start', true);
this.collection.fetch({
data: {
for_stay: true,
page: this.model.get('page'),
perpage: this.model.get('perpage')
},
success: function () {
this.render();
}.bind(this),
error: function (e) {
alert(' Service request failure: ' + e);
}.bind(this),
complete: function (e) {
this.$storiesSpinner.toggleClass('-start', false);
}.bind(this)
})
},
/**
* Pagination
*/
pagination: function(){
// We are using simple-pagination plugin
this.$storiesPagination.pagination({
items: this.model.get('total'),
itemsOnPage : this.model.get('perpage'),
currentPage : this.model.get('page'),
displayedPages: 3,
edges: 1,
selectOnClick: false,
prevText: '<svg><use xlink:href="#shape-arrow-left"></use></svg>',
nextText: '<svg><use xlink:href="#shape-arrow-right"></use></svg>',
onPageClick: function(page, e){
e && e.preventDefault();
this.$storiesPagination.pagination('drawPage', page);
this.model.set('page', page);
}.bind(this)
});
},
});
return StoriesListView;
});
| JavaScript | 0 | @@ -2672,127 +2672,76 @@
his.
-render();%0A %7D.bind(this),%0A %0A error: function (e) %7B%0A alert(' Service request failure: ' + e
+$storiesSpinner.toggleClass('-start', false);%0A this.render(
);%0A
@@ -2761,16 +2761,24 @@
(this),%0A
+
%0A
@@ -2782,16 +2782,13 @@
-complete
+error
: fu
@@ -2853,32 +2853,83 @@
start', false);%0A
+ alert(' Service request failure: ' + e);%0A
%7D.bind(t
@@ -2924,32 +2924,42 @@
%7D.bind(this)
+,%0A
%0A %7D)%0A %7D,
|
d1f435ba5e0bcfe9c376abae7ab7bf3e2afe8b16 | Add missing js reference | test/test-main.js | test/test-main.js | var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
allTestFiles.push(file);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
paths: {
'slugify': 'slugify'
},
baseUrl: '/base/app/js',
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
}); | JavaScript | 0.000002 | @@ -336,16 +336,52 @@
slugify'
+,%0A 'calculator': 'calculator'
%0A %7D,%0A
|
0a405b82e358e187fa284d5f50b50a5a6d957e31 | Update location.js | routes/location.js | routes/location.js | var _connection;
exports.connect = function(req, res, next) {
try {
var config = require('../app.config.json');
var mysql = require('mysql');
_connection = mysql.createConnection({
host: config.db.host,
user: config.db.username,
password: config.db.password,
port: config.db.port
});
next();
} catch(e) {
console.log('mysql error', e);
next(e);
}
};
exports.disconnect = function() {
try {
_connection.end();
}
catch (e) {
console.log('Error when attempting to close connection.', e);
}
}
/*
* Find
*/
exports.find = function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
try {
var q = req.params.q;
q = q.toLowerCase();
q = q.replace('å', '?');
q = q.replace('ä', '?');
q = q.replace('ö', '?');
q = q.replace('\'', '');
q = q.replace('"', '');
q = q.replace(';', '');
console.log(q);
q = decodeURIComponent(q);
console.log(q);
var getQuery = 'SELECT * FROM `maxmind`.`locations` WHERE LCASE(`city`) LIKE \'\%' + q + '\%\'';
_connection.query(getQuery, function (err, rows, fields) {
if (err)
throw err;
res.send(rows);
});
}
catch (e) {
res.end("error");
}
finally {
next();
}
};
| JavaScript | 0.000001 | @@ -669,20 +669,35 @@
ion/json
+; charset=utf-8
');%0A
-
res.se
@@ -801,96 +801,8 @@
);%0A%0A
- q = q.replace('%C3%A5', '?');%0A q = q.replace('%C3%A4', '?');%0A q = q.replace('%C3%B6', '?');%0A%0A
@@ -883,36 +883,16 @@
, '');%0A%0A
- console.log(q);%0A
q =
@@ -918,28 +918,12 @@
q);%0A
+
-console.log(q);%0A
%0A
|
f4396a1bd8d1ceb7105d1589e33d1cff8590c202 | Fix call button click handler | src/components/CallArea.js | src/components/CallArea.js | import React from 'react';
import PropTypes from 'prop-types';
import Paper from 'material-ui/Paper';
import styled from 'styled-components';
import { trim } from 'lodash';
import { PhoneNumberUtil } from 'google-libphonenumber';
import { withState, compose, pure, withPropsOnChange, withHandlers, getContext } from 'recompose';
import TextField from 'material-ui/TextField';
import IconButton from 'material-ui/IconButton';
import CallIcon from 'material-ui-icons/Call';
import CallEndIcon from 'material-ui-icons/CallEnd';
import { CALL_STATUS_IDLE, CALL_STATUS_STARTING, CALL_STATUS_ACTIVE } from 'react-sip';
const phoneUtil = PhoneNumberUtil.getInstance();
const conferencePhoneNumber = '3500';
const Wrapper = styled(Paper)`
flex-grow: 1;
display: flex;
padding-top: 80px;
align-items: center;
justify-content: center;
`;
const CallForm = styled.div`
max-width: 600px;
display: flex;
align-items: center;
`;
const ActionButtonWrapper = styled.div`width: 40px;`;
const CallArea = ({
phoneNumber,
phoneNumberIsValid,
phoneNumberIsEmpty,
onPhoneNumberChange,
onPhoneNumberKeyDown,
onStartButtonClick,
onStopButtonClick,
callStatus,
helperText,
}) =>
(<Wrapper>
<CallForm>
<TextField
label={callStatus === CALL_STATUS_IDLE ? 'Who shall we call?' : ' '}
placeholder="e.g. +44 000 000-00-00"
error={!phoneNumberIsEmpty && !phoneNumberIsValid}
helperText={helperText}
value={phoneNumber}
disabled={callStatus !== CALL_STATUS_IDLE}
InputProps={{
onChange: onPhoneNumberChange,
onKeyDown: onPhoneNumberKeyDown,
}}
/>
<ActionButtonWrapper>
{callStatus === CALL_STATUS_IDLE
? <IconButton
color={phoneNumberIsEmpty || !phoneNumberIsValid ? undefined : 'primary'}
disabled={phoneNumberIsEmpty || !phoneNumberIsValid}
onClick={onStartButtonClick}
>
<CallIcon />
</IconButton>
: null}
{callStatus === CALL_STATUS_ACTIVE
? <IconButton color="primary" onClick={onStopButtonClick}>
<CallEndIcon />
</IconButton>
: null}
</ActionButtonWrapper>
</CallForm>
</Wrapper>);
export default compose(
getContext({
sipStart: PropTypes.func,
sipAnswer: PropTypes.func,
sipStop: PropTypes.func,
callStatus: PropTypes.string,
}),
withState('phoneNumber', 'setPhoneNumber', conferencePhoneNumber),
withPropsOnChange(['phoneNumber'], ({ phoneNumber }) => {
const phoneNumberIsEmpty = trim(phoneNumber) === '';
let phoneNumberIsValid = false;
if (phoneNumber.replace(/\s/g, '') === conferencePhoneNumber) {
phoneNumberIsValid = true;
} else if (!phoneNumberIsEmpty) {
try {
const phoneNumberProto = phoneUtil.parse(phoneNumber, 'UK');
phoneNumberIsValid = phoneUtil.isValidNumber(phoneNumberProto);
} catch (e) {
/* eslint-disable-line no-empty */
}
}
return {
phoneNumberIsValid,
phoneNumberIsEmpty,
};
}),
withPropsOnChange(['callStatus'], ({ callStatus }) => {
let helperText = ' ';
if (callStatus === CALL_STATUS_STARTING) {
helperText = 'dialing...';
}
if (callStatus === CALL_STATUS_ACTIVE) {
helperText = 'on air!';
}
return {
helperText,
};
}),
withHandlers({
onPhoneNumberChange: ({ setPhoneNumber }) => (e) => {
setPhoneNumber(e.target.value);
},
onPhoneNumberKeyDown: ({ callStatus, phoneNumberIsValid, phoneNumber, sipStart }) => (e) => {
if (e.which === 13) {
// enter
if (callStatus === CALL_STATUS_IDLE && phoneNumberIsValid) {
sipStart(phoneNumber);
}
}
},
onStopButtonClick: ({ sipStop, callStatus }) => () => {
if (callStatus === CALL_STATUS_ACTIVE) {
sipStop();
}
},
}),
pure,
)(CallArea);
| JavaScript | 0.000002 | @@ -3772,24 +3772,232 @@
%7D%0A %7D,%0A
+ onStartButtonClick: (%7B sipStart, callStatus, phoneNumberIsValid, phoneNumber %7D) =%3E () =%3E %7B%0A if (callStatus === CALL_STATUS_IDLE && phoneNumberIsValid) %7B%0A sipStart(phoneNumber);%0A %7D%0A %7D,%0A
onStopBu
|
3d7d29aa854ac8358b0abba039b518817486a9bc | fix calltoaction json | src/messaging-manager.js | src/messaging-manager.js | 'use strict';
const graphApi = require('./graph-api');
const POKEMON = require('../db/pokemon');
function receivedMessage(event) {
const senderId = event.sender.id;
const recipientId = event.recipient.id;
const timeOfMessage = event.timestamp;
const message = event.message;
console.log('Received message for user %d and page %d at %d with message:', senderId, recipientId, timeOfMessage);
console.log(JSON.stringify(message));
const messageId = message.mid;
const messageText = message.text;
const messageAttachments = message.attachments;
if (messageText) {
// check if messageText matches any pokemon
if (Object.keys(POKEMON).indexOf(messageText.toUpperCase()) !== -1) {
// TODO check for length
sendPokemonDetail(senderId, messageText.toUpperCase());
} else if (messageText.toUpperCase() === 'HI') {
sendIntroductionMessage(senderId);
} else {
sendTextMessage(senderId, `Didn't find anything about ${messageText}. 😞`);
}
}
}
/**
* sends a basic message to a specific recipient.
*
* @param string recipientId
* @param string messageText
* @return Promise
*/
function sendTextMessage(recipientId, messageText) {
const messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
},
};
return graphApi.callSendAPI(messageData);
}
function sendPokemonDetail(recipientId, pokemonName) {
const pokemon = POKEMON[pokemonName.toUpperCase()];
const message = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: [
{
title: `${pokemon.name} (#00${pokemon['#']})`,
image_url: 'https://lh3.googleusercontent.com/-Ygm1wuBzWL4/Vy1Qcix3LDI/AAAAAAAAGP0/uTg0CfxsGI4Y1okeCL7ZPLaZgZbvN5zpwCCo/s300/Screen%2Bshot%2B2016-05-06%2Bat%2B10.14.42%2BPM.png?refresh=900&resize_h=NaN&resize_w=NaN',
subtitle: `Types: ${pokemon.types.join(', ')}
Height: ${pokemon.height}
Weight: ${pokemon.weight}`
}
]
}
}
}
};
}
/**
* send first time users an introduction.
*
* @param object messagingEvent
*/
function sendIntroductionMessage(recipientId) {
const introduction = {
recipient: {
id: recipientId
},
message: require('../messages/introduction.json')
};
const callToAction = {
recipient: {
id: recipientId
},
message: require('../messages/introduction.json')
};
graphApi.callSendAPI(introduction)
.then(() => graphApi.callSendAPI(callToAction));
}
module.exports = {
receivedMessage,
sendIntroductionMessage,
};
| JavaScript | 0.000003 | @@ -2362,39 +2362,41 @@
re('../messages/
-introdu
+call-to-a
ction.json')%0A%09%7D;
|
28a79e50317415e751f290f60007aa0ae3b0548b | Bump kMaxLength to 512x1024 | src/main/javascript/nodyn/bindings/smalloc.js | src/main/javascript/nodyn/bindings/smalloc.js | /*
* Copyright 2014 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.alloc = function(obj, len, type) {
return io.nodyn.smalloc.Smalloc.alloc(obj, len);
}
module.exports.truncate = function(obj, len) {
return io.nodyn.smalloc.Smalloc.truncate(obj, len);
}
module.exports.sliceOnto = function(src, dest, start, end) {
return io.nodyn.smalloc.Smalloc.sliceOnto(src, dest, start, end);
}
module.exports.kMaxLength = 128 * 1024;
| JavaScript | 0.000004 | @@ -686,32 +686,33 @@
loc(obj, len);%0A%7D
+;
%0A%0Amodule.exports
@@ -795,24 +795,25 @@
obj, len);%0A%7D
+;
%0A%0Amodule.exp
@@ -932,16 +932,17 @@
end);%0A%7D
+;
%0A%0Amodule
@@ -967,11 +967,11 @@
h =
+5
12
-8
* 1
|
cbad95003d20cabe55df11d88491087403be23fa | Update tests to use playerHasCandidate from previous refactor of game.js | test/test.game.js | test/test.game.js | var assert = require('assert');
var m = require('mori');
var game = require('./../game.js');
describe('getInitialState', function(){
it('should return a mori hashMap', function(){
assert(m.isMap(game.getInitialState()));
});
it('should have a deck with 81 cards and a toDeal with 81 shuffled integers', function(){
var state = game.getInitialState();
var toDeal = m.get(state, 'toDeal');
var deck = m.get(state, 'deck')
assert.equal(m.count(toDeal), 81);
assert.equal(m.nth(toDeal,0)===0, false);
assert.equal(m.count(deck), 81);
assert(m.hasKey(m.nth(deck,0), "color"));
});
it('should have a players map', function(){
var state = game.getInitialState();
assert(m.hasKey(state, 'players'));
assert(m.isMap(m.get(state, 'players')));
});
});
describe('addPlayer', function(){
it('should add the name to the players hashMap', function(){
var state0 = game.getInitialState();
var state1 = game.addPlayer('Anjana', state0);
assert(m.hasKey(m.get(state1, 'players'), 'Anjana'));
});
it('should associate the name in players with a proper hashMap', function(){
var state0 = game.getInitialState();
var state1 = game.addPlayer('Anjana', state0);
var playerMap = m.getIn(state1, ['players', 'Anjana']);
assert(m.isMap(playerMap));
assert(m.hasKey(playerMap, 'score'));
assert(m.hasKey(playerMap, 'claimed'));
assert.equal(m.get(playerMap, 'score'), 0);
assert.equal(m.get(playerMap, 'claimed'), m.set());
});
});
describe('removePlayer', function(){
it('should remove the name from the players hashMap', function(){
var state0 = game.getInitialState();
var added = game.addPlayer('Anjana', state0);
var removed = game.removePlayer('Anjana', added);
assert.equal(m.hasKey(m.get(removed, 'players')), false);
});
});
describe('claimCard', function(){
it('should add the card object to the players.player.claimed set', function(){
var state = game.addPlayer('Anjana', game.getInitialState());
var claimedState = game.claimCard('Anjana', 3, state);
var claimed = m.getIn(claimedState, ['players', 'Anjana', 'claimed']);
assert.equal(m.count(claimed), 1);
assert(m.hasKey(m.first(claimed), 'color'));
assert(m.equals(m.first(claimed), m.nth(m.get(claimedState, 'deck'), 3)));
});
});
describe('playerHasSet', function() {
it('should return null if player has less than 3 claimed cards', function(){
var state = game.addPlayer('Anjana', game.getInitialState());
assert.equal(game.playerHasSet('Anjana', state), null);
});
it('should return boolean if player has 3 cards', function(){
var state = game.addPlayer('Anjana', game.getInitialState());
var claimedState = game.claimCard('Anjana', 1, game.claimCard('Anjana', 2, game.claimCard('Anjana', 3, state)));
assert.equal(typeof(game.playerHasSet('Anjana', claimedState)), 'boolean');
});
});
| JavaScript | 0 | @@ -2506,30 +2506,923 @@
rHas
-Set', function() %7B%0A
+Candidate', function() %7B%0A var state;%0A beforeEach(function() %7B%0A state = game.addPlayer('Leia', game.addPlayer('Luke', game.getInitialState()));%0A %7D);%0A%0A it('should return true if player has 3 claimed cards', function() %7B%0A var claimedState = game.claimCard('Leia', 1, game.claimCard('Leia', 2, game.claimCard('Leia', 3, state)));%0A assert(game.playerHasCandidate('Leia', claimedState));%0A %7D);%0A%0A it('should return false if player has more or less than 3 cards', function() %7B%0A var claimedState = game.claimCard('Leia', 1, game.claimCard('Leia', 2, game.claimCard('Leia', 3, game.claimCard('Leia', 4, state))));%0A claimedState = game.claimCard('Luke', 1, state);%0A assert.equal(game.playerHasCandidate('Leia', claimedState), false);%0A assert.equal(game.playerHasCandidate('Luke', claimedState), false);%0A %7D);%0A%7D);%0A%0Adescribe('playerHasSet', function() %7B%0A //
it(
@@ -3491,36 +3491,39 @@
function()%7B%0A
+//
+
var state = game
@@ -3567,24 +3567,27 @@
tate());%0A
+ //
assert.
@@ -3634,24 +3634,27 @@
, null);%0A
+ //
%7D);%0A it(
|
de501e5fc4df8f92d7be5d8d39f309335e95faab | Remove surplus global navigation logic | src/middleware/locals.js | src/middleware/locals.js | const path = require('path')
const logger = require('../../config/logger')
const config = require('../../config')
let webpackManifest = {}
try {
webpackManifest = require(`${config.buildDir}/manifest.json`)
} catch (err) {
logger.error('Manifest file is not found. Ensure assets are built.')
}
const globalNavItems = [
{ path: '/companies', label: 'Companies' },
{ path: '/contacts', label: 'Contacts' },
{ path: '/investment-projects', label: 'Investment projects' },
{ path: '/omis', label: 'OMIS Orders' },
]
module.exports = function locals (req, res, next) {
const baseUrl = `${(req.encrypted ? 'https' : req.protocol)}://${req.get('host')}`
const breadcrumbItems = res.breadcrumb()
res.locals = Object.assign({}, res.locals, {
BASE_URL: baseUrl,
CANONICAL_URL: baseUrl + req.originalUrl,
CURRENT_PATH: req.path,
GOOGLE_TAG_MANAGER_KEY: config.googleTagManagerKey,
BREADCRUMBS: breadcrumbItems,
IS_XHR: req.xhr,
QUERY: req.query,
GLOBAL_NAV_ITEMS: globalNavItems.map(item => {
const url = path.resolve(req.baseUrl, item.path)
let isActive
if (url === '/') {
isActive = req.path === '/'
} else {
isActive = req.path.startsWith(url)
}
return Object.assign(item, {
url,
isActive,
})
}),
getMessages () {
return req.flash()
},
getPageTitle () {
const items = breadcrumbItems.map(item => item.name)
const title = res.locals.title
if (title) {
if (items.length === 1) {
return [title]
}
items.pop()
items.push(title)
}
return items.reverse().slice(0, -1)
},
getAssetPath (asset) {
const assetsUrl = config.assetsHost || baseUrl
const webpackAssetPath = webpackManifest[asset]
if (webpackAssetPath) {
return `${assetsUrl}/${webpackAssetPath}`
}
return `${assetsUrl}/${asset}`
},
getLocal (key) {
return res.locals[key]
},
translate (key) {
return req.translate(key)
},
})
next()
}
| JavaScript | 0 | @@ -1089,103 +1089,56 @@
th)%0A
+%0A
-let isActive%0A%0A if (url === '/') %7B%0A isActive = req.path === '/'%0A %7D else %7B
+return Object.assign(item, %7B%0A url,
%0A
@@ -1150,18 +1150,17 @@
isActive
- =
+:
req.pat
@@ -1180,82 +1180,8 @@
url)
-%0A %7D%0A%0A return Object.assign(item, %7B%0A url,%0A isActive
,%0A
|
5480b68c35ca3c912f98951532541b71232a91ec | add validator | src/middlewares/index.js | src/middlewares/index.js | import morgan from 'morgan'
import compression from 'compression'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import session from 'express-session'
import Redis from 'ioredis'
import connectRedis from 'connect-redis'
import flash from 'express-flash'
import cors from 'cors'
import helmet from 'helmet'
import methodOverride from 'method-override'
import passport from 'passport'
import { compose } from 'compose-middleware'
import expressWinston from 'express-winston'
import config from '../config'
import winstonInstance from '../config/logger'
const RedisStore = connectRedis(session)
const redis = new Redis(config.redis.port, config.redis.host)
const sessionConfig = { ...config.session, store: new RedisStore({ client: redis }) }
const logger = (config.env === 'development')
? () => morgan('dev')
: () => expressWinston.logger({ winstonInstance })
const middlewares = [
logger(),
compression(),
cookieParser(),
session(sessionConfig),
cors(),
helmet(),
methodOverride(),
flash(),
bodyParser.urlencoded({ extended: false }),
bodyParser.json(),
passport.initialize(),
passport.session()
]
if (config.env === 'test') middlewares.shift()
export errorHandler from './errorhandler'
export httpProxy from './proxy'
export authorize from './authorize'
export validator from './validator'
export default () => compose(middlewares)
| JavaScript | 0.000025 | @@ -407,16 +407,65 @@
ssport'%0A
+import expressValidator from 'express-validator'%0A
import %7B
@@ -1034,16 +1034,38 @@
onfig),%0A
+ expressValidator(),%0A
cors()
|
6e14e628a32fbe8c7274cdb931ec12006566a91b | Update newegg.user.js | rtx/newegg.user.js | rtx/newegg.user.js | // ==UserScript==
// @name Newegg RTX Checker
// @namespace github.com/denniskupec
// @match https://www.newegg.com/p/pl?d=rtx+30*
// @grant GM_notification
// @grant GM_xmlhttpRequest
// @grant GM_openInTab
// @version 1
// @author Dennis Kupec
// @run-at document-end
// @noframes
// ==/UserScript==
const RELOAD_INTERVAL = 5 * 60 * 1000,
PUSHOVER_TOKEN = '1234',
PUSHOVER_USER = '1234';
window.setTimeout(function(){
console.info('Checking stock...')
let items = document.querySelectorAll('.list-wrap .item-cell')
if (items.length > 0) {
items.forEach(el => {
let btn = el.querySelector('.item-button-area'),
item_id = el.querySelector('.item-title');
if (!btn || !item_id) {
return;
}
if (btn.innerText.includes('ADD TO CART')) {
console.info(`${item_id[1]}: ✅ CARD IN STOCK ✅`)
console.info(`https://secure.newegg.com/Shopping/AddtoCart.aspx?Submit=ADD&ItemList=${item_id[1]}`)
GM_openInTab(`https://secure.newegg.com/Shopping/AddtoCart.aspx?Submit=ADD&ItemList=${item_id[1]}`)
GM_openInTab('https://secure.newegg.com/shop/cart')
GM_notification({
title: 'RTX 3080 IN STOCK',
text: 'RTX3080 available on Newegg. Added to cart!'
})
pushover_notify('RTX 3080 IN STOCK', 'RTX3080 available on Newegg. Added to cart.')
}
else {
console.info(`${item_id[1]}: ${btn.innerText}`)
}
})
}
window.setTimeout(() => window.location.reload(), RELOAD_INTERVAL)
}, 3000)
function Request(url, opt={}) {
Object.assign(opt, {
url,
timeout: 2000,
responseType: 'json'
})
return new Promise((resolve, reject) => {
opt.onerror = reject
opt.ontimeout = reject
opt.onload = resolve
GM_xmlhttpRequest(opt)
})
}
async function pushover_notify(title, msg) {
let opts = {
method: 'POST',
data: encodeURI(`token=${PUSHOVER_TOKEN}&user=${PUSHOVER_USER}&title=${title}&message=${msg}`),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
return await Request('https://api.pushover.net/1/messages.json', opts)
}
| JavaScript | 0.000001 | @@ -826,17 +826,16 @@
return
-;
%0A
@@ -833,32 +833,35 @@
n%0A %7D%0A
+%0A
%0A
@@ -850,24 +850,72 @@
+item_id = item_id.href.match(/(N%5BA-Z0-9%5D%7B14%7D)/)%0A
%0A
|
ec83c14b87458225bc247c7c4ad459a3cdd76aa1 | Update GatewayDriver.js | src/lib/settings/GatewayDriver.js | src/lib/settings/GatewayDriver.js | const SettingResolver = require('../parsers/SettingResolver');
const Gateway = require('./Gateway');
const util = require('../util/util');
/**
* <warning>GatewayDriver is a singleton, use {@link KlasaClient#gateways} instead.</warning>
* Gateway's driver to make new instances of it, with the purpose to handle different databases simultaneously.
*/
class GatewayDriver {
/**
* @typedef {Object} GatewayDriverRegisterOptions
* @property {string} [provider] The name of the provider to use
* @property {boolean} [download=true] Whether the Gateway should download all entries or not
* @property {boolean} [waitForDownload=true] Whether this Gateway should wait for all the data from the gateway to be downloaded
*/
/**
* @typedef {Object} GatewayDriverGuildsSchema
* @property {SchemaPieceJSON} prefix The per-guild's configurable prefix key
* @property {SchemaPieceJSON} language The per-guild's configurable language key
* @property {SchemaPieceJSON} disableNaturalPrefix The per-guild's configurable disableNaturalPrefix key
* @property {SchemaPieceJSON} disabledCommands The per-guild's configurable disabledCommands key
* @private
*/
/**
* @typedef {Object} GatewayDriverClientStorageSchema
* @property {SchemaPieceJSON} userBlacklist The client's configurable user blacklist key
* @property {SchemaPieceJSON} guildBlacklist The client's configurable guild blacklist key
* @property {SchemaPieceJSON} schedules The schedules where {@link ScheduledTask}s are stored at
* @private
*/
/**
* @since 0.3.0
* @param {KlasaClient} client The Klasa client
*/
constructor(client) {
/**
* The client this GatewayDriver was created with.
* @since 0.3.0
* @name GatewayDriver#client
* @type {KlasaClient}
* @readonly
*/
Object.defineProperty(this, 'client', { value: client });
/**
* The register creation queue.
* @since 0.5.0
* @name GatewayDriver#_queue
* @type {Array<Function>}
* @readonly
* @private
*/
Object.defineProperty(this, '_queue', { value: [] });
/**
* The resolver instance this Gateway uses to parse the data.
* @type {SettingResolver}
*/
this.resolver = new SettingResolver(client);
/**
* All the types accepted for the Gateway.
* @type {?Set<string>}
*/
this.types = null;
/**
* All the gateways added
* @type {Set<string>}
*/
this.keys = new Set();
/**
* The Gateway that manages per-guild data
* @type {?Gateway}
*/
this.guilds = null;
/**
* The Gateway that manages per-user data
* @type {?Gateway}
*/
this.users = null;
/**
* The Gateway that manages per-client data
* @type {?Gateway}
*/
this.clientStorage = null;
}
/**
* The data schema Klasa uses for guild configs.
* @since 0.5.0
* @readonly
* @type {GatewayDriverGuildsSchema}
*/
get guildsSchema() {
return {
prefix: {
type: 'string',
default: this.client.options.prefix,
min: null,
max: 10,
array: Array.isArray(this.client.options.prefix),
configurable: true
},
language: {
type: 'language',
default: this.client.options.language,
min: null,
max: null,
array: false,
configurable: true
},
disableNaturalPrefix: {
type: 'boolean',
default: false,
min: null,
max: null,
array: false,
configurable: Boolean(this.client.options.regexPrefix)
},
disabledCommands: {
type: 'command',
default: [],
min: null,
max: null,
array: true,
configurable: true
}
};
}
/**
* The data schema Klasa uses for user configs.
* @since 0.5.0
* @readonly
* @type {GatewayDriverUsersSchema}
*/
get usersSchema() {
return {};
}
/**
* The data schema Klasa uses for client-wide configs.
* @since 0.5.0
* @readonly
* @type {GatewayDriverClientStorageSchema}
*/
get clientStorageSchema() {
return {
userBlacklist: {
type: 'user',
default: [],
min: null,
max: null,
array: true,
configurable: true
},
guildBlacklist: {
type: 'string',
default: [],
min: 17,
max: 19,
array: true,
configurable: true
},
schedules: {
type: 'any',
default: [],
min: null,
max: null,
array: true,
configurable: false
}
};
}
/**
* Registers a new Gateway.
* @since 0.5.0
* @param {string} name The name for the new gateway
* @param {Object} [defaultSchema = {}] The schema for use in this gateway
* @param {GatewayDriverRegisterOptions} [options = {}] The options for the new gateway
* @returns {this}
* @chainable
*/
register(name, defaultSchema = {}, { provider = this.client.options.providers.default } = {}) {
if (typeof name !== 'string') throw new TypeError('You must pass a name for your new gateway and it must be a string.');
if (!util.isObject(defaultSchema)) throw new TypeError('Schema must be a valid object or left undefined for an empty object.');
if (this.name !== undefined && this.name !== null) throw new Error(`The key '${name}' is either taken by another Gateway or reserved for GatewayDriver's functionality.`);
const gateway = new Gateway(this, name, { provider });
this.keys.add(name);
this[name] = gateway;
this._queue.push(gateway.init.bind(gateway, defaultSchema));
return this;
}
/**
* Initialise all gateways from the queue
* @since 0.5.0
*/
async init() {
this.types = new Set(Object.getOwnPropertyNames(SettingResolver.prototype).slice(1));
await Promise.all([...this._queue].map(fn => fn()));
this._queue.length = 0;
}
/**
* Sync all gateways
* @since 0.5.0
* @param {...*} args The arguments to pass to each Gateway#sync
* @returns {Promise<Array<Gateway>>}
*/
sync(...args) {
return Promise.all([...this.keys].map(key => this[key].sync(...args)));
}
/**
* The GatewayDriver with all gateways, types and keys as JSON.
* @since 0.5.0
* @returns {Object}
*/
toJSON() {
const object = {
types: [...this.types],
keys: [...this.keys],
ready: this.ready
};
for (const key of this.keys) object[key] = this[key].toJSON();
return object;
}
/**
* The stringified GatewayDriver with all the managed gateways.
* @since 0.5.0
* @returns {string}
*/
toString() {
return `GatewayDriver(${[...this.keys].join(', ')})`;
}
}
module.exports = GatewayDriver;
| JavaScript | 0 | @@ -496,234 +496,8 @@
use%0A
-%09 * @property %7Bboolean%7D %5Bdownload=true%5D Whether the Gateway should download all entries or not%0A%09 * @property %7Bboolean%7D %5BwaitForDownload=true%5D Whether this Gateway should wait for all the data from the gateway to be downloaded%0A
%09 */
|
7364d58eaac55fde71e73e1b546da96eb8307a91 | fix mbaas js | src/modules/api_mbaas.js | src/modules/api_mbaas.js | var console =require("console");
var cloud = require("./waitForCloud");
var fhparams = require("./fhparams");
var ajax = require("./ajax");
var JSON = require("JSON");
var handleError = require("./handleError");
var consts = require("./constants");
module.exports = function(opts, success, fail){
console.log("mbaas is called.");
if(!fail){
fail = function(msg, error){
console.log(msg + ":" + JSON.stringify(error));
};
}
var mbaas = opts.service;
var params = opts.params;
cloud.ready(function(err, cloudHost){
console.log("Calling mbaas now");
if(err){
return fail(err.message, err);
} else {
var cloud_host = cloud.getCloudHost();
var url = cloud_host.getMBAASUrl(mbaas);
params = fhparams.addFHParams(params);
return ajax({
"url": url,
"tryJSONP": true,
"type": "POST",
"dataType": "json",
"data": JSON.stringify(params),
"contentType": "application/json",
"timeout": opts.timeout || consts.fh_timeout,
"success": success,
"error": fail
});
}
});
} | JavaScript | 0.000008 | @@ -1102,8 +1102,9 @@
%0A %7D);%0A%7D
+
|
e4a2f5aa80e37c3a19df3314199d8ec407088a64 | refactor getTranslation to use axios | src/config/localeConfig.js | src/config/localeConfig.js | import { URLNames, PropertyNames, VariableNames } from 'data/enum/configNames';
import configManagerInstance from './configManagerInstance';
const languages = configManagerInstance.getProperty(PropertyNames.AVAILABLE_LOCALES).map((locale) => {
if (typeof locale === 'string') {
return {
code: locale,
urlPrefix: locale,
translationKey: locale,
};
}
return locale;
});
const config = {
persistent: false,
defaultCode: configManagerInstance.getProperty(PropertyNames.DEFAULT_LOCALE),
languages,
};
const proxy = {
getTranslation({ translationKey }) {
return fetch(configManagerInstance.getURL(URLNames.LOCALE, { locale: translationKey }), {
method: 'get',
credentials: 'same-origin',
mode: 'cors',
headers: {
Accept: 'application/json',
},
})
.then(response => response.json())
.catch(() => {
// eslint-disable-next-line no-console
console.error(`Error loading locale: ${translationKey}`);
});
},
};
export default {
localeEnabled: configManagerInstance.getVariable(VariableNames.LOCALE_ENABLED),
localeRoutingEnabled: configManagerInstance.getVariable(VariableNames.LOCALE_ROUTING_ENABLED),
config,
proxy,
};
| JavaScript | 0.000001 | @@ -1,12 +1,39 @@
+import axios from 'axios';%0A
import %7B URL
@@ -605,13 +605,17 @@
urn
-fetch
+axios.get
(con
@@ -692,74 +692,8 @@
, %7B%0A
-%09%09%09method: 'get',%0A%09%09%09credentials: 'same-origin',%0A%09%09%09mode: 'cors',%0A
%09%09%09h
@@ -779,14 +779,12 @@
nse.
-json()
+data
)%0A%09%09
|
b76a4d1e9f84594bb95285aff73351bb0feadcc2 | Fix v2 create_credit_card_mutation test | src/schema/v2/me/__tests__/create_credit_card_mutation.test.js | src/schema/v2/me/__tests__/create_credit_card_mutation.test.js | /* eslint-disable promise/always-return */
import { runAuthenticatedQuery } from "schema/v2/test/utils"
describe("Credit card mutation", () => {
const creditCard = {
id: "foo-foo",
_id: "123",
name: "Foo User",
last_digits: "1234",
expiration_month: 3,
expiration_year: 2018,
}
const oldQuery = `
mutation {
createCreditCard(input: {token: "123abc"}) {
credit_card {
name
last_digits
expiration_month
expiration_year
}
}
}
`
const newQuery = `
mutation {
createCreditCard(input: {token: "tok_foo", oneTimeUse: true}) {
creditCardOrError {
... on CreditCardMutationSuccess {
creditCard {
id
}
}
... on CreditCardMutationFailure {
mutationError {
type
message
detail
}
}
}
}
}
`
const context = {
createCreditCardLoader: () => Promise.resolve(creditCard),
}
it("creates a credit card with the old-style query", async () => {
const data = await runAuthenticatedQuery(oldQuery, context)
expect(data).toEqual({
createCreditCard: {
credit_card: {
name: "Foo User",
last_digits: "1234",
expiration_month: 3,
expiration_year: 2018,
},
},
})
})
it("creates a credit card and returns an edge", async () => {
const edgeQuery = `
mutation {
createCreditCard(input: {token: "tok_foo", oneTimeUse: true}) {
creditCardOrError {
... on CreditCardMutationSuccess {
creditCardEdge {
node {
id
name
last_digits
expiration_month
expiration_year
}
}
}
... on CreditCardMutationFailure {
mutationError {
type
message
detail
}
}
}
}
}
`
const data = await runAuthenticatedQuery(edgeQuery, context)
expect(data).toEqual({
createCreditCard: {
creditCardOrError: {
creditCardEdge: {
node: {
id: "foo-foo",
name: "Foo User",
last_digits: "1234",
expiration_month: 3,
expiration_year: 2018,
},
},
},
},
})
})
it("creates a credit card with an error message", async () => {
const errorRootValue = {
createCreditCardLoader: () =>
Promise.reject(
new Error(
`https://stagingapi.artsy.net/api/v1/me/credit_cards?provider=stripe&token=tok_chargeDeclinedExpiredCard&one_time_use=true - {"type":"payment_error","message":"Payment information could not be processed.","detail":"Your card has expired."}`
)
),
}
const data = await runAuthenticatedQuery(newQuery, errorRootValue)
expect(data).toEqual({
createCreditCard: {
creditCardOrError: {
mutationError: {
detail: "Your card has expired.",
message: "Payment information could not be processed.",
type: "payment_error",
},
},
},
})
})
it("throws an error if there is one we don't recognize", async () => {
const errorRootValue = {
createCreditCardLoader: () => {
throw new Error("ETIMEOUT service unreachable")
},
}
runAuthenticatedQuery(newQuery, errorRootValue).catch(error => {
expect(error.message).toEqual("ETIMEOUT service unreachable")
})
})
it("creates a credit card successfully with the new-style query", async () => {
const data = await runAuthenticatedQuery(newQuery, context)
expect(data).toEqual({
createCreditCard: {
creditCardOrError: { creditCard: { id: "foo-foo" } },
},
})
})
})
| JavaScript | 0.000058 | @@ -313,220 +313,9 @@
nst
-oldQuery = %60%0A mutation %7B%0A createCreditCard(input: %7Btoken: %22123abc%22%7D) %7B%0A credit_card %7B%0A name%0A last_digits%0A expiration_month%0A expiration_year%0A %7D%0A %7D%0A %7D%0A %60%0A%0A const newQ
+q
uery
@@ -497,33 +497,41 @@
%7B%0A i
-d
+nternalID
%0A %7D%0A
@@ -799,373 +799,8 @@
%7D%0A%0A
- it(%22creates a credit card with the old-style query%22, async () =%3E %7B%0A const data = await runAuthenticatedQuery(oldQuery, context)%0A expect(data).toEqual(%7B%0A createCreditCard: %7B%0A credit_card: %7B%0A name: %22Foo User%22,%0A last_digits: %221234%22,%0A expiration_month: 3,%0A expiration_year: 2018,%0A %7D,%0A %7D,%0A %7D)%0A %7D)%0A%0A
it
@@ -1108,17 +1108,25 @@
i
-d
+nternalID
%0A
@@ -1155,26 +1155,25 @@
last
-_d
+D
igits%0A
@@ -1188,26 +1188,25 @@
expiration
-_m
+M
onth%0A
@@ -1224,18 +1224,17 @@
piration
-_y
+Y
ear%0A
@@ -1668,25 +1668,33 @@
i
-d
+nternalID
: %22foo-foo%22,
@@ -1736,34 +1736,33 @@
last
-_d
+D
igits: %221234%22,%0A
@@ -1776,34 +1776,33 @@
expiration
-_m
+M
onth: 3,%0A
@@ -1810,34 +1810,33 @@
expiration
-_y
+Y
ear: 2018,%0A
@@ -2386,36 +2386,33 @@
henticatedQuery(
-newQ
+q
uery, errorRootV
@@ -2954,28 +2954,25 @@
icatedQuery(
-newQ
+q
uery, errorR
@@ -3123,33 +3123,8 @@
ully
- with the new-style query
%22, a
@@ -3185,12 +3185,9 @@
ery(
-newQ
+q
uery
@@ -3294,17 +3294,25 @@
ard: %7B i
-d
+nternalID
: %22foo-f
|
b464a347fc0f97b602f061625f8b1c316cb0ec2a | Make sure all spawned processes are killed after testing | test-app/tests/cucumber/features/step_definitions/cli-steps.js | test-app/tests/cucumber/features/step_definitions/cli-steps.js | (function () {
// TODO: Replace process.env.PWD with getAppPath for Windows support
'use strict';
module.exports = function () {
var fs = require('fs-extra'),
_ = require('underscore'),
path = require('path'),
spawn = require('child_process').spawn,
DDPClient = require('ddp');
var stdOutMessages = [],
stdErrMessages = [];
var cwd = require('os').tmpdir(),
meteor;
console.log(cwd);
this.Given(/^I deleted the folder called "([^"]*)"$/, function (folder, callback) {
fs.remove(_resolveToCurrentDir(folder), callback);
});
this.Given(/^I created a folder called "([^"]*)"$/, function (folder, callback) {
fs.mkdirs(_resolveToCurrentDir(folder), callback);
});
this.Given(/^I created a file called "([^"]*)" with$/, function (file, text, callback) {
fs.outputFile(_resolveToCurrentDir(file), text, callback);
});
this.When(/^I run cuke-monkey inside "([^"]*)"$/, function (directory, callback) {
// TODO: Not sure if that process.env.PWD works here
var proc = spawn(path.join(process.env.PWD, 'bin/cuke-monkey'), [], {
cwd: _resolveToCurrentDir(directory),
stdio: null
});
proc.stdout.on('data', function (data) {
stdOutMessages.push(data.toString());
});
proc.stderr.on('data', function (data) {
stdErrMessages.push(data.toString());
});
proc.on('exit', function (code) {
if (code !== 0) {
callback.fail('Exit code was ' + code);
} else {
callback();
}
});
});
this.Then(/^I see "([^"]*)" in the console$/, function (message, callback) {
if (stdOutMessages.join().indexOf(message) !== -1) {
callback();
} else {
callback.fail(message + ' was not seen in the console log');
}
});
this.Given(/^I ran "([^"]*)"$/, _runCliCommand);
this.Given(/^I changed directory to "([^"]*)"$/, function (directory, callback) {
cwd = _resolveToCurrentDir(directory);
callback();
});
this.Given(/^I started meteor$/, function (callback) {
var toOmit = [
'ROOT_URL',
'PORT',
'MOBILE_DDP_URL',
'MOBILE_ROOT_URL',
'MONGO_OPLOG_URL',
'MONGO_URL',
'METEOR_PRINT_ON_LISTEN',
'METEOR_PARENT_PID',
'TMPDIR',
'APP_ID',
'OLDPWD',
'IS_MIRROR'
];
var currentEnv = _.omit(process.env, toOmit);
var command = isWindows() ? 'meteor.bat' : 'meteor';
meteor = spawn(command, ['-p', '3030'], {
cwd: cwd,
stdio: 'pipe',
detached: true,
env: currentEnv
});
var onMeteorData = function (data) {
var stdout = data.toString();
//console.log('[meteor-output]', stdout);
if (stdout.match(/=> App running at/i)) {
//console.log('[meteor-output] Meteor started', stdout);
//meteor.stdout.removeListener('data', onMeteorData);
callback();
}
};
meteor.stdout.on('data', onMeteorData);
meteor.stdout.pipe(process.stdout);
meteor.stderr.pipe(process.stderr);
});
this.Given(/^I create a fresh meteor project called "([^"]*)"$/, function (arg1, callback) {
fs.remove(_resolveToCurrentDir('myApp'), function () {
_runCliCommand('meteor create myApp', callback);
});
});
this.Given(/^I install the generic testing framework in "([^"]*)"$/, function (appName, callback) {
//And I created a folder called "myApp/packages"
fs.mkdirsSync(_resolveToCurrentDir(path.join(appName, 'packages')));
//And I changed directory to "myApp/packages"
cwd = _resolveToCurrentDir(path.join(appName, 'packages'));
//And I symlinked the generic framework to this directory
var velocityPackagePath = path.resolve(process.env.PWD, '..');
var genericPackagePath = path.resolve(process.env.PWD, '..', 'generic-framework');
fs.copySync(velocityPackagePath, _resolveToCurrentDir('velocity-core'));
fs.copySync(genericPackagePath, _resolveToCurrentDir('generic-framework'));
cwd = _resolveToCurrentDir('..');
//And I ran "meteor add velocity:generic-test-framework"
_runCliCommand('meteor add velocity:generic-framework', callback);
});
this.When(/^I call "([^"]*)" via DDP$/, function (method, callback) {
var app = new DDPClient({
host: 'localhost',
port: '3030',
ssl: false,
autoReconnect: true,
autoReconnectTimer: 500,
maintainCollections: true,
ddpVersion: '1',
useSockJs: true
});
app.connect(function (error) {
if (error) {
console.error('DDP connection error!', error);
callback.fail();
} else {
app.call(method, [{framework: 'generic'}], function (e) {
if (e) {
callback.fail(e.message);
} else {
callback();
}
});
}
});
});
this.Then(/^I should see the file "([^"]*)"$/, function (file, callback) {
fs.exists(_resolveToCurrentDir(file), function(exists){
if (exists) {
callback();
} else {
callback.fail('Could not find the file ' + file);
}
});
});
function isWindows() {
return process.platform === 'win32';
}
function _resolveToCurrentDir (location) {
return path.join(cwd, location);
}
function _runCliCommand (runLine, callback) {
var splitCommand = runLine.split(' ');
var command = splitCommand.splice(0, 1)[0];
var proc = spawn(command, splitCommand, {
cwd: cwd,
stdio: null,
env: process.env
});
proc.stdout.on('data', function (data) {
console.log('[cli]', data.toString());
});
proc.stderr.on('data', function (data) {
console.error('[cli]', data.toString());
});
proc.on('exit', function (code) {
if (code !== 0) {
callback.fail('Exit code was ' + code);
} else {
callback();
}
});
}
};
})();
| JavaScript | 0 | @@ -432,16 +432,121 @@
eteor;%0A%0A
+ process.on('exit', function () %7B%0A if (meteor) %7B%0A meteor.kill('SIGINT');%0A %7D%0A %7D);%0A%0A
cons
@@ -2258,32 +2258,142 @@
n (callback) %7B%0A%0A
+ if (meteor) %7B%0A // Skip if meteor is already started%0A callback();%0A return;%0A %7D%0A%0A
var toOmit
@@ -2886,32 +2886,8 @@
e',%0A
- detached: true,%0A
|
607b6c78e2f3b18d1028c1f4742f9c2c6e79c03e | update addThumbnail example | test/thumbnail.js | test/thumbnail.js | 'use strict'
const spaceBro = require('spacebro-client')
const config = require('standard-settings').getSettings().service.spacebro
spaceBro.connect(config.host, config.port, {
clientName: config.client,
channelName: config.channel,
verbose: false,
sendBack: false
})
console.log('Connecting to spacebro on ' + config.host + ':' + config.port)
spaceBro.on(config.outputMessage, function (data) {
console.log('video is ready: ' + data.output)
})
const data = {
path: './test/assets/pacman.mov',
details: {
thumbnail: {
path: './test/assets/logo.png'
}
}
}
setTimeout(function () {
spaceBro.emit(config.inputMessage, data)
console.log('emit ')
}, 300)
| JavaScript | 0 | @@ -12,24 +12,34 @@
'%0Aconst
-s
+%7B S
pace
-B
+b
ro
+Client %7D
= requi
@@ -66,22 +66,24 @@
)%0Aconst
-config
+settings
= requi
@@ -119,16 +119,26 @@
ttings()
+%0A%0Asettings
.service
@@ -150,262 +150,140 @@
ebro
-%0A%0AspaceBro.connect(config.host, config.port, %7B%0A
+.
client
-Name: config.client,%0A channelName: config.channel,%0A verbose: false,%0A sendBack: false%0A%7D)%0Aconsole.log('Connecting to spacebro on ' + config.host + ':' + config.port)%0A%0A
+.name += '-test'%0Aconst spacebro = new SpacebroClient()%0A%0Aspacebro.on(settings.service.
space
-Bro.on(config.outputMessag
+bro.client%5B'out'%5D.outMedia.eventNam
e, f
@@ -338,19 +338,37 @@
' +
-data.output
+JSON.stringify(data, null, 2)
)%0A%7D)
@@ -505,29 +505,35 @@
%7D%0A%0As
-etTimeout(function
+pacebro.on('connect',
()
+ =%3E
%7B%0A
@@ -542,17 +542,17 @@
pace
-B
+b
ro.emit(
conf
@@ -551,26 +551,63 @@
mit(
-config.inputMessag
+settings.service.spacebro.client%5B'in'%5D.inMedia.eventNam
e, d
@@ -639,11 +639,6 @@
')%0A%7D
-, 300
)%0A
|
872150b34854dd744dd3b888005cb288f2be78b0 | get username not name | problems/requesting_you_pull_please/verify.js | problems/requesting_you_pull_please/verify.js | #!/usr/bin/env node
var request = require('request')
var spawn = require('child_process').spawn
var concat = require('concat-stream')
// var url = "http://localhost:5563/pr?username="
var url = 'http://reporobot.jlord.us/pr?username='
var user = spawn('git', ['config', 'user.name'])
user.stdout.pipe(concat(onUser))
function onUser(output) {
var username = output.toString().trim()
pullrequest(username)
}
// check that they've submitted a pull request
// to the original repository jlord/patchwork
function pullrequest(username) {
request(url + username, {json: true}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var pr = body.pr
if (pr) console.log(true)
else console.log("No pull request found for " + username)
}
})
} | JavaScript | 0.999997 | @@ -271,16 +271,20 @@
, 'user.
+user
name'%5D)%0A
|
c0dbb8635c6a64299e7858256e8f17fa9075851d | make linter happy about rename | docs/lint.js | docs/lint.js | #!/usr/bin/env node
var fs = require("fs")
var path = require("path")
//lint rules
function lint(file, data) {
ensureCodeIsHighlightable(file, data)
ensureCodeIsSyntaticallyValid(file, data)
ensureCodeIsRunnable(file, data)
ensureCommentStyle(file, data)
}
function ensureCodeIsHighlightable(file, data) {
var codeBlocks = data.match(/```(.|\n|\r)*?```/gim) || []
codeBlocks.forEach(function(block) {
block = block.slice(3, -3)
if (block.indexOf("javascript") !== 0) {
try {if (new Function(block)) console.log(file + " - javascript block missing language tag after triple backtick\n\n" + block + "\n\n---\n\n")}
catch (e) {/*not a js block, ignore*/}
}
})
}
function ensureCodeIsSyntaticallyValid(file, data) {
var codeBlocks = data.match(/```javascript(.|\n|\r)*?```/gim) || []
codeBlocks.forEach(function(block) {
block = block.slice(13, -3)
try {new Function(block)}
catch (e) {console.log(file + " - javascript block has wrong syntax\n\n" + e.message + "\n\n" + block + "\n\n---\n\n")}
})
}
function ensureCodeIsRunnable(file, data) {
var codeBlocks = data.match(/```javascript(.|\n|\r)*?```/gim) || []
var code = codeBlocks.map(function(block) {return block.slice(13, -3)}).join(";")
//stubs
var silentConsole = {log: function() {}}
var fetch = function() {
return Promise.resolve({
json: function() {}
})
}
try {
initMocks()
new Function("console,fetch,module,require", code).call(this, silentConsole, fetch, {exports: {}}, function(dep) {
if (dep.indexOf("./mycomponent") === 0) return {view: function() {}}
if (dep.indexOf("mithril/ospec/ospec") === 0) return global.o
if (dep.indexOf("mithril/stream") === 0) return global.stream
if (dep === "mithril") return global.m
})
}
catch (e) {console.log(file + " - javascript code cannot run\n\n" + e.stack + "\n\n" + code + "\n\n---\n\n")}
}
function ensureCommentStyle(file, data) {
var codeBlocks = data.match(/```javascript(.|\n|\r)*?```/gim) || []
codeBlocks.forEach(function(block) {
block = block.slice(13, -3)
if (block.match(/(^|\s)\/\/[\S]/)) console.log(file + " - comment missing space\n\n" + block + "\n\n---\n\n")
})
}
function initMocks() {
global.window = require("../test-utils/browserMock")()
global.document = window.document
global.m = require("../index")
global.o = require("../ospec/ospec")
global.stream = require("../stream")
global.alert = function() {}
//routes consumed by request.md
global.window.$defineRoutes({
"GET /api/v1/users": function(request) {
return {status: 200, responseText: JSON.stringify([{name: ""}])}
},
"GET /api/v1/users/search": function(request) {
return {status: 200, responseText: JSON.stringify([{id: 1, name: ""}])}
},
"GET /api/v1/users/1/projects": function(request) {
return {status: 200, responseText: JSON.stringify([{id: 1, name: ""}])}
},
"GET /api/v1/todos": function(request) {
return {status: 200, responseText: JSON.stringify([])}
},
"PUT /api/v1/users/1": function(request) {
return {status: 200, responseText: request.query.callback ? request.query.callback + "([])" : "[]"}
},
"POST /api/v1/upload": function(request) {
return {status: 200, responseText: JSON.stringify([])}
},
"GET /files/icon.svg": function(request) {
return {status: 200, responseText: "<svg></svg>"}
},
"GET /files/data.csv": function(request) {
return {status: 200, responseText: "a,b,c"}
},
"GET /api/v1/users/123": function(request) {
return {status: 200, responseText: JSON.stringify({id: 123})}
},
"GET /api/v1/users/foo:bar": function(request) {
return {status: 200, responseText: JSON.stringify({id: 123})}
},
})
}
//runner
function traverseDirectory(pathname, callback) {
pathname = pathname.replace(/\\/g, "/")
return new Promise(function(resolve, reject) {
fs.lstat(pathname, function(err, stat) {
if (err) reject(err)
if (stat.isDirectory()) {
fs.readdir(pathname, function(err, pathnames) {
if (err) reject(err)
var promises = []
for (var i = 0; i < pathnames.length; i++) {
pathnames[i] = path.join(pathname, pathnames[i])
promises.push(traverseDirectory(pathnames[i], callback))
}
callback(pathname, stat, pathnames)
resolve(Promise.all(promises))
})
}
else {
callback(pathname, stat)
resolve(pathname)
}
})
})
}
//run
traverseDirectory("./docs", function(pathname) {
if (pathname.indexOf(".md") > -1 && !pathname.match(/migration|node_modules/)) {
fs.readFile(pathname, "utf8", function(err, data) {
if (err) console.log(err)
else lint(pathname, data)
})
}
})
.then(process.exit)
| JavaScript | 0.000001 | @@ -4468,17 +4468,18 @@
ch(/
-migration
+change-log
%7Cnod
|
107a3431559080cd06f08ddf2ef67c31b9cedc1e | Disable autocomplete on New Player Name input | app/scripts/components/dashboard.js | app/scripts/components/dashboard.js | import m from 'mithril';
import ClipboardJS from 'clipboard';
import classNames from '../classnames.js';
// The area of the game UI consisting of game UI controls and status messages
class DashboardComponent {
oninit({ attrs: { game, session } }) {
this.game = game;
this.session = session;
}
// Prepare game players by creating new players (if necessary) and deciding
// which player has the starting move
setPlayers(gameType) {
if (this.game.players.length > 0) {
// Reset new games before choosing number of players (no need to reset
// the very first game)
this.game.resetGame();
}
this.game.setPlayers(gameType);
}
startGame(newStartingPlayer) {
this.game.startGame({
startingPlayer: newStartingPlayer
});
}
endGame(roomCode) {
if (roomCode) {
// The local player ID and room code will be automatically passed by the
// session.emit() function
this.session.emit('end-game');
} else {
this.game.endGame();
}
}
createNewPlayer() {
this.session.status = 'newPlayer';
}
setNewPlayerName(inputEvent) {
this.newPlayerName = inputEvent.target.value;
inputEvent.redraw = false;
}
submitNewPlayer(submitEvent, roomCode) {
submitEvent.preventDefault();
if (roomCode) {
this.addNewPlayerToGame(roomCode);
} else {
this.startOnlineGame();
}
}
addNewPlayerToGame(roomCode) {
this.session.status = 'connecting';
let submittedPlayer = { name: this.newPlayerName, color: 'blue' };
this.session.emit('add-player', { roomCode, player: submittedPlayer }, ({ game, localPlayer }) => {
this.game.restoreFromServer({ game, localPlayer });
m.redraw();
});
}
startOnlineGame() {
this.session.connect();
this.session.on('connect', () => {
// Construct a placeholder player with the name we entered and the default
// first player color
let submittedPlayer = { name: this.newPlayerName, color: 'red' };
// Request a new room and retrieve the room code returned from the server
this.session.emit('open-room', { player: submittedPlayer }, ({ roomCode, game, localPlayer }) => {
this.game.restoreFromServer({ game, localPlayer });
console.log('new room', roomCode);
m.route.set(`/room/${roomCode}`);
});
// When P2 joins, automatically update P1's screen
this.session.on('add-player', ({ game, localPlayer }) => {
this.game.restoreFromServer({ game, localPlayer });
m.redraw();
});
this.session.on('end-game', ({ requestingPlayer }) => {
this.game.requestingPlayer = requestingPlayer;
this.game.endGame();
m.redraw();
});
});
}
configureCopyControl({ dom }) {
this.shareLinkCopier = new ClipboardJS(dom);
this.copyStatusDuration = 1000;
this.shareLinkCopier.on('success', () => {
this.copyStatus = 'Copied!';
this.copyStatusFlash = true;
m.redraw();
// Reset status message after a second or two
clearTimeout(this.copyStatusTimer);
this.copyStatusTimer = setTimeout(() => {
this.copyStatus = null;
this.copyStatusFlash = false;
m.redraw();
}, this.copyStatusDuration);
});
}
view({ attrs: { roomCode } }) {
return m('div#game-dashboard', [
m('p#game-message',
// If the current player needs to enter a name
this.session.status === 'newPlayer' ?
'Enter your player name:' :
this.session.status === 'waitingForPlayers' ?
[
'Waiting for other player...',
m('div#share-controls', [
m('input[type=text]#share-link', {
value: window.location.href,
onclick: ({ target }) => target.select()
}),
m('button#copy-share-link', {
'data-clipboard-text': window.location.href,
oncreate: ({ dom }) => this.configureCopyControl({ dom })
}, 'Copy'),
m('span#share-link-copy-status', {
class: classNames({ 'copy-status-flash': this.copyStatusFlash })
}, this.copyStatus)
])
] :
this.session.status === 'connecting' ?
'Connecting to server...' :
this.session.status === 'roomNotFound' ?
'This room does not exist.' :
// If user has not started any game yet
this.game.players.length === 0 ?
'Welcome! How many players?' :
// If a game is in progress
this.game.currentPlayer ?
`${this.game.currentPlayer.name}, your turn!` :
// If a player wins the game
this.game.winner ?
`${this.game.winner.name} wins! Play again?` :
// If the grid is completely full
this.game.grid.checkIfFull() ?
'We\'ll call it a draw! Play again?' :
// If the user just chose a number of players for the game to be started
!roomCode && this.game.type !== null ?
'Which player should start first?' :
roomCode && this.game.requestingPlayer ?
`${this.game.requestingPlayer.name} has ended the game.` :
// Otherwise, if game was ended manually by the user
'Game ended. Play again?'
),
// If game is in progress, allow user to end game at any time
this.game.inProgress ? [
m('button', { onclick: () => this.endGame(roomCode) }, 'End Game')
] :
this.session.status === 'newPlayer' ? [
m('form', {
onsubmit: (submitEvent) => this.submitNewPlayer(submitEvent, roomCode)
}, [
m('input[type=text]#new-player-name', {
name: 'new-player-name',
autofocus: true,
oninput: (inputEvent) => this.setNewPlayerName(inputEvent)
}),
m('button[type=submit]', roomCode ? 'Join Game' : 'Start Game')
])
] :
!roomCode ? [
// If number of players has been chosen, ask user to choose starting player
this.game.type !== null ?
this.game.players.map((player) => {
return m('button', {
onclick: () => this.startGame(player)
}, player.name);
}) : [
// Select a number of human players
m('button', {
onclick: () => this.setPlayers({ gameType: '1P' })
}, '1 Player'),
m('button', {
onclick: () => this.setPlayers({ gameType: '2P' })
}, '2 Players'),
m('button', {
onclick: () => this.createNewPlayer()
}, 'Online')
]
] : null
]);
}
}
export default DashboardComponent;
| JavaScript | 0.000001 | @@ -5683,16 +5683,34 @@
pe=text%5D
+%5Bautocomplete=off%5D
#new-pla
|
510504fab99c4030937f0f0faa87272b90903db1 | fix logic to extract move | app/scripts/controllers/notation.js | app/scripts/controllers/notation.js | 'use strict';
/**
* @ngdoc function
* @name chessmateApp.controller:NotationCtrl
* @description
* # NotationCtrl
* Controller of the chessmateApp
*/
angular.module('chessmateApp')
.controller('NotationCtrl', function ($scope, $rootScope) {
$scope.buildGame = function (notation) {
var game = {
"boards": [$scope.buildInitialBoard()]
};
$scope.generateBoardFromNotation(game.boards, notation);
$rootScope.$broadcast('game-updated', game);
};
$scope.buildInitialBoard = function () {
var board = {
"turn": 0,
"source": undefined,
"destination": undefined,
"position": {
"A1": $scope.buildPiece('R', "white"),
"B1": $scope.buildPiece('N', "white"),
"C1": $scope.buildPiece('C', "white"),
"D1": $scope.buildPiece('K', "white"),
"E1": $scope.buildPiece('M', "white"),
"F1": $scope.buildPiece('C', "white"),
"G1": $scope.buildPiece('N', "white"),
"H1": $scope.buildPiece('R', "white"),
"A3": $scope.buildPiece('B', "white"),
"B3": $scope.buildPiece('B', "white"),
"C3": $scope.buildPiece('B', "white"),
"D3": $scope.buildPiece('B', "white"),
"E3": $scope.buildPiece('B', "white"),
"F3": $scope.buildPiece('B', "white"),
"G3": $scope.buildPiece('B', "white"),
"H3": $scope.buildPiece('B', "white"),
"A6": $scope.buildPiece('B', "black"),
"B6": $scope.buildPiece('B', "black"),
"C6": $scope.buildPiece('B', "black"),
"D6": $scope.buildPiece('B', "black"),
"E6": $scope.buildPiece('B', "black"),
"F6": $scope.buildPiece('B', "black"),
"G6": $scope.buildPiece('B', "black"),
"H6": $scope.buildPiece('B', "black"),
"A8": $scope.buildPiece('R', "black"),
"B8": $scope.buildPiece('N', "black"),
"C8": $scope.buildPiece('C', "black"),
"D8": $scope.buildPiece('M', "black"),
"E8": $scope.buildPiece('K', "black"),
"F8": $scope.buildPiece('C', "black"),
"G8": $scope.buildPiece('N', "black"),
"H8": $scope.buildPiece('R', "black")
}
};
return board;
};
$scope.generateBoardFromNotation = function (boardsArray, notation) {
//extract header and moves out of notation string
var header = notation.substring(0,notation.lastIndexOf("]"));
//do something with header
var moves = $scope.getMoves(notation);
//while still have moves
var dotPos;
while ((dotPos = moves.indexOf(".")) != -1) {
//find first 6 and send with white colour
var whiteMove = moves.substring(dotPos + 1, moves.indexOf(' '));
boardsArray.push($scope.buildBoard(boardsArray[boardsArray.length - 1], whiteMove, 'white'));
//find last 6 and send with black colour
var indexOfFirstBlack = dotPos+1+whiteMove.length+1;
var indexOfSecondSpace = moves.indexOf(' ', indexOfFirstBlack);
var blackMove = moves.substring(indexOfFirstBlack ,indexOfSecondSpace);
boardsArray.push($scope.buildBoard(boardsArray[boardsArray.length - 1], blackMove, 'black'));
moves = moves.substring(moves.indexOf(blackMove)+blackMove.length+1);
}
};
$scope.getMoves = function (notation) {
var lastIndexOfBracket = notation.lastIndexOf("]");
return notation.substring(lastIndexOfBracket + 1);
};
$scope.buildBoard = function (currentBoard, move, color) {
var board = angular.copy(currentBoard);
var char = (move.indexOf("=") == -1) ? move.substring(0, 1) : "M";
var source = move.substring(1, 3);
var destination = move.substring(4, 6);
board.turn = currentBoard.turn + 1;
board.source = source;
board.destination = destination;
board.position[destination] = $scope.buildPiece(char, color);
delete board.position[source];
return board;
};
$scope.buildPiece = function (char, color) {
var piece = {
type: $scope.getType(char),
color: color
};
piece.value = buildValue(piece);
return piece;
};
$scope.getType = function (char) {
var type;
if (char == 'B') {
type = "pawn";
} else if (char == 'R') {
type = "rook";
} else if (char == 'N') {
type = "knight";
} else if (char == 'C') {
type = "bishop";
} else if (char == 'K') {
type = "king";
} else if (char == 'M') {
type = "queen";
}
return type;
};
var buildValue = function (piece) {
var map = Immutable.Map({
"rook-black": "♜",
"knight-black": "♞",
"bishop-black": "♝",
"king-black": "♚",
"queen-black": "♛",
"pawn-black": "♟",
"rook-white": "♖",
"knight-white": "♘",
"bishop-white": "♗",
"king-white": "♔",
"queen-white": "♕",
"pawn-white": "♙"
});
var key = piece.type + "-" + piece.color;
return map.get(key);
};
$scope.notationString = "[White AMA][Black 500miles] [Tournament Thai Chess League][Date -1-0] [Result 1/2-1/2]" +
"1.BF3-F4 BC6-C5 2.NG1-F3 BD6-D5 3.BE3-E4 NB8-C6 4.ME1-F2 MD8-C7 5.MF2-E3 MC7-D6 6.CC1-C2 CF8-F7 7.NB1-D2 NG8-E7 8.BH3-H4 BH6-H5 9.CF1-F2 BA6-A5 10.KD1-E2 CC8-C7";
});
| JavaScript | 0.000005 | @@ -2788,16 +2788,23 @@
exOf(' '
+,dotPos
));%0A
|
665bf7b7a890ed3dce72294489f0bbbccfef96f0 | fix missing service qualifications | app/scripts/services/cockpit.api.js | app/scripts/services/cockpit.api.js | 'use strict';
/**
* @ngdoc service
* @name blimpCockpitApp.cockpit.api
* @description
* # cockpit.api
* Service in the blimpCockpitApp.
*/
angular.module('blimpCockpitApp')
.factory('cockpitApi', ['$resource', '$http', '$q', '$rootScope', '$state',
function ($resource, $http, $q, $rootScope, $state) {
var service = {
current_user: null,
login: function (username, password) {
var deferred = $q.defer();
$http.post('/musterroll/login', {
'username': username,
'password': password
}).
success(function (data) {
current_user = data;
$rootScope.currentUser = data.id;
deferred.resolve(data);
}).
error(function (data) {
deferred.resolve(false);
});
return deferred.promise;
},
logOut: function(){
var deferred = $q.defer();
$http.get('/musterroll/logout').
success(function (data, status, header) {
$rootScope.currentUser = null;
deferred.resolve(data);
}).
error(function (data, status) {
deferred.resolve(status);
});
return deferred.promise;
},
getCurrentUser: function () {
var deferred = $q.defer();
if(current_user && current_user.id)
{
deferred.resolve(current_user);
}
else
{
deferred.resolve(status)
$http.get('/musterroll/api/v1/currentUser').
success(function (data, status, header) {
$rootScope.currentUser = data.id;
deferred.resolve(data);
}).
error(function (data, status) {
deferred.resolve(status);
});
}
return deferred.promise;
}
};
return service;
}]);
| JavaScript | 0.999996 | @@ -616,32 +616,40 @@
%7B%0A
+service.
current_user = d
@@ -653,16 +653,16 @@
= data;%0A
-
@@ -1102,16 +1102,59 @@
= null;%0A
+ service.current_user = null;%0A
@@ -1510,16 +1510,24 @@
resolve(
+service.
current_
@@ -1714,32 +1714,32 @@
atus, header) %7B%0A
-
@@ -1764,32 +1764,77 @@
User = data.id;%0A
+ service.current_user = data;%0A
|
9d981f6743c878dfde8fd35bb9fba6cc9e0dc090 | Revert "workaround to make homeui work regardless of MQTT message order" | app/scripts/services/mqttService.js | app/scripts/services/mqttService.js | 'use strict';
var mqttServiceModule = angular.module('homeuiApp.mqttServiceModule', ['ngResource']);
mqttServiceModule.factory('mqttClient', function($window) {
var globalPrefix = '';
var service = {};
var client = {};
if($window.localStorage['prefix'] === 'true') globalPrefix = '/client/' + $window.localStorage['user'];
service.connect = function(host, port, user, password) {
var options = {
onSuccess: service.onConnect,
onFailure: service.onFailure
};
if(user != undefined && password != undefined) {
options.userName = user;
options.password = password;
}
console.log("Try to connect to MQTT Broker on " + host + ":" + port + " with user " + user);
client = new Paho.MQTT.Client(host, parseInt(port), '/', user);
client.connect(options);
client.onConnectionLost = service.onConnectionLost;
client.onMessageDelivered = service.onMessageDelivered;
client.onMessageArrived = service.onMessageArrived;
};
service.onConnect = function() {
console.log("Connected to " + client.host + ":" + client.port + " as '" + client.clientId + "'");
if(globalPrefix != '') console.log('With globalPrefix: ' + globalPrefix);
client.subscribe(globalPrefix + "/devices/#");
//~ client.subscribe(globalPrefix + "/config/#");
client.subscribe(globalPrefix + "/config/default_dashboard/#");
client.subscribe(globalPrefix + "/config/rooms/#");
client.subscribe(globalPrefix + "/config/widgets/#");
client.subscribe(globalPrefix + "/config/dashboards/#");
$window.localStorage.setItem('connected', true);
};
service.onFailure = function() {
console.log("Failure to connect to " + client.host + ":" + client.port + " as " + client.clientId);
$window.localStorage.setItem('connected', false);
};
service.publish = function(topic, payload) {
client.publish(topic, payload, {retain: true});
console.log('publish-Event sent '+ payload + ' with topic: ' + topic + ' ' + client);
};
service.onMessage = function(callback) {
service.callback = callback;
};
service.onConnectionLost = function (errorCallback) {
console.log("Server connection lost: " + errorCallback.errorMessage);
$window.localStorage.setItem('connected', false);
};
service.onMessageDelivered = function(message) {
console.log("Delivered message: " + JSON.stringify(message));
};
service.onMessageArrived = function(message) {
// console.log("Arrived message: " + message.destinationName + " with " + message.payloadBytes.length + " bytes of payload");
// console.log("Message: " + String.fromCharCode.apply(null, message.payloadBytes));
service.callback(message);
};
service.send = function(destination, payload) {
var topic = globalPrefix + destination;
var message = new Paho.MQTT.Message(payload);
message.destinationName = topic;
message.retained = true;
client.send(message);
};
service.disconnect = function() {
client.disconnect();
};
return service;
}); | JavaScript | 0 | @@ -152,20 +152,32 @@
($window
+, $rootScope
) %7B%0A
-
var gl
@@ -232,16 +232,41 @@
t = %7B%7D;%0A
+ var connected = false;%0A
if($wi
@@ -1295,12 +1295,8 @@
%0A
- //~
cli
@@ -1347,298 +1347,48 @@
c
-lient.subscribe(globalPrefix + %22/config/default_dashboard/#%22);%0A client.subscribe(globalPrefix + %22/config/rooms/#%22);%0A client.subscribe(globalPrefix + %22/config/widgets/#%22);%0A client.subscribe(globalPrefix + %22/config/dashboards/#%22);%0A%0A%0A $window.localStorage.setItem('connected', true
+onnected = true;%0A $rootScope.$digest(
);%0A
@@ -1539,38 +1539,8 @@
-$window.localStorage.setItem('
conn
@@ -1540,32 +1540,57 @@
connected
-',
+ =
false
+;%0A $rootScope.$digest(
);%0A %7D;%0A%0A s
@@ -2001,38 +2001,8 @@
-$window.localStorage.setItem('
conn
@@ -2010,16 +2010,41 @@
cted
-',
+ =
false
+;%0A $rootScope.$digest(
);%0A
@@ -2786,16 +2786,81 @@
;%0A %7D;%0A%0A
+ service.isConnected = function () %7B%0A return connected;%0A %7D;%0A
return
@@ -2869,11 +2869,12 @@
ervice;%0A
-
%7D);
+%0A
|
9362cf7a4c253a8f54270229794989b9c44c5a3c | fix cms (#791) | app/services/data/get-cms-export.js | app/services/data/get-cms-export.js | const knex = require('../../../knex').web
module.exports = function (id, type) {
const selectList = [
'contactregionname',
'contactlduname',
'contactteamname',
'contactdate',
'omcontactdate',
'contactname',
'contactgradecode',
'omregionname',
'omlduname',
'omteamname',
'contactid',
'omname',
'omgradecode',
'contactdescription',
'contactcode',
'contactpoints',
'ompoints',
'caserefno',
'omcaserefno',
'omcontactdescription',
'omcontactcode'
]
let query = knex('cms_export_view')
.withSchema('app')
.select(selectList)
if (id !== undefined && (!isNaN(parseInt(id, 10)))) {
query = query.where(`om${type}id`, id).orWhere(`contact${type}id`, id)
}
return query.then(function (results) {
results.forEach(function (result) {
if (!result.caseRefNo) {
result.caseRefNo = result.omCaseRefNo
}
if (!result.contactDescription) {
result.contactDescription = result.omContactDescription
}
if (!result.contactCode) {
result.contactCode = result.omContactCode
}
if (!result.contactDate) {
result.contactDate = result.omContactDate
}
})
return results
})
}
| JavaScript | 0 | @@ -852,20 +852,20 @@
ult.case
-RefN
+refn
o) %7B%0A
@@ -880,20 +880,20 @@
ult.case
-RefN
+refn
o = resu
@@ -901,16 +901,16 @@
t.om
-CaseRefN
+caserefn
o%0A
@@ -932,33 +932,33 @@
(!result.contact
-D
+d
escription) %7B%0A
@@ -973,25 +973,25 @@
sult.contact
-D
+d
escription =
@@ -1000,24 +1000,24 @@
esult.om
-C
+c
ontact
-D
+d
escripti
@@ -1052,17 +1052,17 @@
.contact
-C
+c
ode) %7B%0A
@@ -1082,17 +1082,17 @@
.contact
-C
+c
ode = re
@@ -1102,16 +1102,16 @@
t.om
-C
+c
ontact
-C
+c
ode%0A
@@ -1143,17 +1143,17 @@
.contact
-D
+d
ate) %7B%0A
@@ -1173,17 +1173,17 @@
.contact
-D
+d
ate = re
@@ -1193,16 +1193,16 @@
t.om
-C
+c
ontact
-D
+d
ate%0A
|
ed59595d56fe19cc6197a7efb153a4f0272b6dae | Add PatternFly styling to Area charts (transferred from ManageIQ/manageiq@d76cefe145992ce7ba4746580fa9283b2dfa06ed) | app/assets/javascripts/miq_c3_config.js | app/assets/javascripts/miq_c3_config.js | /**
* C3 chart configuration for ManageIQ.
*
* To be replaced with `c3ChartDefaults` once available through PatternFly:
*
* https://github.com/patternfly/patternfly/blob/master/dist/js/patternfly.js
*/
(function (ManageIQ) {
var pfColors = [$.pfPaletteColors.blue, $.pfPaletteColors.red, $.pfPaletteColors.green, $.pfPaletteColors.orange, $.pfPaletteColors.cyan,
$.pfPaletteColors.gold, $.pfPaletteColors.purple, $.pfPaletteColors.lightBlue, $.pfPaletteColors.lightGreen, $.pfPaletteColors.black];
var c3mixins = {};
c3mixins.showGrid = {
grid: {
x: {
show: true
},
y: {
show: true
}
}
};
c3mixins.smallerBarWidth = {
bar: {
width: {
ratio: 0.3
}
}
};
c3mixins.noLegend = {
legend: {
show: false
}
};
c3mixins.legendOnRightSide = {
legend: {
position: 'right'
}
};
c3mixins.noTooltip = {
tooltip: {
show: false
}
};
c3mixins.pfDataColorFunction = {
data: {
color: function (color, d) {
return pfColors[d.index % pfColors.length];
}
}
};
c3mixins.pfColorPattern = {
color: {
pattern: pfColors
}
};
c3mixins.xAxisCategory = {
axis: {
x: {
type: 'category',
tick: {
outer: false,
multiline: false
}
}
}
};
c3mixins.xAxisCategoryRotated = {
axis: {
x: {
type: 'category',
tick: {
outer: false,
multiline: false,
rotate: 45
}
}
}
};
c3mixins.yAxisNoOuterTick = {
axis: {
y: {
tick: {
outer: false
}
}
}
};
function percentLabelFormat (value, ratio) {
return d3.format('%')(ratio);
}
ManageIQ.charts.c3config = {
Bar: _.defaultsDeep(
{
axis : {x:{type: 'category'},
rotated: true},
data : {type: 'bar'},
},
c3mixins.pfColorPattern,
$().c3ChartDefaults().getDefaultBarConfig()
),
Column: _.defaultsDeep({
axis : {x:{type: 'category'}},
data : {type: 'bar'},
},c3mixins.pfColorPattern,
$().c3ChartDefaults().getDefaultBarConfig()
),
StackedBar: _.defaultsDeep(
{
axis : {x:{type: 'category'},
rotated: true},
data : {type: 'bar'},
},c3mixins.pfColorPattern,
$().c3ChartDefaults().getDefaultGroupedBarConfig()
),
StackedColumn: _.defaultsDeep(
{
axis : {x:{type: 'category'}},
data : {type: 'bar'},
},c3mixins.pfColorPattern,
$().c3ChartDefaults().getDefaultGroupedBarConfig()
),
Pie: _.defaultsDeep({
data: {
type: 'pie'
},
pie: {
label: {
format: percentLabelFormat
},
expand: false
}
},
c3mixins.pfColorPattern,
c3mixins.legendOnRightSide,
c3mixins.noTooltip
),
Donut: _.defaultsDeep({
data: {
type: 'donut'
},
donut: {
label: {
format: percentLabelFormat
},
expand: false
}
},
c3mixins.pfColorPattern,
c3mixins.legendOnRightSide,
c3mixins.noTooltip
),
Line: _.defaultsDeep(
{
axis : {x:{type: 'category'}},
data : {type: 'line'},
},c3mixins.pfColorPattern,
$().c3ChartDefaults().getDefaultLineConfig()
),
Area: _.defaultsDeep({
data: {
type: 'area'
},
area: {
label: {
format: percentLabelFormat
},
expand: false
}
},
c3mixins.xAxisCategory,
c3mixins.pfColorPattern,
c3mixins.legendOnRightSide,
c3mixins.noTooltip
),
StackedArea: _.defaultsDeep({
data: {
type: 'area'
},
area: {
label: {
format: percentLabelFormat
},
expand: false
}
},
c3mixins.xAxisCategory,
c3mixins.pfColorPattern,
c3mixins.legendOnRightSide,
c3mixins.noTooltip
)
};
})(ManageIQ);
| JavaScript | 0 | @@ -3488,39 +3488,30 @@
efaultsDeep(
-%7B
%0A
- data:
%7B%0A
@@ -3513,283 +3513,153 @@
- type: 'area'%0A %7D,%0A area: %7B%0A label: %7B%0A format: percentLabelFormat%0A %7D,%0A expand: false%0A %7D%0A %7D,%0A c3mixins.xAxisCategory,%0A c3mixins.pfColorPattern,%0A c3mixins.legendOnRightSide,%0A c3mixins.noTooltip
+axis : %7Bx:%7Btype: 'category'%7D%7D,%0A data : %7Btype: 'area'%7D,%0A %7D,c3mixins.pfColorPattern,%0A $().c3ChartDefaults().getDefaultAreaConfig()
%0A
|
781c7951b19a9f5464c87737eee99969222d2b41 | Replace hardcoded coordinates with randomly generated values | app/props/ball.js | app/props/ball.js | import Prop from 'props/prop';
import canvas from 'canvas';
import collision from 'lib/collision';
import events from 'lib/events';
// Maybe make these coords an array so we can easily multiply without lodash _.mapValues for speed.
const coords = {
northEast: {
x: 1,
y: -1,
},
southEast: {
x: 1,
y: 1,
},
southWest: {
x: -1,
y: 1,
},
northWest: {
x: -1,
y: -1,
},
};
export default class Ball extends Prop {
constructor() {
const width = 10;
const height = 10;
const x = (canvas.width / 2) - (width / 2);
const y = (canvas.height / 2) - (height / 2);
super(x, y, width, height);
this.speed = 2;
this.direction = coords.northWest;
}
rebound() {
const calculate = (num) => num <= 0 ? Math.abs(num) : -(num);
this.direction.x = calculate(this.direction.x);
this.direction.y = calculate(this.direction.y);
}
fire() {
const move = () => {
this.move(this.direction.x, this.direction.y);
events.publish('ballMove', this);
if (!collision.isOutOfBounds(this)) {
return requestAnimationFrame(move);
}
};
requestAnimationFrame(move);
}
}
| JavaScript | 0.001053 | @@ -131,293 +131,8 @@
';%0A%0A
-// Maybe make these coords an array so we can easily multiply without lodash _.mapValues for speed.%0Aconst coords = %7B%0A northEast: %7B%0A x: 1,%0A y: -1,%0A %7D,%0A southEast: %7B%0A x: 1,%0A y: 1,%0A %7D,%0A southWest: %7B%0A x: -1,%0A y: 1,%0A %7D,%0A northWest: %7B%0A x: -1,%0A y: -1,%0A %7D,%0A%7D;%0A%0A
expo
@@ -382,16 +382,17 @@
ed = 2;%0A
+%0A
this
@@ -396,36 +396,427 @@
his.
-direction = coords.northWest
+createRandomDirection();%0A console.log('this.direction', this.direction);%0A %7D%0A%0A createRandomDirection() %7B%0A // Generate random number from -3 - 3, not including 0.%0A function create() %7B%0A const number = Math.floor(Math.random() * 3) + 1;%0A const positive = !!Math.round(Math.random());%0A%0A return positive ? number : -(number);%0A %7D%0A%0A this.direction = %7B%0A x: create(),%0A y: create(),%0A %7D
;%0A
|
e7bb0b51a0fdaebb89dea3e20f33ebb0a9a261b2 | update tests since actions now return an object instead of a string | server/spec/multi/game/actionFnsSpec.js | server/spec/multi/game/actionFnsSpec.js | describe('actionFns', function() {
var actionFns = require('../../../multi/game/actionFns');
var Board = require('../../../multi/game/board');
var game, board, player1, player2;
beforeEach(function() {
player1 = {
_id: 1,
name: 'Philly',
team: 1
};
player2 = {
_id: 2,
name: 'Sue Grafton',
team: 2
};
var columns = 2;
var rows = 2;
board = new Board([player1, player2], columns, rows);
game = {
board: board
}
});
it('should perform a valid action', function() {
board.target(1,0,0).card = {
abilities: ['heal'],
health: 3
};
var result = actionFns.doAction(game, player1, 'heal', [{playerId:1, column:0, row:0}, {playerId:1, column:0, row:0}]);
expect(result).toEqual({newHealth: 4});
expect(board.target(1,0,0).card.health).toBe(4);
});
it('should not perform an action on an invalid target', function() {
var result = actionFns.doAction(game, player1, 'heal', [{playerId:1, column:0, row:0}]);
expect(result).not.toBe('ok');
});
it('should not let you use a card you do not own', function() {
board.target(2,0,0).card = {
abilities: ['heal'],
health: 3
};
var result = actionFns.doAction(game, player1, 'heal', [{playerId:2, column:0, row:0}]);
expect(result).toContain('not your card');
});
it('should not let you use an ability the card does not have', function() {
board.target(1,0,0).card = {
abilities: [],
player: player1
};
board.target(2,0,0).card = {
player: player2
};
var result = actionFns.doAction(game, player1, 'rbld', [{playerId:1, column:0, row:0}, {playerId:2, column:0, row:0}]);
expect(result).toContain('card does not have the ability');
});
it('should perform multi-step validations', function() {
board.target(1,0,0).card = {
abilities: ['male'],
moves: 1
};
board.target(1,0,1).card = {
abilities: ['feml'],
moves: 1
};
var result = actionFns.doAction(game, player1, 'male', [
{playerId:1, column:0, row:0}, //male
{playerId:1, column:0, row:1}, //female
{playerId:1, column:1, row:0} //empty slot for child
]);
expect(board.target(1,1,0).card.name).toBe('GROW TUBE');
});
it('should fail bad multi-step validations', function() {
board.target(1,0,0).card = {
abilities: ['male']
};
board.target(1,0,1).card = {
abilities: ['feml']
};
var result = actionFns.doAction(game, player1, 'feml', [
{playerId:1, column:0, row:1}, //male
{playerId:1, column:0, row:0}, //female
{playerId:2, column:1, row:0} //enemy territory, should fail here
]);
expect(result).toBe('target is not allowed');
});
}); | JavaScript | 0.000001 | @@ -1240,32 +1240,36 @@
%0A%09%09expect(result
+.err
).toContain('not
@@ -1627,24 +1627,28 @@
xpect(result
+.err
).toContain(
@@ -2576,19 +2576,28 @@
sult).to
-Be(
+Equal(%7Berr:
'target
@@ -2611,16 +2611,17 @@
allowed'
+%7D
);%0A%09%7D);%0A
|
84ecef6678b80802bb63f9695d43c2bc1c643f8b | fix registry error log: there is no log.critical | src/registry.js | src/registry.js | /**
* Patterns registry - Central registry and scan logic for patterns
*
* Copyright 2012-2013 Simplon B.V.
* Copyright 2012-2013 Florian Friesdorf
* Copyright 2013 Marko Durkovic
* Copyright 2013 Rok Garbas
*/
/*
* changes to previous patterns.register/scan mechanism
* - if you want initialised class, do it in init
* - init returns set of elements actually initialised
* - handle once within init
* - no turnstile anymore
* - set pattern.jquery_plugin if you want it
*/
define([
"jquery",
"./core/logger",
"./utils",
// below here modules that are only loaded
"./compat"
], function($, logger, utils) {
var log = logger.getLogger("registry"),
jquery_plugin = utils.jquery_plugin;
var disable_re = /patterns-disable=([^&]+)/g,
disabled = {}, match;
while ((match=disable_re.exec(window.location.search))!==null) {
disabled[match[1]] = true;
log.info('Pattern disabled via url config:', match[1]);
}
var registry = {
patterns: {},
// as long as the registry is not initialized, pattern
// registration just registers a pattern. Once init is called,
// the DOM is scanned. After that registering a new pattern
// results in rescanning the DOM only for this pattern.
initialized: false,
init: function() {
$(document).ready(function() {
log.info('loaded: ' + Object.keys(registry.patterns).sort().join(', '));
registry.scan(document.body);
registry.initialized = true;
log.info('finished initial scan.');
});
},
scan: function(content, do_not_catch_init_exception, patterns) {
var $content = $(content),
all = [], allsel,
pattern, $match, plog;
// If no list of patterns was specified, we scan for all
// patterns
patterns = patterns || Object.keys(registry.patterns);
// selector for all patterns
patterns.forEach(function(name) {
if (disabled[name]) {
log.debug('Skipping disabled pattern:', name);
return;
}
pattern = registry.patterns[name];
if (pattern.transform) {
try {
pattern.transform($content);
} catch (e) {
log.critical("Transform error for pattern" + name, e);
}
}
if (pattern.trigger) {
all.push(pattern.trigger);
}
});
allsel = all.join(",");
// Find all elements that belong to any pattern.
$match = $content.findInclusive(allsel);
$match = $match.filter(function() { return $(this).parents('pre').length === 0; });
$match = $match.filter(":not(.cant-touch-this)");
// walk list backwards and initialize patterns inside-out.
//
// XXX: If patterns would only trigger via classes, we
// could iterate over an element classes and trigger
// patterns in order.
//
// Advantages: Order of pattern initialization controled
// via order of pat-classes and more efficient.
$match.toArray().reduceRight(function(acc, el) {
var $el = $(el);
for (var name in registry.patterns) {
pattern = registry.patterns[name];
plog = logger.getLogger("pat." + name);
if ($el.is(pattern.trigger)) {
plog.debug("Initialising:", $el);
try {
pattern.init($el);
plog.debug("done.");
} catch (e) {
if (do_not_catch_init_exception) {
throw e;
} else {
plog.error("Caught error:", e);
}
}
}
}
}, null);
},
// XXX: differentiate between internal and custom patterns
// _register vs register
register: function(pattern) {
if (!pattern.name) {
log.error("Pattern lacks name:", pattern);
return false;
}
if (registry.patterns[pattern.name]) {
log.error("Already have a pattern called: " + pattern.name);
return false;
}
// register pattern to be used for scanning new content
registry.patterns[pattern.name] = pattern;
// register pattern as jquery plugin
if (pattern.jquery_plugin) {
var pluginName = ("pat-" + pattern.name)
.replace(/-([a-zA-Z])/g, function(match, p1) {
return p1.toUpperCase();
});
$.fn[pluginName] = jquery_plugin(pattern);
// BBB 2012-12-10
$.fn[pluginName.replace(/^pat/, "pattern")] = jquery_plugin(pattern);
}
log.debug("Registered pattern:", pattern.name, pattern);
if (registry.initialized) {
registry.scan(document.body, false, [pattern.name]);
}
return true;
}
};
$(document) .on("patterns-injected.patterns", function(ev) {
registry.scan(ev.target);
$(ev.target).trigger("patterns-injected-scanned");
});
return registry;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
| JavaScript | 0.998571 | @@ -2469,16 +2469,13 @@
log.
-critical
+error
(%22Tr
|
c87bb58a86d26fd3ba852db6bf4063c14eeee937 | Make emojis searchable | app/views/main.js | app/views/main.js | var clipboard = require("nativescript-clipboard");
var observableModule = require("data/observable");
var observableArrayModule = require("data/observable-array");
var emojiSet = require('emojione/emoji_strategy.json');
var emojiArray = [];
for (var key in emojiSet) {
emojiArray.push({
value: String.fromCodePoint(parseInt(emojiSet[key].unicode, 16)),
});
}
var pageData = new observableModule.Observable({
displayableEmojiList: new observableArrayModule.ObservableArray(emojiArray)
});
exports.loaded = function(args) {
console.log('page loaded');
page = args.object;
page.bindingContext = pageData;
};
exports.buttonTapped = function(eventData) {
console.log('button tapped', eventData.eventName, eventData.object, eventData.object.text);
// put the emoji in the clipboard
clipboard.setText(eventData.object.text).then(function() {
console.log('OK, ' + eventData.object.text + ' copied to the clipboard');
});
};
| JavaScript | 0.999989 | @@ -17,17 +17,17 @@
require(
-%22
+'
nativesc
@@ -40,17 +40,17 @@
lipboard
-%22
+'
);%0Avar o
@@ -67,33 +67,33 @@
odule = require(
-%22
+'
data/observable%22
@@ -91,17 +91,17 @@
servable
-%22
+'
);%0Avar o
@@ -131,17 +131,17 @@
require(
-%22
+'
data/obs
@@ -157,9 +157,45 @@
rray
-%22
+');%0Avar view = require('ui/core/view'
);%0A%0A
@@ -388,21 +388,150 @@
16)),%0A%09
-%7D);%0A%7D
+%09keywords: emojiSet%5Bkey%5D.keywords.split(' ')%0A%09%7D);%0A%7D%0A%0Avar displayableEmojiList = new observableArrayModule.ObservableArray(emojiArray);
%0A%0Avar pa
@@ -574,16 +574,27 @@
able(%7B%0A%09
+emojiList:
displaya
@@ -609,67 +609,277 @@
List
-: new observableArrayModule.ObservableArray(emojiArray)%0A
+,%0A%09query: ''%0A%7D);%0A%0Afunction copy(text) %7B%0A%09clipboard.setText(text).then(function() %7B%0A%09%09console.log('OK, ' + text + ' copied to the clipboard');%0A%09%7D);%0A%7D%0A%0Afunction matches(emoji, text) %7B%0A%09return emoji.keywords.some(function(keyword) %7B%0A%09%09return keyword.includes(text);%0A%09
%7D);
+%0A%7D
%0A%0Aex
@@ -1009,18 +1009,18 @@
rts.
-buttonTapp
+queryChang
ed =
@@ -1060,19 +1060,13 @@
og('
-button tapp
+chang
ed',
@@ -1079,18 +1079,8 @@
Data
-.eventName
, ev
@@ -1124,61 +1124,99 @@
);%0A%09
-// put the emoji in the clipboard%0A%09clipboard.setText(
+displayableEmojiList.splice(0);%0A%09emojiArray.forEach(function(emoji) %7B%0A%09%09if (matches(emoji,
even
@@ -1232,37 +1232,177 @@
ect.text
-)
.t
-hen(function(
+oLowerCase())) %7B%0A%09%09%09displayableEmojiList.push(emoji);%0A%09%09%7D%0A%09%7D);%0A%09console.log('length', displayableEmojiList.length);%0A%7D%0A%0Aexports.itemTap = function(eventData
) %7B%0A
-%09
%09console
@@ -1411,73 +1411,127 @@
og('
-OK, ' + eventData.object.text + ' copied to the clipboard');%0A%09%7D
+item tapped', eventData, eventData.object, eventData.index);%0A%09copy(displayableEmojiList.getItem(eventData.index).value
);%0A%7D
-;
%0A
|
f87853e78c42571f2979801a7c204cfc818bf80c | Update menu unit test with better example objects. | frameworks/desktop/tests/panes/menu/methods.js | frameworks/desktop/tests/panes/menu/methods.js | // ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
// portions copyright @2009 Apple Inc.
// License: Licened under MIT license (see license.js)
// ==========================================================================
/*global module test htmlbody ok equals same stop start */
var menu;
var menuItemTarget;
var menuItemTargetName = "The Target";
var menuItemCheckboxKey = "isCheckbox";
module('SC.MenuPane#MenuItemTargetIsSet', {
setup: function() {
menuItemTarget = SC.Object.create({
myName: menuItemTargetName
});
menu = SC.MenuPane.create({
layout: { width: 80, height: 0 },
itemTargetKey: 'myTarget',
itemTitleKey: 'myTitle',
itemCheckboxKey: menuItemCheckboxKey,
items: [
{ myTitle: "Item1", myTarget: menuItemTarget }
],
contentView: SC.View.extend({})
});
},
teardown: function() {
menuItemTarget.destroy();
menuItemTarget = null;
menu.destroy();
menu = null;
}
});
test("Menu sets item target.", function() {
menu.get('displayItems');
menu.append(); // force a rendering of the menu item child views
var target = menu.menuItemViews[0].get('target'); // see if the target propagated through
menu.remove(); // remove the menu
var success = (target && (target.myName === menuItemTargetName)); // check to see if it's the right target
ok(success, "Menu item should have the target we specified.");
});
test("Menu sets MenuItem.contentCheckboxKey.", function() {
menu.get('displayItems');
menu.append();
var key = menu.menuItemViews[0].get('contentCheckboxKey');
menu.remove();
var success = (key && (key === menuItemCheckboxKey));
ok(success, "MenuItem.contentCheckboxKey should equal MenuPane.itemCheckboxKey after being rendered.");
});
| JavaScript | 0 | @@ -449,562 +449,912 @@
var
-menu;%0Avar m
+items = %5B%0A %7B title: 'M
enu
+
Item
-Target;%0Avar menuItemTargetName = %22The Target%22;%0Avar m
+', keyEquivalent: 'ctrl_shift_n' %7D,%0A %7B title: 'Checked M
enu
+
Item
-CheckboxKey = %22isCheckbox%22;%0A%0Amodule('SC.MenuPane#
+', isChecked: YES, keyEquivalent: 'ctrl_a' %7D,%0A %7B title: 'Selected
Menu
+
Item
-TargetIsSet', %7B%0A setup: function() %7B%0A m
+', keyEquivalent: 'backspace' %7D,%0A %7B isSeparator: YES %7D,%0A %7B title: 'M
enu
+
Item
-Target = SC.Object.create(%7B%0A myName: m
+ with Icon', icon: 'inbox', keyEquivalent: 'ctrl_m' %7D,%0A %7B title: 'M
enu
+
Item
-TargetName%0A %7D);%0A %0A menu = SC.MenuPane.create(%7B%0A layout: %7B width: 80, height: 0 %7D,%0A itemTargetKey: 'myTarget',%0A itemTitleKey: 'myTitle',%0A itemCheckboxKey: m
+ with Icon', icon: 'folder', keyEquivalent: 'ctrl_p' %7D,%0A %7B isSeparator: YES %7D,%0A %7B title: 'Selected Menu Item%E2%80%A6', isChecked: YES, keyEquivalent: 'ctrl_shift_o' %7D,%0A %7B title: 'Item with Submenu', subMenu: %5B%7B title: 'Submenu item 1' %7D, %7B title: 'Submenu item 2'%7D%5D %7D,%0A %7B title: 'Disabled M
enu
+
Item
-CheckboxKey,%0A items: %5B%0A %7B myTitle: %22Item1%22, myTarget: menuItemTarget %7D%0A %5D,%0A contentView: SC.View.extend(%7B%7D)
+', isEnabled: NO %7D,%0A %7B isSeparator: YES %7D,%0A %7B groupTitle: 'Menu Label', items: %5B%7B title: 'Nested Item' %7D, %7B title: 'Nested Item' %7D%5D %7D%0A%5D;%0A%0Avar menu;%0A%0Amodule('SC.MenuPane#popup', %7B%0A setup: function() %7B%0A menu = SC.MenuPane.create(%7B%0A layout: %7B width: 200 %7D,%0A items: items
%0A
@@ -1363,18 +1363,16 @@
);%0A %7D,%0A
-
%0A teard
@@ -1401,594 +1401,75 @@
menu
-ItemTarget.destroy();%0A menuItemTarget = null;%0A menu.destroy();%0A menu = null;%0A %7D%0A%7D);%0A%0Atest(%22Menu sets item target.%22, function() %7B%0A menu.get('displayItems');%0A menu.append(); // force a rendering of the menu item child views%0A var target = menu.menuItemViews%5B0%5D.get('target'); // see if the target propagated through%0A menu.remove(); // remove the menu%0A var success = (target && (target.myName === menuItemTargetName)); // check to see if it's the right target%0A ok(success, %22Menu item should have the target we specified.%22);%0A%7D);%0A%0Atest(%22Menu sets MenuItem.contentCheckboxKey.%22
+.destroy();%0A menu = null;%0A %7D%0A%7D);%0A%0Atest('SC.MenuPane - append()'
, fu
@@ -1472,25 +1472,24 @@
, function()
-
%7B%0A menu.get
@@ -1489,283 +1489,15 @@
enu.
-get('displayItems');%0A menu.append();%0A var key = menu.menuItemViews%5B0%5D.get('contentCheckboxKey');%0A menu.remove();%0A var success = (key && (key === menuItemCheckboxKey));%0A ok(success, %22MenuItem.contentCheckboxKey should equal MenuPane.itemCheckboxKey after being rendered.%22
+append(
);%0A%7D
|
91d0ea010a5a52b28d18726422da4f7cab8ee9c3 | Update frappe/public/js/frappe/form/controls/table.js | frappe/public/js/frappe/form/controls/table.js | frappe/public/js/frappe/form/controls/table.js | import Grid from '../grid';
frappe.ui.form.ControlTable = frappe.ui.form.Control.extend({
make: function() {
this._super();
// add title if prev field is not column / section heading or html
this.grid = new Grid({
frm: this.frm,
df: this.df,
perm: this.perm || (this.frm && this.frm.perm) || this.df.perm,
parent: this.wrapper
});
if(this.frm) {
this.frm.grids[this.frm.grids.length] = this;
}
// description
if(this.df.description) {
$('<p class="text-muted small">' + __(this.df.description) + '</p>')
.appendTo(this.wrapper);
}
this.$wrapper.on('paste',':text', function(e) {
var cur_table_field =$(e.target).closest('div [data-fieldtype="Table"]').data('fieldname');
var cur_field = $(e.target).data('fieldname');
var cur_grid= cur_frm.get_field(cur_table_field).grid;
var cur_grid_rows = cur_grid.grid_rows;
var cur_doctype = cur_grid.doctype;
var cur_row_docname =$(e.target).closest('div .grid-row').data('name');
var row_idx = locals[cur_doctype][cur_row_docname].idx;
var clipboardData, pastedData;
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData || e.originalEvent.clipboardData;
pastedData = clipboardData.getData('Text');
if (!pastedData) return;
var data = frappe.utils.csv_to_array(pastedData,'\t');
if (data.length === 1 & data[0].length === 1) return;
if (data.length > 100){
data = data.slice(0, 100);
frappe.msgprint(__('for performance, only the first 100 rows processed!'));
}
var fieldnames = [];
var get_field = function(name_or_label){
var fieldname;
$.each(cur_grid.meta.fields,(ci,field)=>{
name_or_label = name_or_label.toLowerCase()
if (field.fieldname.toLowerCase() === name_or_label ||
(field.label && field.label.toLowerCase() === name_or_label)){
fieldname = field.fieldname;
return false;
}
});
return fieldname;
}
if (get_field(data[0][0])){ // for raw data with column header
$.each(data[0], (ci, column)=>{fieldnames.push(get_field(column));});
data.shift();
}
else{ // no column header, map to the existing visible columns
var visible_columns = cur_grid_rows[0].get_visible_columns();
var find;
$.each(visible_columns, (ci, column)=>{
if (column.fieldname === cur_field) find = true;
find && fieldnames.push(column.fieldname);
})
}
$.each(data, function(i, row) {
var blank_row = true;
$.each(row, function(ci, value) {
if(value) {
blank_row = false;
return false;
}
});
if(!blank_row) {
if (row_idx > cur_frm.doc[cur_table_field].length){
cur_grid.add_new_row();
}
var cur_row = cur_grid_rows[row_idx - 1];
row_idx ++;
var row_name = cur_row.doc.name;
$.each(row, function(ci, value) {
if (fieldnames[ci]) frappe.model.set_value(cur_doctype, row_name, fieldnames[ci], value);
});
frappe.show_progress(__('Processing'), i, data.length);
}
});
frappe.hide_progress();
return false; // Prevent the default handler from running.
});
},
refresh_input: function() {
this.grid.refresh();
},
get_value: function() {
if(this.grid) {
return this.grid.get_data();
}
},
set_input: function( ) {
//
},
validate: function() {
return this.get_value();
}
});
| JavaScript | 0 | @@ -1476,17 +1476,17 @@
int(__('
-f
+F
or perfo
@@ -1517,16 +1517,21 @@
00 rows
+were
processe
@@ -1531,17 +1531,17 @@
rocessed
-!
+.
'));%0A%09%09%09
|
d3dc4817e1b6dcf032b8c00a7a08dcd71057c84d | Implement FizzBuzz | fizzbuzz/src/fizzbuzz.js | fizzbuzz/src/fizzbuzz.js | JavaScript | 0.000005 | @@ -0,0 +1,111 @@
+'use strict'%0A%0Amodule.exports = %7B%0A%09fizzBuzz: function(num) %7B%0A%09%09if(num%2515 === 0) %7B%0A%09%09%09return 'FizzBuzz';%0A%09%09%7D%0A%09%7D%0A%7D
|
|
9f484db399b360938c5889b5a6cd0e1129db8115 | Remove Unused Variable | app/components/ui/files/registration-modal/component.js | app/components/ui/files/registration-modal/component.js | import Ember from 'ember';
import layout from './template';
import RSVP from 'rsvp';
import EventStream from 'npm:sse.js';
import config from '../../../../config/environment';
export default Ember.Component.extend({
layout,
authRequest: Ember.inject.service(),
userAuth: Ember.inject.service(),
internalState: Ember.inject.service(),
tokenHandler: Ember.inject.service(),
notificationHandler: Ember.inject.service(),
datasources: Ember.A(),
dev: config.dev,
num_results: -1,
error: false,
errorMessage: '',
searching: false,
searchDataId: '',
dataId: '',
doi: '',
name: '',
repository: '',
size: '',
useDev: '',
devUrl: 'https://dev.nceas.ucsb.edu/knb/d1/mn/v2',
prodUrl: 'https://cn.dataone.org/cn/v2',
didInsertElement() {
this._super(...arguments);
$(".info.circle.grey.icon").hover(function() {
$("#info-data-content").removeClass("hidden");
},
function() {
$("#info-data-content").addClass("hidden");
}
);
},
disableRegister() {
Ember.$('.icon.register').removeClass('checkmark');
Ember.$('.ui.positive.register.button').addClass('disabled');
},
enableRegister(dataId) {
let ds = this.datasources.find(ds => {
return (dataId == ds.dataId || dataId == ds.doi);
});
this.set('dataId', ds.dataId);
this.set('doi', ds.doi);
this.set('name', ds.name);
this.set('repository', ds.repository);
this.set('size', ds.size);
Ember.$('.icon.register').addClass('checkmark');
Ember.$('.ui.positive.register.button').removeClass('disabled');
},
clearModal() {
Ember.$('#harvester-dropdown').dropdown('clear');
Ember.$('#results').addClass('hidden');
Ember.$('#searchbox').val('');
this.set('datasources', Ember.A());
this.set('error', false);
this.set('errorMessage', '');
this.set('num_results', -1);
this.set('dataId', '');
this.set('doi', '');
this.set('name', '');
this.set('repository', '');
this.set('size', '');
},
didRender() {
let self = this;
Ember.$('#harvester-dropdown').dropdown({
onChange: function(dataId) {
if(!dataId || dataId === "") {
self.disableRegister();
return;
}
self.enableRegister(dataId);
}
});
},
getEventStream() {
let token = this.get('tokenHandler').getWholeTaleAuthToken();
let source = new EventStream.SSE(config.apiUrl+"/notification/stream?timeout=15000", {headers: {'Girder-Token': token}});
let self = this;
source.addEventListener('message', function(evt) {
let payload = JSON.parse(evt.data);
let notifier = self.get('notificationHandler');
notifier.pushNotification({
message: payload.data.message,
header: payload.data.title
});
});
source.stream();
return source;
},
actions: {
updateDev(value) {
// Called if the `use dev` checkbox is clicked
this.set('useDev', value)
},
register() {
this.set('error', false);
let self = this;
let state = this.get('internalState');
let userAuth = this.get('userAuth');
let parentId = state.getCurrentParentId();
let parentType = state.getCurrentParentType();
if(!!parentId || parentId === "undefined" || parentId === undefined) {
parentId = userAuth.getCurrentUserID();
parentType = "user";
}
let queryParams = "?"+[
"parentType="+parentType,
"parentId="+parentId,
"public=false"
].join('&');
let dataMap = JSON.stringify([{
name: this.name,
dataId: this.dataId,
repository: this.repository
}]);
let baseUrl=this.get('podUrl');
if (this.get('useDev')) {
baseUrl=this.get('devUrl')
}
let url = config.apiUrl + '/dataset/register' + queryParams;
let options = {
method: 'POST',
data: {
dataMap: dataMap,
base_url: baseUrl
}
};
let source = this.getEventStream();
this.get('authRequest').send(url, options)
.then(rep => {
})
.catch(e => {
let notifier = self.get('notificationHandler');
notifier.pushNotification({
header: "Error Registering Dataset",
message: e
});
})
.finally(_ => {
source.close();
});
this.clearModal();
this.disableRegister();
},
cancel() {
this.clearModal();
this.disableRegister();
},
search() {
this.clearModal();
this.set('searching', true);
Ember.$('#results').removeClass('hidden');
let url = config.apiUrl + '/repository/lookup';
let baseUrl=this.get('podUrl');
if (this.get('useDev')) {
baseUrl=this.get('devUrl')
}
let options = {
method: 'GET',
data: {
dataId: JSON.stringify(this.searchDataId.split()),
base_url: baseUrl
}
};
let self = this;
return self.get('authRequest').send(url, options)
.then(rep => {
self.set('error', false);
self.set('num_results', rep.length);
self.datasources.pushObjects(rep);
if(rep.length === 1) {
let name = self.datasources[0].name;
let dataId = self.datasources[0].dataId;
Ember.run.later(self, function() {
Ember.$('#harvester-dropdown').dropdown('set text', name);
Ember.$('#harvester-dropdown').dropdown('set value', dataId);
}, 250);
}
else {
Ember.$('#harvester-dropdown').dropdown('set visible');
Ember.$('#harvester-dropdown').dropdown('set active');
let menu = Ember.$('#harvester-dropdown .menu');
menu.removeClass('hidden');
menu.addClass('transition visible');
}
})
.catch(e => {
console.log("Error: " + e);
self.set('error', true);
self.set('errorMessage', 'No matching results found.');
self.disableRegister();
})
.finally((_) => {
self.set('searching', false);
});
}
}
});
| JavaScript | 0 | @@ -469,29 +469,8 @@
(),%0A
- dev: config.dev,%0A
|
69630531d493568c9dff5a4e2992b044796094d5 | Remove unused code. I accidentially left an unused variable in the component. | app/components/ui/files/registration-modal/component.js | app/components/ui/files/registration-modal/component.js | import Ember from 'ember';
import layout from './template';
import RSVP from 'rsvp';
import EventStream from 'npm:sse.js';
import config from '../../../../config/environment';
export default Ember.Component.extend({
layout,
authRequest: Ember.inject.service(),
userAuth: Ember.inject.service(),
internalState: Ember.inject.service(),
tokenHandler: Ember.inject.service(),
notificationHandler: Ember.inject.service(),
datasources: Ember.A(),
num_results: -1,
error: false,
errorMessage: '',
searching: false,
searchDataId: '',
dataId: '',
doi: '',
name: '',
repository: '',
// Size of the package found
size: '',
// When set to true, the backend will search the DataONE dev server
useDev: '',
// Controls whether the results section is shown in the UI
showResults: false,
// URL to the Development member node
devUrl: 'https://dev.nceas.ucsb.edu/knb/d1/mn/v2',
// URL to the DataONE production server
prodUrl: 'https://cn.dataone.org/cn/v2',
// Flag that controls the grey background
showGrey: false,
didInsertElement() {
this._super(...arguments);
$(".info.circle.grey.icon").hover(function() {
$("#info-data-content").removeClass("hidden");
},
function() {
$("#info-data-content").addClass("hidden");
}
);
},
disableRegister() {
Ember.$('.icon.register').removeClass('checkmark');
Ember.$('.ui.positive.register.button').addClass('disabled');
},
enableRegister(dataId) {
let ds = this.datasources.find(ds => {
return (dataId == ds.dataId || dataId == ds.doi);
});
this.set('dataId', ds.dataId);
this.set('doi', ds.doi);
this.set('name', ds.name);
this.set('repository', ds.repository);
this.set('size', ds.size);
Ember.$('.icon.register').addClass('checkmark');
Ember.$('.ui.positive.register.button').removeClass('disabled');
},
clearModal() {
this.clearErrors();
this.clearSearch();
this.clearResults();
this.clearPackageResults();
},
clearErrors() {
this.set('error', false);
this.set('errorMessage', '');
},
clearResults() {
Ember.$('#harvester-dropdown').dropdown('clear');
this.set('showResults', false);
this.set('num_results', -1);
this.set('datasources', Ember.A());
},
clearPackageResults() {
this.set('dataId', '');
this.set('doi', '');
this.set('name', '');
this.set('repository', '');
this.set('size', '');
},
clearSearch() {
Ember.$('#searchbox').val('');
},
didRender() {
let self = this;
Ember.$('#harvester-dropdown').dropdown({
onChange: function(dataId) {
if(!dataId || dataId === "") {
self.disableRegister();
return;
}
self.enableRegister(dataId);
}
});
},
getEventStream() {
let token = this.get('tokenHandler').getWholeTaleAuthToken();
let source = new EventStream.SSE(config.apiUrl+"/notification/stream?timeout=15000", {headers: {'Girder-Token': token}});
let self = this;
source.addEventListener('message', function(evt) {
let payload = JSON.parse(evt.data);
let notifier = self.get('notificationHandler');
notifier.pushNotification({
message: payload.data.message,
header: payload.data.title
});
});
source.stream();
return source;
},
actions: {
updateDev(value) {
// Called if the `use dev` checkbox is clicked
this.set('useDev', value);
},
register() {
this.clearErrors();
let self = this;
let state = this.get('internalState');
let userAuth = this.get('userAuth');
let parentId = state.getCurrentParentId();
let parentType = state.getCurrentParentType();
if(!!parentId || parentId === "undefined" || parentId === undefined) {
parentId = userAuth.getCurrentUserID();
parentType = "user";
}
let queryParams = "?"+[
"parentType="+parentType,
"parentId="+parentId,
"public=false"
].join('&');
let dataMap = JSON.stringify([{
name: this.name,
dataId: this.dataId,
repository: this.repository
}]);
let baseUrl=this.get('podUrl');
if (this.get('useDev')) {
baseUrl=this.get('devUrl')
}
let url = config.apiUrl + '/dataset/register' + queryParams;
let options = {
method: 'POST',
data: {
dataMap: dataMap,
base_url: baseUrl
}
};
let source = this.getEventStream();
this.get('authRequest').send(url, options)
.then(rep => {
})
.catch(e => {
let notifier = self.get('notificationHandler');
notifier.pushNotification({
header: "Error Registering Dataset",
message: e
});
})
.finally(_ => {
source.close();
});
this.clearModal();
this.disableRegister();
},
cancel() {
this.clearModal();
this.disableRegister();
},
search() {
this.clearResults();
this.clearErrors();
this.clearPackageResults()
this.set('searching', true);
this.set('showResults', true);
let url = config.apiUrl + '/repository/lookup';
let baseUrl=this.get('podUrl');
if (this.get('useDev')) {
baseUrl=this.get('devUrl')
}
let options = {
method: 'GET',
data: {
dataId: JSON.stringify(this.searchDataId.split()),
base_url: baseUrl
}
};
let self = this;
return self.get('authRequest').send(url, options)
.then(rep => {
self.set('error', false);
self.set('num_results', rep.length);
self.datasources.pushObjects(rep);
if(rep.length === 1) {
let name = self.datasources[0].name;
let dataId = self.datasources[0].dataId;
Ember.run.later(self, function() {
Ember.$('#harvester-dropdown').dropdown('set text', name);
Ember.$('#harvester-dropdown').dropdown('set value', dataId);
}, 250);
}
else {
Ember.$('#harvester-dropdown').dropdown('set visible');
Ember.$('#harvester-dropdown').dropdown('set active');
let menu = Ember.$('#harvester-dropdown .menu');
menu.removeClass('hidden');
menu.addClass('transition visible');
}
})
.catch(e => {
console.log("Error: " + e);
self.set('error', true);
self.set('errorMessage', 'No matching results found.');
self.disableRegister();
})
.finally((_) => {
self.set('searching', false);
});
}
}
});
| JavaScript | 0 | @@ -1044,75 +1044,8 @@
v2',
-%0A // Flag that controls the grey background%0A showGrey: false,
%0A%0A
|
8b5bac293533589ed8d905e646c929511a826e9f | Allow borders in cloudinary-url | src/core/cloudinary-url.js | src/core/cloudinary-url.js | // http://res.cloudinary.com/demo/image/upload/f_auto,q_auto,w_250,h_250,c_fit/sample.jpg
const defaultState = 'f_auto,q_auto,fl_lossy';
export default (url, { mode, maxWidth, maxHeight, width, height, cropX, cropY, quality, blur, retina } = {}, crop) => {
if (!mode) mode = 'fill';
if (retina && width) width *= 2;
if (retina && height) height *= 2;
if (retina && maxWidth) maxWidth *= 2;
if (retina && maxHeight) maxHeight *= 2;
if (!url) return url;
if (crop) {
width = crop[0];
height = crop[1];
cropX = crop[2];
cropY = crop[3];
}
if (url.indexOf('http://res.cloudinary.com/') === 0) {
url = url.split('ttp://res.cloudinary.com/').join('ttps://res.cloudinary.com/');
}
if (url.indexOf('https://res.cloudinary.com/') !== 0) return url;
let part = defaultState;
if (cropX !== undefined && cropY !== undefined) {
part = `x_${cropX},y_${cropY},w_${width},h_${height},c_crop/${part}`;
} else if (width && height) {
part = `w_${width},h_${height},c_${mode}/${part}`;
}
if (maxWidth || maxHeight) {
if (maxWidth) part += `,w_${maxWidth}`;
if (maxHeight) part += `,h_${maxHeight}`;
part += `,c_${mode}`;
}
if (quality) {
part += `,q_${quality}`;
}
if (blur) {
part += `,e_blur:${blur}`;
}
if (part === defaultState) {
part += ',q_75';
}
return url.replace('/upload/', `/upload/${part}/`);
};
| JavaScript | 0 | @@ -180,16 +180,24 @@
xHeight,
+ border,
width,
@@ -1330,24 +1330,148 @@
',q_75';%0A %7D
+%0A if (border) %7B%0A Object.keys(border).map((key) =%3E %7B%0A part = %60bo_$%7Bborder%5Bkey%5D%7Dpx_solid_$%7Bkey%7D/$%7Bpart%7D%60;%0A %7D);%0A %7D
%0A%0A return u
|
71dd3cbb35dffac4edcb662369f433fa693a0125 | Order props and methods on lambda context, add comment regarding prototype | src/createLambdaContext.js | src/createLambdaContext.js | const { randomId } = require('./utils');
// https://docs.aws.amazon.com/lambda/latest/dg/limits.html
// default function timeout in seconds
const DEFAULT_TIMEOUT = 900; // 15 min
/*
Mimicks the lambda context object
http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
*/
module.exports = function createLambdaContext(fun, provider, cb) {
const functionName = fun.name;
const timeout = (fun.timeout || provider.timeout || DEFAULT_TIMEOUT) * 1000;
const endTime = new Date().getTime() + timeout;
return {
/* Methods */
done: cb,
succeed: res => cb(null, res, true),
fail: err => cb(err, null, true),
getRemainingTimeInMillis: () => endTime - new Date().getTime(),
/* Properties */
functionName,
memoryLimitInMB: fun.memorySize || provider.memorySize,
functionVersion: `offline_functionVersion_for_${functionName}`,
invokedFunctionArn: `offline_invokedFunctionArn_for_${functionName}`,
awsRequestId: `offline_awsRequestId_${randomId()}`,
logGroupName: `offline_logGroupName_for_${functionName}`,
logStreamName: `offline_logStreamName_for_${functionName}`,
identity: {},
clientContext: {},
};
};
| JavaScript | 0 | @@ -360,17 +360,16 @@
, cb) %7B%0A
-%0A
const
@@ -543,20 +543,32 @@
/
-* M
+/ doc-deprecated m
ethods
- */
%0A
@@ -652,24 +652,119 @@
null, true),
+%0A%0A // methods%0A // NOTE: the AWS context methods are OWN FUNCTIONS (NOT on the prototype!)
%0A getRema
@@ -830,11 +830,11 @@
/
-* P
+/ p
rope
@@ -842,90 +842,103 @@
ties
- */
%0A
-functionName,%0A memoryLimitInMB: fun.memorySize %7C%7C provider.memorySiz
+awsRequestId: %60offline_awsRequestId_$%7BrandomId()%7D%60,%0A clientContext: %7B%7D,%0A functionNam
e,%0A
@@ -956,19 +956,16 @@
Version:
-
%60offlin
@@ -1000,24 +1000,42 @@
tionName%7D%60,%0A
+ identity: %7B%7D,%0A
invokedF
@@ -1100,70 +1100,8 @@
%7D%60,%0A
- awsRequestId: %60offline_awsRequestId_$%7BrandomId()%7D%60,%0A
@@ -1113,22 +1113,16 @@
oupName:
-
%60offlin
@@ -1176,21 +1176,16 @@
eamName:
-
%60offlin
@@ -1230,58 +1230,62 @@
-identity: %7B%7D,%0A clientContext: %7B%7D
+memoryLimitInMB: fun.memorySize %7C%7C provider.memorySize
,%0A
|
958e57e5869199781ef8dfe33b51052d38ed1b1b | add comment in reference section | app/src/containers/ReferenceSection/ReferenceSection.js | app/src/containers/ReferenceSection/ReferenceSection.js | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Reference, Slider, Divider } from 'components';
import './ReferenceSection.scss';
const ReferenceSection = ({
references
}) => (
<section className="reference-section">
<h1 className="section-header">References</h1>
<Divider />
<Slider>
{references.map((ref, i) =>
<div>
<Reference
key={i}
reference={ref}
/>
</div>
)}
</Slider>
<div className="owl-buttons">
<div className="owl-prev">
<i className="fa fa-angle-left"></i>
</div>
<div className="owl-next">
<i className="fa fa-angle-right"></i>
</div>
</div>
</section>
);
ReferenceSection.propTypes = {
references: PropTypes.array.isRequired
};
const mapStateToProps = (state) => ({
references: state.references
});
export default connect(mapStateToProps)(ReferenceSection);
| JavaScript | 0 | @@ -166,16 +166,44 @@
scss';%0A%0A
+// TODO: move to components%0A
const Re
|
0a946224a61fe5394f24997028cb9b4f654bf9c8 | Remove unused code to make Toolbar functional | app/routes/events/components/Toolbar.js | app/routes/events/components/Toolbar.js | // @flow
import { Component } from 'react';
import { Link, NavLink } from 'react-router-dom';
import Modal from 'app/components/Modal';
import Time from 'app/components/Time';
import EventEditor from './EventEditor';
import styles from './Toolbar.css';
import type { ActionGrant } from 'app/models';
import cx from 'classnames';
type Props = {
actionGrant: ActionGrant,
};
type State = {
editorOpen: boolean,
};
class Toolbar extends Component<Props, State> {
state = {
editorOpen: false,
};
render() {
const { actionGrant } = this.props;
return (
<div className={styles.root}>
<div className={styles.time}>
<Time format="ll" className={styles.timeNow} />
</div>
<NavLink
exact
to="/events"
activeClassName={styles.active}
className={cx(styles.pickerItem, styles.list)}
>
Liste
</NavLink>
<NavLink
to="/events/calendar"
activeClassName={styles.active}
className={cx(styles.pickerItem, styles.calender)}
>
Kalender
</NavLink>
<div className={styles.create}>
{actionGrant?.includes('create') && (
<Link to="/events/create">Lag nytt</Link>
)}
</div>
<Modal
keyboard={false}
show={this.state.editorOpen}
onHide={() => this.setState({ editorOpen: false })}
closeOnBackdropClick={false}
>
<EventEditor />
</Modal>
</div>
);
}
}
export default Toolbar;
| JavaScript | 0.000001 | @@ -7,43 +7,8 @@
ow%0A%0A
-import %7B Component %7D from 'react';%0A
impo
@@ -64,121 +64,38 @@
ort
-Modal from 'app/components/Modal';%0Aimport Time from 'app/components/Time';%0Aimport EventEditor from './EventEditor
+Time from 'app/components/Time
';%0Ai
@@ -257,209 +257,54 @@
%7D;%0A%0A
-type State = %7B%0A editorOpen: boolean,%0A%7D;%0A%0Aclass Toolbar extends Component%3CProps, State%3E %7B%0A state = %7B%0A editorOpen: false,%0A %7D;%0A%0A render() %7B%0A const %7B actionGrant %7D = this.props;%0A return
+const Toolbar = (%7B actionGrant %7D: Props) =%3E
(%0A
-
%3Cd
@@ -331,20 +331,16 @@
.root%7D%3E%0A
-
%3Cdiv
@@ -371,20 +371,16 @@
%3E%0A
-
%3CTime fo
@@ -419,28 +419,24 @@
Now%7D /%3E%0A
-
-
%3C/div%3E%0A%0A
@@ -431,28 +431,24 @@
%3C/div%3E%0A%0A
-
-
%3CNavLink%0A
@@ -454,22 +454,14 @@
-
-
exact%0A
-
@@ -475,20 +475,16 @@
events%22%0A
-
ac
@@ -511,36 +511,32 @@
s.active%7D%0A
-
className=%7Bcx(st
@@ -566,34 +566,26 @@
.list)%7D%0A
- %3E%0A
+%3E%0A
Liste%0A
@@ -584,20 +584,16 @@
Liste%0A
-
%3C/Na
@@ -596,28 +596,24 @@
%3C/NavLink%3E%0A%0A
-
%3CNavLink
@@ -619,20 +619,16 @@
k%0A
-
to=%22/eve
@@ -641,20 +641,16 @@
lendar%22%0A
-
ac
@@ -685,20 +685,16 @@
%7D%0A
-
-
classNam
@@ -736,34 +736,26 @@
ender)%7D%0A
- %3E%0A
+%3E%0A
Kalend
@@ -757,20 +757,16 @@
alender%0A
-
%3C/Na
@@ -773,20 +773,16 @@
vLink%3E%0A%0A
-
%3Cdiv
@@ -815,20 +815,16 @@
%3E%0A
-
-
%7BactionG
@@ -853,20 +853,16 @@
') && (%0A
-
@@ -903,20 +903,16 @@
%3C/Link%3E%0A
-
)%7D
@@ -912,20 +912,16 @@
)%7D%0A
-
%3C/di
@@ -927,269 +927,19 @@
iv%3E%0A
-%0A %3CModal%0A keyboard=%7Bfalse%7D%0A show=%7Bthis.state.editorOpen%7D%0A onHide=%7B() =%3E this.setState(%7B editorOpen: false %7D)%7D%0A closeOnBackdropClick=%7Bfalse%7D%0A %3E%0A %3CEventEditor /%3E%0A %3C/Modal%3E%0A %3C/div%3E%0A );%0A %7D%0A%7D
+ %3C/div%3E%0A);
%0A%0Aex
|
216584c33080610dda2e2ba58a1c2cddd4df6a93 | load history new every time | app/scripts/history/historyDirective.js | app/scripts/history/historyDirective.js | 'use strict';
angular.module('CollaborativeMap')
.directive('history', ['$http', 'MapHandler',
function($http, MapHandler) {
function startCompare(objA, objB) {
var results = document.getElementById('results');
results.innerHTML = '';
compareTree(objA, objB, 'Feature', results);
}
function compareTree(a, b, name, results) {
var typeA = typeofReal(a);
var typeB = typeofReal(b);
var typeSpanA = document.createElement('span');
typeSpanA.appendChild(document.createTextNode('(' + typeA + ')'));
typeSpanA.setAttribute('class', 'diff-typeName');
var typeSpanB = document.createElement('span');
typeSpanB.appendChild(document.createTextNode('(' + typeB + ')'));
typeSpanB.setAttribute('class', 'diff-typeName');
var aString = (typeA === 'object' || typeA === 'array') ? '' : String(a) + ' ';
var bString = (typeB === 'object' || typeB === 'array') ? '' : String(b) + ' ';
var leafNode = document.createElement('span');
leafNode.appendChild(document.createTextNode(name));
if (a === undefined) {
leafNode.setAttribute('class', 'diff-added');
leafNode.appendChild(document.createTextNode(': ' + bString));
leafNode.appendChild(typeSpanB);
} else if (b === undefined) {
leafNode.setAttribute('class', 'diff-removed');
leafNode.appendChild(document.createTextNode(': ' + aString));
leafNode.appendChild(typeSpanA);
} else if (typeA !== typeB || (typeA !== 'object' && typeA !== 'array' && a !== b)) {
leafNode.setAttribute('class', 'diff-changed');
leafNode.appendChild(document.createTextNode(': ' + aString));
leafNode.appendChild(typeSpanA);
leafNode.appendChild(document.createTextNode(' => ' + bString));
leafNode.appendChild(typeSpanB);
} else {
leafNode.appendChild(document.createTextNode(': ' + aString));
leafNode.appendChild(typeSpanA);
}
if (typeA === 'object' || typeA === 'array' || typeB === 'object' || typeB === 'array') {
var keys = [];
for (var i in a) {
if (a.hasOwnProperty(i)) {
keys.push(i);
}
}
for (var i in b) {
if (b.hasOwnProperty(i)) {
keys.push(i);
}
}
keys.sort();
var listNode = document.createElement('ul');
listNode.appendChild(leafNode);
for (var i = 0; i < keys.length; i++) {
if (keys[i] === keys[i - 1]) {
continue;
}
var li = document.createElement('li');
listNode.appendChild(li);
compareTree(a && a[keys[i]], b && b[keys[i]], keys[i], li);
}
results.appendChild(listNode);
} else {
results.appendChild(leafNode);
}
}
function isArray(value) {
return value && typeof value === 'object' && value.constructor === Array;
}
function typeofReal(value) {
return isArray(value) ? 'array' : typeof value;
}
return {
restrict: 'E', // E = Element, A = Attribute, C = Class, M = Comment
templateUrl: 'partials/history',
replace: true,
// transclude: true,
// compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
link: function($scope) { //, iElm, iAttrs, controller) {
var visible = false;
$scope.hideDocumentRevisionView = false;
$scope.hideDiffView = true;
function loadHistory(fid) {
$http({
method: 'GET',
url: '/api/documentRevisions/' + $scope.mapId + '/' + fid
})
.
success(function(data) { //, status, headers, config) {
console.log(data);
$scope.documentRevision = data;
})
.
error(function(data) { //, status, headers, config) {
console.log(data);
});
}
$scope.revertFeature = function(id, rev) {
MapHandler.revertFeature($scope.mapId, id, rev, $scope.userName);
};
$scope.toggleHistoryModal = function(fid) {
visible = !visible;
$('#historyModal').modal('toggle');
if (visible) {
loadHistory(fid);
}
};
$scope.closeDiffView = function(){
console.log('close');
$scope.hideDocumentRevisionView = false;
$scope.hideDiffView = true;
};
$scope.showChanges = function(fid, rev, index){
var length = $scope.documentRevision.length;
if(length >= index + 1){
startCompare($scope.documentRevision[index], $scope.documentRevision[index+1]);
}
$scope.hideDocumentRevisionView = true;
$scope.hideDiffView = false;
};
}
};
}
]);
| JavaScript | 0 | @@ -3742,26 +3742,263 @@
ion
-loadHistory(fid) %7B
+init() %7B%0A $scope.documentRevision = %5B%5D;%0A $scope.hideDocumentRevisionView = false;%0A $scope.hideDiffView = true;%0A %7D%0A%0A function loadHistory(fid) %7B%0A init();%0A console.log(%22load history%22);
%0A
@@ -4218,41 +4218,8 @@
) %7B%0A
- console.log(data);%0A
@@ -4704,37 +4704,8 @@
');%0A
- if (visible) %7B%0A
@@ -4730,30 +4730,16 @@
y(fid);%0A
- %7D%0A
@@ -4791,44 +4791,11 @@
on()
+
%7B%0A
- console.log('close');%0A
@@ -4953,16 +4953,17 @@
, index)
+
%7B%0A
@@ -5027,16 +5027,17 @@
if
+
(length
@@ -5049,16 +5049,17 @@
dex + 1)
+
%7B%0A
@@ -5140,17 +5140,19 @@
on%5Bindex
-+
+ +
1%5D);%0A
|
bf66f03495af5289338c0ec90956dad126ec8614 | update formula, simplify logic | app/scripts/infuse/dimInfuse.factory.js | app/scripts/infuse/dimInfuse.factory.js | (function() {
'use strict';
angular.module('dimApp')
.factory('infuseService', infuseService);
infuseService.$inject = [];
function infuseService() {
var _data = {
source: null,
targets: [],
infused: 0,
view: [],
infusable: [],
// huge props to /u/Apswny
// https://www.reddit.com/r/destinythegame/comments/3n6pox/python_infusion_calculator
getThreshold: function(target, source) {
if(source.tier === 'Exotic') {
// upgrade exotic with an exotic, threshold = 5
// else we're upgrading exotic with rare or legendary, threshold = 4
return target.tier === 'Exotic' ? 5 : 4;
}
// infusing a rare or legendary with a rare or legendary, threshold = 6
if((source.tier === 'Rare' || source.tier === 'Legendary') &&
(target.tier === 'Rare' || target.tier === 'Legendary')) return 6;
// otherwise we're upgradeing a rare/legendary with an exotic, threshold = 7
return 7;
},
calculate: function() {
var result = 0;
var source = _data.source.primStat.value;
// Exotics get 70%
var multiplier = (_data.source.tier === 'Exotic') ? 0.7 : 0.8;
for(var i=0;i<_data.targets.length;i++) {
var target = _data.targets[i].primStat.value;
// if we already have a partial
if (result > 0) {
var source = result;
}
// compute threshold
if (target - source <= _data.getThreshold(_data.targets[i], _data.source)) {
result = target;
} else {
result = Math.round((target - source) * multiplier + source);
}
}
return result;
}
};
return {
setSourceItem: function(item) {
// Set the source and reset the targets
_data.source = item;
_data.infused = 0;
_data.targets = [];
},
setInfusibleItems: function(items) {
_data.infusable = items;
_data.view = items;
},
toggleItem: function(item) {
// Add or remove the item from the infusion chain
var index = _.indexOf(_data.targets, item);
if (index > -1) {
_data.targets.splice(index, 1);
}
else {
_data.targets.push(item);
}
// Value of infused result
_data.infused = _data.calculate();
// The difference from start to finish
_data.difference = _data.infused - _data.source.primStat.value;
// let's remove the used gear and the one that are lower than the infused result
_data.view = _.chain(_data.infusable)
.difference(_data.targets)
.filter(function(item) {
return item.primStat.value > _data.infused;
})
.value();
},
data: _data,
}
}
})();
| JavaScript | 0.000515 | @@ -307,885 +307,195 @@
swny
-%0A // https://www.reddit.com/r/destinythegame/comments/3n6pox/python_infusion_calculator%0A getThreshold: function(target, source) %7B%0A if(source.tier === 'Exotic') %7B%0A // upgrade exotic with an exotic, threshold = 5%0A // else we're upgrading exotic with rare or legendary, threshold = 4%0A return target.tier === 'Exotic' ? 5 : 4;%0A %7D%0A%0A // infusing a rare or legendary with a rare or legendary, threshold = 6%0A if((source.tier === 'Rare' %7C%7C source.tier === 'Legendary') &&%0A (target.tier === 'Rare' %7C%7C target.tier === 'Legendary')) return 6;%0A%0A // otherwise we're upgradeing a rare/legendary with an exotic, threshold = 7%0A return 7;%0A %7D,%0A calculate: function() %7B%0A var result = 0;%0A var source = _data.source.primStat.value;%0A%0A // Exotics get 70%25%0A var multiplier
+ https://github.com/Apsu%0A calculate: function() %7B%0A var base = _data.source.primStat.value,%0A scaler = _data.source.tier === 'Exotic' ? 0.7 : 0.8,%0A step
=
-(
_dat
@@ -524,21 +524,16 @@
tic'
-)
?
-0.7 : 0.8
+4 : 6
;%0A%0A
@@ -543,46 +543,45 @@
-for(var i=0;i%3C_data.targets.length;i++
+_data.targets.forEach(function(target
) %7B%0A
@@ -603,32 +603,22 @@
arget =
-_data.
target
-s%5Bi%5D
.primSta
@@ -624,17 +624,17 @@
at.value
-;
+,
%0A
@@ -640,228 +640,59 @@
-// if we already have a partial%0A if (result %3E 0) %7B%0A var source = result;%0A %7D%0A // compute threshold %0A if (target - source %3C= _data.getThreshold(_data.targets%5Bi%5D, _data.source)
+ diff = target - base;%0A%0A if (diff %3C= step
) %7B%0A
@@ -703,22 +703,20 @@
-result
+base
= targe
@@ -753,15 +753,14 @@
-result
+base +
= Ma
@@ -772,47 +772,21 @@
und(
-(target - source) * multiplier + source
+diff * scaler
);%0A
@@ -797,32 +797,34 @@
%7D%0A %7D
+);
%0A return
@@ -823,22 +823,20 @@
return
-result
+base
;%0A
|
2b04347f93b2a731bc61f4910c8204b28285b60f | Add headers in the api request to update consigna | app/scripts/services/content-service.js | app/scripts/services/content-service.js | (function () {
'use strict';
angular
.module('moi.services')
.factory('ContentService', ContentService);
function ContentService($http,
$state,
ENV,
PopupService,
$q,
$auth) {
var service = {
readContent: readContent,
addNotesToContent: addNotesToContent,
recommendedContents: recommendedContents,
changeImageStatus: changeImageStatus,
getContent: getContent,
uploadConsigna: uploadConsigna
};
var popupOptions = { title: 'Error'};
return service;
function readContent(content) {
/*jshint camelcase: false */
var contentId = content.id,
neuronId = content.neuron_id;
return $http({
method: 'POST',
url: ENV.apiHost + '/api/neurons/' + neuronId + '/contents/' + contentId + '/read',
data: {}
}).then(function success(res) {
return res;
}, function error(err) {
popupOptions.content = err.statusText;
if(err.status === 422){
PopupService.showModel('alert', popupOptions, function() {
$state.go('tree', {
username: $auth.user.username
});
});
}else if(err.status !== 404){
PopupService.showModel('alert', popupOptions);
}
return $q.reject(err);
});
}
function addNotesToContent(content){
/*jshint camelcase: false */
var contentId = content.id,
neuronId = content.neuron_id,
userNotes = content.user_notes;
return $http({
method: 'POST',
url: ENV.apiHost + '/api/neurons/' + neuronId + '/contents/' + contentId + '/notes',
data: {note: userNotes}
}).then(function success(res) {
return res;
}, function error(err) {
if(err.status !== 404){
popupOptions.content = err.statusText;
PopupService.showModel('alert', popupOptions);
}
return err;
});
}
function recommendedContents(content){
/*jshint camelcase: false */
var neuronId = content.neuron_id,
kind = content.kind;
return $http({
method: 'GET',
url: ENV.apiHost + '/api/neurons/' + neuronId + '/recommended_contents/' + kind
}).then(function success(res) {
return res.data;
}, function error(err) {
if(err.status !== 404){
popupOptions.content = err.statusText;
PopupService.showModel('alert', popupOptions);
}
return err;
});
}
function changeImageStatus(params){
var contentId = params.contentId,
neuronId = params.neuronId;
return $http({
method: 'POST',
url: ENV.apiHost + '/api/neurons/' + neuronId + '/contents/' + contentId + '/media_open',
data: {
media_url: params.mediaUrl //jshint ignore:line
}
}).then(function success(res) {
return res;
}, function error(err) {
if(err.status !== 404){
popupOptions.content = err.statusText;
PopupService.showModel('alert', popupOptions);
}
return err;
});
}
function getContent(params) {
return $http({
method: 'GET',
url: ENV.apiHost + '/api/neurons/' + params.neuronId + '/contents/' + params.contentId
}).then(function success(res) {
return res.data;
}, function error(err) {
if(err.status !== 404){
popupOptions.content = err.statusText;
PopupService.showModel('alert', popupOptions);
}
});
}
function uploadConsigna(paramsData) {
return $http({
method: 'POST',
url: ENV.apiHost + '/api/content_validations/send_request',
data: paramsData
}).then(function success(res) {
return res;
}, function error(err) {
if(err.status !== 404){
popupOptions.content = err.statusText;
PopupService.showModel('alert', popupOptions);
}
return err;
});
}
}
})();
| JavaScript | 0 | @@ -3722,24 +3722,131 @@
ramsData) %7B%0A
+ var authHeaders = $auth.retrieveData('auth_headers');%0A authHeaders%5B'Content-Type'%5D = undefined;%0A
return
@@ -3846,32 +3846,32 @@
return $http(%7B%0A
-
method:
@@ -3970,16 +3970,46 @@
ramsData
+,%0A headers: authHeaders
%0A %7D
@@ -4245,35 +4245,46 @@
%0A return
+$q.reject(
err
+)
;%0A %7D);%0A
|
331d58d33c2ec62c1589307a73ed598eb68e6aa4 | add typeProperty and propsProperty to _FactoryMixin | src/dijit/_FactoryMixin.js | src/dijit/_FactoryMixin.js | define([
'dojo/_base/declare',
'dojo/dom-construct'
], function(declare, domConstruct) {
return declare(null, {
scaffoldClass: 'dcomponent',
factory: null,
_renderItem: function(item) {
if(!item.properties) {
item.properties = {};
}
item = this._mountOnChangeEvent(item);
var element = this._createElement(item);
return this._createScaffold(item, element);
},
_createElement: function(item) {
var node = domConstruct.create('span', null, this.containerNode);
return this.factory.createElement(item, node);
},
/**
* Overrideable
*/
_createScaffold: function(item, element) {
var scaffoldNode = domConstruct.create('span', {
'class': this.scaffoldClass
});
domConstruct.create('span', {
innerHTML: item.label,
'class': 'label'
}, scaffoldNode);
var elementNode = domConstruct.create('span', {
'class': 'element'
}, scaffoldNode);
domConstruct.place(element.domNode || element, elementNode, 'only');
return scaffoldNode;
},
_mountOnChangeEvent: function(item) {
var onChange = item.properties.onChange;
item.properties.onChange = this._onChange.bind(this, item, onChange);
console.log(item);
return item;
},
_onChange: function(item, callback, value) {
var props = item.properties;
if(props.hasOwnProperty('checked')) {
props.checked = value;
} else {
props.value = value;
}
this.set('skipRendering', true);
this.store.put(item).then((function() {
if(typeof callback === 'function') {
callback(value);
}
this.set('skipRendering', false);
}).bind(this));
},
_setStoreAttr: function(store) {
this.inherited(arguments);
if(store && this.factory && this.factory.isLoaded()) {
this._render();
}
},
_setFactoryAttr: function(factory) {
this._set('factory', factory);
this.factory.loaded.then(this._render.bind(this));
}
});
}); | JavaScript | 0 | @@ -151,24 +151,93 @@
nent',%0A %0A
+ typeProperty: 'type',%0A %0A propsProperty: 'properties',%0A %0A
factory:
@@ -300,46 +300,64 @@
item
-.properties) %7B%0A item.properties
+%5Bthis.propsProperty%5D) %7B%0A item%5Bthis.propsProperty%5D
= %7B
@@ -664,28 +664,66 @@
y.create
-Element(item
+(item%5Bthis.typeProperty%5D, item%5Bthis.propsProperty%5D
, node);
@@ -1345,35 +1345,44 @@
hange = item
-.properties
+%5Bthis.propsProperty%5D
.onChange;%0A
@@ -1390,27 +1390,36 @@
item
-.properties
+%5Bthis.propsProperty%5D
.onChang
@@ -1469,33 +1469,8 @@
e);%0A
- console.log(item);%0A
@@ -1572,19 +1572,28 @@
item
-.properties
+%5Bthis.propsProperty%5D
;%0A%0A
|
8caf1258287ed8cf4cd97353c25698d81b13f127 | Fix download url | app/scripts/services/opensensemapapi.js | app/scripts/services/opensensemapapi.js | (function () {
'use strict';
angular
.module('app.services')
.factory('OpenSenseMapAPI', OpenSenseMapAPI);
OpenSenseMapAPI.$inject = ['$http', '$q', '$window', '$httpParamSerializer'];
function OpenSenseMapAPI ($http, $q, $window, $httpParamSerializer) {
var service = {
getUrl: getUrl,
getBoxes: getBoxes,
getData: getData,
getBox: getBox,
getBoxLocations: getBoxLocations,
getSensors: getSensors,
getSensorData: getSensorData,
idwInterpolation: idwInterpolation,
postMeasurements: postMeasurements,
deleteMeasurements: deleteMeasurements,
getStats: getStats,
getStatisticalData: getStatisticalData
};
return service;
////
function success (response) {
return response.data;
}
function failed (error) {
return $q.reject(error.data);
}
function getUrl () {
return '@@OPENSENSEMAP_API_URL';
}
function getBoxes (data) {
return $http.get(getUrl() + '/boxes', data)
.then(success)
.catch(failed);
}
function getData (data) {
var query = $httpParamSerializer(data);
var url = encodeURI(getUrl() + '/boxes/data?' + query)
$window.open(url, '_blank');
}
function getStatisticalData (data) {
var query = $httpParamSerializer(data);
var url = encodeURI(getUrl() + '/statistics/descriptive?' + query)
$window.open(url, '_blank');
}
function getBox (boxId) {
return $http.get(getUrl() + '/boxes/' + boxId)
.then(success)
.catch(failed);
}
function getBoxLocations (boxId, data) {
return $http
.get(getUrl() + '/boxes/' + boxId + '/locations', data)
.then(success)
.catch(failed);
}
function getSensors (boxId) {
return $http.get(getUrl() + '/boxes/' + boxId + '/sensors')
.then(success)
.catch(failed);
}
function getSensorData (boxId, sensorId, data) {
return $http.get(getUrl() + '/boxes/' + boxId + '/data/' + sensorId, data)
.then(success)
.then(function (measurements) {
// attach an id to each measurement
for (var i = 0; i < measurements.length; i++) {
measurements[i].id = i;
}
return measurements;
})
.catch(failed);
}
function postMeasurements(boxId, measurements, format) {
var url = getUrl() + '/boxes/' + boxId + '/data';
return $http.post(url, measurements, {
headers: { 'content-type': format }
})
.then(success)
.catch(failed);
}
function deleteMeasurements (boxId, sensorId) {
var url = getUrl() + '/boxes/' + boxId + '/' + sensorId + '/measurements';
return $http.delete(url, {auth: true})
.then(success)
.catch(failed);
}
function idwInterpolation (data) {
return $http.get(getUrl() + '/statistics/idw', data)
.then(success)
.catch(failed);
}
function getStats () {
var url = getUrl() + '/stats';
return $http.get(url)
.then(success)
.catch(failed);
}
}
})();
| JavaScript | 0 | @@ -1163,34 +1163,24 @@
var url =
-encodeURI(
getUrl() + '
@@ -1192,33 +1192,33 @@
s/data?' + query
-)
+;
%0A $window.o
@@ -1351,18 +1351,8 @@
l =
-encodeURI(
getU
@@ -1392,17 +1392,17 @@
+ query
-)
+;
%0A $
|
0b65fe817a99177bd77d00cfd3ff04a56af1b007 | Use the new octocat library to list releases | src/releases.js | src/releases.js | 'use strict';
const github = require('../lib/github.js');
const releaseList = repo => {
return new Promise(resolve => {
github.repos.getReleases({
owner: 'ilios',
repo
}).then(response => {
const names = response.data.map(obj => obj.name);
resolve(names);
}).catch(err => {
console.error(`error: ${err}`);
});
});
};
const listFrontendReleases = (bot, message) => {
releaseList('frontend').then(response => {
bot.reply(message, response.join(', '));
});
};
module.exports = bot => {
bot.hears('frontend releases', 'direct_message,direct_mention,mention', listFrontendReleases);
};
| JavaScript | 0 | @@ -75,21 +75,36 @@
st =
+ async (owner,
repo
+)
=%3E %7B%0A
retu
@@ -103,149 +103,130 @@
%7B%0A
-return new Promise(resolve =%3E %7B%0A github.repos.getReleases(%7B%0A owner: 'ilios',%0A repo%0A %7D).then(
+try %7B%0A return await github.paginate(%0A 'GET /repos/:owner/:repo/releases',%0A %7B owner,
re
-s
po
-nse =%3E %7B%0A const names
+ %7D,%0A response
=
+%3E
res
@@ -244,76 +244,55 @@
map(
-obj =%3E obj.name);%0A resolve(
+release =%3E release.
name
-s
+)
);%0A
+%7D
- %7D).
catch
+
(e
-rr =%3E
+)
%7B%0A
-
cons
@@ -311,15 +311,38 @@
rror
+ unable to fetch releases
: $%7Be
-rr
%7D%60);
@@ -350,18 +350,22 @@
-%7D)
+return %5B%5D
;%0A %7D
-);%0A
%0A%7D;%0A
@@ -393,16 +393,22 @@
leases =
+ async
(bot, m
@@ -422,16 +422,39 @@
=%3E %7B%0A
+const releases = await
releaseL
@@ -457,16 +457,25 @@
aseList(
+'ilios',
'fronten
@@ -481,30 +481,10 @@
nd')
-.then(response =%3E %7B%0A
+;%0A
bo
@@ -502,22 +502,22 @@
sage, re
-sponse
+leases
.join(',
@@ -526,14 +526,8 @@
));%0A
- %7D);%0A
%7D;%0A%0A
|
2e12649d780d9e66eef40e48046f4a71c1b749c6 | test default param | arrow-function.js | arrow-function.js | // Use with traceur: traceur simple-generators.js --experimental
"use strict";
function Klass() {
this.value = 2;
this.test = (p, q) => p * q * this.value;
}
var klass = new Klass();
console.log(klass.test(3, 5)); | JavaScript | 0.000001 | @@ -136,16 +136,20 @@
= (p, q
+ = 6
) =%3E p *
@@ -222,10 +222,7 @@
st(3
-, 5
));
|
b0a1887334f51775f1a637e7c2e5598f217029fd | add tags page to public site | troposphere/static/js/public_site/routers/ApplicationRouter.js | troposphere/static/js/public_site/routers/ApplicationRouter.js | define(function (require) {
'use strict';
var Marionette = require('marionette'),
Root = require('components/Root.react'),
React = require('react'),
context = require('context'),
ApplicationListPage = require('components/applications/ApplicationListPage.react'),
ApplicationDetailsPage = require('components/applications/ApplicationDetailsPage.react'),
ApplicationSearchResultsPage = require('components/applications/ApplicationSearchResultsPage.react'),
Backbone = require('backbone');
var Router = Marionette.AppRouter.extend({
appRoutes: {
'': 'showApplications',
'images': 'showApplications',
'images/:id': 'showApplicationDetails',
'images/search/:query': 'showApplicationSearchResults',
'*path': 'defaultRoute'
}
});
var Controller = Marionette.Controller.extend({
render: function (content, route) {
var app = Root({
profile: context.profile,
content: content,
route: route || Backbone.history.getFragment()
});
React.render(app, document.getElementById('application'));
},
//
// Route handlers
//
defaultRoute: function () {
Backbone.history.navigate('', {trigger: true});
},
showApplications: function () {
this.render(ApplicationListPage(), ["images"]);
},
showApplicationDetails: function (appId) {
var content = ApplicationDetailsPage({
applicationId: appId
});
this.render(content, ["images"]);
},
showApplicationSearchResults: function (query) {
var content = ApplicationSearchResultsPage({
query: query
});
this.render(content, ["images", "search"]);
}
});
return {
start: function () {
var controller = new Controller();
var router = new Router({
controller: controller
});
}
}
});
| JavaScript | 0 | @@ -598,32 +598,127 @@
tsPage.react'),%0A
+ ImageTagsPage = require('components/applications/ImageTagsPage.react'),%0A
Backbone
@@ -890,32 +890,72 @@
wApplications',%0A
+ 'images/tags': 'showImageTags',%0A
'images/
@@ -1210,17 +1210,73 @@
var
-app = Roo
+Component = React.createFactory(Root);%0A var app = Componen
t(%7B%0A
@@ -1678,50 +1678,265 @@
-this.render(ApplicationListPage(), %5B%22image
+var Component = React.createFactory(ApplicationListPage);%0A this.render(Component(), %5B%22images%22%5D);%0A %7D,%0A%0A showImageTags: function () %7B%0A var Component = React.createFactory(ImageTagsPage);%0A this.render(Component(), %5B%22images%22, %22tag
s%22%5D)
@@ -2004,34 +2004,56 @@
var
-c
+Comp
on
-t
ent =
+React.createFactory(
ApplicationD
@@ -2058,24 +2058,58 @@
nDetailsPage
+);%0A var content = Component
(%7B%0A
@@ -2261,26 +2261,48 @@
var
-c
+Comp
on
-t
ent =
+React.createFactory(
Applicat
@@ -2321,18 +2321,18 @@
ultsPage
-(%7B
+);
%0A
@@ -2332,18 +2332,41 @@
-
+var content = Component(%7B
query: q
@@ -2369,25 +2369,16 @@
y: query
-%0A
%7D);%0A
|
6e45e676e04c9ed943a851adf88e349a49593447 | Remove unnecessary apply() for style listener function | draft-svg.js | draft-svg.js | (function() {
draft.View.mixin({
svg(width, height) {
this._svgMaxWidth = width || this._svgMaxWidth || this.width();
this._svgMaxHeight = height || this._svgMaxHeight || this.height();
if (this._svg === undefined) {
const NS = 'http://www.w3.org/2000/svg';
// const XMLNS = 'http://www.w3.org/2000/xmlns/';
// const XLINK = 'http://www.w3.org/1999/xlink';
const VERSION = '1.1';
var calcX = function(element) {
return draft.px(element.prop('x')) - element.width() / 2;
};
var calcY = function(element) {
return -draft.px(element.prop('y')) - element.height() / 2;
};
var domPrefix = `${this.doc.domID}:${this.domID}:svg`;
var domID = function(element) {
return `${domPrefix}:${element.domID}`;
};
var find = function(element) {
return document.getElementByID(domID(element));
};
var render = function(element) {
console.info('rendering svg:', element.domID);
var node = document.createElementNS(NS, element.type);
// TODO: separate listener for each property?
var listener;
var styleListener = function(prop, val) {
prop = prop.replace('.color', '').replace('.', '-');
var color = /^(fill|stroke)(-opacity)?$/;
var stroke = /^stroke-(width)?$/;
if (color.test(prop) || stroke.test(prop)) {
node.setAttribute(prop, val);
}
};
var setStyle = function(...args) {
element.on('change', styleListener);
for (let style of args) {
for (let prop of ['color', 'opacity', 'width']) {
prop = `${style}.${prop}`;
let val = element.prop(prop) || draft.defaults[prop];
styleListener.apply({target: element}, [prop, val]);
}
}
};
switch (element.type) {
case 'group':
node = document.createElementNS(NS, 'g');
for (let child of element.children) {
let childNode = render(child);
if (childNode) {
node.appendChild(childNode);
}
}
element.on('add', function(child) {
let childNode = render(child);
if (childNode) {
node.appendChild(childNode);
}
});
element.on('remove', function(child) {
node.removeChild(find(child));
});
// Falls through
case 'rect':
setStyle('fill', 'stroke');
listener = function(prop, val) {
val = draft.px(val);
switch (prop) {
case 'width':
node.setAttribute('width', val);
// Falls through
case 'x':
node.setAttribute('x', calcX(this.target));
break;
case 'height':
node.setAttribute('height', val);
// Falls through
case 'y':
node.setAttribute('y', calcY(this.target));
break;
}
};
break;
case 'circle':
setStyle('fill', 'stroke');
listener = function(prop, val) {
val = draft.px(val);
/* if (prop === 'cy') {
val *= -1;
}
node.setAttribute(prop, val); */
switch (prop) {
case 'r':
node.setAttribute('r', val);
break;
case 'x':
node.setAttribute('cx', val);
break;
case 'y':
node.setAttribute('cy', -val);
break;
}
};
break;
}
// TODO: support all elements
if (typeof listener === 'function') {
node.id = domID(element);
for (let prop in element.prop()) {
listener.apply({target: element}, [prop, element.prop(prop)]);
}
element.on('change', listener);
return node;
}
};
var svg = this._svg = document.createElementNS(NS, 'svg');
svg.setAttribute('xmlns', NS);
svg.setAttribute('version', VERSION);
// svg.setAttributeNS(XMLNS, 'xmlns:xlink', XLINK);
svg.id = domID(this);
var listener = function(prop) {
if (prop === 'width' || prop === 'height') {
// 1 SVG user unit = 1px
svg.setAttribute('viewBox', [
calcX(this.target), calcY(this.target),
this.target.width(), this.target.height()
].join(' '));
let zoom = Math.min(
draft.px(this.target._svgMaxWidth) / this.target.width(),
draft.px(this.target._svgMaxHeight) / this.target.height()
);
let svgWidth = this.target.width() * zoom;
let svgHeight = this.target.height() * zoom;
this.target._svg.setAttribute('width', svgWidth);
this.target._svg.setAttribute('height', svgHeight);
// console.info('aspect ratio:', this.target.aspectRatio);
}
};
listener.apply({target: this}, ['width']);
listener.apply({target: this}, ['height']);
this.on('change', listener);
svg.appendChild(render(this.parent));
}
return this._svg;
}
});
})();
| JavaScript | 0.000001 | @@ -1885,35 +1885,9 @@
ener
-.apply(%7Btarget: element%7D, %5B
+(
prop
@@ -1891,17 +1891,16 @@
rop, val
-%5D
);%0A
|
25fdae0c3337ad818a0c2cb1ac1b951734c54a3f | apply ui.FindUser on issue list | public/javascripts/service/hive.issue.List.js | public/javascripts/service/hive.issue.List.js | /**
* @(#)hive.issue.List.js 2013.03.13
*
* Copyright NHN Corporation.
* Released under the MIT license
*
* http://hive.dev.naver.com/license
*/
(function(ns){
var oNS = $hive.createNamespace(ns);
oNS.container[oNS.name] = function(htOptions){
var htVar = {};
var htElement = {};
/**
* initialize
*/
function _init(htOptions){
_initVar(htOptions || {})
_initElement(htOptions || {});
_attachEvent();
_initLabel(htOptions.htOptLabel);
_initPagination();
_setLabelColor();
}
/**
* initialize variables except element
*/
function _initVar(htOptions){
htVar.nTotalPages = htOptions.nTotalPages || 1;
}
/**
* initialize element
*/
function _initElement(htOptions){
htElement.welForm = $("form.form-search");
htElement.welFieldset = $("fieldset.properties");
htElement.welAssigneeId = htElement.welFieldset.find("button.active[data-assigneeId]");
htElement.welMilestoneId = htElement.welFieldset.find("button.active[data-milestoneId]");
htElement.welBtnOptions = htElement.welFieldset.find("div.controls button");
htElement.welBtnAdvance = $(".btn-advanced");
htElement.welPagination = $(htOptions.elPagination || "#pagination");
htElement.welLabels = $("button.issue-label[data-color]");
}
/**
* attach event handlers
*/
function _attachEvent(){
htElement.welForm.submit(_onSubmitForm);
htElement.welBtnOptions.click(_onClickBtnOptions);
htElement.welBtnAdvance.click(_onClickBtnAdvance);
}
/**
* on submit search form
*/
function _onSubmitForm(){
// AssigneeId
var sAssigneeId = htElement.welAssigneeId.attr("data-assigneeId")
if(typeof sAssigneeId != "undefined"){
htElement.welForm.append(_getHiddenInput("assigneeId", sAssigneeId));
}
// Milestone Id
var sMilestoneId = htElement.welMilestoneId.attr("data-milestoneId");
if(typeof sMilestoneId != "undefined"){
htElement.welForm.append(_getHiddenInput("milesone", sMilestoneId));
}
}
/**
* get HTMLInputElement <input type="hidden">
* @param {String} sName
* @param {String} sValue
* @returns {HTMLInputElement}
*/
function _getHiddenInput(sName, sValue){
return $('<input type="hidden" name="' + sName + '" value="' + sValue + '">')
}
/**
* on click button
*/
function _onClickBtnOptions(e){
var welTarget = $(e.target || e.srcElement || e.originalTarget);
if (welTarget.hasClass("active")) {
welTarget.removeClass("active");
return false;
}
}
function _onClickBtnAdvance(){
$(".inner").toggleClass("advanced");
}
/**
* initialize hive.Label
* @param {Hash Table} htOptions
*/
function _initLabel(htOptions){
hive.Label.init(htOptions);
}
/**
* update Pagination
* @requires hive.Pagination
*/
function _initPagination(){
hive.Pagination.update(htElement.welPagination, htVar.nTotalPages);
}
/**
* update Label color
*/
function _setLabelColor(){
var welLabel, sColor;
htElement.welLabels.each(function(){
welLabel = $(this);
sColor = welLabel.data("color");
welLabel.css("background-color", sColor);
welLabel.css("color", $hive.getContrastColor(sColor));
});
welLabel = sColor = null;
}
_init(htOptions);
};
})("hive.issue.List");
| JavaScript | 0 | @@ -664,16 +664,89 @@
s %7C%7C 1;%0A
+%09%09%09htVar.oTypeahead = new hive.ui.FindUser(%22input%5Bname=authorLoginId%5D%22);%0A
%09%09%7D%0A%09%09%0A%09
|
f931f287c449695b2261c61ea97da5d82193559f | increase d3 groups color scale | src/settings.js | src/settings.js | import 'd3'
import fillUpNestedObjects from './utils/fill_up_nested_objects'
const SETTINGS = {
chart: {
height: '400px',
width: '100%',
showDistX: false,
showDistY: false,
useVoronoi: true,
duration: 350,
color: d3.scale.category10().range(),
xAxis: {
tickFormat: '.02f'
},
yAxis: {
tickFormat: '.02f'
},
zoom: {
active: false,
extend: 100
},
}
}
function Opts(opts) {
return fillUpNestedObjects(opts, SETTINGS)
}
export default Opts
| JavaScript | 0.000004 | @@ -257,17 +257,17 @@
category
-1
+2
0().rang
|
242d8c9bdc8af245056a36735b3fdbe1b7592427 | Delete accidentally commited key | src/settings.js | src/settings.js | // Copyright (c) 2016 Alejandro Blanco <alejandro.b.e@gmail.com>
// MIT License
const settings = {
token: '287339343:AAEBqMm5I3XN80TY2lp4ACF6L9rp39XR6Jo',
maxResults: 10, // 50 is the maximum allowed by Telegram
bggClient: {
timeout: 10000, // timeout of 10s (5s is the default)
// see https://github.com/cujojs/rest/blob/master/docs/interceptors.md#module-rest/interceptor/retry
retry: {
initial: 100,
multiplier: 2,
max: 15e3
}
}
};
module.exports = settings;
| JavaScript | 0 | @@ -108,55 +108,42 @@
en:
-'287339343:AAEBqMm5I3XN80TY2lp4ACF6L9rp39XR6Jo'
+process.env.BGG_TELEGRAM_BOT_TOKEN
,%0A%0A
|
7ec5cab1c605250a0b57f683ef2b57d0d9885320 | comment out test for now | redef/catalinker/module-test/workflow_test.js | redef/catalinker/module-test/workflow_test.js | /*global require, it, describe, before, after, document, Promise*/
"use strict";
var chai = require("chai"),
expect = chai.expect,
sinon = require("sinon"),
axios = require("axios"),
fs = require("fs");
describe("Catalinker", function () {
describe("/Workflow", function () {
require('./testdom')('<html><body><div id="container"/></body></html>');
var testRactive, Main;
before(function (done) {
global.history = {
replaceState: function () {
}
}
// load module
Main = require("../client/src/main.js");
// STUBS
// http requests from axios used in module, faking returned promises
sinon.stub(axios, "get").callsFake(function (path) {
switch (path) {
case "/config":
return Promise.resolve({data: {
kohaOpacUri: "http://koha.deichman.no",
kohaIntraUri: "http://koha.deichman.no",
ontologyUri: "/services/ontology",
resourceApiUri: "/services/",
tabs: [
{
id: "confirm-person",
rdfType: "Work",
label: "Bekreft person",
inputs: [{rdfProperty: "creator", type: "searchable-with-result-in-side-panel"}],
nextStep: {
buttonLabel: "Bekreft verk",
createNewResource: "Work"
}
}
],
authorityMaintenance:[
{
inputs: [{
searchMainResource: {
label: 'label',
indexType: 'type'
}
}]
}
]
}});
case "/main_template.html":
return Promise.resolve({data: fs.readFileSync(__dirname + "/../public/main_template.html", "UTF-8") });
case "/services/ontology":
return Promise.resolve({data: fs.readFileSync(__dirname + "/mocks/ontology.json", "UTF-8") });
case "/services/work/w123456":
return Promise.resolve({data: fs.readFileSync(__dirname + "/mocks/w123456.json", "UTF-8") });
case "/services/person/h123456":
return Promise.resolve({data: fs.readFileSync(__dirname + "/mocks/h123456.json", "UTF-8") });
case "/services/publication/p123456":
return Promise.resolve({data: fs.readFileSync(__dirname + "/mocks/p123456.json", "UTF-8") });
case "/services/authorized_values/language":
return Promise.resolve({data: fs.readFileSync(__dirname + "/mocks/authorized_language.json", "UTF-8") });
case "/services/authorized_values/format":
return Promise.resolve({data: fs.readFileSync(__dirname + "/mocks/authorized_format.json", "UTF-8") });
case "/services/authorized_values/nationality":
return Promise.resolve({data: fs.readFileSync(__dirname + "/mocks/authorized_nationality.json", "UTF-8") });
case "/services/genre/m123456":
return Promise.resolve({data: fs.readFileSync(__dirname + "/mocks/m123456.json", "UTF-8") });
default:
if (/^\/(partials|templates)\//.test(path)) {
return Promise.resolve({data: fs.readFileSync(__dirname + "/../public" + path, "UTF-8") });
} else {
return Promise.reject({error: "not found: " + path})
}
}
});
// Stub creating new resource
sinon.stub(axios, "post").callsFake(function (path, data, headers) {
return Promise.resolve({data: {}, headers: { location: ""} });
});
// Stub updating resource
sinon.stub(axios, "patch").callsFake(function (path, data, headers) {
return Promise.resolve({data: {}, headers: { location: ""} });
});
// load module
Main.init('workflow').then(function (m) {
testRactive = Main.getRactive();
}).then(function () {
done();
}).catch(function (err) {
done(err);
});
});
after(function (done) {
axios.get.restore();
axios.post.restore();
axios.patch.restore();
done();
});
describe("Verksside", function () {
it("har riktig side-tittel", function (done) {
//console.log(document.body.innerHTML);
expect(document.querySelector("h2[data-automation-id='page-heading']").innerHTML).to.equal("Katalogisering og vedlikehold av samlingen");
done();
});
it("populerer med utvalgte faner fra /config", function (done) {
var tabs = document.querySelectorAll(".grid-tabs li");
expect(tabs.length).to.equal(2);
expect(tabs[0].children[0].id).to.equal("tab0");
done();
});
});
});
});
| JavaScript | 0 | @@ -206,16 +206,19 @@
%22fs%22);%0A%0A
+/*%0A
describe
@@ -4707,12 +4707,14 @@
;%0A %7D);%0A%7D);%0A
+*/
|
4993bfc08ff27224503d714496a2e57d541985fc | Fix missing `id` lens, failure to set `lens` property in AsyncUpdate constructor | src/sunshine.js | src/sunshine.js | /* @flow */
import Kefir from 'kefir'
import { id, get, set } from 'safety-lens/lens'
import type { Emitter, Property, Stream } from 'kefir'
import type { Lens_ } from 'safety-lens/lens'
export type Reducer_<State, Event> = (s: State, e: Event) => ?EventResult<State>
export type Reducer<State, Event> = [Class<Event>, Reducer_<State, Event>]
export type Reducers<State> = Iterable<Reducer<State, any>>
export type Include<State, NestedState> = [App<NestedState>, Lens_<State, NestedState>]
export type Includes<State> = Iterable<Include<State, any>>
export type EventResult<State> = {
state?: State,
asyncUpdate?: Promise<Updater<State>>,
events?: Iterable<Object>,
}
/*
* An `App` instance describes how a Sunshine app is initialized and functions.
* More specifically, an `App` is a factory for `Session` instances.
*/
class App<State> {
initialState: State;
reducers: Reducer<State, any>[];
includes: Include<State, any>[];
constructor(
initialState: State,
reducers: Reducers<State> = [],
includes: Includes<State> = [],
) {
this.initialState = initialState
this.reducers = Array.from(reducers)
this.includes = Array.from(includes)
Object.freeze(this)
Object.freeze(this.reducers)
Object.freeze(this.includes)
}
onEvent(...reducers: Reducer<State, any>[]): App<State> {
return new App(this.initialState, this.reducers.concat(reducers), this.includes)
}
include(...includes: Include<State, any>[]): App<State> {
return new App(this.initialState, this.reducers, this.includes.concat(includes))
}
run(): Session<State> {
const { initialState, reducers, includes } = this
return new Session(initialState, reducers, includes)
}
}
/* helpers for building reducers and includes */
function reduce<State, Event>(
eventType: Class<Event>,
reducer: Reducer_<State, Event>
): Reducer<State, Event> {
return [eventType, reducer]
}
function include<TopState, NestedState>(
app: App<NestedState>,
lens: Lens_<TopState, NestedState>
): Include<TopState, NestedState> {
return [app, lens]
}
/* helper functions for building EventResult<T> values */
function emit<T>(...events: Object[]): EventResult<T> {
return { events }
}
function update<State>(newState: State): EventResult<State> {
return { state: newState }
}
function updateAndEmit<State>(newState: State, ...events: Object[]): EventResult<State> {
return { state: newState, events }
}
function asyncUpdate<State>(asyncUpdate: Promise<Updater<State>>): EventResult<State> {
return { asyncUpdate }
}
/* special event types */
export type Updater<State> = (latestState: State) => State
// intentionally not exported
class AsyncUpdate<A,B> {
updater: Updater<B>;
lens: Lens_<A,B>;
constructor(updater: Updater<B>, lens: Lens_<A,B>) { this.updater = updater }
}
/* implementation */
/*
* A `Session` instance represents a running app. It exposes state as a Kefir
* `Property`, and accepts input events via an `emit` method.
*/
class Session<State> {
state: Property<State>;
events: Stream<Object>;
currentState: State;
_emitter: Emitter<Object>;
_reducers: Reducer<State,any>[];
_includes: Include<State,any>[];
constructor(
initialState: State,
reducers: Reducer<State, any>[],
includes: Include<State, any>[],
) {
const input = Kefir.stream(emitter => { this._emitter = emitter })
const output = input.scan(this._reduceAll.bind(this), initialState)
this.state = output
this.events = input
this._includes = includes
this.currentState = initialState
// special event reducers
this._reducers = reducers.concat([
reduce(AsyncUpdate, (state, { updater, lens }) => {
const newValue = updater(get(lens, state))
return update(
set(lens, newValue, state)
)
})
])
Object.freeze(this._reducers)
output.onValue(noop) // force observables to activate
}
emit<Event: Object>(event: Event) {
setTimeout(() => this._emitter.emit(event), 0);
}
_reduceAll(prevState: State, event: Object): State {
const nestedUpdates = this._includes.reduce(
(state, [app, lens]) => {
const prevNestedState = get(lens, prevState)
const nextNestedState = this._reduce(app.reducers, lens, prevNestedState, event)
return set(lens, nextNestedState, state)
},
prevState
)
const nextState = this._reduce(this._reducers, id, nestedUpdates, event)
this.currentState = nextState
return nextState;
}
_reduce<T>(reducers: Reducer<T,any>[], lens: Lens_<State,T>, prevState: T, event: Object): T {
const applicableReducers = reducers
.filter(([klass, _]) => event instanceof klass)
.map(([_, reducer]) => reducer)
const nextState = applicableReducers.reduce(
(state, reducer) => this._applyResult(lens, reducer(state, event), state),
prevState
)
return nextState
}
_applyResult<T>(lens: Lens_<State,T>, result: ?EventResult<T>, prevState: T): T {
if (!result) { return prevState }
const { state, asyncUpdate, events } = result
if (asyncUpdate) {
asyncUpdate.then(
updater => {
this.emit(new AsyncUpdate(updater, lens))
},
this._emitter.error
)
}
if (events) {
for (const event of events) {
this.emit(event)
}
}
return state || prevState
}
}
function noop () {}
export {
App,
Session,
asyncUpdate,
emit,
include,
reduce,
update,
updateAndEmit,
}
| JavaScript | 0.000001 | @@ -40,20 +40,16 @@
import %7B
- id,
get, se
@@ -2801,16 +2801,20 @@
%3CA,B%3E) %7B
+%0A
this.up
@@ -2828,16 +2828,39 @@
updater
+%0A this.lens = lens%0A
%7D%0A%7D%0A%0A%0A/
@@ -5456,16 +5456,53 @@
op () %7B%7D
+%0Afunction id%3CT%3E(x: T): T %7B return x %7D
%0A%0Aexport
|
8a73a24e7659f26ee92a569441d4b9c2e98e8835 | clean code | cron/heat_map.js | cron/heat_map.js | const async = require( 'async' );
// --------------------------------------------------------------------------------------
var exp = {}
// --------------------------------------------------------------------------------------
// perform heat map data counting
// --------------------------------------------------------------------------------------
exp.process_old_data = function (database, callback) {
// find the lowest date in database and go from that date to present
var date;
var current = new Date();
var curr_min = new Date(current.getFullYear(), current.getMonth(), current.getUTCDate(), 0, 0, 0, 0); // current day hh:mm:ss:ms set to 00:00:00:000
// find all, sort by timestamp, display only timestamp, display one document only
database.logs.find({ query : {}, $orderby : { timestamp : 1 } } , { timestamp : 1, _id : 0 }, { limit : 1 },
function(err, doc) {
var date = doc;
date = String(date[0]["timestamp"]); // get only string representation of date
var fields = date.split(" ");
var months = { // months dict for date constructor
"Jan" : 0,
"Feb" : 1,
"Mar" : 2,
"Apr" : 3,
"May" : 4,
"Jun" : 5,
"Jul" : 6,
"Aug" : 7,
"Sep" : 8,
"Oct" : 9,
"Nov" : 10,
"Dec" : 11
}
var min = new Date(fields[3], months[fields[1]], fields[2], 0, 0, 0, 0); // hh:mm:ss:ms set to 0
var max = new Date(fields[3], months[fields[1]], Number(fields[2]) + 1, 0, 0, 0, 0); // next day, hh:mm:ss:ms set to 0
// search uses lower than max condition !
// this date handling should guarantee correct interval for all processed records
async.whilst(function () {
return min < curr_min;
},
function(next) {
async.series([
function(done) {
search(database, min, max, done); // calls done when finished
},
function(done) {
min.setDate(min.getDate() + 1); // continue
max.setDate(max.getDate() + 1); // continue
done(null); // done
}
],
function(err, results) {
next(); // next whilst iteration
});
},
function(err) {
if(err)
console.log(err);
else
console.log("cron task mac_count finished processing old data");
callback(null, null);
});
});
};
// --------------------------------------------------------------------------------------
// perform heat map data counting
// --------------------------------------------------------------------------------------
exp.process_current_data = function (database)
{
var realms = [];
var curr = new Date(); // current day
var prev_min = new Date(curr.getFullYear(), curr.getMonth(), curr.getUTCDate() - 1, 0, 0, 0, 0); // previous day hh:mm:ss:ms set to 00:00:00:000
var prev_max = new Date(curr.getFullYear(), curr.getMonth(), curr.getUTCDate(), 0, 0, 0, 0); // current day hh:mm:ss:ms set to 00:00:00:000
// search uses lower than max condition !
database.realms.aggregate([
{ $project : { _id : 0, realm : 1 } }
],
function(err, items) {
for(var item in items)
realms.push(items[item].realm);
// debug
//realms = [ 'cvut.cz', 'fit.cvut.cz', 'cuni.cz' ];
search(database, realms, prev_min, prev_max);
});
}
// --------------------------------------------------------------------------------------
// process data of 2d matrix of all realms
// --------------------------------------------------------------------------------------
function search(database, realms, min, max, done)
{
async.forEachOf(realms, function (value_src, key_src, callback_src) { // loop realms as source
var item = {}; // database item
item.inst_name = realms[key_src];
item.timestamp = min;
item.institutions = [];
async.forEachOf(realms, function (value_dst, key_dst, callback_dst) { // loop realms as destination
database.logs.aggregate([
{ $match : { realm : realms[key_src], visinst : realms[key_dst], // search for source and destination
timestamp : { $gte : min, $lt : max } } }, // get data for one day
{ $group : { _id : { visinst : "$visinst" }, count : { $sum : 1 } } },
{ $project : { count : 1, _id : 0 } }
],
function(err, items) {
if(items.length != 0) { // non empty result
item.institutions.push({ inst_name : realms[key_dst], count : items[0].count}); // add to array
}
callback_dst(null);
});
}, function (err) {
if (err)
console.log(err);
else {
// save item
database.heat_map.update({ inst_name : item.inst_name, timestamp: item.timestamp }, item, { upsert : true },
function(err, result) {
if(err)
console.log(err);
callback_src(null); // continue when record is saved
});
}
});
}, function (err) {
if (err)
console.log(err);
if(done) { // callback is defined
done(null, null);
}
});
}
// --------------------------------------------------------------------------------------
// generate realm list for realms collection
// --------------------------------------------------------------------------------------
function generate_realms(database)
{
var realm_list = [];
// possible TODO - remove limitation just to .cz
database.logs.aggregate([
{ $match : { realm : /.*\.cz$/ } },
{ $project : { realm : { $toLower : "$realm" } } }, // use lower case to match all possible realm forms
{ $group : { _id : { realm : "$realm" } } },
{ $project : { realm : "$_id.realm", _id : 0 } }
],
function(err, items) {
for(var item in items)
realm_list.push(items[item].realm);
for(realm in realm_list) {
database.realms.update({ realm : realm_list[realm] }, { realm : realm_list[realm] }, { upsert : true },
function(err, result) {
if(err)
console.log(err);
});
}
});
}
module.exports = exp;
| JavaScript | 0.000008 | @@ -2373,17 +2373,16 @@
ask
-mac_count
+heat map
fin
@@ -2455,18 +2455,16 @@
%7D);%0A%7D;%0A
-%0A%0A
// -----
@@ -3392,77 +3392,8 @@
);%0A%0A
- // debug%0A //realms = %5B 'cvut.cz', 'fit.cvut.cz', 'cuni.cz' %5D;%0A
|
e079169d8f19a6eb2b06e22a2c1f57e1877fcf6e | fix broken export in ui | src/ui/index.js | src/ui/index.js | import * as facets from "./facets";
import * as overlay from "./overlay";
import * as results from "./results";
import * as searchInput from "./searchInput";
export { facets, overlay, results, searchInput };
| JavaScript | 0 | @@ -121,38 +121,24 @@
as
-searchInput from %22./searchInpu
+text from %22./tex
t%22;%0A
@@ -176,18 +176,11 @@
ts,
-searchInpu
+tex
t %7D;
|
490ef35deaf8ec6c29afca890d6182b824d24dda | create ui.removeNavigationButtons() | src/utils/ui.js | src/utils/ui.js | /**
* ui module provide ui functions
* @module utils/ui
*/
'use strict';
/**
* Append "previous page" and "next page" navigation buttons
* @function appendNavigationButtons
* @static
* @param {Paginator} paginator The instancied paginator binded to the matched editor.
* @returns void
*/
exports.appendNavigationButtons = function(paginator){
/**
* Validate input page rank and request a page change if input is valid
* @callback
* @param {Event} evt The change callback event
* @returns void
*/
function onInputRankChanges(evt){
var toPage;
var rank = evt.target.valueAsNumber;
var actualRank = paginator.getCurrentPage().rank;
if (rank !== actualRank) {
try {
toPage = paginator.getPage(rank);
paginator.gotoPage(toPage);
} catch (e) {
if (e instanceof require('../classes/paginator/errors').InvalidPageRankError) {
window.alert('Il n\'y a pas de page #'+rank);
console.log($(this));
$(this).val(actualRank);
} else throw e;
}
}
}
var navbar;
var navbarElements = {};
var body = $('body');
var btnSelector = '<a></a>';
var btnCommonClasses = 'btn glyphicon';
var btnCommonStyles = {'background': 'white', 'width':'100%', 'top':'0'};
// Create a div vertical wrapper to append nav elements into
navbar = $('<div></div>')
.attr('id','paginator-navbar')
.css({
'width': '60px',
'position': 'absolute',
'-moz-border-radius': '50%',
'-webkit-border-radius': '50%',
'border-radius': '50%',
'top': (window.screen.height/2 -35)+'px',
'right': '40px',
'z-index': '999'
}).appendTo(body);
// navigate to previous page
navbarElements.btnPrevious = $(btnSelector)
.attr('href','#')
.css($.extend(btnCommonStyles,{
'border-top-left-radius': '50%',
'border-top-right-radius': '50%',
'border-bottom-left-radius': '0',
'border-bottom-right-radius': '0'
}))
.addClass(btnCommonClasses + ' glyphicon-chevron-up')
.click(function(){
paginator.gotoPrevious();
return false;
})
.appendTo(navbar)
;
// input to show and control current page
navbarElements.inputRank = $('<input></input>')
.attr('type','number').attr('id','input-rank')
.css({ 'width': '100%', 'line-height': '30px', 'text-align': 'center' })
.change(onInputRankChanges).appendTo(navbar)
;
setTimeout(function(){
navbarElements.inputRank.val(paginator.getCurrentPage().rank);
},500);
// navigate to next page
navbarElements.btnNext = $(btnSelector)
.attr('href','#')
.css($.extend(btnCommonStyles,{
'width': '100%',
'border-top-left-radius': '0',
'border-top-right-radius': '0',
'border-bottom-left-radius': '50%',
'border-bottom-right-radius': '50%'
}))
.addClass(btnCommonClasses + ' glyphicon-chevron-down')
.click(function(){
paginator.gotoNext();
return false;
})
.appendTo(navbar)
;
};
exports.updatePageRankInput = function(rank){
$('#input-rank').val(rank);
};
| JavaScript | 0 | @@ -2998,16 +2998,162 @@
;%0A%7D;%0A%0A
+/**%0A * Remove navigation buttons%0A * @function%0A * @static%0A */%0Aexports.removeNavigationButtons = function()%7B%0A $('#paginator-navbar').remove();%0A%7D;%0A%0A
exports.
|
1c824703229059fe580727244fbf070df4ad6aa0 | fix condition | src/validate.js | src/validate.js | const supportedMethods = ['GET', 'POST', 'PUT', 'DELETE']
const validTypes = [null, '', 'arraybuffer', 'blob', 'document', 'text', 'json']
/**
* Validate HTTP method
* @param {String} method – HTTP method
* @return {String} error
*/
function validateMethod (method) {
if (!method) {
return `HTTP method is not specified`
}
if (typeof method !== 'string') {
return `HTTP method should be type of string`
}
if (supportedMethods.indexOf(method.toUpperCase()) >= 0) {
return `Http method ${method} is not supported`
}
}
/**
* Basicly validate url
* @param {String} url – URL
* @return {String} error
*/
function validateUrl (url) {
if (!url) {
return `Url is not specified`
}
if (typeof url !== 'string') {
return `Url should be type of string`
}
}
/**
* Validate header to all parts be strings
* @param {String} key – Header key
* @param {String} value – Header value
* @return {String} error
*/
function validateHeader (key, value) {
if (typeof key !== 'string' || typeof value !== 'string')
return `Parts of header ${key}:${value} must be strings`
}
/**
* Validate headers
* @param {Object} headers – headers
* @return {Array} error
*/
function validateHeaders (headers) {
const aggr = []
for (let [key, value] of headers)
aggr.push(validateHeader(key, value))
return aggr
}
/**
* Validates response type
* @param {string} type - response type
* @return {String} error
*/
function validateResponseType (type) {
if (validTypes.indexOf(type) >= 0)
return `Response content type ${type} is not supported`
}
/**
* @ignore
* Validate HTTP request model
* @param {String} url – url
* @param {String} method – HTTP method
* @param {Map} headers – HTTP headers
* @param {String} responseType – response type
* @return {Array} array of errors
*/
function validate (url, method, headers, responseType) {
return [validateUrl(url),
validateMethod(method),
validateResponseType(responseType)]
.concat(validateHeaders(headers)).filter(_ => !!_)
}
export default validate
| JavaScript | 0.000001 | @@ -472,18 +472,17 @@
Case())
-%3E=
+%3C
0) %7B%0A
@@ -1519,10 +1519,9 @@
pe)
-%3E=
+%3C
0)%0A
|
3efe7e4d3661f5c0c44138444ec01c5b67f2cf23 | Add createActivity function for a form | src/App.js | src/App.js | import React, { Component } from 'react';
import moment from 'moment';
import './css/styles.css';
import sampleActivities from './sampleActivities';
class App extends Component {
constructor(props) {
super(props);
this.loadSampleActivities = this.loadSampleActivities.bind(this);
}
state = {
activitiesByTimestamp: {},
activityTimestamps: [],
currentDay: moment().startOf('day')
};
renderActivity(timestamp,activity) {
return (
<div key={timestamp} className="row">
<p>{moment(+timestamp).format('MMMM DD, YYYY')}</p>
<p>{activity.description}</p>
</div>
)
}
loadSampleActivities() {
this.setState({
activityTimestamps: Object.keys(sampleActivities),
activitiesByTimestamp: sampleActivities,
})
}
addActivity(activity) {
const now = moment().format('x');
this.setState({
activitiesByTimestamp: {
...this.state.activitiesByTimestamp,
[now]: activity,
},
activityTimestamps: [...this.state.activityTimestamps, now]
})
}
choosePreviousDay() {
this.setState({
currentDay: this.state.currentDay.subtract(1, 'day')
})
}
chooseNextDay() {
this.setState({
currentDay: this.state.currentDay.add(1, 'day')
})
}
getCurrentDayTimestamps() {
const { currentDay, activityTimestamps } = this.state;
const start = +currentDay.startOf('day');
const end = +currentDay.endOf('day');
return activityTimestamps
.filter( timestamp => start <= +timestamp && timestamp <= end)
}
render() {
const { activitiesByTimestamp, currentDay } = this.state;
return (
<div className="container">
<div className="row row--center">
<div className="col">
Today daily tracker
</div>
</div>
<div className="row row--center">
current day: {currentDay.format('MMMM DD, YYYY')}
</div>
<div className="row row--center">
<div className="col--3">
<button onClick={this.loadSampleActivities}>Load sample activities</button>
</div>
</div>
{
this.getCurrentDayTimestamps()
.sort()
.reverse()
.map(timestamp => this.renderActivity(timestamp, activitiesByTimestamp[timestamp]))
}
</div>
);
}
}
export default App;
| JavaScript | 0.000001 | @@ -1284,16 +1284,204 @@
%7D)%0A %7D%0A%0A
+ createActivity(e) %7B%0A e.preventDefault();%0A const activity = %7B%0A description: this.description.value,%0A %7D%0A%0A this.addActivity(activity);%0A this.activityForm.reset();%0A %7D%0A%0A
getCur
|
818448baebf2c8ddb7dddf38136af7f036042bcb | Add en locale data and detect language using various methods | src/App.js | src/App.js | import React from 'react';
import {compose, branch, renderComponent} from 'recompose';
import {BrowserRouter, withRouter} from 'react-router-dom';
import {IntlProvider} from 'react-intl';
import Prepare from './pages/Prepare';
import Countdown from './pages/Countdown';
import './App.css';
const Screen = compose(
withRouter,
branch(
({location}) => !location.search,
renderComponent(Prepare),
renderComponent(Countdown)
)
)();
const navigator = window.navigator;
let language = (navigator && navigator.language) || 'en';
const App = () => (
<IntlProvider
locale={language}
>
<BrowserRouter>
<Screen />
</BrowserRouter>
</IntlProvider>
)
export default compose(
)(App);
| JavaScript | 0 | @@ -161,16 +161,31 @@
Provider
+, addLocaleData
%7D from '
@@ -302,16 +302,131 @@
.css';%0A%0A
+import messages from './i18n/messages.json';%0A%0Aimport en from 'react-intl/locale-data/en';%0AaddLocaleData(%5B...en%5D);%0A%0A
%0Aconst S
@@ -625,16 +625,18 @@
nguage =
+%0A
(naviga
@@ -664,76 +664,236 @@
uage
-) %7C%7C 'en';%0A%0Aconst App = () =%3E (%0A %3CIntlProvider%0A locale=%7Blanguage
+s && navigator.languages%5B0%5D) %7C%7C%0A (navigator && navigator.language) %7C%7C%0A 'en';%0Alanguage = language.split(%22-%22)%5B0%5D;%0A%0Aconst App = () =%3E (%0A %3CIntlProvider%0A locale=%7Blanguage%7D%0A defaultLocale='en'%0A messages=%7Bmessages%5Blanguage%5D
%7D%0A
|
1c8589692d28d600eb47cb9e6180138cf24754bb | remove unused require option | src/App.js | src/App.js |
var createClass = require('./functions/createClass');
var ServiceContainer = require('./ServiceContainer');
var Service = require('./Service');
var HashStateHandler = require('./HashStateHandler');
var PageView = require('./PageView');
var FrontController = require('./FrontController');
var Dispatcher = require('./Dispatcher');
var Router = require('./Router');
var App = createClass(
/** @lends App.prototype */
{
/**
* Convenient class for basic application structure. Contains service
* container with preddefined services:
*
* * ViewFactory
* * FrontController
* * PageView
*
* @constructs
*/
constructor: function(options)
{
var scope, element, require, middlewares, dispatcher;
this.options = options = options || {};
scope = options.scope || {};
element = options.element || null;
require = options.require || null;
var modules = options.modules || null;
this.env = options.env || { document: document, window: window };
this.dispatcher = null;
if(this.options.middlewares instanceof Array) middlewares = this.options.middlewares;
else middlewares = [];
var AppDispatcher;
// Dependency injection container configuration:
if(this.options.dispatcher)
{
AppDispatcher = new Service({
construct: Dispatcher,
args: [this.options.dispatcher.actions || {}],
shared: true
});
}
var AppHashStateHandler = new Service({
construct: HashStateHandler,
shared: true
});
var AppPageView = new Service({
construct: PageView,
args: [{
serviceContainer: '@',
element: element,
scope: scope,
env: this.env
}]
});
var AppRouter = new Service({
construct: Router,
shared: true
});
var AppFrontController = new Service({
construct: FrontController,
args: [{
serviceContainer: '@',
defaultView: 'AppPageView',
stateHandler: '@AppHashStateHandler',
dispatcher: AppDispatcher ? '@AppDispatcher' : undefined,
middlewares: middlewares,
element: null,
env: this.env
}],
shared: true
});
this.serviceContainer = new ServiceContainer();
this.serviceContainer.registerServices(options.services);
this.serviceContainer.registerServices({
AppPageView: AppPageView,
AppFrontController: AppFrontController,
AppDispatcher: AppDispatcher,
AppHashStateHandler: AppHashStateHandler,
AppRouter: AppRouter
});
if('services' in options) this.serviceContainer.registerServices(options.services);
return this;
},
/**
* Initiates application. Gets a 'frontController' service from container
* and calls its init method.
*
* @return {[type]} [description]
*/
init: function()
{
var frontControllerOptions = { element: this.options.element };
var frontController = this.frontController = this.serviceContainer.getService('AppFrontController', [frontControllerOptions]);
if(this.options.router)
{
var routerOptions = {
routes: this.options.router.routes || [],
params: this.options.router.params || null
};
if(this.options.router.params) routerOptions.params = this.serviceContainer.resolveParameters(this.options.router.params);
var router = this.serviceContainer.getService('AppRouter', [routerOptions]);
frontController.setRouter(router);
}
if(this.options.stateHandler)
{
frontController.setStateHandler(this.serviceContainer.resolveParameters(this.options.stateHandler));
}
if(this.options.defaultView)
{
frontController.setDefaultView(this.options.defaultView);
}
frontController.init();
},
/**
* Destroys the application
*/
destroy: function()
{
if(this.frontController) this.frontController.destroy();
},
/**
* Returns internal service container instance.
*
* @return {ServiceContainer} service container instance
*/
getServiceContainer: function()
{
return this.serviceContainer;
}
});
module.exports = App; | JavaScript | 0.000011 | @@ -673,17 +673,8 @@
ent,
- require,
mid
@@ -809,45 +809,8 @@
ll;%0A
-%09%09require = options.require %7C%7C null;%0A
%09%09va
|
f7e979d635f97bc823909234161c8640fb9ee312 | create react components from arrays of data I | src/App.js | src/App.js | import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(){
super();
this.state = {increasing: false}
}
update(){
ReactDOM.render(
<App val={this.props.val + 1}/>,
document.getElementById('root'))
}
componentWillReceiveProps(nextProps){
this.setState({increasing: nextProps.val > this.props.val})
}
shouldComponentUpdate(nextProps, nextState){
return nextProps.val % 5 === 0;
}
componentDidUpdate(prevProps, prevState){
console.log(`prevProps: ${prevProps.val}`);
}
render(){
console.log(this.state.increasing)
return (
<button onClick={this.update.bind(this)}>{this.props.val}</button>
)
}
}
App.defaultProps = {val: 0}
export default App; | JavaScript | 0 | @@ -144,435 +144,216 @@
= %7Bi
-ncreasing: false%7D%0A %7D%0A%0A update()%7B%0A ReactDOM.render(%0A %3CApp val=%7Bthis.props.val + 1%7D/%3E,%0A document.getElementById('root'))%0A %7D%0A%0A componentWillReceiveProps(nextProps)%7B%0A this.setState(%7Bincreasing: nextProps.val %3E this.props.val%7D)%0A %7D%0A%0A shouldComponentUpdate(nextProps, nextState)%7B%0A return nextProps.val %25 5 === 0;%0A %7D%0A%0A componentDidUpdate(prevProps, prevState)%7B%0A console.log(%60prevProps: $%7BprevProps.val%7D%60);
+tems: %5B%5D%7D%0A %7D%0A%0A componentWillMount()%7B%0A fetch('https://swapi.co/api/people/?format=json', %7Bmode: 'no-cors'%7D)%0A .then(response =%3E response.json)%0A .then((%7Bresults: items%7D) =%3E this.setState(%7Bitems%7D))
%0A %7D
@@ -374,20 +374,20 @@
-console.log(
+let items =
this
@@ -398,18 +398,12 @@
te.i
-ncreasing)
+tems
%0A
@@ -423,72 +423,74 @@
%3C
-button onClick=%7Bthis.update.bind(this)%7D%3E%7Bthis.props.val%7D%3C/button
+div%3E%0A %7Bitems.map(item =%3E %3Ch4%3E%7Bitem.name%7D%3C/h4%3E)%7D%0A %3C/div
%3E%0A
|
ec6fe614156746929aea3fd2d6e1311581798f68 | Add --version option | src/Cli.js | src/Cli.js | 'use strict';
const EventEmitter = require('events');
const Getopt = require('node-getopt');
const CliError = require('./CliError');
const Options = require('./Options');
const Runner = require('./Runner');
class Cli extends EventEmitter
{
constructor(argv, stdin, stdout, stderr)
{
super();
this.argv = argv;
this.stdin = stdin;
this.stdout = stdout;
this.stderr = stderr;
this.getopt = new Getopt([
['h', 'help', 'show this help'],
['I', 'ignore-json-error', 'ignore broken JSON'],
['v', 'verbose', 'display additional information'],
['S', 'sort-external-buffer-size=SIZE', 'use SIZE bytes for `sort` memory buffer'],
['B', 'sort-in-memory-buffer-length=ROWS', 'save up to ROWS rows for in-memory sort'],
['T', 'temporary-directory=DIR', 'use DIR for temporaries, not $TMPDIR or /tmp'],
['b', 'bind=BIND=VALUE+', 'bind valiable']
]);
this.getopt.setHelp(
'Usage: jl-sql [OPTIONS] SQL\n'
+ 'OPTIONS:\n'
+ '[[OPTIONS]]\n'
+ '\n'
+ 'See full documentation at https://github.com/avz/jl-sql\n'
);
this.getopt.error(this.onArgumentError.bind(this));
}
parseOptions()
{
const getopt = this.getopt.parse(this.argv.slice(1));
if (getopt.options.help) {
this.throwUsage();
}
if (!getopt.argv.length) {
this.throwArgumentError('SQL expected');
}
if (getopt.argv.length > 1) {
this.throwArgumentError('too many arguments');
}
const options = new Options(getopt.argv[0]);
if (getopt.options['ignore-json-error']) {
options.ignoreJsonErrors = true;
}
if (getopt.options.verbose) {
options.verbose = true;
}
if (getopt.options['temporary-directory']) {
options.tmpDir = getopt.options['temporary-directory'];
}
options.sortOptions = {
};
if (getopt.options['sort-external-buffer-size']) {
options.sortOptions.bufferSize = parseInt(getopt.options['sort-external-buffer-size']);
}
if (getopt.options['sort-in-memory-buffer-length']) {
options.sortOptions.inMemoryBufferSize = parseInt(getopt.options['sort-in-memory-buffer-length']);
} else {
options.sortOptions.inMemoryBufferSize = 10000;
}
if (getopt.options.bind) {
options.binds = this.parseBinds(getopt.options.bind);
}
return options;
}
parseBinds(binds)
{
const map = {};
for (const def of binds) {
const m = def.match(/^(::?)(.*?)=(.*)$/);
if (!m) {
this.throwArgumentError('wrong bind definition: ' + def);
}
const name = m[2];
const value = m[3];
const isArray = m[1] === '::';
if (isArray) {
if (name in map) {
if (!(map[name] instanceof Array)) {
this.throwArgumentError('bind name ::' + name + ' must not be mixed with :' + name);
}
map[name].push(value);
} else {
map[name] = [value];
}
} else {
if (name in map) {
if (map[name] instanceof Array) {
this.throwArgumentError('bind name ::' + name + ' must not be mixed with :' + name);
}
this.throwArgumentError('bind name :' + name + ' redefinition');
}
map[name] = value;
}
}
return map;
}
run()
{
const options = this.parseOptions();
const runner = new Runner(options);
runner.on('error', (err) => {
this.emit('error', err);
});
runner.on('warning', (warn) => {
this.emit('warning', warn);
});
runner.run(this.stdin, this.stdout, this.stderr);
}
throwUsage(code = 255)
{
this.throwArgumentError(null);
}
getUsage()
{
return this.getopt.getHelp();
}
throwArgumentError(message = null)
{
let m = '';
if (message !== null) {
m += 'ERROR: ' + message + '\n\n';
}
m += this.getUsage();
throw new CliError(m, 255);
}
throwRuntimeError(message)
{
throw new CliError(message, 1);
}
onArgumentError(err)
{
this.throwArgumentError(err.message);
}
}
module.exports = Cli;
| JavaScript | 0.000002 | @@ -864,17 +864,65 @@
liable'%5D
+,%0A%09%09%09%5B'', 'version', 'show version information'%5D
%0A
-
%09%09%5D);%0A%0A%09
@@ -1023,24 +1023,73 @@
'%0A%09%09%09+ '%5Cn'%0A
+%09%09%09+ 'Version: ' + this.versionString() + '%5Cn%5Cn'%0A
%09%09%09+ 'See fu
@@ -1306,24 +1306,24 @@
ons.help) %7B%0A
-
%09%09%09this.thro
@@ -1333,24 +1333,85 @@
age();%0A%09%09%7D%0A%0A
+%09%09if (getopt.options.version) %7B%0A%09%09%09this.throwVersion();%0A%09%09%7D%0A%0A
%09%09if (!getop
@@ -3574,16 +3574,303 @@
l);%0A%09%7D%0A%0A
+%09versionString()%0A%09%7B%0A%09%09const myVersion = require('../package').version;%0A%09%09const apiVersion = require('jl-sql-api').version %7C%7C 'X.X.X';%0A%0A%09%09return 'jl-sql v' + myVersion + ' (jl-sql-api v' + apiVersion + ')';%0A%09%7D%0A%0A%09throwVersion()%0A%09%7B%0A%09%09throw new CliError(this.versionString() + '%5Cn', 0);%0A%09%7D%0A%0A
%09getUsag
|
4f2a31f86eb45d7db4a58bed31756eda6f4ef03f | Update s3tiles.js | s3tiles.js | s3tiles.js | var aws = require('aws-sdk')
, util = require('util')
, fs = require('fs')
, path = require('path')
, url = require('url')
, qs = require('querystring')
, s3
;
var options = {
credentials: path.resolve(process.env.AWS_CREDENTIALS_FILE || './aws-credentials.json'),
region: process.env.AWS_REGION || 'us-east-1'
};
if (!fs.existsSync(options.credentials)) {
throw new Error ('AWS credentails file not found: %s', options.credentials);
}
aws.config.loadFromPath(options.credentials);
aws.config.update({region:options.region});
s3 = new aws.S3();
exports = module.exports = S3Tiles;
function S3Tiles(uri, callback) {
if (typeof uri === 'string') {
uri = url.parse(uri, true);
} else if (typeof uri.query === 'string') {
uri.query = qs.parse(uri.query);
}
this._isWriting = 0;
this.contentType = 'image/jpeg';
if (uri.hash) {
this.contentType = uri.hash.split('#')[1];
} else {
console.log('warning: no content-type specified, defaulting to %s.', this.contentType);
}
var bucket = this.bucket = uri.host;
this.tileset = uri.path.split('/')[1];
var that = this;
s3.headBucket({"Bucket":bucket})
.on('success', function(response) {
callback(null, that);
})
.on('error', function(err) {
s3.createBucket({"Bucket":bucket})
.on('success', function(response) {
callback(null, that);
})
.on('error', function(response) {
callback(new Error(util.format('error creating bucket %s', JSON.stringify(response))));
})
.send();
})
.send();
}
S3Tiles.registerProtocols = function(tilelive) {
tilelive.protocols['s3tiles:'] = S3Tiles;
};
S3Tiles.prototype.getTile = function(z, x, y, callback) {
if (typeof callback !== 'function') throw new Error('Callback needed');
var that = this;
s3.getObject({
Bucket: this.bucket,
Key: util.format('%s/%s/%s/%s', this.tileset, z, x, y),
})
.on('success', function(response) {
var options = {
'Content-Type': that.getMimeType(response.data.Body),
'Last-Modified': response.data.LastModified,
'ETag': response.data.ETag
};
callback(null, response.data.Body, options);
})
.on('error', function(err) {
return callback((new Error(err)));
})
.send();
}
S3Tiles.prototype.getGrid = function(z, x, y, callback) {
s3.getObject({
Bucket: this.bucket,
Key: util.format('%s/%s/%s/%s', this.tileset, z, x, y),
})
.on('success', function(err, data) {
if (err) {
return callback(new Error(err));
}
callback(null, data.Buffer);
})
.on('error', function(err) {
return callback((new Error(err)));
})
.send();
}
S3Tiles.prototype.getInfo = function(callback) {
callback(null, {
bounds: [-180, -90, 180, 90]
});
}
S3Tiles.prototype.startWriting = function(callback) {
if (typeof callback !== 'function') throw new Error('Callback needed');
this._isWriting ++;
callback(null);
}
S3Tiles.prototype.stopWriting = function(callback) {
if (typeof callback !== 'function') throw new Error('Callback needed');
this._isWriting --;
callback(null);
}
S3Tiles.prototype.putInfo = function(info, callback) {
if (typeof callback !== 'function') throw new Error('Callback needed');
callback(null);
}
S3Tiles.prototype.putTile = function(z, x, y, tile, callback) {
if (typeof callback !== 'function') throw new Error('Callback needed');
if (!this._isWriting) return callback(new Error('S3Tiles not in write mode'));
if (!Buffer.isBuffer(tile)) return callback(new Error('Image needs to be a Buffer'));
try {
s3.putObject({
Body: tile,
Bucket: this.bucket,
Key: util.format('%s/%s/%s/%s', this.tileset, z, x, y),
ContentType: this.contentType,
ACL: 'public-read'
}, function(err, data) {
if (err) {
return callback(err)
}
callback(null);
});
} catch(err) {
console.log('S3 Exception not handled: %s', util.inspect(err));
console.log('Retrying operation in 1 second');
var that = this;
setTimeout(function() {
that.putTile(z, x, y, tile, callback);
}, 1000);
}
}
S3Tiles.prototype.putGrid = function(z, x, y, grid, callback) {
if (typeof callback !== 'function') throw new Error('Callback needed');
callback(null);
}
S3Tiles.prototype.close = function(callback) {
callback(null);
}
S3Tiles.prototype.getMimeType = function(data) {
if (data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4E &&
data[3] === 0x47 && data[4] === 0x0D && data[5] === 0x0A &&
data[6] === 0x1A && data[7] === 0x0A) {
return 'image/png';
} else if (data[0] === 0xFF && data[1] === 0xD8 &&
data[data.length - 2] === 0xFF && data[data.length - 1] === 0xD9) {
return 'image/jpeg';
} else if (data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46 &&
data[3] === 0x38 && (data[4] === 0x39 || data[4] === 0x37) &&
data[5] === 0x61) {
return 'image/gif';
}
};
| JavaScript | 0 | @@ -917,111 +917,8 @@
1%5D;%0A
- %7D else %7B%0A console.log('warning: no content-type specified, defaulting to %25s.', this.contentType);%0A
%7D%0A
|
bd41bd594cb9646c5090c54de0bbb144ac3e46b5 | fix input type in examples | src/ng/filter/limitTo.js | src/ng/filter/limitTo.js | 'use strict';
/**
* @ngdoc filter
* @name limitTo
* @kind function
*
* @description
* Creates a new array or string containing only a specified number of elements. The elements
* are taken from either the beginning or the end of the source array, string or number, as specified by
* the value and sign (positive or negative) of `limit`. If a number is used as input, it is
* converted to a string.
*
* @param {Array|string|number} input Source array, string or number to be limited.
* @param {string|number} limit The length of the returned array or string. If the `limit` number
* is positive, `limit` number of items from the beginning of the source array/string are copied.
* If the number is negative, `limit` number of items from the end of the source array/string
* are copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
* had less than `limit` elements.
*
* @example
<example module="limitToExample">
<file name="index.html">
<script>
angular.module('limitToExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.letters = "abcdefghi";
$scope.longNumber = 2345432342;
$scope.numLimit = 3;
$scope.letterLimit = 3;
$scope.longNumberLimit = 3;
}]);
</script>
<div ng-controller="ExampleController">
Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
<p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
<p>Output letters: {{ letters | limitTo:letterLimit }}</p>
Limit {{longNumber}} to: <input type="integer" ng-model="longNumberLimit">
<p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
</div>
</file>
<file name="protractor.js" type="protractor">
var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
var longNumberLimitInput = element(by.model('longNumberLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
it('should limit the number array to first three items', function() {
expect(numLimitInput.getAttribute('value')).toBe('3');
expect(letterLimitInput.getAttribute('value')).toBe('3');
expect(longNumberLimitInput.getAttribute('value')).toBe('3');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
expect(limitedLetters.getText()).toEqual('Output letters: abc');
expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
});
it('should update the output when -3 is entered', function() {
numLimitInput.clear();
numLimitInput.sendKeys('-3');
letterLimitInput.clear();
letterLimitInput.sendKeys('-3');
longNumberLimitInput.clear();
longNumberLimitInput.sendKeys('-3');
expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: ghi');
expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
});
it('should not exceed the maximum size of input array', function() {
numLimitInput.clear();
numLimitInput.sendKeys('100');
letterLimitInput.clear();
letterLimitInput.sendKeys('100');
longNumberLimitInput.clear();
longNumberLimitInput.sendKeys('100');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
});
</file>
</example>
*/
function limitToFilter(){
return function(input, limit) {
if (isNumber(input)) input = input.toString();
if (!isArray(input) && !isString(input)) return input;
if (Math.abs(Number(limit)) === Infinity) {
limit = Number(limit);
} else {
limit = int(limit);
}
if (isString(input)) {
//NaN check on limit
if (limit) {
return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
} else {
return "";
}
}
var out = [],
i, n;
// if abs(limit) exceeds maximum length, trim it
if (limit > input.length)
limit = input.length;
else if (limit < -input.length)
limit = -input.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = input.length + limit;
n = input.length;
}
for (; i<n; i++) {
out.push(input[i]);
}
return out;
};
}
| JavaScript | 0 | @@ -1584,39 +1584,47 @@
o: %3Cinput type=%22
-integer
+number%22 step=%221
%22 ng-model=%22numL
@@ -1731,39 +1731,47 @@
o: %3Cinput type=%22
-integer
+number%22 step=%221
%22 ng-model=%22lett
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.