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 |
|---|---|---|---|---|---|---|---|
5684e73b7cf946c67ac4c1c18c28c7b74628be75 | Change reference to this as self [skip ci] | website/static/js/pages/home-page.js | website/static/js/pages/home-page.js | var SignUp = require('../signUp.js');
new SignUp('#signUpScope', '/api/v1/register/');
var TweenLite = require('TweenLite');
require('EasePack');
require('vendor/youtube');
// ANIMATION FOR FRONT PAGE
$( document ).ready(function() {
$('#logo').removeClass('off');
$('.youtube').YouTubeModal({autoplay:1, width:640, height:480});
});
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = 'Don\'t call this twice without a uniqueId';
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
(function() {
var width;
var height;
var largeHeader;
var canvas;
var ctx;
var points;
var target;
var animateHeader = true;
// Main
initHeader();
initAnimation();
addListeners();
function initHeader() {
width = window.innerWidth;
height = '800';
target = {x: width/2, y: height/2};
largeHeader = document.getElementById('home-hero');
canvas = $('#demo-canvas')[0];
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
// create points
points = [];
for(var x = 0; x < width; x = x + width/20) {
for(var y = 0; y < height; y = y + height/20) {
var px = x + Math.random()*width/20;
var py = y + Math.random()*height/20;
var p = {x: px, originX: px, y: py, originY: py };
points.push(p);
}
}
// for each point find the 5 closest points
for(var i = 0; i < points.length; i++) {
var closest = [];
var p1 = points[i];
for(var j = 0; j < points.length; j++) {
var p2 = points[j];
if (p1 !== p2) {
var placed = false;
for(var k = 0; k < 5; k++) {
if(!placed) {
if(closest[k] === undefined) {
closest[k] = p2;
placed = true;
}
}
}
for(var m = 0; m < 5; m++) {
if(!placed) {
if(getDistance(p1, p2) < getDistance(p1, closest[m])) {
closest[m] = p2;
placed = true;
}
}
}
}
}
p1.closest = closest;
}
// assign a circle to each point
for(var n in points) {
var c = new Circle(points[n], 2+Math.random()*2, 'rgba(255,255,255,0.3)');
points[n].circle = c;
}
}
// Event handling
function addListeners() {
setPos();
window.addEventListener('scroll', scrollCheck);
window.addEventListener('resize', resize);
}
function setPos(e) {
target.x = window.innerWidth/2;
target.y = 330;
}
function scrollCheck() {
if(document.body.scrollTop > height) animateHeader = false;
else animateHeader = true;
}
function resize() {
if (window.innerWidth > 990) {
waitForFinalEvent(function(){
$('#demo-canvas').remove();
$('#canvas-container').append('<canvas id="demo-canvas"></canvas>');
initHeader();
initAnimation();
}, 300, 'resize');
}
}
// animation
function initAnimation() {
animate();
for(var i in points) {
shiftPoint(points[i]);
}
}
function animate() {
if(animateHeader) {
ctx.clearRect(0,0,width,height);
for(var i in points) {
// detect points in range
if(Math.abs(getDistance(target, points[i])) < 4000) {
points[i].active = 0.3;
points[i].circle.active = 0.6;
} else if(Math.abs(getDistance(target, points[i])) < 20000) {
points[i].active = 0.1;
points[i].circle.active = 0.3;
} else if(Math.abs(getDistance(target, points[i])) < 40000) {
points[i].active = 0.02;
points[i].circle.active = 0.1;
} else {
points[i].active = 0;
points[i].circle.active = 0;
}
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}
function shiftPoint(p) {
TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
onComplete: function() {
shiftPoint(p);
}});
}
// Canvas manipulation
function drawLines(p) {
if(!p.active) return;
for(var i in p.closest) {
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.closest[i].x, p.closest[i].y);
ctx.strokeStyle = 'rgba(156,217,249,'+ p.active+')';
ctx.stroke();
}
}
function Circle(pos,rad,color) {
var _this = this;
// constructor
(function() {
_this.pos = pos || null;
_this.radius = rad || null;
_this.color = color || null;
})();
this.draw = function() {
if(!_this.active) return;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(156,217,249,'+ _this.active+')';
ctx.fill();
};
}
// Util
function getDistance(p1, p2) {
return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
}
})(); | JavaScript | 0 | @@ -5479,21 +5479,20 @@
var
-_this
+self
= this;
@@ -5550,21 +5550,20 @@
-_this
+self
.pos = p
@@ -5586,21 +5586,20 @@
-_this
+self
.radius
@@ -5625,21 +5625,20 @@
-_this
+self
.color =
@@ -5717,21 +5717,20 @@
if(!
-_this
+self
.active)
@@ -5791,21 +5791,20 @@
arc(
-_this
+self
.pos.x,
_thi
@@ -5803,21 +5803,20 @@
.x,
-_this
+self
.pos.y,
_thi
@@ -5811,21 +5811,20 @@
.pos.y,
-_this
+self
.radius,
@@ -5901,13 +5901,12 @@
,'+
-_this
+self
.act
|
8253093a2bd1dc5c16fafc4ced340d4ab46174ac | Clean up comment | js/indexedDB.js | js/indexedDB.js | import IdbKvStore from "idb-kv-store";
import { throttle } from "./utils";
const LOCAL_STORAGE_KEY = "webamp_state";
export async function bindToIndexedDB(webamp, clearState, useState) {
const localStore = new IdbKvStore("webamp_state_database");
if (clearState) {
try {
await localStore.clear();
} catch (e) {
console.log("Failed to clear our IndexeddB state", e);
}
}
if (!useState) {
return;
}
let previousSerializedState = null;
try {
previousSerializedState = await localStore.get(LOCAL_STORAGE_KEY);
} catch (e) {
console.error("Failed to load the saves state from IndexedDB", e);
}
if (previousSerializedState != null) {
webamp.__loadSerializedState(previousSerializedState);
}
async function persist() {
const serializedState = webamp.__getSerializedState();
try {
await localStore.set(LOCAL_STORAGE_KEY, serializedState);
} catch (e) {
console.log("Failed to save our state to IndexedDB", e);
}
}
webamp.__onStateChange(throttle(persist, 1000));
}
| JavaScript | 0 | @@ -607,17 +607,17 @@
the save
-s
+d
state f
|
58206c902cbfb58e48afa3bc3a7634bd04737113 | Fix bug with entries array not getting truncated | src/ui/ArrayInput.js | src/ui/ArrayInput.js | import { select, event } from 'd3-selection';
import { color } from 'd3-color';
import { className } from './utils';
/**
* Get a color as #rrggbb for input type='color'
*/
function colorString(value) {
const asColor = color(value);
const r = asColor.r.toString(16);
const g = asColor.g.toString(16);
const b = asColor.b.toString(16);
return `#${r.length === 1 ? '0' : ''}${r}${g.length === 1 ? '0' : ''}${g}${b.length === 1 ? '0' : ''}${b}`;
}
/**
* Helper that returns true if the value is a color
*/
function isColor(value) {
return value && color(value) != null;
}
export default class ArrayInput {
constructor(parent, props) {
this.parent = parent;
this.update(props);
this.addEntry = this.addEntry.bind(this);
this.removeEntry = this.removeEntry.bind(this);
}
update(nextProps) {
this.props = nextProps;
this.render();
}
setup() {
// create the main panel div
this.root = select(this.parent)
.append('div')
.attr('class', className('array-input'));
this.entries = [];
}
/**
* Callback for when an input field is modified
*/
inputChange(target) {
const index = parseInt(target.parentNode.getAttribute('data-index'), 10);
const { values, onChange } = this.props;
const oldValues = values;
// try to convert it to a number
let newValue = target.value;
if (!isNaN(parseFloat(newValue))) {
newValue = parseFloat(newValue);
}
const newValues = [...oldValues.slice(0, index), newValue, ...oldValues.slice(index + 1)];
onChange(newValues);
}
/**
* Callback for when a new entry should be added
*/
addEntry(target) {
const index = parseInt(target.parentNode.getAttribute('data-index'), 10);
const { values, onChange } = this.props;
const oldValues = values;
const newValues = [...oldValues.slice(0, index + 1), oldValues[index], ...oldValues.slice(index + 1)];
onChange(newValues);
}
/**
* Callback for when an entry should be removed.
*/
removeEntry(target) {
const index = parseInt(target.parentNode.getAttribute('data-index'), 10);
const { values, onChange } = this.props;
const oldValues = values;
const newValues = [...oldValues.slice(0, index), ...oldValues.slice(index + 1)];
onChange(newValues);
}
startDrag(target) {
const index = parseInt(target.parentNode.getAttribute('data-index'), 10);
const { values } = this.props;
this.dragging = target;
this.dragStartY = event.clientY;
this.dragStartValue = values[index];
}
drag(target) {
const index = parseInt(target.parentNode.getAttribute('data-index'), 10);
const { values, onChange } = this.props;
const delta = event.clientY - this.dragStartY;
// a minimum of 8 pixels of mousemovement to start a drag
if (Math.abs(delta) < 8) {
return;
}
const oldValues = values;
let increment = Math.abs(this.dragStartValue * 0.01);
// if it is an integer, minimum increment is 1
let isInteger = false;
if (this.dragStartValue === Math.round(this.dragStartValue)) {
isInteger = true;
increment = Math.max(1, Math.round(increment));
}
let newValue = this.dragStartValue + (increment * -delta);
// roughly get 2 decimal places if not an integer
if (!isInteger) {
newValue = Math.round(newValue * 100) / 100;
}
const newValues = [...oldValues.slice(0, index), newValue, ...oldValues.slice(index + 1)];
onChange(newValues);
}
endDrag() {
this.dragging = undefined;
this.dragStartY = undefined;
this.dragStartValue = undefined;
}
renderEntry(entry, index, removable) {
let root = this.entries[index];
if (!root) {
const that = this;
root = this.entries[index] = this.root.append('div')
.attr('class', className('input-entry'));
root.append('input')
.attr('class', className('input-entry-field'))
.attr('type', 'text')
.on('change', function inputChange() {
that.inputChange(this);
})
.on('mousedown', function mousedown() {
const target = this;
if (isColor(this.value)) {
return;
}
that.startDrag(target);
select(window)
.on('mousemove.arrayinput', () => {
that.drag(target);
})
.on('mouseup.arrayinput', () => {
that.endDrag(target);
select(window).on('mouseup.arrayinput', null)
.on('mousemove.arrayinput', null);
});
});
root.append('span')
.attr('class', className('input-entry-add'))
.text('+')
.on('click', function addClick() {
that.addEntry(this);
});
root.append('span')
.attr('class', className('input-entry-remove'))
.text('×')
.on('click', function removeClick() {
that.removeEntry(this);
});
root.append('input')
.attr('class', className('input-entry-color'))
.attr('type', 'color')
.on('change', function colorChange() {
that.inputChange(this);
});
}
root.select('input').property('value', entry);
root.select(`.${className('input-entry-remove')}`).classed(className('hidden'), !removable);
root.attr('data-index', index);
// handle if color
if (isColor(entry)) {
root.select('input').classed(className('draggable'), false);
root.select(`.${className('input-entry-color')}`)
.property('value', colorString(entry))
.classed(className('hidden'), false);
} else {
root.select('input').classed(className('draggable'), true);
root.select(`.${className('input-entry-color')}`)
.classed(className('hidden'), true);
}
}
render() {
if (!this.root) {
this.setup();
}
const { values, minLength } = this.props;
const removable = values.length > minLength;
values.forEach((entry, i) => {
this.renderEntry(entry, i, removable);
});
// remove any excess entries
this.entries.filter((entry, i) => i >= values.length).forEach(entry => entry.remove());
}
}
| JavaScript | 0 | @@ -6187,14 +6187,71 @@
ove());%0A
+ this.entries = this.entries.slice(0, values.length);%0A
%7D%0A%7D%0A
|
27b339ddeb07b7c00a58b047240b9d599c3ed8bb | Support json schema URIs | schema/spec.js | schema/spec.js | export default {
"defs": {
"spec": {
"title": "Vega visualization specification",
"type": "object",
"allOf": [
{"$ref": "#/defs/scope"},
{
"properties": {
"schema": {
"type": "object",
"properties": {
"language": {"enum": ["vega"]},
"version": {"type": "string"}
}
},
"description": {"type": "string"},
"width": {"type": "number"},
"height": {"type": "number"},
"padding": {"$ref": "#/defs/padding"},
"autosize": {"$ref": "#/defs/autosize"},
"background": {"$ref": "#/defs/background"}
}
}
]
}
}
};
| JavaScript | 0 | @@ -211,16 +211,17 @@
%22
+$
schema%22:
@@ -226,193 +226,41 @@
%22: %7B
-%0A %22type%22: %22object%22,%0A %22properties%22: %7B%0A %22language%22: %7B%22enum%22: %5B%22vega%22%5D%7D,%0A %22version%22: %7B%22type%22: %22string%22%7D%0A %7D%0A
+%22type%22: %22string%22, %22format%22: %22uri%22
%7D,%0A
|
644722b03afad3402de57ca89380fbc05d48b890 | Remove result after query string changes. | scripts/app.js | scripts/app.js | (function () {
"use strict";
var sparql;
sparql = angular.module("sparql", []);
sparql.factory("rdfstore", function () {
var store;
store = null;
return {
getStore: function (callback) {
if (store === null) {
rdfstore.create({
persistent: true,
name: "sparql"
}, function (instance) {
store = instance;
callback(store);
});
} else {
callback(store);
}
}
};
});
sparql.controller("query", function ($scope, rdfstore) {
$scope.queryString = "SELECT * WHERE {?s ?p ?o .}";
$scope.sparqlResult = [];
$scope.sparqlResultVariables = [];
$scope.submitQuery = function () {
try {
rdfstore.getStore(function (store) {
store.execute($scope.queryString, function (success, result) {
var variables, normalizedResult;
if (success === true) {
if (Array.isArray(result) === true) {
if (result.length > 0) {
// Extract variable names.
variables = Object.keys(result[0]);
// Normalize result.
normalizedResult = [];
result.forEach(function (binding) {
var normalizedBinding;
normalizedBinding = [];
variables.forEach(function (variable) {
normalizedBinding.push(binding[variable]);
});
normalizedResult.push(normalizedBinding);
});
$scope.sparqlResult = normalizedResult;
$scope.sparqlResultVariables = variables;
}
}
} else {
console.error(result);
}
});
});
} catch (ex) {
console.error(ex);
}
};
});
sparql.directive("codemirror", function () {
return {
template: "<textarea></textarea>",
restrict: "E",
scope: {
value: "="
},
link: function (scope, element, attrs) {
var textarea;
textarea = element.find("textarea").get(0);
textarea.value = scope.value;
CodeMirror.fromTextArea(textarea, {
mode: "application/x-sparql-query",
tabMode: "indent",
matchBrackets: true,
// Two-finger scrolling in Chrome is prone to go back to the last page.
lineWrapping: true,
onChange: function (editor) {
scope.value = editor.getValue();
scope.$apply();
}
});
}
};
});
}());
| JavaScript | 0.000002 | @@ -2509,32 +2509,180 @@
%7D%0A %7D;%0A
+ $scope.$watch(%22queryString%22, function () %7B%0A $scope.sparqlResult = %5B%5D;%0A $scope.sparqlResultVariables = %5B%5D;%0A %7D);%0A
%7D);%0A%0A spa
|
a9e189cacd46690c7e42f69872ad1bc22d2dd4cd | fix deep equal utility | src/utils/generic.js | src/utils/generic.js | export function deepAssign (target, ...sources) {
sources.forEach((source) => {
forOwn(source, (property) => {
if (isObject(source[property])) {
if (!target[property] || !isObject(target[property])) {
target[property] = {};
}
deepAssign(target[property], source[property]);
} else {
target[property] = source[property];
}
});
});
return target;
}
export function deepEqual (first, second) {
let bool = true;
forOwn(second, (property) => {
if (isObject(second[property])) {
bool = deepEqual(first[property], second[property]);
} else if (first[property] !== second[property]) bool = false;
});
return bool;
}
export function isObject (object) {
return object !== null && typeof object === 'object' &&
(object.constructor === Object || Object.prototype.toString.call(object) === '[object Object]');
}
export function forOwn (object, callback) {
if (isObject(object)) {
for (const property in object) {
if (object.hasOwnProperty(property)) {
callback(property);
}
}
} else {
throw new TypeError('Expected an object literal.');
}
}
export function logger (message) {
if (console) {
console.log(`ScrollReveal: ${message}`); // eslint-disable-line no-console
}
}
export const nextUniqueId = (() => {
let uid = 0;
return () => uid++;
})();
| JavaScript | 0.000001 | @@ -473,16 +473,31 @@
y) =%3E %7B%0A
+%09%09if (bool) %7B%0A%09
%09%09if (is
@@ -524,16 +524,17 @@
ty%5D)) %7B%0A
+%09
%09%09%09bool
@@ -583,16 +583,17 @@
ty%5D);%0A%09%09
+%09
%7D else i
@@ -647,16 +647,20 @@
false;%0A
+%09%09%7D%0A
%09%7D);%0A%09re
|
53e60b640550b072906ee24d7310805c3d9fe9cb | exit status 1 if tests fail | javascript/gulpfile.js | javascript/gulpfile.js | var browserify = require('browserify');
var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require("vinyl-source-stream");
var reactify = require('reactify');
var watchify = require('watchify');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var addsrc = require('gulp-add-src');
var jasmineBrowser = require('gulp-jasmine-browser');
var production = (process.env.NODE_ENV === 'production');
function rebundle(bundler) {
var stream = bundler.bundle().
on('error', gutil.log.bind(gutil, 'Browserify Error')).
pipe(source('../public/build.js'));
if (production) {
stream = stream.pipe(buffer()).pipe(uglify());
}
stream.pipe(gulp.dest('.'));
}
gulp.task('compile-build', function () {
var bundler = browserify('./event_handler.jsx', { debug: !production });
bundler.transform(reactify);
return rebundle(bundler);
});
gulp.task('compile-concourse', function () {
var stream = gulp.src('./concourse/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(concat('concourse.js'))
if (production) {
stream = stream.pipe(buffer()).pipe(uglify());
}
return stream.pipe(gulp.dest('../public/'));
});
// jasmine stuff
var externalFiles = ["../public/jquery-2.1.1.min.js", "spec/helpers/**/*.js"]
var jsSourceFiles = ["concourse/*.js", "spec/**/*_spec.js"]
var hintSpecFiles = function() {
gulp.src('spec/**/*_spec.js')
}
gulp.task('jasmine-cli', function(cb) {
return gulp.src(jsSourceFiles)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.on('error', function(){
process.exit(1);
})
.pipe(addsrc(externalFiles))
.pipe(jasmineBrowser.specRunner({console: true}))
.pipe(jasmineBrowser.phantomjs());
});
gulp.task('jasmine', function() {
return gulp.src(jsSourceFiles)
.pipe(addsrc(externalFiles))
.pipe(jasmineBrowser.specRunner())
.pipe(jasmineBrowser.server());
});
gulp.task('watch', function () {
var bundler = watchify(browserify('./event_handler.jsx'), { debug: !production });
bundler.transform(reactify);
bundler.on('update', function() { rebundle(bundler); });
return rebundle(bundler);
});
gulp.task('default', ['compile-build', 'compile-concourse']);
| JavaScript | 0 | @@ -1675,48 +1675,37 @@
r',
-function()%7B%0A process.exit(1);%0A %7D
+process.exit.bind(process, 1)
)%0A
@@ -1826,16 +1826,64 @@
tomjs())
+%0A .on('error', process.exit.bind(process, 1))
;%0A%7D);%0A%0Ag
|
67097ed2c3c1bb9122ab8ba9e33ee0af1722ce51 | Update services.js | wordmapper/client/src/js/services.js | wordmapper/client/src/js/services.js | module.exports = {
ImportExportService: require('./services/import_export.js'),
Persistence: require('./services/persistence.js'),
StorageLocal: require('./services/storage_local.js'),
StorageRemote: require('./services/storage_remote.js')
};
| JavaScript | 0.000001 | @@ -124,25 +124,26 @@
tence.js'),%0A
-%09
+
StorageLocal
@@ -188,9 +188,10 @@
'),%0A
-%09
+
Stor
|
13c5ee09b524c38fc70e92b11d188c8d26864a83 | expand conditional | lib/appBuilder.js | lib/appBuilder.js | /*
* Copyright (c) 2015 Limerun Project Contributors
* Portions Copyright (c) 2015 Internet of Protocols Assocation (IOPA)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Module dependencies.
*/
var Middleware = require('./middleware.js');
var Mount = require('./iopa/iopaMount.js');
var Images = require('./util/images.js');
var constants = require('./util/constants.js');
var guidFactory = require('./util/guid.js');
var expandContext = require('./iopa/iopaExpand.js');
var Shallow = require('./util/shallow.js');
var Promise = require('bluebird');
function AppBuilder(properties) {
this.properties = Shallow.merge(properties, {
"server.AppId" : guidFactory.guid(),
"server.Capabilities" : {},
"server.Logger" : console,
"app.DefaultApp": DefaultApp,
"app.DefaultMiddleware": [RespondMiddleware]
});
this.log = this.properties["server.Logger"];
this.middleware = [];
}
exports = module.exports = AppBuilder;
var app = AppBuilder.prototype;
app.use = function(mw){
this.middleware.push(Middleware(this, mw));
return this;
};
app.mount = function (location, appletFunc) {
var appFunc, appBuilderChild, mounted;
appBuilderChild = new AppBuilder();
appletFunc(appBuilderChild);
appFunc = appBuilderChild.build();
mounted = Mount(location, appFunc);
this.middleware.push(mounted);
return this;
};
/***
* AppBuilder Function to Compile/Build all Middleware in the Pipeline into single IOPA AppFunc
*
*@return {function(context)} IOPA application
* @public
*/
app.build = function(){
var middleware = this.properties[constants.app.DefaultMiddleware].concat(this.middleware).concat(this.properties[constants.app.DefaultApp]);
var app = this;
var pipeline = function appbuilder_pipeline(context){
try {
var i, prev, curr;
i = middleware.length;
prev = function (){return Promise.resolve(null);};
while (i--) {
curr = middleware[i];
prev = curr.bind(app, context, prev);
}
return prev()
}
catch (err)
{
DefaultError(context,err);
context = null;
return Promise.resolve(null);
}
};
pipeline.log = this.log;
return pipeline;
}
// DEFAULT HANDLERS: RESPOND, DEFAULT APP, ERROR HELPER
function RespondMiddleware(context, next){
expandContext.expandContext.call(this, context);
return next().then(
function (ret){
expandContext.shrinkContext(context);
return ret;
},
function (err){
DefaultError(context,err);
expandContext.shrinkContext(context);
return Promise.resolve(null);
});
}
function DefaultApp(context, next){
if (context["server.Error"])
{
return Promise.reject(context["server.Error"]);
}
else
{
return Promise.resolve(null);
}
}
function DefaultError(context, err){
if (context["iopa.Protocol"] == "HTTP/1.1")
{
DefaultErrorHttp(context, err);
}
else
{
context.log.error("Server/Middleware Error: " + err);
throw(err);
}
}
function DefaultErrorHttp(context, err){
context.log.error(err);
if (err===404)
{
context.response.writeHead(404, {'Content-Type': 'text/html'});
context.response.write(Images.logo);
context.response.end('<h1>404 Not Found</h1><p>Could not find resource:</p><xmb>' + this.request.path + '</xmb>');
}
else
{
context.response.writeHead(500, {'Content-Type': 'text/html'});
context.response.write(Images.logo);
context.response.end('<h1>500 Server Error</h1><p>An error has occurred:</p><xmb>' + err + '</xmb> ');
}
}
| JavaScript | 0.999426 | @@ -1362,16 +1362,54 @@
dleware%5D
+,%0A %22server.ExpandContext%22: true,
%0A %7D);
@@ -1495,16 +1495,81 @@
e = %5B%5D;%0A
+ %0A this.expand = this.properties%5B%22server.ExpandContext%22%5D ;%0A
%7D%0A%0Aexpor
@@ -2457,22 +2457,8 @@
t)%7B%0A
- try %7B%0A
@@ -2745,166 +2745,8 @@
)%0A
- %7D%0A catch (err)%0A %7B%0A DefaultError(context,err);%0A context = null;%0A return Promise.resolve(null);%0A %7D %0A
@@ -2903,24 +2903,48 @@
next)%7B%0A %0A
+ if (this.expand)%0A
expandCo
@@ -3050,24 +3050,67 @@
tion (ret)%7B%0A
+ if (this.expand)%0A
@@ -3304,24 +3304,67 @@
ntext,err);%0A
+ if (this.expand)%0A
@@ -3860,30 +3860,24 @@
con
-text.log.error
+sole.log
(%22Server
|
02a4b0c5685a222d14d51d81d5f41b50632b7d43 | Update parameters passed to CloudAppX.makepri | lib/appPackage.js | lib/appPackage.js | var fs = require('fs'),
os = require('os'),
path = require('path'),
url = require('url');
var archiver = require('archiver'),
cloudappx = require('cloudappx-server'),
Q = require('q'),
request = require('request');
var manifoldjsLib = require('manifoldjs-lib');
var CustomError = manifoldjsLib.CustomError,
log = manifoldjsLib.log;
var serviceEndpoint = 'http://cloudappx.azurewebsites.net';
// Quick sanity check to ensure that the placeholder parameters in the manifest
// have been replaced by the user with their publisher details before generating
// a package.
function validateManifestPublisherDetails(appFolder, shouldSign, callback) {
var manifestPath = path.join(appFolder, 'appxmanifest.xml');
return Q.nfcall(fs.readFile, manifestPath, 'utf8').then(function (data) {
if (shouldSign) {
return;
}
var packageIdentityPlaceholders = /<Identity.*(Name\s*=\s*"INSERT-YOUR-PACKAGE-IDENTITY-NAME-HERE"|Publisher\s*=\s*"CN=INSERT-YOUR-PACKAGE-IDENTITY-PUBLISHER-HERE")/g;
var publisherDisplayNamePlaceholder = /<PublisherDisplayName>\s*INSERT-YOUR-PACKAGE-PROPERTIES-PUBLISHERDISPLAYNAME-HERE\s*<\/PublisherDisplayName>/g;
if (packageIdentityPlaceholders.test(data) || publisherDisplayNamePlaceholder.test(data)) {
return Q.reject(new Error('The application manifest is incomplete. Register the app in the Windows Store to obtain the Package/Identity/Name, \nPackage/Identity/Publisher, and Package/Properties/PublisherDisplayName details. \nThen, use this information to update the corresponding placeholders in the appxmanifest.xml file before \ncreating the App Store package.'));
}
})
.catch(function (err) {
return Q.reject(new CustomError('The specified path does not contain a valid app manifest file.', err));
})
.nodeify(callback);
}
function invokeCloudAppX(name, appFolder, outputFilePath, operation, callback) {
var deferred = Q.defer();
var archive = archiver('zip');
var zipFile = path.join(os.tmpdir(), name + '.zip');
var output = fs.createWriteStream(zipFile);
var endPointValue = '/v2/' + operation;
archive.on('error', function (err) {
deferred.reject(err);
});
archive.pipe(output);
archive.directory(appFolder, name);
archive.finalize();
var operationUrl = url.resolve(process.env.CLOUDAPPX_SERVICE_ENDPOINT || serviceEndpoint, endPointValue);
output.on('close', function () {
var options = {
method: 'POST',
url: operationUrl,
encoding: 'binary'
};
log.debug('Invoking the CloudAppX service...');
var req = request.post(options, function (err, resp, body) {
if (err) {
return deferred.reject(err);
}
if (resp.statusCode !== 200) {
return deferred.reject(new Error('Failed to create the package. The CloudAppX service returned an error - ' + resp.statusMessage + ' (' + resp.statusCode + '): ' + body));
}
fs.writeFile(outputFilePath, body, { 'encoding': 'binary' }, function (err) {
if (err) {
return deferred.reject(err);
}
fs.unlink(zipFile, function (err) {
if (err) {
return deferred.reject(err);
}
return deferred.resolve();
});
});
});
req.form().append('xml', fs.createReadStream(zipFile));
});
return deferred.promise.nodeify(callback);
}
var makeAppx = function (appFolder, outputPath, shouldSign, callback) {
var name = 'windows';
var appxFile = path.join(outputPath, name + '.appx');
return validateManifestPublisherDetails(appFolder, shouldSign).then(function () {
// call sign endpoint or traditional
if (shouldSign === true) {
log.debug('Invoking the CloudAppX service to generate a signed APPX package');
return invokeCloudAppX(name, appFolder, appxFile, 'buildsigned');
}
else {
return Q({ 'dir': appFolder, 'name': 'resources', 'out': appFolder })
.then(cloudappx.makePri)
.thenResolve({ 'dir': appFolder, 'name': name, 'out': outputPath, 'shouldSign': shouldSign })
.then(cloudappx.makeAppx)
.catch(function (err) {
log.debug('Unable to create the package locally. Invoking the CloudAppX service instead...');
return invokeCloudAppX(name, appFolder, appxFile, 'build');
});
}
})
.nodeify(callback);
};
var makePri = function (appFolder, outputPath, callback) {
var name = 'resources';
return Q({ 'dir': appFolder, 'name': name, 'out': outputPath })
.then(cloudappx.makePri)
.catch(function () {
log.debug('Unable to index resources locally. Invoking the CloudAppX service instead...');
var priFile = path.join(outputPath, name + '.pri');
return invokeCloudAppX(name, appFolder, priFile, 'makepri');
})
.nodeify(callback);
};
var makeWeb = function (appFolder, outputPath, callback) {
var deferred = Q.defer();
var archive = archiver('zip');
var packagePath = path.join(outputPath, 'windows.web');
var output = fs.createWriteStream(packagePath);
var manifestPath = path.resolve(appFolder, '../manifest.json');
archive.on('error', function (err) {
deferred.reject(err);
});
archive.pipe(output);
output.on('close', function() {
deferred.resolve();
});
archive.glob('**/*.*', { cwd: appFolder, ignore: 'appxmanifest.xml' });
archive.file(manifestPath, { name: 'manifest.json' });
archive.finalize();
return deferred.promise.nodeify(callback);
};
module.exports = {
makeAppx: makeAppx,
makePri: makePri,
makeWeb: makeWeb
}; | JavaScript | 0.000001 | @@ -2160,17 +2160,17 @@
ue = '/v
-2
+3
/' + ope
@@ -4029,102 +4029,54 @@
rn Q
-(%7B 'dir': appFolder, 'name': 'resources', 'out': appFolder %7D)%0D%0A .then(cloudappx.makePri
+.fcall(cloudappx.makePri, appFolder, appFolder
)%0D%0A
@@ -4229,35 +4229,32 @@
catch(function (
-err
) %7B%0D%0A l
@@ -4574,107 +4574,56 @@
rn Q
-(%7B 'dir': appFolder, 'name': name, 'out': outputPath %7D)%0D%0A .then(cloudappx.makePri)%0D%0A
+.fcall(cloudappx.makePri, appFolder, outputPath)
.cat
@@ -4636,38 +4636,32 @@
ction () %7B%0D%0A
-
log.
debug('Unabl
@@ -4640,37 +4640,36 @@
n () %7B%0D%0A log.
-debug
+info
('Unable to inde
@@ -4731,30 +4731,24 @@
tead...');%0D%0A
-
var priF
@@ -4788,30 +4788,24 @@
+ '.pri');%0D%0A
-
return i
@@ -4864,24 +4864,12 @@
%0D%0A
- %7D)%0D%0A
+%7D)%0D%0A
.n
@@ -5329,24 +5329,26 @@
nction() %7B%0D%0A
+
deferred
@@ -5354,25 +5354,24 @@
d.resolve();
-
%0D%0A %7D);%0D%0A%0D%0A
|
abe7faa289b1247861fcc22b46ee085edf6b4a45 | use valid identifier. | src/Control/Monad/Eff/JQuery.js | src/Control/Monad/Eff/JQuery.js | /* global exports */
"use strict";
// module Control.Monad.Eff.JQuery
exports.ready = function(func) {
return function() {
jQuery(document).ready(func);
};
};
exports.select = function(selector) {
return function() {
return jQuery(selector);
};
};
exports.find = function(selector) {
return function(ob) {
return function() {
return ob.find(selector);
};
};
};
exports.parent = function(ob) {
return function() {
return ob.parent();
};
};
exports.closest = function(selector) {
return function(ob) {
return function() {
return ob.closest(selector);
};
};
};
exports.create = function(html) {
return function() {
return jQuery(html);
};
};
exports.setAttr = function(attr) {
return function(val) {
return function(ob) {
return function() {
return ob.attr(attr, val);
};
};
};
};
exports.attr = function(attrs) {
return function(ob) {
return function() {
return ob.attr(attrs);
};
};
};
exports.css = function(props) {
return function(ob) {
return function() {
return ob.css(props);
};
};
};
exports.hasClass = function(cls) {
return function(ob) {
return function() {
return ob.hasClass(cls);
};
};
};
exports.toggleClass = function(cls) {
return function(ob) {
return function() {
return ob.toggleClass(cls);
};
};
};
exports.setClass = function(cls) {
return function(flag) {
return function(ob) {
return function() {
return ob.toggleClass(cls, flag);
};
};
};
};
exports.setProp = function(p) {
return function(val) {
return function(ob) {
return function() {
return ob.prop(p, val);
};
};
};
};
exports.getProp = function(p) {
return function(ob) {
return function() {
return ob.prop(p);
};
};
};
exports.append = function(ob1) {
return function(ob) {
return function() {
return ob.append(ob1);
};
};
};
exports.appendText = function(s) {
return function(ob) {
return function() {
return ob.append(s);
};
};
};
exports.body = function() {
return jQuery(document.body);
};
exports.remove = function(ob) {
return function() {
return ob.remove();
};
};
exports.clear = function(ob) {
return function() {
return ob.empty();
};
};
exports.before = function(ob) {
return function(ob1) {
return function() {
return ob1.before(ob);
};
};
};
exports.getText = function(ob) {
return function() {
return ob.text();
};
};
exports.setText = function(text) {
return function(ob) {
return function() {
return ob.text(text);
};
};
};
exports.getValue = function(ob) {
return function() {
return ob.val();
};
};
exports.setValue = function(val) {
return function(ob) {
return function() {
return ob.val(val);
};
};
};
exports.toggle = function(ob) {
return function() {
return ob.toggle();
};
};
exports.setVisible = function(flag) {
return function(ob) {
return function() {
return ob.toggle(flag);
};
};
};
exports.on = function(evt) {
return function(act) {
return function(ob) {
return function() {
return ob.on(evt, function(e) {
act(e)(jQuery(this))();
});
};
};
};
};
exports.on$prime = function(evt) {
return function(sel) {
return function(act) {
return function(ob) {
return function() {
return ob.on(evt, sel, function(e) {
act(e)(jQuery(this))();
});
};
};
};
};
};
exports.preventDefault = function(e) {
return function() {
e.preventDefault();
};
};
exports.stopPropagation = function(e) {
return function() {
e.stopPropagation();
};
};
exports.stopImmediatePropagation = function(e) {
return function() {
e.stopImmediatePropagation();
};
};
| JavaScript | 0.000114 | @@ -3802,17 +3802,15 @@
orts
-.on$prime
+%5B%22on'%22%5D
= f
|
9a3b178fc453401c8664c26eb3de89feba6489e9 | Fix the cdn path of the images for Amazon s3 | grunt/cdn.js | grunt/cdn.js | // CDN will replace local paths with your CDN path
module.exports = {
cloudfiles: {
options: {
cdn: '<%= secrets.cloudfiles.uri %>', // See README for secrets.json or replace this with your cdn uri
flatten: true,
supportedTypes: 'html'
},
cwd: './<%= paths.dist %>',
dest: './<%= paths.dist %>',
src: ['*.html']
},
aws_s3: {
options: {
cdn: '<%= secrets.s3.bucketuri %>/<%= secrets.s3.bucketname %>/<%= secrets.s3.bucketdir %>', // See README for secrets.json or replace this with your Amazon S3 bucket uri
flatten: true,
supportedTypes: 'html'
},
cwd: './<%= paths.dist %>',
dest: './<%= paths.dist %>',
src: ['*.html']
}
};
| JavaScript | 0.98465 | @@ -427,37 +427,8 @@
/%3C%25=
- secrets.s3.bucketname %25%3E/%3C%25=
sec
|
c44796bdfc47dd51859233eb934a7befe61fb5ba | fix grunt watch paths | gruntfile.js | gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
appName: 'SampleApp',
appDir: 'app',
cssDir: '<%= appDir %>/css',
sassDir: '<%= appDir %>/scss',
appScss: '<%= sassDir %>/styles.scss',
appCss: '<%= cssDir %>/styles.css',
sass: {
dev: {
options: {
sourcemap: true
},
files: {
'<%= appCss %>': '<%= appScss %>'
}
},
dist: {
files: {
'<%= appCss %>': '<%= appScss %>'
}
}
},
jshint: {
files: [
'<%= appDir %>/**/*.js',
'!<%= appDir %>/bower_components/**',
'specs/**/*.js',
'tests/**/*.js',
'e2e-tests/**/*.js',
'!.*/**'
],
options: {
reporter: require('jshint-stylish'),
laxbreak: true,
strict: true,
globals: {
jQuery: true
}
}
},
watch: {
sass: {
files: ['<%= sassDir %>/**/*.scss', '<%= appDir %>/parts/**/*.scss'],
tasks: ['sass:dev'],
options: {
spawn: false,
livereload: true
}
},
jshint: {
files: ['<%= appDir %>/*.js', '<%= appDir %>/parts/**/*.js'],
tasks: ['jshint']
},
other: {
files: ['<%= appDir %>/**/*.html', '<%= appDir %>/**/*.js'],
options: {
livereload: true
}
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['jshint', 'sass:dist']);
}; | JavaScript | 0.000001 | @@ -1276,28 +1276,27 @@
iles: %5B'%3C%25=
-sass
+app
Dir %25%3E/**/*.
@@ -1299,24 +1299,25 @@
*/*.scss', '
+!
%3C%25= appDir %25
@@ -1322,23 +1322,27 @@
%25%3E/
-parts/**/*.scss
+bower_components/**
'%5D,%0A
@@ -1575,15 +1575,19 @@
%25%3E/*
+*/*
.js', '
+!
%3C%25=
@@ -1600,21 +1600,27 @@
%25%3E/
-parts/**/*.js
+bower_components/**
'%5D,%0A
|
4c6512b197fef9e39b6a936fb6fe83be4724e735 | Correct name for options | gruntfile.js | gruntfile.js | /* globals module:false, require:false */
module.exports = function (grunt) {
'use strict';
// load all grunt tasks matching the 'grunt-*' pattern
require('load-grunt-tasks')(grunt);
grunt.initConfig({
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
},
auto: {
configFile: 'karma.conf.js',
autoWatch: true
}
},
uglify: {
options: {
mangle: true
},
target: {
files: {
'dist/angular-base-class.min.js': 'src/angular-base-class.js'
}
}
},
bump: {
scripts: {
files: ['package.json', 'bower.json'],
commitFiles: ['-a'],
push: false,
pushTo: 'origin'
}
}
});
// Load all modules from package.json which name starts with 'grunt-'. Very helpful to avoid having to loadNpmTasks for every grunt module
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.registerTask('test', ['karma:unit']);
};
| JavaScript | 0.995712 | @@ -754,14 +754,14 @@
-script
+option
s: %7B
@@ -884,42 +884,8 @@
alse
-,%0A pushTo: 'origin'
%0A
|
87a74307b673648c2d5869847e51fa41bf72f072 | update gruntfile.js to let jshint adhere to .jshintrc | gruntfile.js | gruntfile.js | module.exports = function(grunt) {
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
jade: {
files: ['app/views/**'],
options: {
livereload: true,
},
},
js: {
files: ['public/js/**', 'app/**/*.js'],
tasks: ['jshint'],
options: {
livereload: true,
},
},
html: {
files: ['public/views/**'],
options: {
livereload: true,
},
},
css: {
files: ['public/css/**'],
options: {
livereload: true
}
}
},
jshint: {
all: ['gruntfile.js', 'public/js/**/*.js', 'test/mocha/**/*.js', 'test/karma/**/*.js', 'app/**/*.js']
},
nodemon: {
dev: {
options: {
file: 'server.js',
args: [],
ignoredFiles: ['README.md', 'node_modules/**', '.DS_Store'],
watchedExtensions: ['js'],
watchedFolders: ['app', 'config'],
debug: true,
delayTime: 1,
env: {
PORT: 3000
},
cwd: __dirname
}
}
},
concurrent: {
tasks: ['nodemon', 'watch'],
options: {
logConcurrentOutput: true
}
},
mochaTest: {
options: {
reporter: 'spec'
},
src: ['test/mocha/**/*.js']
},
env: {
test: {
NODE_ENV: 'test'
}
},
karma: {
unit: {
configFile: 'test/karma/karma.conf.js'
}
}
});
//Load NPM tasks
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-env');
//Making grunt default to force in order not to break the project.
grunt.option('force', true);
//Default task(s).
grunt.registerTask('default', ['jshint', 'concurrent']);
//Test task.
grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
}; | JavaScript | 0 | @@ -880,16 +880,39 @@
all:
+ %7B%0A src:
%5B'grunt
@@ -992,32 +992,127 @@
, 'app/**/*.js'%5D
+,%0A options: %7B%0A jshintrc: true%0A %7D%0A %7D
%0A %7D,%0A
@@ -2773,8 +2773,9 @@
t'%5D);%0A%7D;
+%0A
|
61a446701e2b193dfb29631b0290e28010afefc9 | Remove execCommand | lib/connection.js | lib/connection.js | var Bluebird = require('bluebird');
var Client = Bluebird.promisifyAll(require('ssh2').Client);
var errors = require('./errors');
function Connection(options) {
this.host = options.host;
this.username = options.username;
this.debug = options.debug;
this.options = options;
this._connection = new Client();
this._log('new connection');
}
Connection.prototype = {
connect: function connect() {
_this = this;
return new Bluebird(function connectPromise(resolve) {
_this._connection.on('ready', function() {
_this._log('ready');
resolve(_this);
}).connect(_this.options);
});
},
exec: function exec(commands) {
var _this = this;
var stdout = '';
var stderr = '';
var code = 0;
return Bluebird.each(commands, function(command) {
return _this._connection.execAsync(command)
.then(function(stream) {
stream.on('data', function onStdout(data) {
stdout += data;
});
stream.stderr.on('data', function onStderr(data) {
stdout += data;
});
return new Bluebird(function(resolve) {
stream.on('close', function onClose(code, signal) {
_this._log('closed "' + command + '" with exit code ' + code);
code += code;
resolve(_this._connection);
});
});
});
}).then(function() {
_this._log('closing connection');
_this._connection.end();
return [code, stdout, stderr];
});
},
execCommand: function execCommand(command) {
var _this = this;
var stdout = '';
var stderr = '';
this._log('Exec command "' + command + '"');
return this._connection
.execAsync(command)
.then(function (stream) {
return new Bluebird(function (resolve) {
stream.on('close', function onClose(code, signal) {
_this._log('closed "' + command + '" with exit code ' + code);
resolve([code, stdout, stderr]);
});
stream.on('data', function onStdout(data) {
stdout += data;
});
stream.stderr.on('data', function onStderr(data) {
stdout += data;
});
});
})
.then(function (result) {
_this._log('closing connection');
_this._connection.end();
return result;
});
},
toString: function toString() {
return this.username + '@' + this.host;
},
_log: function _log(message) {
if (this.debug) console.log(this + ': ' + message);
}
};
module.exports = Connection;
| JavaScript | 0.000022 | @@ -1538,867 +1538,8 @@
%7D,%0A%0A
- execCommand: function execCommand(command) %7B%0A var _this = this;%0A var stdout = '';%0A var stderr = '';%0A this._log('Exec command %22' + command + '%22');%0A return this._connection%0A .execAsync(command)%0A .then(function (stream) %7B%0A return new Bluebird(function (resolve) %7B%0A stream.on('close', function onClose(code, signal) %7B%0A _this._log('closed %22' + command + '%22 with exit code ' + code);%0A resolve(%5Bcode, stdout, stderr%5D);%0A %7D);%0A%0A stream.on('data', function onStdout(data) %7B%0A stdout += data;%0A %7D);%0A%0A stream.stderr.on('data', function onStderr(data) %7B%0A stdout += data;%0A %7D);%0A %7D);%0A %7D)%0A .then(function (result) %7B%0A _this._log('closing connection');%0A _this._connection.end();%0A return result;%0A %7D);%0A %7D,%0A%0A
to
|
7470d49b74e1797987d20035f002a3ec91b47c97 | Add default value for map center | addon/components/flexberry-map.js | addon/components/flexberry-map.js | import Ember from 'ember';
import layout from '../templates/components/flexberry-map';
import ContainerMixin from 'ember-flexberry-gis/mixins/layercontainer';
export default Ember.Component.extend(ContainerMixin, {
layout,
model: undefined,
center: Ember.computed('model.lat', 'model.lng', function () {
return L.latLng(this.get('model.lat'), this.get('model.lng'));
}),
zoom: Ember.computed('model.zoom', function() {
return this.get('model.zoom');
}),
leafletMap: undefined,
didInsertElement() {
this._super(...arguments);
let map = L.map(this.element, this.get('options'));
map.setView(this.get('center'), this.get('zoom'));
this.set('leafletMap', map);
this.buildLayers(map);
this.setOrder({ index: 0 });
},
willDestoryElement() {
var leafletMap = this.get('leafletMap');
if (leafletMap) {
leafletMap.remove();
this.set('leafletMap', null);
}
}
});
| JavaScript | 0 | @@ -347,16 +347,21 @@
el.lat')
+ %7C%7C 0
, this.g
@@ -375,16 +375,21 @@
el.lng')
+ %7C%7C 0
);%0A %7D),
|
8ec960ac98bc0c9193b592a88ed01c3d3d995a06 | Support watching sass/scss files with grunt | gruntfile.js | gruntfile.js | 'use strict';
module.exports = function(grunt) {
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
assets: grunt.file.readJSON('config/assets.json'),
watch: {
js: {
files: ['gruntfile.js', 'server.js', 'app/**/*.js', 'public/js/**', 'test/**/*.js'],
tasks: ['jshint'],
options: {
livereload: true
}
},
html: {
files: ['public/views/**', 'app/views/**'],
options: {
livereload: true
}
},
css: {
files: ['public/css/**'],
tasks: ['csslint'],
options: {
livereload: true
}
}
},
jshint: {
all: {
src: ['gruntfile.js', 'server.js', 'app/**/*.js', 'public/js/**', 'test/**/*.js', '!test/coverage/**/*.js'],
options: {
jshintrc: true
}
}
},
uglify: {
production: {
files: '<%= assets.js %>'
}
},
csslint: {
options: {
csslintrc: '.csslintrc'
},
all: {
src: ['public/css/**/*.css']
}
},
cssmin: {
combine: {
files: '<%= assets.css %>'
}
},
nodemon: {
dev: {
script: 'server.js',
options: {
args: [],
ignore: ['public/**'],
ext: 'js,html',
nodeArgs: ['--debug'],
delayTime: 1,
env: {
PORT: 3000
},
cwd: __dirname
}
}
},
concurrent: {
tasks: ['nodemon', 'watch'],
options: {
logConcurrentOutput: true
}
},
mochaTest: {
options: {
reporter: 'spec',
require: 'server.js'
},
src: ['test/mocha/**/*.js']
},
env: {
test: {
NODE_ENV: 'test'
}
},
karma: {
unit: {
configFile: 'test/karma/karma.conf.js'
}
},
sass: {
dist: {
files: {
'public/stylesheets/style.css' : 'assets/sass/style.scss'
}
}
}
});
//Load NPM tasks
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-env');
grunt.loadNpmTasks('grunt-sass');
//Making grunt default to force in order not to break the project.
grunt.option('force', true);
//Default task(s).
if (process.env.NODE_ENV === 'production') {
grunt.registerTask('default', ['jshint', 'csslint', 'cssmin', 'uglify', 'concurrent']);
} else {
grunt.registerTask('default', ['jshint', 'csslint', 'concurrent', 'sass']);
}
//Test task.
grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
};
| JavaScript | 0 | @@ -820,32 +820,232 @@
%7D%0A
+ %7D,%0A sass: %7B%0A files: %5B'assets/sass/**/*.scss'%5D,%0A tasks: %5B'sass'%5D,%0A options: %7B%0A livereload: true%0A %7D%0A
%7D%0A
|
debe3ba58faf44a9b6eefb3d0d2131be51d9ecaa | Add assertion comment, https://github.com/phetsims/phet-io/issues/1141 | js/BarrierRectangle.js | js/BarrierRectangle.js | // Copyright 2017, University of Colorado Boulder
/**
* Semi-transparent black barrier used to block input events when a dialog (or other popup) is present, and fade out
* the background.
*
* @author - Michael Kauzmann (PhET Interactive Simulations)
*/
define( function( require ) {
'use strict';
// modules
var inherit = require( 'PHET_CORE/inherit' );
var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
var Emitter = require( 'AXON/Emitter' );
var Plane = require( 'SCENERY/nodes/Plane' );
var ButtonListener = require( 'SCENERY/input/ButtonListener' );
var Tandem = require( 'TANDEM/Tandem' );
var TBarrierRectangle = require( 'SCENERY_PHET/TBarrierRectangle' );
/**
* @param {ObservableArray} modalNodeStack - see usage in Sim.js
* @param {Object} [options]
* @constructor
*/
function BarrierRectangle( modalNodeStack, options ) {
var self = this;
options = _.extend( {
tandem: Tandem.tandemRequired(),
phetioType: TBarrierRectangle
}, options );
Plane.call( this );
// @private
this.startedCallbacksForFiredEmitter = new Emitter();
this.endedCallbacksForFiredEmitter = new Emitter();
modalNodeStack.lengthProperty.link( function( numBarriers ) {
self.visible = numBarriers > 0;
} );
this.addInputListener( new ButtonListener( {
fire: function( event ) {
self.startedCallbacksForFiredEmitter.emit();
assert && assert( modalNodeStack.length > 0 );
modalNodeStack.get( modalNodeStack.length - 1 ).hide();
self.endedCallbacksForFiredEmitter.emit();
}
} ) );
// @private
this.disposeBarrierRectangle = function() {
modalNodeStack.lengthProperty.unlink();
};
this.mutate( options );
}
sceneryPhet.register( 'BarrierRectangle', BarrierRectangle );
return inherit( Plane, BarrierRectangle, {
// @public
dispose: function() {
this.disposeBarrierRectangle();
Plane.prototype.dispose.call( this );
}
} );
} ); | JavaScript | 0 | @@ -1473,16 +1473,62 @@
ngth %3E 0
+, 'There must be a Node in the stack to hide.'
);%0A
|
ba5a627fb5cf09ebfbce8143a5a77bf2a3d57c87 | Add jshint to the "release" task. | gruntfile.js | gruntfile.js | // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
(function () {
"use strict";
module.exports = function (grunt) {
var config = require("./config.js");
// Make sure that Grunt doesn't remove BOM from our utf8 files
// on read
grunt.file.preserveBOM = true;
// Helper function to load the config file
function loadConfig(path) {
var glob = require("glob");
var object = {};
var key;
glob.sync("*", { cwd: path }).forEach(function (option) {
key = option.replace(/\.js$/, "");
object[key] = require(path + option);
});
return object;
}
// Load task options
var gruntConfig = loadConfig("./tasks/options/");
// Package data
gruntConfig.pkg = grunt.file.readJSON("package.json");
// Project config
grunt.initConfig(gruntConfig);
// Load all grunt-tasks in package.json
require("load-grunt-tasks")(grunt);
// Register external tasks
grunt.loadTasks("tasks/");
// Task alias's
grunt.registerTask("default", ["clean", "less", "concat", "copy", "replace"]);
grunt.registerTask("release", ["default", "uglify"]);
grunt.registerTask("css", ["less"]);
grunt.registerTask("base", ["clean:base", "concat:baseDesktop", "concat:basePhone", "concat:baseStringsDesktop", "concat:baseStringsPhone", "replace"]);
grunt.registerTask("ui", ["clean:ui", "concat:uiDesktop", "concat:uiPhone", "concat:uiStringsDesktop", "concat:uiStringsPhone", "replace", "less"]);
grunt.registerTask("lint", ["jshint"]);
};
})();
| JavaScript | 0.000002 | @@ -1390,22 +1390,29 @@
ase%22, %5B%22
-defaul
+jshint%22, %22tes
t%22, %22ugl
@@ -1826,24 +1826,74 @@
%22jshint%22%5D);%0A
+ grunt.registerTask(%22minify%22, %5B%22uglify%22%5D);%0A
%7D;%0A%7D)();
|
6b5161b733c55403a8da393912732a0a5d97cefb | remove extra hr in about | js/components/about.js | js/components/about.js | // Create the features component.
var features = {
// Create the view-model.
vm: {
init: function() {
console.log ("about features vm init");
}
},
// Create the controller.
controller: function() {
features.vm.init ();
},
// Create the view.
view: function() {
// Kickstarter video
return m("section", {class: "about-features"}, [
// Overview
m("div", [
m("div", {class: "about-features-overview hero"}, [
m("div", [
m("div", {class: "vertical-center col span_4_of_12"}, [
m("div", [
m("h3", "The Mobile RPG You've Been Waiting For"),
m("p", "Adventure Guild is a social Roguelike RPG built for mobile devices. "
+ "Party up with your friends to explore the farthest reaches of the world. "
+ "Tackle tactically challenging turn-based combat that forces you to work as a team."),
m("img", {src: "imgs/features/back-to-back.png", alt: "Party Up"})
])
]),
m("div", {class: "vertical-center col span_8_of_12"}, [
m("div", {class: "kickstarter-video-container"}, [
m("iframe", {src: "https://www.kickstarter.com/projects/yesandgames/adventure-guild/widget/video.html", frameborder: "0", scrolling: "no", allowfullscreen: true})
])
])
])
])
]),
m("hr", {class: "hr-gradient"}),
// RPG features
m("div", [
m("div", {class: "about-features-rpg hero"}, [
m("div", [
m("div", {class: "vertical-center col span_4_of_12"}, [
m("div", [
m("h3", "A Full-Fledged Multiplayer Tactics RPG"),
m("p", "Adventure Guild is one of the most full-featured multiplayer RPGs ever developed for mobile platforms. " +
"Gone are the expectations that mobile games lack depth and complexity. " +
"Adventure Guild strikes the perfect balance between the substantial gameplay of a real RPG and the simplicity of design mobile games demand."),
])
]),
m("div", {class: "vertical-center col span_8_of_12"}, [
m(".embed-container", {class: "youtube-video-container"},
m("iframe", {src:"https://www.youtube.com/embed/ySlAPkteu5k", frameborder: "0", allowfullscreen: "yes"})
),
])
])
])
]),
m("hr", {class: "hr-gradient"}),
// Character customization features
m("div", [
m("div", {class: "about-features-customization hero"}, [
m("div", [
m("div", {class: "vertical-center col span_4_of_12"}, [
m("div", [
m("h3", "Completely Customize Your Adventurers"),
m("p", "Create, customize, and grow a totally unique party of Adventurers. " +
"Tweak everything visual from their facial features to their hair color to their wearable cosmetics without affecting equipment stats. " +
"Personalize their strategic playstyle by equipping new weapons and armor and choosing the loaded out Skills they take into battle."),
])
]),
m("div", {class: "vertical-center col span_8_of_12"}, m("div", [
m("img", {src: "imgs/screenshots/character.png", alt: "Adventurer"})
]))
])
])
]),
m("hr", {class: "hr-gradient"}),
// Mobility features
m("div", [
m("div", {class: "about-features-mobile hero"}, [
m("div", [
m("div", {class: "vertical-center col span_4_of_12"}, [
m("div", [
m("h3", "Adventure Anytime, Anywhere, with Anyone"),
m("p", "Adventure Guild is built for mobility from the ground up. "
+ "Adventure with your friends from your computer, phone, or tablet from iOS, Android, Windows, or your favorite browser. "
+ "Our unbeatable cross-platform systems will make sure you never miss a beat."),
m("div", {class: "platform-images"}, [
m("img", {src: "imgs/logos/ios.png", alt: "iOS"}),
m("img", {src: "imgs/logos/android.png", alt: "Android"}),
m("img", {src: "imgs/logos/windows.png", alt: "Windows 10 Mobile"})
])
])
]),
m("div", {class: "col span_8_of_12"}, [
])
])
])
]),
m("hr", {class: "hr-gradient"}),
//
]);
}
}
// Create the about component.
var about = {
// Create the view-model.
vm: {
init: function() {
console.log ("about vm init");
}
},
// Create the controller.
controller: function() {
about.vm.init ();
},
// Create the view.
view: function() {
return [
m.component(nav, {page: "about"}),
m.component(features),
m.component(footer)
]
}
}
// Initialize the home component chain.
// m.mount (document.body, about);
| JavaScript | 0 | @@ -4585,58 +4585,8 @@
%5D),
-%0A%0A m(%22hr%22, %7Bclass: %22hr-gradient%22%7D),%0A%0A //
%0A
|
a6c8507f17be33a385d64bddbb85b544f2c953ca | fix appveyor | gruntfile.js | gruntfile.js | 'use strict';
module.exports = function(grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
grunt.initConfig({
// Set this variables for different projects
projectName: 'h-opc',
testProjectPath: 'tests/',
nuspecFile: 'package.nuspec',
// These variables shouldn't be changed, but sometimes it might be necessary
solutionName: '<%= projectName %>.sln',
srcPath: './',
dotNetVersion: '4.5.0',
platform: 'Any CPU',
styleCopRules: 'Settings.StyleCop',
ruleSet: 'rules.ruleset',
pkg: grunt.file.readJSON('package.json'),
assemblyinfo: {
options: {
files: ['<%= srcPath %><%= solutionName %>'],
info: {
version: '<%= pkg.version %>',
fileVersion: '<%= pkg.version %>',
company: 'hylasoft',
copyright: ' ',
product: '<%= projectName %>'
}
}
},
msbuild: {
release: {
src: ['<%= srcPath %><%= solutionName %>'],
options: {
projectConfiguration: 'Release',
platform: '<%= platform %>',
targets: ['Clean', 'Rebuild'],
buildParameters: {
StyleCopEnabled: false
}
}
},
debug: {
src: ['<%= srcPath %><%= solutionName %>'],
options: {
projectConfiguration: 'Debug',
platform: '<%= platform %>',
targets: ['Clean', 'Rebuild'],
buildParameters: {
StyleCopEnabled: true,
StyleCopTreatErrorsAsWarnings: false,
StyleCopOverrideSettingsFile: process.cwd() + '/<%= styleCopRules %>',
RunCodeAnalysis: true,
CodeAnalysisRuleSet: process.cwd() + '/<%= ruleSet %>',
TreatWarningsAsErrors: true
},
}
}
},
mstest: {
debug: {
src: ['<%= srcPath %>/<%= testProjectPath %>/bin/Debug/*.dll'] // Points to test dll
}
},
nugetrestore: {
restore: {
src: '<%= srcPath %><%= solutionName %>',
dest: 'packages/'
options: {
msbuildversion: 12
}
}
},
nugetpack: {
dist: {
src: '<%= nuspecFile %>',
dest: '.',
options: {
version: '<%= pkg.version %>',
basePath: '<%= projectName %>/bin/Release',
includeReferencedProjects: true,
excludeEmptyDirectories: true,
verbose: true
}
}
},
nugetpush: {
src: '*.<%= pkg.version %>.nupkg',
options: {}
},
clean: {
nuget: ['*.nupkg'],
},
shell: {
options: {
stderr: false
},
nunit: {
command: '.\\packages\\NUnit.ConsoleRunner.3.4.1\\tools\\nunit3-console.exe tests\\bin\\Debug\\tests.dll'
}
}
});
grunt.registerTask('default', ['build']);
grunt.registerTask('build', ['nugetrestore','msbuild:debug','msbuild:release']);
grunt.registerTask('test', ['nugetrestore','msbuild:debug', 'shell:nunit']);
grunt.registerTask('release', ['assemblyinfo', 'test']);
grunt.registerTask('publishNuget', ['release', 'msbuild:release', 'nugetpack', 'nugetpush', 'clean:nuget']);
grunt.registerTask('coverage', '', function() {
var exec = require('child_process').execSync;
var result = exec('packages\\OpenCover.4.6.519\\tools\\OpenCover.Console.exe -register:user -target:.\\packages\\NUnit.ConsoleRunner.3.4.1\\tools\\nunit3-console.exe "-targetargs:""tests\\bin\\Debug\\tests.dll"" "--x86 -output:opencoverCoverage.xml', { encoding: 'utf8' });
grunt.log.writeln(result);
});
grunt.registerTask('viewCoverage', '', function() {
var exec = require('child_process').execSync;
var result = exec('packages\\ReportGenerator.2.4.5.0\\tools\\ReportGenerator.exe -reports:"opencoverCoverage.xml" -targetdir:"code_coverage"', { encoding: 'utf8' });
exec('explorer code_coverage\\index.htm', { encoding: 'utf8' });
});
grunt.registerTask('coverageAll', ['coverage', 'viewCoverage']);
};
| JavaScript | 0.000001 | @@ -2171,16 +2171,17 @@
ckages/'
+,
%0A%09%09%09%09opt
|
04f1d82892e9c83789fc6dfcad79d6aa8cb96a3c | update PaggingSize | src/_PaggingSize/PaggingSize.js | src/_PaggingSize/PaggingSize.js | /**
* @file PaggingSize component
* @author liangxiaojun(liangxiaojun@derbysoft.com)
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import DropdownSelect from '../DropdownSelect';
export default class PaggingSize extends Component {
static propTypes = {
className: PropTypes.string,
style: PropTypes.object,
pageSize: PropTypes.number,
pageSizes: PropTypes.array,
onPageSizeChange: PropTypes.func
};
static defaultProps = {
className: '',
style: null,
pageSize: 10,
pageSizes: [5, 10, 15, 20]
};
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.pageSizeChangeHandle = ::this.pageSizeChangeHandle;
}
pageSizeChangeHandle(newPageSize) {
const {pageSize, onPageSizeChange} = this.props;
pageSize != newPageSize && onPageSizeChange && onPageSizeChange(newPageSize);
}
render() {
const {className, style, pageSize, pageSizes} = this.props;
let temp = pageSizes.find(item => item && item.value === pageSize),
value = temp ? temp : pageSize;
return (
<div className={`pagging-size ${className}`}
style={style}>
<label>Show Rows:</label>
<DropdownSelect className="pagging-size-select"
value={value}
data={pageSizes}
autoClose={true}
onChange={this.pageSizeChangeHandle}/>
</div>
);
}
}; | JavaScript | 0 | @@ -215,23 +215,8 @@
';%0A%0A
-export default
clas
@@ -254,367 +254,8 @@
%7B%0A%0A
- static propTypes = %7B%0A%0A className: PropTypes.string,%0A style: PropTypes.object,%0A%0A pageSize: PropTypes.number,%0A pageSizes: PropTypes.array,%0A%0A onPageSizeChange: PropTypes.func%0A%0A %7D;%0A static defaultProps = %7B%0A%0A className: '',%0A style: null,%0A%0A pageSize: 10,%0A pageSizes: %5B5, 10, 15, 20%5D%0A%0A %7D;%0A%0A
@@ -1263,8 +1263,355 @@
%7D%0A%7D;
+%0A%0APaggingSize.propTypes = %7B%0A%0A className: PropTypes.string,%0A style: PropTypes.object,%0A%0A pageSize: PropTypes.number,%0A pageSizes: PropTypes.array,%0A%0A onPageSizeChange: PropTypes.func%0A%0A%7D;%0A%0APaggingSize.defaultProps = %7B%0A%0A className: '',%0A style: null,%0A%0A pageSize: 10,%0A pageSizes: %5B5, 10, 15, 20%5D%0A%0A%7D;%0A%0Aexport default PaggingSize;
|
e92d80ddb38d96e51a32f6803484d4b40b95774a | clean code | data/js/map.ui.js | data/js/map.ui.js | /* Copyright (c) 2012-2016 The TagSpaces Authors. All rights reserved.
* Use of this source code is governed by a AGPL3 license that
* can be found in the LICENSE file. */
/* global define, Handlebars, isNode, isFirefox */
define(function(require, exports, module) {
'use strict';
console.log('Loading map.ui.js ...');
var TSCORE = require('tscore');
var TSPOSTIO = require("tspostioapi");
require('leaflet');
require('leafletlocate');
// TagSpaces Map
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showLocationNotFound);
} else {
TSCORE.showAlertDialog("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
}
function showLocationNotFound(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
TSCORE.showAlertDialog("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
TSCORE.showAlertDialog("Location information is unavailable.");
break;
case error.TIMEOUT:
TSCORE.showAlertDialog("The request to get user location timed out.");
break;
}
}
var MB_ATTR = 'Map data © <a href="http://tagspaces.org">TagSpaces</a>';
var OSM_URL = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var OSM_ATTRIB = '';
var tagSpacesMapOptions = {
//layers: [MB_ATTR],
zoomControl: true,
detectRetina: true
};
var tagSpacesMap = L.map('mapTag', tagSpacesMapOptions);
var tileLayer = L.tileLayer(OSM_URL, {
attribution: MB_ATTR,
id: 'tagSpacesMap'
});
var marker;
//
//var trackMe = L.control.locate({
// position: 'topright',
// strings: {
// title: $.i18n.t('ns.dialogs:yourLocation') //
// }
//}).addTo(tagSpacesMap);
var currentLat, currentLng;
function splitValue(value, index) {
currentLat = value.substring(0, index);
currentLng = value.substring(index);
return parseFloat(currentLat) + "," + parseFloat(currentLng);
}
function showViewLocation() {
tagSpacesMap.setView(new L.LatLng(54.5259614, +15.2551187), 5);
}
function showGeoLocation(coordinate) {
showViewLocation();
tileLayer.addTo(tagSpacesMap);
var regExp = /^([-+]?)([\d]{1,2})(((\.)(\d+)(,)))(\s*)(([-+]?)([\d]{1,3})((\.)(\d+))?)$/g;
var currentCoordinate;
if (coordinate.lastIndexOf('+') !== -1) {
currentCoordinate = splitValue(coordinate, coordinate.lastIndexOf('+'));
} else if (coordinate.lastIndexOf('-') !== -1) {
currentCoordinate = splitValue(coordinate, coordinate.lastIndexOf('-'));
}
var geoTag = TSCORE.selectedTag === 'geoTag';
if (geoTag) {
showViewLocation();
}
if (regExp.exec(currentCoordinate)) {
tagSpacesMap.setView([currentLat, currentLng], 13);
var getCoord = L.latLng(currentLat, currentLng);
addMarker(getCoord);
} else {
showViewLocation();
//tagSpacesMap.setView([54.5259614, +15.2551187], 5);
}
}
function addMarker(currentCoord) {
//var getLatLng = L.latLng(currentLat, currentLng);
// Add marker to map at click location; add popup window
if (typeof marker === 'undefined') {
if (currentCoord.latlng) {
marker = new L.marker(currentCoord.latlng, {
draggable: true,
showOnMouseOver: true
}).update();
} else {
marker = new L.marker(currentCoord, {
draggable: true,
showOnMouseOver: true
}).update();
}
marker.addTo(tagSpacesMap);
} else {
if (currentCoord.latlng) {
marker.setLatLng(currentCoord.latlng);
} else {
marker.setLatLng(currentCoord);
}
}
}
function removeMarker(e) {
//tagSpacesMap.removeLayer(marker);
//if (tagSpacesMap.removeLayer(marker)) {
// console.log("MARKER REMOVED");
//}
//tagSpacesMap.clearLayers(marker);
}
var lat, lng;
var latlng;
function onMapClick(e) {
console.log(e.latlng);
addMarker(e);
parseCoordinateMap(e);
lat = e.latlng.lat.toFixed(7);
lng = e.latlng.lng.toFixed(7);
}
function parseCoordinateMap(e) {
var date = $('#coordinateMap')[0];
var long = lng >= 0 ? '+' + lng : lng;
var dateValue = e.latlng.lat.toFixed(7) + "" + long;
date.value = dateValue.trim();
}
function tagYourself() {
tagSpacesMap.locate({
setView: true,
watch: true
}) /* This will return map so you can do chaining */.on('locationfound', function(e) {
var marker = L.marker([e.latitude, e.longitude]).bindPopup('Current position', {showOnMouseOver: true});
var circle = L.circle([e.latitude, e.longitude], e.accuracy / 2, {
weight: 1,
color: 'blue',
fillColor: '#cacaca',
fillOpacity: 0.2
});
tagSpacesMap.addLayer(marker);
tagSpacesMap.addLayer(circle);
}).on('locationerror', function(error) {
showLocationNotFound(error);
});
}
function initMap() {
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
var target = $(e.target).attr("href"); // activated tab
if (target === "#geoLocation") {
tagSpacesMap.invalidateSize();
$('#editTagButton').click(function() {
var longitude = lng >= 0 ? '+' + lng : lng;
latlng = lat + "" + longitude;
console.log(latlng);
TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, latlng.trim());
});
$('#dialogEditTag').on('hidden.bs.modal', function() {
//removeMarker();
if (TSCORE.selectedTag === 'geoTag') {
TSCORE.TagUtils.removeTag(TSCORE.selectedFiles[0], TSCORE.selectedTag);
removeMarker();
}
});
}
});
tagSpacesMap.on('resize', function() {
tagSpacesMap.invalidateSize();
});
$('#dialogEditTag').on('shown.bs.modal', function() {
var data = $('#coordinateMap')[0];
data.value = TSCORE.selectedTag;
});
tagSpacesMap.on('click', onMapClick);
//tagSpacesMap.on('locationfound', onLocationFound);
tagSpacesMap.on('layeradd', function(e) {
//console.log('layeradd', e);
});
showGeoLocation(TSCORE.selectedTag);
}
// Public API definition
exports.initMap = initMap;
exports.tagYourself = tagYourself;
exports.onMapClick = onMapClick;
exports.addMarker = addMarker;
exports.showGeoLocation = showGeoLocation;
exports.getLocation = getLocation;
exports.showPosition = showPosition;
exports.splitValue = splitValue;
}); | JavaScript | 0.000008 | @@ -4104,35 +4104,8 @@
) %7B%0A
- console.log(e.latlng);%0A
|
846ca1976e096bbb7962c91bb53537187cfc4077 | Set store.firestore to firestoreInstance. Fixes #19 | src/enhancer.js | src/enhancer.js | import { defaultConfig } from './constants';
import createFirestoreInstance from './createFirestoreInstance';
let firestoreInstance;
/**
* @name reduxFirestore
* @external
* @description Redux store enhancer that accepts configuration options and adds
* store.firestore. Enhancers are most commonly placed in redux's `compose` call
* along side applyMiddleware.
* @property {Object} firebaseInstance - Initiated firebase instance
* @property {Object} config - Containing react-redux-firebase specific configuration
* @return {Function} That accepts a component and returns a Component which
* wraps the provided component (higher order component).
* @return {Function} That enhances a redux store with store.firestore
* @example <caption>Setup</caption>
* import { createStore, compose } from 'redux'
* import { reduxFirestore } from 'redux-firestore'
* import firebase from 'firebase' // must be 4.5.0 or higher
import 'firebase/firestore' // make sure you add this for firestore
* // Redux Firestore Config
* const config = {
* // here is where you place other config options
* }
* // initialize script from Firestore page
* const fbConfg = {} // firebase config object
* firebase.initializeApp(fbConfig)
* firebase.firestore()
*
* // Add redux-firestore enhancer to store creation compose
* // Note: In full projects this will often be within createStore.js or store.js
const store = createStore(
makeRootReducer(),
initialState,
compose(
// pass firebase instance and config
reduxFirestore(firebase, reduxConfig),
// applyMiddleware(...middleware),
// ...enhancers
)
)
*
* // Use Function later to create store
* const store = createStoreWithFirestore(rootReducer, initialState)
*/
export default (firebaseInstance, otherConfig) => next =>
(reducer, initialState, middleware) => {
const store = next(reducer, initialState, middleware);
const configs = { ...defaultConfig, ...otherConfig };
firestoreInstance = createFirestoreInstance( // eslint-disable-line no-param-reassign
firebaseInstance.firebase_ || firebaseInstance, // eslint-disable-line no-underscore-dangle, no-undef, max-len
configs,
store.dispatch // eslint-disable-line comma-dangle
);
store.firestore = firebaseInstance;
return store;
};
/**
* @description Expose Firestore instance created internally. Useful for
* integrations into external libraries such as redux-thunk and redux-observable.
* @example <caption>redux-thunk integration</caption>
* import { applyMiddleware, compose, createStore } from 'redux';
* import thunk from 'redux-thunk';
* import makeRootReducer from './reducers';
* import { reduxFirestore, getFirestore } from 'redux-firestore';
*
* const fbConfig = {} // your firebase config
*
* const store = createStore(
* makeRootReducer(),
* initialState,
* compose(
* applyMiddleware([
* // Pass getFirestore function as extra argument
* thunk.withExtraArgument(getFirestore)
* ]),
* reduxFirestore(fbConfig)
* )
* );
* // then later
* export const addTodo = (newTodo) =>
* (dispatch, getState, getFirestore) => {
* const firebase = getFirestore()
* firebase
* .add('todos', newTodo)
* .then(() => {
* dispatch({ type: 'SOME_ACTION' })
* })
* };
*
*/
export const getFirestore = () => {
// TODO: Handle recieveing config and creating firebase instance if it doesn't exist
/* istanbul ignore next: Firebase instance always exists during tests */
if (!firestoreInstance) {
throw new Error('Firebase instance does not yet exist. Check your compose function.'); // eslint-disable-line no-console
}
// TODO: Create new firebase here with config passed in
return firestoreInstance;
};
| JavaScript | 0 | @@ -2296,27 +2296,28 @@
store = fire
-bas
+stor
eInstance;%0A%0A
|
54e26cb46b06d6abce6b04b344201e880a00556c | fix some typos in description strings | source/views/settings/screens/push-notifications/ios-settings-button.js | source/views/settings/screens/push-notifications/ios-settings-button.js | // @flow
import * as React from 'react'
import {Linking} from 'react-native'
import {appName} from '@frogpond/constants'
import {Section, PushButtonCell} from '@frogpond/tableview'
type Props = {
pushesEnabled: boolean,
hasPrompted: boolean,
onEnable: () => any,
}
export function IosNotificationSettingsButton(props: Props) {
let {pushesEnabled, hasPrompted, onEnable} = props
let offString = `Notifications are turned off for "${appName()}".`
let onString = `Notifications are turned on for "${appName()}".`
let titleText: string
let footerText: string
let onPress: () => any
if (pushesEnabled) {
// we have seen the prompt and given permission
// -- show a button to open settings to turn off notifications
titleText = 'Disable Notifications'
footerText = `${onString}. You can turn notifications off for this app in Settings.`
onPress = () => Linking.openURL('app-settings:')
} else {
if (hasPrompted) {
// we declined the initial prompt
// -- show a button to open settings to turn on notifications
titleText = 'Open Settings'
footerText = `${offString} You can turn notifications on for this app in Settings.`
onPress = () => Linking.openURL('app-settings:')
} else {
// we have not been prompted before
// -- let onesignal prompt for permissions
titleText = 'Enable Notifications'
footerText = `${offString}. You can turn notifications on for this app by pushing the button above.`
onPress = onEnable
}
}
return (
<Section footer={footerText} header="NOTIFICATION SETTINGS">
<PushButtonCell onPress={onPress} title={titleText} />
</Section>
)
}
| JavaScript | 0.999999 | @@ -784,25 +784,24 @@
%60$%7BonString%7D
-.
You can tur
@@ -1364,17 +1364,16 @@
fString%7D
-.
You can
|
46f2f77cfb4d00d3a1d2acd30a23563db0ef56f3 | fix bug : notification wasn't disappear if dismissAfter was null | src/helpers/index.js | src/helpers/index.js | import {STATUS} from '../constants';
/**
* Convert status in a understandable status for the Notification component
* @param {String|Number} status
* @returns {String} status an understandable status
*/
export function convertStatus(status) {
const reHttpStatusCode = /^\d{3}$/;
// convert HTTP status code
if (reHttpStatusCode.test(status)) {
switch (true) {
case /^1/.test(status):
return STATUS.info;
case /^2/.test(status):
return STATUS.success;
case /^(4|5)/.test(status):
return STATUS.error;
}
}
return status;
}
/**
* Create a Timer
* @param {Function} callback
* @param {Number} delay
* @constructor
*/
export function Timer(callback, delay) {
let timerId;
let start;
let remaining = delay;
this.pause = () => {
clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = () => {
start = new Date();
clearTimeout(timerId);
timerId = setTimeout(callback, remaining);
};
this.getTimeRemaining = () => {
return remaining;
};
}
/**
* Treat data of a notification
* @param {Object} notification
* @returns {Object} a notification
*/
export function treatNotification(notification) {
notification.dismissAfter = parseInt(notification.dismissAfter);
if (notification.image) {
notification.status = STATUS.default;
}
else {
notification.status = convertStatus(notification.status);
}
if (!notification.buttons) {
notification.buttons = [];
}
return notification;
}
| JavaScript | 0.000003 | @@ -1214,16 +1214,53 @@
tion) %7B%0A
+ if (notification.dismissAfter) %7B%0A
notifi
@@ -1318,16 +1318,20 @@
After);%0A
+ %7D%0A
if (no
|
a77a5b659c1921d6425ea58c3be813e1d80bdb85 | Fix regex to allow relative urls. | src/Backend/Core/Js/ckeditor/plugins/medialibrary/dialogs/linkDialog.js | src/Backend/Core/Js/ckeditor/plugins/medialibrary/dialogs/linkDialog.js | CKEDITOR.dialog.add(
'linkDialog',
function (editor) {
var urlRegex = 'https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}(\\.[a-z]{2,6})?\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)';
return {
title: 'Add link',
minWidth: 400,
minHeight: 200,
contents: [
{
id: 'tab',
label: '',
elements: [
{
type: 'text',
id: 'displayText',
label: 'Display Text',
validate: CKEDITOR.dialog.validate.notEmpty('Display cannot be empty.'),
setup: function(element) {
this.setValue(element.getText());
},
commit: function (element) {
element.setText(this.getValue());
}
},
{
type: 'text',
id: 'url',
label: 'URL',
validate: CKEDITOR.dialog.validate.regex(new RegExp(urlRegex), 'URL is not valid.'),
setup: function(element) {
this.setValue(element.getAttribute('href'));
},
commit: function (element) {
element.setAttribute('href', this.getValue());
}
},
{
type: 'button',
id: 'browseServer',
label: 'Browse server',
onClick: function () {
var editor = this.getDialog().getParentEditor();
editor.popup(window.location.origin + jsData.MediaLibrary.browseAction, 800, 500);
window.onmessage = function (event) {
if (event.data) {
this.setValueOf('tab', 'url', event.data);
}
}.bind(this.getDialog());
}
}
]
}
],
onOk: function () {
var dialog = this,
anchor = dialog.element;
dialog.commitContent(anchor);
if (dialog.insertMode) {
editor.insertElement(anchor);
}
},
onShow: function () {
var dialog = this;
var selection = editor.getSelection();
var initialText = selection.getSelectedText();
var element = selection.getStartElement();
if (element) {
element = element.getAscendant('a', true);
}
dialog.insertMode = !element || element.getName() !== 'a';
if (dialog.insertMode) {
element = editor.document.createElement('a');
dialog.setValueOf('tab', initialText.match(urlRegex) ? 'url' : 'displayText', initialText);
}
this.element = element;
if (!this.insertMode) {
this.setupContent(element)
}
}
}
}
)
| JavaScript | 0.000001 | @@ -80,16 +80,17 @@
egex = '
+(
https?:%5C
@@ -153,11 +153,13 @@
6%7D)?
+)?
%5C%5C
-b
+/
(%5B-a
|
e140e5644c09ef3d5733ff4d92a5bcb96ae36011 | undo fix from other PR | new-lamassu-admin/src/components/layout/Sidebar.js | new-lamassu-admin/src/components/layout/Sidebar.js | import { makeStyles } from '@material-ui/core/styles'
import classnames from 'classnames'
import React from 'react'
import { P } from 'src/components/typography'
import { ReactComponent as CompleteStageIconZodiac } from 'src/styling/icons/stage/zodiac/complete.svg'
import { ReactComponent as CurrentStageIconZodiac } from 'src/styling/icons/stage/zodiac/current.svg'
import { ReactComponent as EmptyStageIconZodiac } from 'src/styling/icons/stage/zodiac/empty.svg'
import styles from './Sidebar.styles'
const useStyles = makeStyles(styles)
const Sidebar = ({
data,
displayName,
isSelected,
onClick,
children,
itemRender,
loading = false
}) => {
const classes = useStyles()
return (
<div className={classes.sidebar}>
{loading && <P>Loading...</P>}
{!loading &&
data?.map((it, idx) => (
<div
key={idx}
className={classnames({
[classes.activeLink]: isSelected(it),
[classes.customRenderActiveLink]: itemRender && isSelected(it),
[classes.customRenderLink]: itemRender,
[classes.link]: true
})}
onClick={() => onClick(it)}>
{itemRender ? itemRender(it, isSelected(it)) : displayName(it)}
</div>
))}
{!loading && children}
</div>
)
}
export default Sidebar
const Stepper = ({ step, it, idx, steps }) => {
const classes = useStyles()
const active = step === idx
const past = idx < step
const future = idx > step
return (
<div className={classes.item}>
<span
className={classnames({
[classes.itemText]: true,
[classes.itemTextActive]: active,
[classes.itemTextPast]: past
})}>
{it.label}
</span>
{active && <CurrentStageIconZodiac />}
{past && <CompleteStageIconZodiac />}
{future && <EmptyStageIconZodiac />}
{idx < steps.length - 1 && (
<div
className={classnames({
[classes.stepperPath]: true,
[classes.stepperPast]: past
})}></div>
)}
</div>
)
}
export { Stepper }
| JavaScript | 0 | @@ -805,17 +805,16 @@
data
-?
.map((it
|
ce08fb465a394a819796e8977c3ff2e0b4d190b5 | Reformat (tidy) Javascript | src/inject/inject.js | src/inject/inject.js | chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
// This runs when page is done loading.
// TODO Document whe the interval is cleared.
clearInterval(readyStateCheckInterval);
}
}, 10);
var COMMENT_TITLE = 'Toggle comments ';
/**
* Add buttons for toggling comment visibility to each comment thread container.
*/
function addButtonsIfNotExist() {
[].slice.call(document.querySelectorAll('.comment-thread-container')).forEach(function (container) {
if ($(container).has('button.ba-hide-comment-button').length == 0) {
var resolveButton = container.innerText.toLowerCase().indexOf('resolved.') == -1 ? '<button class="ba-resolve-button">resolve</button>' : '';
var $toggle = $('<div class="ba-container"><button class="ba-hide-comment-button"></button>' + resolveButton + '</div>');
$(container).prepend($toggle);
}
// Do this no matter whether we're adding the button or not - always needs to be updated
// because the number of comments could have changed.
var commentsCount = $(container).find('.comment').length;
$(container).find('button.ba-hide-comment-button').text(COMMENT_TITLE + '(' + commentsCount + ')');
});
}
/**
* Hide all comments that have the text `resolved.` in them.
* - ignores buttons that the user has clicked, indicated by `user-override`.
*
* Case insensitive.
*/
function hideResolved() {
[].slice.call(document.querySelectorAll('.comment-thread-container')).forEach(function (container) {
if (container.innerText.toLowerCase().indexOf('resolved.') != -1
&& !$(container).hasClass('user-override')) {
$(container).addClass('ba-hidden');
}
});
}
/**
* Handles clicks on the toggle buttons which are prepended to each comment thread container.
*/
$(document).on('click', 'button.ba-hide-comment-button', function handleToggleButtonClick(e) {
var threadContainer = $(e.target).closest('.comment-thread-container');
var visible = !threadContainer.hasClass('ba-hidden');
if (visible) {
$(threadContainer).addClass('ba-hidden').addClass('user-override');
} else {
$(threadContainer).removeClass('ba-hidden').addClass('user-override');
}
});
/**
* Handles clicks on the resolve buttons which are prepended to each comment thread container.
*/
$(document).on('click', 'button.ba-resolve-button', function (e) {
var container = $(e.target).closest('.comment-thread-container');
var replyButton = $(container).find('.reply-link.execute.click')[0];
replyButton.click();
container.find('#id_new_comment').text('Resolved. This thread was resolved by Bitbucket Awesomizer. [Download from the chrome webstore and make bitbucket awesome!](https://chrome.google.com/webstore/detail/bitbucket-awesomizer/fpcpncnhbbmlmhgicafejpabkdjenloi?authuser=1)');
var submitButton = container.find('button[type="submit"].aui-button');
submitButton.trigger('click');
// $(e.target).remove();
});
// We don't yet have a way to be event driven, so need to poll for changes.
setInterval(function () {
addButtonsIfNotExist();
hideResolved();
}, 2000);
console.log('bitbucket awesomizer loaded')
});
| JavaScript | 0 | @@ -47,16 +47,18 @@
onse) %7B%0A
+
var re
@@ -102,24 +102,28 @@
unction() %7B%0A
+
if (docu
@@ -158,24 +158,30 @@
e%22) %7B%0A
+
+
// This runs
@@ -211,24 +211,30 @@
ing.%0A%0A
+
+
// TODO Docu
@@ -240,17 +240,17 @@
ument wh
-e
+y
the int
@@ -273,16 +273,22 @@
.%0A
+
+
clearInt
@@ -323,18 +323,24 @@
l);%0A
-%7D%0A
+ %7D%0A
%7D, 10)
@@ -612,33 +612,32 @@
forEach(function
-
(container) %7B%0A
@@ -1760,17 +1760,16 @@
function
-
(contain
@@ -1850,32 +1850,16 @@
') != -1
-%0A
&& !$(c
@@ -2554,24 +2554,25 @@
%7D%0A %7D);%0A
+%0A
/**%0A
@@ -2738,17 +2738,16 @@
function
-
(e) %7B%0A
@@ -3409,17 +3409,17 @@
be event
-
+-
driven,
@@ -3471,17 +3471,16 @@
function
-
() %7B%0A
|
b6af4714757e19f4f20d02fdf42462d3bf86b7a8 | Use EasyWiki as title if not available. | src/inject/inject.js | src/inject/inject.js | var statusa;
chrome.extension.sendRequest({msg: "getStatus"}, function(response) {
if (response.status == 1) {
statusa = true;
} else {
statusa = false;
}
});
WIKI_URL_REGEX = /^((http|https):\/\/)?[a-z]+.wikipedia.org\/wiki\/[a-zA-Z0-9_()#%,.!-]+$/i
CLASS_MATCHER = /easy-wiki-popover/i
var extractLanguage = function(url) {
return url.match(/\/[a-z]{2}/i)[0].replace("/", '');
}
var extractTitle = function(url) {
return url.match(/wiki\/[a-zA-Z0-9_()#%,.!-]+$/i)[0].replace("wiki/", '');
}
var wikiFetch = function(url) {
language = extractLanguage(url);
title = extractTitle(url);
fetchUrl = "http://" + language + '.wikipedia.org/w/api.php?' + 'action=query&prop=extracts&exchars=500&format=json&titles=' + title;
$.ajax({
url: fetchUrl,
timeout: 30000,
})
.done(function(data) {
var ewp_content = '';
var ewp_title = "";
$.each(data.query.pages, function(key) {
ewp_content = data.query.pages[key].extract.replace(/(<([^>]+)>)/ig,"");
ewp_title = data.query.pages[key].title;
});
var link = $(".ewp-active");
link.attr("data-content", ewp_content);
link.attr("data-title", ewp_title);
link.attr("data-original-title", ewp_title);
$(".popover-content").html(ewp_content);
$(".popover-title").html(ewp_title);
})
.fail(function(data) {
var ewp_content = "Drats! Error fetching the Wikipedia page.";
var ewp_title = "Error";
var link = $(".ewp-active");
link.attr("data-content", ewp_content);
link.attr("data-title", ewp_title);
link.attr("data-original-title", ewp_title);
$(".popover-content").html(ewp_content);
$(".popover-title").html(ewp_title);
});
}
$(document).ready(function() {
var delay = 700, timer;
$("a").on('mouseenter', function() {
__this = this;
popTitle = $(this).attr("title");
if (statusa && !($(this).hasClass("easy-wiki-popover"))) {
$(this).attr("title", "");
}
timer = setTimeout(function() {
if (statusa && __this.href.match(WIKI_URL_REGEX)) {
$(__this).addClass("ewp-active");
if (!($(__this).hasClass("easy-wiki-popover"))) {
$(__this).addClass("easy-wiki-popover");
$(__this).popover({
html: true,
trigger: 'manual',
title: popTitle,
content: "Loading..."
}).on("mouseenter", function() {
var _this = this;
$(this).popover("show");
$(this).siblings(".popover").on("mouseleave", function () {
$(_this).popover('destroy');
$(_this).removeClass("ewp-active");
});
}).on("mouseleave", function() {
var _this = this;
setTimeout(function () {
if (!$(".popover:hover").length) {
$(_this).popover("destroy");
$(_this).removeClass("ewp-active");
}
}, 5);
}).popover("show");
wikiFetch(__this.href);
}
}
}, delay);
});
$("a").on("mouseleave", function() {
clearTimeout(timer);
});
}); | JavaScript | 0 | @@ -2205,16 +2205,30 @@
popTitle
+ %7C%7C 'EasyWiki'
,%0A%09%09%09%09%09%09
|
fa4b2be9cd095640c6e7e69907ff8b57560faadf | Allow enabling and disabling switcher | src/jquery.geokbd.js | src/jquery.geokbd.js | (function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkeys: ['~', '`']
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
this.each(function() {
var $this = $(this);
if ($this.is(':text, textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find(':text, textarea'));
} else if ($this.is(':checkbox')) {
switchers = switchers.add($this);
} else if ($this.hasClass('switchButton')){
switchers = switchers.add($this);
}
});
function toggleLang() {
$('.switch').toggleClass('active-kbd');
isOn = !isOn;
$('.switch').prop('checked', isOn);
}
function enableLang() {
isOn = true
$('.switch').prop('checked', isOn);
$('.switch').removeClass('active-kbd');
}
function disableLang() {
isOn = false
$('.switch').prop('checked', isOn);
$('.switch').addClass('active-kbd');
}
function getIsOn() {
return isOn
}
switchers
.click(function() {
toggleLang();
});
switchers.enableLang = enableLang
switchers.disableLang = disableLang
switchers.getIsOn = getIsOn
toggleLang(isOn = false);
$(document).keypress(function(e) {
if (e.target.type === 'password' || e.target.type === 'email') {return;}
if ( $(e.target).attr('maxlength') !== undefined ) {
var limit = parseInt($(e.target).attr('maxlength'));
var currentLength = $(e.target).val().length;
if (currentLength >= limit) {return;}
}
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkeys.indexOf(ch) != -1) {
toggleLang();
e.preventDefault();
}
if (!isOn) {
return;
}
if (!$(e.target).is('input')) {return;}
kach = translateToKa.call(ch);
if (ch !== kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function translateToKa() {
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart !== undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
}
return switchers
};
}(jQuery));
| JavaScript | 0 | @@ -66,16 +66,33 @@
%0A%09isOn,%0A
+%09enabled = true,%0A
%09inputs
@@ -100,16 +100,16 @@
$(%5B%5D),%0A
-
%09switche
@@ -707,24 +707,42 @@
gleLang() %7B%0A
+%09%09%09if(enabled) %7B%0A%09
$('.sw
@@ -775,16 +775,17 @@
-kbd');%0A
+%09
is
@@ -796,16 +796,17 @@
!isOn;%0A
+%09
$(
@@ -839,16 +839,23 @@
isOn);%0A
+%09 %7D%0A
%09%7D%0A%0A%09fun
@@ -961,32 +961,51 @@
('active-kbd');%0A
+%09%09return switchers%0A
%09%7D%0A%0A%09function di
@@ -1106,24 +1106,43 @@
tive-kbd');%0A
+%09%09return switchers%0A
%09%7D%0A%0A%09functio
@@ -1173,16 +1173,140 @@
sOn%0A%09%7D%0A%0A
+%09function disable() %7B%0A%09%09enabled = false%0A%09%09return switchers%0A%09%7D%0A%0A%09function enable() %7B%0A%09%09enabled = true%0A%09%09return switchers%0A%09%7D%0A%0A
switch
@@ -1428,32 +1428,32 @@
g = disableLang%0A
-
switchers.getI
@@ -1467,16 +1467,79 @@
getIsOn
+%0A switchers.disable %09%09= disable%0A switchers.enable %09%09%09= enable
%0A%0A%09toggl
|
b89b40a4de75eedfd6fd18ba48da5013ad8082a5 | test fix | mpwo_client/e2e/admin-sports.test.js | mpwo_client/e2e/admin-sports.test.js | import { Selector } from 'testcafe'
import { TEST_URL } from './utils'
// database must be initialiazed
const adminEmail = 'admin@example.com'
const adminPassword = 'mpwoadmin'
// eslint-disable-next-line no-undef
fixture('/admin/sports').page(`${TEST_URL}/admin/sports`)
test('admin should be able to access sports administration page', async t => {
// admin login
await t
.navigateTo(`${TEST_URL}/login`)
.typeText('input[name="email"]', adminEmail)
.typeText('input[name="password"]', adminPassword)
.click(Selector('input[type="submit"]'))
await t
.navigateTo(`${TEST_URL}/admin/sports`)
.expect(Selector('H1').withText('Administration - Sports').exists).ok()
.expect(Selector('.sport-items').withText('Hiking').exists).ok()
})
| JavaScript | 0 | @@ -719,20 +719,10 @@
or('
-.sport-items
+TD
').w
@@ -752,12 +752,11 @@
s).ok()%0A
-%0A
%7D)%0A
|
05a545d16f3fa1beaf64ddf849ea88cde592042b | Update mainClient.js | src/js/mainClient.js | src/js/mainClient.js | import CanvasStreamerClient from './canvasStreamerClient';
| JavaScript | 0 | @@ -52,8 +52,60 @@
lient';%0A
+window.CanvasStreamerClient = CanvasStreamerClient;%0A
|
3f2834a9c7559d4f9c42643dd3d7ea159da2ad00 | Move module initialize code to addModule. | src/js/summernote.js | src/js/summernote.js | define([
'jquery',
'summernote/base/core/func',
'summernote/base/core/list'
], function ($, func, list) {
/**
* @param {jQuery} $note
* @param {Object} options
* @return {Context}
*/
var Context = function ($note, options) {
var self = this;
var ui = $.summernote.ui;
this.modules = {};
this.buttons = {};
this.layoutInfo = {};
this.options = options;
this.initialize = function () {
// create layout info
this.layoutInfo = ui.createLayout($note, options);
// initialize module
Object.keys(this.options.modules).forEach(function (key) {
var module = new self.options.modules[key](self);
if (module.initialize) {
module.initialize.apply(module);
}
self.addModule(key, module);
});
// add optional buttons
Object.keys(this.options.buttons).forEach(function (key) {
var button = self.options.buttons[key];
self.addButton(key, button);
});
$note.hide();
return this;
};
this.destroy = function () {
Object.keys(this.modules).forEach(function (key) {
self.removeModule(key);
});
$note.removeData('summernote');
ui.removeLayout($note, this.layoutInfo);
};
this.code = function (html) {
if (html === undefined) {
var isActivated = this.invoke('codeview.isActivated');
this.invoke('codeview.sync');
return isActivated ? this.layoutInfo.codable.val() : this.layoutInfo.editable.html();
}
this.layoutInfo.editable.html(html);
};
this.triggerEvent = function () {
var namespace = list.head(arguments);
var args = list.tail(list.from(arguments));
var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')];
if (callback) {
callback.apply($note[0], args);
}
$note.trigger('summernote.' + namespace, args);
};
this.addModule = function (key, instance) {
this.modules[key] = instance;
};
this.removeModule = function (key) {
if (this.modules[key].destroy) {
this.modules[key].destroy();
}
delete this.modules[key];
};
this.addButton = function (key, handler) {
this.buttons[key] = handler;
};
this.removeButton = function (key) {
if (this.buttons[key].destroy) {
this.buttons[key].destroy();
}
delete this.buttons[key];
};
this.createInvokeHandler = function (namespace, value) {
return function (event) {
event.preventDefault();
self.invoke(namespace, value || $(event.target).data('value') || $(event.currentTarget).data('value'));
};
};
this.invoke = function () {
var namespace = list.head(arguments);
var args = list.tail(list.from(arguments));
var splits = namespace.split('.');
var hasSeparator = splits.length > 1;
var moduleName = hasSeparator && list.head(splits);
var methodName = hasSeparator ? list.last(splits) : list.head(splits);
var module = this.modules[moduleName || 'editor'];
if (!moduleName && this[methodName]) {
return this[methodName].apply(this, args);
} else if (module && module[methodName]) {
return module[methodName].apply(module, args);
}
};
return this.initialize();
};
$.summernote = $.summernote || {
lang: {}
};
$.fn.extend({
/**
* Summernote API
*
* @param {Object|String}
* @return {this}
*/
summernote: function () {
var type = $.type(list.head(arguments));
var isExternalAPICalled = type === 'string';
var hasInitOptions = type === 'object';
var options = hasInitOptions ? list.head(arguments) : {};
options = $.extend({}, $.summernote.options, options);
options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
this.each(function (idx, note) {
var $note = $(note);
if (!$note.data('summernote')) {
$note.data('summernote', new Context($note, options));
$note.data('summernote').triggerEvent('init');
}
});
var $note = this.first();
if (isExternalAPICalled && $note.length) {
var context = $note.data('summernote');
return context.invoke.apply(context, list.from(arguments));
} else {
return this;
}
}
});
});
| JavaScript | 0 | @@ -620,24 +620,27 @@
-var module = new
+self.addModule(key,
sel
@@ -665,136 +665,8 @@
key%5D
-(self);%0A if (module.initialize) %7B%0A module.initialize.apply(module);%0A %7D%0A self.addModule(key, module
);%0A
@@ -1851,19 +1851,153 @@
ey,
-instance) %7B
+ModuleClass) %7B%0A var instance = new ModuleClass(this);%0A if (instance.initialize) %7B%0A instance.initialize.apply(instance);%0A %7D%0A
%0A
|
be2ea1d95b5e4764ec9255c1ec3c09db1ab92c14 | Add an error call back param | src/lib/GoogleApi.js | src/lib/GoogleApi.js | export const GoogleApi = function(opts) {
opts = opts || {};
if (!opts.hasOwnProperty('apiKey')) {
throw new Error('You must pass an apiKey to use GoogleApi');
}
const apiKey = opts.apiKey;
const libraries = opts.libraries || ['places'];
const client = opts.client;
const URL = opts.url || 'https://maps.googleapis.com/maps/api/js';
const googleVersion = opts.version || '3.31';
let script = null;
let google = (typeof window !== 'undefined' && window.google) || null;
let loading = false;
let channel = null;
let language = opts.language;
let region = opts.region || null;
let onLoadEvents = [];
const url = () => {
let url = URL;
let params = {
key: apiKey,
callback: 'CALLBACK_NAME',
libraries: libraries.join(','),
client: client,
v: googleVersion,
channel: channel,
language: language,
region: region
};
let paramStr = Object.keys(params)
.filter(k => !!params[k])
.map(k => `${k}=${params[k]}`)
.join('&');
return `${url}?${paramStr}`;
};
return url();
};
export default GoogleApi;
| JavaScript | 0 | @@ -896,16 +896,49 @@
: region
+,%0A onError: 'ERROR_FUNCTION'
%0A %7D;%0A
|
89525bed41c67e1898cf0289cbe26c408f73c902 | add correct name for Chinese | src/lib/api/langs.js | src/lib/api/langs.js |
import Promise from 'bluebird';
import _ from 'lodash';
export const langs = {
en: {
slug: "en",
label: "EN",
name: "English"
},
de: {
slug: "de",
label: "DE",
name: "Deutsch"
},
es: {
slug: "es",
label: "ES",
name: "Español"
},
fr: {
slug: "fr",
label: "FR",
name: "Français"
},
zh: {
slug: "zh",
label: "ZH",
name: "Chinese"
},
};
export function getLang(slug) {
return Promise.resolve(_.get(langs, slug));
};
export function getLangs(slugs = []) {
console.log('getLangs', slugs.toString());
if (!Array.isArray(slugs) || slugs.length === 0 || slugs.indexOf('all') !== -1) {
return Promise.resolve(_.values(langs));
} else {
return Promise.map(slugs, slug => _.get(langs, slug));
}
};
export default langs;
| JavaScript | 0.999996 | @@ -342,10 +342,10 @@
l: %22
-ZH
+%E4%B8%AD%E6%96%87
%22,%0A%09
@@ -356,15 +356,10 @@
e: %22
-Chinese
+%E4%B8%AD%E6%96%87
%22%0A%09%7D
|
c3a20f529b55eba26e2d577b20aa5dfd00ee7e01 | remove unneeded comment | dom/src/index.js | dom/src/index.js | import most from 'most'
import hold from '@most/hold'
import snabbdom from 'snabbdom'
import h from 'snabbdom/h'
const {
a, abbr, address, area, article, aside, audio, b, base,
bdi, bdo, blockquote, body, br, button, canvas, caption,
cite, code, col, colgroup, dd, del, dfn, dir, div, dl,
dt, em, embed, fieldset, figcaption, figure, footer, form,
h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html,
i, iframe, img, input, ins, kbd, keygen, label, legend,
li, link, map, mark, menu, meta, nav, noscript, object,
ol, optgroup, option, p, param, pre, q, rp, rt, ruby, s,
samp, script, section, select, small, source, span, strong,
style, sub, sup, table, tbody, td, textarea, tfoot, th,
thead, title, tr, u, ul, video,
} = require(`hyperscript-helpers`)(h)
import matchesSelector from 'snabbdom-selector'
import filter from 'fast.js/array/filter'
import reduce from 'fast.js/array/reduce'
import concat from 'fast.js/array/concat'
import fastMap from 'fast.js/array/map'
import {getDomElement} from './utils'
import fromEvent from './fromEvent'
import parseTree from './parseTree'
const isolateSource =
(_source, _scope) =>
_source.select(`.cycle-scope-${_scope}`)
const isolateSink =
(sink, scope) =>
sink.map(
vtree => {
if (vtree.sel.indexOf(`cycle-scope-${scope}`) === -1) {
const c = `${vtree.sel}.cycle-scope-${scope}`
vtree.sel = c
}
return vtree
}
)
const makeIsStrictlyInRootScope =
(rootList, namespace) =>
leaf => {
const classIsForeign =
c => {
const matched = c.match(/cycle-scope-(\S+)/)
return matched && namespace.indexOf(`.${c}`) === -1
}
for (let el = leaf.elm.parentElement;
el !== null; el = el.parentElement) {
if (rootList.indexOf(el) >= 0) {
return true
}
const classList = el.className.split(` `)
if (classList.some(classIsForeign)) {
return false
}
}
return true
}
const makeEventsSelector =
element$ =>
(eventName, useCapture = false) => {
if (typeof eventName !== `string`) {
throw new Error(`DOM drivers events() expects argument to be a ` +
`string representing the event type to listen for.`)
}
return element$
.map(elements => {
if (!elements) {
return most.empty()
}
return fromEvent(eventName, elements, useCapture)
}).switch().multicast()
}
const mapToElement = element => Array.isArray(element) ?
fastMap(element, el => el.elm) :
element.elm
function makeFindBySelector(selector, namespace) {
return function findBySelector(rootElem) {
const matches = Array.isArray(rootElem) ?
reduce(rootElem, (m, el) =>
concat(matchesSelector(selector, el), m),
[]) : matchesSelector(selector, rootElem)
return filter(
matches,
makeIsStrictlyInRootScope(matches, namespace)
)
}
}
// Use function not 'const = x => {}' for this.namespace below
function makeElementSelector(rootElem$) {
return function DOMSelect(selector) {
if (typeof selector !== `string`) {
throw new Error(`DOM drivers select() expects first argument to be a ` +
`string as a CSS selector`)
}
const namespace = this.namespace
const scopedSelector = `${namespace.join(` `)} ${selector}`.trim()
const element$ =
selector.trim() === `:root` ?
rootElem$ :
rootElem$.map(makeFindBySelector(scopedSelector, namespace))
return {
observable: element$.map(mapToElement),
namespace: namespace.concat(selector),
select: makeElementSelector(element$),
events: makeEventsSelector(element$.map(mapToElement)),
isolateSource,
isolateSink,
}
}
}
const validateDOMDriverInput =
view$ => {
if (!view$ || typeof view$.observe !== `function`) {
throw new Error(`The DOM driver function expects as input an ` +
`Observable of virtual DOM elements`)
}
}
const makeDOMDriver =
(container, modules = [
require(`snabbdom/modules/class`),
require(`snabbdom/modules/props`),
require(`snabbdom/modules/attributes`),
require(`snabbdom/modules/style`),
]) => {
const patch = snabbdom.init(modules)
const rootElem = getDomElement(container)
const DOMDriver =
view$ => {
validateDOMDriverInput(view$)
const rootElem$ =
view$
.map(parseTree)
.switch()
.scan((oldVnode, vnode) => patch(oldVnode, vnode), rootElem)
.skip(1) // emits rootElem first
return {
namespace: [],
select: makeElementSelector(hold(rootElem$)),
isolateSink,
isolateSource,
}
}
return DOMDriver
}
export {
makeDOMDriver,
h,
a, abbr, address, area, article, aside, audio, b, base,
bdi, bdo, blockquote, body, br, button, canvas, caption,
cite, code, col, colgroup, dd, del, dfn, dir, div, dl,
dt, em, embed, fieldset, figcaption, figure, footer, form,
h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html,
i, iframe, img, input, ins, kbd, keygen, label, legend,
li, link, map, mark, menu, meta, nav, noscript, object,
ol, optgroup, option, p, param, pre, q, rp, rt, ruby, s,
samp, script, section, select, small, source, span, strong,
style, sub, sup, table, tbody, td, textarea, tfoot, th,
thead, title, tr, u, ul, video,
}
| JavaScript | 0 | @@ -4622,32 +4622,9 @@
p(1)
- // emits rootElem first
+%0A
%0A
|
6caaa7492c97d50ccd33ada441a81a1e9703b684 | Fix bug in search results - Multiple switches fail as state wasn't being bubbled back up properly | discord-client/src/commands/searchResults.js | discord-client/src/commands/searchResults.js | const { formatHaiku } = require('../formatHaiku');
const messageFromResults = (searchResults, index) => `Found ${searchResults.length} haiku${searchResults.length !== 1 ? 's' : ''}:
Showing result (${index + 1})`;
// Cycle through search results
// indexDelta should be -1 on left, +1 on right
const switchResults = async (state, indexDelta, message) => {
const { searchResults, currentIndex, context } = state;
const newIndex = currentIndex + indexDelta;
if (newIndex >= 0 && newIndex < searchResults.length) {
// Edit message
const content = messageFromResults(searchResults, newIndex);
const embed = await formatHaiku(searchResults[newIndex], context.client, context.server);
await message.edit(content, embed);
return { searchResults, currentIndex: newIndex };
}
return { searchResults, currentIndex };
};
const onReact = (messageReaction, user, state) => {
const { message, emoji } = messageReaction;
let newState = { ...state };
switch (emoji.name) {
case '⬅': newState = switchResults(state, -1, message);
messageReaction.remove(user);
break;
case '➡': newState = switchResults(state, 1, message);
messageReaction.remove(user);
break;
default:
}
return { remove: false, newState };
};
// Send search results message to channel, add it to map
const addSearchResults = async (searchResults, context) => {
const content = messageFromResults(searchResults, 0);
const embed = await formatHaiku(searchResults[0], context.client, context.server);
const message = await context.channel.send(content, embed);
await message.react('⬅');
await message.react('➡');
const initialState = {
searchResults,
currentIndex: 0,
context,
};
context.messagesMap.addMessage(message.id, initialState, onReact);
};
exports.searchResultsCommand = async (context, args) => {
if (args.length === 0) {
throw Error('No search keywords provided');
}
try {
const searchResults = await context.api.searchHaikus(context.server.id, args);
if (searchResults.length === 0) {
await context.channel.send(`No results found for '${args.join(' ')}'`);
} else {
await addSearchResults(searchResults, context);
}
} catch (error) {
console.log(`Caught error ${JSON.stringify(error)}, sending simplified error message to discord`);
await context.channel.send('An error occurred while searching for haikus');
}
};
| JavaScript | 0 | @@ -779,24 +779,33 @@
ex: newIndex
+, context
%7D;%0A %7D%0A re
@@ -838,16 +838,25 @@
entIndex
+, context
%7D;%0A%7D;%0A%0A
@@ -870,16 +870,22 @@
nReact =
+ async
(messag
@@ -1030,32 +1030,38 @@
'%E2%AC%85': newState =
+ await
switchResults(s
@@ -1153,16 +1153,22 @@
wState =
+ await
switchR
|
7763e8993fdd1bdd6dc33079c9822e5c47e66c52 | clean up group component props | src/victory-container/victory-container.js | src/victory-container/victory-container.js | import React, { PropTypes } from "react";
import { assign, omit } from "lodash";
import Portal from "../victory-portal/portal";
import { Timer } from "../victory-util/index";
export default class VictoryContainer extends React.Component {
static displayName = "VictoryContainer";
static propTypes = {
className: PropTypes.string,
style: PropTypes.object,
height: PropTypes.number,
width: PropTypes.number,
events: PropTypes.object,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.node),
React.PropTypes.node
]),
title: PropTypes.string,
desc: PropTypes.string,
portalComponent: PropTypes.element,
responsive: PropTypes.bool,
standalone: PropTypes.bool
}
static defaultProps = {
title: "Victory Chart",
desc: "",
portalComponent: <Portal/>,
responsive: true
}
static contextTypes = {
getTimer: React.PropTypes.func
}
static childContextTypes = {
portalUpdate: React.PropTypes.func,
portalRegister: React.PropTypes.func,
portalDeregister: React.PropTypes.func,
getTimer: React.PropTypes.func
}
constructor(props) {
super(props);
this.getTimer = this.getTimer.bind(this);
}
componentWillMount() {
this.savePortalRef = (portal) => this.portalRef = portal;
this.portalUpdate = (key, el) => this.portalRef.portalUpdate(key, el);
this.portalRegister = () => this.portalRef.portalRegister();
this.portalDeregister = (key) => this.portalRef.portalDeregister(key);
}
componentWillUnmount() {
if (!this.context.getTimer) {
this.getTimer().stop();
}
}
getChildContext() {
return this.props.standalone === true || this.props.standalone === undefined ?
{
portalUpdate: this.portalUpdate,
portalRegister: this.portalRegister,
portalDeregister: this.portalDeregister,
getTimer: this.getTimer
} : {};
}
getTimer() {
if (this.context.getTimer) {
return this.context.getTimer();
}
if (!this.timer) {
this.timer = new Timer();
}
return this.timer;
}
// overridden in custom containers
getChildren(props) {
return props.children;
}
// Overridden in victory-core-native
renderContainer(props, svgProps, style) {
const { title, desc, portalComponent, className, standalone } = props;
return standalone || standalone === undefined ?
(
<svg {...svgProps} style={style} className={className}>
<title id="title">{title}</title>
<desc id="desc">{desc}</desc>
{this.getChildren(props)}
{React.cloneElement(portalComponent, {ref: this.savePortalRef})}
</svg>
) :
(
<g {...svgProps} style={style} className={className}>
<title id="title">{title}</title>
<desc id="desc">{desc}</desc>
{this.getChildren(props)}
</g>
);
}
render() {
const { width, height, responsive, events, standalone } = this.props;
const style = responsive ? this.props.style : omit(this.props.style, ["height", "width"]);
const useViewBox = responsive ? standalone || standalone === undefined : false;
const svgProps = assign(
{
"aria-labelledby": "title desc", role: "img", width, height,
viewBox: useViewBox ? `0 0 ${width} ${height}` : undefined
},
events
);
return this.renderContainer(this.props, svgProps, style);
}
}
| JavaScript | 0.000001 | @@ -1695,55 +1695,17 @@
one
-=== true %7C%7C this.props.standalone === undefined
+!== false
?%0A
@@ -2354,35 +2354,17 @@
one
-%7C%7C standalone === undefined
+!== false
?%0A
@@ -2728,92 +2728,8 @@
e%7D%3E%0A
- %3Ctitle id=%22title%22%3E%7Btitle%7D%3C/title%3E%0A %3Cdesc id=%22desc%22%3E%7Bdesc%7D%3C/desc%3E%0A
@@ -2983,215 +2983,246 @@
nst
-useViewBox = responsive ? standalone %7C%7C standalone === undefined : false;%0A const svgProps = assign(%0A %7B%0A %22aria-labelledby%22: %22title desc%22, role: %22img%22, width, height,%0A viewBox: useViewBox
+svgProps = assign(%0A %7B%0A width, height,%0A %22aria-labelledby%22: standalone !== false ? %22title desc%22 : undefined,%0A role: standalone !== false ? %22img%22 : %22presentation%22,%0A viewBox: responsive && standalone !== false
? %60
|
42ad97caef150934bd4605e0893185bdd9a5742b | fix filename | src/views/PostDetailView/PostDetailView.js | src/views/PostDetailView/PostDetailView.js | import React, {PropTypes, Component} from 'react'
import { connect } from 'react-redux'
import { actions } from '../../redux/modules/post'
import { Link } from 'react-router'
import CommentCard from 'components/CommentCard'
import CommentEditor from 'Components/CommentEditor'
import Card from 'material-ui/lib/card/card'
import CardText from 'material-ui/lib/card/card-text'
import CardHeader from 'material-ui/lib/card/card-header'
export class PostDetailView extends Component {
static propTypes = {
params: PropTypes.object.isRequired,
fetchPost: PropTypes.func.isRequired,
fetchPostComments: PropTypes.func.isRequired,
requestAddComment: PropTypes.func.isRequired,
setCommentEditorText: PropTypes.func.isRequired,
postId: PropTypes.string,
postFetch: PropTypes.object,
commentsFetch: PropTypes.object,
addCommentFetch: PropTypes.object,
commentEditorText: PropTypes.any,
post: PropTypes.object,
comments: PropTypes.array
};
constructor(props) {
super(props)
this.onCommentEditorChange = this.onCommentEditorChange.bind(this)
this.onPostCommentTap = this.onPostCommentTap.bind(this)
}
onCommentEditorChange() {
this.props.setCommentEditorText(this.refs.commentEditor.getValue())
}
onPostCommentTap() {
this.props.requestAddComment({
text: this.refs.commentEditor.getValue(),
postId: this.props.post.id
})
}
componentWillMount() {
const postId = this.props.params.postId
this.props.fetchPost(postId)
this.props.fetchPostComments(postId)
}
render() {
const {postFetch, commentsFetch, post, comments, addCommentFetch, commentEditorText} = this.props
if (!postFetch || !commentsFetch || postFetch.pending || commentsFetch.pending) {
return <span>Loading...</span>
}
if (postFetch.rejected || commentsFetch.rejected) {
return <span>Error... </span>
}
const commentsView = comments.map(comment => (
<CommentCard comment={comment}/>
// <ListItem primaryText={comment.text} leftAvatar={<Avatar src={comment.user.avatarUrl} />} />
))
console.log('commentEditorText', this.props.commentEditorText)
return (
<div className='container'>
<Link to='/'>Back</Link>
<div className='row'>
<div className='col-md-6'>
<h3>评论</h3>
<CommentEditor
ref='commentEditor'
value={commentEditorText}
onChange={this.onCommentEditorChange}
onPost={this.onPostCommentTap}
disabled={addCommentFetch && addCommentFetch.pending}
/>
{commentsView}
</div>
<div className='col-md-6'>
<h3>全文</h3>
<Card style={{marginTop: 20}}>
<CardHeader
title={post.user.name}
subtitle='xxxxx'
avatar={post.user.avatarUrl}
/>
<CardText>
{post.text}
</CardText>
</Card>
</div>
</div>
</div>
)
}
}
export default connect(state => ({
postFetch: state.post.postFetch,
post: state.post.post,
commentsFetch: state.post.commentsFetch,
comments: state.post.comments,
commentEditorText: state.post.commentEditorText
}), actions)(PostDetailView)
| JavaScript | 0.998679 | @@ -244,17 +244,17 @@
r from '
-C
+c
omponent
|
47ab485aa66aa74f4d4cf8e0c733788c4a271fd1 | Make loading source maps safer (#5095) | src/actions/sources/newSources.js | src/actions/sources/newSources.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
/**
* Redux actions for the sources state
* @module actions/sources
*/
import { syncBreakpoint } from "../breakpoints";
import { loadSourceText } from "./loadSourceText";
import { togglePrettyPrint } from "./prettyPrint";
import { selectLocation } from "../sources";
import { getRawSourceURL, isPrettyURL } from "../../utils/source";
import { prefs } from "../../utils/prefs";
import {
getSource,
getPendingSelectedLocation,
getPendingBreakpointsForSource
} from "../../selectors";
import type { Source } from "../../types";
import type { ThunkArgs } from "../types";
function createOriginalSource(
originalUrl,
generatedSource,
sourceMaps
): Source {
return {
url: originalUrl,
id: sourceMaps.generatedToOriginalId(generatedSource.id, originalUrl),
isPrettyPrinted: false,
isWasm: false,
isBlackBoxed: false,
loadedState: "unloaded"
};
}
/**
* @memberof actions/sources
* @static
*/
function loadSourceMap(generatedSource) {
return async function({ dispatch, getState, sourceMaps }: ThunkArgs) {
const urls = await sourceMaps.getOriginalURLs(generatedSource);
if (!urls) {
// If this source doesn't have a sourcemap, do nothing.
return;
}
const originalSources = urls.map(url =>
createOriginalSource(url, generatedSource, sourceMaps)
);
// TODO: check if this line is really needed, it introduces
// a lot of lag to the application.
const generatedSourceRecord = getSource(getState(), generatedSource.id);
await dispatch(loadSourceText(generatedSourceRecord));
dispatch(newSources(originalSources));
};
}
// If a request has been made to show this source, go ahead and
// select it.
function checkSelectedSource(source: Source) {
return async ({ dispatch, getState }: ThunkArgs) => {
const pendingLocation = getPendingSelectedLocation(getState());
if (!pendingLocation || !pendingLocation.url || !source.url) {
return;
}
const pendingUrl = pendingLocation.url;
const rawPendingUrl = getRawSourceURL(pendingUrl);
if (rawPendingUrl === source.url) {
if (isPrettyURL(pendingUrl)) {
return await dispatch(togglePrettyPrint(source.id));
}
await dispatch(
selectLocation({ ...pendingLocation, sourceId: source.id })
);
}
};
}
function checkPendingBreakpoints(sourceId) {
return async ({ dispatch, getState }: ThunkArgs) => {
// source may have been modified by selectLocation
const source = getSource(getState(), sourceId);
const pendingBreakpoints = getPendingBreakpointsForSource(
getState(),
source.get("url")
);
if (!pendingBreakpoints.size) {
return;
}
// load the source text if there is a pending breakpoint for it
await dispatch(loadSourceText(source));
const pendingBreakpointsArray = pendingBreakpoints.valueSeq().toJS();
for (const pendingBreakpoint of pendingBreakpointsArray) {
await dispatch(syncBreakpoint(sourceId, pendingBreakpoint));
}
};
}
/**
* Handler for the debugger client's unsolicited newSource notification.
* @memberof actions/sources
* @static
*/
export function newSource(source: Source) {
return async ({ dispatch, getState }: ThunkArgs) => {
const _source = getSource(getState(), source.id);
if (_source) {
return;
}
dispatch({ type: "ADD_SOURCE", source });
if (prefs.clientSourceMapsEnabled) {
dispatch(loadSourceMap(source));
}
dispatch(checkSelectedSource(source));
dispatch(checkPendingBreakpoints(source.id));
};
}
export function newSources(sources: Source[]) {
return async ({ dispatch, getState }: ThunkArgs) => {
const filteredSources = sources.filter(
source => !getSource(getState(), source.id)
);
if (filteredSources.length == 0) {
return;
}
dispatch({
type: "ADD_SOURCES",
sources: filteredSources
});
for (const source of filteredSources) {
dispatch(checkSelectedSource(source));
dispatch(checkPendingBreakpoints(source.id));
}
return Promise.all(
filteredSources.map(source => dispatch(loadSourceMap(source)))
);
};
}
| JavaScript | 0 | @@ -1099,20 +1099,283 @@
%7D;%0A%7D%0A%0A
+// TODO: It would be nice to make getOriginalURLs a safer api%0Aasync function loadOriginalSourceUrls(sourceMaps, generatedSource) %7B%0A try %7B%0A return await sourceMaps.getOriginalURLs(generatedSource);%0A %7D catch (e) %7B%0A console.error(e);%0A return null;%0A %7D%0A%7D%0A%0A
/**%0A
-
* @memb
@@ -1552,35 +1552,43 @@
ait
-sourceMaps.getOriginalURLs(
+loadOriginalSourceUrls(sourceMaps,
gene
@@ -1601,17 +1601,16 @@
ource);%0A
-%0A
if (
|
1ee8f0447a3cee59c695276256ff1d67f6d465ad | Create embed theme for STT | plugins/livedesk-embed/gui-resources/scripts/js/core/utils/str.js | plugins/livedesk-embed/gui-resources/scripts/js/core/utils/str.js | define(['utils/utf8'],function(utf8){
str = function(str){
this.init(str);
}
str.prototype = {
init: function(str) {
this.str = str;
},
format: function() {
var arg = arguments, idx = 0;
if (arg.length == 1 && typeof arg[0] == 'object')
arg = arg[0];
return this.str.replace(/%?%(?:\(([^\)]+)\))?([disr])/g, function(all, name, type) {
if (all[0] == all[1]) return all.substring(1);
var value = arg[name || idx++];
if(typeof value === 'undefined') {
return all;
}
return (type == 'i' || type == 'd') ? +value : utf8.decode(value);
});
},
toString: function() {
return utf8.decode(this.str);
}
};
return str;
}); | JavaScript | 0 | @@ -30,17 +30,17 @@
n(utf8)%7B
-%0D
+%0A
%09str = f
@@ -52,17 +52,17 @@
on(str)%7B
-%0D
+%0A
%09%09this.i
@@ -74,12 +74,12 @@
tr);
-%0D%09%7D%0D
+%0A%09%7D%0A
%09str
@@ -92,17 +92,17 @@
type = %7B
-%0D
+%0A
%09%09init:
@@ -116,17 +116,17 @@
n(str) %7B
-%0D
+%0A
%09%09%09this.
@@ -139,15 +139,15 @@
str;
-%0D
+%0A
%09%09%7D,%09
-%0D
+%0A
%09%09fo
@@ -164,17 +164,17 @@
tion() %7B
-%0D
+%0A
%09%09%09var a
@@ -197,17 +197,17 @@
idx = 0;
-%0D
+%0A
%09%09%09if (a
@@ -250,17 +250,17 @@
object')
-%0D
+%0A
%09%09%09%09arg
@@ -268,17 +268,17 @@
arg%5B0%5D;
-%0D
+%0A
%09%09%09retur
@@ -279,16 +279,28 @@
%09return
+utf8.decode(
this.str
@@ -368,17 +368,17 @@
type) %7B
-%0D
+%0A
%09%09%09 if
@@ -420,17 +420,17 @@
ring(1);
-%0D
+%0A
%09%09%09 var
@@ -461,17 +461,17 @@
++%5D;%09%09
-%0D
+%0A
%09%09%09 if(
@@ -501,17 +501,17 @@
ined') %7B
-%0D
+%0A
%09%09%09%09retu
@@ -521,16 +521,16 @@
all;
-%0D
+%0A
%09%09%09 %7D
-%0D
+%0A
%09%09%09
@@ -581,40 +581,28 @@
e :
-utf8.decode(
value
-);%0D
+;%0A
%09%09%09%7D)
-;%0D
+);%0A
%09%09%7D,
-%0D
+%0A
%09%09to
@@ -621,17 +621,17 @@
tion() %7B
-%0D
+%0A
%09%09%09retur
@@ -658,17 +658,17 @@
tr);
-%0D%09%09%7D%0D%09%7D;%0D
+%0A%09%09%7D%0A%09%7D;%0A
%09ret
@@ -679,8 +679,8 @@
str;
-%0D
+%0A
%7D);
|
9c2071517b629d69e0f3d98a738064fc76ff2bfa | upgrade flexible.js | src/flexible.js | src/flexible.js | /**
* author: WangLe
* github: [https://github.com/jiankafei]
* 博客: [https://jiankafei.github.io/]
*/
;(function(G, lib){
'use strict';
var doc = G.document,
de = doc.documentElement,
vp = doc.querySelector('meta[name=viewport]'),
ua = G.navigator.appVersion,
ds = 750, // 设计稿大小
maxW = 540, // 最大字体宽度
realDPR = G.devicePixelRatio,
dfDpr = de.getAttribute('data-dpr') || '',
dpr = !!dfDpr ? dfDpr : realDPR ? realDPR === Math.floor(realDPR) ? realDPR : 1 : 1,
scale = 1 / dpr,
flexible = lib.flexible || (lib.flexible = {}),
tid = null,
dt = deviceType(),
pcStyleEle = null, //给pc添加的样式元素
getW = function(){return de.getBoundingClientRect().width}; // 宽度
console.log(de.getBoundingClientRect().width);
// 为html元素添加data-dpr属性
de.setAttribute('data-dpr', dpr);
// pc上隐藏滚动条,宽度为414,并且为html和定位fixed元素添加宽度
dt === 'pc' && (pcStyleEle = addStylesheetRules('::-webkit-scrollbar{display: none !important}.fixed{position: fixed !important;left: 0 !important;right: 0 !important;}html, .fixed{margin-left: auto !important;margin-right: auto !important;width: '+ 414 * dpr +'px !important;}'));
// 缩放
vp.setAttribute('name', 'viewport');
vp.setAttribute('content', 'target-densitydpi=device-dpi, width=device-width, initial-scale=' + scale + ', minimum-scale=' + scale + ', maximum-scale=' + scale + ', user-scalable=no');
// 改变窗口
G.addEventListener('resize', function () {
clearTimeout(tid);
tid = G.setTimeout(trans, 300);
}, false);
G.addEventListener('pageshow', function (ev) {
ev.persisted && (clearTimeout(tid), tid = G.setTimeout(trans, 300));
}, false);
G.orientation !== undefined && G.addEventListener('orientationchange', function(){
clearTimeout(tid);
/*switch (G.orientation) {
case 0:
case 180:
console.log('portrait');
break;
case 90:
case -90:
console.log('landscape');
break;
}*/
tid = G.setTimeout(trans, 300);
}, false);
// 为body添加默认字体大小
'complete' === doc.readyState ? doc.body.style.fontSize = 12 * dpr + 'px' : doc.addEventListener('DOMContentLoaded', function (e) {
doc.body.style.fontSize = 12 * dpr + 'px';
}, false);
// 执行转换
trans();
// 为flexible对象添加属性
flexible.dpr = G.dpr = dpr;
flexible.trans = trans;
flexible.rem2px = function(d){
var val = G.parseFloat(d) * this.rem;
'string' === typeof d && d.match(/rem$/) && (val += 'px');
return val;
};
flexible.px2rem = function(d){
var val = G.parseFloat(d) / 100;
'string' === typeof d && d.match(/px$/) && (val += 'rem');
return val;
};
// 设置根字体大小
function trans(){
var realDPR = G.devicePixelRatio,
tempDpr = realDPR ? realDPR === Math.floor(realDPR) ? realDPR : 1 : 1;
tempDpr !== dpr && G.location.reload();
var w = getW();
w > maxW && (w = maxW);
var rem = G.parseFloat(dpr * w * 100 / ds);
de.style.fontSize = rem + 'px';
flexible.rem = G.rem = rem;
};
// 设备检测
function deviceType(){
var dt = 'pc';
/(iPhone|iPod|iPad)/i.test(ua) ? dt = 'ios' : /(Android)/i.test(ua) ? dt = 'android' : /(Windows Phone)/i.test(ua) ? dt = 'wp' : dt = 'pc';
return dt;
};
// 添加css规则
function addStylesheetRules(css) {
var head = de.firstElementChild,
style = doc.createElement('style');
style.type = 'text/css';
style.styleSheet && style.styleSheet.cssText ? style.styleSheet.cssText = css : style.appendChild(doc.createTextNode(css));
head.appendChild(style);
return style;
};
})(window, window.lib || (window.lib = {}));
| JavaScript | 0.000001 | @@ -618,32 +618,11 @@
%E7%B4%A0%0A%09%09
-getW = function()%7Breturn
+w =
de.
@@ -650,17 +650,16 @@
().width
-%7D
; // %E5%AE%BD%E5%BA%A6%0A
@@ -2680,26 +2680,8 @@
();%0A
-%09%09var w = getW();%0A
%09%09w
@@ -2702,16 +2702,40 @@
maxW);%0A
+%09%09console.log('w: '+w);%0A
%09%09var re
|
7881fc2c690dc6a7ab5b4194304731d3501390d0 | fix network handler test | test/businessTier/networkHandler/networkHandlerSpec.js | test/businessTier/networkHandler/networkHandlerSpec.js | /*jshint node: true, -W106 */
'use strict';
/*
* Name : networkHandlerSpec.js
* Module : UnitTest
* Location : /test/businessTier/networkHandler
*
* History :
*
* Version Date Programmer Description
* =========================================================
* 0.0.1 2015-05-29 Samuele Zanella Initial code
* =========================================================
*/
var NetworkHandler = require('../../../lib/businessTier/networkHandler/networkHandler.js');
var Socket=require('../../../lib/presentationTier/socket.js');
var assert = require('assert');
var request = require('superagent');
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
io.listen(5000);
var Routes=require('../../presentationTier/routes.js');
describe('NetworkHandler', function() {
it('returns null when there are no params', function() {
assert.strictEqual((new NetworkHandler()).hasOwnProperty('_app'), false);
});
it('returns null when passed invalid parameters', function() {
assert.strictEqual((new NetworkHandler('abc', 'def', 2)).hasOwnProperty('_app'), false);
});
it('set param values to properties', function() {
var nh1=new NetworkHandler(app, io, '/norris');
assert.deepEqual(nh1._app, app);
assert.deepEqual(nh1._io, io);
assert.deepEqual(nh1._norrisNamespace, '/norris');
assert.strictEqual(nh1._routes, new Routes(app, '/norris'));
});
describe('#createSocket', function() {
it('returns the created socket object', function() {
var nh1=new NetworkHandler(app, io, '/norris');
assert.deepEqual(nh1.createSocket('/page1'), new Socket(io, '/page1'));
});
});
describe('#addPageToRouting', function() {
it('adds the given page to the application routing', function() {
var nh1=new NetworkHandler(app, io, '/norris');
nh1.addPageToRouting('/page1');
request.post('localhost:3000/page').end(function(res){
assert.strictEqual(res.status,200);
});
});
});
}); | JavaScript | 0.000001 | @@ -820,16 +820,23 @@
('../../
+../lib/
presenta
|
130893b601bd94600e569058d5cce47194957981 | Fix TS2307 Cannot find module 'cesium/Sou.. error | scripts/webpack.common.js | scripts/webpack.common.js | /**
* Webpack common configuration.
* it:
* - Define the app entry point (./src) -> Where webpack will start compiling/bundling
* - Define where assets will be served at by our webserver (static/)
* - Clean previous build on each build
* - Generates the index.html file automatically by injecting bundled assets in it (css, js)
* - Allow to load html files as strings in js code (i.e: import htmlString from './myHtmlFile.html)
* - Allow to automatically generates the dependencies injection for angularJS components annotated with
* `'ngInject';` or `@ngInject` in comments. See https://docs.angularjs.org/guide/di
*/
const path = require('path');
var WebpackBuildNotifierPlugin = require('webpack-build-notifier');
const hslPaths = require(path.join( __dirname, '..', 'common_paths')); //TODO this should not be necessary
const DynamicPubPathPlugin = require('dynamic-pub-path-plugin');
const webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, '../main.ts'),
output: {
// Path where bundled files will be output
path: path.resolve(__dirname, '../dist'),
filename: 'hslayers-ng.js',
library: 'hslayers-ng',
libraryTarget:'umd'
},
// Just for build speed improvement
resolve: { symlinks: true,
extensions: ['.tsx', '.ts', '.js'],
modules: [
path.join(__dirname, '..'),
"../node_modules",
].concat(hslPaths.paths)
},
plugins: [
new DynamicPubPathPlugin({
'expression': `(window.HSL_PATH || './node_modules/hslayers-ng/dist/')`,
}),
// Clean before build
//new CleanWebpackPlugin()
new WebpackBuildNotifierPlugin({
title: "HsLayersNg",
suppressSuccess: false
}),
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
// For Angular 5, see also https://github.com/angular/angular/issues/20357#issuecomment-343683491
/\@angular(\\|\/)core(\\|\/)fesm5/,
'../', // location of your src
{
// your Angular Async Route paths relative to this root directory
}
)
],
module: {
rules: [
{
test: /\.ts?$/,
use: [
{ loader: 'ng-annotate-loader' },
'ts-loader'
],
exclude: /node_modules/,
},
{test: /\.xml$/, loader: 'raw-loader'},
{
// Mark files inside `@angular/core` as using SystemJS style dynamic imports.
// Removing this will cause deprecation warnings to appear.
test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
parser: { system: true }, // enable SystemJS
},
// Automatically generates $inject array for angularJS components annotated with:
// 'ngInject';
// or commented with /**@ngInject */
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
// Babel syntax dynamic import plugin allow babel to correctly parse js files
// using webpack dynamic import expression (i.e import('angular').then(...))
plugins: ['angularjs-annotate', '@babel/plugin-syntax-dynamic-import']
}
}
]
}
]
}
};
| JavaScript | 0.000001 | @@ -1355,16 +1355,29 @@
,%0A
+path.resolve(
%22../node
@@ -1385,16 +1385,17 @@
modules%22
+)
,%0A %5D.
@@ -2118,16 +2118,179 @@
)%0A %5D,%0A
+ amd: %7B%0A // Enable webpack-friendly use of require in Cesium%0A toUrlUndefined: true%0A %7D,%0A node: %7B%0A // Resolve node module use of fs%0A fs: 'empty'%0A %7D,%0A
module
|
f3f05a08e798245f0aa21035c4850aabc202e0f4 | fix issues with Base#destroy | domkit/ui/base.js | domkit/ui/base.js | define(
['jquery', 'domkit/domkit', 'domkit/util/touchclickcanceller'],
function ($, Domkit, TouchClickCanceller) {
var _DATA_FIELD_KEY = '_data_dk_object';
// Base extends any HTML element, giving providing common behaviors for all
// domkit ui elements.
// Arguments:
// jQueryOrDomID: A CSS style id selector or jQuery object.
// opt_createClickCancel: optional, prevents active click cancelling on
// touch events.
var Base = function (jQueryOrDomID, opt_preventClickCancel) {
var $element = Domkit.validateOrRetrieveJQueryObject(jQueryOrDomID);
this._$element = $element;
this._canceller = !opt_preventClickCancel ?
TouchClickCanceller.create($element) : null;
$element.data(_DATA_FIELD_KEY, this);
};
// Whether the element cancels clicks when processing touch events.
Base.prototype.cancelsTouchGeneratedClicks = function () {
return !!this._canceller;
};
// destroy the domkit ui element.
Base.prototype.destory = function () {
if (this._canceller) {
this._canceller.destroy();
this._canceller = null;
}
this._$element.data(_DATA_FIELD_KEY, null);
};
// getElement returns the jQuery object that the domkit ui element is built
// upon.
Base.prototype.getElement = function () {
return this._$element;
};
// create returns a domkit ui element for the given domID. If the instance
// already exists then the instance is returned, if not then a new instance
// is returned.
// Arguments:
// elementConstructor: function taking the element identifier and whether
// to cancel clicks.
// jQueryOrDomID: A CSS style id selector or jQuery object.
// opt_createClickCancel: optional, prevents active click cancelling on
// touch events.
Base.create = function (
elementConstructor, jQueryOrDomID, opt_preventClickCancel) {
var $element = Domkit.validateOrRetrieveJQueryObject(jQueryOrDomID);
var elementInstance = $element.data(_DATA_FIELD_KEY);
return elementInstance ?
elementInstance :
new elementConstructor($element, opt_preventClickCancel);
};
return Base;
});
| JavaScript | 0 | @@ -994,18 +994,18 @@
ype.dest
-o
r
+o
y = func
|
124dde6d61bded5fabfd9861f429623779642c20 | fix due date display | src/admin/redux/modules/member.js | src/admin/redux/modules/member.js | /* @flow */
const { createAction, handleAction } = require('redux-actions')
const { stopSubmit } = require('redux-form')
const { flip, replace, compose, map, prop, concat, converge, contains
, mergeAll, unapply, cond, T, identity, is, reject, propOr, chain, keys
, path, reduce, assoc, join, values, equals, assocPath, over, lens
, lensProp } =
require('ramda')
const { get_body, post } = require('app/http')
const { format: format_dated, standardise } = require('app/transform_dated')
const { format_due_date } = require('app/format_date')
import type { Action, Reducer } from 'redux'
const FETCHING_MEMBER =
'FETCHING_MEMBER'
export const FETCHED_MEMBER =
'MEMBER_FETCHED'
const DEACTIVATED_MEMBER =
'DEACTIVATED_MEMBER'
const REACTIVATED_MEMBER =
'REACTIVATED_MEMBER'
export const UPDATED_MEMBER =
'UPDATED_MEMBER'
const CREATED_MEMBER =
'CREATED_MEMBER'
const reducer: Reducer<{}, Action> =
(member = { }, { type, payload }) => {
switch (type) {
case FETCHED_MEMBER:
return prepare_for_form(payload)
case DEACTIVATED_MEMBER:
return (
{ ...member
, activation_status: { value: 'deactivated' }
, deletion_date: { value: new Date().toISOString() }
}
)
case REACTIVATED_MEMBER:
return (
{ ...member
, activation_status: { value: 'activated' }
, deletion_date: {}
, deletion_reason: { value: null }
}
)
case UPDATED_MEMBER:
return (
{ ...member
, ...prepare_for_form(payload)
})
case CREATED_MEMBER:
return typeof payload === 'string'
? { ...member, id: { value: payload } }
: member
default:
return member
}
}
const post_user_url = '/api/members/{ID}'
const get_user_url = '/members/{ID}'
const make_user_url = url => flip(replace('{ID}'))(url)
const null_to_undefined = val => val === null ? undefined : val
const parse_if_needed = cond(
[ [is(String), JSON.parse]
, [T, identity]
]
)
const pull_across = origin => destination =>
over(lens(path(origin), assocPath(destination)), identity)
const reshape = compose
( pull_across(['membership_type', 'value'])(['membership_type'])
, pull_across(['membership_type', 'amount'])(['subscription_amount'])
)
const reshape_if_necessary = (member) =>
typeof member.membership_type === 'object' ? reshape(member) : member
const prepare_for_form = (member) =>
({ ...wrap_values(member)
, other:
{ subscription_amount: member.subscription_amount
, payments: member.payments
}
})
const wrap_values = map((v) => (v && { value: String(v) }))
const to_member = compose
( over(lensProp('due_date'), format_due_date)
, format_dated
, reshape_if_necessary
, map(null_to_undefined)
, parse_if_needed
)
const flatten = converge
( unapply(mergeAll)
, map(propOr({}), ['personal', 'address', 'membership', 'edit'])
)
const has_errors = compose(Boolean, path(['body', 'error']))
const to_errors = (dispatch) => ({ body: { invalidAttributes } }) => {
const errors = reduce
( (errors, key) =>
assoc(key, invalidAttributes[key][0].message, errors)
, {}
, keys(invalidAttributes)
)
dispatch(
stopSubmit(
'member'
, { _error: join(' ', values(errors))
, ...errors
}
)
)
}
const id_value = compose(String, path(['body', 'id']))
const null_empty = map((v) => v == '' ? null : v)
const errors_or = (on_success) => (dispatch) =>
cond(
[ [has_errors, to_errors(dispatch)]
, [T, on_success]
]
)
const errors_or_to_member = errors_or(compose(to_member, prop('body')))
const error_id = errors_or(id_value)
export const fetch_member = createAction
( FETCHED_MEMBER
, compose(map(to_member), get_body, make_user_url(get_user_url))
)
export const update_member = createAction
( UPDATED_MEMBER
, (member, dispatch) => compose
( map(errors_or_to_member(dispatch))
, compose(post, null_empty, standardise)(member)
, make_user_url(post_user_url)
)(member.id)
)
export const deactivate_member = createAction(DEACTIVATED_MEMBER)
export const reactivate_member = createAction(REACTIVATED_MEMBER)
export const create_member = createAction
( CREATED_MEMBER
, (member, dispatch) =>
compose(map(error_id(dispatch)), flip(post)('addmember'), standardise)(member)
)
export default reducer
| JavaScript | 0.000002 | @@ -339,16 +339,23 @@
lensProp
+, slice
%7D =%0A
@@ -500,63 +500,8 @@
ed')
-%0Aconst %7B format_due_date %7D = require('app/format_date')
%0A%0Aim
@@ -2706,23 +2706,33 @@
'),
-format_due_date
+slice(0, -'/YYYY'.length)
)%0A
|
00181a6b43e0c2d8dd6004f41587e3aa3e24a916 | Test failure to initialize during first-run | test/firstrun/components/master-password-setup-test.js | test/firstrun/components/master-password-setup-test.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import waitUntil from "async-wait-until";
import chai, { expect } from "chai";
import chaiEnzyme from "chai-enzyme";
import React from "react";
import sinon from "sinon";
import { simulateTyping } from "test/common";
import mountWithL10n from "test/mocks/l10n";
import MasterPasswordSetup from
"src/webextension/firstrun/components/master-password-setup";
chai.use(chaiEnzyme());
describe("firstrun > components > master-password-setup", () => {
let wrapper;
beforeEach(() => {
sinon.spy(MasterPasswordSetup.prototype, "render");
wrapper = mountWithL10n(<MasterPasswordSetup/>);
browser.runtime.onMessage.addListener(() => {});
});
afterEach(() => {
MasterPasswordSetup.prototype.render.restore();
browser.runtime.onMessage.mockClearListener();
});
it("render <MasterPasswordSetup/>", () => {
expect(wrapper.find("h3")).to.have.text("eNTEr mASTEr pASSWORd");
});
it("submit matched password", () => {
simulateTyping(wrapper.find("input[name='password']"), "n0str0m0");
simulateTyping(wrapper.find("input[name='confirmPassword']"), "n0str0m0");
wrapper.find('button[type="submit"]').simulate("submit");
});
it("submit mismatched password", async() => {
simulateTyping(wrapper.find("input[name='password']"), "n0str0m0");
simulateTyping(wrapper.find("input[name='confirmPassword']"), "jonesy");
wrapper.find('button[type="submit"]').simulate("submit");
await waitUntil(() => MasterPasswordSetup.prototype.render.callCount === 4);
expect(wrapper).to.have.state(
"error", "Passwords do not match"
);
});
});
| JavaScript | 0.000001 | @@ -1801,13 +1801,428 @@
);%0A %7D);
+%0A%0A it(%22catch failures to initialize%22, async() =%3E %7B%0A browser.runtime.onMessage.mockClearListener();%0A browser.runtime.onMessage.addListener(() =%3E %7B%0A throw new Error();%0A %7D);%0A wrapper.find('button%5Btype=%22submit%22%5D').simulate(%22submit%22);%0A await waitUntil(() =%3E MasterPasswordSetup.prototype.render.callCount === 2);%0A expect(wrapper).to.have.state(%0A %22error%22, %22Could not initialize!%22%0A );%0A %7D);
%0A%7D);%0A
|
c1bcd24ace87b9a78b94f67186fc6f704898a2b6 | fix the test case on user admin controller | test/tests/controllers/admin/users/rgiUserAdminCtrl.js | test/tests/controllers/admin/users/rgiUserAdminCtrl.js | 'use strict';
/*jslint nomen: true newcap: true */
var describe, beforeEach, afterEach, it, inject, expect, sinon;
describe('rgiUserAdminCtrl', function () {
beforeEach(module('app'));
var $scope, rgiUserSrvc, rgiAssessmentSrvc;
beforeEach(inject(
function ($rootScope, $controller, _rgiUserSrvc_, _rgiAssessmentSrvc_) {
$scope = $rootScope.$new();
rgiUserSrvc = _rgiUserSrvc_;
rgiAssessmentSrvc = _rgiAssessmentSrvc_;
var data = [
{
assessments: [
{assessment_id: 'assessment-0-0'},
{assessment_id: 'assessment-0-1'}
]
},
{
assessments: [
{assessment_id: 'assessment-1-0'},
{assessment_id: 'assessment-1-1'}
]
}
];
var userQuerySpy = sinon.spy(function(uselessOptions, callback) {
callback(data);
});
var userQueryStub = sinon.stub(rgiUserSrvc, 'query', userQuerySpy);
var assessmentGetSpy = function(assessment) {
var detailsMap = {
'assessment-0-0': 'details-0-0',
'assessment-0-1': 'details-0-1',
'assessment-1-0': 'details-1-0',
'assessment-1-1': 'details-1-1'
};
return detailsMap[assessment.assessment_ID];
};
var assessmentGetStub = sinon.stub(rgiAssessmentSrvc, 'get', assessmentGetSpy);
$controller('rgiUserAdminCtrl', {$scope: $scope});
userQueryStub.restore();
assessmentGetStub.restore();
}
));
it('initializes sort options', function () {
_.isEqual($scope.sort_options, [
{value: 'firstName', text: 'Sort by First Name'},
{value: 'lastName', text: 'Sort by Last Name'},
{value: 'username', text: 'Sort by Username'},
{value: 'role', text: 'Sort by Role'},
{value: 'approved', text: 'Sort by Approved'},
{value: 'submitted', text: 'Sort by Submitted'}
]).should.be.equal(true);
});
it('sets sort order', function () {
$scope.sort_order.should.be.equal('lastName');
});
it('loads assessments data', function() {
_.isEqual($scope.users, [
{
assessments: [
{assessment_id: 'assessment-1-0', details: 'details-1-0'},
{assessment_id: 'assessment-1-1', details: 'details-1-1'}
]
},
{
assessments: [
{assessment_id: 'assessment-0-0', details: 'details-0-0'},
{assessment_id: 'assessment-0-1', details: 'details-0-1'}
]
}
]).should.be.equal(true);
});
});
| JavaScript | 0.000007 | @@ -1,12 +1,35 @@
+/*jslint node: true */%0A
'use strict'
@@ -70,16 +70,19 @@
e */%0Avar
+ _,
describ
@@ -496,16 +496,88 @@
tSrvc_;%0A
+ /*jshint unused: true*/%0A /*jslint unparam: true*/
%0A
@@ -675,34 +675,34 @@
%7Bassessment_
-id
+ID
: 'assessment-0-
@@ -734,34 +734,34 @@
%7Bassessment_
-id
+ID
: 'assessment-0-
@@ -886,34 +886,34 @@
%7Bassessment_
-id
+ID
: 'assessment-1-
@@ -945,34 +945,34 @@
%7Bassessment_
-id
+ID
: 'assessment-1-
@@ -1028,33 +1028,17 @@
%5D
-;%0A var
+,
userQue
@@ -1063,16 +1063,17 @@
function
+
(useless
@@ -1139,33 +1139,17 @@
%7D)
-;%0A var
+,
userQue
@@ -1207,26 +1207,9 @@
Spy)
-;%0A%0A var
+,
ass
@@ -1223,16 +1223,32 @@
GetSpy =
+%0A
functio
@@ -1248,16 +1248,17 @@
function
+
(assessm
@@ -1276,24 +1276,28 @@
+
+
var detailsM
@@ -1303,16 +1303,20 @@
Map = %7B%0A
+
@@ -1372,32 +1372,36 @@
+
'assessment-0-1'
@@ -1429,32 +1429,36 @@
+
+
'assessment-1-0'
@@ -1470,24 +1470,28 @@
tails-1-0',%0A
+
@@ -1550,12 +1550,20 @@
-%7D;%0A%0A
+ %7D;%0A%0A
@@ -1635,26 +1635,14 @@
-%7D;%0A
- var
+%7D,
ass
@@ -1713,16 +1713,91 @@
GetSpy);
+%0A /*jshint unused: false*/%0A /*jslint unparam: false*/
%0A%0A
@@ -2579,16 +2579,17 @@
function
+
() %7B%0A
@@ -2688,34 +2688,34 @@
%7Bassessment_
-id
+ID
: 'assessment-1-
@@ -2767,34 +2767,34 @@
%7Bassessment_
-id
+ID
: 'assessment-1-
@@ -2923,34 +2923,34 @@
%7Bassessment_
-id
+ID
: 'assessment-0-
@@ -3014,10 +3014,10 @@
ent_
-id
+ID
: 'a
|
9391de4702f07d6269d21d1f83bae558f5c70e42 | use the oribella instance from dependencies | src/gestures.js | src/gestures.js | import {customAttribute, bindable, inject} from "aurelia-framework";
class Gesture {
constructor(element, oribella, type) {
this.element = element;
this.oribella = oribella;
this.type = type;
}
bind() {
this.remove = this.oribella.on(this.element, this.type, {
selector: this.selector,
options: this.options,
start: this.start,
update: this.update,
end: this.end,
cancel: this.cancel,
timeEnd: this.timeEnd
});
}
unbind() {
this.remove();
}
}
@customAttribute("tap")
@inject(Element, "oribella")
export class Tap extends Gesture {
@bindable selector = undefined;
@bindable options = {};
@bindable start = function() {};
@bindable update = function() {};
@bindable end = function() {};
@bindable cancel = function() {};
constructor(element, oribella) {
super(element, oribella, "tap");
}
}
@customAttribute("doubletap")
@inject(Element, "oribella")
export class Doubletap extends Gesture {
@bindable selector = undefined;
@bindable options = {};
@bindable start = function() {};
@bindable update = function() {};
@bindable end = function() {};
@bindable cancel = function() {};
constructor(element, oribella) {
super(element, oribella, "doubletap");
}
}
@customAttribute("longtap")
@inject(Element, "oribella")
export class Longtap extends Gesture {
@bindable selector = undefined;
@bindable options = {};
@bindable start = function() {};
@bindable update = function() {};
@bindable end = function() {};
@bindable cancel = function() {};
@bindable timeEnd = function() {};
constructor(element, oribella) {
super(element, oribella, "longtap");
}
}
@customAttribute("swipe")
@inject(Element, "oribella")
export class Swipe extends Gesture {
@bindable selector = undefined;
@bindable options = {};
@bindable start = function() {};
@bindable update = function() {};
@bindable end = function() {};
@bindable cancel = function() {};
constructor(element, oribella) {
super(element, oribella, "swipe");
}
}
@customAttribute("longtap-swipe")
@inject(Element, "oribella")
export class LongtapSwipe extends Gesture {
@bindable selector = undefined;
@bindable options = {};
@bindable start = function() {};
@bindable update = function() {};
@bindable end = function() {};
@bindable cancel = function() {};
constructor(element, oribella) {
super(element, oribella, "longtapswipe");
}
}
@customAttribute("pinch")
@inject(Element, "oribella")
export class Pinch extends Gesture {
@bindable selector = undefined;
@bindable options = {};
@bindable start = function() {};
@bindable update = function() {};
@bindable end = function() {};
@bindable cancel = function() {};
constructor(element, oribella) {
super(element, oribella, "pinch");
}
}
@customAttribute("rotate")
@inject(Element, "oribella")
export class Rotate extends Gesture {
@bindable selector = undefined;
@bindable options = {};
@bindable start = function() {};
@bindable update = function() {};
@bindable end = function() {};
@bindable cancel = function() {};
constructor(element, oribella) {
super(element, oribella, "rotate");
}
}
| JavaScript | 0.000001 | @@ -61,16 +61,68 @@
mework%22;
+%0Aimport %7Boribella%7D from %22oribella-default-gestures%22;
%0A%0Aclass
@@ -153,26 +153,16 @@
element,
- oribella,
type) %7B
@@ -194,38 +194,8 @@
nt;%0A
- this.oribella = oribella;%0A
@@ -245,21 +245,16 @@
emove =
-this.
oribella
@@ -558,36 +558,24 @@
ject(Element
-, %22oribella%22
)%0Aexport cla
@@ -816,34 +816,24 @@
ctor(element
-, oribella
) %7B%0A supe
@@ -842,26 +842,16 @@
element,
- oribella,
%22tap%22);
@@ -899,36 +899,24 @@
ject(Element
-, %22oribella%22
)%0Aexport cla
@@ -1163,34 +1163,24 @@
ctor(element
-, oribella
) %7B%0A supe
@@ -1189,26 +1189,16 @@
element,
- oribella,
%22double
@@ -1250,36 +1250,24 @@
ject(Element
-, %22oribella%22
)%0Aexport cla
@@ -1549,34 +1549,24 @@
ctor(element
-, oribella
) %7B%0A supe
@@ -1571,34 +1571,24 @@
per(element,
- oribella,
%22longtap%22);
@@ -1632,36 +1632,24 @@
ject(Element
-, %22oribella%22
)%0Aexport cla
@@ -1892,34 +1892,24 @@
ctor(element
-, oribella
) %7B%0A supe
@@ -1918,26 +1918,16 @@
element,
- oribella,
%22swipe%22
@@ -1981,36 +1981,24 @@
ject(Element
-, %22oribella%22
)%0Aexport cla
@@ -2248,34 +2248,24 @@
ctor(element
-, oribella
) %7B%0A supe
@@ -2274,26 +2274,16 @@
element,
- oribella,
%22longta
@@ -2336,36 +2336,24 @@
ject(Element
-, %22oribella%22
)%0Aexport cla
@@ -2596,34 +2596,24 @@
ctor(element
-, oribella
) %7B%0A supe
@@ -2622,26 +2622,16 @@
element,
- oribella,
%22pinch%22
@@ -2686,20 +2686,8 @@
ment
-, %22oribella%22
)%0Aex
@@ -2943,26 +2943,16 @@
(element
-, oribella
) %7B%0A
@@ -2969,18 +2969,8 @@
ent,
- oribella,
%22ro
|
44e57b4978abb22a3e532b30e34cdcdc385dfec5 | Update open_VWSC.js | mac/resources/open_VWSC.js | mac/resources/open_VWSC.js | define(function() {
'use strict';
var transitionNames = [
null,
'wipeRight', 'wipeLeft', 'wipeDown', 'wipeUp',
'centerOutHorizontal', 'edgesInHorizontal',
'centerOutVertical', 'edgesInVertical',
'centerOutSquare', 'edgesInSquare',
'pushLeft', 'pushRight', 'pushDown', 'pushUp',
'revealUp', 'revealUpRight', 'revealRight', 'revealDownRight',
'revealDown', 'revealDownLeft', 'revealLeft', 'revealUpLeft',
'dissolvePixelsFast', 'dissolveBoxyRectangles',
'dissolveBoxySquares', 'dissolvePatterns',
'randomRows', 'randomColumns',
'coverDown', 'coverDownLeft', 'coverDownRight', 'coverLeft',
'coverRight', 'coverUp', 'coverUpLeft', 'coverUpRight',
'venetianBlinds', 'checkerboard',
'stripsBottomBuildLeft', 'stripsBottomBuildRight',
'stripsLeftBuildDown', 'stripsLeftBuildUp',
'stripsRightBuildDown', 'stripsRightBuildUp',
'stripsTopBuildLeft', 'stripsTopBuildRight',
'zoomOpen', 'zoomClose',
'verticalBlinds',
'dissolveBitsFast', 'dissolvePixels', 'dissolveBits',
];
var SPRITE_BYTES = 16; // 20
var SPRITE_COUNT = 49;
function FrameView(buffer, byteOffset, byteLength) {
Object.defineProperty(this, 'dv', {value:new DataView(buffer, byteOffset, byteLength)});
}
Object.defineProperties(FrameView.prototype, {
duration: {
get: function() {
var v = this.dv.getInt8(4);
return (v === 0) ? 'default'
: (v >= 1 && v <= 60) ? (1000 / v)
: (v <= -1 && v >= -30) ? (250 * -v)
: (v === -128) ? 'untilUserAction'
: (v >= -122 && v <= -121) ? ('untilAfterSound' + (-120 - v))
: 'untilAfterVideo' + (v + 121);
},
enumerable: true,
},
transition: {
get: function() {
var v = this.dv.getUint8(5);
return (v >= transitionNames.length) ? v : transitionNames[v];
},
enumerable: true,
},
audio1: {
get: function() {
return this.dv.getUint16(6, false);
},
enumerable: true,
},
audio2: {
get: function() {
return this.dv.getUint16(8, false);
},
enumerable: true,
},
script: {
get: function() {
return this.dv.getUint16(16, false);
},
enumerable: true,
},
palette: {
get: function() {
var v = this.dv.getInt16(0x14, false);
return (v === 0) ? 'default'
: (v < 0) ? ('system' + (-v))
: v;
},
enumerable: true,
},
sprites: {
get: function() {
var sprites = {};
var buffer = this.dv.buffer, byteOffset = this.dv.byteOffset + SPRITE_BYTES * 2;
for (var i = 1; i <= SPRITE_COUNT; i++) {
var spriteView = new FrameSpriteView(buffer, byteOffset, SPRITE_BYTES);
if (spriteView.cast) {
sprites[i] = spriteView;
}
byteOffset += SPRITE_BYTES;
}
Object.defineProperty(this, 'sprites', {value:sprites});
return sprites;
},
enumerable: true,
},
toJSON: {
get: function() {
return {
duration: this.duration,
transition: this.transition,
audio1: this.audio1,
audio2: this.audio2,
script: this.script,
palette: this.palette,
sprites: this.sprites,
};
},
},
});
function FrameSpriteView(buffer, byteOffset, byteLength) {
Object.defineProperty(this, 'dv', {value:new DataView(buffer, byteOffset, byteLength)});
}
Object.defineProperties(FrameSpriteView.prototype, {
cast: {
get: function() {
return this.dv.getUint16(6, false);
},
enumerable: true,
},
top: {
get: function() {
return this.dv.getInt16(8, false);
},
enumerable: true,
},
left: {
get: function() {
return this.dv.getInt16(10, false);
},
enumerable: true,
},
bottom: {
get: function() {
return this.dv.getInt16(12, false);
},
enumerable: true,
},
right: {
get: function() {
return this.dv.getInt16(14, false);
},
enumerable: true,
},
script: {
get: function() {
return this.dv.getUint16(16, false);
},
enumerable: true,
},
ink: {
get: function() {
var v = this.dv.getUint8(5) & 0xf;
switch (v) {
case 0x00: return 'copy';
case 0x01: return 'transparent';
case 0x02: return 'reverse';
case 0x03: return 'ghost';
case 0x04: return 'notCopy';
case 0x05: return 'notTransparent';
case 0x06: return 'notReverse';
case 0x07: return 'notGhost';
case 0x08: return 'matte';
case 0x09: return 'mask';
case 0x20: return 'blend';
case 0x21: return 'addPin';
case 0x22: return 'add';
case 0x23: return 'subtractPin';
case 0x25: return 'lightest';
case 0x26: return 'subtract';
case 0x27: return 'darkest';
default: return v;
}
},
enumerable: true,
},
toJSON: {
get: function() {
return {
cast: this.cast,
top: this.top,
left: this.left,
bottom: this.bottom,
right: this.right,
script: this.script,
ink: this.ink,
};
},
},
});
return function(item) {
return item.getBytes().then(function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (dv.getUint32(0, false) !== bytes.length) {
return Promise.reject('length does not match data');
}
var previousData = new Uint8Array(1024);
var dataObject = [];
var pos = 4;
while (pos < bytes.length) {
var frameData = new Uint8Array(previousData);
var endPos = pos + dv.getUint16(pos);
if (endPos === pos) break;
pos += 2;
while (pos < endPos) {
var patchLength = bytes[pos] * 2, patchOffset = bytes[pos + 1] * 2;
pos += 2;
var patch = bytes.subarray(pos, pos + patchLength);
pos += patchLength;
frameData.set(patch, patchOffset);
}
dataObject.push(new FrameView(frameData.buffer, frameData.byteOffset, frameData.byteLength));
}
item.setDataObject(dataObject);
previousData = frameData;
});
};
});
| JavaScript | 0.000001 | @@ -3067,35 +3067,37 @@
toJSON: %7B%0A
-get
+value
: function() %7B%0A
@@ -5175,35 +5175,37 @@
toJSON: %7B%0A
-get
+value
: function() %7B%0A
|
77161cea538d9fc7c0eadcebcd1c05f5a0052b2b | use es6 import for the demo | demo/js/index.js | demo/js/index.js | // Load the module.
var perfundo = require('perfundo');
// Initialize a perfundo Lightbox.
var myLightbox = new perfundo('.perfundo-js', {
disableHistory: true,
swipe: true
});
| JavaScript | 0 | @@ -17,31 +17,29 @@
le.%0A
-var perfundo = require(
+import Perfundo from
'per
@@ -44,17 +44,16 @@
erfundo'
-)
;%0A// Ini
|
689e5296b9e080c746177eeee7aa9166d791bbe8 | change install/update notification | dist/event.js | dist/event.js | /* global chrome */
var devtoolsPort = [];
var notifId = '';
chrome.runtime.onConnect.addListener(function (port) {
devtoolsPort.push(port);
});
var dsDebug = (chrome.runtime.id === 'ikbablmmjldhamhcldjjigniffkkjgpo' ? false : true);
function addBlocking() {
removeBlocking();
if (chrome.declarativeWebRequest)
chrome.declarativeWebRequest.onRequest.addRules([{
id: 'dataslayerBlocking',
conditions: [
new chrome.declarativeWebRequest.RequestMatcher({
url: {
hostSuffix: 'google-analytics.com',
pathPrefix: '/collect',
schemes: ['http', 'https']
},
}),
new chrome.declarativeWebRequest.RequestMatcher({
url: {
hostSuffix: 'google-analytics.com',
pathPrefix: '/__utm.gif',
schemes: ['http', 'https']
},
}),
new chrome.declarativeWebRequest.RequestMatcher({
url: {
hostSuffix: 'stats.g.doubleclick.net',
pathPrefix: '/__utm.gif',
schemes: ['http', 'https']
},
}),
new chrome.declarativeWebRequest.RequestMatcher({
url: {
hostSuffix: 'doubleclick.net',
pathPrefix: '/activity',
schemes: ['http', 'https']
},
}),
new chrome.declarativeWebRequest.RequestMatcher({
url: {
pathPrefix: '/b/ss',
queryContains: 'AQB=1',
schemes: ['http', 'https']
},
})
],
actions: [
new chrome.declarativeWebRequest.RedirectToTransparentImage()
]
}]);
}
function removeBlocking() {
if (chrome.declarativeWebRequest)
chrome.declarativeWebRequest.onRequest.removeRules(['dataslayerBlocking']);
}
chrome.storage.sync.get(null, function (items) {
if (items.hasOwnProperty('blockTags') && items.blockTags === true) addBlocking();
else removeBlocking();
});
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (dsDebug) console.log(message);
if (message.type === 'dataslayer_gtm_push' || message.type === 'dataslayer_gtm' || message.type === 'dataslayer_tlm' || message.type === 'dataslayer_tco' || message.type === 'dataslayer_var' || message.type === 'dataslayer_dtm') {
message.tabID = sender.tab.id;
devtoolsPort.forEach(function (v, i, x) {
try {
v.postMessage(message);
} catch (e) {
console.log(e);
}
});
} else if (message.type === 'dataslayer_pageload' || message.type === 'dataslayer_opened') {
chrome.tabs.executeScript(message.tabID, {
file: 'content.js',
runAt: 'document_idle',
allFrames: true
});
} else if (message.type === 'dataslayer_refresh') {
chrome.tabs.sendMessage(message.tabID, {
ask: 'refresh'
});
} else if (message.type === 'dataslayer_unload')
chrome.tabs.executeScript(message.tabID, {
code: 'document.head.removeChild(document.getElementById(\'dataslayer_script\'));',
runAt: "document_idle"
});
else if (message.type === 'dataslayer_loadsettings') {
if (message.data.blockTags)
addBlocking();
else
removeBlocking();
devtoolsPort.forEach(function (v, i, x) {
v.postMessage(message);
});
}
});
chrome.runtime.onInstalled.addListener(function (details) {
// if (details.reason === 'install')
// chrome.tabs.create({
// url: 'chrome-extension://' + chrome.runtime.id + '/options.html#install',
// active: true
// });
if ((details.reason === 'update') && (!dsDebug)) {
chrome.notifications.create('', {
type: 'basic',
title: 'dataslayer' + (dsDebug ? ' beta' : ''),
message: 'dataslayer' + (dsDebug ? ' beta' : '') + ' has been updated to version ' + chrome.runtime.getManifest().version + '.',
iconUrl: 'i128.png'
},
function (notificationId) {
notifId = notificationId;
}
);
// chrome.notifications.onClicked.addListener(function (notificationId) {
// if (notificationId == notifId) chrome.tabs.create({
// url: 'chrome-extension://' + chrome.runtime.id + '/options.html#whatsnew',
// active: true
// });
// });
}
}); | JavaScript | 0 | @@ -3073,19 +3073,16 @@
ils) %7B%0A%09
-//
if (deta
@@ -3108,19 +3108,16 @@
tall')%0A%09
-//
%09chrome.
@@ -3131,27 +3131,24 @@
eate(%7B%0A%09
-//
%09%09url: '
chrome-e
@@ -3143,80 +3143,55 @@
l: '
-chrome-extension://' + chrome.runtime.id + '/options.html#install
+https://bearcla.ws/dataslayer/#releaseNotes
',%0A%09
-//
%09%09ac
@@ -3202,19 +3202,16 @@
: true%0A%09
-//
%09%7D);%0A%09if
@@ -3496,16 +3496,50 @@
ion + '.
+%5Cn%5CnClick here to see what%5C's new.
',%0A%09%09%09%09i
@@ -3636,19 +3636,16 @@
%0A%09%09);%0A%09%09
-//
chrome.n
@@ -3709,19 +3709,16 @@
Id) %7B%0A%09%09
-//
%09if (not
@@ -3768,19 +3768,16 @@
%7B%0A%09%09
-//
%09%09url: '
chro
@@ -3776,82 +3776,56 @@
l: '
-chrome-extension://' + chrome.runtime.id + '/options.html#whatsnew
+https://bearcla.ws/dataslayer/#releaseNotes
',%0A%09%09
-//
%09%09ac
@@ -3841,21 +3841,15 @@
e%0A%09%09
-//
%09%7D);%0A%09%09
-//
%7D);%0A
|
2c0a14cefd43802649380327155e66ff60c99903 | Fix typo | calibrate.js | calibrate.js | var app = Argon.init();
app.context.setDefaultReferenceFrame(app.context.localOriginEastNorthUp);
//is there a better way to access the video element?
var video = Argon.ArgonSystem.instance.container.get(Argon.LiveVideoRealityLoader).videoElement;
var flow = new oflow.VideoFlow(video);
var dx = 0;
flow.onCalculated((dir) => { dx += dir.u; });
var button = document.getElementById("calibrateButton");
var Quaternion = Argon.Cesium.Quaternion;
function calibrate() {
button.disabled = true;
dx = 0;
var oldOrientation = Quaternion.clone(app.context.getEntityPose(app.device.displayEntity).orientation);
console.log(oldOrientation);
flow.startCapture();
window.setTimeout(endCalibration, 5000, oldOrientation);
}
function endCalibration(oldOrientation) {
flow.stopCapture();
var newOrientation = app.context.getEntityPose(app.device.displayEntity).orientation;
console.log("old: " + oldOrientation);
console.log("new: " + newOrientation);
var inverse = new Quaternion();
Quaternion.inverse(oldOrientation, inverse);
var difference = new Quaternion();
Quaternion.inverse(newOrientation, inverse, difference);
var theta = Quaternion.computeAngle(difference);
var f = dx / 2 * Math.tan(0.5 * theta);
var approxFov = 2 * Math.atan(video.videoWidth / 2 * f);
console.log("dx = " + dx);
console.log("theta = " + theta);
console.log("fov = " + approxFov);
button.disabled = false;
} | JavaScript | 0.999999 | @@ -1127,23 +1127,24 @@
ternion.
-inverse
+multiply
(newOrie
@@ -1333,20 +1333,16 @@
2 * f);%0A
-
%0A con
|
e8a62a28548ac045f8c6d6297063da8d088d5c9a | Remove TODOs (created issues #2 and #3 instead) | dropbox-fetch.js | dropbox-fetch.js | const assert = require('assert-plus');
const fetch = require('node-fetch');
/**
* The authorization token with which calls to the API are made.
* @type {String}
*/
let _token = '';
const API_VERSION = '2/';
const AUTHORIZE_ENDPOINT = 'https://www.dropbox.com/oauth2/authorize';
const CONTENT_UPLOAD_ENDPOINT = 'https://content.dropboxapi.com/';
/**
* Authorize via OAuth 2.0 for Dropbox API calls.
*
* @parameter {string} clientId your app's key
* @parameter {string} redirectUri the uri where the user should be redirected
* to, after authorization has completed
* @return {function} a promise that resolves or fails both with the returned
* HTTP status code
*/
const authorize = (clientId, redirectUri = '') => {
return new Promise((resolve, reject) => {
reject('Not implemented yet, please obtain a token manually and store it via setToken');
});
};
/**
* Set the token that is used for all Dropbox API calls to the given value.
* If you set this value, you can omit the `token` parameter in all the calls
* to this library.
* @param {string} t The new token value.
*/
const setToken = (token) => {
if (typeof token !== 'string') {
throw new Error('invalid argument ' + token + ' (expected: string)');
}
_token = token;
};
/**
* Generic function for posting some content to a given endpoint using a certain
* API method. If no wrapper function for the method you need exists, feel free
* to use this for your calls to the Dropbox API.
*
* See https://www.dropbox.com/developers/documentation/http/documentation for
* the documentation of the Dropbox HTTP API.
*
* @param {string} apiMethod the method to call
* @param {object} apiArgs an object that is passed as the Dropbox-API-Arg header
* @param {string} content the content to upload (e.g. the file content you
* whish to upload)
* @param {string?} endpoint the URL endpoint to use; defaults to
* https://content.dropboxapi.com as this is used for all file operations,
* which are most frequently used when operating on a dropbox
* @param {string?} token your Dropbox API token
* (defaults to the value set via setToken`)
* @return {function} a promise that, depending on if your call was successfull,
* either resolves or rejects with the answer from the Dropbox HTTP Api
*/
const post = (
apiMethod,
apiArgs,
content,
endpoint = CONTENT_UPLOAD_ENDPOINT,
token = _token
) => {
assert.string(apiMethod, 'invalid argument ' + apiMethod + ' (expected: string)');
assert.object(apiArgs, 'invalid argument ' + apiArgs + ' (expected: object)');
assert.string(content, 'invalid argument ' + content + ' (expected: string)');
assert.string(endpoint, 'invalid argument ' + endpoint + ' (expected: string)');
assert.string(token, 'invalid argument ' + token + ' (expected: string)');
/*
* TODO:
* - Add checks for leading and trailing slashes in the path etc. and add
* and / or remove them if necessary
* - Check if the given endpoint is a URL
*/
return fetch(endpoint + API_VERSION + apiMethod, {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
'Authorization': 'Bearer ' + token,
'Dropbox-API-Arg': JSON.stringify(apiArgs)
},
body: content
});
};
/**
* Upload the given file to the dropbox.
* @param {object} file an object describing the file, consisting of:
* - {string} path the path in the dropbox where the file should
* be uploaded to (with a leading slash)
* - {string} mode what to do when the file already exists ('add', 'overwrite' or 'update')
* - {boolean} autorename
* - {boolean} mute
* @param {string} content the content that should be written to the file
* described in the apiArgs parameter
* @param {string?} token the OAuth 2 token that is used to access your app;
* can be omitted (in this case, the token that is set via ``setToken` is used)
* @return {function} a promise that resolves when the upload is complete or
* fails with an error message
*/
const upload = (
{
path,
mode = 'add',
autorename = true,
mute = false
},
content,
token = _token
) => {
assert.string(path); // TODO: Check if this is a valid path with a leading forward slash / add the leading slash if it is missing
assert.string(mode);
assert.bool(autorename);
assert.bool(mute);
return post('files/upload', { path, mode, autorename, mute }, content, CONTENT_UPLOAD_ENDPOINT, token);
};
module.exports = {
AUTHORIZE_ENDPOINT,
CONTENT_UPLOAD_ENDPOINT,
authorize,
setToken,
post,
upload
};
| JavaScript | 0 | @@ -2815,190 +2815,8 @@
);%0A%0A
- /*%0A * TODO:%0A * - Add checks for leading and trailing slashes in the path etc. and add%0A * and / or remove them if necessary%0A * - Check if the given endpoint is a URL%0A */%0A%0A
re
@@ -3978,117 +3978,8 @@
th);
- // TODO: Check if this is a valid path with a leading forward slash / add the leading slash if it is missing
%0A a
|
23367bd69f3b293ec5a338914937c2ae81f11bf5 | Add prefix setting to Tailwind | web/tailwind.config.js | web/tailwind.config.js | module.exports = {
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
| JavaScript | 0 | @@ -151,10 +151,27 @@
ns: %5B%5D,%0A
+ prefix: 'tw-',%0A
%7D%0A
|
5f357a498242243872e1236c4c6856215204639e | Add `Buffer` to no-redeclare whitelist | etc/eslint/rules/stdlib.js | etc/eslint/rules/stdlib.js | 'use strict';
/**
* ESLint rules specific to stdlib.
*
* @namespace rules
*/
var rules = {};
/**
* Require an empty line before single-line comments.
*
* @name empty-line-before-comment
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* function square( x ) {
* var out;
* // Square the number:
* out = x*x;
* return out;
* }
*
* @example
* // Good...
* function square( x ) {
* var out;
*
* // Square the number:
* out = x*x;
* return out;
* }
*/
rules[ 'stdlib/empty-line-before-comment' ] = 'error';
/**
* Enforce that require() calls have only string literals as parameters.
*
* @name no-dynamic-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var pkg = '@stdlib/math/base/special/betainc';
* var betainc = require( pkg );
*
* @example
* // Good...
* var betainc = require( '@stdlib/math/base/special/betainc' );
*/
rules[ 'stdlib/no-dynamic-require' ] = 'error';
/**
* Disallow require() calls of another package's internals.
*
* @name no-internal-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var betainc = require( '@stdlib/math/base/special/betainc/lib/index.js' );
*
* @example
* // Good...
* var betainc = require( '@stdlib/math/base/special/betainc' );
*/
rules[ 'stdlib/no-internal-require' ] = 'error';
/**
* Never allow a variable to be declared multiple times within the same scope or for built-in globals to be redeclared.
*
* @name no-redeclare
* @memberof rules
* @type {Array}
* @default [ 'error', { 'builtinGlobals': false, 'globalsWhitelist': [] } ]
* @see [no-redeclare]{@link http://eslint.org/docs/rules/no-redeclare}
*
* @example
* // Bad...
* var a = 'beep';
* // ...
* var a = 'boop';
*
* @example
* // Good...
* var a = 'beep';
* // ...
* a = 'boop';
*/
rules[ 'stdlib/no-redeclare' ] = [ 'error', {
'builtinGlobals': true,
'globalsWhitelist': [
'Float32Array',
'Float64Array',
'Int8Array',
'Int16Array',
'Int32Array',
'Uint8Array',
'Uint8ClampedArray',
'Uint16Array',
'Uint32Array'
]
}];
/**
* Enforce that require() calls of files end with a whitelisted file extension.
*
* @name require-file-extensions
* @memberof rules
* @type {Array}
* @default [ 'error', { 'extensionsWhitelist': [ '.js', '.json', '.node' ] } ]
*
* @example
* // Bad...
*
* // Invalid file extension:
* var readme = require( '@stdlib/types/array/int32/README.md' );
*
* // Missing file extension:
* var debug = require( 'debug/src/browser' );
*
* @example
* // Good...
*
* var Int32Array = require( '@stdlib/types/array/int32' );
*
* var debug = require( 'debug/src/browser.js' );
*/
rules[ 'stdlib/require-file-extensions' ] = [ 'off', { // TODO: Enable once all @stdlib/tools packages are moved to @stdlib/_tools
'extensionsWhitelist': [
'.js',
'.json',
'.node'
]
}];
/**
* Enforce that typed array constructors are explicitly required.
*
* @name require-typed-arrays
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var arr = new Float32Array();
*
* @example
* // Good...
* var Float32Array = require( '@stdlib/types/array/float32' );
*
* var arr = new Float32Array();
*/
rules[ 'stdlib/require-typed-arrays' ] = 'error';
/**
* Enforce that typed array constructors are explicitly required.
*
* @name section-headers
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad... (require two trailing slashes)
*
* // EXPORTS
*
* module.exports = {};
*
* @example
* // Bad... (require a known header type)
*
* // EXPRTS //
*
* module.exports = {};
*
* @example
* // Bad... (require all uppercase letters)
*
* // EXPorts //
*
* module.exports = {};
*
* @example
* // Good...
*
* // EXPORTS //
*
* module.exports = {};
*/
rules[ 'stdlib/section-headers' ] = 'error';
// EXPORTS //
module.exports = rules;
| JavaScript | 0.000001 | @@ -2075,16 +2075,28 @@
32Array'
+,%0A%09%09'Buffer'
%0A%09%5D%0A%7D%5D;%0A
|
8bca4ec886c517df4e4462e3be47458637102773 | Add missing space | templates/system/modules/pwa/themes/base/js/sw-register.js | templates/system/modules/pwa/themes/base/js/sw-register.js | /*
* Author: Pierre-Henry Soria <hello@ph7cms.com>
* Copyright: (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
*/
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('[$url_root]service-worker.js', {
scope: '/'
}).then(function (registration) {
console.log('Service Worker registered on scope:' + registration.scope);
}).catch(function (error) {
console.log('Service Worker registration has failed: ', error);
});
navigator.serviceWorker.getRegistrations().then(function (registrations) {
registrations.forEach(function (registration) {
if (!isBaseUrl(registration.scope)) {
return registration.unregister();
}
});
});
}
function isBaseUrl(scope) {
const url = new URL(scope);
return url.pathname === '/';
}
| JavaScript | 0.023392 | @@ -457,16 +457,17 @@
n scope:
+
' + regi
|
92fbd1e6e692d0300a3be5e3965d2dc54dc4ca7f | Store ship name in closure; fix disable comms | eugene/static/js/eugene.js | eugene/static/js/eugene.js | $(document).ready(function() {
var timerID = null;
var updateMessages = function updateMessages(msgs) {
// Takes list of {sender, text} objects.
var allMessages = $('#message-table tbody').children();
var firstID = -1;
if (allMessages.length > 0) {
firstID = allMessages.first().data('msg-id');
}
for (var i = 0; i < msgs.length; i++) {
var msg = msgs[i];
if (msg.id <= firstID) {
continue;
}
// GROSS!
var new_row = $('<tr class="msg-data">' +
'<td>' + msg.created + '</td>' +
'<td>' + msg.sender + '</td>' +
'<td>' + msg.text + '</td></tr>');
new_row.data('msg-id', msg.id);
new_row.insertBefore('#message-table tbody tr:first-child');
}
};
var getNewMessages = function getNewMessages() {
var ship_name = $('body').data('ship-name');
if (!ship_name) {
return;
}
$.ajax({
type: 'GET',
url: '/api/v1/message/' + ship_name,
dataType: 'json',
success: function(resp, status, jqxhr) {
updateMessages(resp.messages);
}});
};
var timerClick = function timerClick() {
getNewMessages();
timerID = window.setTimeout(timerClick, 5000);
};
$('#enable-comms').click(function(event) {
event.preventDefault();
// Set everything up
var name = $('#ship-name-input').val().toUpperCase();
$('#ship-name').text('COMMS: ' + name);
$('title').text('C: ' + name);
$('body').data('ship-name', name);
$('#message-table tbody tr.msg-data').empty();
// Hide login form and unhide display
$('#comms-name-form').addClass('hidden');
$('#comms-display').removeClass('hidden');
timerClick();
});
$('#disable-comms').click(function(event) {
event.preventDefault();
window.clearTimeout(timerID);
timerID = null;
// Tell the server we're offlline.
$.ajax({
type: 'POST',
url: '/api/v1/user/' + ship_name,
data: JSON.stringify({
available: false
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
// Disable things
$('#ship-name').text('COMMS');
$('title').text('(C: ' + $('body').data('ship-name') + ')');
$('body').data('ship-name', '');
// Hide display and unhide login form
$('#comms-name-form').removeClass('hidden');
$('#comms-display').addClass('hidden');
});
$('#send-message').click(function(event) {
event.preventDefault();
var name = $('body').data('ship-name');
var msg = $('#message-input').val();
if (msg) {
// quick sanitize of msg.
msg = msg.toUpperCase();
msg = msg.replace(/[<>'"\\\/]/g, '.');
$.ajax({
type: 'POST',
url: '/api/v1/message',
data: JSON.stringify({
sender: name,
recipient: 'EVERYONE',
text: msg
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
$('#message-input').val('');
getNewMessages();
}
});
});
| JavaScript | 0 | @@ -43,24 +43,50 @@
erID = null;
+%0A var ship_name = null;
%0A%0A var up
@@ -993,61 +993,8 @@
) %7B%0A
- var ship_name = $('body').data('ship-name');%0A
@@ -1543,36 +1543,37 @@
hing up%0A
-var
+ship_
name = $('#ship-
@@ -1643,24 +1643,29 @@
'COMMS: ' +
+ship_
name);%0A
@@ -1691,16 +1691,21 @@
'C: ' +
+ship_
name);%0A
@@ -1739,16 +1739,21 @@
-name',
+ship_
name);%0A
@@ -2059,32 +2059,59 @@
ventDefault();%0A%0A
+ if (timerID) %7B%0A
window.c
@@ -2132,32 +2132,36 @@
merID);%0A
+
timerID = null;%0A
@@ -2155,24 +2155,91 @@
erID = null;
+%0A %7D%0A%0A if (!ship_name) %7B%0A return;%0A %7D
%0A%0A //
@@ -2683,49 +2683,8 @@
)');
-%0A $('body').data('ship-name', '');
%0A%0A
@@ -2922,56 +2922,8 @@
);%0A%0A
- var name = $('body').data('ship-name');%0A
@@ -3232,32 +3232,32 @@
SON.stringify(%7B%0A
-
@@ -3268,16 +3268,21 @@
sender:
+ship_
name,%0A
|
3fc61e2bc319fa2cf61d113d9f277cdfd1fc441c | fix typo | dropbox_server.js | dropbox_server.js | DropboxOauth = {};
OAuth.registerService('dropbox', 2, null, function(query) {
var response = getTokenResponse(query);
var accessToken = response.accessToken;
var identity = getIdentity(accessToken);
var serviceData = {
id: identity.uid,
accessToken: accessToken,
expiresAt: (+new Date()) + (1000 * response.expiresIn)
};
// include all fields from dropbox
// https://www.dropbox.com/developers/core/docs#account-info
var fields = _.pick(identity, ['display_name', 'country']);
return {
serviceData: serviceData,
options: {
profile: fields
}
};
});
// checks whether a string parses as JSON
var isJSON = function (str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
};
// returns an object containing:
// - accessToken
// - expiresIn: lifetime of token in seconds
var getTokenResponse = function (query) {
var config = ServiceConfiguration.configurations.findOne({service: 'dropbox'});
if (!config)
throw new ServiceConfiguration.ConfigError("Service not configured");
var responseContent;
try {
// Request an access token
responseContent = Meteor.http.post(
"https://api.dropbox.com/1/oauth2/token", {
auth: [config.appId, config.secret].join(':'),
params: {
grant_type: 'authorization_code',
code: query.code,
redirect_uri: Meteor.absoluteUrl("_oauth/dropbox?close")
}
}).content;
} catch (err) {
throw new Error("Failed to complete OAuth handshake with dropbox. " + err.message);
}
// If 'responseContent' does not parse as JSON, it is an error.
if (!isJSON(responseContent)) {
throw new Error("Failed to complete OAuth handshake with dropbox. " + responseContent);
}
// Success! Extract access token and expiration
var parsedResponse = JSON.parse(responseContent);
var accessToken = parsedResponse.access_token;
var expiresIn = parsedResponse.expires_in;
if (!accessToken) {
throw new Error("Failed to complete OAuth handshake with dropbox " +
"-- can't find access token in HTTP response. " + responseContent);
}
return {
accessToken: accessToken,
expiresIn: expiresIn
};
};
var getIdentity = function (accessToken) {
try {
return Meteor.http.get("https://api.dropbox.com/1/account/info", {
headers: { "Authorization": 'bearer ' + accessToken }
}).data;
} catch (err) {
throw new Error("Failed to fetch identity from dropbox. " + err.message);
}
};
DropboxOauth.retrieveCredential = function(credentialToken, credentialSecret) {
return OAuth.retrieveCredential(credentialToken, credentialSecret);
};
| JavaScript | 0.999991 | @@ -1245,11 +1245,14 @@
fig.
-app
+client
Id,
@@ -2357,17 +2357,16 @@
ders: %7B
-%22
Authoriz
@@ -2374,13 +2374,12 @@
tion
-%22
: '
-b
+B
eare
|
516ca63b252fea6148805fe86c73fb4af4beb62f | Use ES5 in examples/inject_ol_cesium.js | examples/inject_ol_cesium.js | examples/inject_ol_cesium.js | (function() {
const mode = window.location.href.match(/mode=([a-z0-9\-]+)\&?/i);
const isDev = mode && mode[1] === 'dev';
window.IS_DEV = isDev;
const cs = isDev ? 'CesiumUnminified/Cesium.js' : 'Cesium/Cesium.js';
window.CESIUM_URL = `../node_modules/@camptocamp/cesium/Build/${cs}`;
if (!window.LAZY_CESIUM) {
document.write(`<scr${'i'}pt type="text/javascript" src="${window.CESIUM_URL}"></scr${'i'}pt>`);
}
})();
| JavaScript | 0.000001 | @@ -1,25 +1,155 @@
-(function() %7B%0A const
+// This file is ES5 on purpose.%0A// It does not go through webpack; it is directly loaded by the html.%0A(function() %7B%0A /* eslint-disable no-var */%0A var
mod
@@ -208,21 +208,19 @@
?/i);%0A
-const
+var
isDev =
@@ -278,13 +278,11 @@
;%0A
-const
+var
cs
@@ -548,16 +548,46 @@
%3E%60);%0A %7D
+%0A%0A /* eslint-enable no-var */
%0A%7D)();%0A%0A
|
9cb4577c63132e8c2ef2db3e6d2bde8865f180e1 | add auth obj in options if set in config | mailer.js | mailer.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var qs = require('querystring')
var P = require('bluebird')
var nodemailer = require('nodemailer')
module.exports = function (log) {
function Mailer(translator, templates, config) {
var options = {
host: config.host,
secureConnection: config.secure,
port: config.port
}
this.mailer = nodemailer.createTransport('SMTP', options)
this.sender = config.sender
this.verificationUrl = config.verificationUrl
this.passwordResetUrl = config.passwordResetUrl
this.accountUnlockUrl = config.accountUnlockUrl
this.translator = translator
this.templates = templates
}
Mailer.prototype.stop = function () {
this.mailer.close()
}
Mailer.prototype.send = function (message) {
log.info({ op: 'mailer.send', email: message && message.to })
var d = P.defer()
this.mailer.sendMail(
message,
function (err, status) {
log.trace(
{
op: 'mailer.send.1',
err: err && err.message,
status: status && status.message,
id: status && status.messageId
}
)
return err ? d.reject(err) : d.resolve(status)
}
)
return d.promise
}
Mailer.prototype.verifyEmail = function (message) {
log.trace({ op: 'mailer.verifyEmail', email: message.email, uid: message.uid })
var translator = this.translator(message.acceptLanguage)
var query = {
uid: message.uid,
code: message.code
}
if (message.service) { query.service = message.service }
if (message.redirectTo) { query.redirectTo = message.redirectTo }
if (message.resume) { query.resume = message.resume }
var link = this.verificationUrl + '?' + qs.stringify(query)
var values = {
translator: translator,
link: link,
email: message.email
}
var localized = this.templates.verifyEmail(values)
var email = {
sender: this.sender,
to: message.email,
subject: translator.gettext('Verify your account'),
text: localized.text,
html: localized.html,
headers: {
'X-Uid': message.uid,
'X-Verify-Code': message.code,
'X-Service-ID': message.service,
'X-Link': link,
'Content-Language': translator.language
}
}
return this.send(email)
}
Mailer.prototype.recoveryEmail = function (message) {
log.trace({ op: 'mailer.recoveryEmail', email: message.email })
var translator = this.translator(message.acceptLanguage)
var query = {
token: message.token,
code: message.code,
email: message.email
}
if (message.service) { query.service = message.service }
if (message.redirectTo) { query.redirectTo = message.redirectTo }
if (message.resume) { query.resume = message.resume }
var link = this.passwordResetUrl + '?' + qs.stringify(query)
var values = {
translator: translator,
link: link,
email: message.email,
code: message.code
}
var localized = this.templates.recoveryEmail(values)
var email = {
sender: this.sender,
to: message.email,
subject: translator.gettext('Reset your password'),
text: localized.text,
html: localized.html,
headers: {
'X-Recovery-Code': message.code,
'X-Link': link,
'Content-Language': translator.language
}
}
return this.send(email)
}
Mailer.prototype.unlockEmail = function (message) {
log.trace({ op: 'mailer.unlockEmail', email: message.email, uid: message.uid })
var translator = this.translator(message.acceptLanguage)
var query = {
uid: message.uid,
code: message.code
}
if (message.service) { query.service = message.service }
if (message.redirectTo) { query.redirectTo = message.redirectTo }
if (message.resume) { query.resume = message.resume }
var link = this.accountUnlockUrl + '?' + qs.stringify(query)
var values = {
translator: translator,
link: link,
email: message.email
}
var localized = this.templates.unlockEmail(values)
var email = {
sender: this.sender,
to: message.email,
subject: translator.gettext('Re-verify your account'),
text: localized.text,
html: localized.html,
headers: {
'X-Uid': message.uid,
'X-Unlock-Code': message.code,
'X-Service-ID': message.service,
'X-Link': link,
'Content-Language': translator.language
}
}
return this.send(email)
}
return Mailer
}
| JavaScript | 0.000001 | @@ -494,24 +494,166 @@
g.port%0A %7D
+%0A%0A if (config.user && config.password) %7B%0A options.auth = %7B%0A user: config.user,%0A pass: config.password%0A %7D%0A %7D%0A
%0A this.ma
|
53e22b570d08d71902380403052377d4984fd355 | add add actioncreator for set current page | static/js/actions/collectionsPagination.js | static/js/actions/collectionsPagination.js | // @flow
import { createAction } from "redux-actions"
import type { Dispatch } from "redux"
import * as api from "../lib/api"
const qualifiedName = (name: string) => `COLLECTIONS_PAGINATION_${name}`
const constants = {}
const actionCreators = {}
constants.REQUEST_GET_PAGE = qualifiedName("REQUEST_GET_PAGE")
actionCreators.requestGetPage = createAction(
constants.REQUEST_GET_PAGE)
constants.RECEIVE_GET_PAGE_SUCCESS = qualifiedName("RECEIVE_GET_PAGE_SUCCESS")
actionCreators.receiveGetPageSuccess = createAction(
constants.RECEIVE_GET_PAGE_SUCCESS)
constants.RECEIVE_GET_PAGE_FAILURE = qualifiedName("RECEIVE_GET_PAGE_FAILURE")
actionCreators.receiveGetPageFailure = createAction(
constants.RECEIVE_GET_PAGE_FAILURE)
actionCreators.getPage = (page: number) => {
const thunk = async (dispatch: Dispatch) => {
dispatch(actionCreators.requestGetPage({page}))
try {
const response = await api.getCollections({page})
const data = response.data || {}
// @TODO: ideally we would dispatch an action here to save collections to
// a single place in state (e.g. state.collections).
// However, it take a non-trivial refactor to implement this schema
// change. So in the interest of scope, we store collections here.
// This will likely be confusing for future developers, and I recommend
// refactoring.
dispatch(actionCreators.receiveGetPageSuccess({
page,
count: (data.count || 0),
collections: (data.results || []),
}))
} catch (error) {
dispatch(actionCreators.receiveGetPageFailure({
page,
error
}))
}
}
return thunk
}
export { actionCreators, constants }
| JavaScript | 0 | @@ -750,16 +750,23 @@
Page = (
+opts: %7B
page: nu
@@ -769,23 +769,48 @@
: number
+%7D
) =%3E %7B%0A
+ const %7B page %7D = opts%0A
const
@@ -967,51 +967,25 @@
%7Bpag
-e%7D)%0A const data = response.data %7C%7C %7B%7D
+ination: %7Bpage%7D%7D)
%0A
@@ -1457,20 +1457,24 @@
(
-data
+response
.count %7C
@@ -1505,12 +1505,16 @@
s: (
-data
+response
.res
@@ -1675,19 +1675,156 @@
n thunk%0A
-
%7D%0A%0A
+constants.SET_CURRENT_PAGE = qualifiedName(%22SET_CURRENT_PAGE%22)%0AactionCreators.setCurrentPage = createAction(constants.SET_CURRENT_PAGE)%0A%0A
export %7B
|
1266fd052ed687d449e0b1771a3b357e445473fa | Remove duplicate `var headers = {};` | samples/websocket/src/main/resources/static/resources/js/message.js | samples/websocket/src/main/resources/static/resources/js/message.js |
function ApplicationModel(stompClient) {
var self = this;
self.friends = ko.observableArray();
self.username = ko.observable();
self.conversation = ko.observable(new ImConversationModel(stompClient,this.username));
self.notifications = ko.observableArray();
self.csrfToken = ko.computed(function() {
return JSON.parse($.ajax({
type: 'GET',
url: 'csrf',
dataType: 'json',
success: function() { },
data: {},
async: false
}).responseText);
}, this);
self.connect = function() {
var headers = {};
var csrf = self.csrfToken();
var headers = {};
headers[csrf.headerName] = csrf.token;
stompClient.connect(headers, function(frame) {
console.log('Connected ' + frame);
self.username(frame.headers['user-name']);
// self.friendSignin({"username": "luke"});
stompClient.subscribe("/user/queue/errors", function(message) {
self.pushNotification("Error " + message.body);
});
stompClient.subscribe("/app/users", function(message) {
var friends = JSON.parse(message.body);
for(var i=0;i<friends.length;i++) {
self.friendSignin({"username": friends[i]});
}
});
stompClient.subscribe("/topic/friends/signin", function(message) {
var friends = JSON.parse(message.body);
for(var i=0;i<friends.length;i++) {
self.friendSignin(new ImFriend({"username": friends[i]}));
}
});
stompClient.subscribe("/topic/friends/signout", function(message) {
var friends = JSON.parse(message.body);
for(var i=0;i<friends.length;i++) {
self.friendSignout(new ImFriend({"username": friends[i]}));
}
});
stompClient.subscribe("/user/queue/messages", function(message) {
self.conversation().receiveMessage(JSON.parse(message.body));
});
}, function(error) {
self.pushNotification(error)
console.log("STOMP protocol error " + error);
});
}
self.pushNotification = function(text) {
self.notifications.push({notification: text});
if (self.notifications().length > 5) {
self.notifications.shift();
}
}
self.logout = function() {
stompClient.disconnect();
window.location.href = "../logout.html";
}
self.friendSignin = function(friend) {
self.friends.push(friend);
}
self.friendSignout = function(friend) {
var r = self.friends.remove(
function(item) {
item.username == friend.username
}
);
self.friends(r);
}
}
function ImFriend(data) {
var self = this;
self.username = data.username;
}
function ImConversationModel(stompClient,from) {
var self = this;
self.stompClient = stompClient;
self.from = from;
self.to = ko.observable(new ImFriend('null'));
self.draft = ko.observable('')
self.messages = ko.observableArray();
self.receiveMessage = function(message) {
var elem = $('#chat');
var isFromSelf = self.from() == message.from;
var isFromTo = self.to().username == message.from;
if(!(isFromTo || isFromSelf)) {
self.chat(new ImFriend({"username":message.from}))
}
var atBottom = (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight());
self.messages.push(new ImModel(message));
if (atBottom)
elem.scrollTop(elem[0].scrollHeight);
};
self.chat = function(to) {
self.to(to);
self.draft('');
self.messages.removeAll()
$('#trade-dialog').modal();
}
self.send = function() {
var data = {
"created" : new Date(),
"from" : self.from(),
"to" : self.to().username,
"message" : self.draft()
};
var destination = "/app/im"; // /queue/messages-user1
stompClient.send(destination, {}, JSON.stringify(data));
self.draft('');
}
};
function ImModel(data) {
var self = this;
self.created = new Date(data.created);
self.to = data.to;
self.message = data.message;
self.from = data.from;
self.messageFormatted = ko.computed(function() {
return self.created.getHours() + ":" + self.created.getMinutes() + ":" + self.created.getSeconds() + " - " + self.from + " - " + self.message;
})
};
| JavaScript | 0.00758 | @@ -552,36 +552,16 @@
oken();%0A
-%09%09var headers = %7B%7D;%0A
%09%09header
|
918783a8ce3946fff2783d928b8e329c572c1811 | Fix leave modal when leaving new post | ghost/admin/routes/editor/new.js | ghost/admin/routes/editor/new.js | import base from 'ghost/mixins/editor-route-base';
var EditorNewRoute = Ember.Route.extend(SimpleAuth.AuthenticatedRouteMixin, base, {
classNames: ['editor'],
model: function () {
var self = this;
return this.get('session.user').then(function (user) {
return self.store.createRecord('post', {
author: user
});
});
},
setupController: function (controller, model) {
this._super(controller, model);
controller.set('scratch', '');
// used to check if anything has changed in the editor
controller.set('previousTagNames', Ember.A());
// attach model-related listeners created in editor-route-base
this.attachModelHooks(controller, model);
},
actions: {
willTransition: function (transition) {
var controller = this.get('controller'),
isDirty = controller.get('isDirty'),
model = controller.get('model'),
isNew = model.get('isNew'),
isSaving = model.get('isSaving'),
isDeleted = model.get('isDeleted'),
modelIsDirty = model.get('isDirty');
this.send('closeRightOutlet');
// when `isDeleted && isSaving`, model is in-flight, being saved
// to the server. when `isDeleted && !isSaving && !modelIsDirty`,
// the record has already been deleted and the deletion persisted.
//
// in either case we can probably just transition now.
// in the former case the server will return the record, thereby updating it.
// @TODO: this will break if the model fails server-side validation.
if (!(isDeleted && isSaving) && !(isDeleted && !isSaving && !modelIsDirty) && isDirty) {
transition.abort();
this.send('openModal', 'leave-editor', [controller, transition]);
return;
}
if (isNew) {
model.deleteRecord();
}
// since the transition is now certain to complete..
window.onbeforeunload = null;
// remove model-related listeners created in editor-route-base
this.detachModelHooks(controller, model);
}
}
});
export default EditorNewRoute;
| JavaScript | 0 | @@ -519,16 +519,60 @@
h', '');
+%0A controller.set('titleScratch', '');
%0A%0A
|
d8419a8b85506a7cb1c840171b29cf85663b1f68 | Improve order normalization awareness algorithm | js/collections/ordered_collection.js | js/collections/ordered_collection.js | "use strict";
var _ = require('underscore-contrib')
, $ = require('jquery')
, Backbone = require('../backbone')
function makeorderedSave(origSave) {
return function (attributes, options) {
var that = this
, needsNormalization = this.collection.getMinOrderingStep() < this.collection.minOrderingStep
, normalize = this.collection.normalizeOrderingValues.bind(this.collection)
, refresh = this.collection.refreshOrdering.bind(this.collection)
, save = origSave.bind(this, attributes, options)
, dfd
if (this.isNew()) {
dfd = needsNormalization ? normalize() : (new $.Deferred()).resolve();
dfd.then(function () {
var idx = that.collection.indexOf(that)
, ordering = that.collection.getIntermediateOrderingValue(idx, true, true)
ordering = Math.floor(ordering);
that.set('ordering', ordering);
}).then(save).done(refresh);
} else {
dfd = save();
if (needsNormalization) dfd.then(normalize).done(refresh);
}
}
}
module.exports = Backbone.Collection.extend({
orderingAttribute: 'ordering',
orderNormalizationURL: function () { return _.result(this, 'url') + 'normalize_order/' },
minOrderingStep: 25,
initialize: function () {
var orderAwareModel = this.model.extend({});
orderAwareModel.prototype.save = makeorderedSave(this.model.prototype.save);
this.model = orderAwareModel;
this.comparator = this.orderingAttribute;
},
/*
*
*/
add: function (models, options) {
var orderingStart
, orderingAttribute = this.orderingAttribute
options = options || {};
models = _.isArray(models) ? models : [models];
if (_.isEmpty(models)) return;
// Get the starting value for the order.
orderingStart = this.getIntermediateOrderingValue(
options.hasOwnProperty('at') ? options.at : this.models.length);
_.forEach(models, function (model, i) {
var isModel = model instanceof Backbone.Model
, ordering = orderingStart + (i / models.length)
if (isModel && (!model.isNew() || model.get(this.orderingAttribute))) return;
if (!isModel && (model.hasOwnProperty('id') ||
model.hasOwnProperty(this.orderingAttribute))) return;
// If the model has not explicitly set an ordering and does not yet
// exist, set it automatically.
if (isModel) {
model.set(orderingAttribute, ordering);
} else {
model[orderingAttribute] = ordering;
}
}, this);
Backbone.Collection.prototype.add.call(this, models, options);
},
normalizeOrderingValues: function () {
var that = this
, promise = $.ajax({
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRFToken', $('input[name="csrfmiddlewaretoken"]').val());
},
url: _.result(this, 'orderNormalizationURL'),
data: {}
});
promise.done(function (data) {
that.set(data, { add: false, remove: false, sort: false });
that.refreshOrdering();
});
return promise;
},
// Assumes that the sections are in order, and changes `ordering` values
// accordingly. This is especially important for unsaved sections that cannot
// be given values with the `normalizeOrderingValues` method.
refreshOrdering: function () {
var orderingAttribute = this.orderingAttribute;
this.forEach(function (model, idx) {
var prev, next, startIdx;
if (model.isNew()) return;
prev = this.chain()
.first(idx)
.reverse()
.takeWhile(function (model) { return model.isNew() })
.value();
if (prev.length) {
startIdx = this.getIntermediateOrderingValue(idx, true, true);
prev.forEach(function (model, i) {
var ordering = startIdx + (i / prev.length);
model.set(orderingAttribute, ordering);
});
}
next = this.chain()
.rest(idx)
.takeWhile(function (model) { return model.isNew() })
.value();
if (next.length) {
startIdx = this.getIntermediateOrderingValue(idx + 1, true, true);
next.forEach(function (model, i) {
var ordering = startIdx + (i / next.length);
model.set(orderingAttribute, ordering);
});
}
}, this);
this.sort();
},
getMinOrderingStep: function () {
var orderingAttribute = this.orderingAttribute
, orderings
orderings = _.chain(this.models)
.filter(function (model) { return !model.isNew() })
.map(function (model) { return parseInt(model.get(orderingAttribute), 10) })
.sort(function (a, b) { return a - b })
.value();
if (_.any(orderings, _.isNaN)) return 0;
return _.chain(orderings)
.map(function (n, i, arr) { return arr[i + 1] - n; })
.filter(Boolean)
.min()
.value();
},
getIntermediateOrderingValue: function (idx, skipIdx, skipNew) {
var prevModel, nextModel, order;
idx = idx || 0;
prevModel = idx <= 0 ? null : this.at(idx - 1);
if (prevModel && skipNew) {
prevModel = this.chain()
.first(idx)
.reverse()
.filter(function (model) { return !model.isNew() })
.first()
.value();
}
nextModel = idx >= this.length ? null : this.at(idx + (skipIdx ? 1 : 0));
if (nextModel && skipNew) {
nextModel = this.chain()
.rest(idx)
.filter(function (model) { return !model.isNew() })
.first()
.value();
}
if (!prevModel && !nextModel) {
order = 100;
} else if (!nextModel) {
order = prevModel.get(this.orderingAttribute) + 100;
} else if (!prevModel) {
order = nextModel.get(this.orderingAttribute) / 2;
} else {
order = (nextModel.get(this.orderingAttribute) + prevModel.get(this.orderingAttribute)) / 2;
}
return order;
}
});
| JavaScript | 0.000013 | @@ -259,62 +259,28 @@
ion.
-getMinOrderingStep() %3C this.collection.minOrderingStep
+needsNormalization()
%0A
@@ -4318,24 +4318,303 @@
rt();%0A %7D,%0A%0A
+ needsNormalization: function () %7B%0A var curMinOrderingStep = this.getMinOrderingStep();%0A%0A if (!_.isFinite(curMinOrderingStep)) %7B%0A return true;%0A %7D else if (curMinOrderingStep %3C this.minOrderingStep) %7B%0A return true;%0A %7D else %7B%0A return false;%0A %7D%0A %7D,%0A%0A
getMinOrde
|
79a3444d39b69a341f4ac9ecc41147bee51b89df | Add support for fermenter-iteration attribute. | src/common/fermenter/fermenterEnv.js | src/common/fermenter/fermenterEnv.js | import { Record } from 'immutable';
export default Record({
createdAt: null,
temperature: null,
humidity: null,
isValid: false,
errors: 0,
});
| JavaScript | 0 | @@ -143,12 +143,28 @@
ors: 0,%0A
+ iterations: 0%0A
%7D);%0A
|
f3bc0a1b6a68a68e8c5227d625ae82e58471d78e | Fix tag grouping bugs. | packages/eslint-plugin/rules/jsdoc-tag-grouping.js | packages/eslint-plugin/rules/jsdoc-tag-grouping.js | /**
* ESLint rules: specify JSDoc tag grouping rules.
*
* Site Kit by Google, Copyright 2020 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
*/
const { default: iterateJsdoc } = require( 'eslint-plugin-jsdoc/dist/iterateJsdoc' );
/**
* Internal dependencies
*/
const { findTagInGroup } = require( '../utils' );
module.exports = iterateJsdoc( ( {
context,
jsdoc,
jsdocNode,
utils,
} ) => {
if ( ! jsdoc.tags || ! jsdoc.tags.length ) {
return;
}
// If the `@ignore` tag is in this JSDoc block, ignore it and don't require any ordering.
if ( utils.hasTag( 'ignore' ) ) {
return;
}
const lastTagInFirstGroup = findTagInGroup( [ 'private', 'deprecated', 'see', 'since' ], utils );
// This is a rule violation, but of a different rule. For now, just skip the check.
if ( ! lastTagInFirstGroup ) {
return;
}
const hasSecondGroup = !! utils.filterTags( ( { tag } ) => {
return ! [ 'private', 'deprecated', 'see', 'since' ].includes( tag );
} ).length;
// If there's no second group, don't check tag grouping.
if ( ! hasSecondGroup ) {
if (
jsdoc.source.match(
new RegExp( `@${ lastTagInFirstGroup }.*\\n\\n`, 'gm' )
)
) {
context.report( {
data: { name: jsdocNode.name },
message: `The @${ lastTagInFirstGroup } tag should not be followed by an empty line when it is the last tag.`,
node: jsdocNode,
} );
return;
}
return;
}
const firstTagInSecondGroup = findTagInGroup( [ 'param', 'typedef', 'type', 'return' ], utils );
if ( firstTagInSecondGroup === null ) {
context.report( {
data: { name: jsdocNode.name },
message: `Unrecognized tag @${ jsdoc.tags[ jsdoc.tags.length - 1 ].tag } in last group of the JSDoc block. You may need to add this to the sitekit/jsdoc-tag-grouping rules.`,
node: jsdocNode,
} );
return;
}
if (
! jsdoc.source.match(
new RegExp( `@${ lastTagInFirstGroup }.*\\n\\n@${ firstTagInSecondGroup }`, 'gm' )
)
) {
context.report( {
data: { name: jsdocNode.name },
message: `The @${ lastTagInFirstGroup } tag should be followed by an empty line, and then by the @${ firstTagInSecondGroup } tag.`,
node: jsdocNode,
} );
}
}, {
iterateAllJsdocs: true,
meta: {
docs: {
description: 'Requires that all functions have properly sorted doc annotations.',
},
fixable: 'code',
type: 'suggestion',
},
} );
| JavaScript | 0 | @@ -1624,30 +1624,33 @@
f (%0A%09%09%09jsdoc
-.sourc
+Node.valu
e.match(%0A%09%09%09
@@ -1695,17 +1695,21 @@
%7D.*%5C%5Cn%5C%5C
-n
+s*%5C%5C*
%60, 'gm'
|
ef50092daad966073df5ec49f8636e77ee413df2 | Make when clicked hats trigger on mouse down | src/io/mouse.js | src/io/mouse.js | const MathUtil = require('../util/math-util');
class Mouse {
constructor (runtime) {
this._x = 0;
this._y = 0;
this._isDown = false;
/**
* Reference to the owning Runtime.
* Can be used, for example, to activate hats.
* @type{!Runtime}
*/
this.runtime = runtime;
}
/**
* Activate "event_whenthisspriteclicked" hats if needed.
* @param {number} x X position to be sent to the renderer.
* @param {number} y Y position to be sent to the renderer.
* @param {?bool} wasDragged Whether the click event was the result of
* a drag end.
* @private
*/
_activateClickHats (x, y, wasDragged) {
if (this.runtime.renderer) {
const drawableID = this.runtime.renderer.pick(x, y);
for (let i = 0; i < this.runtime.targets.length; i++) {
const target = this.runtime.targets[i];
if (target.hasOwnProperty('drawableID') &&
target.drawableID === drawableID) {
// only activate click hat if the mouse up event wasn't
// the result of a drag ending
if (!wasDragged) {
// Activate both "this sprite clicked" and "stage clicked"
// They were separated into two opcodes for labeling,
// but should act the same way.
// Intentionally not checking isStage to make it work when sharing blocks.
// @todo the blocks should be converted from one to another when shared
this.runtime.startHats('event_whenthisspriteclicked',
null, target);
this.runtime.startHats('event_whenstageclicked',
null, target);
}
return;
}
}
// If haven't returned, activate click hats for stage.
// Still using both blocks for sharing compatibility.
this.runtime.startHats('event_whenthisspriteclicked',
null, this.runtime.getTargetForStage());
this.runtime.startHats('event_whenstageclicked',
null, this.runtime.getTargetForStage());
}
}
/**
* Mouse DOM event handler.
* @param {object} data Data from DOM event.
*/
postData (data) {
if (data.x) {
this._clientX = data.x;
this._scratchX = MathUtil.clamp(
480 * ((data.x / data.canvasWidth) - 0.5),
-240,
240
);
}
if (data.y) {
this._clientY = data.y;
this._scratchY = MathUtil.clamp(
-360 * ((data.y / data.canvasHeight) - 0.5),
-180,
180
);
}
if (typeof data.isDown !== 'undefined') {
this._isDown = data.isDown;
// Make sure click is within the canvas bounds to activate click hats
if (!this._isDown &&
data.x > 0 && data.x < data.canvasWidth &&
data.y > 0 && data.y < data.canvasHeight) {
this._activateClickHats(data.x, data.y, data.wasDragged);
}
}
}
/**
* Get the X position of the mouse in client coordinates.
* @return {number} Non-clamped X position of the mouse cursor.
*/
getClientX () {
return this._clientX;
}
/**
* Get the Y position of the mouse in client coordinates.
* @return {number} Non-clamped Y position of the mouse cursor.
*/
getClientY () {
return this._clientY;
}
/**
* Get the X position of the mouse in scratch coordinates.
* @return {number} Clamped X position of the mouse cursor.
*/
getScratchX () {
return this._scratchX;
}
/**
* Get the Y position of the mouse in scratch coordinates.
* @return {number} Clamped Y position of the mouse cursor.
*/
getScratchY () {
return this._scratchY;
}
/**
* Get the down state of the mouse.
* @return {boolean} Is the mouse down?
*/
getIsDown () {
return this._isDown;
}
}
module.exports = Mouse;
| JavaScript | 0 | @@ -695,20 +695,8 @@
x, y
-, wasDragged
) %7B%0A
@@ -1138,102 +1138,8 @@
//
- the result of a drag ending%0A if (!wasDragged) %7B%0A //
Act
@@ -1211,20 +1211,16 @@
-
// They
@@ -1265,20 +1265,16 @@
beling,%0A
-
@@ -1333,28 +1333,24 @@
-
// Intention
@@ -1432,20 +1432,16 @@
-
// @todo
@@ -1516,36 +1516,32 @@
-
-
this.runtime.sta
@@ -1594,36 +1594,32 @@
-
null, target);%0A
@@ -1629,36 +1629,32 @@
-
-
this.runtime.sta
@@ -1702,36 +1702,32 @@
-
null, target);%0A
@@ -1729,30 +1729,8 @@
t);%0A
- %7D%0A
@@ -2822,28 +2822,151 @@
-this._isDown = data.
+const previousDownState = this._isDown;%0A this._isDown = data.isDown;%0A const isNewMouseDown = !previousDownState && this._
isDo
@@ -3071,17 +3071,18 @@
if (
-!this._is
+isNewMouse
Down
@@ -3262,25 +3262,8 @@
ta.y
-, data.wasDragged
);%0A
|
2f956971e1340a7663cbffe57b0113d2b908abd4 | fix entry.js regex | src/js/entry.js | src/js/entry.js | var files = require.context('.', true, /\components\/\.js$/);
files.keys().forEach(files);
| JavaScript | 0.000009 | @@ -33,17 +33,17 @@
true, /
-%5C
+(
componen
@@ -48,15 +48,9 @@
ents
-%5C/%5C.js$
+)
/);%0A
|
53b622f80438cbccb5c8a54c5304fabc51430602 | use main site | src/js/oseam.js | src/js/oseam.js | // -------------------------------------------------------------------------------------------------
// OpenSeaMap Water Depth - Web frontend for depth data handling.
//
// Written in 2012 by Dominik Fässler dfa@bezono.org
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// -------------------------------------------------------------------------------------------------
OSeaM = {
models: {},
routers: {},
views: {},
utils: {},
container: null,
frontend: null,
router: null,
// apiUrl: 'http://192.168.1.29:8100/org.osm.depth.upload/api2/',
// apiUrl: 'http://depth.openseamap.org:8080/org.osm.depth.upload/api2/',
apiUrl: 'http://testdepth.openseamap.org:8080/org.osm.depth.upload.stage/api2/',
// apiUrl: 'http://localhost:8080/org.osm.depth.upload/api2/',
autoId: 0,
init: function() {
OSeaM.configureBackboneSync();
this.frontend = new OSeaM.models.Frontend();
this.frontend.setLanguage('en');
this.container = $('.oseam-container');
this.router = new OSeaM.routers.Router();
Backbone.history.start();
},
configureBackboneSync: function() {
var originalSync = Backbone.sync;
Backbone.sync = function(method, model, options) {
options = options || {};
options.crossDomain = true;
options.xhrFields = {
withCredentials: true
};
return originalSync(method, model, options);
};
},
loadTemplate: function(template) {
return Handlebars.templates[template];
},
id: function(prefix) {
prefix = prefix || 'oseam-';
this.autoId++;
return prefix + this.autoId;
}
};
OSeaM.View = Backbone.View.extend({
close: function() {
this.$el.empty();
this.undelegateEvents();
}
});
| JavaScript | 0 | @@ -911,18 +911,16 @@
api2/',%0A
-//
apiU
@@ -978,32 +978,34 @@
.upload/api2/',%0A
+//
apiUrl: 'htt
|
3b751a698f27a106088ef496e8a1c89b94f7e7af | refactor for..of to reduce array instead | src/js/print.js | src/js/print.js | import Browser from './browser'
import { cleanUp } from './functions'
const Print = {
send: (params, printFrame) => {
// Append iframe element to document body
document.getElementsByTagName('body')[0].appendChild(printFrame)
// Get iframe element
const iframeElement = document.getElementById(params.frameId)
// Wait for iframe to load all content
iframeElement.onload = () => {
if (params.type === 'pdf') {
performPrint(iframeElement, params)
return
}
// Get iframe element document
let printDocument = (iframeElement.contentWindow || iframeElement.contentDocument)
if (printDocument.document) printDocument = printDocument.document
// Append printable element to the iframe body
printDocument.body.appendChild(params.printableElement)
// Add custom style
if (params.type !== 'pdf' && params.style) {
// Create style element
const style = document.createElement('style')
style.innerHTML = params.style
// Append style element to iframe's head
printDocument.head.appendChild(style)
}
// If printing images, wait for them to load inside the iframe
const images = printDocument.getElementsByTagName('img')
if (images.length > 0) {
loadIframeImages(images).then(() => performPrint(iframeElement, params))
} else {
performPrint(iframeElement, params)
}
}
}
}
function performPrint (iframeElement, params) {
try {
iframeElement.focus()
// If Edge or IE, try catch with execCommand
if (Browser.isEdge() || Browser.isIE()) {
try {
iframeElement.contentWindow.document.execCommand('print', false, null)
} catch (e) {
iframeElement.contentWindow.print()
}
} else {
// Other browsers
iframeElement.contentWindow.print()
}
} catch (error) {
params.onError(error)
} finally {
cleanUp(params)
}
}
function loadIframeImages (images) {
const promises = []
for (let image of images) {
if (image.src && image.src !== window.location.href) promises.push(loadIframeImage(image))
}
return Promise.all(promises)
}
function loadIframeImage (image) {
return new Promise(resolve => {
const pollImage = () => {
!image || typeof image.naturalWidth === 'undefined' || image.naturalWidth === 0 || !image.complete
? setTimeout(pollImage, 500)
: resolve()
}
pollImage()
})
}
export default Print
| JavaScript | 0 | @@ -2025,46 +2025,75 @@
s =
-%5B%5D%0A%0A for (let image of
+Array.prototype.slice.call(images).reduce((memo,
image
-s
)
+ =%3E
%7B%0A
+
if (
@@ -2141,24 +2141,32 @@
n.href)
-promises
+%7B%0A memo
.push(lo
@@ -2186,20 +2186,54 @@
(image))
+;
%0A
-%7D
+ %7D%0A return memo;%0A %7D, %5B%5D);
%0A%0A retu
|
b1f4e71c82c3bd5719f1ab66bcd1cd43109dd50b | Set `dev` | src/js/serve.js | src/js/serve.js | const express = require('express')
const fs = require('fs-extra')
const getPort = require('get-port')
const lodashTemplate = require('lodash.template')
const markdownExtensions = require('markdown-extensions')
const path = require('path')
const sirv = require('sirv')
const createFileWatcher = require('./create-file-watcher')
const createWebSocketServer = require('./create-web-socket-server')
const formatMarkdownFile = require('./format-markdown-file')
const renderMarkdownFile = require('./render-markdown-file')
const render = lodashTemplate(
fs.readFileSync(
path.resolve(__dirname, '..', 'html', 'template.html'),
'utf8'
)
)
const markdownRoutesRegularExpression = new RegExp(
'.*.(' + markdownExtensions.join('|') + ')$',
'i'
)
const directory = process.cwd()
async function serve (file, { port, shouldFormat, theme }) {
const serverPort = await getPort({ port })
const webSocketPort = await getPort({ port: port + 1 })
return new Promise(async function (resolve, reject) {
const broadcastChangedMarkdownToClients = await createWebSocketServer(
webSocketPort
)
await createFileWatcher(directory, async function (changedFile) {
const filePath = path.join(directory, changedFile)
if (shouldFormat && (await formatMarkdownFile(filePath))) {
return
}
try {
const html = await renderMarkdownFile(filePath)
broadcastChangedMarkdownToClients(changedFile, html)
} catch (error) {
reject(error)
}
})
const app = express()
app.get(markdownRoutesRegularExpression, async function (req, res, next) {
try {
const html = await renderMarkdownFile(
path.join(directory, req.originalUrl)
)
res.send(
render({
content: html,
theme,
title: path.basename(req.path),
webSocketPort: webSocketPort
})
)
} catch (error) {
reject(error)
next()
}
})
app.use(
'/__rdd',
express.static(path.resolve(__dirname, '..', '..', 'build'))
)
app.use(sirv(directory))
app.listen(serverPort, function () {
const url = `0.0.0.0:${serverPort}/${file}`
console.log(`Serving on ${url}`)
resolve(`http://${url}`)
})
})
}
module.exports = serve
| JavaScript | 0 | @@ -2117,16 +2117,23 @@
app.use(
+%0A
sirv(dir
@@ -2138,17 +2138,51 @@
irectory
-)
+, %7B%0A dev: true%0A %7D)%0A
)%0A%0A a
|
99ae11d7ffb521bbad029e6da38df01c23922da8 | add passport script and login facebook module, #1 | examples/booklog-homa/index.js | examples/booklog-homa/index.js | /**
* Module dependencies.
*/
var express = require('../../lib/express');
// Path to our public directory
var pub = __dirname + '/public';
// setup middleware
var app = express();
app.use(express.static(pub));
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/booklog2');
var dbConn = mongoose.connection;
dbConn.on('error', console.error.bind(console, 'connection error:'));
dbConn.once('open', function callback () {
console.log('MongoDB: connected.');
});
//Table
var postSchema = new mongoose.Schema({
subject: { type: String, default: ''},
content: String
});
//put to express framework
//'Post'=Tablename
//Model is definition of document.
//new schema to a model, naming for the schema to a model named 'Post'.
//Collection name=&model_name+"s"(lower case), e.g. posts.
app.db = {
posts: mongoose.model('Post', postSchema)
};
// Optional since express defaults to CWD/views
app.set('views', __dirname + '/views');
// Set our default template engine to "jade"
// which prevents the need for extensions
// (although you can still mix and match)
app.set('view engine', 'jade');
var posts = [{
subject: "Hello",
content: "Hi !"
}, {
subject: "World",
content: "Hi !"
}];
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.all('*', function(req, res, next){
if (!req.get('Origin')) return next();
// use "*" here to accept any origin
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'PUT');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
// res.set('Access-Control-Allow-Max-Age', 3600);
if ('OPTIONS' == req.method) return res.send(200);
next();
});
app.get('/', function(req, res) {
res.render('index');
});
app.get('/download', function(req, res) {
var events = require('events');
var workflow = new events.EventEmitter();
workflow.outcome = {
success: false,
};
workflow.on('vaidate', function() {
var password = req.query.password;
if (typeof(req.retries) === 'undefined')
req.retries = 3;
if (password === '123456') {
return workflow.emit('success');
}
return workflow.emit('error');
});
workflow.on('success', function() {
workflow.outcome.success = true;
workflow.outcome.redirect = {
url: '/welcome'
};
workflow.emit('response');
});
workflow.on('error', function() {
if (req.retries > 0) {
req.retries--;
workflow.outcome.retries = req.retries;
workflow.emit('response');
}
workflow.outcome.success = false;
workflow.emit('response');
});
workflow.on('response', function() {
return res.send(workflow.outcome);
});
return workflow.emit('vaidate');
});
app.get('/post', function(req, res) {
res.render('post', {
posts: posts
});
});
app.get('/1/post/:id', function(req, res) {
var id = req.params.id;
var model = req.app.db.posts;
//Read
//"_id:" is the attribute auto generated by mongodb, meanwhile it's represented the document name also.
model.findOne({_id: id}, function(err, post) {
res.send({post: post});
});
});
app.get('/1/post', function(req, res) {
var model = req.app.db.posts;
model.find(function(err, posts) {
res.send({posts: posts});
});
});
app.post('/1/post', function(req, res) {
var model = req.app.db.posts;
var subject;
var content;
if (typeof(req.body) === 'undefined') {
subject = req.query.subject;
content = req.query.content;
} else {
subject = req.body.subject;
content = req.body.content;
}
var post = {
subject: subject,
content: content
};
//posts.push(post);
//Create
var card = new model(post);//new a document by post object.
card.save();
res.send({ status: 'OK'});
});
app.delete('/1/post', function(req, res) {
res.send("Delete a post");
});
app.put('/1/post/:postId', function(req, res) {
var id = req.params.postId;
res.send("Update a post: " + id);
});
// change this to a better error handler in your code
// sending stacktrace to users in production is not good
app.use(function(err, req, res, next) {
res.send(err.stack);
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
| JavaScript | 0 | @@ -1266,24 +1266,1126 @@
-parser');%0A%0A
+var passport = require('passport')%0A , FacebookStrategy = require('passport-facebook').Strategy;%0A%0Apassport.use(new FacebookStrategy(%7B%0A clientID: %22573894422722633%22,%0A clientSecret: %22cd295293760fb7fe56a69c1aae66da51%22,%0A callbackURL: %22http://localhost:3000/auth/facebook/callback%22%0A %7D,%0A function(accessToken, refreshToken, profile, done) %7B%0A User.findOrCreate(..., function(err, user) %7B%0A if (err) %7B return done(err); %7D%0A done(null, user);%0A %7D);%0A %7D%0A));%0A%0A// Redirect the user to Facebook for authentication. When complete,%0A// Facebook will redirect the user back to the application at%0A// /auth/facebook/callback%0Aapp.get('/auth/facebook', passport.authenticate('facebook'));%0A%0A// Facebook will redirect the user to this URL after approval. Finish the%0A// authentication process by attempting to obtain an access token. If%0A// access was granted, the user will be logged in. Otherwise,%0A// authentication has failed.%0Aapp.get('/auth/facebook/callback', %0A passport.authenticate('facebook', %7B successRedirect: '/',%0A failureRedirect: '/login' %7D));%0A%0A
app.use(body
|
bdeff7f1f425f87b51b91bb49b0e3067e263c39b | Make randomize a utility of the class | matrix.js | matrix.js | // Tiny Matrix Class
// Copyright 2016 Motivara
var Matrix = function(r,c) { // pass a row count or an array of arrays
if(Array.isArray(r)) {this.$=r;}
else {
var i,j;
for(i=0,this.$=[];i<r;i++) {
this.$[i]=[];
if (typeof c === 'number') // if col count, then init
{for(j=0;j<c;j++) {this.$[i][j]=0;}}
}
}
};
Matrix.prototype = {
constructor: Matrix,
T: function() { //transpose
var ar=this.rows,ac=this.cols,b,i,j;
for(b=new Matrix(ac),i=0;i<ac;i++)
{for(j=0;j<ar;j++) { b.$[i][j]=this.$[j][i];}}
return b;
},
err: function(ar,xc,br,bc){return "shapes ("+ar+","+xc+") and ("+br+","+bc+") not aligned";},
dot: function(b) { // matrix product: $(m,n) * b(n,p) = c(m,p)
if(Array.isArray(b)) {b=new Matrix(b);}
var ar=this.rows,ac=this.cols,br=b.rows,bc=b.cols,c,i,j,k;
if (ac!==br) {throw(this.err(ar,ac,br,bc));}
for (i=0,c= new Matrix(ar); i<ar; ++i)
{for (j=0; j<bc; ++j)
{for (k=c.$[i][j]=0; k<ac; ++k) {c.$[i][j] += this.$[i][k] * b.$[k][j];}}}
return c;
},
mul: function(b) {
if(Array.isArray(b)) {b=new Matrix(b);}
var ar=this.rows,ac=this.cols,br=b.rows,bc=b.cols,c,i,j;
if (ar===br && ac===bc) {
for(c=new Matrix(ar),i=0;i<ar;i++) // entrywise product: $(m,n) * b(m,n) = c(m,n)
{for(j=0;j<ac;j++) {c.$[i][j]=this.$[i][j]*b.$[i][j];}}
return c;
} else
if (ac===br) // e.g. (3,2) * (2,5) > perform dot product
{return this.dot(b);} // or (3,2) * (2,3)
else //if (ar!=br || ac!=bc)
{throw(this.err(ar,ac,br,bc));} // (3,3) * (5,6) > err
},
sub: function(b) {
if(Array.isArray(b)) {b=new Matrix(b);}
var ar=this.rows,ac=this.cols,br=b.rows,bc=b.cols,c,i,j;
if (ar!==br || ac!==bc) {throw(this.err(ar,ac,br,bc));}
for(c=new Matrix(ar),i=0;i<ar;i++)
{for(j=0;j<ac;j++) {c.$[i][j]=this.$[i][j]-b.$[i][j];}}
return c;
},
add: function(b) {
if(Array.isArray(b)) { b=new Matrix(b); }
var ar=this.rows,ac=this.cols,br=b.rows,bc=b.cols,c,i,j;
if (ar!==br || ac!==bc) {throw(this.err(ar,ac,br,bc));}
for(c=new Matrix(ar),i=0;i<ar;i++)
{for(j=0;j<ac;j++) {c.$[i][j]=this.$[i][j]+b.$[i][j];}}
return c;
},
map: function(f) {
if(typeof f !== 'function') {throw("function not passed!");}
var ar=this.rows,ac=this.cols,c,i,j;
for(c=new Matrix(ar),i=0;i<ar;i++)
{for(j=0;j<ac;j++) {c.$[i][j]=f(this.$[i][j]);}}
return c;
},
mean: function() {
var ar=this.rows,ac=this.cols,m,i,j;
for(m=0,i=0;i<ar;i++)
{for(j=0;j<ac;j++) {m+=this.$[i][j];}}
return m/(ar*ac);
},
// getters
get array() {return this.$;},
get rows() {return this.$.length;},
get cols() {return this.$[0].length;}
};
var randomize = function(r,c) { // create a rxc matrix with randomized values +1 to -1
return new Matrix(r,c).map(function(x) {
return 2*Math.random()-1;});
};
| JavaScript | 0.000288 | @@ -2752,20 +2752,23 @@
th;%7D%0A%7D;%0A
-var
+Matrix.
randomiz
|
9b11dfe6d83e1f6ae937f1194860bb705f533c07 | Update stylesheet.js | plugins/stylesheet.js | plugins/stylesheet.js | // hot damn we really need a <stylesheet> tag
onepoint.stylesheet = Plugin({
name: "Stylesheet",
description: "<stylesheet> tag",
version: "0.1",
author: "GeekyGamer14",
help: "Use <stylesheet sheet=\"path_to_sheet.css\"></stylesheet>"
})
onepoint.stylesheet.check = function(){
var ss = onepoint.stylesheet;
$('stylesheet').each(function(){
if($(this).attr('styled') != 'true'){
$(this).html('<link href="' + $(this).attr('sheet') + '" rel="stylesheet" type="text/css"></link>');
$(this).attr('styled', 'true');
onepoint.write(ss, 'Loaded stylesheet from ' + $(this).attr('sheet'));
}
});
}
onepoint.stylesheet.check();
$(document).ready(function(){
onepoint.stylesheet.check();
setInterval(onepoint.stylesheet.check, 500);
}); | JavaScript | 0.000001 | @@ -605,16 +605,200 @@
%09%7D%0A%09%7D);%0A
+%09%0A%09$('style').each(function()%7B%0A%09%09if($(this).attr('src') !== undefined)%7B%0A%09%09%09$(this).html('%3Clink href=%22' + $(this).attr('sheet') + '%22 rel=%22stylesheet%22 type=%22text/css%22%3E%3C/link%3E');%0A%09%09%7D%0A%09%7D)%0A
%7D%0Aonepoi
@@ -929,8 +929,9 @@
00);%0A%7D);
+%0A
|
22122f5f3832c6211aa92eb5e208090d60dea88e | correct details | matrix.js | matrix.js | // Input Matrix
// 1 0 0 1
// 0 0 1 0
// 0 0 0 0
// Matrix after modification
// 1 1 1 1
// 1 1 1 1
// 1 0 1 1
var setZeros = function(matrix){
//to remember which columns we need to fill with 1's
var rows = [];
var columns = [];
for(i=0; i<(matrix.length); i++){
var rowLength = matrix[i].length
// console.log(matrix[i])
for(j=0; j<(matrix[i].length); j++){
// console.log(matrix[i][j])
if(matrix[i][j]==1){
//if element is 1, note which row and column we need to fill with 1's
rows.push(i);
columns.push(j);
}
}
}
columns.sort();
console.log("Rows:", rows)
console.log("Columns:", columns)
//fill matrix with 1's on rows and columns
for(i=0; i<(rows.length); i++){
matrix[rows[i]].fill(1)
}
for(i=0; i<(matrix.length); i++){
for(j = 0; j<(matrix[i].length); j++){
if(columns.includes(j)){
matrix[i][j] = 1
}
}
}
console.log(matrix)
}
setZeros([[1,0,0,1], [0,0,1,0], [0,0,0,0]])
| JavaScript | 0.000079 | @@ -192,16 +192,52 @@
ith 1's%0A
+%0A%09if(matrix.length == 0)%0A%09%09return;%0A%0A
%09var row
@@ -263,16 +263,19 @@
s = %5B%5D;%0A
+%0A%0A%0A
%09for(i=0
@@ -307,19 +307,19 @@
%7B%0A%09%09var
-row
+col
Length =
@@ -377,34 +377,25 @@
(j=0; j%3C
-(matrix%5Bi%5D.l
+colL
ength
-)
; j++)%7B%0A
@@ -711,17 +711,16 @@
(i=0; i%3C
-(
rows.len
@@ -718,25 +718,24 @@
%3Crows.length
-)
; i++)%7B%0A%09%09ma
@@ -764,33 +764,32 @@
%09%7D%0A%0A%09for(i=0; i%3C
-(
matrix.length);
@@ -777,33 +777,32 @@
i%3Cmatrix.length
-)
; i++)%7B%0A%09%09for(j
@@ -808,17 +808,16 @@
= 0; j%3C
-(
matrix%5Bi
@@ -824,17 +824,16 @@
%5D.length
-)
; j++)%7B%0A
@@ -961,10 +961,71 @@
0,0,0%5D%5D)
+ //%3C-returns %5B%5B 1, 1, 1, 1 %5D, %5B 1, 1, 1, 1 %5D, %5B 1, 0, 1, 1 %5D%5D
%0A%0A
|
e2a098d9c7497bfb7b3c5f68d00310ce90b97af3 | Rename variable for clarity. | src/Parser/Core/Modules/Items/BFA/Raids/Uldir/InoculatingExtract.js | src/Parser/Core/Modules/Items/BFA/Raids/Uldir/InoculatingExtract.js | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import {formatNumber} from 'common/format';
import ItemHealingDone from 'Interface/Others/ItemHealingDone';
import Analyzer from 'Parser/Core/Analyzer';
/**
* Inoculating Extract -
* Use: Inject 5 stacks of Mutating Antibodies into a friendly target for 30 sec. your direct heals on
* that ally will consume a Mutating Antibody to restore an additional 3135 health. (1 Min, 30 Sec
* Cooldown).
*/
class InoculatingExtract extends Analyzer{
healing = 0;
uses = 0;
constructor(...args){
super(...args);
this.active = this.selectedCombatant.hasTrinket(ITEMS.INOCULATING_EXTRACT.id);
}
on_byPlayer_heal(event){
const spellId = event.ability.guid;
if(spellId === SPELLS.MUTATING_ANTIBODY.id){
this.healing += (event.amount || 0) + (event.absorbed || 0);
this.uses += 1;
}
}
item(){
return{
item: ITEMS.INOCULATING_EXTRACT,
result: (
<React.Fragment>
<dfn data-tip={`Used <b>${Math.ceil(this.uses/5)}</b> times, consuming <b>${this.uses}</b> charges.`}>
{formatNumber(this.healing)} Healing
</dfn><br />
<ItemHealingDone amount={this.healing} />
</React.Fragment>
),
};
}
}
export default InoculatingExtract;
| JavaScript | 0 | @@ -555,18 +555,21 @@
= 0;%0A
-us
+charg
es = 0;%0A
@@ -895,18 +895,21 @@
this.
-us
+charg
es += 1;
@@ -1074,18 +1074,21 @@
il(this.
-us
+charg
es/5)%7D%3C/
@@ -1121,10 +1121,13 @@
his.
-us
+charg
es%7D%3C
|
9624dc70d335ddf42d4860264e1ef9ec35a9ba78 | Simplify JX.JSON.stringify() implementation | src/lib/JSON.js | src/lib/JSON.js | /**
* Simple JSON serializer.
*
* @requires javelin-install javelin-util
* @provides javelin-json
* @javelin
*/
JX.install('JSON', {
statics : {
parse : function(data) {
if (typeof data != 'string'){
return null;
}
if (JSON && JSON.parse) {
var obj;
try {
obj = JSON.parse(data);
} catch (e) {}
return obj || null;
}
return eval('(' + data + ')');
},
stringify : function(obj) {
if (__DEV__) {
try {
return JX.JSON._stringify(obj);
} catch (x) {
JX.log(
'JX.JSON.stringify(...): '+
'caught exception while serializing object. ('+x+')');
}
} else {
return JX.JSON._stringify(obj);
}
},
_stringify : function(val) {
if (JSON && JSON.stringify) { return JSON.stringify(val); }
var out = [];
if (
val === null || val === true || val === false || typeof val == 'number'
) {
return '' + val;
}
if (val.push && val.pop) {
for (var ii = 0; ii < val.length; ii++) {
if (typeof val[ii] != 'undefined') {
out.push(JX.JSON._stringify(val[ii]));
}
}
return '[' + out.join(',') + ']';
}
if (typeof val == 'string') {
return JX.JSON._esc(val);
}
for (var k in val) {
out.push(JX.JSON._esc(k) + ':' + JX.JSON._stringify(val[k]));
}
return '{' + out.join(',') + '}';
},
// Lifted more or less directly from Crockford's JSON2.
_escexp : /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
_meta : {
'\b' : '\\b',
'\t' : '\\t',
'\n' : '\\n',
'\f' : '\\f',
'\r' : '\\r',
'"' : '\\"',
'\\' : '\\\\'
},
_esc : function(str) {
JX.JSON._escexp.lastIndex = 0;
return JX.JSON._escexp.test(str) ?
'"' + str.replace(JX.JSON._escexp, JX.JSON._replace) + '"' :
'"' + str + '"';
},
_replace : function(m) {
if (m in JX.JSON._meta) {
return JX.JSON._meta[m];
}
return '\\u' + (('0000' + m.charCodeAt(0).toString(16)).slice(-4));
}
}
});
| JavaScript | 0.000011 | @@ -468,19 +468,19 @@
unction(
-obj
+val
) %7B%0A
@@ -489,244 +489,31 @@
if (
-__DEV__) %7B%0A try %7B%0A return JX.JSON._stringify(obj);%0A %7D catch (x) %7B%0A JX.log(%0A 'JX.JSON.stringify(...): '+%0A 'caught exception while serializing object. ('+x+')');%0A %7D%0A %7D else
+JSON && JSON.stringify)
%7B%0A
@@ -526,25 +526,21 @@
return
-JX.
JSON.
-_
stringif
@@ -545,126 +545,19 @@
ify(
-obj);%0A %7D%0A %7D,%0A%0A _stringify : function(val) %7B%0A if (JSON && JSON.stringify) %7B return JSON.stringify(val);
+val);%0A
%7D%0A%0A
@@ -862,33 +862,32 @@
ut.push(JX.JSON.
-_
stringify(val%5Bii
@@ -1119,17 +1119,16 @@
JX.JSON.
-_
stringif
|
d967a3c6647697a8e3af70bc9e508843cc534f02 | Fix ‘created_at’ and ‘updated_at’ values in data objects table | src/apps/DataObjects/DataObjectsTable/DataObjectsTableDateCell.js | src/apps/DataObjects/DataObjectsTable/DataObjectsTableDateCell.js | import React from 'react';
import Moment from 'moment';
const DataObjectsTableDateCell = ({ content }) => {
const dateValue = content.value;
const date = Moment(dateValue).format('DD/MM/YYYY');
const time = Moment(dateValue).format('LTS');
const title = `${date} ${time}`;
return (
<div title={title}>
{date}
</div>
);
};
export default DataObjectsTableDateCell;
| JavaScript | 0.000001 | @@ -118,62 +118,25 @@
date
-Value = content.value;%0A const date = Moment(dateValue
+ = Moment(content
).fo
@@ -181,17 +181,15 @@
ent(
-dateValue
+content
).fo
|
fb56e129aed76de6fc3ac624d51cadfcb08ff938 | Update add-and-commit.js | examples/add-and-commit.js | examples/add-and-commit.js | var nodegit = require("../");
var path = require("path");
var fse = require("fs-extra");
var fileName = "newfile.txt";
var fileContent = "hello world";
var directoryName = "salad/toast/strangerinastrangeland/theresnowaythisexists";
/**
* This example creates a certain file `newfile.txt`, adds it to the git
* index and commits it to head. Similar to a `git add newfile.txt`
* followed by a `git commit`
**/
var repo;
var index;
var oid;
nodegit.Repository.open(path.resolve(__dirname, "../.git"))
.then(function(repoResult) {
repo = repoResult;
return fse.ensureDir(path.join(repo.workdir(), directoryName));
}).then(function(){
return fse.writeFile(path.join(repo.workdir(), fileName), fileContent);
})
.then(function() {
return fse.writeFile(
path.join(repo.workdir(), directoryName, fileName),
fileContent
);
})
.then(function() {
return repo.refreshIndex();
})
.then(function(indexResult) {
index = indexResult;
})
.then(function() {
// this file is in the root of the directory and doesn't need a full path
return index.addByPath(fileName);
})
.then(function() {
// this file is in a subdirectory and can use a relative path
return index.addByPath(path.posix.join(directoryName, fileName));
})
.then(function() {
// this will write both files to the index
return index.write();
})
.then(function() {
return index.writeTree();
})
.then(function(oidResult) {
oid = oidResult;
return nodegit.Reference.nameToId(repo, "HEAD");
})
.then(function(head) {
return repo.getCommit(head);
})
.then(function(parent) {
var author = nodegit.Signature.now("Scott Chacon",
"schacon@gmail.com");
var committer = nodegit.Signature.now("Scott A Chacon",
"scott@github.com");
return repo.createCommit("HEAD", author, committer, "message", oid, [parent]);
})
.done(function(commitId) {
console.log("New Commit: ", commitId);
});
| JavaScript | 0.000001 | @@ -1,11 +1,13 @@
-var
+const
nodegit
@@ -25,19 +25,21 @@
%22../%22);%0A
-var
+const
path =
@@ -59,15 +59,16 @@
%22);%0A
-var
+const
fs
-e
= r
@@ -81,21 +81,17 @@
(%22fs
--extra%22);%0Avar
+%22);%0Aconst
fil
@@ -113,19 +113,21 @@
e.txt%22;%0A
-var
+const
fileCon
@@ -148,19 +148,21 @@
world%22;%0A
-var
+const
directo
@@ -415,39 +415,45 @@
*/%0A%0A
-var repo;%0Avar index;%0Avar oid;%0A%0A
+%0A(async () =%3E %7B%0A const repo = await
node
@@ -511,157 +511,132 @@
t%22))
-%0A.then(function(repoResult) %7B%0A repo = repoResult;%0A return fse.ensureDir(path.join(repo.workdir(), directoryName));%0A%7D).then(function()%7B%0A return fse
+;%0A %0A await fs.promises.mkdir(path.join(repo.workdir(), directoryName), %7B%0A recursive: true,%0A %7D);%0A %0A await fs.promises
.wri
@@ -697,42 +697,27 @@
t);%0A
-%7D)%0A.then(function() %7B%0A return fse
+ await fs.promises
.wri
@@ -805,137 +805,56 @@
);%0A
-%7D)%0A.then(function() %7B%0A return repo.refreshIndex();%0A%7D)%0A.then(function(indexResult) %7B%0A index = indexResult;%0A%7D)%0A.then(function() %7B
+ %0A const index = await repo.refreshIndex();%0A
%0A /
@@ -920,38 +920,37 @@
d a full path%0A
-return
+await
index.addByPath
@@ -961,38 +961,16 @@
eName);%0A
-%7D)%0A.then(function() %7B%0A
// thi
@@ -1027,22 +1027,21 @@
path%0A
-return
+await
index.a
@@ -1092,38 +1092,16 @@
Name));%0A
-%7D)%0A.then(function() %7B%0A
// thi
@@ -1139,22 +1139,21 @@
index%0A
-return
+await
index.w
@@ -1164,193 +1164,75 @@
();%0A
-%7D)%0A.then(function() %7B%0A return index.writeTree();%0A%7D)%0A.then(function(oidResult) %7B%0A oid = oidResult;%0A return nodegit.Reference.nameToId(repo, %22HEAD%22);%0A%7D)%0A.then(function(head) %7B%0A return
+ %0A const oid = await index.writeTree();%0A %0A const parent = await
rep
@@ -1240,55 +1240,29 @@
.get
+Head
Commit(
-head);%0A%7D)%0A.then(function(parent) %7B%0A var
+);%0A const
aut
@@ -1337,11 +1337,13 @@
;%0A
-var
+const
com
@@ -1423,14 +1423,30 @@
%0A%0A
-return
+const commitId = await
rep
@@ -1518,37 +1518,8 @@
%5D);%0A
-%7D)%0A.done(function(commitId) %7B
%0A c
@@ -1558,10 +1558,12 @@
tId);%0A%7D)
+()
;%0A
|
48adc22711c25bc843a29ab353e48445ef8578b8 | update math/multiply.js | src/math/multiply.js | src/math/multiply.js | function times (arr) {
return arr.reduce(function (prod, item, key) {
if (key === 0) return prod = item
return prod *= item
})
}
module.exports = times
| JavaScript | 0.000002 | @@ -1,16 +1,48 @@
+var clean = require('./clean')%0A%0A
function times (
@@ -57,19 +57,31 @@
return
-arr
+clean(arr)%0A
.reduce(
@@ -113,16 +113,18 @@
) %7B%0A
+
if (key
@@ -153,16 +153,18 @@
tem%0A
+
return p
@@ -175,16 +175,18 @@
*= item%0A
+
%7D)%0A%7D%0A%0A
|
5fd7dd2fb382264a46cf58d65c7041a2851b575a | use a wait instead of sleep | test/functional/android/gpsdemos/location-specs.js | test/functional/android/gpsdemos/location-specs.js | "use strict";
var setup = require("../../common/setup-base")
, desired = require("./desired");
describe("gpsDemo - location @skip-real-device", function () {
var driver;
setup(this, desired).then(function (d) { driver = d; });
it('should set geo location', function (done) {
var getText = function () {
return driver
.elementsByClassName("android.widget.TextView")
.then(function (els) {
return els[1].text();
});
};
var newLat = "27.17";
var newLong = "78.04";
driver
.resolve(getText())
.then(function (text) {
text.should.not.include("Latitude: " + newLat);
text.should.not.include("Longitude: " + newLong);
})
.setGeoLocation(newLat, newLong)
.sleep(1000)
.then(getText)
.then(function (text) {
text.should.include("Latitude: " + newLat.substr(0, 4));
text.should.include("Longitude: " + newLong.substr(0, 4));
})
.nodeify(done);
});
});
| JavaScript | 0.005995 | @@ -89,18 +89,56 @@
esired%22)
+%0A , Asserter = require('wd').Asserter
;%0A
-
%0Adescrib
@@ -509,16 +509,438 @@
%7D;%0A%0A
+ var textPopulated = new Asserter(%0A function () %7B%0A return getText().then(function (text) %7B%0A if (text === 'GPS Tutorial') %7B%0A var err = new Error('retry');%0A err.retriable = true; // if an asserter throws an error with the %60retriable%60 property set to true, it gets retried%0A throw err;%0A %7D else %7B%0A return true;%0A %7D%0A %7D);%0A %7D%0A );%0A
%0A var
@@ -1226,18 +1226,32 @@
.
-sleep(1000
+waitFor(textPopulated, 3
)%0A
|
38848cc26741ebb7ba23ad593cfa4814c21396c2 | Update line-bot.js | src/line-bot.js | src/line-bot.js | import express from 'express';
import bodyParser from 'body-parser';
import request from 'request';
import config from '../config';
const app = express();
const port = '7123';
const { CHANNEL_ID, CHANNEL_SERECT, MID } = {...config};
const LINE_API = 'https://trialbot-api.line.me/v1/events';
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', (req, res) => {
const result = req.body.result;
for(let i=0; i<result.length; i++){
const data = result[i]['content'];
console.log('receive: ', data);
sendTextMessage(data.from, data.text);
}
});
app.listen(port, () => console.log(`listening on port ${port}`));
function sendTextMessage(sender, text) {
const data = {
to: [sender],
toChannel: 1383378250,
eventType: '138311608800106203',
content: {
contentType: 1,
toType: 1,
text: text+'test'
}
};
console.log('send: ', data);
request({
url: LINE_API,
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'X-Line-ChannelID': CHANNEL_ID,
'X-Line-ChannelSecret': CHANNEL_SERECT,
'X-Line-Trusted-User-With-ACL': MID
},
method: 'POST',
body: JSON.stringify(data)
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
console.log('send response: ', body);
});
}
| JavaScript | 0.000001 | @@ -380,16 +380,24 @@
.post('/
+callback
', (req,
|
40b162bdf2a22e66f686c6368b14e49b73d9d9a8 | Update live-css.js | src/live-css.js | src/live-css.js | var liveCss = (function () {
'use strict';
var _modifiers = {};
var api = {
init: init
}
return api;
/**
* Init live CSS tools
* @param {Object} config Live CSS configuration
*/
function init(config) {
var form = _initForm(),
index = 0;
for (var key in config) {
if (config.hasOwnProperty(key)) {
var css = config[key];
_addModifier(key, css.selectors, css.property);
_addInput(form, key, index, _modifiers[key].elements.length);
index++;
}
}
_addForm(form);
}
/**
* Create container for inputs
* @returns {Element} Container element
*/
function _initForm() {
//var html = '<aside id="live-css" class="live-css"><h1>Live CSS</h1><button>Export</button></aside>';
var form = document.createElement('aside');
form.className = 'css-live';
return form;
}
/**
* Add a modifier in _modifiers list
* @param {String} name Name of the modifier
* @param {Array} selectors List of CSS selectors
* @param {String} property CSS property to modify
*/
function _addModifier(name, selectors, property) {
var elements = [];
for (var selector of selectors) { // ES6
var nodes = document.querySelectorAll(selector);
//for (var node of nodes) { // ES6 not working
for (var i = 0; i < nodes.length; i++) {
elements.push(nodes[i]);
}
}
_modifiers[name] = {
elements: elements,
property: property
};
}
/**
* Create and add input
* @param {Element} form Container element
* @param {String} name Name of the modifier
* @param {Number} index Index of the modifier
* @param {Number} count Number of elements
*/
function _addInput(form, name, index, count) {
var row, labelElt, inputElt;
// Row
row = document.createElement('div');
row.className = 'css-live__row';
// Label
labelElt = document.createElement('label');
labelElt.className = 'css-live__row__label';
labelElt.setAttribute('for', 'css-live-input' + index);
labelElt.appendChild(document.createTextNode(name + ' (' + count + ')'));
row.appendChild(labelElt);
// Input
inputElt = document.createElement('input');
inputElt.setAttribute('type', 'color');
inputElt.name = name; // Used to get config from input
inputElt.id = 'css-live-input' + index;
inputElt.className = 'css-live__row__input';
inputElt.addEventListener('focus', _hightlightElement);
inputElt.addEventListener('blur', _unhightlightElement);
inputElt.addEventListener('change', _updateStyle);
row.appendChild(inputElt);
form.appendChild(row);
}
/**
* Add container element to body
* @param {Element} form Container element
*/
function _addForm(form) {
document.body.appendChild(form);
}
/**
* Highlight the focused element
* @param {Object} event Emitted event
*/
function _hightlightElement(event) {
var modifier = _modifiers[event.target.name];
for (var element of modifier.elements) { // ES6
element.style.border = '1px solid red';
}
}
/**
* Unhighlight the unfocused element
* @param {Object} event Emitted event
*/
function _unhightlightElement(event) {
var modifier = _modifiers[event.target.name];
for (var element of modifier.elements) { // ES6
element.style.border = 'inherit';
}
}
/**
* Update style of the modifier
* @param {Object} event Emitted event
*/
function _updateStyle(event) {
var modifier = _modifiers[event.target.name];
for (var element of modifier.elements) { // ES6
element.style[modifier.property] = event.target.value;
}
}
}()); | JavaScript | 0 | @@ -1128,31 +1128,24 @@
selectors) %7B
- // ES6
%0A%09%09%09var node
@@ -1224,13 +1224,9 @@
//
-ES6 n
+N
ot w
@@ -2884,32 +2884,25 @@
.elements) %7B
- // ES6
%0A
+
%09%09%09element.s
@@ -3151,39 +3151,32 @@
fier.elements) %7B
- // ES6
%0A%09%09%09element.styl
@@ -3361,32 +3361,32 @@
.target.name%5D;%0A%0A
+
%09%09for (var eleme
@@ -3415,15 +3415,8 @@
s) %7B
- // ES6
%0A%09%09%09
|
427415ffff53fbf603a386a9f3dbbbe41102765b | Fix comment typo | examples/nodeloadlib-ex.js | examples/nodeloadlib-ex.js | #!/usr/bin/env node
// Instructions:
//
// 1. Get node (http://nodejs.org/#download)
// 2. git clone http://github.com/benschmaus/nodeload.git
// 3. node nodeload/examples/nodeloadlib-ex.js
//
// This example performs a micro-benchmark of Riak (http://riak.basho.com/), a key-value store,
// running on localhost:8080. First, it first loads 2000 objects into the store as quickly as
// possible. Then, it performs a 90% read + 10% update test at total request rate of 300 rps.
// From minutes 5-8, the read load is increased by 100 rps. The test runs for 10 minutes.
var sys = require('sys');
require('../nodeloadlib');
function riakUpdate(loopFun, client, url, body) {
var req = traceableRequest(client, 'GET', url, { 'host': 'localhost' });
req.addListener('response', function(response) {
if (response.statusCode != 200 && response.statusCode != 404) {
loopFun({req: req, res: response});
} else {
var headers = {
'host': 'localhost',
'content-type': 'text/plain',
'x-riak-client-id': 'bmxpYg=='
};
if (response.headers['x-riak-vclock'] != null)
headers['x-riak-vclock'] = response.headers['x-riak-vclock'];
req = traceableRequest(client, 'PUT', url, headers, body);
req.addListener('response', function(response) {
loopFun({req: req, res: response});
});
req.close();
}
});
req.close();
}
var i=0;
runTest({
name: "Load Data",
host: 'localhost',
port: 8098,
numClients: 20,
numRequests: 2000,
successCodes: [204],
reportInterval: 2,
stats: ['result-codes', 'latency', 'concurrency', 'uniques'],
requestLoop: function(loopFun, client) {
riakUpdate(loopFun, client, '/riak/b/o' + i++, 'original value');
}
}, startRWTest);
function startRWTest() {
process.stdio.write("Running read + update test.");
var reads = addTest({
name: "Read",
host: 'localhost',
port: 8098,
numClients: 30,
timeLimit: 600,
targetRps: 270,
successCodes: [200,404],
reportInterval: 2,
stats: ['result-codes', 'latency', 'concurrency', 'uniques'],
requestGenerator: function(client) {
var url = '/riak/b/o' + Math.floor(Math.random()*8000);
return traceableRequest(client, 'GET', url, { 'host': 'localhost' });
}
});
var writes = addTest({
name: "Write",
host: 'localhost',
port: 8098,
numClients: 5,
timeLimit: 600,
targetRps: 30,
successCodes: [204],
reportInterval: 2,
stats: ['result-codes', 'latency', 'concurrency', 'uniques'],
requestLoop: function(loopFun, client) {
var url = '/riak/b/o' + Math.floor(Math.random()*8000);
riakUpdate(loopFun, client, url, 'updated value');
}
});
// From minute 5, schedule 10x 10 read requests per second in 3 minutes = adding 100 requests/sec
addRamp({
test: reads,
numberOfSteps: 10,
rpsPerStep: 10,
clientsPerStep: 2,
timeLimit: 180,
delay: 300
});
startTests();
}
| JavaScript | 0.000003 | @@ -310,18 +310,23 @@
lhost:80
-80
+98/riak
. First,
@@ -383,14 +383,14 @@
ckly
- as
%0A//
+ as
pos
|
6ae8c74e6d798c75ddb5c9d2a7e23eeddadf7dc1 | Revert "defaultTotalDimension should not exceed screen dimensions (#184)" | FlatGrid.js | FlatGrid.js | import React, {
forwardRef, memo, useState, useCallback, useMemo,
} from 'react';
import {
View, Dimensions, FlatList,
} from 'react-native';
import PropTypes from 'prop-types';
import { chunkArray, calculateDimensions, generateStyles } from './utils';
const FlatGrid = memo(
forwardRef((props, ref) => {
const {
style,
spacing,
fixed,
data,
itemDimension,
renderItem,
horizontal,
onLayout,
staticDimension,
maxDimension,
additionalRowStyle: externalRowStyle,
itemContainerStyle,
keyExtractor,
invertedRow,
maxItemsPerRow,
...restProps
} = props;
// eslint-disable-next-line react/prop-types
if (props.items && !props.data) {
// eslint-disable-next-line no-console
throw new Error('React Native Super Grid - Prop "items" has been renamed to "data" in version 4');
}
const [totalDimension, setTotalDimension] = useState(() => {
let defaultTotalDimension = staticDimension;
if (!staticDimension) {
const dimension = horizontal ? 'height' : 'width';
defaultTotalDimension = Dimensions.get('window')[dimension];
if (maxDimension && defaultTotalDimension > maxDimension) {
defaultTotalDimension = maxDimension;
}
}
return defaultTotalDimension;
});
const onLayoutLocal = useCallback(
(e) => {
if (!staticDimension) {
const { width, height } = e.nativeEvent.layout || {};
let newTotalDimension = horizontal ? height : width;
if (maxDimension && newTotalDimension > maxDimension) {
newTotalDimension = maxDimension;
}
if (totalDimension !== newTotalDimension && newTotalDimension > 0) {
setTotalDimension(newTotalDimension);
}
}
// call onLayout prop if passed
if (onLayout) {
onLayout(e);
}
},
[staticDimension, maxDimension, totalDimension, horizontal, onLayout],
);
const renderRow = useCallback(
({
rowItems,
rowIndex,
separators,
isLastRow,
itemsPerRow,
rowStyle,
containerStyle,
}) => {
// To make up for the top padding
let additionalRowStyle = {};
if (isLastRow) {
additionalRowStyle = {
...(!horizontal ? { marginBottom: spacing } : {}),
...(horizontal ? { marginRight: spacing } : {}),
};
}
return (
<View style={[rowStyle, additionalRowStyle, externalRowStyle]}>
{rowItems.map((item, index) => {
const i = invertedRow ? -index + itemsPerRow - 1 : index;
return (
<View
key={
keyExtractor
? keyExtractor(item, i)
: `item_${rowIndex * itemsPerRow + i}`
}
style={[containerStyle, itemContainerStyle]}
>
{renderItem({
item,
index: rowIndex * itemsPerRow + i,
separators,
rowIndex,
})}
</View>
);
})}
</View>
);
},
[renderItem, spacing, keyExtractor, externalRowStyle, itemContainerStyle, horizontal, invertedRow],
);
const { containerDimension, itemsPerRow, fixedSpacing } = useMemo(
() => calculateDimensions({
itemDimension,
staticDimension,
totalDimension,
spacing,
fixed,
maxItemsPerRow,
}),
[itemDimension, staticDimension, totalDimension, spacing, fixed, maxItemsPerRow],
);
const { containerStyle, rowStyle } = useMemo(
() => generateStyles({
horizontal,
itemDimension,
containerDimension,
spacing,
fixedSpacing,
fixed,
}),
[horizontal, itemDimension, containerDimension, spacing, fixedSpacing, fixed],
);
let rows = chunkArray(data, itemsPerRow); // Splitting the data into rows
if (invertedRow) {
rows = rows.map(r => r.reverse());
}
const localKeyExtractor = useCallback(
(rowItems, index) => {
if (keyExtractor) {
return rowItems
.map((rowItem, rowItemIndex) => keyExtractor(rowItem, rowItemIndex))
.join('_');
}
return `row_${index}`;
},
[keyExtractor],
);
return (
<FlatList
data={rows}
ref={ref}
extraData={totalDimension}
renderItem={({ item, index }) => renderRow({
rowItems: item,
rowIndex: index,
isLastRow: index === rows.length - 1,
itemsPerRow,
rowStyle,
containerStyle,
})
}
style={[
{
...(horizontal
? { paddingLeft: spacing }
: { paddingTop: spacing }),
},
style,
]}
onLayout={onLayoutLocal}
keyExtractor={localKeyExtractor}
{...restProps}
horizontal={horizontal}
/>
);
}),
);
FlatGrid.displayName = 'FlatGrid';
FlatGrid.propTypes = {
renderItem: PropTypes.func.isRequired,
data: PropTypes.arrayOf(PropTypes.any).isRequired,
itemDimension: PropTypes.number,
maxDimension: PropTypes.number,
fixed: PropTypes.bool,
spacing: PropTypes.number,
style: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.array]),
additionalRowStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.array]),
itemContainerStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.array]),
staticDimension: PropTypes.number,
horizontal: PropTypes.bool,
onLayout: PropTypes.func,
keyExtractor: PropTypes.func,
listKey: PropTypes.string,
invertedRow: PropTypes.bool,
maxItemsPerRow: PropTypes.number,
};
FlatGrid.defaultProps = {
fixed: false,
itemDimension: 120,
spacing: 10,
style: {},
additionalRowStyle: undefined,
itemContainerStyle: undefined,
staticDimension: undefined,
horizontal: false,
onLayout: null,
keyExtractor: null,
listKey: undefined,
maxDimension: undefined,
invertedRow: false,
maxItemsPerRow: undefined,
};
export default FlatGrid;
| JavaScript | 0 | @@ -1135,16 +1135,32 @@
nsion =
+maxDimension %7C%7C
Dimensio
@@ -1191,134 +1191,8 @@
on%5D;
-%0A if (maxDimension && defaultTotalDimension %3E maxDimension) %7B%0A defaultTotalDimension = maxDimension;%0A %7D
%0A
|
a850dfcd6edb572ab681c36a850be1e37a983426 | Check for correct route on the compact income expense (#1370) | src/extension/features/reports/compact-income-vs-expense/index.js | src/extension/features/reports/compact-income-vs-expense/index.js | import { Feature } from 'toolkit/extension/features/feature';
import { isCurrentRouteBudgetPage } from 'toolkit/extension/utils/ynab';
export class CompactIncomeVsExpense extends Feature {
injectCSS() { return require('./index.css'); }
shouldInvoke() {
return isCurrentRouteBudgetPage();
}
invoke() {
let viewWidth = $('.reports-content').width();
let columnCount = $('.income-expense-column.income-expense-column-header').length;
let tableWidth = columnCount * 115 + 200 + 32;
let percentage = Math.ceil(tableWidth / viewWidth * 100);
$('.income-expense-table').css({ width: percentage + '%' });
// Strip away YNAB's default scroll behavior
$('.reports-income-expense').off('scroll');
// Re-implement default behavior, but with modifications to the fixed-position header
$('.reports-income-expense').scroll(function (e) {
var r = $('.income-expense-header');
var scrollTop = $('.ember-view.reports-income-expense').scrollTop();
var scrollLeft = $('.ember-view.reports-income-expense').scrollLeft();
if (scrollLeft < 40) {
$('.income-expense-first-column').css({
position: 'static',
maxWidth: 'auto',
left: 0,
borderRight: 'none'
});
} else {
$('.income-expense-first-column').css({
position: 'relative',
maxWidth: $('.income-expense-level2 .income-expense-row .income-expense-column:first-child').outerWidth() || 200,
left: e.scrollLeft - (parseFloat($('.reports-content').css('padding-left') || 0)),
borderRight: '1px solid #dfe4e9'
});
$('.income-expense-h1 .income-expense-first-column').css('borderRight', 'none');
}
if (scrollTop < 40) {
r.css({
position: 'static',
width: 'auto',
marginLeft: 0,
paddingRight: 0
});
$('.income-expense-table').css('padding-top', 0);
} else {
var leftPos = $('.income-expense-income').offset().left;
r.css({
position: 'fixed',
top: $('.reports-header').outerHeight() + $('.reports-controls').outerHeight(),
width: $('.income-expense-income').width(),
marginLeft: -($(e).scrollLeft() || 0),
left: leftPos
});
$('.income-expense-table').css('padding-top', $('.reports-header').outerHeight());
}
});
}
observe(changedNodes) {
if (!this.shouldInvoke()) return;
if (changedNodes.has('income-expense-row') ||
changedNodes.has('income-expense-column income-expense-number') ||
changedNodes.has('income-expense-header')) {
this.invoke();
}
}
onRouteChanged() {
if (this.shouldInvoke()) {
this.invoke();
}
}
}
| JavaScript | 0 | @@ -64,18 +64,19 @@
mport %7B
-is
+get
CurrentR
@@ -79,25 +79,19 @@
entRoute
-BudgetPag
+Nam
e %7D from
@@ -258,18 +258,19 @@
return
-is
+get
CurrentR
@@ -277,19 +277,48 @@
oute
-BudgetPage(
+Name().includes('reports.income-expense'
);%0A
|
af6474db6d94b00ca097b1fceab5c61e57ebe723 | Disable outputting module dependencies when compiling | Gulpfile.js | Gulpfile.js | var gulp = require('gulp'),
babel = require('gulp-babel'),
del = require('del'),
fs = require('fs-extra'),
runSequence = require('run-sequence'),
sourcemaps = require('gulp-sourcemaps'),
watch = require('gulp-watch');
var queue = [];
var inProgress = 0;
var MAX_PARALLEL_CLOSURE_INVOCATIONS = 4;
/**
* @return {Promise} Compilation promise.
*/
var closureCompile = function() {
// Rate limit closure compilation to MAX_PARALLEL_CLOSURE_INVOCATIONS
// concurrent processes.
return new Promise(function(resolve) {
function start() {
inProgress++;
compile().then(function() {
inProgress--;
next();
resolve();
}, function(e) {
console.error('Compilation error', e.message, 'bok ye', e.stack);
process.exit(1);
});
}
function next() {
if (!queue.length) {
return;
}
if (inProgress < MAX_PARALLEL_CLOSURE_INVOCATIONS) {
queue.shift()();
}
}
queue.push(start);
next();
});
};
function compile() {
var closureCompiler = require('google-closure-compiler').gulp();
return new Promise(function(resolve, reject) {
console.log('Starting closure compiler');
// var wrapper = '(function(){%output%})();';
var srcs = [
'src/**/*.js',
'!**_test.js',
'!**/test-*.js'
];
var externs = [];
return gulp.src(srcs).
pipe(sourcemaps.init()).
pipe(closureCompiler({
compilation_level: 'ADVANCED_OPTIMIZATIONS',
warning_level: 'VERBOSE',
language_in: 'ECMASCRIPT6_TYPED',
assume_function_wrapper: true,
language_out: 'ECMASCRIPT5_STRICT',
output_module_dependencies: 'dist/dependencies.json',
// preserve_type_annotations: true,
summary_detail_level: 3,
// new_type_inf: true,
// tracer_mode: 'ALL',
use_types_for_optimization: true,
// output_wrapper: wrapper,
externs: externs,
dependency_mode: 'STRICT',
process_common_js_modules: true,
formatting: ['PRETTY_PRINT'/*, 'PRINT_INPUT_DELIMITER'*/],
js_module_root: '/src',
jscomp_error: '*',
jscomp_warning: ['lintChecks'],
jscomp_off: ['extraRequire', 'inferredConstCheck'],
hide_warnings_for: '[synthetic',
entry_point: 'index',
generate_exports: true,
export_local_property_definitions: true,
angular_pass: true,
// output_manifest: 'dist/manifest.txt',
// variable_renaming_report: 'dist/variable_map.txt',
// property_renaming_report: 'dist/property_map.txt',
js_output_file: 'index.js'
})).
on('error', function(err) {
console.error(err);
process.exit(1);
}).
pipe(sourcemaps.write('/')).
pipe(gulp.dest('dist')).
on('end', function() {
console.log('Compilation successful.');
resolve();
}).
on('error', function() {
console.log('Error during compilation!');
reject();
});
});
}
gulp.task('default', function(cb) {
runSequence('clean', 'compile', cb);
});
gulp.task('clean', function() {
return del(['dist/*']);
});
gulp.task('compile', function() {
return closureCompile();
});
gulp.task('watch', function() {
return gulp.src(['src/**/*.js']).
pipe(watch('src/**/*.js')).
pipe(sourcemaps.init()).
pipe(babel({
presets: ['es2015'], resolveModuleSource: (src, fn) => `./${src}`
})).
pipe(sourcemaps.write('.')).
pipe(gulp.dest('dist'));
});
| JavaScript | 0.000001 | @@ -1989,16 +1989,19 @@
+ //
output_
|
8fdad9ebfabaf4dae64b4e2fbdaca59218da2d23 | Remove redundant ‘gulp-rename’ include from Gulpfile.js | Gulpfile.js | Gulpfile.js | const gulp = require('gulp');
const sass = require('gulp-sass');
const pug = require('gulp-pug');
const rename = require('gulp-rename');
const browserSync = require('browser-sync').create();
gulp.task('demo', ['demo:scss', 'demo:pug'], () => {
browserSync.init({ server: 'demo' });
gulp.watch('demo/**/*.scss', ['demo:scss']);
gulp.watch('demo/**/*.pug', ['demo:pug']);
});
gulp.task('demo:scss', () => (
gulp
.src('demo/demo.scss')
.pipe(sass({ includePaths: ['scss'] }).on('error', sass.logError))
.pipe(gulp.dest('demo'))
.pipe(browserSync.stream())
));
gulp.task('demo:pug', () => (
gulp
.src('demo/index.pug')
.pipe(pug({ basedir: 'demo' }))
.pipe(gulp.dest('demo'))
.pipe(browserSync.stream())
));
| JavaScript | 0 | @@ -95,47 +95,8 @@
');%0A
-const rename = require('gulp-rename');%0A
cons
|
40d9953a4b9b3e924f4d5210b0a9d66e49de0625 | add gulp config | Gulpfile.js | Gulpfile.js | JavaScript | 0.000001 | @@ -1 +1,538 @@
%0A
+var gulp = require('gulp')%0Avar webpack = require('webpack')%0Avar wpConf = require('./webpack.config.js')%0Avar gutil = require('gulp-util')%0Avar mocha = require('gulp-mocha')%0A%0Agulp.task('default', %5B'webpack'%5D)%0A%0Agulp.task('test', %5B'webpack'%5D, function () %7B%0A return gulp.src('test/index.js', %7Bread: false%7D)%0A .pipe(mocha(%7B%7D))%0A%7D)%0A%0Agulp.task('webpack', function (callback) %7B%0A webpack(wpConf, function (err, stats) %7B%0A if (err) throw new gutil.PluginError('webpack', err)%0A gutil.log('%5Bwebpack%5D', stats.toString(%7B%7D))%0A callback()%0A %7D)%0A%7D)%0A
| |
e5e266d54dce041c404014c389c5cfaf1f529d9d | Update default gulp tasks | Gulpfile.js | Gulpfile.js | 'use strict'; // eslint-disable-line
/**
* Gulp file for front-end js check and etc.
* Date : 2015/10/21
* copyright : (c) hustcer
*/
let gulp = require('gulp'),
sloc = require('gulp-sloc2'),
eslint = require('gulp-eslint'),
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant');
gulp.task('check', () => {
let src = ['Gulpfile.js', 'star.js', 'lib/**/*.js'];
return gulp.src(src)
.pipe(eslint({ configFile: 'eslint.json' }))
.pipe(eslint.format('stylish'));
});
gulp.task('sloc', () => {
let src = ['Gulpfile.js', 'star.js', 'lib/**/*.js'];
gulp.src(src).pipe(sloc());
});
gulp.task('opt', () => {
let imgPath = ['snapshot/*'];
return gulp.src(imgPath)
.pipe(imagemin({
progressive : true,
use : [pngquant()],
}))
.pipe(gulp.dest('snapshot/'));
});
let defaultTasks = ['check', 'opt'];
gulp.task('default', defaultTasks, () => {
console.log(`---------> All gulp task has been done! Task List: ${defaultTasks}`);
});
| JavaScript | 0.000001 | @@ -1011,16 +1011,24 @@
', 'opt'
+, 'sloc'
%5D;%0A%0Agulp
|
391d465df75ecea6b9f049cc1e1e982ebc25728b | add specs to jshint task | Gulpfile.js | Gulpfile.js | var _ = require('lodash');
var express = require('express');
var fs = require('fs');
var gulp = require('gulp');
var lr = require('tiny-lr');
var path = require('path');
var browserify = require('gulp-browserify');
var concat = require('gulp-concat');
var gulpif = require('gulp-if');
var gzip = require('gulp-gzip');
var haml = require('gulp-haml');
var imagemin = require('gulp-imagemin');
var jasmine = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var refresh = require('gulp-livereload');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var stylus = require('gulp-stylus');
var server = lr();
var config = _.extend({
port: 8080,
lrport: 35729,
env: 'development'
}, gulp.env);
console.log(config);
var production = config.env === 'production';
gulp.task('lr-server', function () {
server.listen(config.lrport, function (err) {
if (err) {
console.log(err);
}
});
});
gulp.task('commands', function () {
var commands =
fs.readdirSync('src/js/lib/commands')
.filter(function (f) {
return f[0] != '.' && f.substr(-3) == '.js';
}).map(function (f) {
return 'require("' + './commands/' + f + '");';
});
fs.writeFileSync('src/js/lib/commands.js', commands.join('\n'));
});
gulp.task('file-system', function () {
var _fs = {};
var _ignore = [
'.DS_Store'
];
var root = 'src/js/lib/fs';
(function readdir(path, container) {
var files = fs.readdirSync(path);
files.forEach(function (file) {
if (~_ignore.indexOf(file)) {
return;
}
var stat = fs.statSync(path + '/' + file);
if (stat.isDirectory()) {
var f = {};
readdir(path + '/' + file, f);
container[file] = f;
} else {
container[file] = fs.readFileSync(path + '/' + file).toString();
}
});
})(root, _fs);
fs.writeFileSync('src/js/lib/file-system.json', JSON.stringify(_fs, null, 2));
});
gulp.task('jshint', function() {
gulp.src(['Gulpfile.js', 'src/js/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('js', ['jshint', 'commands', 'file-system'], function () {
gulp.src('src/js/main.js')
.pipe(browserify({ debug: !production }))
.pipe(concat('all.js'))
.pipe(gulpif(production, uglify()))
.pipe(gulp.dest('out/js'))
.pipe(gulpif(production, gzip()))
.pipe(gulpif(production, gulp.dest('out/js')))
.pipe(refresh(server));
});
gulp.task('css', function () {
gulp.src('src/css/**/*.styl')
.pipe(stylus({ set: production ? ['compress'] : [] }))
.pipe(concat('all.css'))
.pipe(gulp.dest('out/css'))
.pipe(gulpif(production, gzip()))
.pipe(gulp.dest('out/css'))
.pipe(refresh(server));
});
gulp.task('images', function () {
gulp.src('src/images/**')
.pipe(gulpif(production, imagemin()))
.pipe(gulp.dest('out/images'))
.pipe(refresh(server));
});
gulp.task('html', function () {
gulp.src('src/**/*.haml')
.pipe(haml({ optimize: production }))
.pipe(gulp.dest('out'))
.pipe(gulpif(production, gzip()))
.pipe(gulp.dest('out'))
.pipe(refresh(server));
});
gulp.task('start-server', function() {
express()
.use(express.static(path.resolve("./out")))
.use(express.directory(path.resolve("./out")))
.listen(config.port, function() {
console.log("Listening on ", config.port);
});
});
gulp.task('spec', function () {
gulp.src('spec/**/*-spec.js')
.pipe(jasmine());
});
gulp.task('build', ['js', 'css', 'images', 'html']);
gulp.task('server', ['build', 'lr-server', 'start-server'], function () {
gulp.watch('src/js/**/*.js', function () {
gulp.run('js');
});
gulp.watch('src/css/**/*.styl', function () {
gulp.run('css');
});
gulp.watch('src/images/**', function () {
gulp.run('images');
});
gulp.watch('src/**/*.haml', function () {
gulp.run('html');
});
});
| JavaScript | 0 | @@ -2016,16 +2016,32 @@
ile.js',
+ 'spec/**/*.js',
'src/js
|
2e87a7e7c903d8704e0b03469d6d9816172a7f68 | Comment out unused header | src/models/Server.js | src/models/Server.js | import axios from 'axios'
export default axios.create({
// baseURL: process.env.REACT_APP_API_SERVER,
headers: {'X-Key-Inflection': 'camel'}, // camel case keys
timeout: 30000,
})
| JavaScript | 0 | @@ -99,16 +99,19 @@
ERVER,%0A
+ //
headers
@@ -162,16 +162,80 @@
ase keys
+ // created by Olive Branch on server side, not currently in use
%0A timeo
|
08964c74088b08deb7605e65a05fc7ff5e1f85fc | use flatMap on sequences instead of .map().flatten()Immutable sequence are lazy: cannot relate on order of map() and flatten() | src/modules/merge.js | src/modules/merge.js | 'use strict';
const Immutable = require('immutable');
const UNIQUE_PREFIX = 'cashflow_unique_prefix';
const mergeCFFs = (immutableCFFs) => {
const mergeLines = (lines) => {
const groupedLinesMap = lines.reduce(
(acc, line, index) => {
const lineID = line.has('id') ? line.get('id') : UNIQUE_PREFIX + index;
const mergedFrom = acc.has(lineID) ? acc.get(lineID).get('mergedFrom') : Immutable.Vector();
const newLine = line.set('mergedFrom', mergedFrom.push(line.get('parentID'))).remove('parentID');
return acc.mergeDeep(Immutable.Map().set(lineID, newLine));
},
Immutable.Map()
);
return groupedLinesMap.toVector();
};
const mergeSourceDescriptions = (immutableCFFs) => {
return immutableCFFs.reduce((acc, x, index) => {
return index === immutableCFFs.length - 1 ?
acc + x.get('sourceDescription') :
acc + x.get('sourceDescription') + ', ';
},
'merge of: '
);
};
const groupedLines = immutableCFFs.map((cff) => {
// save parentID inside each line
return cff.get('lines').map((line) => line.set('parentID', cff.get('sourceId')));
}).flatten();
const mergedLines = mergeLines(groupedLines);
return Immutable.fromJS(
{
sourceId: 'MERGE_MODULE',
sourceDescription: mergeSourceDescriptions(immutableCFFs),
lines: mergedLines
}
);
};
module.exports = mergeCFFs;
| JavaScript | 0.000002 | @@ -791,28 +791,24 @@
=%3E %7B%0A
-
return index
@@ -839,36 +839,32 @@
h - 1 ?%0A
-
acc + x.get('sou
@@ -887,28 +887,24 @@
: %0A
-
-
acc + x.get(
@@ -938,27 +938,19 @@
;%0A
- %7D,%0A
+%7D,%0A
'm
@@ -1010,17 +1010,21 @@
bleCFFs.
-m
+flatM
ap((cff)
@@ -1025,26 +1025,24 @@
((cff) =%3E %7B%0A
-
// save
@@ -1067,18 +1067,16 @@
ch line%0A
-
retu
@@ -1159,21 +1159,9 @@
;%0A
- %7D).flatten(
+%7D
);%0A%0A
@@ -1208,18 +1208,16 @@
Lines);%0A
-
%0A retur
|
9ed6fc520c678fa2cf118a5db7096e65a5e7cafe | update code style | src/num-util.js | src/num-util.js | /**
* Verificar se um valor é um número, da língua portuguesa, valido.
*
* @method isValidNumber
* @param {string} val Um valor para ser verificado.
* @returns {boolean} Verificação do valor.
*/
export const isValidNumber = (val, isCommaSeparator=false) => {
if (typeof val === 'number') {
// Se for um inteiro e não for seguro
if (Number.isInteger(val) && !Number.isSafeInteger(val)) {
return false
}
// Se for um float
if (!Number.isInteger(val)) {
return true
}
}
/*
* Geral
*/
// "1000000", "-2000", etc.
const isNotFormatted = /^-?\d+$/.test(val)
/*
* Separados por "." (ponto)
*/
// "1.000.000", "-2.000", etc.
const isFormattedDot = /^-?\d{1,3}\d?((\.\d{3})+)?$/.test(val)
// "1.000.000,42", "-2.000,00", etc.
const isFormattedDecimalDot = /^-?\d{1,3}\d?((\.\d{3})+)?,\d+$/.test(val)
// "1000000,42", "-2000,00", etc.
const isNotFormattetDecimalDot = /^-?\d+,\d+$/.test(val)
/*
* Separados por "," (vírgula)
*/
// "1,000,000", "-2,000", etc.
const isFormattedComma = /^-?\d{1,3}\d?((,\d{3})+)?$/.test(val)
// "1,000,000.42", "-2,000.00", etc.
const isFormattedDecimalComma = /^-?\d{1,3}\d?((,\d{3})+)?\.\d+$/.test(val)
// "1000000.42", "-2000.00", etc.
const isNotFormattetDecimalComma = /^-?\d+\.\d+$/.test(val)
if (isCommaSeparator) {
return isNotFormatted
|| isFormattedComma
|| isFormattedDecimalComma
|| isNotFormattetDecimalComma
}
return isNotFormatted
|| isFormattedDot
|| isFormattedDecimalDot
|| isNotFormattetDecimalDot
}
/**
* Analisar um número.
*
* @method parseNumber
* @param {string} val Um número para ser analisado
* @returns {object} Objeto com as informações do número
*/
export const parseNumber = (num, isCommaSeparator=false) => {
const separator = isCommaSeparator ? ',' : '.'
const decimalSeparator = isCommaSeparator ? '.' : ','
const isNegative = /^-/.test(num)
const normalized = num.replace(RegExp(`(-|\\${separator})`, 'g'), '')
if (normalized.includes(decimalSeparator)) {
const [integer, decimal] = normalized
.split(decimalSeparator)
.map((val) => val.replace(/^0+$/, '0'))
return {
isNegative,
integer,
decimal
}
}
return {
isNegative,
integer: normalized,
decimal: '0'
}
} | JavaScript | 0 | @@ -2098,16 +2098,17 @@
const %5B
+
integer,
@@ -2115,16 +2115,17 @@
decimal
+
%5D = norm
|
1398ab01c34bb7264190d75fd71949c88afacd3c | Move store and records declarations | lib/mixins/ampersand-sync-localstorage.js | lib/mixins/ampersand-sync-localstorage.js | function guid() {
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
}
module.exports = function (name) {
var store = localStorage.getItem(name),
records = (store && store.split(',')) || [];
return function (method, model, options) {
var result;
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
model = options.attrs || model.toJSON(options);
}
try {
switch(method) {
case 'create':
if (!model.id) model.id = guid();
records.push(model.id.toString());
case 'update':
if(records.indexOf(model.id.toString()) === -1) records.push(model.id.toString());
localStorage.setItem(name + '-' + model.id, JSON.stringify(model));
break;
case 'patch':
// TODO
throw new Error('not implemented');
break;
case 'delete':
records.splice(records.indexOf(model.id.toString()), 1);
localStorage.removeItem(name + '-' + model.id);
break;
case 'read':
if(!model.id) {
result = records
.map(function (id) { return JSON.parse(localStorage.getItem(name + '-' + id)); })
.filter(function (r) { return r !== null });
} else {
result = JSON.parse(localStorage.getItem(name + '-' + model.id));
}
break;
}
localStorage.setItem(name, records.join(','));
} catch (ex) {
if (options && options.error) options.error(result, 'error', ex.message)
else throw ex;
}
if (options && options.success) options.success(result, 'success');
};
};
| JavaScript | 0 | @@ -235,24 +235,75 @@
on (name) %7B%0A
+ return function (method, model, options) %7B%0A
var stor
@@ -390,56 +390,8 @@
%5B%5D;
-%0A%0A return function (method, model, options) %7B
%0A
|
eb554106d77496e98d7e1cda5f7024ab7c4e4c8c | Add style for close window button in paymentr.js | src/paymentr.js | src/paymentr.js | (function () {
"use strict";
function receiveMessage(event) {
if (event.data.url) {
window.location.href = event.data.url;
};
return false;
}
window.addEventListener("message", receiveMessage, false);
var PaymentForm = function (options) {
if (!options.url) {
return false;
};
this.url = options.url;
this.styles = options.style;
this.type = options.type;
this.anchor = options.id;
this.iframeDivId = 'paymentForm';
if (options.size) {
this.size = options.size;
} else {
this.size = { height: 320, width: 350 };
};
};
PaymentForm.prototype.isMobile = function () {
if ( navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/Windows Phone/i) ) {
return true;
} else {
return false;
}
}
PaymentForm.prototype.prepareIframe = function (url) {
var iframeDiv = document.createElement("div");
iframeDiv.setAttribute("id", this.iframeDivId);
iframeDiv.style.display = "none";
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", url);
iframe.setAttribute("frameborder", "0");
iframe.style.display = "block";
iframe.style.margin = "auto";
if (this.size) {
iframe.style.width = this.size.width + "px";
iframe.style.height = this.size.height + "px";
};
iframeDiv.appendChild(iframe);
if (this.anchor && document.getElementById(this.anchor)) {
document.getElementById(this.anchor).appendChild(iframeDiv);
} else {
document.body.appendChild(iframeDiv);
};
var styles = this.styles;
iframe.onload = function() {
iframe.contentWindow.postMessage({ css: styles }, "*");
$('a#closeWindow').click(function() {
$('#dialogWindow').dialog('close');
});
};
return iframe;
}
PaymentForm.prototype.buildOverlayForm = function (url) {
var linkId = '#' + this.anchor;
var size = this.size;
var that = this;
var dialogId = "dialogWindow";
var emptyDiv = document.createElement('div');
emptyDiv.setAttribute("id", dialogId);
document.body.appendChild(emptyDiv);
var reg = new RegExp('([http|https].+\/)checkout')
var path = reg.exec(this.url)[1];
var cssPath = path + 'stylesheets/jquery-ui.min.css'
$('body').append('<link rel="stylesheet" href="' + cssPath + '">');
$(linkId).click(function(event) {
event.preventDefault();
if (that.isMobile()) {
window.open(that.url);
return false;
}
$('#' + dialogId).dialog({
modal: true,
width: size.width + 10,
height: size.height + 30,
show: {
effect: "fadeIn"
},
hide: {
effect: "fadeOut"
},
open: function () {
if ($('#' + dialogId).children('iframe').size() == 0) {
document.getElementById(dialogId).appendChild(that.prepareIframe(url + "&iframe=true"));
if ($('#closeWindow').size() == 0) {
$('.ui-dialog').prepend("<a href='#' id='closeWindow'></div>");
};
};
}
});
});
};
PaymentForm.prototype.buildInlineForm = function(url) {
if (!this.isMobile()) {
url = url + "&iframe=true";
};
this.prepareIframe(url);
$('#' + this.iframeDivId).show();
}
PaymentForm.prototype.buildForm = function () {
if (options.style) {
this.styles = options.style;
};
if (this.type == 'overlay') {
this.buildOverlayForm(this.url);
return false;
};
if (this.type == 'inline') {
this.buildInlineForm(this.url);
return false;
};
};
window.PaymentForm = PaymentForm;
}());
| JavaScript | 0 | @@ -3150,24 +3150,82 @@
'%3E%3C/div%3E%22);%0A
+ $(%22a#closeWindow%22).css(%22left%22, size.width);%0A
|
a0e49e96b36630a945bb5b8f34d85e4b60d545de | fix homepage | src/quiz/QuizView.js | src/quiz/QuizView.js | import React, { Component } from 'react'
import firebase from 'firebase'
import {HashLink as Link} from 'react-router-hash-link'
import _copyNested from '../_shared/_copyNested'
import Option from './Option'
import './QuizView.css'
class QuizView extends Component {
constructor (props) {
super(props)
this.state = {
answerData: this.props.answerData,
}
this._onInputChange = this._onInputChange.bind(this)
this._onInputSubmit = this._onInputSubmit.bind(this)
this._onSelect = this._onSelect.bind(this)
}
componentWillReceiveProps (nextProps) {
this.setState((prevState, props) => {
return {
answerData: nextProps.answerData,
}
})
}
_onInputChange (event) {
this.setState((prevState, props) => {
prevState.answerData = event.target.value || ''
return prevState
})
}
_onInputSubmit (event) {
firebase.database().ref(`answer/${this.props.answerOwner}/${this.props.quizData.id}`).set(this.state.answerData)
}
_onSelect (event) {
firebase.database().ref(`answer/${this.props.answerOwner}/${this.props.quizData.id}`).set(event.target.getAttribute('data-value'))
}
render () {
const orderData = this.props.orderData || {}
const quizData = this.props.quizData
const optionData = quizData.option
const routeData = quizData.route
const answerData = this.state.answerData
let answerDataJSX
if (quizData.type === 'select') {
if (optionData) {
const optionDataJSX = optionData.map((item, key) => {
const className = answerData === item.value ? 'active' : ''
const next = routeData ?
(routeData[item.value] || orderData.next)
: orderData.next
return (
<Option
{...item}
key={key}
next={next}
className={className}
onClick={this._onSelect}
/>
)
})
answerDataJSX = (
<div className='ui vertical fluid basic buttons'>
{optionDataJSX}
</div>
)
}
}
if (quizData.type === 'input') {
const link = orderData.next ? `/quiz/${orderData.next}/` : '/answer/'
answerDataJSX = (
<div className='ui action input'>
<input
type='text'
id={quizData.id}
placeholder={answerData}
value={answerData}
onChange={this._onInputChange}
/>
<Link
to={link}
className='ui button'
onClick={this._onInputSubmit}
>
Submit
</Link>
</div>
)
}
return (
<section className='QuizView'>
<div className='Question ui center aligned basic segment'>
<h3 className='ui header'>
{quizData.title}
</h3>
<p>
{quizData.description}
</p>
{ answerDataJSX }
</div>
</section>
)
}
}
export default QuizView
| JavaScript | 0.000007 | @@ -1275,16 +1275,62 @@
uizData%0A
+ if (!quizData) %7B%0A return null%0A %7D%0A%0A
cons
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.