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
|
---|---|---|---|---|---|---|---|
398717726c06e289a1607d75fa6adcc00a051f8e | Remove unused variable | tests/unit/lib/remap.js | tests/unit/lib/remap.js | define([
'intern!object',
'intern/chai!assert',
'../../../lib/node!istanbul/lib/collector',
'../../../lib/loadCoverage',
'../../../lib/remap'
], function (registerSuite, assert, Collector, loadCoverage, remap) {
registerSuite({
name: 'remap-istanbul/lib/remap',
'remapping': function () {
var coverage = remap(loadCoverage('tests/unit/support/coverage.json'));
assert.instanceOf(coverage, Collector, 'Return values should be instance of Collector');
assert(coverage.store.map['tests/unit/support/basic.ts'],
'The Collector should have a remapped key');
assert.strictEqual(Object.keys(coverage.store.map).length, 1,
'Collector should only have one map');
var map = JSON.parse(coverage.store.map['tests/unit/support/basic.ts']);
assert.strictEqual(map.path, 'tests/unit/support/basic.ts');
assert.strictEqual(Object.keys(map.statementMap).length, 28, 'Map should have 28 statements');
assert.strictEqual(Object.keys(map.fnMap).length, 6, 'Map should have 6 functions');
assert.strictEqual(Object.keys(map.branchMap).length, 6, 'Map should have 6 branches');
},
'base64 source map': function () {
var coverage = remap(loadCoverage('tests/unit/support/inline-coverage.json'));
assert.instanceOf(coverage, Collector, 'Return values should be instance of Collector');
assert(coverage.store.map['tests/unit/support/basic.ts'],
'The Collector should have a remapped key');
assert.strictEqual(Object.keys(coverage.store.map).length, 1,
'Collector should only have one map');
var map = JSON.parse(coverage.store.map['tests/unit/support/basic.ts']);
assert.strictEqual(map.path, 'tests/unit/support/basic.ts');
assert.strictEqual(Object.keys(map.statementMap).length, 28, 'Map should have 28 statements');
assert.strictEqual(Object.keys(map.fnMap).length, 6, 'Map should have 6 functions');
assert.strictEqual(Object.keys(map.branchMap).length, 6, 'Map should have 6 branches');
},
'empty options': function () {
assert.throws(remap, TypeError);
},
'basePath' : function() {
var coverage = remap(loadCoverage('tests/unit/support/coverage.json'), {
basePath : 'foo/bar'
});
assert(coverage.store.map['foo/bar/basic.ts'], 'The base path provided should have been used');
assert.strictEqual(Object.keys(coverage.store.map).length, 1,
'Collector should only have one map');
var map = JSON.parse(coverage.store.map['foo/bar/basic.ts']);
assert.strictEqual(map.path, 'foo/bar/basic.ts', 'The base path should be used in the map as well');
},
'missing coverage source': function () {
var warnStack = [];
function warn() {
warnStack.push(arguments);
}
remap(loadCoverage('tests/unit/support/badcoverage.json'), {
warn: warn
});
assert.strictEqual(warnStack.length, 2, 'warn should have been called twice');
assert.instanceOf(warnStack[0][0], Error, 'should have been called with error');
assert.strictEqual(warnStack[0][0].message, 'Could not find file: "tests/unit/support/bad.js"',
'proper error message should have been returend');
assert.instanceOf(warnStack[1][0], Error, 'should have been called with error');
assert.strictEqual(warnStack[1][0].message, 'Could not find source map for: "tests/unit/support/bad.js"',
'proper error message should have been returend');
},
'missing source map': function () {
var coverage = loadCoverage('tests/unit/support/missingmapcoverage.json');
assert.throws(function () {
remap(coverage);
}, Error);
},
'unicode in map': function () {
var coverage = remap(loadCoverage('tests/unit/support/coverage-unicode.json'));
assert(coverage.store.map['tests/unit/support/unicode.ts'], 'The file should have been properly mapped.');
assert.strictEqual(Object.keys(coverage.store.map).length, 1,
'Collector should have only one map.');
},
'skip in source map': function () {
var coverage = remap(loadCoverage('tests/unit/support/coverage-skip.json'));
var coverageData = JSON.parse(coverage.store.map['tests/unit/support/basic.ts']);
assert.isTrue(coverageData.statementMap['18'].skip, 'skip is perpetuated');
assert.isUndefined(coverageData.statementMap['1'].skip, 'skip is not present');
assert.isTrue(coverageData.fnMap['5'].skip, 'skip is perpetuated');
assert.isUndefined(coverageData.fnMap['1'].skip, 'skip is not present');
},
'non transpiled coverage': function () {
var warnStack = [];
var coverage = remap(loadCoverage('tests/unit/support/coverage-import.json'), {
warn: function () {
warnStack.push(arguments);
}
});
var coverageData = JSON.parse(coverage.store.map['tests/unit/support/foo.js']);
assert.strictEqual(1, coverageData.statementMap['1'].start.line);
assert.strictEqual(1, warnStack.length);
assert.instanceOf(warnStack[0][0], Error, 'should have been called with error');
assert.strictEqual(warnStack[0][0].message, 'Could not find source map for: "tests/unit/support/foo.js"',
'proper error message should have been returend');
},
'exclude - string': function () {
var warnStack = [];
var coverage = remap(loadCoverage('tests/unit/support/coverage-import.json'), {
warn: function () {
warnStack.push(arguments);
},
exclude: 'foo.js'
});
assert.strictEqual(1, warnStack.length);
assert.strictEqual(warnStack[0][0], 'Excluding: "tests/unit/support/foo.js"');
},
'exclude - RegEx': function () {
var warnStack = [];
var coverage = remap(loadCoverage('tests/unit/support/coverage-import.json'), {
warn: function () {
warnStack.push(arguments);
},
exclude: /foo\.js$/
});
assert.strictEqual(1, warnStack.length);
assert.strictEqual(warnStack[0][0], 'Excluding: "tests/unit/support/foo.js"');
}
});
});
| JavaScript | 0.000015 | @@ -5495,39 +5495,24 @@
%5B%5D;%0A%09%09%09%0A%09%09%09
-var coverage =
remap(loadCo
|
3aa18b30575d851ece72de1ce1dadbfd18585331 | Fix donationsThermometer error when empty | app/javascript/state/thermometer/index.js | app/javascript/state/thermometer/index.js | // @flow
import type { ChampaignGlobalObject } from '../../types';
import { isEmpty, mapValues } from 'lodash';
export type Action =
| { type: '@@chmp:initialize', payload: ChampaignGlobalObject }
| { type: '@@chmp:thermometer:update', attrs: State }
| { type: '@@chmp:thermometer:increment', temperature: number };
export type State =
| {}
| {
active: boolean,
goals: { [currency: string]: number },
offset: number,
remainingAmounts: { [currency: string]: number },
title: ?string,
totalDonations?: { [currency: string]: number },
};
const defaults: State = {
active: false,
goals: {},
offset: 0,
remainingAmounts: {},
title: '',
totalDonations: {},
};
export default function reducer(
state?: State = defaults,
action: Action
): State {
switch (action.type) {
case '@@chmp:initialize':
return getStateFromChampaign(action.payload);
default:
return state;
}
}
export function update(attrs: State): Action {
return { type: '@@chmp:thermometer:update', attrs };
}
export function increment(temperature: number): Action {
return { type: '@@chmp:thermometer:increment', temperature };
}
function getStateFromChampaign(chmp: ChampaignGlobalObject): State {
const data = chmp.personalization.donationsThermometer;
if (isEmpty(data)) return { active: false };
return {
active: data.active,
offset: data.offset,
title: data.title,
goals: data.goals,
remainingAmounts: data.remaining_amounts,
totalDonations: data.total_donations,
};
}
| JavaScript | 0.000123 | @@ -610,111 +610,8 @@
= %7B
-%0A active: false,%0A goals: %7B%7D,%0A offset: 0,%0A remainingAmounts: %7B%7D,%0A title: '',%0A totalDonations: %7B%7D,%0A
%7D;%0A%0A
@@ -1235,23 +1235,8 @@
rn %7B
- active: false
%7D;%0A
|
321cfa90d832f8004ccc783eaf8cd7f29ab154ab | Fix crash when opening some new datasets | app/resonant-laboratory/models/Dataset.js | app/resonant-laboratory/models/Dataset.js | import MetadataItem from './MetadataItem';
import datalib from 'datalib';
let girder = window.girder;
let COMPATIBLE_TYPES = {
boolean: ['boolean'],
integer: ['integer', 'boolean'],
number: ['number', 'integer', 'boolean'],
date: ['date'],
string: ['string', 'date', 'number', 'integer', 'boolean'],
'string_list': ['string_list']
};
let VALID_EXTENSIONS = [
'csv',
'tsv',
'json'
];
let dictCompare = (a, b) => {
let aKeys = Object.keys(a);
let bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
for (let aKey of aKeys) {
if (!b.hasOwnProperty(aKey) || a[aKey] !== b[aKey]) {
return false;
}
}
return true;
};
let Dataset = MetadataItem.extend({
initialize: function () {
window.mainPage.loadedDatasets[this.getId()] = this;
this.rawCache = null;
this.parsedCache = null;
let meta = this.getMeta();
this.listenTo(this, 'rl:swapId', this.swapId);
let fileTypePromise;
if (meta.fileType) {
fileTypePromise = Promise.resolve(meta.fileType);
} else {
fileTypePromise = this.inferFileType();
}
let attributePromise;
if (meta.attributes) {
attributePromise = Promise.resolve(meta.attributes);
} else {
attributePromise = this.inferAttributes();
}
let prevFileType = this.getMeta('fileType');
let prevAttributes = this.getMeta('attributes');
Promise.all([fileTypePromise, attributePromise]).then(() => {
// Don't call save() if nothing changed
if (this.getMeta('fileType') !== prevFileType ||
!dictCompare(this.getMeta('attributes'), prevAttributes)) {
this.save().then(() => {
this.trigger('rl:changeType');
this.trigger('rl:changeSpec');
}).catch(errorObj => {
throw errorObj;
});
}
});
},
swapId: function (newData) {
window.mainPage.loadedDatasets[newData._id] = window.mainPage.loadedDatasets[newData._oldId];
delete window.mainPage.loadedDatasets[newData._oldId];
window.mainPage.loadedDatasets[newData._id].set(newData);
},
drop: function () {
this.dropped = true;
this.stopListening();
delete window.mainPage.loadedDatasets[this.getId()];
},
save: function () {
// It's possible for a dataset to be dropped from a collection
// (e.g. it's replaced with a copy). In this case, we want to
// stop all future attempts to save any changes to the dropped
// dataset)
if (this.dropped) {
return Promise.resolve();
} else {
return MetadataItem.prototype.save.apply(this).catch(this.saveFailure);
}
},
saveFailure: function (errorObj) {
window.mainPage.trigger('rl:error', errorObj);
},
loadData: function (cache = true) {
// TODO: support more file formats / non-Girder
// files (e.g. pasted browser data)
if (cache && this.rawCache !== null) {
return Promise.resolve(this.rawCache);
} else {
return Promise.resolve(girder.restRequest({
path: 'item/' + this.getId() + '/download',
type: 'GET',
error: null,
dataType: 'text'
})).then((data) => {
if (cache) {
this.rawCache = data;
}
return data;
}).catch(() => {
this.rawCache = null;
return null;
});
}
},
getSpec: function () {
let meta = this.getMeta();
let spec = {
name: this.name()
};
if (!meta.attributes) {
// We haven't inferred the attributes yet...
spec.attributes = {};
} else {
spec.attributes = meta.attributes;
}
return spec;
},
parse: function (cache = true) {
if (cache && this.parsedCache !== null) {
return Promise.resolve(this.parsedCache);
} else {
let parsedData;
return this.loadData().then(rawData => {
if (rawData === null) {
this.parsedCache = parsedData = null;
} else {
let meta = this.getMeta();
let formatPrefs = {
type: meta.fileType
};
if (meta.attributes) {
formatPrefs.parse = meta.attributes;
} else {
formatPrefs.parse = 'auto';
}
try {
parsedData = datalib.read(rawData, formatPrefs);
} catch (e) {
parsedData = null;
}
if (cache) {
this.parsedCache = parsedData;
}
}
return parsedData;
});
}
},
inferFileType: function () {
let fileType = this.get('name');
if (fileType === undefined || fileType.indexOf('.') === -1) {
fileType = 'txt';
} else {
fileType = fileType.split('.');
fileType = fileType[fileType.length - 1];
}
this.setMeta('fileType', fileType);
return fileType;
},
setFileType: function (fileType) {
this.setMeta('fileType', fileType);
return this.save().then(() => {
this.trigger('rl:changeType');
});
},
inferAttributes: function () {
return this.parse().then(data => {
let attributes;
if (data === null) {
attributes = {};
} else {
attributes = datalib.type.all(data);
}
this.setMeta('attributes', attributes);
return attributes;
});
},
setAttribute: function (attrName, dataType) {
let attributes = this.getMeta('attributes');
attributes[attrName] = dataType;
this.setMeta('attributes', attributes);
return this.save().then(() => {
this.trigger('rl:changeSpec');
});
}
});
Dataset.COMPATIBLE_TYPES = COMPATIBLE_TYPES;
Dataset.VALID_EXTENSIONS = VALID_EXTENSIONS;
export default Dataset;
| JavaScript | 0.000003 | @@ -428,16 +428,96 @@
b) =%3E %7B%0A
+ if (!(a instanceof Object) %7C%7C !(b instanceof Object)) %7B%0A return false;%0A %7D%0A
let aK
|
ef646ca6a9fdbc43ff709a6171053c63ca7188b2 | Remove console.log. | app/scripts/Widget/plugins/Match/Match.js | app/scripts/Widget/plugins/Match/Match.js | import React, { Component, PropTypes } from 'react'
import * as Paths from '../../../Paths'
import { isValidEmail } from '../../../../util/validation-helper'
import { Error, Input } from '../../../../components/FormUtil'
import { TellAFriend, OverlayWidget } from '../../../components'
import { addActivistMatch } from './actions'
import { Choices } from './components'
class Match extends Component {
constructor(props, context) {
super(props, context)
this.state = {
numberSelected: undefined,
letterSelected: undefined,
combined: false,
errors: []
}
}
redirectTo(e) {
const { mobilization, widget, editable } = this.props
if (e) e.preventDefault()
if (editable) {
this.context.router.transitionTo(
Paths.matchChoicesMobilizationWidget(mobilization.id, widget.id)
)
}
}
formIsValid() {
const { firstname, lastname, email } = this.state
let errors = []
if (!firstname) errors.push('O campo Nome não pode ficar em branco.')
if (!lastname) errors.push('O campo Sobrenome não pode ficar em branco.')
if (!email) errors.push('O campo Email não pode ficar em branco.')
else if (!isValidEmail(email)) errors.push('Email inválido.')
const hasErrors = errors.length !== 0
if (hasErrors) this.setState({ errors })
return !hasErrors
}
handleCombineClick(e) {
if (e) e.preventDefault()
if (this.formIsValid()) {
const { dispatch } = this.props
const { firstname, lastname, email } = this.state
const matchId = this.findMatchItem().id
const activist = { firstname, lastname, email }
console.log({ matchId, activist });
dispatch(addActivistMatch({ matchId, activist }))
this.setState({ combined: true })
}
}
enableMatchButton() {
const { selectedChoice1, selectedChoiceA } = this.state
return selectedChoice1 && selectedChoiceA
}
renderErrors() {
const { errors } = this.state
return (
errors.length > 0
&& <div>{errors.map(error => <Error message={error} />)}</div>
)
}
renderChoices() {
const {
selectedChoice1, selectedChoiceA,
name, email,
numberSelected, letterSelected
} = this.state
const { editable, loading } = this.props
const { widget: { settings: {
title_text,
labelChoices1, labelChoicesA,
choices1, choicesA
}}
} = this.props
const optionsChoices1 = choices1 ? choices1.split(',') : []
const optionsChoicesA = choicesA ? choicesA.split(',') : []
return (
<OverlayWidget editable={editable} onClick={::this.redirectTo}>
<div className="match-widget p3 bg-darken-3 relative">
<h2 className="mt0 mb3 center">{title_text}</h2>
<Choices
title={labelChoices1}
selected={this.state.numberSelected}
options={optionsChoices1}
onChange={(option) => {
this.setState({ selectedChoice1: option.target.value })
}}
classNames={['mb2']}
/>
<Choices
{ ...this.props }
title={labelChoicesA}
selected={this.state.letterSelected}
options={optionsChoicesA}
disabled={!(selectedChoice1)}
onChange={(option) => {
this.setState({ selectedChoiceA: option.target.value })
}}
classNames={['mb2']}
/>
<Input
uid="input-match-firstname"
type="text"
label="Nome"
placeholder="Insira aqui seu nome"
required={true}
onChange={e => { this.setState({ firstname: e.target.value }) }}
show={!!selectedChoiceA}
/>
<Input
uid="input-match-lastname"
type="text"
label="Sobrenome"
placeholder="Insira aqui seu sobrenome"
required={true}
onChange={e => { this.setState({ lastname: e.target.value }) }}
show={!!selectedChoiceA}
/>
<Input
uid="input-match-email"
type="email"
label="Email"
placeholder="Insira aqui seu email"
required={true}
onChange={e => { this.setState({ email: e.target.value }) }}
show={!!selectedChoiceA}
/>
{this.renderErrors()}
<button
className="match caps button bg-darken-4 p2 full-width mt1 mb2"
onClick={::this.handleCombineClick}
disabled={loading || !(this.enableMatchButton())}>
{loading ? 'Combinando...' : 'Combinar' }
</button>
</div>
</OverlayWidget>
)
}
findMatchItem() {
const { widget } = this.props
const matchList = widget.match_list.filter(match => {
const { first_choice, second_choice } = match
const { selectedChoice1, selectedChoiceA } = this.state
return first_choice === selectedChoice1 && second_choice === selectedChoiceA
})
if (matchList && matchList.length > 0) {
return matchList[0]
}
}
renderShareButtons() {
const matchItem = this.findMatchItem()
const { selectedChoice1, selectedChoiceA } = this.state
let combinationImageUrl = 'https://placeholdit.imgix.net/~text?txtsize=28&bg=e9e9e9&txtclr=364C'
+ '55&txt=300%C3%97300&w=300&h=300&txt=Imagem%20n%C3%A3o%20configurada'
let share = ''
if (matchItem) {
combinationImageUrl = matchItem.goal_image
share = Paths.shareMatchWrapper(matchItem.widget_id, matchItem.id)
}
////
// @todo
// - talvez prop `message` configurável?
////
return <TellAFriend {...this.props}
message="Resultado da sua combinação"
href={ window.location.origin + share }
imageUrl={combinationImageUrl}
imageWidth="100%" />
}
render() {
const { combined } = this.state
return (
<div>
{ combined ? this.renderShareButtons() : this.renderChoices() }
</div>
)
}
}
Match.propTypes = {
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired
}
Match.contextTypes = {
router: PropTypes.object.isRequired,
}
export default Match
| JavaScript | 0 | @@ -1632,50 +1632,8 @@
%7D%0A%0A
- console.log(%7B matchId, activist %7D);%0A
|
c70db31f7a58d516795f2ff4e4a29ff5a291d6c1 | Update misc.js | src/misc.js | src/misc.js | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
ext.comment = function(string) {};
ext.title_r = function() {
return document.title;
};
ext.title_s = function(string) {
document.title = string;
};
ext.page_back_r = function () {
return document.body.style.background;
};
ext.page_back_s = function (url) {
return document.body.style.background = "url(url) no-repeat right top";
};
// Block and block menu descriptions
var descriptor = {
blocks: [
[' ', '/ %s', 'comment', 'comment'],
["r", "tab name", "title_r"],
[" ", "Set tab name to %s", "title_s", "Hello World"],
["r", "page background", "page_back_r"],
[" ", "Set page background to %s", "page_back_s", "url"],
]
};
// Register the extension
ScratchExtensions.register('Mod - Misc', descriptor, ext);
})({});
| JavaScript | 0.000001 | @@ -675,19 +675,27 @@
= %22url(
-url
+%22 + url + %22
) no-rep
|
a59b98a1dfe7cfa511b57bd75ff213272de124cb | enforce callback | src/cli_list.js | src/cli_list.js | var _ = require("lodash");
var Table = require("cli-table");
var clc = require("cli-color");
var SauceBrowsers = require("./browsers");
module.exports = function (callback) {
console.log("Available Sauce Browsers:");
var browsers = SauceBrowsers.filter(function () { return true; });
var families = _.groupBy(browsers, function (browser) {
return browser.family;
});
var maxFamWidth = _.max(Object.keys(families), function (f) { return f.length; }).length + 5;
var maxCLIWidth = _.max(_.pluck(browsers, "id"), function (b) { return b.length; }).length + 5;
var maxBrowserWidth = _.max(browsers.map(function (b) { return b.desiredCapabilities.browserName || "Native app"; }), function (b) { return b.length; }).length + 5;
var maxVersionWidth = _.max(browsers.map(function (b) { return b.desiredCapabilities.version || b.desiredCapabilities.platformVersion; }), function (b) { return b.toString().length; }).length + 5;
var maxOSWidth = _.max(_.pluck(browsers, "desiredCapabilities.platform"), function (b) { return b.length; }).length + 5;
var maxDeviceWidth = _.max(_.map(browsers, function (b) {
return b.desiredCapabilities.deviceName || "Desktop";
}), function (b) { return b.length; }).length + 5;
var table = new Table({
head: ["Family", "Alias", "Browser/Env", "Version", "OS", "Device"],
colWidths: [maxFamWidth, maxCLIWidth, maxBrowserWidth, maxVersionWidth, maxOSWidth, maxDeviceWidth]
});
var count = 1;
Object.keys(families).sort().forEach(function (family) {
table.push([clc.red(family)]);
families[family].forEach(function (b) {
table.push([
clc.blackBright(count + "."),
b.id,
b.desiredCapabilities.browserName || "Native app",
b.desiredCapabilities.version || b.desiredCapabilities.platformVersion,
b.desiredCapabilities.platform,
(b.desiredCapabilities.deviceName ? clc.cyanBright(b.desiredCapabilities.deviceName) : "Desktop")
]);
count++;
});
});
if(callback){
callback(table);
}
}; | JavaScript | 0.000001 | @@ -1996,26 +1996,8 @@
);%0A%0A
- if(callback)%7B%0A
ca
@@ -2015,10 +2015,6 @@
e);%0A
- %7D%0A
%7D;
|
b1a7845386f262c05632ecdbac3d44b7f454a03e | Fix selector | R7.Documents.Dnn/js/selectDocuments.js | R7.Documents.Dnn/js/selectDocuments.js | function r7d_selectDocument(documentId, checked, value) {
var values = JSON.parse(value);
var index = values.indexOf(documentId);
if (checked) {
if (index < 0) {
values.push(documentId);
}
} else {
if (index >= 0) {
values.splice(index, 1);
}
}
return JSON.stringify(values);
}
function r7d_getModuleId(target) {
var c = $(target).closest("div.DnnModule").attr("class");
var moduleId = c.match("DnnModule-(\\d+)")[1];
return moduleId;
}
function r7d_selectDocument2(target) {
var documentId = $(target).data("document-id");
var moduleId = r7d_getModuleId(target);
var field = document.getElementById("dnn_ctr" + moduleId + "_ViewDocuments_hiddenSelectedDocuments");
field.value = r7d_selectDocument(documentId, target.checked, field.value);
}
function r7d_selectDeselectAll(target) {
var moduleId = r7d_getModuleId(target);
$("div.DnnModule-" + moduleId + " .EditCell input[type='checkbox']").prop("checked", target.checked).trigger("change");
}
| JavaScript | 0.000001 | @@ -945,13 +945,14 @@
%22 .
-EditC
+edit-c
ell
|
70022bbe7a319c03986e5f14ce80c5d0d5bd5ee5 | Use an ANSI colored prompt for the REPL | bin/client.js | bin/client.js | #!/usr/bin/env node
var repl = require('repl');
var util = require('util');
var fs = require('fs');
var path = require('path');
var program = require('commander');
var Chrome = require('../');
function display(object) {
return util.inspect(object, {
'colors': process.stdout.isTTY,
'depth': null
});
}
function inheritProperties(from, to) {
for (var property in from) {
to[property] = from[property];
}
}
///
function inspect(options, args) {
if (args.webSocket) {
options.chooseTab = args.webSocket;
}
if (args.protocol) {
options.protocol = JSON.parse(fs.readFileSync(args.protocol));
}
Chrome(options, function (chrome) {
// keep track of registered events
var registeredEvents = {};
var chromeRepl = repl.start({
'prompt': '>>> ',
'ignoreUndefined': true,
'writer': display
});
// make the history persistent
var history_file = path.join(process.env.HOME, '.cri_history');
require('repl.history')(chromeRepl, history_file);
function overridePrompt(string) {
// hack to get rid of the prompt (clean line and reposition cursor)
console.log('\033[2K\033[G%s', string);
chromeRepl.displayPrompt(true);
}
function overrideCommand(command) {
// hard code a callback to display the result
var override = function (params) {
command(params, function (error, response) {
var repr = {};
repr[error ? 'error' : 'result'] = response;
overridePrompt(display(repr));
});
};
// inherit the doc decorations
inheritProperties(command, override);
return override;
}
function overrideEvent(chrome, domainName, itemName) {
var event = chrome[domainName][itemName];
var eventName = domainName + '.' + itemName;
// hard code a callback to display the event data
var override = function (filter) {
// remove all the listeners (just one actually) anyway
chrome.removeAllListeners(eventName);
var status = {};
// a filter will always enable/update the listener
if (!filter && registeredEvents[eventName]) {
delete registeredEvents[eventName];
status[eventName] = false;
} else {
// use the filter (or true) as a status token
var statusToken = (filter ? filter.toString() : true);
status[eventName] = registeredEvents[eventName] = statusToken;
event(function (params) {
var repr = {};
if (filter) {
params = filter(params);
}
repr[eventName] = params;
overridePrompt(display(repr));
});
}
// show the registration status to the user
return status;
};
// inherit the doc decorations
inheritProperties(event, override);
return override;
}
// disconnect on exit
chromeRepl.on('exit', function () {
console.log();
chrome.close();
});
// exit on disconnection
this.on('disconnect', function () {
console.error('Disconnected.');
process.exit(1);
});
// add protocol API
chrome.protocol.domains.forEach(function (domainObject) {
// walk the domain names
var domainName = domainObject.domain;
chromeRepl.context[domainName] = {};
for (var itemName in chrome[domainName]) {
// walk the items in the domain and override commands and events
var item = chrome[domainName][itemName];
switch (item.category) {
case 'command':
item = overrideCommand(item);
break;
case 'event':
item = overrideEvent(chrome, domainName, itemName);
break;
}
chromeRepl.context[domainName][itemName] = item;
}
});
}).on('error', function (err) {
console.error('Cannot connect to Chrome:', err.toString());
});
}
function list(options, args) {
Chrome.List(options, function (err, tabs) {
if (err) {
console.error(err.toString());
process.exit(1);
}
console.log(display(tabs));
});
}
function _new(options, args) {
options.url = args;
Chrome.New(options, function (err, tab) {
if (err) {
console.error(err.toString());
process.exit(1);
}
console.log(display(tab));
});
}
function activate(options, args) {
options.id = args;
Chrome.Activate(options, function (err) {
if (err) {
console.error(err.toString());
process.exit(1);
}
});
}
function close(options, args) {
options.id = args;
Chrome.Close(options, function (err) {
if (err) {
console.error(err.toString());
process.exit(1);
}
});
}
function version(options, args) {
Chrome.Version(options, function (err, info) {
if (err) {
console.error(err.toString());
process.exit(1);
}
console.log(display(info));
});
}
function protocol(options, args) {
options.remote = args.remote;
Chrome.Protocol(options, function (err, protocol) {
if (err) {
console.error(err.toString());
process.exit(1);
}
console.log(display(protocol));
});
}
///
var action;
var actionArguments;
program
.option('-t, --host <host>', 'HTTP frontend host')
.option('-p, --port <port>', 'HTTP frontend port');
program
.command('inspect')
.description('inspect a Remote Debugging Protocol target')
.option('-w, --web-socket <url>', 'WebSocket URL')
.option('-j, --protocol <file.json>', 'Remote Debugging Protocol descriptor')
.action(function (args) {
action = inspect;
actionArguments = args;
});
program
.command('list')
.description('list all the available tabs')
.action(function () {
action = list;
});
program
.command('new [<url>]')
.description('create a new tab')
.action(function (args) {
action = _new;
actionArguments = args;
});
program
.command('activate <id>')
.description('activate a tab by id')
.action(function (args) {
action = activate;
actionArguments = args;
});
program
.command('close <id>')
.description('close a tab by id')
.action(function (args) {
action = close;
actionArguments = args;
});
program
.command('version')
.description('show the browser version')
.action(function () {
action = version;
});
program
.command('protocol')
.description('show the currently available protocol descriptor')
.option('-r, --remote', 'Attempt to fetch the protocol descriptor remotely')
.action(function (args) {
action = protocol;
actionArguments = args;
});
program.parse(process.argv);
// common options
var options = {
'host': program.host,
'port': program.port
};
if (action) {
action(options, actionArguments);
} else {
program.outputHelp();
process.exit(1);
}
| JavaScript | 0.000002 | @@ -846,11 +846,26 @@
': '
-%3E%3E%3E
+%5C033%5B32m%3E%3E%3E%5C033%5B0m
',%0A
|
70a79440ea0afa283fc83a3d2812a16e916836e5 | Define default implementation of accumulate polymorphic method. | core.js | core.js | /* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true browser: true devel: true
forin: true latedef: false globalstrict: true */
'use strict';
var create = Object.create
var Method = require('method')
var Box = require('./box')
// Define a shortcut for `Array.prototype.slice.call`.
var unbind = Function.call.bind(Function.bind, Function.call)
var slice = Array.slice || unbind(Array.prototype.slice)
var end = Box('end of the sequence')
exports.end = end
var accumulated = Box('Indicator that source has being accumulateed')
exports.accumulated = accumulated
var error = Box('error')
exports.error = error
var accumulate = Method()
exports.accumulate = accumulate
function accumulateEmpty(_, f, start) { f(end(), start) }
accumulate.define(undefined, accumulateEmpty)
accumulate.define(null, accumulateEmpty)
accumulate.define(Array, function(array, next, initial) {
var state = initial, index = 0, count = array.length
while (index < count) {
state = next(array[index++], state)
if (state && state.is === accumulated) break
}
next(end(), state)
})
function transformer(source, transform) {
return convert(source, function(self, next, initial) {
return accumulate(transform(source), next, initial)
})
}
exports.transformer = transformer
function convert(source, method) {
return accumulate.implement(create(source), method)
}
exports.convert = convert
function transform(source, f) {
return convert(source, function(self, next, initial) {
accumulate(source, function(value, result) {
return value && value.isBoxed ? next(value, result)
: f(next, value, result)
}, initial)
})
}
exports.transform = transform
function filter(source, predicate) {
/**
Composes filtered version of given `source`, such that only items contained
will be once on which `f(item)` was `true`.
**/
return transform(source, function(next, value, accumulated) {
return predicate(value) ? next(value, accumulated) : accumulated
})
}
exports.filter = filter
function map(source, f) {
/**
Composes version of given `source` where each item of source is mapped using `f`.
**/
return transform(source, function(next, value, accumulated) {
return next(f(value), accumulated)
})
}
exports.map = map
function take(source, n) {
/**
Composes version of given `source` containing only element up until `f(item)`
was true.
**/
return transformer(source, function(source) {
var count = n >= 0 ? n : Infinity
return transform(source, function(next, value, result) {
count = count - 1
return count === 0 ? next(accumulated(), next(value, result)) :
count > 0 ? next(value, result) :
next(accumulated(), result)
})
})
}
exports.take = take
function drop(source, n) {
/**
Reduces given `reducible` to a firs `n` items.
**/
return transformer(source, function(source) {
var count = n >= 0 ? n : 1
return transform(source, function(next, value, result) {
return count -- > 0 ? result :
next(value, result)
})
})
}
exports.drop = drop
function takeWhile(source, predicate) {
/**
Composes version of given `source` containing only firs `n` items of it.
**/
return transform(source, function(next, value, state) {
return predicate(value) ? next(value, state) :
next(accumulated(), state)
})
}
exports.takeWhile = takeWhile
function dropWhile(source, predicate) {
/**
Reduces `reducible` further by dropping first `n`
items to on which `f(item)` ruturns `true`
**/
return transformer(source, function(source) {
var active = true
return transform(source, function(next, value, result) {
return active && (active = predicate(value)) ? result :
next(value, result)
})
})
}
exports.dropWhile = dropWhile
function tail(source) {
return drop(source, 1)
}
exports.tail = tail
//console.log(into(skip(2, [ 1, 2, 3, 4, 5, 6 ])))
//
function append1(left, right) {
return convert({}, function(self, next, initial) {
accumulate(left, function(value, result) {
return value && value.is === end ? accumulate(right, next, result) :
next(value, result)
}, initial)
})
}
function append(left, right, rest) {
/**
Joins given `reducible`s into `reducible` of items
of all the `reducibles` preserving an order of items.
**/
return rest ? slice(arguments, 1).reduce(append1, left) :
append1(left, right)
}
exports.append = append
function capture(source, recover) {
return convert(source, function(self, next, initial) {
accumulate(source, function(value, result) {
if (value && value.is === error) {
accumulate(recover(value.value, result), next, result)
} else {
next(value, result)
}
}, initial)
})
}
exports.capture = capture
| JavaScript | 0 | @@ -680,16 +680,80 @@
Method(
+function(self, next, start) %7B%0A next(end(), next(self, start))%0A%7D
)%0Aexport
|
26b18511625dbc6416decfc56c41d41b372d402d | Find next staff | src/page.js | src/page.js | /*
Copyright (C) 2011 by Gregory Burlet, Alastair Porter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* Creates a new page
*
* @class Represents a page of music
*/
Toe.Model.Page = function() {
// initialize staves
this.staves = new Array();
}
Toe.Model.Page.prototype.constructor = Toe.Model.Page;
/**
* Set canvas width and height directly
*
* @methodOf Toe.Model.Page
* @param {Number} width Width of the page
* @param {Number} height Height of the page
*/
Toe.Model.Page.prototype.setDimensions = function(width, height) {
this.width = width;
this.height = height;
}
/**
* Calculate dimensions of page from bounding boxes within facsimile data in MEI file
*
* (.) <ulx,uly> (.)
*
*
* (.) <lrx,lry> (.)
*
* @methodOf Toe.Model.Page
* @param {jQuery Wrapped Element Set} meiZones bounding boxes from facsimile data from an MEI document
* @returns {Array} dimensions [width, height] of the canvas
*/
Toe.Model.Page.prototype.calcDimensions = function(meiZones) {
var max_x = 0;
var max_y = 0;
$(meiZones).each(function(it, el) {
var lrx = parseInt($(el).attr("lrx"));
var lry = parseInt($(el).attr("lry"));
if (lrx > max_x) {
max_x = lrx;
}
if (lry > max_y) {
max_y = lry;
}
});
// return page properties
return [max_x, max_y];
}
/**
* Given coordinates, find the index of the closest staff
*
* @methodOf Toe.Model.Page
* @param {Object} coords {x: , y:}
* @returns {Number} sInd
*/
Toe.Model.Page.prototype.getClosestStaff = function(coords) {
var sInd = this.staves.length-1;
// for each staff, except the last
for (var i = 0; i < this.staves.length-1; i++) {
if (coords.y < this.staves[i].zone.lry + (this.staves[i+1].zone.uly - this.staves[i].zone.lry)/2) {
// this is the correct staƒf
sInd = i;
break;
}
}
return this.staves[sInd];
}
/**
* Adds a given number of staves to the page
*
* @methodOf Toe.Model.Page
* @param {Toe.Model.Staff} staff the staff to add to the model
* @returns {Toe.Model.Page} pointer to the current page for chaining
*/
Toe.Model.Page.prototype.addStaff = function(staff) {
this.staves.push(staff);
// update view
$(staff).trigger("vRenderStaff", [staff]);
return this;
}
| JavaScript | 0.998782 | @@ -2952,24 +2952,455 @@
s%5BsInd%5D;%0A%7D%0A%0A
+/**%0A * Given a staff, get the next staff on the page%0A *%0A * @methodOf Toe.Model.Page%0A * @param %7BToe.Model.Staff%7D staff %0A * @returns %7BStaff%7D nextStaff the next staff%0A */%0AToe.Model.Page.prototype.getNextStaff = function(staff) %7B%0A // for each staff, except the last%0A for (var i = 0; i %3C this.staves.length-1; i++) %7B%0A if (staff == this.staves%5Bi%5D) %7B%0A return this.staves%5Bi+1%5D;%0A %7D%0A %7D%0A%0A return null;%0A%7D%0A%0A
/**%0A * Adds
|
cd849727f447d76e39248e24225ff7b2fef69f5d | Remove use of window inside closure | src/confetti.js | src/confetti.js | // Based off of http://stackoverflow.com/questions/16322869/trying-to-create-a-confetti-effect-in-html5-how-do-i-get-a-different-fill-color
// and http://codepen.io/linrock/pen/Amdhr
(function (global) {
'use strict';
var DEFAULT_NUM_CONFETTI = 500,
animate = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (cb) {
setTimeout(callback, 1000 / 60);
};
function Canvas(element, canvas) {
this.element = element;
this.canvas = canvas;
this.context = canvas.getContext('2d');
this.width = element.offsetWidth;
this.height = element.offsetHeight;
this.setDimensions = function () {
this.width = this.element.offsetWidth;
this.height = this.element.offsetHeight;
this.canvas.width = this.width;
this.canvas.height = this.height;
};
}
Canvas.prototype.step = function (particles, config) {
var canvas = this;
return function animator() {
if (canvas.halt) {
return;
}
var context = canvas.context;
context.clearRect(0, 0, canvas.width, canvas.height);
if (config.updateState) {
config.updateState();
}
for (var i = 0; i < particles.length; i++) {
config.draw(particles[i], i);
config.updatePosition(particles[i], i);
}
if (config.batch) {
context[(config.fill) ? 'fill' : 'stroke']();
}
global.Confetti.animate(canvas.step(particles, config));
};
};
Canvas.prototype.destroy = function () {
var canvas = this;
window.removeEventListener('resize', canvas.setDimensions);
canvas.halt = true;
};
function ConfettiClass(config) {
for (var prop in config) {
this[prop] = config[prop];
}
if (!config.d) {
this.d = randomFrom(10, DEFAULT_NUM_CONFETTI + 10);
}
if (!config.color) {
this.color = color();
}
}
ConfettiClass.prototype.isFlakeExiting = function (canvas) {
return (this.x > canvas.width + 5 || this.x < -5 || this.y > canvas.height);
};
global.Confetti = {
DEFAULT_NUM: DEFAULT_NUM_CONFETTI,
color: color,
randomFrom: randomFrom,
animate: animate.bind(global),
createCanvas: function (element, canvas) {
var newCanvas = new Canvas(element, canvas);
window.addEventListener('resize', newCanvas.setDimensions);
newCanvas.setDimensions();
return newCanvas;
},
create: function (config) {
return new ConfettiClass(config);
}
};
function color() {
return 'rgba(' + randomFrom(0, 256) + ', ' +
randomFrom(0, 256) + ', ' +
randomFrom(0, 256) + ', ' + Math.random() + ')';
}
function randomFrom(a, b, factor) {
if (!factor) {
factor = 1;
}
return a + (Math.floor((b - a) * Math.random() * factor) / factor);
}
})(window);
| JavaScript | 0.000001 | @@ -262,22 +262,22 @@
imate =
-window
+global
.request
@@ -302,22 +302,22 @@
-window
+global
.webkitR
@@ -348,22 +348,22 @@
-window
+global
.mozRequ
@@ -1603,22 +1603,22 @@
is;%0A
-window
+global
.removeE
@@ -2343,22 +2343,22 @@
;%0A
-window
+global
.addEven
|
42476d365fb1e1e493e98fade100591530b87cd3 | Improve Pipe function | src/pipe.js | src/pipe.js | import _ from 'lodash';
import { isPipeline } from './Pipeline';
/**
* Pipes in pipeline can be functions (pipes) or pipeline (multiple pipes connected).
* When piping stream pipe is needed.
* @param pipeline
* @returns {*}
*/
function resolvePipe(pipeline) { // TODO - better name
if (isPipeline(pipeline)) {
// TODO - find better way then creating new function (optimization)
// Maybe bind when adding pipe?
return pipeline.pipe.bind(pipeline);
} else if (_.isFunction(pipeline)) {
return pipeline;
}
// pipeline = pipelineDescriptor
return resolvePipe(pipeline.pipe);
}
function transformOutStream(newStream, stream, pipeDescriptor) {
const { outTransformer } = pipeDescriptor;
return outTransformer ? outTransformer(newStream, stream) : newStream;
}
function transformInStream(stream, pipeDescriptor) {
const { inTransformer } = pipeDescriptor;
return inTransformer ? inTransformer(stream) : stream;
}
/**
* Premise.
* Instead passing next as argument, close is passed. Reason behind it is optimistic approach.
* More frequent case should be continuing flow, not closing, for that reason,
* simpler should be to continue then to stop.
*/
export default function pipe(stream, pipeline, index = 0) { // TODO - rename (and this file)
return new Promise((resolve, reject) => {
// Pipeline descriptor or pipe (a function or a pipeline) - TODO - standardise
const currentPipeDescriptor = _.isArray(pipeline) ? pipeline[index] : pipeline;
if (!currentPipeDescriptor) {
// No more pipes, resolve
resolve(stream);
return;
}
const currentPipe = resolvePipe(currentPipeDescriptor);
const inStream = transformInStream(stream, currentPipeDescriptor);
let closed = false;
// Close flow so that newStream doesn't go further.
const closePipe = (closedStream = stream) => {
// Helps handle both async and sync flows.
closed = true;
reject(closedStream);
};
// Only when stream is piped through nextPipe resolve current.
// This creates recursive mechanism resolving all from bottom to top.
// Final effect is pipes serialization.
const nextPipe =
nextStream =>
pipe(transformOutStream(nextStream, stream, currentPipeDescriptor), pipeline, index + 1)
.then(resolve)
// It is not needed to check here if flow is closed because nextPipe is only going
// to be called if previous passed or it was in parallel.
.catch(closePipe);
const newStream = currentPipe(inStream, closePipe);
if (closed) {
// Closed with closePipe function.
// It is a bit hidden relation but it simplifies closing pattern.
// Removes need to return anything when closing.
return;
}
// TODO - invalidate close after stream is piped (either sync or async)
// Once stream is piped close SHOULD NOT be called!
if (_.isUndefined(newStream)) {
// TODO - newStream === stream?
// Trying to preserve as much as possible JS practices
// Early return of `undefined` is one of them when nothing is done?
// However, returning same object would be more explicit.
nextPipe(stream);
} else if (newStream instanceof Promise) {
newStream.then(nextPipe).catch(closePipe);
} else if (_.isPlainObject(newStream)) {
nextPipe(newStream);
} else {
console.log('Invalid stream, must be object, undefined or promise.');
console.log('Stream value: ', newStream);
console.log('Pipe: ', pipeline);
closePipe(newStream);
}
});
}
| JavaScript | 0.000002 | @@ -315,117 +315,8 @@
) %7B%0A
- // TODO - find better way then creating new function (optimization)%0A // Maybe bind when adding pipe?%0A
@@ -339,23 +339,8 @@
pipe
-.bind(pipeline)
;%0A
@@ -1120,16 +1120,18 @@
x = 0) %7B
+%0A
// TODO
@@ -1139,28 +1139,82 @@
- re
-name (and this file)
+move new promise overhead for sync returns; use Promise.resolve %7C%7C .reject
%0A r
@@ -2551,24 +2551,62 @@
ipe function
+ (It means close flow already started)
.%0A // I
|
9893d7bfacf47bf183fefa05e02fe3fc50ac18a6 | add decade, make colors lower case | data.js | data.js | 'use strict'
const fetch = require('isomorphic-fetch')
const groupBy = require('lodash.groupBy')
const endpoint = 'http://199.217.112.113:8080/picture/picture'
const filters = ['collection', 'color', 'location', 'motif', 'view']
const err = (e) => {throw e}
const data = fetch(endpoint)
.then((res) => res.json(), err)
.then((photos) => {
const data = {}
data.photos = photos.map((p) => ({
id: p.id
, url: p.Bildname
, thumb: {
url: p.BildSmall
, width: p.width
, height: p.height
}
, collection: p.Collection
, color: p.Color
, location: p.Location
, motif: p.Subject
, view: p.View
}))
for (let filter of filters)
data[filter] = groupBy(data.photos, (p) => p[filter])
data.filters = filters
return data
}, err)
module.exports = data
| JavaScript | 0.999751 | @@ -174,16 +174,26 @@
ters = %5B
+'decade',
'collect
@@ -537,16 +537,104 @@
ght%0A%09%09%7D%0A
+%09%09, year: p.Decade%0A%09%09, decade: ((p.Decade - p.Decade %25 10) %7C%7C '?').toString()%0A
%09%09, coll
@@ -677,16 +677,30 @@
p.Color
+.toLowerCase()
%0A%09%09, loc
|
f1bdfe4bccad190a884df362112976d6536ac250 | --clean. | src/repl.js | src/repl.js |
var repl = module.exports = {};
var
req = require('./req');
var
path = require('path'),
std = require('repl');
var
extend = req.local('aux.js/object/extend'),
colors = req.local('cli-color'),
minimist = req.local('minimist');
var
uconsole = require('./console'),
log = require('./log'),
dir = require('./dir'),
sg = require('./sg'),
aux = require('./aux');
repl.run = function (argv)
{
argv = minimist(argv);
repl.start();
}
repl.start = function ()
{
var instance = std.start({
prompt: 'js > ',
ignoreUndefined: true
});
var context = instance.context;
reset(context);
instance.on('reset', reset);
/* @todo: check reset in other versions */
function reset (context)
{
uconsole(instance);
log(instance);
/* @todo: return value issue */
/*instance.writer = */ context.dir = dir(instance);
sg(instance);
aux(instance);
context.colors = colors;
req.inRepl(instance);
}
return instance;
}
| JavaScript | 0.999814 | @@ -429,16 +429,23 @@
rgv);%0A%0A%09
+return
repl.sta
@@ -447,16 +447,33 @@
l.start(
+%7B argopts: argv %7D
);%0A%7D%0A%0Are
@@ -497,85 +497,134 @@
on (
-)%0A%7B%0A%09var instance = std.start(%7B%0A%09%09prompt: 'js %3E ',%0A%09%09ignoreUndefined: true%0A%09%7D
+options)%0A%7B%0A%09options = extend(%7B%7D, defaults, options %7C%7C %7B%7D);%0A%0A%09var argopts = options.argopts;%0A%0A%09var instance = std.start(options
);%0A%0A
@@ -657,16 +657,42 @@
ntext;%0A%0A
+%09if (! argopts.clean)%0A%09%7B%0A%09
%09reset(c
@@ -700,16 +700,17 @@
ntext);%0A
+%09
%09instanc
@@ -730,16 +730,19 @@
reset);
+%0A%09%7D
%0A%0A%09/* @t
@@ -1045,12 +1045,88 @@
instance;%0A%7D%0A
+%0Avar defaults =%0A%7B%0A%09prompt: 'js %3E ',%0A%09ignoreUndefined: true,%0A%0A%09argopts: %7B%7D%0A%7D%0A
|
ea4c3b7106d111380ed15bfbaeb54440a4c7416d | fix demo | demo.js | demo.js |
'use strict';
const exec = require('child_process').exec;
const chalk = require('chalk');
const config = require('./demo-config');
const engine = require('./index');
console.log(config)
engine.on('tournament:aborted', function() {
console.log(chalk.bold.red('Tournament aborted.'));
});
engine.on('tournament:completed', function() {
console.log(chalk.bold.green('Tournament completed.'));
});
engine.on('gamestate:updated', function(data, done) {
console.log(chalk.bold.green('Gamestate updated.'));
// TODO should call done
});
const tournamentID = config.tournamentId;
const players = config.players;
startPlayerServices().then(function() {
engine.start(tournamentID, players);
});
function startPlayerServices() {
return Promise.all(players.map(function(player){
return new Promise(function(res, rej) {
const port = player.serviceUrl.match(/:([\d]{4})\/$/)[1];
const child = exec('node ./index.js', { cwd: `./demo-players/${player.name}/`, env: { PORT: port } }, function(err, stdout, stderr) {
if (err) {
console.log(chalk.bold.red('An error occurred while trying to open child process'), err);
return rej(err);
}
res();
});
child.stdout.on('data', data => console.log(chalk.bold.green(`${player.name}'s stdout:`), data));
child.stderr.on('data', data => console.log(chalk.bold.red(`${player.name}'s stderr:`), data));
});
}));
}
| JavaScript | 0.000001 | @@ -513,32 +513,15 @@
;%0A
-// TODO should call
done
+();
%0A%7D);
@@ -602,228 +602,43 @@
s;%0A%0A
-startPlayerServices().then(function() %7B%0A engine.start(tournamentID, players);%0A%7D);%0A%0A%0A%0A%0A%0Afunction startPlayerServices() %7B%0A return Promise.all(players.map(function(player)%7B%0A return new Promise(function(res, rej) %7B%0A
+players.forEach(function(player) %7B%0A
co
@@ -693,20 +693,16 @@
$/)%5B1%5D;%0A
-
const
@@ -833,20 +833,16 @@
) %7B%0A
-
-
if (err)
@@ -844,20 +844,16 @@
(err) %7B%0A
-
co
@@ -948,70 +948,16 @@
- return rej(err);%0A %7D%0A res();%0A
+%7D%0A
%7D);%0A
-
ch
@@ -1052,20 +1052,16 @@
data));%0A
-
child.
@@ -1154,21 +1154,114 @@
));%0A
- %7D);%0A %7D));%0A%7D
+%7D);%0A%0Aconsole.log(chalk.bold.green('Ready to start a local tournament.'))%0Aengine.start(tournamentID, players);
%0A
|
218ff20cf0f5213a275677cd211baf9bffce5450 | Fix test.js path | src/test.js | src/test.js |
var fs = require('fs');
var ts2hx = require('./ts2hx');
var hx = ts2hx(fs.readFileSync(__dirname+'/../Example.ts'));
process.stdout.write(hx);
| JavaScript | 0.000032 | @@ -97,16 +97,24 @@
me+'/../
+example/
Example.
|
6a7138dab6088ceff07b253e3720709f23651b51 | Implement tree.leaves on tree.filter. | src/tree.js | src/tree.js | import "heap";
function Tree(root) {
this.root = root;
}
Tree.prototype = {
leaves: tree_leaves,
search: tree_search,
filter: tree_filter
};
function tree_leaves() {
var leaves = [],
node,
nodes = [this.root];
while ((node = nodes.pop()) != null) {
if (node.children) {
var i = -1, n = node.children.length;
while (++i < n) nodes.push(node.children[i]);
} else {
leaves.push(node);
}
}
return leaves;
}
function tree_filter(filter) {
var leaves = [],
node,
nodes = [this.root];
while ((node = nodes.pop()) != null) {
if (filter(node)) {
if (node.children) {
var i = -1, n = node.children.length;
while (++i < n) nodes.push(node.children[i]);
} else {
leaves.push(node);
}
}
}
return leaves;
}
function tree_search(score) {
var minNode,
minScore = Infinity,
candidateNode = this.root,
candidateScore = score(candidateNode),
candidates = heap(tree_ascendingScore),
candidate = {s: candidateScore, n: candidateNode};
do {
if ((candidateNode = candidate.n).children) {
candidateNode.children.forEach(function(c) { candidates.push({s: score(c), n: c}); });
} else if ((candidateScore = score(candidateNode)) < minScore) {
minNode = candidateNode, minScore = candidateScore;
}
} while ((candidate = candidates.pop()) && candidate.s < minScore);
return minNode;
}
function tree_ascendingScore(a, b) {
return a.s - b.s;
}
| JavaScript | 0 | @@ -176,275 +176,64 @@
%7B%0A
-var leaves = %5B%5D,%0A node,%0A nodes = %5Bthis.root%5D;%0A%0A while ((node = nodes.pop()) != null) %7B%0A if (node.children) %7B%0A var i = -1, n = node.children.length;%0A while (++i %3C n) nodes.push(node.children%5Bi%5D);%0A %7D else %7B%0A leaves.push(node);%0A %7D%0A %7D%0A
+return this.filter(tree_true);%0A%7D%0A%0Afunction tree_true() %7B
%0A r
@@ -230,38 +230,36 @@
ue() %7B%0A return
-leaves
+true
;%0A%7D%0A%0Afunction tr
|
157d716e5e6f468ce106a27b76f52c28da9b5fc3 | Fix isOwnerOrStaff function [WAL-739] | app/scripts/services/customers-service.js | app/scripts/services/customers-service.js | 'use strict';
(function() {
angular.module('ncsaas')
.service('customersService', [
'baseServiceClass', '$state', '$q', '$http', 'ENV', 'currentStateService', 'usersService', customersService]);
function customersService(baseServiceClass, $state, $q, $http, ENV, currentStateService, usersService) {
var ServiceClass = baseServiceClass.extend({
filterByCustomer: false,
countryChoices: [],
init:function() {
this._super();
this.endpoint = '/customers/';
},
getBalanceHistory: function(uuid) {
var query = {UUID: uuid, operation: 'balance_history'};
return this.getList(query);
},
getCounters: function(query) {
var query = angular.extend({operation: 'counters'}, query);
return this.getFactory(false).get(query).$promise;
},
isOwnerOrStaff: function() {
var vm = this;
return $q.all([
currentStateService.getCustomer(),
usersService.getCurrentUser()
]).then(function(result) {
return vm.checkCustomerUser.apply(null, result);
});
},
checkCustomerUser: function(customer, user) {
if (user && user.is_staff) {
return true;
}
return customer && this.isOwner(customer, user);
},
isOwner: function(customer, user) {
for (var i = 0; i < customer.owners.length; i++) {
if (user && user.uuid === customer.owners[i].uuid) {
return true;
}
}
return false;
},
loadCountries: function() {
var vm = this;
if (vm.countryChoices.length != 0) {
return $q.when(vm.countryChoices);
} else {
return $http({
method: 'OPTIONS',
url: ENV.apiEndpoint + 'api/customers/'
}).then(function(response) {
vm.countryChoices = response.data.actions.POST.country.choices;
return vm.countryChoices;
});
}
},
countCustomers: function() {
return $http.head(ENV.apiEndpoint + 'api/customers/').success(function(data, status, header) {
return parseInt(header()['x-result-count']);
});
}
});
return new ServiceClass();
}
})();
| JavaScript | 0 | @@ -1085,12 +1085,10 @@
ply(
-null
+vm
, re
|
1f684919c7f8c2e8a486ba53c4b2d210247684f9 | Use parent launch id from URL for Unique errors (#2950) | app/src/controllers/uniqueErrors/sagas.js | app/src/controllers/uniqueErrors/sagas.js | /*
* Copyright 2021 EPAM Systems
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { all, call, put, select, take, takeEvery } from 'redux-saga/effects';
import { URLS } from 'common/urls';
import { activeProjectSelector } from 'controllers/user';
import {
fetchParentItems,
fetchParentLaunch,
launchSelector,
namespaceSelector,
queryParametersSelector,
} from 'controllers/testItem';
import { createFetchPredicate, fetchDataAction } from 'controllers/fetch';
import { pathnameChangedSelector } from 'controllers/pages';
import { PAGE_KEY, SIZE_KEY } from 'controllers/pagination';
import { SORTING_KEY } from 'controllers/sorting';
import { unselectAllItemsAction } from 'controllers/groupOperations';
import {
CLEAR_CLUSTER_ITEMS,
clusterItemsSagas,
selectedClusterItemsSelector,
} from './clusterItems';
import { FETCH_CLUSTERS, NAMESPACE, RELOAD_CLUSTERS } from './constants';
import { setPageLoadingAction } from './actionCreators';
function* fetchClusters(payload = {}) {
const { refresh = false } = payload;
let parentLaunch = yield select(launchSelector);
const project = yield select(activeProjectSelector);
const isPathNameChanged = yield select(pathnameChangedSelector);
const selectedItems = yield select(selectedClusterItemsSelector);
if (selectedItems.length) {
yield put(unselectAllItemsAction(NAMESPACE)());
}
if (isPathNameChanged && !refresh) {
yield put(setPageLoadingAction(true));
}
if (!parentLaunch) {
yield call(fetchParentItems);
} else {
yield call(fetchParentLaunch, { payload: { project, launchId: parentLaunch.id } });
}
parentLaunch = yield select(launchSelector);
const namespace = yield select(namespaceSelector);
const query = yield select(queryParametersSelector, namespace);
yield put(
fetchDataAction(NAMESPACE)(
URLS.clusterByLaunchId(project, parentLaunch.id, {
[PAGE_KEY]: query[PAGE_KEY],
[SIZE_KEY]: query[SIZE_KEY],
[SORTING_KEY]: query[SORTING_KEY],
}),
),
);
if (isPathNameChanged && !refresh) {
const waitEffects = [take(createFetchPredicate(NAMESPACE))];
yield all(waitEffects);
yield put(setPageLoadingAction(false));
}
}
function* reloadClusters() {
yield put({ type: CLEAR_CLUSTER_ITEMS });
yield call(fetchClusters, { refresh: true });
}
function* watchFetchClusters() {
yield takeEvery(FETCH_CLUSTERS, fetchClusters);
}
function* watchReloadClusters() {
yield takeEvery(RELOAD_CLUSTERS, reloadClusters);
}
export function* uniqueErrorsSagas() {
yield all([watchFetchClusters(), clusterItemsSagas(), watchReloadClusters()]);
}
| JavaScript | 0 | @@ -1004,32 +1004,50 @@
eChangedSelector
+, launchIdSelector
%7D from 'control
@@ -1055,24 +1055,24 @@
ers/pages';%0A
-
import %7B PAG
@@ -1562,16 +1562,67 @@
ayload;%0A
+ const launchId = yield select(launchIdSelector);%0A
let pa
@@ -2162,25 +2162,8 @@
chId
-: parentLaunch.id
%7D %7D
@@ -2422,22 +2422,15 @@
ct,
-parentL
+l
aunch
-.i
+I
d, %7B
|
66b6ced07319da19b696944b1dfca516fc299b53 | update writeFile to writeFileSync | src/util.js | src/util.js | var _ = require('lodash')
var fs = require('fs')
module.exports = {
getLatestData(db, filter) {
return _.chain(db)
.filter(filter)
.sortBy('version')
.reverse()
.head()
.value()
},
getDBIndex(db, filter) {
return _.findIndex(db, filter)
},
getNow() {
return Math.floor( (new Date).getTime() / 1000 )
},
readJSON(filePath) {
return JSON.parse(fs.readFileSync(filePath))
},
writeJSON(filePath, data) {
return fs.writeFile(filePath, JSON.stringify(data, null, ' '))
},
backup(data, backupPath) {
var backup = this.readJSON(backupPath)
backup.push(data)
this.writeJSON(backupPath, backup)
},
} | JavaScript | 0 | @@ -476,24 +476,81 @@
h, data) %7B%0D%0A
+ var JSONString = JSON.stringify(data, null, ' ')%0D%0A
return f
@@ -560,16 +560,20 @@
riteFile
+Sync
(filePat
@@ -583,38 +583,22 @@
JSON
-.s
+S
tring
-ify(data, null, ' ')
+, 'utf8'
)%0D%0A
|
d270ce54311c6fbc7148c6efdb3b41edcf79ad0f | add on delete | lib/dialects/base/scheme.js | lib/dialects/base/scheme.js | var SchemeParser = function () {
}
var types = {
"Number": {syntax: "int"},
"BigInt": {syntax: "bigint"},
"String": {syntax: "varchar", length: true},
"Text": {syntax: "text"},
"Real": {syntax: "real"},
"Boolean": {syntax: "tinyint", default_length: 1},
"Blob": {syntax: "blob"},
"Binary": {syntax: "binary", length: true}
}
// for future
var onDeleteTrigger = {
"set_null": "SET NULL",
"cascade": "CASCADE"
}
function getType(field) {
var s = "";
var type = types[field.type];
if (!type) {
throw new Error("Invalid type of field: " + field.type);
}
s += type.syntax;
if (type.length) {
if (!field.length || field.length <= 0) {
throw new Error("Field length can't be less or equal 0");
}
s += "(" + field.length + ")";
} else if (type.default_length) {
s += "(" + type.default_length + ")";
}
return s;
}
function foreignkeys(fields, keys) {
if (!keys || keys.length == 0) {
return "";
}
var s = ", ";
var names = [];
fields.forEach(function (field) {
names.push(field.name)
});
keys.forEach(function (key, i) {
if (!key.field) {
throw new Error("Provide field for foreign key");
}
if (names.indexOf(key.field) < 0) {
throw new Error("Not exists field to make foreign key: " + key.field);
}
if (!key.table || key.table.trim().length == 0) {
throw new Error("Invalid reference table name");
}
if (!key.table_field || key.table_field.trim().length == 0) {
throw new Error("Invalid reference table filed");
}
s += "FOREIGN KEY (" + key.field + ") REFERENCES " + key.table + "(" + key.table_field + ")";
if (i != keys.length - 1) {
s += ",";
}
});
return s;
}
function parse(fields, fkeys) {
var sql_fields = "";
var checkPrimaryKey = false;
var names = [];
fields.forEach(function (field, i) {
if (!field.name) {
throw new Error("Name of field most be provided");
}
if (field.name.trim().length == 0) {
throw new Error("Name most contains characters");
}
if (names.indexOf(field.name) >= 0) {
throw new Error("Two parameters with same name: " + field.name);
}
var line = this.dialect._wrapIdentifier(field.name) + " " + getType(field);
if (field.not_null) {
line += " NOT NULL";
}
if (field.default !== undefined) {
var _type = typeof field.default;
var _default = field.default;
if (_type === "string") {
_default = this.dialect._wrapIdentifier(field.default);
}
line += " default " + _default;
}
if (field.unique) {
line += " UNIQUE";
}
if (field.primary_key) {
if (checkPrimaryKey) {
throw new Error("Too much primary key '" + field.name + "' in table");
} else {
checkPrimaryKey = true;
}
line += " PRIMARY KEY";
}
sql_fields += line;
names.push(field.name);
if (i != fields.length - 1) {
sql_fields += ",";
}
}.bind(this));
sql_fields += foreignkeys(fields, fkeys);
return sql_fields;
}
module.exports = {
parse: parse,
foreignkeys: foreignkeys
} | JavaScript | 0.000001 | @@ -1580,16 +1580,71 @@
ld + %22)%22
+ + (key.on_delete ? %22 ON DELETE %22 + key.on_delete : %22%22)
;%0A%09%09if (
|
2de718365e3afd4ed278a4220916615eca563c4d | Fix environment detecting | src/util.js | src/util.js | import {DEBUGGING} from './constants'
/**
* Define property with value.
*
* @param {Object} object
* @param {String} property
* @param {*} value
* @param {Boolean} [enumerable]
*/
export function defineValue (object, property, value, enumerable) {
Object.defineProperty(object, property, {
value,
enumerable: !!enumerable,
writable: true,
configurable: true,
})
}
/**
* Define property with getter and setter.
*
* @param {Object} object
* @param {String} property
* @param {Function} getter
* @param {Function} setter
*/
export function defineAccessor (object, property, getter, setter) {
Object.defineProperty(object, property, {
get: getter,
set: setter,
enumerable: true,
configurable: true,
})
}
/**
* Array type check.
*
* @return {Boolean}
*/
export const isArray = Array.isArray
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*
* @param {*} object
* @return {Boolean}
*/
const toString = Object.prototype.toString
const OBJECT_STRING = '[object Object]'
export function isPlainObject (object) {
return toString.call(object) === OBJECT_STRING
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*
* @param {*} object
* @return {Boolean}
*/
export function isObject (object) {
return object !== null && typeof object === 'object'
}
/**
* Function type check
*
* @param {*} func
* @param {Boolean}
*/
export function isFunction (func) {
return typeof func === 'function'
}
/**
* Iterate object
*
* @param {Object} object
* @param {Function} callback
*/
export function everyEntries (object, callback) {
const keys = Object.keys(object)
for (let i = 0, l = keys.length; i < l; i++) {
callback(keys[i], object[keys[i]])
}
}
/**
* noop is function which is nothing to do.
*/
export function noop () {}
/**
* @param {String} string
*/
export const warn = typeof DEBUGGING !== undefined && DEBUGGING
&& typeof console !== 'undefined' && console
&& isFunction(console.warn)
? console.warn
: noop
export let _Set
if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) {
// use native Set when available.
_Set = Set
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = function () {
this.set = Object.create(null)
}
_Set.prototype.has = function (key) {
return this.set[key] !== undefined
}
_Set.prototype.add = function (key) {
this.set[key] = 1
}
_Set.prototype.clear = function () {
this.set = Object.create(null)
}
}
| JavaScript | 0.000002 | @@ -2010,24 +2010,25 @@
BUGGING !==
+'
undefined &&
@@ -2024,16 +2024,17 @@
ndefined
+'
&& DEBU
|
ea8dd1bc079ad6e6354f1633e83d3fbdda9053f2 | fix posts initial load | source/pages/feed.js | source/pages/feed.js | import React from "react"
import { connect } from 'react-redux'
import {
List,
ListItem,
Paper,
Toolbar,
ToolbarGroup,
ToolbarTitle
} from "material-ui"
import { FormattedMessage } from "react-intl"
import DefaultRawTheme from 'material-ui/lib/styles/raw-themes/light-raw-theme';
import PostForm from "components/post-form"
import store from "store"
import { posts, pages } from "api"
function mapStateToProps(state, props) {
return {
posts: state.posts,
page: state.pages.get(props.params.pageId)
}
}
function mapDispatchToProps(dispatch) {
return {
loadPosts: (query) => posts.find(query, dispatch),
getPage: (id, query) => pages.get(id, query, dispatch)
}
}
const Feed = React.createClass({
componentWillMount() {
const { params, loadPosts, getPage } = this.props
let query = {}
if (params.pageId) {
getPage(params.pageId)
query.page = params.pageId
}
loadPosts(query)
},
getStyles() {
let bannerImage;
if (this.props.params.pageId) {
bannerImage = "http://d.facdn.net/art/phorque/1397922715/1397922715.phorque_p51mustang_mini.jpg"
}
else {
bannerImage = "http://www.hdwallpaperscool.com/wp-content/uploads/2014/10/harp-seal-desktop-wallpaper-in-high-resolution-wide-free.jpg"
}
return {
banner: {
width: "100%",
background: `#000 url(${bannerImage}) no-repeat center/cover`,
height: 0,
paddingBottom: "30%",
position: "relative"
},
infos: {
fontFamily: DefaultRawTheme.fontFamily,
width: "100%",
background: DefaultRawTheme.palette.textColor,
opacity: 0.8,
position: "absolute",
bottom: 0,
color: DefaultRawTheme.palette.alternateTextColor
}
}
},
renderInfoBanner: function() {
const style = this.getStyles()
let ownerInfos;
if (this.props.page) {
switch (this.props.page.owner_type) {
case "User":
ownerInfos = <h1>{this.props.page.owner.profile.name}</h1>
break;
}
}
else if (!this.props.params.pageId) {
ownerInfos = <h1><FormattedMessage id="links.mainFeed" /></h1>
}
let ownerInfosContainer = "";
if (ownerInfos) {
ownerInfosContainer =
<aside style={style.infos}>
<div style={{padding: "16px 32px"}}>{ownerInfos}</div>
</aside>
}
return (
<div style={style.banner}>
{ownerInfosContainer}
</div>
)
},
renderPost(post) {
let ownerInfos;
switch (post.owner_type) {
case "User":
ownerInfos = <ToolbarTitle text={post.owner.profile.name} />
break;
}
return (
<Paper style={{marginTop: 24}}>
<Toolbar>
<ToolbarGroup key={1} float="left">
{ownerInfos}
</ToolbarGroup>
</Toolbar>
<div style={{padding: 24}}>
{post.data.body}
</div>
</Paper>
)
},
render: function() {
const posts = this.props.posts.map(post => this.renderPost(post))
return (
<div {...this.props}>
{this.renderInfoBanner()}
<div className="container-fluid">
<div className="col-md-8 col-sm-8 col-xs-12" style={{marginTop: 32}}>
<PostForm className="col-xs-12" />
<List>
{posts}
</List>
</div>
</div>
</div>
);
}
})
export default connect(mapStateToProps, mapDispatchToProps)(Feed)
| JavaScript | 0 | @@ -577,27 +577,27 @@
eturn %7B%0A
-loa
+fin
dPosts: (que
@@ -764,27 +764,207 @@
-const %7B params, loa
+this.loadPosts()%0A %7D,%0A%0A componentWillReceiveProps(newProps) %7B%0A if (this.props.params.pageId != newProps.params.pageId) %7B%0A this.loadPosts()%0A %7D%0A %7D,%0A%0A loadPosts() %7B%0A const %7B params, fin
dPos
@@ -990,16 +990,17 @@
s.props%0A
+%0A
let
@@ -1109,19 +1109,19 @@
%7D%0A
-loa
+fin
dPosts(q
|
15cfa010f0b56c46d814ca7153f736b7437959c8 | fix parse. | scraper-engine/services/parseXml.js | scraper-engine/services/parseXml.js | var fs = require('fs')
var xml2js = require('xml2js')
var parser = new xml2js.Parser()
var dataFiled = require(global.appRoot + '/models/data-field')
var navFiled = require(global.appRoot + '/models/navigation-field')
var collections = require(global.appRoot + '/models/xmlFile')
var parse = {
parseFile :
function parseXmlFile(filePath)
{
var data_selectors=[]
var nav_selectors=[]
fs.readFile(filePath, function (err, data) {
parser.parseString(data, function (err, result) {
var url = result['webscraper']['current_url'][0];
var data = result['webscraper']['Data'];
for (var i=0 ; i< data[0].data.length;i++)
{
var data_element =dataFiled.generateData('text',data[0].data[0].title[0],data[0].data[0].element_selector[0])
data_selectors.push(data_element)
}
var nav = result['webscraper']['Nav'];
for (var i=0 ; i< nav[0].nav.length;i++)
{
var nav_element = navFiled.generateNav('category','element_selector')
nav_selectors.push(nav_element)
}
saveData(url,data_selectors,nav_selectors)
})
})
}
}
function saveData(url,data_selectors,nav_selectors)
{
global.xmlfile = collections.generateXmlFile(url,data_selectors,nav_selectors)
console.log('parse url: '+global.xmlfile.url )
}
module.exports = parse | JavaScript | 0.000001 | @@ -852,16 +852,34 @@
+%0A
data_s
@@ -898,32 +898,33 @@
h(data_element)%0A
+%0A
@@ -929,16 +929,17 @@
%7D%0A
+
%0A%0A
@@ -1485,16 +1485,85 @@
ectors)%0A
+//console.log('global.xmlfile parse '+global.xmlfile.data.length)%0A//
console.
|
ed45e45cd4ee03e2e76aa099dffcedd003854100 | update _create & _init prosess of View, fix bug of _delegateEvent of View. | src/view.js | src/view.js | /**
* [description]
* @return {[type]} [description]
*/
window.$MR.View = (function($, $MR) {
'use strict';
var View;
View = $MR.Utils.extend($MR.Bone, {
defaults: {},
events: {},
_create: function(options) {
this.el = options.el;
this.$el = $(this.el);
this.settings = $.extend({}, this.defaults, options, this.$el.data('options'));
this._init();
},
_init: function() {},
_mkCache: function() {
this.settings.cache = {
$: {}
};
return this.settings.cache;
},
$: function(selector, nocache) {
var settings = this.settings,
cache = settings.cache || this._mkCache(),
prefix = (settings.selector && settings.selector.prefix) || '',
css = selector.replace(/\$/g, prefix),
$el;
if (nocache || typeof cache.$[selector] === 'undefined') {
$el = this.$el.find(css);
if ($el[0]) {
cache.$[selector] = $el;
} else {
cache.$[selector] = null;
}
}
return cache.$[selector];
},
_delegateEvent: function(events, target, swc) {
var self = this,
_target = target || self.$el,
_events = events || self.events,
tagElemsRegexp = /^#|^\.|^\[|^button|^label|^input|^select|^option|^textarea|^img|^ul|^li|^span|^div/;
$.each(_events, function(eventName, handler) {
var args = eventName.split(' '),
argsLen = args.length,
_handler = self._bind(handler),
isHasChildElement = tagElemsRegexp.test(args[argsLen-1].toLowerCase());
if (isHasChildElement) {
args = [args.slice(0, argsLen-1).join(' '), args[argsLen-1]];
args.push(_handler);
_target[swc].apply(_target, args);
} else {
_target[swc](eventName, _handler);
}
});
},
_delegate: function(events, target) {
this._delegateEvent(events, target, 'on');
},
_undelegate: function(events, target) {
this._delegateEvent(events, target, 'off');
}
});
return View;
})(jQuery, window.$MR); | JavaScript | 0 | @@ -322,16 +322,56 @@
is.el);%0A
+ this.model = options.model;%0A
@@ -519,16 +519,55 @@
tion() %7B
+%0A this._delegate();%0A
%7D,%0A%0A
@@ -1903,16 +1903,33 @@
lement =
+ (argsLen %3E 1) &&
tagElem
|
5ff7de06362804911b3b027b3ecc450af02ca407 | Update support for visibilityState | src/wait.js | src/wait.js | import * as Utils from './utils';
const P = Utils.P;
let domReady = false;
export function dom() {
if (domReady) return P();
const d = new Utils.Deferred();
if (document.readyState == "complete") {
domReady = true;
setTimeout(d.ok);
return d.promise;
}
function readyLsn() {
document.removeEventListener('DOMContentLoaded', readyLsn);
window.removeEventListener('load', readyLsn);
if (domReady) return;
domReady = true;
d.ok();
}
document.addEventListener('DOMContentLoaded', readyLsn);
window.addEventListener('load', readyLsn);
return d.promise.then(function() {
return imports(document);
});
}
export function ui(val) {
let solve, p;
if (document.hidden) {
p = new Promise(function(resolve) {
solve = resolve;
});
document.addEventListener('visibilitychange', listener, false);
} else {
p = P();
}
const sp = p.then(function() {
return styles(document.head);
}).then(function() {
return sp.fn(val);
});
return sp;
function listener() {
document.removeEventListener('visibilitychange', listener, false);
solve();
}
}
export function styles(head, old) {
const knowns = {};
let thenFn;
const sel = 'link[rel="stylesheet"]';
if (old && head != old) {
for (const item of Utils.all(old, sel)) {
knowns[item.href] = true;
}
thenFn = node;
} else {
thenFn = sheet;
}
return Promise.all(
Utils.all(head, sel).filter(function(item) {
return !knowns[item.href];
}).map(thenFn)
);
}
export function imports(doc) {
const imports = Utils.all(doc, 'link[rel="import"]');
const polyfill = window.HTMLImports;
const whenReady = (function() {
let p;
return function() {
if (!p) p = new Promise(function(resolve) {
polyfill.whenReady(function() {
setTimeout(resolve);
});
});
return p;
};
})();
return Promise.all(imports.map(function(link) {
if (link.import && link.import.readyState == "complete") {
// no need to wait, wether native or polyfill
return P();
}
if (polyfill) {
// link.onload cannot be trusted
return whenReady();
}
return node(link);
}));
}
export function sheet(link) {
let ok = false;
try {
ok = link.sheet && link.sheet.cssRules;
} catch(ex) {
// bail out
ok = true;
}
if (ok) return Promise.resolve();
const nlink = link.cloneNode();
nlink.media = "print";
const p = node(nlink);
const parent = link.parentNode;
parent.insertBefore(nlink, link.nextSibling);
return p.then(function() {
parent.removeChild(nlink);
});
}
export function node(item) {
return new Promise(function(resolve) {
function done() {
item.removeEventListener('load', done);
item.removeEventListener('error', done);
resolve();
}
item.addEventListener('load', done);
item.addEventListener('error', done);
});
}
| JavaScript | 0 | @@ -684,16 +684,99 @@
t.hidden
+ %7C%7C document.visibilityState == %22hidden%22 %7C%7C document.visibilityState == %22prerender%22
) %7B%0A%09%09p
@@ -1069,24 +1069,92 @@
istener() %7B%0A
+%09%09if (!document.hidden %7C%7C document.visibilityState == %22visible%22) %7B%0A%09
%09%09document.r
@@ -1212,16 +1212,17 @@
lse);%0A%09%09
+%09
solve();
@@ -1222,16 +1222,20 @@
olve();%0A
+%09%09%7D%0A
%09%7D%0A%7D%0A%0Aex
|
29e3d126ec12c71679c47046b191a9ec357362cc | Update html/js/user_actions.js | html/js/user_actions.js | html/js/user_actions.js | // This file contains all custom client side scripts
var draw_pie = function() {
///// STEP 0 - setup
// source data table and canvas tag
var data_table = document.getElementById('piechart-table');
var canvas = document.getElementById('piechart');
var td_index = 0; // which TD contains the data
var colors = new Array();
colors[0] = "rgb(75,175,50)";
colors[1] = "rgb(65,148,23)";
colors[2] = "rgb(226,23,27)";
colors[3] = "rgb(178,27,24)";
///// STEP 1 - Get the, get the, get the data!
// get the data[] from the table
var tds, data = [], value = 0, total = 0;
var trs = data_table.getElementsByTagName('tr'); // all TRs
for (var i = 0; i < trs.length; i++) {
tds = trs[i].getElementsByTagName('td'); // all TDs
if (tds.length === 0) continue; // no TDs here, move on
// get the value, update total
value = parseFloat(tds[td_index].innerHTML);
data[data.length] = value;
total += value;
// color
trs[i].style.backgroundColor = colors[i]; // color this TR
}
///// STEP 2 - Draw pie on canvas
// exit if canvas is not supported
if (typeof canvas.getContext === 'undefined') {
return;
}
// get canvas context, determine radius and center
var ctx = canvas.getContext('2d');
var canvas_size = [canvas.width, canvas.height];
var radius = Math.min(canvas_size[0], canvas_size[1]) / 2;
var center = [canvas_size[0]/2, canvas_size[1]/2];
var sofar = 0; // keep track of progress
// loop the data[]
for (var piece in data) {
var thisvalue = data[piece] / total;
ctx.beginPath();
ctx.moveTo(center[0], center[1]); // center of the pie
ctx.arc( // draw next arc
center[0],
center[1],
radius,
Math.PI * (- 0.5 + 2 * sofar), // -0.5 sets set the start to be top
Math.PI * (- 0.5 + 2 * (sofar + thisvalue)),
false
);
ctx.lineTo(center[0], center[1]); // line back to the center
ctx.closePath();
ctx.fillStyle = colors[piece]; // color
ctx.fill();
sofar += thisvalue; // increment progress tracker
}
///// DONE!
// utility - generates random color
function getColor() {
var rgb = [];
for (var i = 0; i < 3; i++) {
rgb[i] = Math.round(100 * Math.random() + 155) ; // [155-255] = lighter colors
}
return 'rgb(' + rgb.join(',') + ')';
}
}
/**
* If an initable pagination link is clicked,
* get the update content from the server,
* remove the old content and insert the new.
*/
function update_inis(page, timeline) {
var url = "update_inis?page=" + page + "&timeline=" + timeline;
$.ajax({
url: url,
type: "POST",
data: { page: page },
dataType: "text",
success: function(data) {
$("#initable").remove();
$("#inipages").remove();
$("#inicontent").append(data);
}
});
return false;
}
/**
* If an news pagination link is clicked,
* get the update content from the server,
* remove the old content and insert the new.
*/
function update_news(page) {
var url = "update_news?newspage=" + page;
$.ajax({
url: url,
type: "POST",
data: { page: page },
dataType: "text",
success: function(data) {
$("#newschart").remove();
$("#newsgraph").remove();
$("#newspages").remove();
$("#newscontent").append(data);
draw_pie();
}
});
return false;
}
/**
* If an opinion pagination link is clicked,
* get the update content from the server,
* remove the old content and insert the new.
*/
function update_opinions(page, suggestion_id) {
var url = "update_opinions?opinionspage=" + page + '&suggestion_id=' + suggestion_id;
$.ajax({
url: url,
type: "POST",
data: { opinionspage: page },
dataType: "text",
success: function(data) {
var $container = $('#opiniondiv');
$container.empty();
$container.append(data);
}
});
return false;
}
/**
* Update the topics for a certain unit, taking into account
* sorting.
*/
function update_areas_table(unit_id, sorting_criteria) {
var url = 'update_areas_table?unit_id=' + unit_id;
var data = {
unit_id: unit_id
};
if(sorting_criteria !== undefined) {
url += '&sort=' + sorting_criteria;
data.sort = sorting_criteria;
}
$.ajax({
url: url,
type: "POST",
data: data,
dataType: "text",
success: function(data) {
var $a = $('a[name="' + unit_id + '"]');
var $table = $a.siblings().filter('table');
$table.replaceWith(data);
}
});
return false;
}
/**
* Update the issues for a certain area
* sorting.
*/
function update_issues_table(area_id, state_filter, issue_page, member_page) {
var url = 'update_issues_table?area_id=' + area_id + '&issue_state=' + state_filter
+ '&page=' + issue_page + '&member_page=' + member_page;
var data = {
area_id: area_id,
issue_state: state_filter,
page: issue_page,
member_page: member_page
};
$.ajax({
url: url,
type: "POST",
data: data,
dataType: "text",
success: function(data) {
var $table = $('#issues-table');
$table.replaceWith(data);
}
});
return false;
}
/**
* Delete the links from the ini and news table pagination,
* so onClick on these will be triggered, if JS is active.
*
* I know onClick is dirty, but have not found another way
* to pass the page parameter from the links.
*/
$(document).ready(function() {
$("#inipages").find("a").attr("href", "#");
$("#newspages").find("a").attr("href", "#newscontent");
$("#filterslide").click(function(){
$("#filter").slideToggle("slow");
return false;
});
$("#initiative-detail").css('height', $("#initiative-detail").height());
$("#initiative-detail").hide();
$("#detailslide").click(function(){
$("#initiative-detail").slideToggle("slow");
return false;
});
$("#initiative-history").css('height', $("#initiative-history").height());
$("#initiative-history").hide();
$("#historyslide").click(function(){
$("#initiative-history").slideToggle("slow");
return false;
});
draw_pie();
});
| JavaScript | 0.000001 | @@ -5638,85 +5638,8 @@
);%0A%0A
- $(%22#initiative-detail%22).css('height', $(%22#initiative-detail%22).height());%0A
@@ -5792,87 +5792,8 @@
);%0A%0A
- $(%22#initiative-history%22).css('height', $(%22#initiative-history%22).height());%0A
|
b7642cc89f14818a1a41fd4f4f94de6fff297f0a | fix issue | pages/list.js | pages/list.js | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { Component } from 'react';
export default class extends Component {
render() {
return (
<ul class="table-view">
<li class="table-view-cell media">
<a class="navigate-right">
<img class="media-object pull-left" src="http://placehold.it/42x42">
<div class="media-body">
Item 1
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore. Lorem ipsum dolor sit amet.</p>
</div>
</a>
</li>
<li class="table-view-cell media">
<a class="navigate-right">
<img class="media-object pull-left" src="http://placehold.it/42x42">
<div class="media-body">
Item 1
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore. Lorem ipsum dolor sit amet.</p>
</div>
</a>
</li>
<li class="table-view-cell media">
<a class="navigate-right">
<img class="media-object pull-left" src="http://placehold.it/42x42">
<div class="media-body">
Item 1
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore. Lorem ipsum dolor sit amet.</p>
</div>
</a>
</li>
</ul>
);
}
}
| JavaScript | 0.000002 | @@ -267,1325 +267,29 @@
%3C
-ul class=%22table-view%22%3E%0A %3Cli class=%22table-view-cell media%22%3E%0A %3Ca class=%22navigate-right%22%3E%0A %3Cimg class=%22media-object pull-left%22 src=%22http://placehold.it/42x42%22%3E%0A %3Cdiv class=%22media-body%22%3E%0A Item 1%0A %3Cp%3ELorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore. Lorem ipsum dolor sit amet.%3C/p%3E%0A %3C/div%3E%0A %3C/a%3E%0A %3C/li%3E%0A %3Cli class=%22table-view-cell media%22%3E%0A %3Ca class=%22navigate-right%22%3E%0A %3Cimg class=%22media-object pull-left%22 src=%22http://placehold.it/42x42%22%3E%0A %3Cdiv class=%22media-body%22%3E%0A Item 1%0A %3Cp%3ELorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore. Lorem ipsum dolor sit amet.%3C/p%3E%0A %3C/div%3E%0A %3C/a%3E%0A %3C/li%3E%0A %3Cli class=%22table-view-cell media%22%3E%0A %3Ca class=%22navigate-right%22%3E%0A %3Cimg class=%22media-object pull-left%22 src=%22http://placehold.it/42x42%22%3E%0A %3Cdiv class=%22media-body%22%3E%0A Item 1%0A %3Cp%3ELorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore. Lorem ipsum dolor sit amet.%3C/p%3E%0A %3C/div%3E%0A %3C/a%3E%0A %3C/li%3E%0A %3C/ul
+p%3E this is a list %3C/p
%3E%0A
|
1186d8ec200a9333d228f34cb478148b137a7743 | Remove as it was covered by previous if-then; cleanup | src/core/run.js | src/core/run.js | import { JSONPath } from 'jsonpath-plus';
import optionAPI from '../api/option';
import traverse from './traverse';
import random from './random';
import utils from './utils';
function pick(data) {
return Array.isArray(data)
? random.pick(data)
: data;
}
function cycle(data, reverse) {
if (!Array.isArray(data)) {
return data;
}
const value = reverse
? data.pop()
: data.shift();
if (reverse) {
data.unshift(value);
} else {
data.push(value);
}
return value;
}
function resolve(obj, data, values, property) {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (!values) {
values = {};
}
if (!data) {
data = obj;
}
if (Array.isArray(obj)) {
return obj.map(x => resolve(x, data, values, property));
}
if (obj.jsonPath) {
const params = typeof obj.jsonPath !== 'object'
? { path: obj.jsonPath }
: obj.jsonPath;
params.group = obj.group || params.group || property;
params.cycle = obj.cycle || params.cycle || false;
params.reverse = obj.reverse || params.reverse || false;
params.count = obj.count || params.count || 1;
const key = `${params.group}__${params.path}`;
if (!values[key]) {
if (params.count > 1) {
values[key] = JSONPath(params.path, data).slice(0, params.count);
} else {
values[key] = JSONPath(params.path, data);
}
}
if (params.cycle || params.reverse) {
return cycle(values[key], params.reverse);
}
return pick(values[key]);
}
Object.keys(obj).forEach(k => {
obj[k] = resolve(obj[k], data, values, k);
});
return obj;
}
// TODO provide types
function run(refs, schema, container) {
try {
const result = traverse(utils.clone(schema), [], function reduce(sub, maxReduceDepth, parentSchemaPath) {
if (typeof maxReduceDepth === 'undefined') {
maxReduceDepth = random.number(1, 3);
}
if (!sub) {
return null;
}
if (typeof sub.generate === 'function') {
return sub;
}
// cleanup
const _id = sub.$id || sub.id;
if (typeof _id === 'string') {
delete sub.id;
delete sub.$id;
delete sub.$schema;
}
if (typeof sub.$ref === 'string') {
if (sub.$ref === '#') {
delete sub.$ref;
return sub;
}
let ref;
if (sub.$ref.indexOf('#/') === -1) {
ref = refs[sub.$ref] || null;
}
if (sub.$ref.indexOf('#/definitions/') === 0) {
ref = schema.definitions[sub.$ref.split('#/definitions/')[1]] || null;
}
if (typeof ref !== 'undefined') {
if (!ref && optionAPI('ignoreMissingRefs') !== true) {
throw new Error(`Reference not found: ${sub.$ref}`);
}
utils.merge(sub, ref || {});
}
// just remove the reference
delete sub.$ref;
return sub;
}
if (Array.isArray(sub.allOf)) {
const schemas = sub.allOf;
delete sub.allOf;
// this is the only case where all sub-schemas
// must be resolved before any merge
schemas.forEach(subSchema => {
const _sub = reduce(subSchema, maxReduceDepth + 1, parentSchemaPath);
// call given thunks if present
utils.merge(sub, typeof _sub.thunk === 'function'
? _sub.thunk()
: _sub);
});
}
if (Array.isArray(sub.oneOf || sub.anyOf)) {
const mix = sub.oneOf || sub.anyOf;
// test every value from the enum against each-oneOf
// schema, only values that validate once are kept
if (sub.enum && sub.oneOf) {
sub.enum = sub.enum.filter(x => utils.validate(x, mix));
}
return {
thunk() {
const copy = utils.omitProps(sub, ['anyOf', 'oneOf']);
const fixed = random.pick(mix);
utils.merge(copy, fixed);
if (sub.oneOf && copy.properties) {
mix.forEach(omit => {
if (omit !== fixed && omit.required) {
omit.required.forEach(key => {
if (copy.properties) {
delete copy.properties[key];
}
});
}
});
}
return copy;
},
};
}
Object.keys(sub).forEach(prop => {
if ((Array.isArray(sub[prop]) || typeof sub[prop] === 'object') && !utils.isKey(prop)) {
sub[prop] = reduce(sub[prop], maxReduceDepth, parentSchemaPath.concat(prop));
}
});
// avoid extra calls on sub-schemas, fixes #458
if (parentSchemaPath) {
const lastProp = parentSchemaPath[parentSchemaPath.length - 1];
if (lastProp === 'properties' || lastProp === 'items') {
return sub;
}
}
return container.wrap(sub);
});
if (optionAPI('resolveJsonPath')) {
return resolve(result);
}
return result;
} catch (e) {
if (e.path) {
throw new Error(`${e.message} in /${e.path.join('/')}`);
} else {
throw e;
}
}
}
export default run;
| JavaScript | 0 | @@ -4149,53 +4149,8 @@
%3E %7B%0A
- if (copy.properties) %7B%0A
@@ -4198,30 +4198,8 @@
y%5D;%0A
- %7D%0A
|
4ffad7130b818c3c7ead3b6063b9e6c9f88e0130 | Use currency database file | src/currency.js | src/currency.js | ( function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
module.require( "../resources/currency-names" );
module.require( "./resource-bundle" );
module.require( "./locale" );
module.exports = factory( global );
} else {
factory( global );
}
}( this, function( global ) {
function Currency( currencyCode, defaultFractionDigits, numericCode ) {
var _currencyCode = currencyCode;
var _defaultFractionDigits = defaultFractionDigits;
var _numericCode = numericCode;
this.getCurrencyCode = function() {
return _currencyCode;
};
this.getDefaultFractionDigits = function() {
return _defaultFractionDigits;
};
this.getNumericCode = function() {
return _numericCode;
};
this.getSymbol = function( locale ) {
var bundle = global.ResourceBundle.getBundle( "CurrencyNames", locale );
return bundle[ _currencyCode ];
};
this.getDisplayName = function( locale ) {
var bundle = global.ResourceBundle.getBundle( "CurrencyNames", locale );
return bundle[ _currencyCode.toLowerCase() ];
};
}
var instances = {
"EUR": new Currency( "EUR", 2, 0 ),
"GBP": new Currency( "GBP", 2, 0 ),
"USD": new Currency( "USD", 2, 0 )
};
Currency.getInstance = function( currencyCode ) {
var instance = instances[ currencyCode ];
if ( !instance ) {
instance = new Currency( currencyCode, -1, 0 );
instances[ currencyCode ] = instance;
}
return instance;
};
Currency.prototype.toString = function() {
return this.getCurrencyCode();
};
global.Currency = Currency;
return Currency;
} ) ); | JavaScript | 0 | @@ -204,24 +204,69 @@
-bundle%22 );%0A
+ module.require( %22./currency-data%22 );%0A
modu
@@ -1342,339 +1342,1398 @@
= %7B
-%0A %22EUR%22: new Currency( %22EUR%22, 2, 0 ),%0A %22GBP%22: new Currency( %22GBP%22, 2, 0 ),%0A %22USD%22: new Currency( %22USD%22, 2, 0 )%0A %7D;%0A%0A Currency.getInstance = function( currencyCode ) %7B%0A var instance = instances%5B currencyCode %5D;%0A if ( !instance ) %7B%0A instance = new Currency( currencyCode, -1, 0 );%0A
+%7D;%0A%0A Currency.getInstance = function( arg ) %7B%0A if ( typeof arg == %22string%22 ) %7B%0A var currencyCode = arg.length %3E 0 ? arg : %22XXX%22 ;%0A var instance = instances%5B currencyCode %5D;%0A if ( !instance ) %7B%0A var data = global.CurrencyData;%0A var numericCode = 0;%0A var defaultFractionDigit = -1;%0A var result = new RegExp( currencyCode + %22%5C%5Cd%7B3%7D%22 ).exec( data%5B%22all%22%5D ).toString();%0A if ( result && result.length %3E 0 ) %7B%0A var regex = new RegExp( currencyCode );%0A numericCode = result.substring( 3 );%0A defaultFractionDigit = 2;%0A if ( regex.test( data%5B %22minor0%22 %5D ) ) %7B%0A defaultFractionDigit = 0;%0A %7D%0A if ( regex.test( data%5B %22minor1%22 %5D ) ) %7B%0A defaultFractionDigit = 1;%0A %7D%0A if ( regex.test( data%5B %22minor3%22 %5D ) ) %7B%0A defaultFractionDigit = 3;%0A %7D%0A if ( regex.test( data%5B %22minorUndefined%22 %5D ) ) %7B%0A defaultFractionDigit = -1;%0A %7D%0A %7D%0A instance = new Currency( currencyCode, defaultFractionDigit, numericCode );%0A if ( defaultFractionDigit != -1 ) %7B%0A
@@ -2774,24 +2774,46 @@
= instance;%0A
+ %7D%0A
%7D%0A
@@ -2814,24 +2814,28 @@
%7D%0A
+
return insta
@@ -2835,24 +2835,440 @@
n instance;%0A
+ %7D else if ( arg instanceof global.Locale ) %7B%0A var locale = arg;%0A var countryCode = locale.getCountry();%0A if ( countryCode && countryCode.length %3E 0 ) %7B%0A return Currency.getInstance( global.CurrencyData%5B countryCode %5D );%0A %7D else %7B%0A return new Currency( %22XXX%22, -1, 0 );%0A %7D%0A %7D else %7B%0A return null;%0A %7D%0A
%7D;%0A%0A
|
c5fea028fee0fbe24620f75d72cf6212fa47536b | add missing function | src/database.js | src/database.js | const knex = require('knex');
const cfg = require('../config');
const db = knex(cfg.db);
module.exports = {
async createUser(telegramId) {
return db('user')
.insert({ telegram_id: telegramId });
},
async linkUser(telegramId, username) {
return db('user')
.where({ telegram_id: telegramId })
.update({ piikki_username: username });
},
async unlinkUser(telegramId) {
return db('user')
.where({ telegram_id: telegramId })
.update({ piikki_username: null, json_state: null });
},
async getUser(telegramId) {
return db('user')
.first()
.where({ telegram_id: telegramId });
},
async getUserState(telegramId) {
const user = await db('user')
.first('json_state')
.where({ telegram_id: telegramId });
return user ? JSON.parse(user.json_state) : null;
},
async setUserState(telegramId, state) {
return db('user')
.where({ telegram_id: telegramId })
.update({ json_state: (state ? JSON.stringify(state) : null) });
},
};
| JavaScript | 0.000004 | @@ -1007,12 +1007,172 @@
%7D);%0A %7D,
+%0A%0A async setDefaultGroup(telegramId, groupName) %7B%0A return db('user')%0A .where(%7B telegram_id: telegramId %7D)%0A .update(%7B default_group: groupName %7D);%0A %7D,
%0A%7D;%0A
|
094a08638a442e1197a0d8f3ba7b29d86dbac8af | Add back lowercase map for iLike | src/db/index.js | src/db/index.js | /* eslint-disable */
import Sequelize from 'sequelize'
import PaperTrail from 'sequelize-paper-trail'
import path from 'path'
import config from '../config'
const { database, username, password, hostname, port } = config.postgres
const { Op } = Sequelize
const operatorsAliases = {
eq: Op.eq,
ne: Op.ne,
gte: Op.gte,
gt: Op.gt,
lte: Op.lte,
lt: Op.lt,
not: Op.not,
in: Op.in,
noIn: Op.notIn,
is: Op.is,
like: Op.like,
notLike: Op.notLike,
iLike: Op.iLike,
notILike: Op.notILike,
regexp: Op.regexp,
notRegexp: Op.notRegexp,
iRegexp: Op.iRegexp,
notIRegexp: Op.notIRegexp,
between: Op.between,
notBetween: Op.notBetween,
overlap: Op.overlap,
contains: Op.contains,
contained: Op.contained,
adjacent: Op.adjacent,
strictLeft: Op.strictLeft,
strictRight: Op.strictRight,
noExtendRight: Op.noExtendRight,
noExtendLeft: Op.noExtendLeft,
and: Op.and,
or: Op.or,
any: Op.any,
all: Op.all,
values: Op.values,
col: Op.col
}
const db = new Sequelize(database, username, password, {
host: hostname,
port,
dialect: 'postgres',
logging: true,
pool: {
idle: 1000,
min: 0,
acquire: 30000
},
operatorsAliases
})
db.addHook('beforeCount', function (options) {
if (this._scope.include && this._scope.include.length > 0) {
options.distinct = true
options.col = this._scope.col || options.col || `"${this.options.name.singular}".id`
}
if (options.include && options.include.length > 0) {
options.include = undefined
}
})
/**
* Import all database models
* @param {[string]} modelNames the names of the models to import
* @returns {*}
*/
function importModels (modelNames) {
const models = modelNames.reduce((modelAcc, modelName) => {
modelAcc[modelName] = db.import(path.join(__dirname, modelName))
return modelAcc
}, {})
models.db = db
models.sequelize = db
Object.keys(models).forEach((modelName) => {
if (Reflect.has(models[modelName], 'associate')) {
models[modelName].associate(models)
}
})
return models
}
const models = importModels([
'Avatar',
'User',
'Rat',
'Rescue',
'RescueRats',
'Client',
'Code',
'Token',
'Reset',
'Epic',
'Ship',
'Decal',
'Group',
'UserGroups',
'VerificationToken',
'Session'
])
const paperTrail = PaperTrail.init(db, {
debug: true,
userModel: 'User',
exclude: [
'createdAt',
'updatedAt'
],
enableMigration: true,
enableRevisionChangeModel: true,
UUID: true,
continuationKey: 'userId'
})
paperTrail.defineModels({})
models.Rescue.Revisions = models.Rescue.hasPaperTrail()
export {
db,
db as sequelize,
Sequelize,
Op
}
export const {
Rat,
Rescue,
User,
Avatar,
RescueRats,
Client,
Code,
Token,
Reset,
Epic,
Ship,
Decal,
Group,
UserGroups,
VerificationToken,
Session
} = models
| JavaScript | 0.000007 | @@ -459,16 +459,35 @@
otLike,%0A
+ ilike: Op.iLike,%0A
iLike:
|
e782815985055d2ef53c50a348a80e6fdf03151c | change evidence spec test | spec/evidenceSpec.js | spec/evidenceSpec.js | /* global describe it expect belhop */
describe('belhop', function() {
'use strict';
var locations = [];
var evidence = null;
describe('evidence can be', function() {
it('created', function(done) {
var onSucc = function(response, status, xhr) {
expect(xhr.status).toEqual(201);
var evidenceLocation = xhr.getResponseHeader('location');
locations.push(evidenceLocation);
done();
};
var onErr = function(xhr) {
expect(xhr.status).toEqual(201);
done();
};
var cb = belhop.factory.callback(onSucc, onErr);
expect(belhop.evidence.create).toBeDefined();
var statement = 'p(evidence) increases p(canBeCreated)';
var citation = {type: 'PubMed', name: 'None', id: '10022765'};
var ctxt = {Species: 9606, Cell: 'fibroblast'};
var summary = 'Found this on a post-it near a sciency looking person.';
var meta = {status: 'draft'};
var factory = belhop.factory.evidence;
var ev = factory(statement, citation, ctxt, summary, meta);
belhop.evidence.create(ev, cb);
});
it('retrieved', function(done) {
expect(locations.length).toEqual(1);
var onSucc = function(response, status, xhr) {
expect(xhr.status).toEqual(200);
evidence = response[0];
done();
};
var onErr = function(xhr) {
expect(xhr.status).toEqual(200);
done();
};
var cb = belhop.factory.callback(onSucc, onErr);
expect(belhop.evidence.get).toBeDefined();
var tokens = locations[0].split('/');
var id = tokens.slice(-1)[0];
belhop.evidence.get(id, null, null, cb);
});
it('reset', function(done) {
expect(evidence).not.toBeNull();
var oldstmt = evidence.bel_statement;
var onSucc = function(response, status, xhr) {
expect(xhr.status).toEqual(200);
expect(evidence.bel_statement).toEqual(oldstmt);
done();
};
var onErr = function(xhr) {
expect(xhr.status).toEqual(200);
done();
};
var newstmt = 'a foo that bars';
evidence.bel_statement = newstmt;
var cb = belhop.factory.callback(onSucc, onErr);
expect(belhop.evidence.reset).toBeDefined();
belhop.evidence.reset(evidence, cb);
});
it('updated', function(done) {
expect(evidence).not.toBeNull();
var onSucc = function(response, status, xhr) {
expect(xhr.status).toEqual(202);
done();
};
var onErr = function(xhr) {
expect(xhr.status).toEqual(202);
done();
};
var newstmt = 'p(evidence) increases p(canBeUpdated)';
evidence.bel_statement = newstmt;
var cb = belhop.factory.callback(onSucc, onErr);
expect(belhop.evidence.update).toBeDefined();
belhop.evidence.update(evidence, cb);
});
it('deleted', function(done) {
expect(evidence).not.toBeNull();
var onSucc = function(response, status, xhr) {
expect(xhr.status).toEqual(202);
done();
};
var onErr = function(xhr) {
expect(xhr.status).toEqual(202);
done();
};
var cb = belhop.factory.callback(onSucc, onErr);
expect(belhop.evidence.delete).toBeDefined();
belhop.evidence.delete(evidence, cb);
});
});
});
| JavaScript | 0 | @@ -793,30 +793,90 @@
t =
-%7BSpecies
+%5B%0A %7Bname: 'Species', value
:
+%5B
9606,
-Cell
+10090%5D%7D,%0A %7Bname: 'Cell', value
:
+%5B
'fib
@@ -883,17 +883,39 @@
roblast'
-%7D
+, 'leukocyte'%5D%7D%0A %5D
;%0A
|
c6789ff6d39868cd231edbc000c45fcf15d0c258 | Add timer parser | specs/parser-spec.js | specs/parser-spec.js | describe("Parser", function () {
beforeEach(function () {
jasmine.clock().install();
jasmine.Ajax.install();
});
afterEach(function () {
jasmine.clock().uninstall();
jasmine.Ajax.uninstall();
});
it("parse data", function () {
var ew = new EchoesWorks({element: 'slide', source: 'data/data.json'});
//
spyOn(ew.parser, 'parse');
ew.parser.init('/data/data.json');
//jasmine.clock().tick(300);
//expect(ew.parser.parse).toHaveBeenCalled();
//
jasmine.Ajax.requests.mostRecent().respondWith({
"status": 200,
"contentType": 'text/plain',
"responseText": '[{"time": "00:05.51",' +
'"code": "https://raw.githubusercontent.com/phodal/echoesworks/master/bower.json","word": "hello, world, next"}]'
});
});
it("parse time", function () {
var ew = new EchoesWorks({element: 'slide', source: 'data/data.json'});
var result = ew.parser.parseTime(["00:05.51"]);
expect(result[0][0]).toBe(5.5);
});
});
| JavaScript | 0.000004 | @@ -206,41 +206,8 @@
);%0A%0A
-%09it(%22parse data%22, function () %7B%0A%09
%09var
@@ -275,20 +275,48 @@
son'%7D);%0A
-%09%09//
+%0A%09it(%22parse data%22, function () %7B
%0A%09%09spyOn
@@ -604,16 +604,8 @@
51%22,
-' +%0A%09%09%09'
%22cod
@@ -736,20 +736,30 @@
(%22parse
-time
+data correctly
%22, funct
@@ -777,76 +777,300 @@
var
-ew = new EchoesWorks(%7Belement: 'slide', source: 'data/data.json'%7D);%0A
+data = %5B%7B%0A%09%09%09%22time%22: %2200:05.51%22,%0A%09%09%09%22code%22: %22https://raw.githubusercontent.com/phodal/echoesworks/master/bower.json%22,%0A%09%09%09%22word%22: %22hello, world, next%22%0A%09%09%7D%5D;%0A%09%09var result = ew.parser.parse(data);%0A%09%09expect(result%5B2%5D%5B0%5D).toBe(%22hello, world, next%22);%0A%09%7D);%0A%0A%09it(%22parse time correctly%22, function () %7B
%0A%09%09v
|
1cebe2d8d150e92357b812ae28ce16894522fc96 | Remove extra logs from debug UI | src/adapters/debug/public/js/index.js | src/adapters/debug/public/js/index.js | $(function() {
window.chat = {
init: function() {
this.chatLog = $('.chat-history');
this.chatLogList = this.chatLog.find('ul');
this.userList = $('.people-list .list');
this.sendButton = $('button');
this.textArea = $('#message-to-send');
this.sendButton.on('click', this.sendMessage.bind(this));
this.textArea.on('keyup', this.sendMessageReturn.bind(this));
this.responseTemplateContent = $('#message-response-template').html();
this.userMessageTemplateContent = $("#message-template").html();
this.userConnectedTemplate = $("#user-connected-template").html();
this.loginForm = $('#login');
this.loginForm.submit(this.performLogin.bind(this));
this.typingIndicator = $('#typing');
this.socket = io();
this.socket
.on('ready', this.socketReady.bind(this))
.on('delete_message', this.deleteMessage.bind(this))
.on('bot_is_typing', this.botIsTyping.bind(this))
.on('add_reaction_to', this.addReactionTo.bind(this))
.on('bot_said', this.processBotMessage.bind(this))
.on('user_said', this.appendResponse.bind(this))
.on('user_connected', this.userConnected.bind(this))
.on('user_disconnected', this.userDisconnected.bind(this))
.on('extra_metadata', this.extraMetadata.bind(this));
},
addUser: function(user) {
console.log(('[data-user-id="' + user.id + '"]'));
if ($('[data-user-id="' + user.id + '"]').length === 0) {
this.userList.append(Mustache.render(this.userConnectedTemplate, user));
}
},
performLogin: function(e) {
e.preventDefault();
e.stopPropagation();
this.socket.emit('identify', {
name: $('#name').val(),
username: $('#username').val()
});
return false;
},
sendMessageReturn: function(e) {
if(e.keyCode === 13) {
e.preventDefault();
e.stopPropagation();
this.sendMessage();
return false;
}
},
sendMessage: function() {
var v = this.textArea.val().trim();
if(v.length) {
this.socket.emit('message', { text: v, ts: Date.now() });
this.textArea.val('');
}
},
scrollToBottom: function() {
this.chatLog.scrollTop(this.chatLog[0].scrollHeight);
},
appendResponse: function(incomingMessage) {
console.log('appendResponse', incomingMessage);
var context = {
time: new Date().toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"),
ts: incomingMessage.ts,
response: incomingMessage.text
};
var template;
if(incomingMessage.user.id === this.userId) {
context.from = 'You';
template = this.userMessageTemplateContent;
} else {
context.from = incomingMessage.user.username;
template = this.responseTemplateContent;
}
this.chatLogList.append(Mustache.render(template, context));
this.scrollToBottom();
},
socketReady: function(msg) {
this.userId = msg.id;
$('.login').fadeOut(300, function() {
this.textArea.focus();
}.bind(this));
msg.userList.forEach(this.addUser.bind(this));
},
deleteMessage: function(msg) {
console.log('deleteMessage', msg);
$('[data-ts="' + msg.ts + '"]').fadeOut(300, function() {
$(this).remove();
});
},
botIsTyping: function() {
this.typingIndicator.fadeIn(300);
},
addReactionTo: function(msg) {
console.log('addReactionTo', msg);
},
processBotMessage: function(msg) {
this.typingIndicator.fadeOut(300);
if(msg.to === 'channel' && !msg.channel) {
this.appendResponse({
ts: msg.ts,
text: msg.message,
user: {
username: 'Giskard'
}
});
} else {
console.log('processBotMessage', msg);
}
this.scrollToBottom();
},
userConnected: function(msg) {
console.log('userConnected', msg);
this.addUser(msg);
},
userDisconnected: function(msg) {
console.log('userDisconnected', msg);
$('[data-user-id="' + msg.id + '"]').remove();
},
extraMetadata: function(msg) {
console.log('extraMetadata', msg);
var _this = this;
$('[data-ts="' + msg.ts + '"]').find('.message').append('<br /><a href="' + msg.value + '" target="_blank"><img style="max-width:100%" src="' + msg.value + '" /></a>').find('img').load(function() {
_this.scrollToBottom();
});
}
};
$('#typing').fadeOut(0);
chat.init();
});
| JavaScript | 0 | @@ -1558,71 +1558,8 @@
) %7B%0A
- console.log(('%5Bdata-user-id=%22' + user.id + '%22%5D'));%0A
@@ -1620,24 +1620,24 @@
th === 0) %7B%0A
+
@@ -2687,68 +2687,8 @@
) %7B%0A
- console.log('appendResponse', incomingMessage);%0A
@@ -3673,55 +3673,8 @@
) %7B%0A
- console.log('deleteMessage', msg);%0A
@@ -4535,55 +4535,8 @@
) %7B%0A
- console.log('userConnected', msg);%0A
@@ -4619,58 +4619,8 @@
) %7B%0A
- console.log('userDisconnected', msg);%0A
@@ -4677,32 +4677,32 @@
e();%0A %7D,%0A
+
extraMet
@@ -4728,55 +4728,8 @@
) %7B%0A
- console.log('extraMetadata', msg);%0A
|
7294b8d0fbb277111b1fb005cffb6225b6c815a2 | add a few inputs to test tabbing through | src/demo/App.js | src/demo/App.js | /* eslint no-magic-numbers: 0 */
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Table} from '../lib';
import {mockData} from './data.js';
const clone = o => JSON.parse(JSON.stringify(o));
class App extends Component {
constructor() {
super();
this.state = {
dataframe: clone(mockData.dataframe),
columns: clone(mockData.columns),
editable: true,
row_selectable: 'multi',
selected_rows: [5, 10, 15]
};
}
render() {
return (
<div>
<label>test events:{'\u00A0\u00A0'}</label>
<input type="text" />
<br />
<br />
<Table
setProps={newProps => {
console.info('--->', newProps);
this.setState(newProps);
}}
{...this.state}
/>
</div>
);
}
}
App.propTypes = {
value: PropTypes.any,
};
export default App;
| JavaScript | 0 | @@ -672,24 +672,100 @@
e=%22text%22 /%3E%0A
+ %3Cinput type=%22text%22 /%3E%0A %3Cinput type=%22text%22 /%3E%0A
|
2f9c96f72bc1fac8234bf0d374c6de524d18b9f5 | include required id | src/demo/App.js | src/demo/App.js | /* eslint no-magic-numbers: 0 */
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Table} from '../lib';
import {mockData} from './data.js';
import Dropdown from 'react-select';
import TestFixtures from '../../tests/fixtures.json';
import {merge} from 'ramda';
const clone = o => JSON.parse(JSON.stringify(o));
class App extends Component {
constructor() {
super();
this.state = {
tableProps: {
dataframe: clone(mockData.dataframe),
columns: clone(mockData.columns),
editable: true,
row_selectable: 'multi',
selected_rows: [5, 10, 15],
},
selectedFixture: null,
};
}
render() {
return (
<div>
<div>
<label>Load test case</label>
<Dropdown
options={TestFixtures.map(t => ({
label: t.name,
value: JSON.stringify(t.props),
}))}
onChange={e =>
this.setState({
tableProps: JSON.parse(e.value),
selectedFixture: e.value,
})
}
value={this.state.selectedFixture}
/>
</div>
<hr />
<label>test events:{'\u00A0\u00A0'}</label>
<input type="text" />
<input type="text" />
<input type="text" />
<hr />
<Table
setProps={newProps => {
console.info('--->', newProps);
this.setState({
tableProps: merge(this.state.tableProps, newProps),
});
}}
{...this.state.tableProps}
/>
</div>
);
}
}
App.propTypes = {
value: PropTypes.any,
};
export default App;
| JavaScript | 0.000118 | @@ -456,16 +456,45 @@
rops: %7B%0A
+ id: 'table',%0A
|
f98e9ddd8fa02c5d16f7d94c8b811b21e2c39b8f | Update Siddhi quick start guide link | src/main/resources/web/js/tool-editor/constants.js | src/main/resources/web/js/tool-editor/constants.js | /**
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
define(function () {
"use strict"; // JS strict mode
/**
* Constants used by the tool - editor
*/
var constants = {
INITIAL_SOURCE_INSTRUCTIONS: "@App:name(\"SiddhiApp\")\n@App:description(\"Description of the plan\")\n\n" +
"-- Please refer to https://docs.wso2.com/display/SP400/Quick+Start+Guide " +
"on getting started with SP editor. \n\n"
};
return constants;
}); | JavaScript | 0 | @@ -968,53 +968,43 @@
s://
-docs.wso2.com/display/SP400/Q
+siddhi.io/en/v5.0/docs/q
uick
-+S
+-s
tart
-+Guide
+/
%22 +
@@ -1038,17 +1038,21 @@
d with S
-P
+iddhi
editor.
|
d09143029b0d45288e06b5b8c9dfb25997304b50 | use Promise.all when crawling filesystem | lib/crawlfs.js | lib/crawlfs.js | 'use strict'
const pify = require('pify')
const fs = process.versions.electron ? require('original-fs') : require('fs')
const glob = pify(require('glob'))
module.exports = function (dir, options) {
const metadata = {}
return glob(dir, options)
.then(filenames => {
for (const filename of filenames) {
const stat = fs.lstatSync(filename)
if (stat.isFile()) {
metadata[filename] = { type: 'file', stat: stat }
} else if (stat.isDirectory()) {
metadata[filename] = { type: 'directory', stat: stat }
} else if (stat.isSymbolicLink()) {
metadata[filename] = { type: 'link', stat: stat }
}
}
return [filenames, metadata]
})
}
| JavaScript | 0.000002 | @@ -48,16 +48,21 @@
st fs =
+pify(
process.
@@ -119,16 +119,17 @@
re('fs')
+)
%0Aconst g
@@ -161,110 +161,35 @@
))%0A%0A
-module.exports = function (dir, options) %7B%0A const metadata = %7B%7D%0A return glob(dir, options)%0A .then
+function determineFileType
(fil
@@ -197,103 +197,60 @@
name
-s =%3E
+)
%7B%0A
- for (const filename of filenames) %7B%0A const stat = fs.lstatSync(filename)%0A
+return fs.lstat(filename)%0A .then(stat =%3E %7B%0A
@@ -276,34 +276,31 @@
) %7B%0A
- metadata
+return
%5Bfilename%5D =
@@ -288,35 +288,33 @@
return %5Bfilename
-%5D =
+,
%7B type: 'file',
@@ -322,33 +322,32 @@
stat: stat %7D
+%5D
%0A
-
-
%7D else if (s
@@ -371,34 +371,31 @@
) %7B%0A
- metadata
+return
%5Bfilename%5D =
@@ -383,35 +383,33 @@
return %5Bfilename
-%5D =
+,
%7B type: 'direct
@@ -422,27 +422,26 @@
stat: stat %7D
+%5D
%0A
-
%7D else
@@ -482,59 +482,481 @@
- metadata%5Bfilename%5D = %7B type: 'link', stat: stat %7D
+return %5Bfilename, %7B type: 'link', stat: stat %7D%5D%0A %7D%0A%0A return %5Bfilename, undefined%5D%0A %7D)%0A%7D%0A%0Amodule.exports = function (dir, options) %7B%0A const metadata = %7B%7D%0A return glob(dir, options)%0A .then(filenames =%3E Promise.all(filenames.map(filename =%3E determineFileType(filename))))%0A .then(results =%3E %7B%0A const filenames = %5B%5D%0A for (const %5Bfilename, type%5D of results) %7B%0A filenames.push(filename)%0A if (type) %7B%0A metadata%5Bfilename%5D = type
%0A
|
a5efc9d95fd2f8442856ce79c2bb9ff3db545cf4 | Update Comments in CustomSwipeGesture | src/awesome_map/CustomSwipeGesture.js | src/awesome_map/CustomSwipeGesture.js | define(function(require) {
'use strict';
var Hammer = require('hammerjs');
var EVALUATION_DEPTH = 2;
var FRICTION = 2;
var moves = [];
function getDirection() {
var start = moves[0];
var end = moves[moves.length - 1];
var deltaX = Math.abs(end.deltaX - start.deltaX);
var deltaY = Math.abs(end.deltaY - start.deltaY);
if (deltaX >= deltaY) {
return start.deltaX > end.deltaX ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
}
return start.deltaY > end.deltaY ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
}
function getVelocity(axis) {
var deltaProp = axis === 'x' ? 'deltaX' : 'deltaY';
var start = moves[0];
var end = moves[moves.length - 1];
var deltaDistance = end[deltaProp] - start[deltaProp];
var deltaTime = end.timeStamp - start.timeStamp;
return Math.abs(deltaDistance / deltaTime / FRICTION);
}
// Default hammerjs Swipe gesture is here:
// https://github.com/hammerjs/hammer.js/blob/1.1.x/src/gestures/swipe.js
var CustomSwipeGesture = {
name: 'swipe',
index: 40,
defaults: {
// set 0 for unlimited, but this can conflict with transform
swipe_max_touches : 1,
swipe_velocity : 0.7
},
handler: function swipeGesture(ev, inst) {
if (ev.eventType === Hammer.EVENT_START) {
moves = [ev, ev];
}
else if (ev.eventType === Hammer.EVENT_MOVE) {
moves.push(ev);
}
else if (ev.eventType === Hammer.EVENT_END) {
// max touches
if (inst.options.swipe_max_touches > 0 &&
ev.touches.length > inst.options.swipe_max_touches) {
return;
}
// Calculate the velocity and direction using the last N moves
// in an attempt to provide for a more "instantaneous" velocity.
// By default, hammer calcs velocity and direction over the
// entire interaction, from start to end.
moves.splice(0, Math.max(0, moves.length - EVALUATION_DEPTH));
ev.velocityX = getVelocity('x');
ev.velocityY = getVelocity('y');
ev.direction = getDirection();
// when the distance we moved is too small we skip this gesture
// or we can be already in dragging
if (ev.velocityX > inst.options.swipe_velocity ||
ev.velocityY > inst.options.swipe_velocity
) {
// trigger swipe events
inst.trigger(this.name, ev);
inst.trigger(this.name + ev.direction, ev);
}
}
}
};
return CustomSwipeGesture;
});
| JavaScript | 0 | @@ -1191,17 +1191,17 @@
//
-s
+S
et 0 for
@@ -1248,16 +1248,17 @@
ransform
+.
%0A
@@ -1674,19 +1674,38 @@
//
-max touches
+Enforce the max touchs option.
%0A
@@ -2422,120 +2422,120 @@
//
-when the distance we moved is too small we skip this gesture%0A // or we can be already in dragging
+If either of the velocities are greater than the%0A // configured threshold, trigger a swipe event.
%0A
|
d48cafba711c35247ce3428ddb1f7276e525e309 | Make Function#bind existence checking simpler. (Thanks @vvakame!) | lib/empower.js | lib/empower.js | /**
* empower.js - Power Assert feature enhancer for assert function/object.
*
* https://github.com/twada/empower
*
* Copyright (c) 2013-2014 Takuto Wada
* Licensed under the MIT license.
* https://raw.github.com/twada/empower/master/MIT-LICENSE.txt
*
* A part of extend function is:
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
(function (root, factory) {
'use strict';
// using returnExports UMD pattern
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.empower = factory();
}
}(this, function () {
'use strict';
function defaultOptions () {
return {
destructive: false,
targetMethods: {
oneArg: [
'ok'
],
twoArgs: [
'equal',
'notEqual',
'strictEqual',
'notStrictEqual',
'deepEqual',
'notDeepEqual'
]
}
};
}
/**
* Enhance Power Assert feature to assert function/object.
* @param assert target assert function or object to enhance
* @param formatter power assert format function
* @param options enhancement options
* @return enhanced assert function/object
*/
function empower (assert, formatter, options) {
var typeOfAssert = (typeof assert),
config;
if ((typeOfAssert !== 'object' && typeOfAssert !== 'function') || assert === null) {
throw new TypeError('empower argument should be a function or object.');
}
if (typeof (function(){}.bind) !== 'function') {
throw new Error('empower module depends on method Function#bind that your browser does not support. Please add es5-shim.js to your dependencies.');
}
if (isEmpowered(assert)) {
return assert;
}
config = extend(defaultOptions(), (options || {}));
switch (typeOfAssert) {
case 'function':
return empowerAssertFunction(assert, formatter, config);
case 'object':
return empowerAssertObject(assert, formatter, config);
default:
throw new Error('Cannot be here');
}
}
function isEmpowered (assertObjectOrFunction) {
return (typeof assertObjectOrFunction._capt === 'function') && (typeof assertObjectOrFunction._expr === 'function');
}
function empowerAssertObject (assertObject, formatter, config) {
var enhancement = enhance(assertObject, formatter, config),
target = config.destructive ? assertObject : Object.create(assertObject);
return extend(target, enhancement);
}
function empowerAssertFunction (assertFunction, formatter, config) {
if (config.destructive) {
throw new Error('cannot use destructive:true to function.');
}
var enhancement = enhance(assertFunction, formatter, config),
powerAssert = function powerAssert (context, message) {
enhancement(context, message);
};
extend(powerAssert, assertFunction);
return extend(powerAssert, enhancement);
}
function enhance (target, formatter, config) {
var events = [],
enhancement = (typeof target === 'function') ? decorateOneArg(target, formatter) : {};
function _capt (value, kind, location) {
events.push({value: value, kind: kind, location: location});
return value;
}
function _expr (value, location, content) {
var captured = events;
events = [];
return { powerAssertContext: {value: value, location: location, content: content, events: captured} };
}
config.targetMethods.oneArg.forEach(function (methodName) {
if (typeof target[methodName] === 'function') {
enhancement[methodName] = decorateOneArg(target[methodName].bind(target), formatter);
}
});
config.targetMethods.twoArgs.forEach(function (methodName) {
if (typeof target[methodName] === 'function') {
enhancement[methodName] = decorateTwoArgs(target[methodName].bind(target), formatter);
}
});
enhancement._capt = _capt;
enhancement._expr = _expr;
return enhancement;
}
function isEspoweredValue (value) {
return (typeof value !== 'undefined') && (typeof value.powerAssertContext !== 'undefined');
}
function decorateOneArg (baseAssert, formatter) {
return function (value, message) {
var context;
if (! isEspoweredValue(value)) {
return baseAssert(value, message);
}
context = value.powerAssertContext;
return baseAssert(context.value, buildPowerAssertText(message, context, formatter));
};
}
function decorateTwoArgs (baseAssert, formatter) {
return function (arg1, arg2, message) {
var context, val1, val2;
if (!(isEspoweredValue(arg1) || isEspoweredValue(arg2))) {
return baseAssert(arg1, arg2, message);
}
if (isEspoweredValue(arg1)) {
context = extend({}, arg1.powerAssertContext);
val1 = arg1.powerAssertContext.value;
} else {
val1 = arg1;
}
if (isEspoweredValue(arg2)) {
if (isEspoweredValue(arg1)) {
context.events = context.events.concat(arg2.powerAssertContext.events);
} else {
context = extend({}, arg2.powerAssertContext);
}
val2 = arg2.powerAssertContext.value;
} else {
val2 = arg2;
}
return baseAssert(val1, val2, buildPowerAssertText(message, context, formatter));
};
}
function buildPowerAssertText (message, context, formatter) {
var powerAssertText = formatter(context);
return message ? message + ' ' + powerAssertText : powerAssertText;
}
// borrowed from qunit.js
function extend (a, b) {
var prop;
for (prop in b) {
if (b.hasOwnProperty(prop)) {
if (typeof b[prop] === 'undefined') {
delete a[prop];
} else {
a[prop] = b[prop];
}
}
}
return a;
}
// using returnExports UMD pattern with substack pattern
empower.defaultOptions = defaultOptions;
return empower;
}));
| JavaScript | 0 | @@ -1838,20 +1838,26 @@
of (
-f
+F
unction
-()%7B%7D
+.prototype
.bin
|
df30eb9b68fd248e7109a7f8a4debc257c98b8d9 | add from_user_name and to_user_name to balance_transactions copy | src/c/user-balance-transaction-row.js | src/c/user-balance-transaction-row.js | import m from 'mithril';
import h from '../h';
const I18nScope = _.partial(h.i18nScope, 'users.balance');
const userBalanceTrasactionRow = {
controller(args) {
const expanded = h.toggleProp(false, true);
if (args.index == 0) {
expanded.toggle();
}
return {
expanded
};
},
view(ctrl, args) {
const item = args.item,
createdAt = h.momentFromString(item.created_at, 'YYYY-MM-DD');
return m(`div[class='balance-card ${(ctrl.expanded() ? 'card-detailed-open' : '')}']`,
m('.w-clearfix.card.card-clickable', [
m('.w-row', [
m('.w-col.w-col-2.w-col-tiny-2', [
m('.fontsize-small.lineheight-tightest', createdAt.format('D MMM')),
m('.fontsize-smallest.fontcolor-terciary', createdAt.format('YYYY'))
]),
m('.w-col.w-col-10.w-col-tiny-10', [
m('.w-row', [
m('.w-col.w-col-4', [
m('div', [
m('span.fontsize-smaller.fontcolor-secondary', I18n.t('debit', I18nScope())),
m.trust(' '),
m('span.fontsize-base.text-error', `R$ ${h.formatNumber(Math.abs(item.debit), 2, 3)}`)
])
]),
m('.w-col.w-col-4', [
m('div', [
m('span.fontsize-smaller.fontcolor-secondary', I18n.t('credit', I18nScope())),
m.trust(' '),
m('span.fontsize-base.text-success', `R$ ${h.formatNumber(item.credit, 2, 3)}`)
])
]),
m('.w-col.w-col-4', [
m('div', [
m('span.fontsize-smaller.fontcolor-secondary', I18n.t('totals', I18nScope())),
m.trust(' '),
m('span.fontsize-base', `R$ ${h.formatNumber(item.total_amount, 2, 3)}`)
])
])
])
])
]),
m(`a.w-inline-block.arrow-admin.${(ctrl.expanded() ? 'arrow-admin-opened' : '')}.fa.fa-chevron-down.fontcolor-secondary[href="javascript:(void(0));"]`, { onclick: ctrl.expanded.toggle })
]),
(ctrl.expanded() ? m('.card', _.map(item.source, (transaction) => {
const pos = transaction.amount >= 0;
const event_data = {
subscription_reward_label: transaction.origin_objects.subscription_reward_label || '',
subscriber_name: transaction.origin_objects.subscriber_name,
service_fee: transaction.origin_objects.service_fee ? (transaction.origin_objects.service_fee*100.0) : '',
project_name: transaction.origin_objects.project_name,
contributitor_name: transaction.origin_objects.contributor_name,
};
return m('div', [
m('.w-row.fontsize-small.u-marginbottom-10', [
m('.w-col.w-col-2', [
m(`.text-${(pos ? 'success' : 'error')}`, `${pos ? '+' : '-'} R$ ${h.formatNumber(Math.abs(transaction.amount), 2, 3)}`)
]),
m('.w-col.w-col-10', [
(transaction.event_name === 'balance_expired'
? m('div', m.trust(I18n.t(`event_names.${transaction.event_name}`, I18nScope(event_data))))
: m('div', I18n.t(`event_names.${transaction.event_name}`, I18nScope(event_data)))
)
])
]),
m('.divider.u-marginbottom-10')
]);
})) : '')
);
}
};
export default userBalanceTrasactionRow;
| JavaScript | 0 | @@ -3480,32 +3480,196 @@
ntributor_name,%0A
+ from_user_name: transaction.origin_objects.from_user_name,%0A to_user_name: transaction.origin_objects.to_user_name,%0A
|
e3291a535f7749931ab682d5b20968a661a09d7d | remove old 'extension extractor' code, not being used any longer | lib/extract.js | lib/extract.js | var fs = require( 'fs' )
, path = require( 'path' )
, extractorPath = path.join( __dirname, "extractors" )
, XmlEntities = require('html-entities').XmlEntities
, entities = new XmlEntities()
, extensionExtractors = {}
, typeExtractors = {}
, regexExtractors = []
, WHITELIST_PRESERVE_LINEBREAKS = /[^A-Za-z\x80-\xFF 0-9 \u2018\u2019\u201C|\u201D\u2026 \u00C0-\u1FFF \u2C00-\uD7FF \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~'-\w\n\r]*/g
, WHITELIST_STRIP_LINEBREAKS = /[^A-Za-z\x80-\xFF 0-9 \u2018\u2019\u201C|\u201D\u2026 \u00C0-\u1FFF \u2C00-\uD7FF \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~'-\w]*/g
, SINGLE_QUOTES = /[\u2018|\u2019]/g
, DOUBLE_QUOTES = /[\u201C|\u201D]/g
, MULTIPLE_SPACES = /[ \t\v\u00A0]{2,}/g // multiple spaces, tabs, vertical tabs, non-breaking space
, extractors = []
, failedExtractorTypes = {}
, totalExtractors = 0
, satisfiedExtractors = 0
, hasInitialized = false
;
var registerExtractor = function( extractor ) {
if ( extractor.types ) {
extractor.types.forEach( function( type ) {
if ( typeof type === "string" ) {
typeExtractors[type] = extractor.extract;
} else {
if ( type instanceof RegExp ) {
regexExtractors.push( { reg: type, extractor: extractor.extract} );
}
}
});
}
if ( extractor.extensions ) {
extractor.extensions.forEach( function( ext ) {
extensionExtractors[ext] = extractor.extract;
});
}
};
var registerFailedExtractor = function( extractor, failedMessage ) {
if ( extractor.types ) {
extractor.types.forEach( function( type ) {
failedExtractorTypes[type] = failedMessage;
});
}
};
var testExtractor = function( extractor, options ) {
extractor.test( options, function( passedTest, failedMessage ) {
satisfiedExtractors++;
if ( passedTest ) {
registerExtractor( extractor );
} else {
registerFailedExtractor( extractor, failedMessage );
}
});
};
// global, all file type, content cleansing
var cleanseText = function( options, cb ) {
return function( error, text ) {
if ( !error ) {
// clean up text
if ( options.preserveLineBreaks ) {
text = text.replace( WHITELIST_PRESERVE_LINEBREAKS, ' ' );
} else {
text = text.replace( WHITELIST_STRIP_LINEBREAKS, ' ' );
}
text = text.replace( / (?! )/g, '' )
.replace( MULTIPLE_SPACES, ' ' ) // replace 2 or more spaces with 1 space
.replace( SINGLE_QUOTES, "'" ) // replace nasty quotes with simple ones
.replace( DOUBLE_QUOTES, '"' ); // replace nasty quotes with simple ones
text = entities.decode(text);
}
cb( error, text );
};
};
var initializeExtractors = function(options) {
hasInitialized = true;
extractors = fs.readdirSync( extractorPath ).filter( function( extractor ) {
return extractor !== "temp";
});
totalExtractors = extractors.length;
extractors.map( function ( item ) {
var fullExtractorPath = path.join( extractorPath, item );
return require( fullExtractorPath );
}).forEach( function( extractor ) {
if ( extractor.test ) {
testExtractor( extractor, options );
} else {
satisfiedExtractors++;
registerExtractor( extractor );
}
});
};
var findExtractor = function( type, filePath ) {
var extension = path.extname( filePath ).substring( 1 );
if ( extensionExtractors[extension] ) {
return extensionExtractors[extension];
} else if ( typeExtractors[type] ) {
return typeExtractors[type];
} else {
for ( var i = 0, iLen = regexExtractors.length; i < iLen; i++ ) {
var extractor = regexExtractors[i];
if ( type.match( extractor.reg ) ) {
return extractor.extractor;
}
}
}
}
var extract = function( type, filePath, options, cb ) {
if (!hasInitialized) {
initializeExtractors(options);
}
if ( totalExtractors === satisfiedExtractors ) {
var theExtractor = findExtractor( type, filePath );
if (theExtractor) {
cb = cleanseText( options, cb );
theExtractor( filePath, options, cb );
} else {
var msg = "Error for type: [[ " + type + " ]], file: [[ " + filePath + " ]]";
// update error message if type is supported but just not configured/installed properly
if (failedExtractorTypes[type]) {
msg += ", extractor for type exists, but failed to initialize. Messge: " + failedExtractorTypes[type];
}
var error = new Error( msg );
error.typeNotFound = true;
cb( error , null );
}
} else {
// async registration has not wrapped up
// try again later
setTimeout(function(){
extract( type, filePath, options, cb );
}, 100);
}
};
module.exports = extract;
| JavaScript | 0 | @@ -196,37 +196,8 @@
s()%0A
- , extensionExtractors = %7B%7D%0A
,
@@ -212,24 +212,24 @@
actors = %7B%7D%0A
+
, regexExt
@@ -1286,157 +1286,8 @@
%0A %7D
-%0A%0A if ( extractor.extensions ) %7B%0A extractor.extensions.forEach( function( ext ) %7B%0A extensionExtractors%5Bext%5D = extractor.extract;%0A %7D);%0A %7D
%0A%7D;%0A
@@ -3150,159 +3150,8 @@
%7B%0A
-var extension = path.extname( filePath ).substring( 1 );%0A if ( extensionExtractors%5Bextension%5D ) %7B%0A return extensionExtractors%5Bextension%5D;%0A %7D else
if (
@@ -3430,16 +3430,17 @@
%7D%0A %7D%0A%7D
+;
%0A%0Avar ex
@@ -3767,24 +3767,24 @@
ions, cb );%0A
-
%7D else %7B
@@ -3780,24 +3780,63 @@
%7D else %7B%0A
+ // cannot extract this file type%0A
var ms
|
6329e020cc0d133d1d5b16a0d24cbc172f15fe2e | Check the iframe existence before closing an application frame tab | seava.e4e.impl/src/main/resources/webapp/js/e4e/base/FrameNavigatorWithIframe.js | seava.e4e.impl/src/main/resources/webapp/js/e4e/base/FrameNavigatorWithIframe.js | /**
* DNet eBusiness Suite. Copyright: Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
e4e.base.FrameNavigatorWithIframe = {
/**
* Maximum number of tabs (application frames) which are allowed to be
* opened at a certain moment. Use -1 for unlimited.
*
* @type Integer
*/
maxOpenTabs : -1,
/**
* When open a new frame, until the translation files are loaded, set the
* tab title as the frame fully qualified name or its simple name
*/
titleAsSimpleName : true,
/**
* Lookup the application frame instance.
*
* @param {}
* frame
* @return {}
*/
getFrameInstance : function(frame) {
var theIFrame = window.frames[Constants.CMP_ID.FRAME_IFRAME_PREFIX
+ frame];
var theFrameInstance = null;
if (theIFrame) {
theFrameInstance = theIFrame.theFrameInstance;
}
return theFrameInstance;
},
/**
* Check if the given frame is already open.
*
* @param {}
* frame Frame name
* @return {}
*/
isFrameOpened : function(frame) {
return !Ext.isEmpty(document
.getElementById(Constants.CMP_ID.FRAME_IFRAME_PREFIX + frame))
},
/**
* Check if the given application frame is active, i.e. the corresponding
* tab panel is active.
*
* @param {}
* frame
* @return {}
*/
isFrameActive : function(frame) {
return (getApplication().getViewBody().getActiveTab().getId() == Constants.CMP_ID.FRAME_TAB_PREFIX);
},
/**
* Show the given frame. If it is open activate it otherwise open a new tab
* and load it there.
*
* @param {}
* frame
* @param {}
* params
*/
showFrame : function(frame, params) {
this._showFrameImpl(frame, params);
},
/**
* Internal implementation function.
*
* @param {}
* frame
* @param {}
* params
*/
_showFrameImpl : function(frame, params) {
if (!(params && params.url)) {
alert("Programming error: params.url not specified in showFrame!");
return;
}
var resourceType = (params.resourceType) ? params.resourceType : "";
var tabID = Constants.CMP_ID.FRAME_TAB_PREFIX + resourceType + frame;
var ifrID = Constants.CMP_ID.FRAME_IFRAME_PREFIX + resourceType + frame;
var vb = getApplication().getViewBody();
var tabTtl = frame;
if (this.titleAsSimpleName) {
tabTtl = tabTtl.substring(tabTtl.lastIndexOf('.') + 1,
tabTtl.length);
}
if (Ext.isEmpty(document.getElementById(ifrID))
&& !Ext.isEmpty(window.frames[ifrID])) {
delete window.frames[ifrID];
}
if (this.isFrameOpened(frame)) {
if (!this.isFrameActive(frame)) {
vb.setActiveTab(tabID);
}
} else {
if (this.maxOpenTabs > 0
&& ((vb.items.getCount() + 1) == this.maxOpenTabs)) {
Ext.Msg
.alert(
'Warning',
'You have reached the maximum number of opened tabs ('
+ (this.maxOpenTabs)
+ ').<br> It is not allowed to open more tabs.');
return;
}
var _odfn = function() {
Ext.destroy(window.frames[this.n21_iframeID].__theViewport__);
Ext.destroy(window.frames[this.n21_iframeID].theFrameInstance);
try {
delete window.frames[this.n21_iframeID];
} catch (e) {
}
this.callParent();
};
var beforeCloseFn = function(tab, eOpts) {
if (window.frames[this.n21_iframeID].theFrameInstance.isDirty()) {
return confirm(Main.translate("msg",
"dirty_data_on_frame_close"));
}
return true;
};
var _p = new Ext.Panel(
{
onDestroy : _odfn,
title : tabTtl,
fqn : frame,
id : tabID,
n21_iframeID : ifrID,
autoScroll : true,
layout : 'fit',
closable : true,
listeners : {
beforeclose : {
fn : beforeCloseFn
}
},
html : '<div style="width:100%;height:100%;overflow: hidden;" id="div_'
+ frame
+ '" ><iframe id="'
+ ifrID
+ '" name="'
+ ifrID
+ '" src="'
+ params.url
+ '" style="border:0;width:100%;height:100%;overflow: hidden" FRAMEBORDER="no"></iframe></div>'
});
vb.add(_p);
vb.setActiveTab(tabID);
}
}
};
| JavaScript | 0 | @@ -3280,20 +3280,26 @@
) %7B%0A%09%09%09%09
-if (
+var _fr =
window.f
@@ -3314,32 +3314,76 @@
is.n21_iframeID%5D
+;%0A%09%09%09%09if (_fr && _fr.theFrameInstance && _fr
.theFrameInstanc
|
e034731cdc07565e324f18988834c5d510133170 | Order classes. | assets/js/components/DateRangeSelector.js | assets/js/components/DateRangeSelector.js | /**
* Date range selector component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { useClickAway } from 'react-use';
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { useCallback, useRef, useState, useContext } from '@wordpress/element';
import { ESCAPE, TAB } from '@wordpress/keycodes';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import DateRangeIcon from '../../svg/date-range.svg';
import { CORE_USER } from '../googlesitekit/datastore/user/constants';
import { useKeyCodesInside } from '../hooks/useKeyCodesInside';
import { getAvailableDateRanges } from '../util/date-range';
import ViewContextContext from './Root/ViewContextContext';
import Menu from './Menu';
import Button from './Button';
import { trackEvent } from '../util';
import { useFeature } from '../hooks/useFeature';
const { useSelect, useDispatch } = Data;
export default function DateRangeSelector() {
const unifiedDashboardEnabled = useFeature( 'unifiedDashboard' );
const ranges = getAvailableDateRanges();
const dateRange = useSelect( ( select ) =>
select( CORE_USER ).getDateRange()
);
const { setDateRange } = useDispatch( CORE_USER );
const [ menuOpen, setMenuOpen ] = useState( false );
const menuWrapperRef = useRef();
const viewContext = useContext( ViewContextContext );
useClickAway( menuWrapperRef, () => setMenuOpen( false ) );
useKeyCodesInside( [ ESCAPE, TAB ], menuWrapperRef, () =>
setMenuOpen( false )
);
const handleMenu = useCallback( () => {
setMenuOpen( ! menuOpen );
}, [ menuOpen ] );
const handleMenuItemSelect = useCallback(
( index ) => {
const newDateRange = Object.values( ranges )[ index ].slug;
if ( dateRange !== newDateRange ) {
trackEvent(
`${ viewContext }_headerbar`,
'change_daterange',
newDateRange
);
}
setDateRange( newDateRange );
setMenuOpen( false );
},
[ ranges, setDateRange, viewContext, dateRange ]
);
const currentDateRangeLabel = ranges[ dateRange ]?.label;
const menuItems = Object.values( ranges ).map( ( range ) => range.label );
return (
<div
ref={ menuWrapperRef }
className="googlesitekit-date-range-selector googlesitekit-dropdown-menu mdc-menu-surface--anchor"
>
<Button
className={ classnames(
'googlesitekit-header__date-range-selector-menu',
'mdc-button--dropdown',
'googlesitekit-header__dropdown',
{
'googlesitekit-header__date-range-selector-menu--has-unified-dashboard': unifiedDashboardEnabled,
}
) }
text
onClick={ handleMenu }
icon={ <DateRangeIcon width="18" height="20" /> }
aria-haspopup="menu"
aria-expanded={ menuOpen }
aria-controls="date-range-selector-menu"
>
{ currentDateRangeLabel }
</Button>
<Menu
menuOpen={ menuOpen }
menuItems={ menuItems }
onSelected={ handleMenuItemSelect }
id="date-range-selector-menu"
className="googlesitekit-width-auto"
/>
</div>
);
}
| JavaScript | 0 | @@ -2891,63 +2891,8 @@
es(%0A
-%09%09%09%09%09'googlesitekit-header__date-range-selector-menu',%0A
%09%09%09%09
@@ -2951,24 +2951,79 @@
_dropdown',%0A
+%09%09%09%09%09'googlesitekit-header__date-range-selector-menu',%0A
%09%09%09%09%09%7B%0A%09%09%09%09%09
|
44a91211ff7fb2c8f51b4e6fed06f5d8460bcd3b | fix eslint | bin/plugin.js | bin/plugin.js | var os = require('os');
var cp = require('child_process');
var fs = require('fs');
var path = require('path');
var fse = require('fs-extra2');
var CMD_SUFFIX = process.platform === 'win32' ? '.cmd' : '';
var WHISLTE_PLUGIN_RE = /^((?:@[\w-]+\/)?whistle\.[a-z\d_-]+)(?:\@([\w.^~*-]*))?$/;
var PLUGIN_PATH = path.join(getWhistlePath(), 'plugins');
var CUSTOM_PLUGIN_PATH = path.join(getWhistlePath(), 'custom_plugins');
var PACKAGE_JSON = '{"repository":"https://github.com/avwo/whistle","license":"MIT"}';
var LICENSE = 'Copyright (c) 2019 avwo';
var RESP_URL = 'https://github.com/avwo/whistle';
function getInstallPath(name, dir) {
return path.join(dir || CUSTOM_PLUGIN_PATH, name);
}
function getHomedir() {
//默认设置为`~`,防止Linux在开机启动时Node无法获取homedir
return (typeof os.homedir == 'function' ? os.homedir() :
process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME']) || '~';
}
function getWhistlePath() {
return process.env.WHISTLE_PATH || path.join(getHomedir(), '.WhistleAppData');
}
function getPlugins(argv) {
return argv.filter(function(name) {
return WHISLTE_PLUGIN_RE.test(name);
});
}
function removeDir(installPath) {
if (fs.existsSync(installPath)) {
fse.removeSync(installPath);
}
}
function removeOldPlugin(name) {
removeDir(path.join(PLUGIN_PATH, 'node_modules', name));
removeDir(path.join(PLUGIN_PATH, 'node_modules', getTempName(name)));
}
function getTempName(name) {
if (name.indexOf('/') === -1) {
return '.' + name;
}
name = name.split('/');
var lastIndex = name.length - 1;
name[lastIndex] = '.' + name[lastIndex];
return name.join('/');
}
function getInstallDir(argv) {
var result = { argv: argv };
for (var i = 0, len = argv.length; i < len; i++) {
var option = argv[i];
if (option && option.indexOf('--dir=') === 0) {
var dir = option.substring(option.indexOf('=') + 1);
result.dir = dir && path.resolve(dir);
argv.splice(i, 1);
return result;
}
}
return result;
}
function install(cmd, name, argv, ver) {
argv = argv.slice();
var result = getInstallDir(argv);
argv = result.argv;
var installPath = getInstallPath(getTempName(name), result.dir);
fse.ensureDirSync(installPath);
fse.emptyDirSync(installPath);
var pkgJson = PACKAGE_JSON;
if (ver) {
pkgJson = pkgJson.replace(',', ',"dependencies":{"' + name + '":"' + ver + '"},')
}
fs.writeFileSync(path.join(installPath, 'package.json'), pkgJson);
fs.writeFileSync(path.join(installPath, 'LICENSE'), LICENSE);
fs.writeFileSync(path.join(installPath, 'README.md'), RESP_URL);
argv.unshift('install', name);
cp.spawn(cmd, argv, {
stdio: 'inherit',
cwd: installPath
}).on('exit', function(code) {
if (code) {
removeDir(installPath);
} else {
var realPath = getInstallPath(name, result.dir);
removeDir(realPath);
try {
fs.renameSync(installPath, realPath);
} catch (e) {
fse.copySync(installPath, realPath);
try {
removeDir(installPath);
} catch (e) {}
}
try {
var pkgPath = path.join(realPath, 'node_modules', name, 'package.json');
if (fs.statSync(pkgPath).mtime.getFullYear() < 2010) {
var now = new Date();
fs.utimesSync(pkgPath, now, now);
}
} catch (e) {}
}
});
}
exports.install = function(cmd, argv) {
var plugins = getPlugins(argv);
if (!plugins.length) {
return;
}
argv = argv.filter(function(name) {
return plugins.indexOf(name) === -1;
});
cmd += CMD_SUFFIX;
argv.push('--no-package-lock');
plugins.forEach(function(name) {
if (WHISLTE_PLUGIN_RE.test(name)) {
name = RegExp.$1;
var ver = RegExp.$2;
removeOldPlugin(name);
install(cmd, name, argv, ver);
}
});
};
exports.uninstall = function(plugins) {
var result = getInstallDir(plugins);
plugins = result.argv;
getPlugins(plugins).forEach(function(name) {
if (WHISLTE_PLUGIN_RE.test(name)) {
name = RegExp.$1;
!result.dir && removeOldPlugin(name);
removeDir(getInstallPath(name, result.dir));
}
});
};
exports.run = function(cmd, argv) {
var newPath = [];
fse.ensureDirSync(CUSTOM_PLUGIN_PATH);
fs.readdirSync(CUSTOM_PLUGIN_PATH).forEach(function(name) {
if (!name.indexOf('whistle.')) {
newPath.push(path.join(CUSTOM_PLUGIN_PATH, name, 'node_modules/.bin'));
} else if (name[0] === '@') {
try {
fs.readdirSync(path.join(CUSTOM_PLUGIN_PATH, name)).forEach(function(modName) {
newPath.push(path.join(CUSTOM_PLUGIN_PATH, name, modName, 'node_modules/.bin'));
});
} catch (e) {}
}
});
process.env.PATH && newPath.push(process.env.PATH);
newPath = newPath.join(os.platform() === 'win32' ? ';' : ':');
process.env.PATH = newPath;
cp.spawn(cmd + CMD_SUFFIX, argv, {
stdio: 'inherit',
env: process.env
});
};
| JavaScript | 0.998292 | @@ -2374,16 +2374,17 @@
+ '%22%7D,')
+;
%0A %7D%0A f
|
6c38ca4b3af365dec1dd6fc7479ebe893e9ee77a | Add deleteItemsById to customerInvoice | src/pages/dataTableUtilities/reducer/getReducer.js | src/pages/dataTableUtilities/reducer/getReducer.js | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Method using a factory pattern variant to get a reducer
* for a particular page or page style.
*
* For a new page - create a constant object with the
* methods from reducerMethods which are composed to create
* a reducer. Add to PAGE_REDUCERS.
*
* Each key value pair in a reducer object should be in the form
* action type: reducer function, returning a new state object
*
*/
import {
filterData,
editTotalQuantity,
focusNextCell,
selectRow,
deselectRow,
deselectAll,
focusCell,
sortData,
openBasicModal,
closeBasicModal,
addMasterListItems,
addItem,
editPageObject,
} from './reducerMethods';
/**
* Used for actions that should be in all pages using a data table.
*/
const BASE_TABLE_PAGE_REDUCER = {
focusNextCell,
focusCell,
sortData,
};
const customerInvoice = {
...BASE_TABLE_PAGE_REDUCER,
filterData,
editTotalQuantity,
selectRow,
deselectRow,
deselectAll,
openBasicModal,
closeBasicModal,
addMasterListItems,
addItem,
editPageObject,
};
const PAGE_REDUCERS = {
customerInvoice,
};
const getReducer = page => {
const reducer = PAGE_REDUCERS[page];
return (state, action) => {
const { type } = action;
if (!reducer[type]) return state;
return reducer[type](state, action);
};
};
export default getReducer;
| JavaScript | 0.000001 | @@ -672,16 +672,35 @@
Object,%0A
+ deleteItemsById,%0A
%7D from '
@@ -1097,16 +1097,35 @@
Object,%0A
+ deleteItemsById,%0A
%7D;%0A%0Acons
|
c7569ac7e342e8ff1b635850a5c41d72f63adf20 | use the right server.js | bin/server.js | bin/server.js | /* eslint no-console: 0 */
import express from 'express';
import http from 'http';
import httpProxy from 'http-proxy';
import path from 'path';
import { port, apiHost, apiPort } from '../config/env';
const targetUrl = `http://${apiHost}:${apiPort}`;
const app = express();
const server = new http.Server(app);
const proxy = httpProxy.createProxyServer({
target: targetUrl,
ws: true,
});
app.use('/', express.static(path.resolve(__dirname, '../public')));
app.use('/api', (req, res) => {
proxy.web(req, res, { target: `${targetUrl}/api` });
});
server.on('upgrade', (req, socket, head) => {
proxy.ws(req, socket, head);
});
proxy.on('error', (error, req, res) => {
if (error.code !== 'ECONNRESET') {
console.error('proxy error', error);
}
if (!res.headersSent) {
res.writeHead(500, { 'content-type': 'application/json' });
}
const json = { error: 'proxy_error', reason: error.message };
res.end(JSON.stringify(json));
});
app.listen(port, (err) => {
if (err) {
console.error(err);
} else {
console.info(`Server listening on port ${port}!`);
}
}); | JavaScript | 0.000002 | @@ -7,1075 +7,461 @@
int
-no-console: 0 */%0Aimport express from 'express';%0Aimport http from 'http';%0Aimport httpProxy from 'http-proxy';%0Aimport path from
+global-require: 0 */%0A%0Aconst path = require(
'path'
+)
;%0A
-import %7B port, apiHost, apiPort %7D from '../config/env';%0Aconst targetUrl = %60http://$%7BapiHost%7D:$%7BapiPort%7D%60;%0Aconst app = express();%0Aconst server = new http.Server(app);%0Aconst proxy = httpProxy.createProxyServer(%7B%0A target: targetUrl,%0A ws: true,%0A%7D);%0Aapp.use('/', express.static(path.resolve(__dirname, '../public')));%0Aapp.use('/api', (req, res) =%3E %7B%0A proxy.web(req, res, %7B target: %60$%7BtargetUrl%7D/api%60 %7D);%0A%7D);%0Aserver.on('upgrade', (req, socket, head) =%3E %7B%0A proxy.ws(req, socket, head);%0A%7D);%0Aproxy.on('error', (error, req, res) =%3E %7B%0A if (error.code !== 'ECONNRESET') %7B%0A console.error('proxy error', error);%0A %7D%0Aif (!res.headersSent) %7B%0A res.writeHead(500, %7B 'content-type': 'application/json' %7D);%0A %7D%0Aconst json = %7B error: 'proxy_
+const webpackIsomorphicToolsConfig = require('../webpack/webpack-isomorphic-tools');%0Aconst WebpackIsomorphicTools = require('webpack-isomorphic-tools');%0A%0Aconst rootDir = path.resolve(__dirname, '..');%0A%0Aglobal.webpackIsomorphicTools = new WebpackIsomorphicTools(webpackIsomorphicToolsConfig)%0A .development(process.env.NODE_ENV === 'development')%0A .serv
er
+(
ro
-r', reason: error.message %7D;%0Ares.end(JSON.stringify(json));%0A%7D);%0Aapp.listen(port, (err) =%3E %7B%0A if (err) %7B%0A console.error(err);%0A %7D else %7B%0A console.info(%60Server listening on port $%7Bport%7D!%60
+otDir, () =%3E %7B%0A require('./_server'
);%0A
-%7D%0A
%7D);
+%0A
|
0464f06fa4a2555bfc65ca8d6404760986e565ab | Add creation of programSupplierRequisition reducer | src/pages/dataTableUtilities/reducer/getReducer.js | src/pages/dataTableUtilities/reducer/getReducer.js | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Method using a factory pattern variant to get a reducer
* for a particular page or page style.
*
* For a new page - create a constant object with the
* methods from reducerMethods which are composed to create
* a reducer. Add to PAGE_REDUCERS.
*
* Each key value pair in a reducer object should be in the form
* action type: reducer function, returning a new state object
*
*/
import {
filterData,
focusNextCell,
selectRow,
deselectRow,
deselectAll,
focusCell,
sortData,
openBasicModal,
closeBasicModal,
addMasterListItems,
addItem,
editTheirRef,
editComment,
deleteRecordsById,
refreshData,
createAutomaticOrder,
hideOverStocked,
showOverStocked,
editField,
selectAll,
hideStockOut,
showStockOut,
selectItems,
editName,
editCountedTotalQuantity,
openStocktakeBatchModal,
closeStocktakeBatchModal,
openModal,
openCommentModal,
openStocktakeOutdatedItems,
resetStocktake,
} from './reducerMethods';
/**
* Used for actions that should be in all pages using a data table.
*/
const BASE_TABLE_PAGE_REDUCER = {
focusNextCell,
focusCell,
sortData,
};
const customerInvoice = {
...BASE_TABLE_PAGE_REDUCER,
filterData,
editField,
selectRow,
deselectRow,
deselectAll,
openBasicModal,
closeBasicModal,
addMasterListItems,
addItem,
editTheirRef,
editComment,
deleteRecordsById,
refreshData,
};
const customerInvoices = {
...BASE_TABLE_PAGE_REDUCER,
filterData,
selectRow,
deselectRow,
deselectAll,
openBasicModal,
closeBasicModal,
deleteRecordsById,
};
const supplierInvoice = {
...BASE_TABLE_PAGE_REDUCER,
filterData,
selectRow,
deselectRow,
deselectAll,
closeBasicModal,
openBasicModal,
editTheirRef,
editComment,
refreshData,
addItem,
editField,
deleteRecordsById,
};
const supplierRequisition = {
...BASE_TABLE_PAGE_REDUCER,
filterData,
selectRow,
deselectRow,
deselectAll,
openBasicModal,
closeBasicModal,
editTheirRef,
editComment,
refreshData,
addMasterListItems,
addItem,
createAutomaticOrder,
hideOverStocked,
showOverStocked,
editField,
deleteRecordsById,
};
const programSupplierRequisition = {
...BASE_TABLE_PAGE_REDUCER,
filterData,
selectRow,
deselectRow,
deselectAll,
openBasicModal,
closeBasicModal,
editTheirRef,
editComment,
refreshData,
addMasterListItems,
addItem,
createAutomaticOrder,
hideOverStocked,
showOverStocked,
editField,
};
const supplierRequisitions = {
sortData,
filterData,
selectRow,
deselectRow,
openBasicModal,
closeBasicModal,
refreshData,
};
const stocktakes = {
openBasicModal,
closeBasicModal,
filterData,
selectRow,
deselectAll,
deselectRow,
sortData,
};
const stocktakeManager = {
selectRow,
deselectAll,
deselectRow,
sortData,
filterData,
selectAll,
hideStockOut,
showStockOut,
selectItems,
editName,
};
const stocktakeEditor = {
...BASE_TABLE_PAGE_REDUCER,
sortData,
filterData,
editComment,
openBasicModal,
closeBasicModal,
editCountedTotalQuantity,
refreshData,
openStocktakeBatchModal,
closeStocktakeBatchModal,
openModal,
openCommentModal,
openStocktakeOutdatedItems,
resetStocktake,
};
const PAGE_REDUCERS = {
customerInvoice,
customerInvoices,
supplierInvoice,
supplierRequisitions,
supplierRequisition,
programSupplierRequisition,
stocktakes,
stocktakeManager,
stocktakeEditor,
};
const getReducer = page => {
const reducer = PAGE_REDUCERS[page];
return (state, action) => {
const { type } = action;
if (!reducer[type]) return state;
return reducer[type](state, action);
};
};
export default getReducer;
| JavaScript | 0 | @@ -3292,24 +3292,356 @@
cktake,%0A%7D;%0A%0A
+const programSupplierRequisition = %7B%0A ...BASE_TABLE_PAGE_REDUCER,%0A filterData,%0A selectRow,%0A deselectRow,%0A deselectAll,%0A openBasicModal,%0A closeBasicModal,%0A editTheirRef,%0A editComment,%0A refreshData,%0A addMasterListItems,%0A addItem,%0A createAutomaticOrder,%0A useSuggestedQuantities,%0A hideOverStocked,%0A showOverStocked,%0A%7D;%0A%0A
const PAGE_R
|
86098625e2d0b912209f14f459f7274c507734b0 | fix for $.extend to du.extend. | lib/filters/QueryStringFilter.js | lib/filters/QueryStringFilter.js | /**
* Parases a query string into a query object
*/
Doppelganger.Filters.QueryStringFilter = new Filter('QueryString', function(request){
if (!(routeData && routeData.params)) {
// Only need to read query parameters on first load.
routeData = $.extend(routeData, {params: Arg.all()});
}
//@todo figure out request object
request.setQuery(query);
return routeData;
});
| JavaScript | 0 | @@ -247,9 +247,10 @@
a =
-$
+du
.ext
|
51bce92bc8bfc2ee0201c851626d862989919bfd | Set intercept right | extension/chrome/background.js | extension/chrome/background.js | "use strict";
const DOMAIN = "http://127.0.0.1:8000"
const SUBMIT_URL = DOMAIN + "/bookmarks/create";
const CHECK_URL = DOMAIN + "/autotags/check";
const REFER_VALUE = DOMAIN + "/.chrome_extension";
let intercept = false;
// Call the callback with the csrf token (read from a cookie)
let getCsrf = function(callback) {
chrome.cookies.get({"url":DOMAIN, "name":"csrftoken"}, (c) => {
callback(c.value);
});
};
// If intercept is true, intercept the request to the submit page and add the referer header (Django requires it to be
// set)
chrome.webRequest.onBeforeSendHeaders.addListener((r) => {
if(!intercept) return;
r.requestHeaders.push({"name":"Referer", "value":REFER_VALUE});
return {requestHeaders: r.requestHeaders};
}, {"urls":[SUBMIT_URL, CHECK_URL]}, ["blocking", "requestHeaders"]);
chrome.runtime.onMessage.addListener(([type, data], sender) => {
switch(type) {
case "submit":
// A bookmark is to be submitted
let toSub = JSON.stringify(data);
intercept = true;
getCsrf((token) => {
fetch(SUBMIT_URL, {
"method":"POST", headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-CSRFToken": token
},
body:"obj=" + encodeURIComponent(toSub),
credentials:"include"
}).then(function(res) {
intercept = false;
chrome.runtime.sendMessage(["submitDone", res.ok]);
});
});
break;
case "check":
// Check to see what tags to autotag
getCsrf((token) => {
fetch(CHECK_URL, {
"method":"POST", headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-CSRFToken": token
},
body:"url=" + encodeURIComponent(data),
credentials:"include"
}).then(function(res) {
intercept = false;
res.json().then((json) => {
chrome.runtime.sendMessage(["checkDone", json.results]);
});
});
});
break;
}
});
| JavaScript | 0.000013 | @@ -1024,38 +1024,8 @@
a);%0A
- intercept = true;%0A
@@ -1058,32 +1058,66 @@
rf((token) =%3E %7B%0A
+ intercept = true;%0A
@@ -1760,32 +1760,66 @@
rf((token) =%3E %7B%0A
+ intercept = true;%0A
|
47c2adc7c35a165e1f5f3568cbf7c7dc3369ab0b | fix sms elections creation | avAdmin/admin-directives/create/create.js | avAdmin/admin-directives/create/create.js | angular.module('avAdmin')
.directive('avAdminCreate', ['$q', 'Authmethod', 'ElectionsApi', '$state', '$i18next', function($q, Authmethod, ElectionsApi, $state, $i18next) {
// we use it as something similar to a controller here
function link(scope, element, attrs) {
scope.creating = false;
scope.log = '';
if (ElectionsApi.currentElections.length === 0 && !!ElectionsApi.currentElection) {
scope.elections = [ElectionsApi.currentElection];
} else {
scope.elections = ElectionsApi.currentElections;
ElectionsApi.currentElections = [];
}
function getCreatePerm(el) {
console.log("creating perm for election " + el.title);
var deferred = $q.defer();
Authmethod.getPerm("create", "AuthEvent", 0)
.success(function(data) {
var perm = data['permission-token'];
el.perm = perm;
deferred.resolve(el);
}).error(deferred.reject);
return deferred.promise;
}
function logInfo(text) {
scope.log += "<p>" + text + "</p>";
}
function logError(text) {
scope.log += "<p class=\"text-brand-danger\">" + text + "</p>";
}
function createAuthEvent(el) {
console.log("creating auth event for election " + el.title);
var deferred = $q.defer();
// Creating the authentication
logInfo($i18next('avAdmin.create.creating', {title: el.title}));
var d = {
auth_method: el.census.auth_method,
census: el.census.census,
config: el.census.config,
extra_fields: []
};
d.extra_fields = _.filter(el.census.extra_fields, function(ef) { return !ef.must; });
Authmethod.createEvent(d)
.success(function(data) {
el.id = data.id;
deferred.resolve(el);
}).error(deferred.reject);
return deferred.promise;
}
function addCensus(el) {
console.log("adding census for election " + el.title);
var deferred = $q.defer();
// Adding the census
logInfo($i18next('avAdmin.create.census', {title: el.title, id: el.id}));
Authmethod.addCensus(el.id, el.census.voters, 'disabled')
.success(function(data) {
deferred.resolve(el);
}).error(deferred.reject);
return deferred.promise;
}
function registerElection(el) {
console.log("registering election " + el.title);
var deferred = $q.defer();
// Registering the election
logInfo($i18next('avAdmin.create.reg', {title: el.title, id: el.id}));
ElectionsApi.command(el, '', 'POST', el)
.then(function(data) { deferred.resolve(el); })
.catch(deferred.reject);
return deferred.promise;
}
function createElection(el) {
console.log("creating election " + el.title);
var deferred = $q.defer();
// Creating the election
logInfo($i18next('avAdmin.create.creatingEl', {title: el.title, id: el.id}));
ElectionsApi.command(el, 'create', 'POST', {})
.then(function(data) { deferred.resolve(el); })
.catch(deferred.reject);
return deferred.promise;
}
function addElection(i) {
var deferred = $q.defer();
if (i === scope.elections.length) {
var el = scope.elections[i - 1];
$state.go("admin.dashboard", {id: el.id});
return;
}
var promise = deferred.promise;
promise = promise
.then(getCreatePerm)
.then(createAuthEvent)
.then(addCensus)
.then(registerElection)
.then(createElection)
.then(function(el) {
console.log("waiting for election " + el.title);
waitForCreated(el.id, function () {
addElection(i+1);
});
})
.catch(function(error) {
scope.creating = false;
scope.creating_text = '';
logError(angular.toJson(error));
});
deferred.resolve(scope.elections[i]);
}
function createElections() {
var deferred = $q.defer();
addElection(0);
var promise = deferred.promise;
scope.creating = true;
}
function waitForCreated(id, f) {
console.log("waiting for election id = " + id);
ElectionsApi.getElection(id, true)
.then(function(el) {
var deferred = $q.defer();
if (el.status === 'created') {
f();
} else {
setTimeout(function() { waitForCreated(id, f); }, 3000);
}
});
}
angular.extend(scope, {
createElections: createElections,
});
}
return {
restrict: 'AE',
scope: {
},
link: link,
templateUrl: 'avAdmin/admin-directives/create/create.html'
};
}]);
| JavaScript | 0.998978 | @@ -1556,24 +1556,167 @@
.title%7D));%0A%0A
+ if (el.census.config.subject && el.census.auth_method !== 'email') %7B%0A delete el.census.config.subject;%0A %7D%0A%0A
|
d688b37bb087c2998688c248770c2fa140921c11 | Remove unnecesary code | lib/helpers.js | lib/helpers.js | /*
Copyright 2017 Bitnami.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
const _ = require('lodash');
const fs = require('fs');
const moment = require('moment');
const path = require('path');
const yaml = require('js-yaml');
function loadKubeConfig() {
const kubeCfgPath = path.join(process.env.HOME, '.kube/config');
let config = {};
if (process.env.KUBECONFIG) {
const configFiles = process.env.KUBECONFIG.split(':');
_.each(configFiles, configFile => {
_.defaults(config, yaml.safeLoad(fs.readFileSync(configFile)));
});
} else if (!fs.existsSync(kubeCfgPath)) {
throw new Error(
'Unable to locate the configuration file for your cluster. ' +
'Make sure you have your cluster configured locally'
);
} else {
config = yaml.safeLoad(fs.readFileSync(kubeCfgPath));
}
return config;
}
function getContextInfo(config, context) {
const contextInfo = _.find(config.contexts, c => c.name === context);
if (!contextInfo) {
throw new Error(`Unable to find configuration of context ${context}`);
}
return contextInfo.context;
}
function getClusterInfo(config, context) {
const clusterName = getContextInfo(config, context).cluster;
const clusterInfo = _.find(config.clusters, c => c.name === clusterName);
if (!clusterInfo) {
throw new Error(`Unable to find cluster information for context ${context}`);
}
return clusterInfo;
}
function getUserInfo(config, context) {
const userName = getContextInfo(config, context).user;
let userInfo = _.find(config.users, u => u.name === userName);
if (!userInfo) {
console.log(`Unable to find user information for context ${context}`);
userInfo = {};
}
return userInfo;
}
function getKubernetesAPIURL(config) {
const currentContext = config['current-context'];
const clusterInfo = getClusterInfo(config, currentContext);
// Remove trailing '/' of the URL in case it exists
let clusterURL = clusterInfo.cluster.server.replace(/\/$/, '');
// Add protocol if missing
clusterURL = _.startsWith(clusterURL, 'http') ? clusterURL : `http://${clusterURL}`;
return clusterURL;
}
function getPropertyText(property, info) {
// Data could be pointing to a file or be base64 encoded
let result = null;
if (!_.isEmpty(info[property])) {
result = fs.readFileSync(info[property]);
} else if (!_.isEmpty(info[`${property}-data`])) {
result = Buffer.from(info[`${property}-data`], 'base64');
}
return result;
}
function getToken(userInfo) {
const token = _.get(userInfo, 'user.token');
const accessToken = _.get(userInfo, 'user.auth-provider.config.access-token');
if (token) {
return token;
} else if (accessToken) {
// Access tokens may expire so we better check the expire date
const expiry = moment(userInfo.user['auth-provider'].config.expiry);
if (expiry < moment()) {
throw new Error(
'The access token has expired. Make sure you can access your cluster and try again'
);
}
return accessToken;
}
return null;
}
function getDefaultNamespace(config) {
const currentContext = config['current-context'];
return getContextInfo(config, currentContext).namespace || 'default';
}
function getConnectionOptions(config, modif) {
const currentContext = config['current-context'];
const userInfo = getUserInfo(config, currentContext);
const clusterInfo = getClusterInfo(config, currentContext);
const connectionOptions = {
group: 'k8s.io',
url: getKubernetesAPIURL(config),
namespace: getDefaultNamespace(config),
};
// Config certificate-authority
const ca = getPropertyText('certificate-authority', clusterInfo.cluster);
if (ca) {
connectionOptions.ca = ca;
} else {
// No certificate-authority found
connectionOptions.insecureSkipTlsVerify = true;
}
// Config authentication
const token = getToken(userInfo);
if (token) {
connectionOptions.auth = {
bearer: token,
};
} else {
// If there is not a valid token we can authenticate either using
// username and password or a certificate and a key
const user = _.get(userInfo, 'user.username');
const password = _.get(userInfo, 'user.password');
if (!_.isEmpty(user) && !_.isEmpty(password)) {
connectionOptions.auth = { user, password };
} else if (!_.isEmpty(userInfo)) {
const properties = {
cert: 'client-certificate',
key: 'client-key',
};
_.each(properties, (property, key) => {
connectionOptions[key] = getPropertyText(property, userInfo.user);
if (!connectionOptions[key]) {
console.log(
'Unable to find required information for authenticating against the cluster'
);
}
});
}
}
return _.defaults({}, modif, connectionOptions);
}
function warnUnsupportedOptions(unsupportedOptions, definedOptions, logFunction) {
unsupportedOptions.forEach((opt) => {
if (!_.isUndefined(definedOptions[opt])) {
logFunction(`Warning: Option ${opt} is not supported for the kubeless plugin`);
}
});
}
module.exports = {
warnUnsupportedOptions,
loadKubeConfig,
getKubernetesAPIURL,
getDefaultNamespace,
getConnectionOptions,
};
| JavaScript | 0.99772 | @@ -2006,18 +2006,20 @@
user;%0A
-le
+cons
t userIn
@@ -2094,27 +2094,31 @@
) %7B%0A
-console.log
+throw new Error
(%60Unable
@@ -2173,27 +2173,8 @@
%60);%0A
- userInfo = %7B%7D;%0A
%7D%0A
@@ -4793,34 +4793,8 @@
else
- if (!_.isEmpty(userInfo))
%7B%0A
|
93c32000bc05cde289c57600e129c1e38791c62c | Add back intlBlock | lib/helpers.js | lib/helpers.js | (function (root, factory) {
var lib = factory();
if (typeof module === 'object' && module.exports) {
// node.js/CommonJs
module.exports = lib;
}
if (typeof define === 'function' && define.amd) {
// AMD anonymous module
define(lib);
}
if (root) {
root.HandlebarsHelperIntl = lib;
}
})(typeof global !== 'undefined' ? global : this, function () {
if (!this.Intl) {
console.log('no intl');
}
var CONTEXT_KEY = 'i18n',
_dateTimeFormats = {},
_numberFormats = {};
function setDateTimeFormat (key, options) {
_dateTimeFormats[key] = options;
}
function getDateTimeFormat (key) {
return _dateTimeFormats[key] || null;
}
function setNumberFormat (key, options) {
_numberFormats[key] = options;
}
function getNumberFormat (key) {
return _numberFormats[key] || null;
}
/**
Central location for helper methods to get a locale to use. Arguments are
looped through to search for locale itmes. After all parameters have been
exhausted, it defaults to the global `this` for a locale.
@protected
@method _getLocale
@param {Object} [hash] `options.hash` from the helper
@param {Object} [ctx] Context of the helper
@return Locale
*/
function _getLocale (hash, ctx) {
/*jshint expr:true */
hash || (hash = {});
/*jshint expr:true */
ctx || (ctx = {});
return hash.locale || ctx.locale || this.locale;
}
/**
Performs a string replacement with provided token, CONTEXT_KEY context, and YRB
formatted objects
@method intlMessage
@param {String} str String on which to perform replacements
@param {Object} options Options passed to the method from the handlebars handler
@return {String} Manipulated string that has had tokens replaced
*/
function intlMessage (str, options) {
if (!options) {
throw new ReferenceError('A string must be provided.');
}
var hash = (options && options.hash) || {},
locale = _getLocale(hash, this),
msg = new IntlMessageFormat(str, locale);
return msg.format(hash);
}
/**
Formats the provided number based on the options. Options may specify if the
returned value should be a delineated number, currency value, or a percentage.
@method intlNumber
@param {Number} num Number to format
@param {Object} options Options passed to the method from the handlebars handler
@return {String} Formatted number
*/
function intlNumber (num, options) {
if (!options) {
throw new ReferenceError('A number must be provided');
}
var hash = (options && options.hash) || {},
formatOptions = hash.format && _numberFormats[hash.format] || hash,
locale = _getLocale(hash, this),
_num;
_num = new Intl.NumberFormat(locale, formatOptions);
num = _num.format(num);
return num;
}
/**
Formats the provided date or time stamp to the current locale
@param {Date|Number} stamp Date Object or time stamp to be formatted
@param {Object} options Options passed to the method from the handlebars handler
@return {String} Formatted date
*/
function intlDate (stamp, options) {
if (!options) {
throw new ReferenceError('A date or time stamp must be provided.');
}
var hash = (options && options.hash) || {},
formatOptions = hash.format && _dateTimeFormats[hash.format] || hash,
locale = _getLocale(hash, this),
_date;
stamp = new Date(stamp).getTime();
_date = new Intl.DateTimeFormat(locale, formatOptions);
return _date.format(stamp);
}
/**
Passes through to other intl methods to format number, format dates, create
new context blocks, format messages, or provide ability to set a value in the
current CONTEXT_KEY value in the current context.
@method intl
@param {Number|Date|String} val Value to be formatted or applied
@param {Object} options Options passed to the method from the handlebars handler
@return {String|null} Returns the formated or translated value.
*/
function intl (val, options) {
if (!options) {
options = val;
val = null;
}
var token,
_val,
len,
i,
context;
// pass off to BLOCK
if (options.fn) {
context = {};
context.prototype = this;
if (options.hash && options.hash.locale) {
context.locale = options.hash.locale;
}
return options.fn(context);
}
// only use token if val is not defined
if (!val) {
if (options.hash.token) {
token = options.hash.token;
token = token.split('.');
_val = this;
for (i = 0, len = token.length; i < len; i++) {
if (_val.hasOwnProperty(token[i])) {
_val = _val[token[i]];
} else {
throw new ReferenceError('Could not find path ' + token + ' in ' + _val + ' at ' + token[i]);
}
}
val = _val;
} else {
throw new SyntaxError('A value or a token must be provided.');
}
}
if (typeof val === 'number') {
// pass off to NUMBER
val = intlNumber.call(this, val, options);
} else if (val instanceof Date) {
// pass off to DATE
val = intlDate.call(this, val, options);
} else {
// pass off to MESSAGE
val = intlMessage.call(this, val, options);
}
return val;
}
return {
// expose the helpers individually in case someone wants to use
// only some of them
helpers: {
intlMessage : intlMessage,
intlNumber : intlNumber,
intlDate : intlDate,
intl : intl
},
// utility method to register all the helpers
register: function(engine) {
engine.registerHelper('intlMessage', intlMessage);
engine.registerHelper('intlNumber', intlNumber);
engine.registerHelper('intlDate', intlDate);
engine.registerHelper('intl', intl);
}
};
});
| JavaScript | 0.000001 | @@ -1554,16 +1554,647 @@
%0A %7D%0A%0A
+ /**%0A Creates a new context for the given code. This allows you to define new%0A values on the context for things like %60locale%60 and %60currency%60%0A @method intlBlock%0A @para %7BObject%7D options Options passed to the method from the handlebars handler%0A @return %7BString%7D%0A */%0A function intlBlock (options) %7B%0A var context = %7B%7D,%0A hash = options.hash %7C%7C %7B%7D;%0A%0A context.prototype = this;%0A%0A if (hash.locale) %7B%0A context.locale = hash.locale;%0A %7D%0A%0A if (hash.currency) %7B%0A context.currency = hash.locale;%0A %7D%0A%0A return options.fn(context);%0A %7D
%0A%0A /*
@@ -5161,29 +5161,8 @@
i
-,%0A context
;%0A%0A
@@ -5231,222 +5231,32 @@
-context = %7B%7D;%0A context.prototype = this;%0A%0A if (options.hash && options.hash.locale) %7B%0A context.locale = options.hash.locale;%0A %7D%0A%0A return options.fn(context
+return intlBlock(options
);%0A
|
d602a2a4c9b2aca9ca330768025fd594ad2f0037 | Add helper for container “created”-status checking | lib/helpers.js | lib/helpers.js | var exec = require('child_process').exec,
_ = require('lodash')
module.exports.asyncIterate = function(array, callback, done) {
function iterate(idx) {
var current = array[idx]
if (current) {
callback(current, function() { iterate(idx+1) }, function(err) { done(err) })
} else {
done()
}
}
iterate(0)
}
module.exports.checkRunning = function(container, callback) {
exec('docker inspect ' + container.name, function(err, stdout) {
if (err) {
callback(false)
} else {
var info = _.head(JSON.parse(stdout))
var isRunning = info && info.State ? !!info.State.Running : false
callback(isRunning)
}
})
}
| JavaScript | 0 | @@ -747,12 +747,215 @@
%7D%0A %7D)%0A%7D%0A%0A
+module.exports.checkCreated = function(container, callback) %7B%0A exec('docker inspect ' + container.name, function(err) %7B%0A var isCreated = err ? false : true%0A callback(isCreated)%0A %7D)%0A%7D%0A
|
dd5e784bca525b41e828a41d6b217e4527eee698 | add ipUtils.getRequestIpAddress to get the ip address of a request | lib/iputils.js | lib/iputils.js | /*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
var events = require('events');
var emitter = new events.EventEmitter();
/**
* @module
*/
var arraysEqual = function(a, b) {
if ((!a && b) || (!b && a)) {
return false;
}
if (a.length !== b.length) {
return false;
}
var len = a.length;
for (var ii = 0; ii < len; ++ii) {
if (a[ii] !== b[ii]) {
return false;
}
}
return true;
};
/**
* Gets the ip address of this machine.
* @returns {String[]} array of ip addresses.
*/
var getIpAddresses = (function() {
// Premature optimization. Don't read this more than once a second
var cacheTime = 1 * 1000; // 1 second
var lastRead = Date.now();
var addresses;
var oldAddressesSorted;
var os = require('os');
var isIpv6WeCareAbout = (function() {
var ignoredTopSegments = {
"fe80": true,
"ff00": true,
"fd00": true,
"fec0": true,
};
return function(address) {
// honestly I don't really understand ipv6 and which address make no sense. It seems
// like the top few bits might stay but
// should probably check for 0 using ip6addr
var topSegment = address.substr(0, 4).toLowerCase();
return ignoredTopSegments[topSegment] === undefined;
};
}());
return function() {
var now = Date.now();
if (!addresses || now - lastRead > cacheTime) {
lastRead = now;
var interfaces = os.networkInterfaces();
addresses = [];
for (var k in interfaces) {
for (var k2 in interfaces[k]) {
var iface = interfaces[k][k2];
if (!iface.internal) {
if (iface.family === 'IPv4') {
addresses.push(iface.address);
} else if (iface.family === 'IPv6' && isIpv6WeCareAbout(iface.address)) {
addresses.push("[" + iface.address + "]");
}
}
}
}
var newAddressesSorted = addresses.slice().sort();
if (!arraysEqual(newAddressesSorted, oldAddressesSorted)) {
oldAddressesSorted = newAddressesSorted;
if (addresses.length > 1) {
console.log("more than 1 IP address found: " + addresses);
}
emitter.emit('changed', addresses);
}
}
return addresses.slice();
};
}());
exports.getIpAddresses = getIpAddresses;
exports.on = emitter.on.bind(emitter);
exports.addListener = exports.on;
exports.removeListener = emitter.removeListener.bind(emitter);
| JavaScript | 0 | @@ -3810,35 +3810,512 @@
);%0A%0A
-exports.getIpAddresses = ge
+function getRequestIpAddresses(req) %7B%0A var ips = req.headers%5B'x-forwarded-for'%5D %7C%7C%0A req.connection.remoteAddress %7C%7C%0A req.socket.remoteAddress %7C%7C%0A req.connection.socket.remoteAddress;%0A if (ips) %7B%0A if (ips.indexOf(',')) %7B%0A ips = ips.split(%22,%22);%0A %7D else %7B%0A ips = %5Bips%5D;%0A %7D%0A ips = ips.map((s) =%3E %7B%0A return s.trim();%0A %7D);%0A %7D%0A return ips && ips.length ? ips : undefined;%0A%7D;%0A%0A%0Aexports.getIpAddresses = getIpAddresses;%0Aexports.getRequestIpAddresses = getReques
tIpA
|
0460931823ac1e5fd3b3b78a8e6ae70da3e7b0c7 | use context | src/commands/Worldstate/Syndicates.js | src/commands/Worldstate/Syndicates.js | 'use strict';
const Command = require('../../models/Command.js');
const SyndicateEmbed = require('../../embeds/SyndicateEmbed.js');
const { createPageCollector } = require('../../CommonFunctions');
const values = ['all', 'arbiters of hexis', 'perrin sequence', 'cephalon suda', 'steel meridian', 'new loka', 'red veil', 'ostrons', 'assassins'];
/**
* Displays the currently active Invasions
*/
class Syndicates extends Command {
/**
* Constructs a callable command
* @param {Genesis} bot The bot object
*/
constructor(bot) {
super(bot, 'warframe.worldstate.syndicate', 'syndicate', 'Gets the starchat nodes for the desired syndicate, or all.');
this.regex = new RegExp(`^${this.call}\\s?(?:(${values.join('|')}))?(?:\\s+on\\s+([pcsxb14]{2,3}))?$`, 'i');
this.usages = [
{
description: 'Display syndicate nodes for a syndicate.',
parameters: ['syndicate'],
},
];
}
async run(message) {
const matches = message.strippedContent.match(this.regex);
const param1 = (matches[1] || '').toLowerCase();
const param2 = (matches[2] || '').toLowerCase();
const syndicate = values.indexOf(param1) > -1 ? param1.toLowerCase() : 'all';
let platformParam;
if (this.platforms.indexOf(param2) > -1) {
platformParam = param2;
} else if (this.platforms.indexOf(param1) > -1) {
platformParam = param1;
}
const platform = platformParam || await this.settings.getChannelSetting(message.channel, 'platform');
const ws = await this.bot.worldStates[platform.toLowerCase()].getData();
const pages = [];
const matching = ws.syndicateMissions.filter(m => m.syndicate.toLowerCase() === syndicate || syndicate === 'all');
if (matching.length) {
matching.forEach((mission) => {
pages.push(new SyndicateEmbed(this.bot, [mission], mission.syndicate, platform, true));
});
if (pages.length) {
const msg = await this.messageManager.embed(message, pages[0], false, false);
await createPageCollector(msg, pages, message.author);
}
if (parseInt(await this.settings.getChannelSetting(message.channel, 'delete_after_respond'), 10) && message.deletable) {
message.delete(10000);
}
return this.messageManager.statuses.SUCCESS;
}
return this.messageManager.statuses.FAILURE;
}
}
module.exports = Syndicates;
| JavaScript | 0.99865 | @@ -942,16 +942,21 @@
(message
+, ctx
) %7B%0A
@@ -1434,72 +1434,20 @@
%7C%7C
-await this.settings.getChannelSetting(message.channel, '
+ctx.
platform
');%0A
@@ -1442,18 +1442,16 @@
platform
-')
;%0A co
|
d47564807a5cdf1e2ea1200ce599c9e83dee9dbd | add comment creation | domo.js | domo.js | !function() {
var global = Function("return this")()
var tags = [
"A", "ABBR", "ACRONYM", "ADDRESS", "AREA", "ARTICLE", "ASIDE", "AUDIO",
"B", "BDI", "BDO", "BIG", "BLOCKQUOTE", "BODY", "BR", "BUTTON",
"CANVAS", "CAPTION", "CITE", "CODE", "COL", "COLGROUP", "COMMAND",
"DATALIST", "DD", "DEL", "DETAILS", "DFN", "DIV", "DL", "DT", "EM",
"EMBED", "FIELDSET", "FIGCAPTION", "FIGURE", "FOOTER", "FORM", "FRAME",
"FRAMESET", "H1", "H2", "H3", "H4", "H5", "H6", "HEAD", "HEADER",
"HGROUP", "HR", "HTML", "I", "IFRAME", "IMG", "INPUT", "INS", "KBD",
"KEYGEN", "LABEL", "LEGEND", "LI", "LINK", "MAP", "MARK", "META",
"METER", "NAV", "NOSCRIPT", "OBJECT", "OL", "OPTGROUP", "OPTION",
"OUTPUT", "P", "PARAM", "PRE", "PROGRESS", "Q", "RP", "RT", "RUBY",
"SAMP", "SCRIPT", "SECTION", "SELECT", "SMALL", "SOURCE", "SPAN",
"SPLIT", "STRONG", "STYLE", "SUB", "SUMMARY", "SUP", "TABLE", "TBODY",
"TD", "TEXTAREA", "TFOOT", "TH", "THEAD", "TIME", "TITLE", "TR",
"TRACK", "TT", "UL", "VAR", "VIDEO", "WBR"
]
function hyphenify(text) {
return text.replace(/[A-Z]/g, "-$&").toLowerCase()
}
function has(object, key) {
return Object.prototype.hasOwnProperty.call(object, key)
}
function flatten(list) {
return Array.prototype.concat.apply([], list)
}
function Domo(document) {
var i = tags.length
var domo = this
domo.Domo = Domo
domo.domo = domo
domo.document = document || global.document
domo.CSS = domo.createCSSRule
while (i--) !function(nodeName) {
domo[nodeName] = function() {
var childNodes = flatten(arguments)
var attributes = childNodes[0]
if (childNodes.length) {
if (typeof attributes != "object" || attributes.nodeType) {
attributes = null
}
else childNodes.shift()
}
return domo.createElement(nodeName, attributes, childNodes)
}
}(tags[i])
}
Domo.prototype.createElement = function(nodeName, attributes, childNodes) {
var doc = this.document
var el = doc.createElement(nodeName)
var child
var i
for (i in attributes) {
if (has(attributes, i)) el.setAttribute(hyphenify(i), attributes[i])
}
for (i = 0; i < childNodes.length; i++) {
child = childNodes[i]
if (typeof child == "function") child = child()
if (!child || !child.nodeType) child = doc.createTextNode(child)
el.appendChild(child)
}
if (nodeName == "HTML") doc.replaceChild(el, doc.documentElement)
return el
}
Domo.prototype.createCSSRule = function(selector) {
var css = selector + "{"
var i = 1
var l = arguments.length
var key
var block
while (i < l) {
block = arguments[i++]
switch (typeof block) {
case "object":
for (key in block) {
css += hyphenify(key) + ":" + block[key]
if (typeof block[key] == "number") css += "px"
css += ";"
}
break
case "string":
css = selector + " " + block + css
break
}
}
css += "}\n"
return css
}
Domo.prototype.globalize = function() {
var domo = this
var values = {}
var key
for (key in domo) {
if (!has(domo, key)) continue
if (key in global) values[key] = global[key]
global[key] = domo[key]
}
domo.noConflict = function() {
if (!values) return
for (key in domo) {
if (key in values) {
if (global[key] == domo[key]) global[key] = values[key]
}
else delete global[key]
}
values = null
return domo
}
return domo
}
typeof module == "object"
? module.exports = Domo
: (new Domo).globalize()
}()
| JavaScript | 0 | @@ -1512,16 +1512,54 @@
eCSSRule
+%0A domo.COMMENT = domo.createComment
%0A%0A wh
@@ -2602,24 +2602,134 @@
urn el%0A %7D%0A%0A
+ Domo.prototype.createComment = function(nodeValue) %7B%0A return this.document.createComment(nodeValue)%0A %7D%0A%0A
Domo.proto
|
9f8773c1a5cde4fd5bcf2429ab5625d3d6aa1284 | disable youtube annotations in player | src/components/Video/YouTubePlayer.js | src/components/Video/YouTubePlayer.js | import cx from 'classnames';
import React from 'react';
import YouTube from 'react-youtube';
import VideoBackdrop from './VideoBackdrop';
const debug = require('debug')('uwave:component:video:youtube');
export default class YouTubePlayer extends React.Component {
static propTypes = {
className: React.PropTypes.string,
size: React.PropTypes.string,
media: React.PropTypes.object,
seek: React.PropTypes.number,
volume: React.PropTypes.number
};
componentDidUpdate(prevProps) {
const { player } = this.refs;
if (player) {
// only set volume after the YT API is fully initialised.
// if it fails here because the API isn't ready, the the volume will still
// be set in onYTReady().
if (player._internalPlayer && prevProps.volume !== this.props.volume) {
debug('YT: setting volume', this.props.volume);
player._internalPlayer.setVolume(this.props.volume);
}
}
}
onYTReady(event) {
event.target.setVolume(this.props.volume);
}
render() {
const { className, size, media, seek } = this.props;
const sizeClass = `YouTubePlayer--${size}`;
const opts = {
width: '100%',
height: '100%',
playerVars: {
autoplay: 1,
controls: 0,
rel: 0,
showinfo: 0,
start: (seek || 0) + (media.start || 0)
}
};
const url = `https://youtube.com/watch?v=${media.sourceID}`;
let backdrop;
if (size === 'small') {
backdrop = <VideoBackdrop url={media.thumbnail} />;
}
// Wrapper span so the backdrop can be full-size…
return (
<span>
{backdrop}
<div className={cx('YouTubePlayer', sizeClass, className)}>
<YouTube
ref="player"
url={url}
opts={opts}
onReady={::this.onYTReady}
/>
</div>
</span>
);
}
}
| JavaScript | 0.000001 | @@ -1261,45 +1261,315 @@
: 0,
-%0A rel: 0,%0A showinfo: 0,
+ // do not show player controls in the bottom%0A rel: 0, // do not show related videos after the video finishes%0A showinfo: 0, // do not show video title etc in the frame%0A iv_load_policy: 3, // disable annotations%0A modestbranding: 1, // hide youtube logo
%0A
|
fa2b0a3797467aa027a082d7afdb2b77b5d16eca | Update linebot.js | lib/linebot.js | lib/linebot.js | var linebot = require('linebot');
var express = require('express');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var bot = linebot({
channelId: '1541948237',
channelSecret: '9a8c7887c8ed7ceb3f963ce8f73d64a9',
channelAccessToken: '3cL4zroJybMhWDUTZPUnLbxzPjfsoNu5FO0EqmZ/fhOka8bgzPZBCCp2EkmVw4l5lRUhDRML3vSuT9wV+VUd/xzw02X6FL6nFi8LaaT8NDuJcNJaaIIyNDzB/C5dfeU21BS73yzS3jQ88fmlwQS1VAdB04t89/1O/w1cDnyilFU='
});
var myClientSecret={"installed":{"client_id":"850824140147-oj4e40n9r73fggk4btnnm7m01sp8l13l.apps.googleusercontent.com","project_id":"fine-iterator-147008","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"GWzuZaS8gGmUsjC_T5eR0DhW","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(myClientSecret.installed.client_id,myClientSecret.installed.client_secret, myClientSecret.installed.redirect_uris[0]);
oauth2Client.credentials ={"access_token":"ya29.GlvsBHdqb5hrgML0chesDxODZCvLYzJc9Gl5STeEzclUU8gd4s_NBfcIrlSBGkbRB7ZGpoVrgnczuRHCBsCiWKvxQ_gfGpbfOxb_fw-CGDUSwz2ww10S8S_NqWyh","refresh_token":"1/taczb5UflFAWqxY_I7WPtJwhiv_r2OaUpvUDbx1oDPE","token_type":"Bearer","expiry_date":1508668680319}
var mySheetId='2PACX-1vQ0469-rXtpbjZlWUy2x7Qp4rbKkM1RkWzrzRFGCEFV2VNwK3rPCurQZRgb--Vk557qRVKN97JCzoQc';
var myQuestions=[];
var users=[];
var totalSteps=0;
var myReplies=[];
getQuestions();
function getQuestions() {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: oauth2Client,
spreadsheetId: mySheetId,
range:encodeURI('QNA')},
function(err, response) {if(err){console.log('讀取問題檔的API產生問題:' + err);return;}
var rows = response.values;
if(rows.length==0){
console.log('No data found.');
}
else{
myQuestions=rows;
totalSteps=myQuestions[0].length;
console.log('要問的問題已下載完畢!');
}
});
}
function appendMyRow(userId) {
var request = {
auth: oauth2Client,
spreadsheetId: mySheetId,
range:encodeURI('FORM1'),
insertDataOption: 'INSERT_ROWS',
valueInputOption: 'RAW',
resource: {
"values": [
users[userId].replies
]
}
};
var sheets = google.sheets('v4');
sheets.spreadsheets.values.append(request, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
});
}
bot.on('message', function(event) {
//if ((event.message.text == 'Lunch+1')&&(event.message.type === 'text')){
if (event.message.type === 'text'){
var myId=event.source.userId;
if (users[myId]==undefined){
users[myId]=[];
users[myId].userId=myId;
users[myId].step=-1;
users[myId].replies=[];
}
var myStep=users[myId].step;
if (myStep===-1)
sendMessage(event,myQuestions[0][0]);
else{
if (myStep==(totalSteps-1))
sendMessage(event,myQuestions[1][myStep]);
else
sendMessage(event,myQuestions[1][myStep]+'\n'+myQuestions[0][myStep+1]);
users[myId].replies[myStep+1]=event.message.text;
}
myStep++;
users[myId].step=myStep;
if (myStep>=totalSteps){
myStep=-1;
users[myId].step=myStep;
users[myId].replies[0]=new Date();
appendMyRow(myId);
}
}
});
function sendMessage(eve,msg){
eve.reply(msg).then(function(data){return true;}).catch(function(error){return false;});
}
const app = express();
const linebotParser = bot.parser();
app.post('/', linebotParser);
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
console.log("App now running on port", port);
});
| JavaScript | 0.000001 | @@ -2803,26 +2803,24 @@
sage.type ==
-=
'text')%7B%0D%0A
|
0b43912af93468dcb1dbb973297c4135dc0da17b | Revert "utils.lang.js.ds: Fix Map & Set hashing to work with JPlus objects properly" | edgedb/lang/common/lang/javascript/ds.js | edgedb/lang/common/lang/javascript/ds.js | /*
* Copyright (c) 2013 Sprymix Inc.
* All rights reserved.
*
* See LICENSE for details.
**/
// %from metamagic.utils.lang.javascript import sx
(function(global) {'use strict'; if (!sx.ds) {
var HASH = 0,
hop = Object.prototype.hasOwnProperty;
var _key = function(key) {
var type = typeof key;
switch (type) {
case 'number':
// we support NaN, but don't care about '+0' and '-0'.
case 'string':
case 'boolean':
return type + key;
case 'undefined':
return 'undefined';
}
if (key === null) {
return 'null';
}
if (key.__class__) {
return 'hash-' + sx.objId(key);
}
return null;
};
var _clone = function(obj) {
function F() {};
F.prototype = obj;
return new F();
};
if (!global.Map) {
var Map = function() {
this.size = 0;
this._hash = {};
this._keys = [];
this._values = [];
};
Map.prototype = {
set: function(key, value) {
var hashed = _key(key);
if (hashed === null) {
this._keys.push(key);
this._values.push(value);
} else {
this._hash[hashed] = value;
}
this.size++;
},
get: function(key) {
var hashed = _key(key);
if (hashed === null) {
var idx = sx.array.index(this._keys, key);
if (idx >= 0) {
return this._values[idx];
}
} else {
return this._hash[hashed];
}
},
has: function(key) {
var hashed = _key(key);
if (hashed === null) {
return sx.array.index(this._keys, key) >= 0;
} else {
return hop.call(this._hash, hashed);
}
},
clear: function() {
this.size = 0;
this._hash = {};
this._keys = [];
this._values = [];
},
del: function(key) {
var hashed = _key(key);
if (hashed === null) {
var idx = sx.array.index(this._keys, key);
if (idx >= 0) {
this._keys.splice(idx, 1);
this._values.splice(idx, 1);
this.size--;
return true;
}
} else {
if (hop.call(this._hash, hashed)) {
delete this._hash[hashed];
this.size--;
return true;
}
}
return false;
}
};
} else {
var Map = function() {
this.map = new global.Map();
};
Map.prototype = {
set: function(key, value) {
return this.map.set(key, value);
},
get: function(key) {
return this.map.get(key);
},
has: function(key) {
return this.map.has(key);
},
clear: function() {
return this.map.clear();
},
del: function(key) {
return this.map['delete'].call(this.map, key);
}
};
Object.defineProperty(Map.prototype, 'size', {
get: function() {
return this.map.size;
}
});
}
if (!global.Set) {
var Set = function() {
this.size = 0;
this._hash = {};
this._items = [];
};
Set.prototype = {
add: function(item) {
var hashed = _key(item);
if (hashed === null) {
this._items.push(item);
} else {
this._hash[hashed] = true;
}
this.size++;
},
has: function(item) {
var hashed = _key(item);
if (hashed === null) {
return sx.array.index(this._items, item) >= 0;
} else {
return hop.call(this._hash, hashed);
}
},
clear: function() {
this.size = 0;
this._hash = {};
this._items = [];
},
del: function(item) {
var hashed = _key(item);
if (hashed === null) {
var idx = sx.array.index(this._keys, item);
if (idx >= 0) {
this._items.splice(idx, 1);
this.size--;
return true;
}
} else {
if (hop.call(this._hash, hashed)) {
delete this._hash[hashed];
this.size--;
return true;
}
}
return false;
}
};
} else {
var Set = function() {
this.set = new global.Set();
};
Set.prototype = {
add: function(item) {
return this.set.add(item);
},
has: function(item) {
return this.set.has(item);
},
clear: function() {
return this.set.clear();
},
del: function(item) {
return this.set['delete'].call(this.set, item);
}
};
Object.defineProperty(Set.prototype, 'size', {
get: function() {
return this.set.size;
}
});
}
sx.ds = {
Map: Map,
Set: Set
};
}})(this);
| JavaScript | 0.000001 | @@ -631,17 +631,125 @@
ass__) %7B
-%0A
+ // sx.class, and we're fine with modifying it%0A var hash = key.$hash;%0A if (hash != null) %7B%0A
@@ -759,30 +759,71 @@
urn
-'
hash
--' + sx.objId(key
+;%0A %7D%0A return (key.$hash = ('hash' + (++HASH))
);%0A
|
5bea630e12d5c59dec5178044d34a89d7b583d15 | Clean up | src/components/fieldinfo/fieldinfo.js | src/components/fieldinfo/fieldinfo.js | 'use strict';
/**
* @ngdoc directive
* @name vleApp.directive:fieldInfo
* @description
* # fieldInfo
*/
angular.module('vleApp')
.directive('fieldInfo', function (Dataset, Drop) {
return {
templateUrl: 'components/fieldinfo/fieldinfo.html',
restrict: 'E',
replace: true,
scope: {
field: '=',
showType: '=',
showInfo: '=',
showCaret: '=',
popupContent: '=',
showRemove: '=',
removeAction: '&',
action: '&',
disableCountOrOCaret: '='
},
link: function(scope, element) {
var funcsPopup;
scope.typeNames = Dataset.typeNames;
scope.stats = Dataset.stats[scope.field.name];
scope.clicked = function($event){
if(scope.action && $event.target !== element.find('.fa-caret-down')[0] &&
$event.target !== element.find('span.type')[0]) {
scope.action($event);
}
};
scope.func = function(field) {
return field.aggr || field.fn ||
(field.bin && 'bin') ||
field._aggr || field._fn ||
(field._bin && 'bin') || (field._any && 'auto');
};
scope.$watch('popupContent', function(popupContent) {
if (!popupContent) { return; }
funcsPopup = new Drop({
content: popupContent,
target: element.find('.type-caret')[0],
position: 'bottom left',
openOn: 'click'
});
});
},
controller: function($scope, Dataset) {
var statsField = $scope.field.aggr === 'count' ? 'count' : $scope.field.name;
$scope.stats = Dataset.stats[statsField];
}
};
}); | JavaScript | 0.000002 | @@ -1184,18 +1184,16 @@
%7D;%0A%0A
-%0A%0A
@@ -1707,12 +1707,13 @@
%7D;%0A %7D);
+%0A
|
87f92ce2364c3dca67022ae0febe8649785516af | Fix tab indent | editor/extensions/ext-overview_window.js | editor/extensions/ext-overview_window.js | /*globals svgEditor, svgedit, $ */
/*jslint es5: true, vars: true*/
/*
* ext-overview_window.js
*
* Licensed under the MIT License
*
* Copyright(c) 2013 James Sacksteder
*
*/
var overviewWindowGlobals = {};
svgEditor.addExtension("overview_window", function() { 'use strict';
// Temporarily disabled in Chrome, see https://github.com/SVG-Edit/svgedit/issues/26 and
// https://code.google.com/p/chromium/issues/detail?id=565120.
if (svgedit.browser.isChrome()) {
return;
}
// Define and insert the base html element.
var propsWindowHtml= "\
<div id=\"overview_window_content_pane\" style=\" width:100%; word-wrap:break-word; display:inline-block; margin-top:20px;\">\
<div id=\"overview_window_content\" style=\"position:relative; left:12px; top:0px;\">\
<div style=\"background-color:#A0A0A0; display:inline-block; overflow:visible;\">\
<svg id=\"overviewMiniView\" width=\"150\" height=\"100\" x=\"0\" y=\"0\" viewBox=\"0 0 4800 3600\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\
<use x=\"0\" y=\"0\" xlink:href=\"#svgroot\"> </use>\
</svg>\
<div id=\"overview_window_view_box\" style=\"min-width:50px; min-height:50px; position:absolute; top:30px; left:30px; z-index:5; background-color:rgba(255,0,102,0.3);\">\
</div>\
</div>\
</div>\
</div>";
$("#sidepanels").append(propsWindowHtml);
// Define dynamic animation of the view box.
var updateViewBox = function(){
var portHeight=parseFloat($("#workarea").css("height"));
var portWidth=parseFloat($("#workarea").css("width"));
var portX=$("#workarea").scrollLeft();
var portY=$("#workarea").scrollTop();
var windowWidth=parseFloat($("#svgcanvas").css("width"));
var windowHeight=parseFloat($("#svgcanvas").css("height"));
var overviewWidth=$("#overviewMiniView").attr("width");
var overviewHeight=$("#overviewMiniView").attr("height");
var viewBoxX=portX/windowWidth*overviewWidth;
var viewBoxY=portY/windowHeight*overviewHeight;
var viewBoxWidth=portWidth/windowWidth*overviewWidth;
var viewBoxHeight=portHeight/windowHeight*overviewHeight;
$("#overview_window_view_box").css("min-width",viewBoxWidth+"px");
$("#overview_window_view_box").css("min-height",viewBoxHeight+"px");
$("#overview_window_view_box").css("top",viewBoxY+"px");
$("#overview_window_view_box").css("left",viewBoxX+"px");
};
$("#workarea").scroll(function(){
if(!(overviewWindowGlobals.viewBoxDragging)){
updateViewBox();
}
});
$("#workarea").resize(updateViewBox);
updateViewBox();
// Compensate for changes in zoom and canvas size.
var updateViewDimensions= function(){
var viewWidth=$("#svgroot").attr("width");
var viewHeight=$("#svgroot").attr("height");
var viewX=640;
var viewY=480;
if(svgedit.browser.isIE())
{
// This has only been tested with Firefox 10 and IE 9 (without chrome frame).
// I am not sure if if is Firefox or IE that is being non compliant here.
// Either way the one that is noncompliant may become more compliant later.
//TAG:HACK
//TAG:VERSION_DEPENDENT
//TAG:BROWSER_SNIFFING
viewX=0;
viewY=0;
}
var svgWidth_old=$("#overviewMiniView").attr("width");
var svgHeight_new=viewHeight/viewWidth*svgWidth_old;
$("#overviewMiniView").attr("viewBox",viewX+" "+viewY+" "+viewWidth+" "+viewHeight);
$("#overviewMiniView").attr("height",svgHeight_new);
updateViewBox();
};
updateViewDimensions();
// Set up the overview window as a controller for the view port.
overviewWindowGlobals.viewBoxDragging=false;
var updateViewPortFromViewBox = function(){
var windowWidth =parseFloat($("#svgcanvas").css("width" ));
var windowHeight=parseFloat($("#svgcanvas").css("height"));
var overviewWidth =$("#overviewMiniView").attr("width" );
var overviewHeight=$("#overviewMiniView").attr("height");
var viewBoxX=parseFloat($("#overview_window_view_box").css("left"));
var viewBoxY=parseFloat($("#overview_window_view_box").css("top" ));
var portX=viewBoxX/overviewWidth *windowWidth;
var portY=viewBoxY/overviewHeight*windowHeight;
$("#workarea").scrollLeft(portX);
$("#workarea").scrollTop(portY);
};
$( "#overview_window_view_box" ).draggable({ containment: "parent"
,drag: updateViewPortFromViewBox
,start:function(){overviewWindowGlobals.viewBoxDragging=true; }
,stop :function(){overviewWindowGlobals.viewBoxDragging=false;}
});
$("#overviewMiniView").click(function(evt){
// Firefox doesn't support evt.offsetX and evt.offsetY.
var mouseX=(evt.offsetX || evt.originalEvent.layerX);
var mouseY=(evt.offsetY || evt.originalEvent.layerY);
var overviewWidth =$("#overviewMiniView").attr("width" );
var overviewHeight=$("#overviewMiniView").attr("height");
var viewBoxWidth =parseFloat($("#overview_window_view_box").css("min-width" ));
var viewBoxHeight=parseFloat($("#overview_window_view_box").css("min-height"));
var viewBoxX=mouseX - 0.5 * viewBoxWidth;
var viewBoxY=mouseY- 0.5 * viewBoxHeight;
//deal with constraints
if(viewBoxX<0){
viewBoxX=0;
}
if(viewBoxY<0){
viewBoxY=0;
}
if(viewBoxX+viewBoxWidth>overviewWidth){
viewBoxX=overviewWidth-viewBoxWidth;
}
if(viewBoxY+viewBoxHeight>overviewHeight){
viewBoxY=overviewHeight-viewBoxHeight;
}
$("#overview_window_view_box").css("top",viewBoxY+"px");
$("#overview_window_view_box").css("left",viewBoxX+"px");
updateViewPortFromViewBox();
});
return {
name: "overview window",
canvasUpdated: updateViewDimensions,
workareaResized: updateViewBox
};
});
| JavaScript | 0.000002 | @@ -470,14 +470,10 @@
) %7B%0A
-
+%09%09
retu
|
f3abfec1588b7ca9494b859b0429a5013b6e4697 | Optimize Executor | src/extender.js | src/extender.js | let Tools = require("./tools.js");
let P_NAME = "[_$a-zA-Z][_$a-zA-Z0-9]*";
let P_PATH = `${P_NAME}(?:\\.(?:${P_NAME}|[0-9]+))*`;
let P_NUMB = "-?[0-9]+(\\.[0-9]+)?";
let P_EXPR = `{(?:(${P_PATH})|(${P_NUMB}))}`;
let P_EACH = `{(${P_NAME}) in (${P_PATH})}`;
let GRE_WS = /\s+/g;
let GRE_EXPR = RegExp(P_EXPR, "g");
let RE_EXPR = RegExp("^" + P_EXPR + "$");
let RE_EACH = RegExp("^" + P_EACH + "$");
// string => boolean
function validateExpr(value) {
return RE_EXPR.test(value);
}
// string => boolean
function validateEach(value) {
return RE_EACH.test(value);
}
// (string, object) => any
function processProp(value, data) {
return RE_EXPR.test(value)
? processExpr(value, data)
: processText(value, data);
}
// (string, object) => string
function processText(value, data) {
return value
.replace(GRE_EXPR, m => {
let res = processExpr(m, data);
return Tools.isVoid(res) ? "" : res + "";
})
.replace(GRE_WS, " ")
.trim();
}
// (string, object) => any
function processExpr(value, data) {
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
let m = value.match(RE_EXPR);
if (!m) {
return null;
}
return m[1] ? processPath(m[1], data) : parseFloat(m[2]);
}
// (string, object) => object | null
function processEach(value, data) {
let m = value.match(RE_EACH);
if (!m) {
return null;
}
let items = processPath(m[2], data);
if (!Array.isArray(items)) {
items = [];
}
return { item: m[1], items };
}
// (string, object) => any
function processPath(path, data) {
return processPathArray(path.split("."), data);
}
// (array, object) => any
function processPathArray(path, data) {
if (!data) {
return null;
}
let value = data[path[0]];
return path.length > 1 ? processPathArray(path.slice(1), value) : value;
}
module.exports = {
validateExpr,
validateEach,
processProp,
processText,
processExpr,
processEach
};
| JavaScript | 0.000004 | @@ -257,29 +257,8 @@
%60;%0A%0A
-let GRE_WS = /%5Cs+/g;%0A
let
@@ -799,25 +799,16 @@
rn value
-%0A
.replace
@@ -833,20 +833,16 @@
-
let res
@@ -865,20 +865,16 @@
data);%0A
-
@@ -923,59 +923,9 @@
- %7D)%0A .replace(GRE_WS, %22 %22)%0A .trim(
+%7D
);%0A%7D
|
def08f8b60ab50d5c947f1ffc0e339fa804ecd69 | replace two functions with one function | src/components/link/link.component.js | src/components/link/link.component.js | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { assign } from 'lodash';
import { Link as RouterLink } from 'react-router';
import Icon from '../icon';
import { validProps } from '../../utils/ether';
import Event from '../../utils/helpers/events';
import tagComponent from '../../utils/helpers/tags';
import LinkStyle from './link.style';
class Link extends React.Component {
static safeProps = ['onClick'];
constructor() {
super();
this.onKeyDown = this.onKeyDown.bind(this);
}
onKeyDown(ev) {
if (this.props.onKeyDown) {
this.props.onKeyDown(ev);
}
// return early if there is no onClick or there is a href prop
// or the event is not an enter key
if (this.props.href || !Event.isEnterKey(ev)) {
return;
}
if (this.props.onClick) {
this.props.onClick(ev);
}
}
get iconLeft() {
if (!this.props.icon || this.props.iconAlign !== 'left') {
return null;
}
return this.icon;
}
get iconRight() {
if (!this.props.icon || this.props.iconAlign !== 'right') {
return null;
}
return this.icon;
}
get icon() {
const classes = classNames(
'carbon-link__icon',
`carbon-link__icon--align-${this.props.iconAlign}`
);
return (
<Icon
type={ this.props.icon }
className={ classes }
tooltipMessage={ this.props.tooltipMessage }
tooltipAlign={ this.props.tooltipAlign }
tooltipPosition={ this.props.tooltipPosition }
/>
);
}
get tabIndex() {
return this.props.tabbable && this.props.disabled ? '-1' : '0';
}
get componentProps() {
let { ...props } = validProps(this);
props.tabIndex = this.tabIndex;
props = assign({}, props, tagComponent('link', this.props));
delete props.href;
delete props.tabbable;
delete props.to;
props.className = this.props.className;
props.onKeyDown = this.onKeyDown;
return props;
}
renderLinkContent() {
return (
<span>
{this.iconLeft}
<span>{this.props.children}</span>
{this.iconRight}
</span>
);
}
renderLink() {
if (this.props.to) {
return (
<RouterLink to={ this.props.to } { ...this.componentProps }>
{this.renderLinkContent()}
</RouterLink>
);
}
return (
<a href={ this.props.href } { ...this.componentProps }>
{this.renderLinkContent()}
</a>
);
}
render() {
return (
<LinkStyle disabled={ this.props.disabled }>
{this.renderLink()}
</LinkStyle>
);
}
}
Link.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
disabled: PropTypes.bool,
href: PropTypes.string,
icon: PropTypes.string,
iconAlign: PropTypes.string,
onClick: PropTypes.func,
onKeyDown: PropTypes.func,
tabbable: PropTypes.bool,
to: PropTypes.string,
tooltipMessage: PropTypes.string,
tooltipPosition: PropTypes.string,
tooltipAlign: PropTypes.string
};
Link.defaultProps = {
iconAlign: 'left',
tabbable: true
};
export default Link;
| JavaScript | 0.999998 | @@ -895,169 +895,80 @@
%0A%0A
-get iconLeft() %7B%0A if (!this.props.icon %7C%7C this.props.iconAlign !== 'left') %7B%0A return null;%0A %7D%0A return this.icon;%0A %7D%0A%0A get iconRight() %7B%0A if (!
+renderLinkIcon = (currentAlignment) =%3E %7B%0A const hasProperAlignment =
this
@@ -979,19 +979,20 @@
ps.icon
-%7C%7C
+&& (
this.pro
@@ -1008,58 +1008,63 @@
ign
-!
==
- 'right') %7B%0A return null;%0A %7D%0A return
+= currentAlignment);%0A%0A return hasProperAlignment ?
thi
@@ -1069,16 +1069,23 @@
his.icon
+ : null
;%0A %7D%0A%0A
@@ -1995,16 +1995,30 @@
his.
-iconL
+renderLinkIcon('l
eft
+')
%7D%0A%0A
@@ -2078,17 +2078,31 @@
his.
-iconR
+renderLinkIcon('r
ight
+')
%7D%0A
|
7ebbd39ef881d6afb8ede14a534ba7842f8a07ba | Fix dependencies | models/vm-template.js | models/vm-template.js | 'use strict';
module.exports = (sequelize, DataTypes) => {
var VMTmpl = sequelize.define('vm_templates', {
distroname: {
type: DataTypes.STRING(64),
allowNull: false
},
uuid: {
type: DataTypes.STRING(36),
allowNull: false
},
repourl : {
type: DataTypes.STRING(255),
allowNull: false
}
}, {
indexes: [
{
name: 'uuid',
fields: ['uuid']
}
],
classMethods: {
associate: function(models) {
VMTmpl.hasOne(models.vm_distros, { as: 'distro_type' });
}
}
});
return VMTmpl;
};
| JavaScript | 0.000004 | @@ -507,14 +507,17 @@
mpl.
-hasOne
+belongsTo
(mod
|
cb92521b4c237e8a6d7b26f0fe02c26b10187c3a | Fix the potential XSS in URI-like strings with <, > and " | modifyurl@2ch.user.js | modifyurl@2ch.user.js | // ==UserScript==
// @id Modify URL @2ch
// @name Modify URL @2ch
// @version 0.0.5
// @namespace curipha
// @author curipha
// @description Modify "ttp://" text to anchor and redirect URIs to direct link.
// @include http://*.2ch.net/*
// @include http://*.bbspink.com/*
// @run-at document-end
// @grant none
// ==/UserScript==
(function(){
var anchor = document.getElementsByTagName('a');
var pattern = /^http:\/\/([^\/]+\.)?(ime\.(nu|st)\/|pinktower\.com\/|jump\.2ch\.net\/\?)/i;
for (var a of anchor) {
if (a.href.indexOf('http') !== 0) continue;
uri = a.href.replace(pattern, 'http://');
a.href = decodeURIComponent(uri);
}
var dd = document.getElementsByTagName('dd');
var ttp = /([^h])(ttps?:\/\/[\x21-\x7E]+)/ig;
for (var d of dd) {
d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>');
}
})();
| JavaScript | 0.000373 | @@ -108,9 +108,9 @@
0.0.
-5
+6
%0A//
@@ -808,16 +808,33 @@
/%5C/%5B%5Cx21
+%5Cx23-%5Cx3b%5Cx3d%5Cx3f
-%5Cx7E%5D+)
|
c165aece12c95123d5a8af20c3f53bc6040bf08b | Trim JSON in cases | each.js | each.js | var path = require('path');
var fs = require('fs');
function read(file) {
return fs.readFileSync(path.join(__dirname, 'cases', file));
}
var extra = require('./extra-cases');
module.exports = function (callback) {
fs.readdirSync(path.join(__dirname, 'cases')).filter(function (i) {
if ( path.extname(i) !== '.json' ) return;
var json = read(i).toString();
var name = path.basename(i, '.json');
var css = extra[name];
if ( !css ) css = read(name + '.css').toString().trim();
callback(name + '.css', css, json);
});
};
| JavaScript | 0.000133 | @@ -376,16 +376,23 @@
String()
+.trim()
;%0A
|
3f73367146fd4f20784c5cd97d2513f298b3fdf3 | Add comment in script.js | http/js/script.js | http/js/script.js | /*
* This file is part of mesamatrix.
*
* Copyright (C) 2014 Romain "Creak" Failliot.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
function fillZeros(number, size) {
var absNum = String(Math.abs(number));
var numZeros = size - absNum.length;
var res = "";
if(number < 0)
res = "-";
res += Array(numZeros + 1).join("0") + absNum;
return res;
}
function getLocalDate(text) {
var eventDate = new Date(text);
var year = eventDate.getFullYear();
var month = fillZeros(eventDate.getMonth() + 1, 2);
var day = fillZeros(eventDate.getDate(), 2);
var hours = fillZeros(eventDate.getHours(), 2);
var minutes = fillZeros(eventDate.getMinutes(), 2);
var seconds = fillZeros(eventDate.getSeconds(), 2);
var timezoneOffset = -eventDate.getTimezoneOffset();
var timezoneMinutes = Math.abs(timezoneOffset);
var timezoneHours = Math.floor(timezoneMinutes / 60);
timezoneMinutes -= timezoneHours * 60;
timezoneHours = fillZeros(timezoneHours, 2);
timezoneMinutes = fillZeros(timezoneMinutes, 2);
if(timezoneMinutes >= 0)
timezoneHours = "+" + timezoneHours;
return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + " (GMT " + timezoneHours + timezoneMinutes + ")";
}
function getRelativeDate(text) {
const MINS_IN_HOUR = 60;
const MINS_IN_DAY = 1440; // 60 * 24
const MINS_IN_WEEK = 10080; // 60 * 24 * 7
const MINS_IN_MONTH = 43200; // 60 * 24 * 30
var eventDate = new Date(text);
var relTimeInMin = (Date.now() - eventDate.getTime()) / (1000 * 60);
if(relTimeInMin < 5) // Less than 5 minutes ago
return "just now";
if(relTimeInMin < MINS_IN_HOUR) {
return Math.round(((relTimeInMin / MINS_IN_HOUR) / 5) * 5) + " minutes";
}
if(relTimeInMin < MINS_IN_DAY) {
var numHours = Math.round(relTimeInMin / MINS_IN_HOUR);
return numHours + " " + (numHours == 1 ? "hour" : "hours");
}
if(relTimeInMin < MINS_IN_WEEK) {
var numDays = Math.round(relTimeInMin / MINS_IN_DAY);
return numDays + " " + (numDays == 1 ? "day" : "days");
}
if(relTimeInMin < MINS_IN_MONTH) {
var numWeeks = Math.round(relTimeInMin / MINS_IN_WEEK);
return numWeeks + " " + (numWeeks == 1 ? "week" : "weeks");
}
if(relTimeInMin < MINS_IN_MONTH * 3) {
var numMonths = Math.round(relTimeInMin / MINS_IN_MONTH);
return numMonths + " " + (numMonths == 1 ? "month" : "months");
}
var year = eventDate.getFullYear();
var month = fillZeros(eventDate.getMonth() + 1, 2);
var day = fillZeros(eventDate.getDate(), 2);
return year + "-" + month + "-" + day;
}
function gaussian(x, a, b, c) {
return a * Math.exp(- Math.pow(x - b, 2) / (2 * Math.pow(c, 2)));
}
$(document).ready(function() {
// Convert to relative date.
$('.toRelativeDate').each(function() {
$(this).text(getRelativeDate($(this).data('timestamp')));
});
// Convert to local date.
$('.toLocalDate').each(function() {
$(this).text(getLocalDate($(this).data('timestamp')));
});
// Add tipsy for the footnote.
$('.footnote').tipsy({gravity: 'w', fade: true});
$('.mesaScore').tipsy({
fallback: 'It represents the completion status of `mesa` only',
gravity: 'n',
fade: true
});
// adjust the opacity of the 'modified' text based on age
var timeConst = 1.2e7;
$('.task span').each(function() {
var timeDiff = (Date.now()/1000) - $(this).data('timestamp');
$(this).css('opacity', gaussian(timeDiff, 1, 0, timeConst));
});
$('.mesaScore').each(function() {
var blend = Math.round($(this).data('score'));
if (blend == 100) {
$(this).addClass('mesaScore-done');
}
else if (blend < 90) {
$(this).addClass('mesaScore-notyet');
}
else {
$(this).addClass('mesaScore-almost');
}
});
});
| JavaScript | 0 | @@ -4293,24 +4293,75 @@
);%0A %7D);%0A%0A
+ // Change mesa score color based on completion%0A
$('.mesa
|
c515c365778b609c1e54a24bc670f23d3ef2fac4 | Set topic rather than queue. | lib/message.js | lib/message.js | /**
* Creates an instance of `Message`.
*
* This class is used as a mock when testing Crane handlers, substituted in
* place of a `Message` from the underlying message queue adapter.
*
* @constructor
* @api protected
*/
function Message(cb) {
this.queue = '/';
this.headers = {};
this.__cb = cb;
}
Message.prototype.ack = function() {
if (this.__cb) { this.__cb(); }
};
/**
* Expose `Response`.
*/
module.exports = Response;
| JavaScript | 0 | @@ -251,21 +251,21 @@
%0A this.
-queue
+topic
= '/';%0A
@@ -397,23 +397,22 @@
Expose %60
-Respons
+Messag
e%60.%0A */%0A
@@ -432,14 +432,13 @@
s =
-Respons
+Messag
e;%0A
|
29dc093c490b8c9a4b9d45260228343908ec83af | remove dependency on full handlebars in production | app-addon/components/un-calendar-month.js | app-addon/components/un-calendar-month.js | import moment from 'moment';
import Ember from 'ember';
var DATE_SLOT_HBS = Handlebars.compile(
'<li class="{{classNames}}" data-date="{{jsonDate}}">' +
'{{date}}' +
'</li>'
);
function containsDate(dates, date) {
if (!dates || !Ember.get(dates, 'length')) {
return false;
}
return dates.any(function(d) {
return date.isSame(d, 'day');
});
}
function forEachSlot(month, iter) {
var totalDays = month.daysInMonth(),
firstDay = month.clone().startOf('month').weekday(),
currentDay = 1;
function popCurrentDay() {
if (currentDay > totalDays) {
return null;
} else {
return moment([month.year(), month.month(), currentDay++]);
}
}
for (var week = 0; week <= 6; week++) {
for (var day = 0; day <= 6; day++) {
if (week === 0) {
iter(day < firstDay ? null : popCurrentDay());
} else {
iter(currentDay <= totalDays ? popCurrentDay() : null);
}
}
if (currentDay > totalDays) {
break;
}
}
}
export default Ember.Component.extend({
tagName: 'ol',
classNames: 'un-calendar-month',
month: null,
selectedDates: null,
disabledDates: null,
init: function() {
this._super();
if (!this.get('selectedDates')) {
throw 'you must provide selectedDates to un-calendar-month';
}
},
click: function(event) {
var $target = Ember.$(event.target);
if ($target.is('.is-disabled')) {
return;
}
if ($target.is('[data-date]')) {
this.sendAction('select', moment($target.data('date'), 'YYYY-MM-DD'));
}
},
monthDidChange: function() {
Ember.run.scheduleOnce('afterRender', this, 'rerender');
}.observes('month'),
selectedDatesDidChange: function() {
Ember.run.scheduleOnce('afterRender', this, 'setSelectedDates');
}.observes('selectedDates.@each'),
setSelectedDates: function() {
var dates = this.get('selectedDates'),
view = this,
json;
if (this.state !== 'inDOM') {
return;
}
this.$('li').removeClass('is-selected');
dates.forEach(function(date) {
json = date.format('YYYY-MM-DD');
view.$('[data-date="' + json + '"]').addClass('is-selected');
});
},
didInsertElement: function() {
this.setSelectedDates();
},
render: function(buff) {
var month = this.get('month'),
view = this;
if (!month) {
return;
}
function renderSlot(slot) {
var attrs;
if (slot) {
attrs = {
date: slot.format('D'),
jsonDate: slot.format('YYYY-MM-DD'),
classNames: ['un-calendar-slot', 'un-calendar-day']
};
view.applyOptionsForDate(attrs, slot);
attrs.classNames = attrs.classNames.join(' ');
buff.push(DATE_SLOT_HBS(attrs));
} else {
buff.push('<li class="un-calendar-slot un-calendar-empty"></li>');
}
}
forEachSlot(month, function(slot) {
renderSlot(slot);
});
},
applyOptionsForDate: function(options, date) {
var disabledDates = this.get('disabledDates'),
selectedDates = this.get('selectedDates');
if (moment().isSame(date, 'day')) {
options.classNames.push('is-today');
}
if (disabledDates && containsDate(disabledDates, date)) {
options.classNames.push('is-disabled');
}
if (selectedDates && containsDate(selectedDates, date)) {
options.classNames.push('is-selected');
}
},
});
| JavaScript | 0.000001 | @@ -54,138 +54,8 @@
';%0A%0A
-var DATE_SLOT_HBS = Handlebars.compile(%0A '%3Cli class=%22%7B%7BclassNames%7D%7D%22 data-date=%22%7B%7BjsonDate%7D%7D%22%3E' +%0A '%7B%7Bdate%7D%7D' +%0A '%3C/li%3E'%0A);%0A%0A
func
@@ -2334,16 +2334,26 @@
ar attrs
+, template
;%0A%0A
@@ -2593,24 +2593,25 @@
slot);%0A
+%0A
attrs.cl
@@ -2606,26 +2606,33 @@
-attrs.classNames =
+template = '%3Cli class=%22'+
att
@@ -2658,48 +2658,102 @@
' ')
-;%0A buff.push(DATE_SLOT_HBS(attrs)
+ + '%22 data-date=%22' + attrs.jsonDate + '%22%3E' + attrs.date + '%3C/li%3E';%0A%0A buff.push(template
);%0A
|
0fd368ce10cbdf4d561192daab092f2926955bcb | Implement cron | echo.js | echo.js | var login = require("facebook-chat-api");
var Forecast = require('forecast');
var forecast = new Forecast({
service: 'forecast.io',
key: '78526c408f187d3668e14c3e79aa6202',
units: 'f', // Only the first letter is parsed
cache: true, // Cache API requests?
ttl: { // How long to cache requests. Uses syntax from moment.js: http://momentjs.com/docs/#/durations/creating/
minutes: 27,
seconds: 45
}
});
var NodeGeocoder = require('node-geocoder');
var options = { provider: 'google' };
var geocoder = NodeGeocoder(options);
// Load enviornment data
require('dotenv').config();
var helpers = require('./helpers');
// Create simple echo bot
login({email: process.env.BOT_USERNAME, password: process.env.BOT_PASSWORD}, function callback (err, api) {
if(err) return console.error(err);
api.listen(function callback(err, message) {
//Ensure this is a real chat message
if(message && message.body) {
var stringComponents = message.body.split(" ");
if(typeof message.body == "string" && message.body.startsWith("@"+process.env.BOT_PREFIX+" echo")) {
api.sendMessage(helpers.removeArgs(stringComponents,2), message.threadID);
} else if(message && message.body && message.body.startsWith("@"+process.env.BOT_PREFIX+" weather")) {
var city = helpers.removeArgs(stringComponents,2);
console.log(city);
if(city) {
geocoder.geocode(city, function(err, res) {
forecast.get([res[0]['latitude'], res[0]['longitude']], function(err, weather) {
if(err) return console.dir(err);
api.sendMessage(res[0]['city'] + " Weather: Currently " + Math.floor(weather['currently']['temperature']) + ", and " + weather['currently']['summary'], message.threadID);
});
});
} else {
api.sendMessage("Usage: @"+BOT_PREFIX+" weather <city>", message.threadID);
}
}
}
});
});
| JavaScript | 0.999518 | @@ -1,12 +1,38 @@
+require('./cronjobs.js')%0A%0A
var login =
|
f96b76dd20b6bd3c89a3a597cc51ffbc949409e5 | Add stub for the choice of author | subscene.js | subscene.js | // ==UserScript==
// @name SubScene Filter
// @namespace www.subscene.com
// @description Add filter to subscene searches
// @include https://*subscene.com/subtitles/*
// @exclude https://*subscene.com/subtitles/title?q*
// @exclude https://*subscene.com/subtitles/*/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @version 1
// @grant none
// ==/UserScript==
$("#flagWrapper").after(
'<div>\
<select id="langChoice">\
<option id="langDefault" value="">All</option>\
</select>\
<input id="myFilterQuery" type="text">\
<label>\
<input type="checkbox" id="caseInsensitiveBox">\
Case Insensitive\
</label>\
<select id="earChoice">\
<option id="earDefault" value="">Any</option>\
<option value="hi">HI</option>\
<option value="nohi">No HI</option>\
</select>\
<button id="filterButton" type="button">Filter</button>\
<button id="clearButton" type="button">Clear</button>\
</div>'
);
var rows = $("tr").filter(function(ix,el) {
return $(this).find("span.l").text();
});
var visibles = rows;
var langs = [];
$("tr td.a1 span.l").each(function() {
lang = $(this).text().trim();
if( langs.indexOf(lang) == -1 ) {
langs.push(lang);
}
});
var el = $("#langChoice");
$.each(langs, function(key,value) {
el.append($("<option></option>")
.attr("value",value).text(value));
});
var render = function() {
rows.hide();
visibles.show();
};
$("#filterButton").click(function() {
// Get the regex to search for
var isValid = true;
try {
if($("#caseInsensitiveBox").prop('checked')) {
var inputRegex = new RegExp($("#myFilterQuery").val(),"i");
} else {
var inputRegex = new RegExp($("#myFilterQuery").val());
}
} catch(e) {
isValid = false;
}
// Get the language filter params
do_filter = $("#langChoice").val() != "";
var filter_lang = $("#langChoice").val();
// Get the hearing impairment filter params
do_hi = $("#earChoice").val() != "";
var filter_hi = $("#earChoice").val();
if(filter_hi == "hi") {
var hi_class = "a41";
} else if (filter_hi == "nohi") {
var hi_class = "a40";
}
visibles = rows.filter(function(ix,el) {
if(!do_filter) {
return true;
}
return $(this).find("span.l").text().trim() == filter_lang;
})
.filter(function(ix,el) {
if(!isValid) {
return true;
}
return $(this).find("td.a1 a span:nth-child(2)").text().trim().match(inputRegex);
})
.filter(function(ix,el) {
if(!do_hi) {
return true;
}
return $(this).find("td:nth-child(3)").attr('class') == hi_class;
});
render();
});
$("#clearButton").click(function() {
visibles = rows;
render();
// restore the filters to the empy state
$("#langChoice").val($("#langDefault").val());
$("#earChoice").val($("#earDefault").val());
$("#caseInsensitiveBox").prop('checked',false);
$("#myFilterQuery").val("");
});
| JavaScript | 0.000001 | @@ -877,24 +877,127 @@
%3C/select%3E%5C%0A
+ %3Cselect id=%22authorChoice%22%3E%5C%0A %3Coption id=%22authorDefault%22 value=%22%22%3EAny%3C/option%3E%5C%0A %3C/select%3E%5C%0A
%3Cbutton
@@ -1041,24 +1041,24 @@
r%3C/button%3E%5C%0A
-
%3Cbutton
@@ -1201,24 +1201,45 @@
text();%0A%7D);%0A
+var filtered = rows;%0A
var visibles
@@ -1545,16 +1545,35 @@
);%0A%7D);%0A%0A
+var authors = %5B%5D;%0A%0A
var rend
@@ -1607,24 +1607,24 @@
de();%0A
-visibles
+filtered
.show();
@@ -2340,24 +2340,24 @@
%0A %7D%0A%0A
-visibles
+filtered
= rows.
@@ -2893,17 +2893,28 @@
ion() %7B%0A
-
+ filtered =
visible
|
401bcbd8a0d6927fe4289a6da77c70f8fdb71562 | update case todo | case/todo/app/scripts/controllers/main.js | case/todo/app/scripts/controllers/main.js | 'use strict';
/**
* @ngdoc function
* @name yoTodoApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the yoTodoApp
*/
angular.module('yoTodoApp')
// .controller('MainCtrl', function ($scope,localStorageService) {
.controller('MainCtrl', function ($scope) {
$scope.todos = [];
// var todosInStore = localStorageService.get('todos');
// $scope.todos = todosInStore && todosInStore.split('\n') || [];
// $scope.$watch('todos',function () {
// localStorageService.add('todos',$scope.todos.join('\n'));
// },true);
$scope.addTodo = function () {
$scope.todos.push($scope.todo);
$scope.todo = '';
};
$scope.removeTodo = function (index) {
$scope.todos.splice(index,1);
};
});
| JavaScript | 0 | @@ -164,19 +164,16 @@
oApp')%0A
- //
.contro
@@ -230,16 +230,19 @@
ice) %7B%0A
+ //
.contro
@@ -311,16 +311,38 @@
//
+use localStorage%0A
var tod
@@ -388,27 +388,24 @@
dos');%0A
- //
$scope.todo
@@ -461,19 +461,16 @@
%5D;%0A
- //
$scope.
@@ -503,19 +503,16 @@
%7B%0A
- //
loc
@@ -571,19 +571,16 @@
);%0A
- //
%7D,true)
|
f364c6d4e2614a074dcc97c0bff54413d5dec455 | Fix util-linux testcase | tests/pkgs/utillinux.js | tests/pkgs/utillinux.js | var nijs = require('nijs');
exports.pkg = function(args) {
return args.stdenv().mkDerivation({
name : "util-linux-2.30",
src : args.fetchurl()({
url : new nijs.NixURL("https://www.kernel.org/pub/linux/utils/util-linux/v2.30/util-linux-2.30.tar.xz"),
sha256 : "13d0ax8bcapga8phj2nclx86w57ddqxbr98ajibpzjq6d7zs8262"
}),
configureFlags : [
"--without-ncurses",
"--disable-use-tty-group",
"--enable-fs-paths-default=/var/setuid-wrappers:/var/run/current-system/sw/sbin:/sbin"
],
buildInputs : [
args.zlib()
],
meta : {
description : "A set of system utilities for Linux."
}
});
};
| JavaScript | 0.009628 | @@ -518,16 +518,91 @@
n:/sbin%22
+,%0A %22--disable-makeinstall-setuid%22,%0A %22--disable-makeinstall-chown%22
%0A %5D,%0A
|
9f68ceeffa822a70de9192a30e24272cf18718f3 | remove log | SingularityUI/app/actions/api/base.es6 | SingularityUI/app/actions/api/base.es6 | import fetch from 'isomorphic-fetch';
const JSON_HEADERS = {'Content-Type': 'application/json', 'Accept': 'application/json'};
export function buildJsonApiAction(actionName, httpMethod, opts={}) {
const JSON_BOILERPLATE = {
method: httpMethod,
headers: JSON_HEADERS
}
let options;
if (typeof opts === 'function') {
options = (...args) => {
let generatedOpts = opts(...args);
generatedOpts.body = JSON.stringify(generatedOpts.body || {});
return _.extend({}, generatedOpts, JSON_BOILERPLATE);
};
} else {
options = (...args) => {
opts.body = JSON.stringify(opts.body || {});
return _.extend({}, opts, JSON_BOILERPLATE);
};
}
return buildApiAction(actionName, options);
}
export function buildApiAction(actionName, opts={}) {
const ACTION = actionName;
const STARTED = actionName + '_STARTED';
const ERROR = actionName + '_ERROR';
const SUCCESS = actionName + '_SUCCESS';
const CLEAR = actionName + '_CLEAR';
let optsFunc;
if (typeof opts === 'function') {
optsFunc = opts;
} else {
optsFunc = () => opts;
}
function trigger(...args) {
return function (dispatch) {
dispatch(started());
let options = optsFunc(...args);
console.log(options);
return fetch(config.apiRoot + options.url, _.extend({credentials: 'include'}, _.omit(options, 'url')))
.then(response => response.json())
.then(json => {
dispatch(success(json));
})
.catch(ex => {
dispatch(error(ex));
});
}
}
function clearData() {
return function (dispatch) {
dispatch(clear());
}
}
function clear() {
return { type: CLEAR };
}
function started() {
return { type: STARTED };
}
function error(error) {
return { type: ERROR, error };
}
function success(data) {
return { type: SUCCESS, data };
}
return {
ACTION,
STARTED,
ERROR,
SUCCESS,
CLEAR,
clear,
clearData,
trigger,
started,
error,
success
}
}
| JavaScript | 0.000001 | @@ -1235,36 +1235,8 @@
s);%0A
- console.log(options);%0A
|
c7e229896f64b8408d33fc78a28bab099a0ef097 | switch GlobalStyleComponent to a PureComponent | src/constructors/createGlobalStyle.js | src/constructors/createGlobalStyle.js | // @flow
import React from 'react'
import { IS_BROWSER, STATIC_EXECUTION_CONTEXT } from '../constants'
import _GlobalStyle from '../models/GlobalStyle'
import StyleSheet from '../models/StyleSheet'
import { StyleSheetConsumer } from '../models/StyleSheetManager'
import StyledError from '../utils/error'
import determineTheme from '../utils/determineTheme'
import { ThemeConsumer, type Theme } from '../models/ThemeProvider'
import type { CSSConstructor, Interpolation, Stringifier } from '../types'
import hashStr from '../vendor/glamor/hash'
export default (stringifyRules: Stringifier, css: CSSConstructor) => {
const GlobalStyle = _GlobalStyle(stringifyRules)
const createGlobalStyle = (
strings: Array<string>,
...interpolations: Array<Interpolation>
) => {
const rules = css(strings, ...interpolations)
const id = `sc-global-${hashStr(JSON.stringify(rules))}`
const style = new GlobalStyle(rules, id)
let count = 0
class GlobalStyleComponent extends React.Component<*, *> {
static defaultProps: Object
instance: number
styleSheet: Object
static styledComponentId = id
constructor() {
super()
count += 1
this.instance = count
}
componentWillUnmount() {
count -= 1
style.removeStyles(this.styleSheet)
}
render() {
if (process.env.NODE_ENV !== 'production') {
if (React.Children.count(this.props.children)) {
throw new StyledError(11)
} else if (IS_BROWSER && this.instance > 1) {
console.warn(
`The global style component ${id} was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in <head>.`
)
}
}
return (
<StyleSheetConsumer>
{(styleSheet?: StyleSheet) => {
this.styleSheet = styleSheet || StyleSheet.master
if (style.isStatic) {
style.renderStyles(STATIC_EXECUTION_CONTEXT, this.styleSheet)
return null
} else {
return (
<ThemeConsumer>
{(theme?: Theme) => {
const { defaultProps } = this.constructor
const context = {
...this.props,
}
if (typeof theme !== 'undefined') {
context.theme = determineTheme(
this.props,
theme,
defaultProps
)
}
style.renderStyles(context, this.styleSheet)
return null
}}
</ThemeConsumer>
)
}
}}
</StyleSheetConsumer>
)
}
}
return GlobalStyleComponent
}
return createGlobalStyle
}
| JavaScript | 0 | @@ -992,16 +992,20 @@
s React.
+Pure
Componen
|
71fc6a3595690f04c800bcf1cdf17a4f92288212 | Enable ckeditor spell check | app/assets/javascripts/ckeditor/config.js | app/assets/javascripts/ckeditor/config.js | CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
/* Filebrowser routes */
// The location of an external file browser, that should be launched when "Browse Server" button is pressed.
config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
// The location of a script that handles file uploads in the Flash dialog.
config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads in the Image dialog.
config.filebrowserImageUploadUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads.
config.filebrowserUploadUrl = "/ckeditor/attachment_files";
config.allowedContent = true;
// Toolbar groups configuration.
config.toolbar = [
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source'] },
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
// { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
// { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
{ name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
{ name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
'/',
{ name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
{ name: 'colors', items: [ 'TextColor', 'BGColor' ] },
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }
];
config.toolbar_mini = [
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
{ name: 'styles', items: [ 'Font', 'FontSize' ] },
{ name: 'colors', items: [ 'TextColor', 'BGColor' ] },
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
{ name: 'insert', items: [ 'Image', 'Table', 'HorizontalRule', 'SpecialChar' ] }
];
config.toolbar_simple = [
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
{ name: 'styles', items: [ 'Font', 'FontSize' ] },
{ name: 'colors', items: [ 'TextColor', 'BGColor' ] },
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
];
config.toolbar_module_author = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
{ name: 'styles', items: ['Format'] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks'], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote'] },
{ name: 'insert', items: [ 'Image', 'Table', 'SpecialChar' ] },
{ name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
{ name: 'basicstyles', groups: [ 'basicstyles'], items: [ 'Bold', 'Italic'] },
];
config.toolbar_module_admin = [
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source'] },
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
// { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
// { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
{ name: 'insert', items: [ 'Image', 'Table', 'HorizontalRule', 'SpecialChar' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv' ] },
'/',
{ name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }
];
};
| JavaScript | 0 | @@ -1302,16 +1302,83 @@
iles%22;%0A%0A
+ //Enable spellcheck%0A config.disableNativeSpellChecker = false;%0A%0A
config
|
02c059525a88ea411474ad72129b7140587263f0 | Save source and target information | adjacencyMatrix/d3.layout.adjacencyMatrix.js | adjacencyMatrix/d3.layout.adjacencyMatrix.js | (function() {
d3.layout.adjacencyMatrix = function() {
var directed = true,
size = [1,1],
nodes = [],
edges = [],
edgeWeight = function (d) {return 1},
nodeID = function (d) {return d.id};
function matrix() {
var width = size[0],
height = size[1],
nodeWidth = width / nodes.length,
nodeHeight = height / nodes.length,
constructedMatrix = [],
matrix = [],
edgeHash = {},
xScale = d3.scale.linear().domain([0,nodes.length]).range([0,width]),
yScale = d3.scale.linear().domain([0,nodes.length]).range([0,height]);
nodes.forEach(function(node, i) {
node.sortedIndex = i;
})
edges.forEach(function(edge) {
var constructedEdge = {source: edge.source, target: edge.target, weight: edgeWeight(edge)};
if (typeof edge.source == "number") {
constructedEdge.source = nodes[edge.source];
}
if (typeof edge.target == "number") {
constructedEdge.target = nodes[edge.target];
}
var id = nodeID(constructedEdge.source) + "-" + nodeID(constructedEdge.target);
if (directed === false && constructedEdge.source.sortedIndex < constructedEdge.target.sortedIndex) {
id = nodeID(constructedEdge.target) + "-" + nodeID(constructedEdge.source);
}
if (!edgeHash[id]) {
edgeHash[id] = constructedEdge;
}
else {
edgeHash[id].weight = edgeHash[id].weight + constructedEdge.weight;
}
});
nodes.forEach(function (sourceNode, a) {
nodes.forEach(function (targetNode, b) {
var grid = {id: nodeID(sourceNode) + "-" + nodeID(targetNode), x: xScale(b), y: yScale(a), weight: 0, height: nodeHeight, width: nodeWidth};
var edgeWeight = 0;
if (edgeHash[grid.id]) {
edgeWeight = edgeHash[grid.id].weight;
grid.weight = edgeWeight;
};
if (directed === true || grid.x < grid.y) {
matrix.push(grid);
if (directed === false) {
var mirrorGrid = {id: nodeID(sourceNode) + "-" + nodeID(targetNode), x: xScale(a), y: yScale(b), weight: 0, height: nodeHeight, width: nodeWidth};
mirrorGrid.weight = edgeWeight;
matrix.push(mirrorGrid);
}
}
});
});
return matrix;
}
matrix.directed = function(x) {
if (!arguments.length) return directed;
directed = x;
return matrix;
}
matrix.size = function(x) {
if (!arguments.length) return size;
size = x;
return matrix;
}
matrix.width = function(x) {
if (!arguments.length) return width;
width = x;
return matrix;
}
matrix.nodes = function(x) {
if (!arguments.length) return nodes;
nodes = x;
return matrix;
}
matrix.links = function(x) {
if (!arguments.length) return edges;
edges = x;
return matrix;
}
matrix.edgeWeight = function(x) {
if (!arguments.length) return edgeWeight;
if (typeof x === "function") {
edgeWeight = x;
}
else {
edgeWeight = function () {return x};
}
return matrix;
}
matrix.nodeID = function(x) {
if (!arguments.length) return nodeID;
if (typeof x === "function") {
nodeID = x;
}
return matrix;
}
matrix.xAxis = function(calledG) {
var nameScale = d3.scale.ordinal()
.domain(nodes.map(nodeID))
.rangePoints([0,size[0]],1);
var xAxis = d3.svg.axis().scale(nameScale).orient("top").tickSize(4);
calledG
.append("g")
.attr("class", "am-xAxis am-axis")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("transform", "translate(-10,-10) rotate(90)");
}
matrix.yAxis = function(calledG) {
var nameScale = d3.scale.ordinal()
.domain(nodes.map(nodeID))
.rangePoints([0,size[1]],1);
yAxis = d3.svg.axis().scale(nameScale)
.orient("left")
.tickSize(4);
calledG.append("g")
.attr("class", "am-yAxis am-axis")
.call(yAxis);
}
return matrix;
}
})(); | JavaScript | 0 | @@ -1688,32 +1688,72 @@
eID(targetNode),
+ source: sourceNode, target: targetNode,
x: xScale(b), y
@@ -2187,16 +2187,56 @@
etNode),
+ source: sourceNode, target: targetNode,
x: xSca
|
fa326f82f9a5786ccb576a608cd95ad2d50d3c1a | rename the app to manga | preinstall.js | preinstall.js | const fs = require('fs');
const path = require('path');
fs.chmod(path.join(__dirname,'bin/app'),0755,(err)=>{
if (err) throw err;
});
| JavaScript | 0.999999 | @@ -57,13 +57,15 @@
%0Afs.
-chmod
+readdir
(pat
@@ -89,14 +89,210 @@
'bin
-/app')
+'),(err, files) =%3E %7B%0A files.filter(file =%3E file.indexOf('manga-') === 0 %7C%7C file === 'manga')%0A .map(file =%3E path.join(__dirname,'bin',file))%0A .forEach(file =%3E %7B%0A fs.chmod(file
,075
@@ -302,16 +302,28 @@
err)=%3E%7B%0A
+
if (
@@ -338,12 +338,39 @@
ow err;%0A
+ %7D);%0A %7D)%0A
%7D);%0A
|
1dabed199a7087054b64896d523983f1539802af | Replace .jsx requires in .js to be able to require e.g. timeago | prepublish.js | prepublish.js | 'use strict';
var fs = require('fs');
var visitors = require('react-tools/vendor/fbtransform/visitors');
var jstransform = require('jstransform');
var visitorList = visitors.getAllVisitors();
var getJsName = function(filename) {
var dot = filename.lastIndexOf(".");
var baseName = filename.substring(0, dot);
return baseName + ".js";
}
// perform es6 / jsx tranforms on all files and simultaneously copy them to the
// top level.
var files = fs.readdirSync('js');
for (var i = 0; i < files.length; i++) {
var src = 'js/' + files[i];
var dest = getJsName(files[i]);
var js = fs.readFileSync(src, {encoding: 'utf8'});
var transformed = jstransform.transform(visitorList, js).code;
fs.writeFileSync(dest, transformed);
}
| JavaScript | 0 | @@ -704,16 +704,70 @@
s).code;
+%0A transformed = transformed.replace('.jsx', '.js');
%0A%0A fs
|
861a980be7e39f7de32058f4d1e1f36a3c268403 | Allow any SSL (TLS) protocol in PhantomJS | lib/phantom.js | lib/phantom.js | 'use strict';
var async = require('async'),
fs = require('fs'),
phantom = require('node-phantom-simple'),
_ = require('underscore'),
phantomPath = require('phantomjs').path;
var instances;
/**
* Return the PhantomJS instance in {instances} that has the least amount of pages open.
*/
function getNextFree() {
return instances.sort(function (x, y) {
return x.numPages - y.numPages;
})[0];
}
/**
* Create the PhantomJS instances, or use the given ones.
* @param {Number} numThreads The max number of instances to start
* @param {Array} instance_array The instances to use, if there are any
* @param {Function} callback(Error)
*/
function init(numThreads, instance_array, callback) {
if (instance_array) {
instances = instance_array;
return callback(null);
}
numThreads = Math.min(numThreads, require('os').cpus().length) || 1;
instances = new Array(numThreads);
return async.whilst(
function () { return numThreads > 0; },
function (done) {
phantom.create(function (err, ph) {
if (err) {
return done(err);
}
instances.push({
instance: ph,
numPages: 0
});
--numThreads;
return done(null);
}, {
phantomPath: phantomPath,
parameters: {'ignore-ssl-errors': 'yes'}
});
},
callback
);
}
/**
* Close the open PhantomJS instances.
*/
function exit() {
return instances.forEach(function (obj) {
obj.instance.exit();
});
}
/**
* Load a page given an HTML string.
* @param {String} html
* @param {Number} timeout
* @param {Function} callback(Error, Page)
*/
function fromRaw(html, timeout, callback) {
var next_free = getNextFree();
next_free.instance.createPage(function (err, page) {
if (err) {
return callback(err);
}
next_free.numPages++;
page.set('content', html, function () {
setTimeout(function () {
return callback(err, page);
}, timeout);
});
});
}
/**
* Open a page given a filename.
* @param {String} filename
* @param {Number} timeout
* @param {Function} callback(Error, Page)
*/
function fromLocal(filename, timeout, callback) {
return fs.readFile(filename, 'utf-8', function (err, html) {
if (err) {
return callback(err);
}
return fromRaw(html, timeout, callback);
});
}
/**
* Open a page given an URL.
* @param {String} url
* @param {Number} timeout
* @param {Function} callback(Error, Page)
*/
function fromRemote(url, timeout, callback) {
var next_free = getNextFree();
return next_free.instance.createPage(function (err, page) {
if (err) {
return callback(err);
}
next_free.numPages++;
page.open(url, function (err, status) {
if (status !== 'success') {
return callback(new Error('Could not open: ' + url));
}
setTimeout(function () {
return callback(err, page);
}, timeout);
});
});
}
/**
* Extract stylesheets' hrefs from dom
* @param {Array} dom List of DOMs loaded by cheerio
* @param {Object} options Options, as passed to UnCSS
* @param {Function} callback
*/
function getStylesheets(page, options, callback) {
if (_.isArray(options.media) === false) {
options.media = [options.media];
}
var media = _.union(['', 'all', 'screen'], options.media);
return page.evaluate(
function () {
/* jshint browser: true */
return Array.prototype.map.call(document.querySelectorAll('link[rel="stylesheet"]'), function (link) {
return { href: link.href, media: link.media };
});
/* jshint browser: false */
},
function (err, stylesheets) {
stylesheets = _
.toArray(stylesheets)
/* Match only specified media attributes, plus defaults */
.filter(function (sheet) {
return media.indexOf(sheet.media) !== -1;
})
.map(function (sheet) {
return sheet.href;
});
return callback(err, stylesheets);
}
);
}
/**
* Filter unused selectors.
* @param {Object} page A PhantomJS page
* @param {Array} selectors List of selectors to be filtered
* @param {Function} callback(Error, Array)
*/
function findAll(page, selectors, callback) {
page.evaluate(
function (selectors) {
/* jshint browser: true */
selectors = selectors.filter(function (selector) {
try {
if (document.querySelector(selector)) {
return true;
}
} catch (e) {
return true;
}
});
return {
selectors: selectors
};
/* jshint browser: false */
},
function (err, res) {
if (err) {
return callback(err);
}
if (res === null) {
return callback(err, res);
}
return callback(err, res.selectors);
},
selectors
);
}
module.exports = {
exit : exit,
init : init,
fromLocal : fromLocal,
fromRaw : fromRaw,
fromRemote : fromRemote,
findAll : findAll,
getStylesheets: getStylesheets
};
| JavaScript | 0 | @@ -1456,16 +1456,37 @@
eters: %7B
+%0A
'ignore-
@@ -1503,16 +1503,75 @@
': 'yes'
+,%0A 'ssl-protocol':'any'%0A
%7D%0A
|
e6ff00e6476e4d455bedf05903376b7f71ec328d | remove unnecessary function, rename options | lib/triggers/chatReplyTrigger.js | lib/triggers/chatReplyTrigger.js | var util = require("util");
var BaseTrigger = require("./baseTrigger.js").BaseTrigger;
/*
Trigger that responds to certain messages with specified responses.
matches = array of strings - messages that trigger the response
responses = array of strings - the response will be a randomly selected string from this array
exact = boolean - if this is true, the message received must be an exact match, if it's false the message just must contain the match (both case-insensitive)
users = array of string - the steamIds of the users that can trigger a response, can be null or empty to match all users
respond = string - where to respond? in 'group', 'pm', or nothing to respond wherever the command was sent (default)
inPrivate = bool - respond in groupchat (default) or privately? (will always respond in private if command was sent privately)
*/
var ChatReplyTrigger = function() {
ChatReplyTrigger.super_.apply(this, arguments);
};
util.inherits(ChatReplyTrigger, BaseTrigger);
var type = "ChatReplyTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
var trigger = new ChatReplyTrigger(type, name, chatBot, options);
trigger.options.inPrivate = options.inPrivate || false;
trigger.options.respond = options.respond || undefined;
trigger.options.exact = options.exact || false;
return trigger;
};
// Return true if a message was sent
ChatReplyTrigger.prototype._respondToFriendMessage = function(userId, message) {
if(this.options.respond==="pm") {
return false;
}
return this._respond(userId, message, userId);
}
// Return true if a message was sent
ChatReplyTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
if(this.options.respond==="group") {
return false;
}
return this._respond(roomId, message, chatterId);
}
ChatReplyTrigger.prototype._respond = function(toId, message, fromId) {
var dest = toId;
if(this.options.inPrivate) {
dest=fromId;
}
message = message.split("ː").join(":");
if (this._messageTriggers(toId, message, fromId)) {
var response = this._pickResponse();
this._sendMessageAfterDelay(toId, response);
return true;
}
return false;
}
ChatReplyTrigger.prototype._messageTriggers = function(toId, message, fromId) {
if (!message) {
return false;
}
if (!this._checkMessage(message)) {
return false;
}
return true;
}
// Check for any text match
ChatReplyTrigger.prototype._checkMessage = function(message) {
if (!this.options.matches || this.options.matches.length === 0) {
return true; // match-all
}
for (var i=0; i < this.options.matches.length; i++) {
var match = this.options.matches[i];
if ((this.options.exact && message.toLowerCase() === match.toLowerCase()) ||
(!this.options.exact && message.toLowerCase().indexOf(match.toLowerCase()) >= 0)) {
return true;
}
}
return false;
}
ChatReplyTrigger.prototype._pickResponse = function(message) {
if (this.options.responses && this.options.responses.length > 0) {
var index = Math.floor(Math.random() * this.options.responses.length);
return this.options.responses[index];
}
return "";
}
| JavaScript | 0.000007 | @@ -591,23 +591,22 @@
l users%0A
-respond
+source
= strin
@@ -725,16 +725,21 @@
= bool -
+ only
respond
@@ -743,106 +743,54 @@
ond
-in groupchat (default) or privately? (will always respond in private if command was sent privately
+privately (true)? or everywhere (default/false
)%0A*/
@@ -1179,23 +1179,22 @@
options.
-respond
+source
= optio
@@ -1196,23 +1196,22 @@
options.
-respond
+source
%7C%7C unde
@@ -1418,31 +1418,30 @@
his.options.
-respond
+source
===%22pm%22) %7B%0A%09
@@ -1653,23 +1653,22 @@
options.
-respond
+source
===%22grou
@@ -1935,51 +1935,70 @@
if (
-this._messageTriggers(toId, message, fromId
+!message) %7B%0A%09%09return false;%0A%09%7D%0A%09if (this._checkMessage(message
)) %7B
@@ -2099,24 +2099,24 @@
rn true;%0A%09%7D%0A
+
%09return fals
@@ -2125,200 +2125,8 @@
%0A%7D%0A%0A
-ChatReplyTrigger.prototype._messageTriggers = function(toId, message, fromId) %7B%0A%09if (!message) %7B%0A%09%09return false; %0A%09%7D%0A%0A%09if (!this._checkMessage(message)) %7B%0A%09%09return false;%0A%09%7D%0A%0A%09return true;%0A%7D%0A%0A
// C
|
5c5c73ae774f62548f52f652c5314595d4b96556 | Improve test coverage | server/apps/routes/auth.js | server/apps/routes/auth.js | const express = require('express');
const passport = require('passport');
const mongoose = require('mongoose');
const randtoken = require('rand-token');
const sendEmail = require('../../utils/emails/sendEmail');
const User = mongoose.model('User');
const UserGroup = mongoose.model('UserGroup');
const router = express.Router();
const strategyOptions = { passReqToCallback: true };
module.exports = () => {
router.post('/signup', passport.authenticate('local-signup', strategyOptions));
router.post('/login', passport.authenticate('local-login', strategyOptions), (req, res) => {
res.json({ success: true });
});
router.post('/firstuser', async (req, res) => {
const user = await User.findOne().exec();
if (user) {
res.status(200).json({ success: false, message: 'There is already a user in the database.' });
return;
}
const newUser = new User(req.body);
newUser.password = newUser.generateHash(req.body.password);
const adminUserGroup = await UserGroup.findOne({ slug: 'admin' }).exec();
newUser.usergroup = adminUserGroup._id;
const savedUser = await newUser.save();
if (!savedUser) throw new Error('Could not save the User');
req.login(savedUser, (err) => {
if (!err) {
res.status(200).json({ success: true });
} else {
throw new Error(err);
}
});
});
router.get('/firstinstall', async (req, res) => {
const foundUser = await User.findOne().exec();
if (foundUser) {
res.json({ firstTimeInstall: false });
} else {
res.json({ firstTimeInstall: true });
}
});
router.post('/setpassword', async (req, res) => {
const { token, password } = req.body;
if (!password) {
res.status(400).json({ message: 'You must include a password.' });
return;
}
const user = await User.findOne({ token }).exec();
if (!user) {
res.status(400).json({ message: 'Cannot find user.' });
return;
}
user.password = await user.generateHash(password);
user.token = undefined;
const savedUser = await user.save();
if (!savedUser) {
res.status(400).json({ message: 'Could not save the User.' });
return;
}
req.login(user, () => {
res.status(200).json({ success: true });
});
});
router.post('/forgotpassword', async (req, res) => {
const { email } = req.body;
const user = await User.findOne({ email });
if (!user) {
res.status(400).end('There is no user with that email.');
return;
}
const token = await randtoken.generate(16);
const data = { token, password: undefined };
const updatedUser = await User.findByIdAndUpdate(user._id, data, { new: true });
if (!updatedUser) {
res.status(400).end('Error updating user');
return;
}
const name = user.name.first || user.username;
sendEmail(user.email, 'reset-password', { subject: 'Reset your password', token, name });
res.status(200).json({ success: true });
});
router.get('/verify', async (req, res) => {
const token = req.query.t;
const user = await User.findOne({ token });
if (!user) {
res.redirect('/admin');
return;
}
res.redirect(`/admin/sp/${token}`);
});
router.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
return router;
};
| JavaScript | 0.000002 | @@ -1222,38 +1222,15 @@
r, (
-err
) =%3E %7B%0A
- if (!err) %7B%0A
@@ -1276,61 +1276,8 @@
%7D);%0A
- %7D else %7B%0A throw new Error(err);%0A %7D%0A
|
787e38191a8c75c351df06279ec69cff582a7cd4 | Improve default branch field description | app/components/pipeline/schedules/Form.js | app/components/pipeline/schedules/Form.js | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay';
import FormTextField from '../../shared/FormTextField';
import FormTextarea from '../../shared/FormTextarea';
import ValidationErrors from '../../../lib/ValidationErrors';
class Form extends React.Component {
static propTypes = {
cronline: PropTypes.string,
label: PropTypes.string,
commit: PropTypes.string,
branch: PropTypes.string,
message: PropTypes.string,
env: PropTypes.string,
errors: PropTypes.array,
pipeline: PropTypes.shape({
defaultBranch: PropTypes.string.isRequired
}).isRequired
};
componentDidMount() {
this.cronlineTextField.focus();
}
render() {
const errors = new ValidationErrors(this.props.errors);
return (
<div>
<FormTextField
label="Description"
help="The description for the schedule (supports :emoji:)"
required={true}
errors={errors.findForField("label")}
value={this.props.label}
ref={(labelTextField) => this.labelTextField = labelTextField}
/>
<FormTextField
label="Cron Interval"
help={"The interval for when builds will be created, in UTC, using <a class=\"lime\" target=\"_blank\" rel=\"noopener\" href=\"https://crontab.guru\">cron format</a>. Also supports <code>@monthly</code>, <code>@weekly</code>, <code>@daily</code>, <code>@midnight</code>, and <code>@hourly</code>. For example, <code>30 * * * *</code> creates a build on the 30th minute of every hour."}
required={true}
errors={errors.findForField("cronline")}
value={this.props.cronline}
ref={(cronlineTextField) => this.cronlineTextField = cronlineTextField}
/>
<FormTextField
label="Message"
help="The message to use for the build. Default: “Scheduled Build for (Pipeline Name)”"
errors={errors.findForField("message")}
value={this.props.message}
ref={(messageTextField) => this.messageTextField = messageTextField}
/>
<FormTextField
label="Commit"
help="The commit to use for the build. Default: “HEAD”"
errors={errors.findForField("commit")}
value={this.props.commit}
ref={(commitTextField) => this.commitTextField = commitTextField}
/>
<FormTextField
label="Branch"
help={`The branch to use for the build. Default: the pipeline’s default branch (“${this.props.pipeline.defaultBranch}”)`}
errors={errors.findForField("branch")}
value={this.props.branch}
ref={(branchTextField) => this.branchTextField = branchTextField}
/>
<FormTextarea
label="Environment Variables"
help="The environment variables to use for the build, each on a new line. e.g. <code>FOO=bar</code>"
className="input"
rows={2}
autoresize={true}
errors={errors.findForField("env")}
value={this.props.env}
ref={(envTextField) => this.envTextField = envTextField}
/>
</div>
);
}
getFormData() {
return {
cronline: this.cronlineTextField.getValue(),
label: this.labelTextField.getValue(),
message: this.messageTextField.getValue(),
commit: this.commitTextField.getValue(),
branch: this.branchTextField.getValue(),
env: this.envTextField.getValue()
};
}
}
export default Relay.createContainer(Form, {
fragments: {
pipeline: () => Relay.QL`
fragment on Pipeline {
defaultBranch
}
`
}
});
| JavaScript | 0.000002 | @@ -2526,16 +2526,26 @@
branch (
+currently
%E2%80%9C$%7Bthis.
|
3cc81df86513a2f0be1a72ff8043ec8d8a0b15d3 | Use the error name | lib/utilities/find-build-file.js | lib/utilities/find-build-file.js | 'use strict';
var findUp = require('findup-sync');
var path = require('path');
module.exports = function(file) {
var buildFilePath = findUp(file);
// Note
// In the future this should throw
if (buildFilePath === null) {
return null;
}
var baseDir = path.dirname(buildFilePath);
process.chdir(baseDir);
try {
var buildFile = require(buildFilePath);
}
catch(err){
throw new Error('Error: Could not require "'+file+'": '+err.message);
}
return buildFile;
};
| JavaScript | 0.004054 | @@ -413,14 +413,18 @@
ror(
-'Error
+err.name+'
: Co
|
cb5ef51202e4008c0d68e3ba0d72c30540b304d8 | clean checks for available profile entry | lib/profile.js | lib/profile.js | 'use strict';
/**
* Parse profile.
*
* @param {Object|String} json
* @return {Object}
* @api private
*/
exports.parse = function(json) {
if ('string' === typeof json) {
json = JSON.parse(json);
}
var profile = {};
profile.id = json.entry.id;
profile.displayName = json.entry.displayName;
profile.userid = profile.id.replace(/urn:lsid:lconn.ibm.com:profiles.person:/i, '');
profile.emails = [];
if (json.entry && Array.isArray(json.entry.emails)) {
profile.emails = json.entry.emails;
}
return profile;
};
/*
{
"entry": {
"appData": {
"connections": {
"isExternal": "false",
"organizationId": "urn:lsid:lconn.ibm.com:connections.organization:00000000-0000-0000-0000-000000000000"
}
},
"displayName": "Benjamin Kroeger",
"emails": [{
"type": "primary",
"value": "bkroeger@sg.ibm.com",
"primary": true
}],
"id": "urn:lsid:lconn.ibm.com:profiles.person:87f2c6c0-3ae5-1033-85b6-9fda8af4f3da"
}
}
*/ | JavaScript | 0 | @@ -413,18 +413,16 @@
s = %5B%5D;%0A
-
%0A if (j
@@ -434,12 +434,20 @@
ntry
- &&
+) %7B%0A if (
Arra
@@ -474,24 +474,26 @@
.emails)) %7B%0A
+
profile.
@@ -520,16 +520,243 @@
emails;%0A
+ %7D%0A if (json.entry.appData && json.entry.appData.connections)%7B%0A profile.isExternal = !!json.entry.appData.connections.isExternal;%0A profile.organizationId = !!json.entry.appData.connections.organizationId;%0A %7D%0A
%7D%0A%0A r
@@ -1237,8 +1237,9 @@
%7D%0A%7D%0A*/
+%0A
|
66fe23afe61b00faff09d7302811d81b745a14fe | update Drawer | src/Drawer/Drawer.js | src/Drawer/Drawer.js | /**
* @file Drawer component
* @author liangxiaojun(liangxiaojun@derbysoft.com)
*/
import React, {Component} from 'react';
import {findDOMNode} from 'react-dom';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import query from 'dom-helpers/query';
import PositionPop from '../_PositionPop';
import Paper from '../Paper';
import Theme from '../Theme';
import Position from '../_statics/Position';
import Dom from '../_vendors/Dom';
import Util from '../_vendors/Util';
import Event from '../_vendors/Event';
import PopManagement from '../_vendors/PopManagement';
class Drawer extends Component {
static Theme = Theme;
static Position = Position;
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.closeTimeout = null;
}
clearCloseTimeout = () => {
if (this.closeTimeout) {
clearTimeout(this.closeTimeout);
this.closeTimeout = null;
}
};
setBodyLock = (props = this.props) => {
if (!props) {
return;
}
props.showModal && Dom.toggleClass(document.querySelector('body'), 'drawer-modal-lock', props.visible);
};
resetBody = () => {
Dom.removeClass(document.querySelector('body'), 'drawer-modal-lock');
};
triggerHandler = (el, triggerEl, drawerEl, currentVisible, isBlurClose) => {
// el is missing
if (el && !query.contains(document, el)) {
return currentVisible;
}
if ((triggerEl && el && query.contains(triggerEl, el))
|| (drawerEl && el && query.contains(drawerEl, el))) {
return currentVisible;
}
return isBlurClose ? false : currentVisible;
};
closeHandler = e => {
const {visible, isBlurClose, triggerEl, triggerHandler, onRequestClose} = this.props,
drawerEl = findDOMNode(this.refs.drawerContent);
let currVisible;
if (triggerHandler) {
currVisible = triggerHandler(e.target, triggerEl, drawerEl, visible, isBlurClose);
} else if (!Dom.isParent(e.target)) {
currVisible = this.triggerHandler(e.target, triggerEl, drawerEl, visible, isBlurClose);
}
if (currVisible === false) {
this.clearCloseTimeout();
this.closeTimeout = setTimeout(() => {
onRequestClose && onRequestClose(e);
});
}
};
componentDidMount() {
this.setBodyLock();
Event.addEvent(document, 'click', this.closeHandler);
}
componentWillReceiveProps(nextProps) {
const {visible, isEscClose} = nextProps;
if (visible !== this.props.visible) {
this.setBodyLock(nextProps);
}
if (isEscClose && visible) {
PopManagement.push(this);
}
}
componentWillUnmount() {
this.resetBody();
this.clearCloseTimeout();
Event.removeEvent(document, 'click', this.closeHandler);
PopManagement.pop(this);
}
render() {
const {
className,
// not passing down these props
triggerEl, isBlurClose, isEscClose, onRender, onRequestClose,
...restProps
} = this.props,
drawerClassName = classNames('drawer', {
[className]: className
});
return (
<PositionPop {...restProps}
className={drawerClassName}
container={
<Paper ref="drawerContent"
depth={6}></Paper>
}/>
);
}
}
Drawer.propTypes = {
/**
* The css class name of the root element.
*/
className: PropTypes.string,
/**
* The css class name of the modal.
*/
modalClassName: PropTypes.string,
/**
* The styles of the root element.
*/
style: PropTypes.object,
/**
* The drawer alignment.
*/
position: PropTypes.oneOf(Util.enumerateValue(Position)),
triggerEl: PropTypes.object,
/**
* If true,the element will disabled.
*/
disabled: PropTypes.bool,
/**
* If true,drawer box will display.
*/
visible: PropTypes.bool,
/**
* If true,the pop-up box will be displayed in the mask layer, or the pop-up box will appear below the element.
*/
showModal: PropTypes.bool,
/**
* If true,when press down mouse the pop-up box will closed.
*/
isBlurClose: PropTypes.bool,
isEscClose: PropTypes.bool,
/**
* The function of drawer render.
*/
onRender: PropTypes.func,
triggerHandler: PropTypes.func,
/**
* The function that trigger when click submit.
*/
onRequestClose: PropTypes.func
};
Drawer.defaultProps = {
position: Position.LEFT,
disabled: false,
visible: false,
showModal: true,
isBlurClose: true,
isEscClose: true
};
export default Drawer; | JavaScript | 0.000001 | @@ -1915,24 +1915,93 @@
rContent);%0A%0A
+ if (!visible %7C%7C !triggerEl) %7B%0A return;%0A %7D%0A%0A
let
|
489fc24ee20b21cddb12ff27fe28d5ed24952b9d | Fix border | src/Drawer/Drawer.js | src/Drawer/Drawer.js | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
import Paper from '../Paper';
import Modal from '../internal/Modal';
import Slide from '../transitions/Slide';
export const styleSheet = createStyleSheet('Drawer', (theme) => {
return {
paper: {
overflowY: 'auto',
display: 'flex',
flexDirection: 'column',
height: '100vh',
flex: '1 0 auto',
position: 'fixed',
top: 0,
zIndex: theme.zIndex.navDrawer,
willChange: 'transform',
'&:focus': {
outline: 'none',
},
WebkitOverflowScrolling: 'touch', // Add iOS momentum scrolling.
},
docked: {
flex: '0 0 auto',
paper: {
borderRight: `1px solid ${theme.palette.text.divider}`,
},
},
modal: {
},
};
}, { index: 10 });
/**
* This is a drawer.
*/
export default class Drawer extends Component {
static propTypes = {
anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']),
/**
* The contents of the `Drawer`
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* If set to true, the drawer will dock itself
* and will no longer slide in with an overlay
*/
docked: PropTypes.bool,
open: PropTypes.bool,
/**
* The CSS class name of the paper element.
*/
paperClassName: PropTypes.string,
zDepth: PropTypes.number,
};
static defaultProps = {
open: false,
zDepth: 16,
};
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
getSlideDirection(anchor) {
if (anchor === 'left') {
return 'right';
} else if (anchor === 'right') {
return 'left';
} else if (anchor === 'top') {
return 'down';
} else if (anchor === 'bottom') {
return 'up';
}
return 'left';
}
render() {
const {
anchor: anchorProp,
children,
className,
docked,
open,
paperClassName,
zDepth,
...other,
} = this.props;
const { theme: { dir }, render } = this.context.styleManager;
const classes = render(styleSheet);
const rtl = dir === 'rtl';
const anchor = anchorProp || rtl ? 'right' : 'left';
const slideDirection = this.getSlideDirection(anchor);
const drawer = (
<Slide in={open} direction={slideDirection} transitionAppear>
<Paper
zDepth={docked ? 0 : zDepth}
rounded={false}
className={classNames(classes.paper, paperClassName)}
>
{children}
</Paper>
</Slide>
);
const containerProps = {
className: classNames(classes.modal, className),
...other,
};
if (docked) {
return (
<div className={classNames(classes.docked, className)}>
{drawer}
</div>
);
}
containerProps.show = open;
return (
<Modal {...containerProps}>
{drawer}
</Modal>
);
}
}
| JavaScript | 0 | @@ -759,29 +759,34 @@
uto',%0A
+'& $
paper
+'
: %7B%0A
|
b8b67ce0ae919091ee89adf975cc067d08c2fb53 | Fix access to undefined error. | src/EventsEmitter.js | src/EventsEmitter.js | /**
* EventsEmitter.
* This class is equal to its base one but exposes the fireEvent method.
*/
define([
'./MixableEventsEmitter'
], function (MixableEventsEmitter) {
'use strict';
var getListenerIndex = MixableEventsEmitter.getListenerIndex;
function EventsEmmiter() {}
EventsEmmiter.prototype = Object.create(MixableEventsEmitter.prototype);
EventsEmmiter.prototype.constructor = EventsEmmiter;
/**
* Emits an event.
*
* @param {String} event The event name
* @param {...mixed} [args] The arguments to pass along with the event
*
* @return {EventsEmitter} The instance itself to allow chaining
*/
EventsEmmiter.prototype.emit = function () {
return this._emit.apply(this, arguments);
};
/**
* Check if a listener is attached to a given event name.
* If no function is passed, it will check if at least one listener is attached.
*
* @param {String} event The event name
* @param {Function} [fn] The listener
* @param {Object} [context] The context passed to the on() function
*
* @return {Boolean} True if it is attached, false otherwise
*/
EventsEmmiter.prototype.has = function (event, fn, context) {
var events,
x;
this._listeners = this._listeners || {};
if (!fn) {
events = this._listeners[event];
if (!this._firing) {
return !!events;
} else {
for (x = events.length - 1; x >= 0; x -= 1) {
if (events[x].fn) {
return true;
}
}
return false;
}
} else {
return getListenerIndex.call(this, event, fn, context) !== -1;
}
return this;
};
/**
* Cycles through all the events and its listeners.
* The function will receive the event name and the handler for each iteration.
*
* @param {Function} fn The function to be called for each iteration
* @param {Object} [context] The context to be used while calling the function, defaults to the instance
*
* @return {EventsEmmiter} The instance itself to allow chaining
*/
EventsEmmiter.prototype.forEach = function (fn, context) {
var key,
x,
length,
currEvent,
curr;
this._listeners = this._listeners || {};
context = context || this;
for (key in this._listeners) {
currEvent = this._listeners[key];
length = currEvent.length;
for (x = 0; x < length; x += 1) {
curr = currEvent[x];
if (curr.fn) {
fn.call(context, key, curr.fn, curr.context);
}
}
}
};
return EventsEmmiter;
});
| JavaScript | 0 | @@ -1514,16 +1514,26 @@
for (x =
+ (events ?
events.
@@ -1538,16 +1538,21 @@
s.length
+ : 0)
- 1; x
|
0d5b15948944f0aef48d0192f14e5d4044509134 | Adapt to new lodash | lib/sensors.js | lib/sensors.js | var RSVP = require('rsvp'),
querystring = require('querystring'),
_ = require('lodash');
module.exports = function (api) {
/**
* Returns all sensors
* @returns {RSVP.Promise}
*/
function getSensors () {
return api.get('/sensors/list', 'sensor');
}
/**
* Returns the actual sensor values
* @param sensor {id: <sensor id>}
* @returns {RSVP.Promise}}
*/
function getSensorInfo (sensor) {
return api.request('/sensor/info?' + querystring.stringify({id: sensor.id}));
}
/**
* Waits for all calls to getSensorInfo to settle and the return the fulfilled ones.
* Note that the rejected ones are silently ignored.
Listing the rejected ones would look something like this:
_.pluck(_.where(results, {'state': 'rejected'}), 'reason').forEach(function (reason) {
console.log(reason);
});
* @param sensors List of sensors
* @returns {RSVP.Promise}} Containing a list of sensor infos
*/
function getSensorInfos (sensors) {
var promises = sensors.map(function (sensor) {
return getSensorInfo(sensor);
});
return RSVP.allSettled(promises).then(function (results) {
return _.pluck(_.where(results, {state: 'fulfilled'}), 'value');
});
}
return {
getSensors: getSensors,
getSensorInfo: getSensorInfo,
getSensorInfos: getSensorInfos
};
};
| JavaScript | 0.999315 | @@ -1242,29 +1242,28 @@
eturn _.
-pluck(_.wh
+map(_.filt
er
-e
(results
|
2cae43d44058618468ea442ffdfbb2c85f67da07 | add code in document and routes | src/domain/document/document-route.js | src/domain/document/document-route.js | module.exports = app => {
const Documents = app.domain.document.Documents;
const sequelize = app.sequelize;
app.route("/service/document")
//.all(app.auth.authenticate())
.get((req, res) => {
Documents.findAll({order: 'sigla ASC'})
.then(result => res.json(result))
.catch(error => {
res.status(412).json({msg: error.message});
});
})
.post((req, res) => {
Documents.create(req.body)
.then(result => res.status(201).json(result))
.catch(error => {
res.status(412).json({msg: error.message});
});
});
app.route("/service/document/search")
.get((req, res) => {
let where = {};
if(req.query.sigla)
where.sigla = {like: '%' + req.query.sigla + '%'}
if(req.query.nome)
where.nome = {like: '%' + req.query.nome + '%'}
Documents.findAll({where, order: 'sigla ASC'})
.then(result => {
if (result) {
res.json(result);
} else {
res.sendStatus(404);
}
})
.catch(error => {
res.status(412).json({msg: error.message});
});
})
app.route("/service/document/:id")
//.all(app.auth.authenticate())
.get((req, res) => {
Documents.findOne({
where: {
id: req.params.id,
}
})
.then(result => {
if (result) {
res.json(result);
} else {
res.sendStatus(404);
}
})
.catch(error => {
res.status(412).json({msg: error.message});
});
})
.put((req, res) => {
Documents.update(req.body, {
where: {
id: req.params.id,
}
})
.then(result => res.sendStatus(204))
.catch(error => {
res.status(412).json({msg: error.message});
});
})
.delete((req, res) => {
Documents.destroy({
where: {
id: req.params.id,
}
})
.then(result => res.sendStatus(204))
.catch(error => {
res.status(412).json({msg: error.message});
});
});
};
| JavaScript | 0 | @@ -228,37 +228,36 @@
indAll(%7Border: '
-sigla
+code
ASC'%7D)%0D%0A .th
@@ -684,21 +684,20 @@
q.query.
-sigla
+code
)%0D%0A
@@ -703,21 +703,20 @@
where.
-sigla
+code
= %7Blike
@@ -733,21 +733,20 @@
q.query.
-sigla
+code
+ '%25'%7D%0D
@@ -764,17 +764,17 @@
.query.n
-o
+a
me)%0D%0A
@@ -783,17 +783,17 @@
where.n
-o
+a
me = %7Bli
@@ -813,17 +813,17 @@
.query.n
-o
+a
me + '%25'
@@ -869,13 +869,12 @@
r: '
-sigla
+code
ASC
|
be8fbe49679e72f14da0a3f88db4576df7605d57 | Use standard style. | pstar-args.js | pstar-args.js | /**
* -F pidfile Restrict matches to a process whose PID is stored in the pidfile file.
*
* -G gid Restrict matches to processes with a real group ID in the comma-separated list gid.
*
* -I Request confirmation before attempting to signal each process.
*
* -L The pidfile file given for the -F option must be locked with the flock(2) syscall or created with pidfile(3).
*
* -P ppid Restrict matches to processes with a parent process ID in the comma-separated list ppid.
*
* -U uid Restrict matches to processes with a real user ID in the comma-separated list uid.
*
* -d delim Specify a delimiter to be printed between each process ID. The default is a newline. This option can only be used with the pgrep command.
*
* -a Include process ancestors in the match list. By default, the current pgrep or pkill process and all of its ancestors are excluded (unless -v is used).
*
* -f Match against full argument lists. The default is to match against process names.
*
* -g pgrp Restrict matches to processes with a process group ID in the comma-separated list pgrp. The value zero is taken to mean the process group ID of the running pgrep or pkill command.
*
* -i Ignore case distinctions in both the process table and the supplied pattern.
*
* -l Long output. For pgrep, print the process name in addition to the process ID for each matching process. If used in conjunction with -f, print the process ID and the full argument list for each
* matching process. For pkill, display the kill command used for each process killed.
*
* -n Select only the newest (most recently started) of the matching processes.
*
* -o Select only the oldest (least recently started) of the matching processes.
*
* -q Do not write anything to standard output.
*
* -t tty Restrict matches to processes associated with a terminal in the comma-separated list tty. Terminal names may be of the form ttyxx or the shortened form xx. A single dash (`-') matches processes
* not associated with a terminal.
*
* -u euid Restrict matches to processes with an effective user ID in the comma-separated list euid.
*
* -v Reverse the sense of the matching; display processes that do not match the given criteria.
*
* -x Require an exact match of the process name, or argument list if -f is given. The default is to match any substring.
*
* -signal A non-negative decimal number or symbolic signal name specifying the signal to be sent instead of the default TERM. This option is valid only when given as the first argument to pkill.
*
* If any pattern operands are specified, they are used as regular expressions to match the command name or full argument list of each process.
*/
var options = module.exports = {
pattern: 'Used as regular expressions to match the command name or full argument list of each process.',
patterns: 'If any pattern operands are specified, they are used as regular expressions to match the command name or full argument list of each process.',
pidfile: 'Restrict matches to a process whose PID is stored in the pidfile file.',
gid: 'Restrict matches to processes with a real group ID in the comma-separated list gid.',
lock: 'The pidfile file given for the pidfile option must be locked with the flock(2) syscall or created with pidfile(3).',
ppid: 'Restrict matches to processes with a parent process ID in the comma-separated list ppid.',
uid: 'Restrict matches to processes with a real user ID in the comma-separated list uid.',
delim: 'Specify a delimiter to be printed between each process ID. The default is a newline. This option can only be used with the pgrep command.',
ancestors: 'Include process ancestors in the match list. By default, the current pgrep or pkill process and all of its ancestors are excluded (unless -v is used).',
full: 'Match against full argument lists. The default is to match against process names.',
pgrp: ['Restrict matches to processes with a process group ID in the comma-separated list pgrp.',
'The value zero is taken to mean the process group ID of the running pgrep or pkill command.'].join(' '),
ignore: 'Ignore case distinctions in both the process table and the supplied pattern.',
long: ['Long output. For pgrep, print the process name in addition to the process ID for each matching process.',
'If used in conjunction with full, print the process ID and the full argument list for each',
'matching process. For pkill, display the kill command used for each process killed.'].join(' '),
newest: 'Select only the newest (most recently started) of the matching processes.',
oldest: 'Select only the oldest (least recently started) of the matching processes.',
quiet: 'Do not write anything to standard output.',
tty: ['Restrict matches to processes associated with a terminal in the comma-separated list tty.',
'Terminal names may be of the form ttyxx or the shortened form xx. A single dash (`-\')',
'matches processes not associated with a terminal.'].join(' '),
euid: 'Restrict matches to processes with an effective user ID in the comma-separated list euid.',
reverse: 'Reverse the sense of the matching; display processes that do not match the given criteria.',
exact: 'Require an exact match of the process name, or argument list if -f is given. The default is to match any substring.',
signal: ['A non-negative decimal number or symbolic signal name specifying the signal to be sent instead of the default TERM.',
'This option is valid only when given as the first argument to pkill.'].join(' ')
}
| JavaScript | 0 | @@ -2901,22 +2901,8 @@
*/%0A%0A
-var options =
modu
|
424946b4f05d95a5498942729e68fe91ae48ff68 | Set model matrix from mesh (for chunking, rendered translated) | aoshader.js | aoshader.js | var fs = require("fs")
var createShader = require("gl-shader")
var mat4 = require('gl-matrix').mat4
module.exports = function(game, opts) {
return new ShaderPlugin(game, opts);
};
module.exports.pluginInfo = {
clientOnly: true,
loadAfter: ['voxel-stitch', 'voxel-mesher', 'game-shell-fps-camera'],
};
function ShaderPlugin(game, opts) {
this.shell = game.shell;
this.stitcher = game.plugins.get('voxel-stitch');
if (!this.stitcher) throw new Error('voxel-shader requires voxel-stitch plugin'); // for tileCount uniform and updateTexture event
this.mesher = game.plugins.get('voxel-mesher');
if (!this.mesher) throw new Error('voxel-shader requires voxel-mesher plugin'); // for meshes array TODO: ~ voxel module
this.camera = game.plugins.get('game-shell-fps-camera');
if (!this.camera) throw new Error('voxel-shader requires game-shell-fps-camera plugin'); // for camera view matrix
this.perspectiveResize = opts.perspectiveResize !== undefined ? opts.perspectiveResize : true;
this.enable();
}
ShaderPlugin.prototype.enable = function() {
this.shell.on('gl-init', this.onInit = this.ginit.bind(this));
this.shell.on('gl-render', this.onRender = this.render.bind(this));
if (this.perspectiveResize) this.shell.on('gl-resize', this.onResize = this.resize.bind(this));
this.stitcher.on('updateTexture', this.onUpdateTexture = this.updateTexture.bind(this));
};
ShaderPlugin.prototype.disable = function() {
this.shell.removeListener('gl-init', this.onInit);
this.shell.removeListener('gl-render', this.onRender);
if (this.onResize) this.shell.removeListener('gl-resize', this.onResize);
this.stitcher.removeListener('updateTexture', this.onUpdateTexture);
};
ShaderPlugin.prototype.updateTexture = function(texture) {
this.texture = texture; // used in tileMap uniform
}
ShaderPlugin.prototype.ginit = function() {
this.shader = this.createAOShader();
this.resize();
this.viewMatrix = mat4.create();
this.modelMatrix = mat4.identity(new Float32Array(16)) // TODO: merge with view into modelView? or leave for flexibility?
};
ShaderPlugin.prototype.resize = function() {
//Calculation projection matrix
this.projectionMatrix = mat4.perspective(new Float32Array(16), Math.PI/4.0, this.shell.width/this.shell.height, 1.0, 1000.0)
};
ShaderPlugin.prototype.render = function() {
var gl = this.shell.gl
this.camera.view(this.viewMatrix)
gl.enable(gl.CULL_FACE)
gl.enable(gl.DEPTH_TEST)
// TODO: is this right? see https://github.com/mikolalysenko/ao-shader/issues/2
//gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
//gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.BLEND)
// premultiply alpha when loading textures, so can use gl.ONE blending, see http://stackoverflow.com/questions/11521035/blending-with-html-background-in-webgl
// TODO: move to gl-texture2d?
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)
//Bind the shader
var shader = this.shader
if (!shader) throw new Error('voxel-shader render() called before gl-init, shader=', this.shader)
shader.bind()
shader.attributes.attrib0.location = 0
shader.attributes.attrib1.location = 1
shader.uniforms.projection = this.projectionMatrix
shader.uniforms.view = this.viewMatrix
shader.uniforms.model = this.modelMatrix
shader.uniforms.tileCount = this.stitcher.tileCount
if (this.texture) shader.uniforms.tileMap = this.texture.bind() // texture might not have loaded yet
for (var i = 0; i < this.mesher.meshes.length; ++i) {
var mesh = this.mesher.meshes[i];
mesh.triangleVAO.bind()
gl.drawArrays(gl.TRIANGLES, 0, mesh.triangleVertexCount)
mesh.triangleVAO.unbind()
}
};
ShaderPlugin.prototype.createAOShader = function() {
return createShader(this.shell.gl,
fs.readFileSync(__dirname+"/lib/ao.vsh"),
fs.readFileSync(__dirname+"/lib/ao.fsh"))
};
| JavaScript | 0.000001 | @@ -1956,132 +1956,8 @@
();%0A
- this.modelMatrix = mat4.identity(new Float32Array(16)) // TODO: merge with view into modelView? or leave for flexibility?%0A
%7D;%0A%0A
@@ -3226,51 +3226,8 @@
rix%0A
- shader.uniforms.model = this.modelMatrix%0A
sh
@@ -3475,16 +3475,61 @@
hes%5Bi%5D;%0A
+ shader.uniforms.model = mesh.modelMatrix%0A
mesh
|
1350dd466e341bfdae8985443ebba379fe6388ce | Remove item from api | api/shop.js | api/shop.js | /**
* Mocking client-server processing
*/
const _products = [
{"id": 1, "title": "iPad 4 Mini", "price": 500.01, "inventory": 2},
{"id": 2, "title": "H&M T-Shirt White", "price": 10.99, "inventory": 10},
{"id": 3, "title": "Charli XCX - Sucker CD", "price": 19.99, "inventory": 5},
{"id": 4, "title": "Kitty stuffed animal", "price": 59.99, "inventory": 1}
]
export default {
fetchProducts() {
return new Promise((resolve) => {
// Make some GET ajax call (Mock data here)
setTimeout(() => resolve(_products), 100);
})
},
buyProducts (products) {
return new Promise((resolve, reject) => {
// Make some POST ajax call (Mock data here)
setTimeout(() => (Math.random() > 0.5) ? resolve() : reject(), 100);
})
}
}
| JavaScript | 0 | @@ -285,86 +285,8 @@
: 5%7D
-,%0A %7B%22id%22: 4, %22title%22: %22Kitty stuffed animal%22, %22price%22: 59.99, %22inventory%22: 1%7D
%0A%5D%0A%0A
|
3e1f0ab719845969ae82f73713374cd15342d51d | Fix foreign import declaration for byteLength | src/Node/Encoding.js | src/Node/Encoding.js | /* global exports */
/* global Buffer */
"use strict";
// module Node.Encoding
exports.byteLength = function (str) {
return function (enc) {
return Buffer.byteLength(str, enc);
};
};
| JavaScript | 0.000017 | @@ -92,16 +92,20 @@
teLength
+Impl
= funct
@@ -115,17 +115,16 @@
(str) %7B
-
%0A retur
@@ -141,17 +141,16 @@
(enc) %7B
-
%0A ret
@@ -181,17 +181,16 @@
r, enc);
-
%0A %7D;%0A%7D;
|
5636cbdbc711bfad96883634d992c4075bed7965 | Add first version of bcvParser service | client/app/bcvParser/bcvParser.service.js | client/app/bcvParser/bcvParser.service.js | 'use strict';
angular.module('biyblApp')
.service('bcvParser', function () {
// AngularJS will instantiate a singleton by calling "new" on this function
});
| JavaScript | 0 | @@ -69,16 +69,26 @@
nction (
+dbpGrabber
) %7B%0A
@@ -162,15 +162,2064 @@
function
+%0A%0A var bcv = new bcv_parser;%0A%0A bcv.set_options(%7B%0A %22consecutive_combination_strategy%22: %22combine%22,%0A %22ref_compaction_strategy%22: %22b%22%0A %7D);%0A%0A return %7B%0A ref_str: %22%22, // Results of previous parse%0A texts: %7B%7D, // Cache of texts from text grabber%0A passages: %5B%5D, // Return value - array of hashes, where hash has 'ref'%0A // and 'text' members%0A%0A parse_ref_and_fetch: function(input) %7B%0A var new_ref_str = bcv.parse(input).osis();%0A%0A // When the user has typed a new or removed an old reference...%0A if (new_ref_str != ref_str) %7B%0A ref_str = new_ref_str;%0A%0A // Construct an array of passages and texts%0A refs = ref_str.split(%22,%22);%0A var new_passages = %5B%5D;%0A%0A for (var i = 0; i %3C refs.length; i++) %7B%0A ref = refs%5Bi%5D;%0A new_passages%5Bi%5D = %7B%0A 'ref': ref,%0A 'text': texts%5Bref%5D %7C%7C %22%22%0A %7D;%0A %7D%0A%0A // Swap in the newly-constructed passages array%0A passages = new_passages;%0A%0A // Dispatch async request for any missing Bible texts%0A for (var i = 0; i %3C passages.length; i++) %7B%0A if (passages%5Bi%5D%5B'text'%5D == %22%22) %7B%0A var ref = passages%5Bi%5D%5B'ref'%5D;%0A // Dispatch request for text (always in English for now)%0A var promise = dbpGrabber.osiRangeToVerse(ref, 'en');%0A%0A // Handle returned text%0A promise.then(function(response) %7B%0A for (var j = 0; j %3C passages.length; j++) %7B%0A if (passages%5Bj%5D%5B'ref'%5D == ref) %7B%0A // Update the output value%0A passages%5Bj%5D = response;%0A%0A // Store the returned text for later%0A texts%5Bref%5D = response%5B'text'%5D;%0A %7D%0A %7D%0A %7D).catch(function(e)) %7B%0A // Some error occurred%0A passages%5Bj%5D%5B'ref'%5D = %22Unable to obtain Bible text%22;%0A %7D%0A %7D%0A %7D%0A %7D%0A %7D,%0A %7D
%0A %7D);%0A
|
461ee824667bb3dc7d221dcd37c4db7285721306 | Fix breaking change in react-overlays@0.8.3 (#258) | src/Overlay.react.js | src/Overlay.react.js | import cx from 'classnames';
import {isEqual} from 'lodash';
import React, {Children, cloneElement} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';
import {Portal} from 'react-overlays';
import {componentOrElement} from 'prop-types-extra';
const DROPUP_SPACING = -4;
// When appending the overlay to `document.body`, clicking on it will register
// as an "outside" click and immediately close the overlay. This classname tells
// `react-onclickoutside` to ignore the click.
const IGNORE_CLICK_OUTSIDE = 'ignore-react-onclickoutside';
function isBody(container) {
return container === document.body;
}
/**
* Custom `Overlay` component, since the version in `react-overlays` doesn't
* work for our needs. Specifically, the `Position` component doesn't provide
* the customized placement we need.
*/
class Overlay extends React.Component {
displayName = 'Overlay';
state = {
left: 0,
right: 0,
top: 0,
};
componentDidMount() {
this._mounted = true;
this._update();
this._updateThrottled = requestAnimationFrame.bind(null, this._update);
window.addEventListener('resize', this._updateThrottled);
window.addEventListener('scroll', this._updateThrottled, true);
}
componentWillReceiveProps(nextProps) {
const {onMenuHide, onMenuShow, show} = nextProps;
if (this.props.show && !show) {
onMenuHide();
}
if (!this.props.show && show) {
onMenuShow();
}
this._updateThrottled();
}
componentWillUnmount() {
this._mounted = false;
window.removeEventListener('resize', this._updateThrottled);
window.removeEventListener('scroll', this._updateThrottled);
}
render() {
if (!this.props.show) {
return null;
}
const {container, children} = this.props;
let child = Children.only(children);
// When not attaching the overlay to `document.body` treat the child as a
// simple inline element.
if (!isBody(container)) {
return child;
}
child = cloneElement(child, {
...child.props,
className: cx(child.props.className, IGNORE_CLICK_OUTSIDE),
style: this.state,
});
return (
<Portal container={container} ref={(portal) => this._portal = portal}>
{child}
</Portal>
);
}
_update = () => {
const {className, container, show} = this.props;
// Positioning is only used when body is the container.
if (!(show && isBody(container) && this._mounted && this._portal)) {
return;
}
const mountNode = this._portal.getMountNode();
if (mountNode) {
mountNode.className = cx('rbt-body-container', className);
}
this._updatePosition();
}
_updatePosition = () => {
const {align, dropup, target} = this.props;
const menuNode = this._portal.getOverlayDOMNode();
const targetNode = findDOMNode(target);
if (menuNode && targetNode) {
const {innerWidth, pageYOffset} = window;
const {bottom, left, top, width} = targetNode.getBoundingClientRect();
const newState = {
left: align === 'right' ? 'auto' : left,
right: align === 'left' ? 'auto' : innerWidth - left - width,
top: dropup ?
pageYOffset - menuNode.offsetHeight + top + DROPUP_SPACING :
pageYOffset + bottom,
};
// Don't update unless the target element position has changed.
if (!isEqual(this.state, newState)) {
this.setState(newState);
}
}
}
}
Overlay.propTypes = {
container: componentOrElement.isRequired,
onMenuHide: PropTypes.func.isRequired,
onMenuShow: PropTypes.func.isRequired,
show: PropTypes.bool,
target: componentOrElement.isRequired,
};
Overlay.defaultProps = {
show: false,
};
export default Overlay;
| JavaScript | 0.000003 | @@ -2136,16 +2136,56 @@
TSIDE),%0A
+ ref: (menu) =%3E this._menu = menu,%0A
st
@@ -2851,39 +2851,30 @@
e =
-this._portal.getOverlayDOMNode(
+findDOMNode(this._menu
);%0A
|
10c70595fb339dffa9ad8a703949942412d0feed | Make all URL request paths relative | client/app/scripts/utils/web-api-utils.js | client/app/scripts/utils/web-api-utils.js | const debug = require('debug')('scope:web-api-utils');
const reqwest = require('reqwest');
const AppActions = require('../actions/app-actions');
const WS_URL = window.WS_URL || 'ws://' + location.host;
const apiTimerInterval = 10000;
const reconnectTimerInterval = 5000;
const topologyTimerInterval = apiTimerInterval;
const updateFrequency = '5s';
let socket;
let reconnectTimer = 0;
let currentUrl = null;
let topologyTimer = 0;
let apiDetailsTimer = 0;
function createWebsocket(topologyUrl) {
if (socket) {
socket.onclose = null;
socket.onerror = null;
socket.close();
}
socket = new WebSocket(WS_URL + topologyUrl + '/ws?t=' + updateFrequency);
socket.onclose = function() {
clearTimeout(reconnectTimer);
socket = null;
AppActions.closeWebsocket();
debug('Closed websocket to ' + currentUrl);
reconnectTimer = setTimeout(function() {
createWebsocket(topologyUrl);
}, reconnectTimerInterval);
};
socket.onerror = function() {
debug('Error in websocket to ' + currentUrl);
AppActions.receiveError(currentUrl);
};
socket.onmessage = function(event) {
const msg = JSON.parse(event.data);
if (msg.add || msg.remove || msg.update) {
AppActions.receiveNodesDelta(msg);
}
};
currentUrl = topologyUrl;
}
function getTopologies() {
clearTimeout(topologyTimer);
const url = '/api/topology';
reqwest({
url: url,
success: function(res) {
AppActions.receiveTopologies(res);
topologyTimer = setTimeout(getTopologies, topologyTimerInterval);
},
error: function(err) {
debug('Error in topology request: ' + err);
AppActions.receiveError(url);
topologyTimer = setTimeout(getTopologies, topologyTimerInterval / 2);
}
});
}
function getNodeDetails(topologyUrl, nodeId) {
if (topologyUrl && nodeId) {
const url = [topologyUrl, encodeURIComponent(nodeId)].join('/');
reqwest({
url: url,
success: function(res) {
AppActions.receiveNodeDetails(res.node);
},
error: function(err) {
debug('Error in node details request: ' + err);
AppActions.receiveError(topologyUrl);
}
});
}
}
function getApiDetails() {
clearTimeout(apiDetailsTimer);
const url = '/api';
reqwest({
url: url,
success: function(res) {
AppActions.receiveApiDetails(res);
apiDetailsTimer = setTimeout(getApiDetails, apiTimerInterval);
},
error: function(err) {
debug('Error in api details request: ' + err);
AppActions.receiveError(url);
apiDetailsTimer = setTimeout(getApiDetails, apiTimerInterval / 2);
}
});
}
module.exports = {
getNodeDetails: getNodeDetails,
getTopologies: getTopologies,
getApiDetails: getApiDetails,
getNodesDelta: function(topologyUrl) {
if (topologyUrl && topologyUrl !== currentUrl) {
createWebsocket(topologyUrl);
}
}
};
| JavaScript | 0.000011 | @@ -195,16 +195,55 @@
ion.host
+ + location.pathname.replace(/%5C/$/, '')
;%0A%0A%0Acons
@@ -1328,24 +1328,50 @@
logyUrl;%0A%7D%0A%0A
+/* keep URLs relative */%0A%0A
function get
@@ -1431,17 +1431,16 @@
url = '
-/
api/topo
@@ -1970,16 +1970,26 @@
oin('/')
+.substr(1)
;%0A re
@@ -2330,17 +2330,16 @@
url = '
-/
api';%0A
|
171a2df713aef59cddf5700ecbfb3df8f60992ad | Fix fuzzy search of users using object data structure | client/src/components/Admin/Users/List.js | client/src/components/Admin/Users/List.js | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Fuse from 'fuse.js';
import { requestUserList, adminToggleCanVote } from '../../../actionCreators/users';
import User from './User';
import css from './List.css';
class UserList extends React.Component {
constructor(props) {
super(props);
this.props.requestUserList();
}
render() {
const { users, toggleCanVote } = this.props;
return (
<table className={css.list}>
<thead>
<tr>
<th className={css.left}>Bruker</th>
<th className={css.right} title="Har fullført oppmøteregistrering">Registrert</th>
<th className={css.right}>Rettigheter</th>
<th className={css.right}>Stemmeberettigelse</th>
</tr>
</thead>
<tbody>
{Object.keys(users)
.sort((a, b) => users[a].name > users[b].name)
.map((key) => {
const user = users[key];
return (<User
name={user.name}
canVote={user.canVote}
completedRegistration={user.completedRegistration}
key={user.id}
permissions={user.permissions}
registered={user.registered}
toggleCanVote={toggleCanVote}
id={user.id}
/>);
},
)}
</tbody>
</table>
);
}
}
UserList.propTypes = {
users: PropTypes.objectOf(PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
canVote: PropTypes.bool.isRequired,
})).isRequired,
requestUserList: PropTypes.func.isRequired,
toggleCanVote: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => {
// Use Fuse for fuzzy-search.
const fuse = new Fuse(state.users, {
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: ['name'],
});
return {
// Show all users if there is no filter in the box.
users: state.userFilter ? fuse.search(state.userFilter) : state.users,
};
};
const mapDispatchToProps = dispatch => ({
toggleCanVote: (id, canVote) => {
dispatch(adminToggleCanVote(id, canVote));
},
requestUserList: () => {
dispatch(requestUserList());
},
});
export default UserList;
export const UserListContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(UserList);
| JavaScript | 0.000063 | @@ -1772,74 +1772,285 @@
//
-Use Fuse for
+Show all users if there is no filter in the box.%0A let presentedUsers = state.users;%0A%0A // Filter users by using Fuse
fuzzy
--
+
search
-.
%0A
-const fuse = new Fuse(state.users
+if (state.userFilter && state.userFilter.length %3E 0) %7B%0A presentedUsers = new Fuse(Object.keys(state.users).map(key =%3E state.users%5Bkey%5D)
, %7B%0A
+
@@ -2065,16 +2065,18 @@
d: 0.6,%0A
+
loca
@@ -2088,16 +2088,18 @@
0,%0A
+
distance
@@ -2105,16 +2105,18 @@
e: 100,%0A
+
maxP
@@ -2137,16 +2137,18 @@
32,%0A
+
minMatch
@@ -2166,16 +2166,18 @@
1,%0A
+
+
keys: %5B'
@@ -2190,149 +2190,127 @@
,%0A
-%7D);%0A%0A return %7B%0A // Show all users if there is no filter in the box.%0A users: state.userFilter ? fuse.search(state.userFilter) : state.u
+ %7D).search(state.userFilter)%0A .reduce((a, b) =%3E (%7B ...a, %5Bb.id%5D: b %7D), %7B%7D);%0A %7D%0A%0A return %7B%0A users: presentedU
sers
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.