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 |
|---|---|---|---|---|---|---|---|
e0f2b4b2b83da856a18cd0c234c24fd9bb719a24 | use lookup for rank weighting | src/modules/rank.js | src/modules/rank.js | import * as ajax from './support/ajax';
import * as layout from './support/layout';
import * as system from './support/system';
import * as task from './support/task';
var ranks;
var myRank;
var theRows;
var rankCount;
var characterRow;
function parseRankData(linkElement, responseText) { // Native
// Makes a weighted calculation of available permissions and gets tax rate
var doc = system.createDocument(responseText);
var checkBoxes = doc.querySelectorAll(
'#pCC input[type="checkbox"]:checked');
var count = 0;
Array.prototype.forEach.call(checkBoxes, function(checkbox) {
var privName = checkbox.nextElementSibling.textContent.trim();
if (privName === 'Bank Withdraw' ||
privName === 'Build/Upgrade/Demolish Structures' ||
privName === 'Can Un-Tag Items') {
count += 5;
} else if (privName === 'Build/Upgrade Structures' ||
privName === 'Can Kick Members') {
count += 4;
} else if (privName === 'Can Mass Messages') {
count += 0.5;
} else if (privName === 'Take Items' ||
privName === 'Can Recall Tagged Items') {
count += 0.2;
} else if (privName === 'Store Items' ||
privName === 'Can View Advisor') {
count += 0.1;
} else {
count += 1;
}
});
var taxRate = doc.querySelector('#pCC input[name="rank_tax"]').value;
linkElement.insertAdjacentHTML('afterbegin', '<span class="fshBlue">(' +
Math.round(10 * count) / 10 + ') Tax:(' + taxRate + '%)</span> ');
}
function fetchRankData() { // jQuery
var calcButton = document.getElementById('getrankweightings');
calcButton.classList.add('fshHide');
var allItems = document.querySelectorAll('#pCC input[value="Edit"]');
Array.prototype.forEach.call(allItems, function(anItem) {
var targetNode = anItem.parentNode.parentNode.previousElementSibling;
var href = /window\.location='(.*)';/.exec(anItem
.getAttribute('onclick'))[1];
$.get(href).done(parseRankData.bind(null, targetNode));
});
}
function ajaxifyRankControls(evt) { // jQuery
var val = evt.target.getAttribute('value');
if (val !== 'Up' && val !== 'Down') {return;}
evt.stopPropagation();
var onclickHREF = /window.location='(.*)';/
.exec(evt.target.getAttribute('onclick'))[1];
var thisRankRow = evt.target.parentNode.parentNode.parentNode;
var thisRankRowNum = thisRankRow.rowIndex;
var targetRowNum = thisRankRowNum + (val === 'Up' ? -1 : 2);
var parentTable = thisRankRow.parentNode;
if (characterRow >= Math.min(thisRankRowNum, targetRowNum) ||
targetRowNum < 1 ||
targetRowNum > parentTable.rows.length) {return;}
$.get(onclickHREF);
var injectRow = parentTable.rows[targetRowNum];
parentTable.insertBefore(thisRankRow, injectRow);
window.scrollBy(0, val === 'Up' ? -22 : 22);
}
function doButtons() { // Native
// gather rank info button
var weightButton = document.createElement('input');
weightButton.id = 'getrankweightings';
weightButton.className = 'custombutton';
weightButton.setAttribute('type', 'button');
weightButton.setAttribute('value', 'Get Rank Weightings');
weightButton.addEventListener('click', fetchRankData);
var theTd = document.getElementById('show-guild-founder-rank-name')
.parentNode;
theTd.insertAdjacentHTML('beforeend', ' ');
theTd.insertAdjacentElement('beforeend', weightButton);
if (system.getValue('ajaxifyRankControls')) {
layout.pCC.addEventListener('click',
ajaxifyRankControls, true);
}
}
function paintRanks() { // Native
var limit = performance.now() + 10;
while (performance.now() < limit &&
rankCount < theRows.length) {
var el = theRows[rankCount];
var rankCell = el.firstElementChild;
var rankName = rankCell.textContent;
if (ranks[rankName]) { // has members
if (rankName === myRank) {
characterRow = rankCount; // limit for ajaxify later
}
rankCell.insertAdjacentHTML('beforeend', ' <span class="fshBlue">- ' +
ranks[rankName].join(', ') + '</span>');
}
rankCount += 1;
}
if (rankCount < theRows.length) {
task.add(3, paintRanks);
}
}
function getRanks(membrList) { // Native
ranks = Object.keys(membrList).reduce(function(prev, curr) {
if (curr !== 'lastUpdate') {
var rankName = membrList[curr].rank_name;
prev[rankName] = prev[rankName] || [];
prev[rankName].push(curr);
}
return prev;
}, {});
myRank = membrList[layout.playerName()].rank_name;
theRows = layout.pCC.firstElementChild
.nextElementSibling.rows[13].firstElementChild.firstElementChild.rows;
rankCount = 1;
task.add(3, paintRanks);
}
export function injectGuildRanks() { // jQuery
ajax.getMembrList(true).done(function(membrList) {
task.add(3, getRanks, [membrList]);
});
task.add(3, doButtons);
}
| JavaScript | 0 | @@ -232,16 +232,317 @@
erRow;%0A%0A
+var privLookup = %7B%0A 'Bank Withdraw': 5,%0A 'Build/Upgrade/Demolish Structures': 5,%0A 'Can Un-Tag Items': 5,%0A 'Build/Upgrade Structures': 4,%0A 'Can Kick Members': 4,%0A 'Can Mass Messages': 0.5,%0A 'Take Items': 0.2,%0A 'Can Recall Tagged Items': 0.2,%0A 'Store Items': 0.1,%0A 'Can View Advisor': 0.1%0A%7D;%0A%0A
function
@@ -975,552 +975,60 @@
ame
-=== 'Bank Withdraw' %7C%7C%0A privName === 'Build/Upgrade/Demolish Structures' %7C%7C%0A privName === 'Can Un-Tag Items') %7B%0A count += 5;%0A %7D else if (privName === 'Build/Upgrade Structures' %7C%7C%0A privName === 'Can Kick Members') %7B%0A count += 4;%0A %7D else if (privName === 'Can Mass Messages') %7B%0A count += 0.5;%0A %7D else if (privName === 'Take Items' %7C%7C%0A privName === 'Can Recall Tagged Items') %7B%0A count += 0.2;%0A %7D else if (privName === 'Store Items' %7C%7C%0A privName === 'Can View Advisor') %7B%0A count += 0.1
+in privLookup) %7B%0A count += privLookup%5BprivName%5D
;%0A
@@ -1037,23 +1037,16 @@
%7D else %7B
-%0A
count +=
@@ -1048,21 +1048,16 @@
nt += 1;
-%0A
%7D%0A %7D);%0A
|
4fa0907b0afff8f64bf9c6a7592f7f70e6e8dddf | Add stub implementation for 'getAudioTracks' and 'getVideoTracks' methods | platform/video.html5/backend.js | platform/video.html5/backend.js | var Player = function(ui) {
var player = ui._context.createElement('video')
player.dom.preload = "metadata"
var dom = player.dom
player.on('play', function() { ui.waiting = false; ui.paused = dom.paused }.bind(ui))
player.on('pause', function() { ui.paused = dom.paused }.bind(ui))
player.on('ended', function() { ui.finished() }.bind(ui))
player.on('seeked', function() { log("seeked"); ui.seeking = false; ui.waiting = false }.bind(ui))
player.on('canplay', function() { log("canplay", dom.readyState); ui.ready = dom.readyState }.bind(ui))
player.on('seeking', function() { log("seeking"); ui.seeking = true; ui.waiting = true }.bind(ui))
player.on('waiting', function() { log("waiting"); ui.waiting = true }.bind(ui))
player.on('stalled', function() { log("Was stalled", dom.networkState); }.bind(ui))
player.on('emptied', function() { log("Was emptied", dom.networkState); }.bind(ui))
player.on('volumechange', function() { ui.muted = dom.muted }.bind(ui))
player.on('canplaythrough', function() { log("ready to play"); ui.paused = dom.paused }.bind(ui))
player.on('error', function() {
log("Player error occured", dom.error, "src", ui.source)
if (!dom.error || !ui.source)
return
ui.error(dom.error)
log("player.error", dom.error)
switch (dom.error.code) {
case 1:
log("MEDIA_ERR_ABORTED error occured")
break;
case 2:
log("MEDIA_ERR_NETWORK error occured")
break;
case 3:
log("MEDIA_ERR_DECODE error occured")
break;
case 4:
log("MEDIA_ERR_SRC_NOT_SUPPORTED error occured")
break;
default:
log("UNDEFINED error occured")
break;
}
}.bind(ui))
player.on('timeupdate', function() {
ui.waiting = false
if (!ui.seeking)
ui.progress = dom.currentTime
}.bind(ui))
player.on('durationchange', function() {
var d = dom.duration
log("Duration", d)
ui.duration = isFinite(d) ? d : 0
}.bind(ui))
player.on('progress', function() {
var last = dom.buffered.length - 1
ui.waiting = false
if (last >= 0)
ui.buffered = dom.buffered.end(last) - dom.buffered.start(last)
}.bind(ui))
this.element = player
this.ui = ui
ui.element.remove()
ui.element = player
ui.parent.element.append(ui.element)
this.setAutoPlay(ui.autoPlay)
}
Player.prototype.setSource = function(url) {
this.ui.ready = false
this.element.dom.src = url
}
Player.prototype.play = function() {
this.element.dom.play()
}
Player.prototype.pause = function() {
this.element.dom.pause()
}
Player.prototype.stop = function() {
//where is no 'stop' method in html5 video player just pause instead
this.pause()
}
Player.prototype.seek = function(delta) {
this.element.dom.currentTime += delta
}
Player.prototype.seekTo = function(tp) {
this.element.dom.currentTime = tp
}
Player.prototype.setVolume = function(volume) {
this.element.dom.volume = volume
}
Player.prototype.setMute = function(muted) {
this.element.dom.muted = muted
}
Player.prototype.setLoop = function(loop) {
this.element.dom.loop = loop
}
Player.prototype.setAutoPlay = function(autoPlay) {
if (autoPlay)
this.element.dom.setAttribute("autoplay", "")
else
this.element.dom.removeAttribute("autoplay");
}
Player.prototype.setRect = function(l, t, r, b) {
//not needed in this port
}
Player.prototype.setVisibility = function(visible) {
log('VISIBILITY LOGIC MISSING HERE, visible:', visible)
}
Player.prototype.setupDrm = function(type, options, callback, error) {
log('Not implemented')
}
Player.prototype.setBackgroundColor = function(color) {
var Color = _globals.core.Color
this.element.dom.style.backgroundColor = new Color(color).rgba()
}
exports.createPlayer = function(ui) {
return new Player(ui)
}
exports.probeUrl = function(url) {
return 50
}
exports.Player = Player
| JavaScript | 0 | @@ -3444,24 +3444,172 @@
mented')%0A%7D%0A%0A
+Player.prototype.getAudioTracks = function() %7B%0A%09log('Not implemented')%0A%7D%0A%0APlayer.prototype.getVideoTracks = function() %7B%0A%09log('Not implemented')%0A%7D%0A%0A
Player.proto
|
0dccdf845643ffa3e017254649a5a58c2c0f5752 | fix auto-complete | playground/src/editor/editor.js | playground/src/editor/editor.js | // Copyright 2018 The AMPHTML Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/monokai.css';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/selection/selection-pointer.js';
import 'codemirror/addon/selection/active-line.js';
import 'codemirror/addon/edit/closebrackets.js';
import 'codemirror/addon/edit/closetag.js';
import 'codemirror/addon/hint/show-hint.js';
import 'codemirror/addon/hint/xml-hint.js';
import 'codemirror/addon/hint/html-hint.js';
import 'codemirror/addon/hint/css-hint.js';
import 'codemirror/mode/css/css.js';
import 'codemirror/mode/htmlmixed/htmlmixed.js';
import 'codemirror/mode/javascript/javascript.js';
import 'codemirror/mode/xml/xml.js';
import events from '../events/events.js';
import {runtimes, EVENT_SET_RUNTIME} from '../runtime/runtimes.js';
import './editor.css';
import './hints.css';
import CodeMirror from 'codemirror';
import Loader from '../loader/base.js';
import { resolve } from 'url';
const DEFAULT_DEBOUNCE_RATE = 500;
const HINT_IGNORE_ENDS = new Set([
';', ',',
')',
'`', '"', "'",
">",
"{", "}",
"[", "]"
]);
const HINTS_URL = 'amphtml-hint.json';
export const EVENT_INPUT_CHANGE = 'editor-input-change';
export const EVENT_INPUT_NEW = 'editor-input-new';
export function createEditor(container) {
return new Editor(container, window);
}
class Editor {
constructor(container, win) {
this.container = container;
this.win = win;
this.debounceRate = DEFAULT_DEBOUNCE_RATE;
this.createCodeMirror();
this.errorMarkers = [];
this.loader = new Loader(this.container);
this.amphtmlHints = this.fetchHintsData();
}
createCodeMirror() {
const input = document.createElement('textarea');
this.container.appendChild(input);
this.codeMirror = CodeMirror.fromTextArea(input, {
mode: 'text/html',
selectionPointer: true,
styleActiveLine: true,
lineNumbers: false,
showCursorWhenSelecting: true,
cursorBlinkRate: 300,
autoCloseBrackets: true,
autoCloseTags: true,
gutters: ['CodeMirror-error-markers'],
extraKeys: {"Ctrl-Space": "autocomplete"},
hintOptions: {
completeSingle: false
}
});
this.codeMirror.on('changes', () => {
if (this.timeout) {
this.win.clearTimeout(this.timeout);
}
if (this.debounceRate === -1) {
this.debounceRate = DEFAULT_DEBOUNCE_RATE;
return;
}
this.timeout = this.win.setTimeout(() => {
events.publish(EVENT_INPUT_CHANGE, this);
this.debounceRate = DEFAULT_DEBOUNCE_RATE;
}, this.debounceRate);
});
this.codeMirror.on('inputRead', (editor, change) => {
if (this.hintTimeout) {
clearTimeout(this.hintTimeout);
}
if (change.origin !== '+input') {
return;
}
if (change && change.text && HINT_IGNORE_ENDS.has(change.text.join(''))) {
return;
}
this.hintTimeout = setTimeout(() => {
if (editor.state.completionActive) {
return;
}
const cur = editor.getCursor();
const token = editor.getTokenAt(cur);
const isCss = token.state.htmlState.context.tagName === 'style';
const isTagDeclaration = token.state.htmlState.tagName;
const isTagStart = token.string === '<';
if (isCss || isTagDeclaration || isTagStart) {
CodeMirror.commands.autocomplete(editor);
}
}, 150);
});
events.subscribe(EVENT_SET_RUNTIME, this.setRuntime.bind(this));
}
setSource(text) {
this.loader.hide();
this.debounceRate = -1; // don't debounce
this.codeMirror.setValue(text);
events.publish(EVENT_INPUT_NEW, this);
}
getSource() {
return this.codeMirror.getValue();
}
setCursorAndFocus(line, col) {
this.codeMirror.setCursor(line - 1, col, {'scroll': true});
this.codeMirror.focus();
}
setCursor(line, col) {
this.codeMirror.setCursor(line, col);
}
getCursor() {
return this.codeMirror.getCursor();
}
setValidationResult(validationResult) {
this.codeMirror.clearGutter('CodeMirror-error-markers');
this.codeMirror.operation(() => {
validationResult.errors.forEach(error => {
const marker = document.createElement('div');
const message = marker.appendChild(document.createElement('span'));
message.appendChild(document.createTextNode(error.message));
marker.className = 'gutter-' + error.icon;
this.codeMirror.setGutterMarker(error.line - 1, 'CodeMirror-error-markers', marker);
});
});
}
showLoadingIndicator() {
this.codeMirror.setValue('');
this.loader.show();
}
lineCount() {
return this.codeMirror.lineCount();
}
getLineTokens(lineNumber) {
return this.codeMirror.getLineTokens(lineNumber);
}
replaceRange(replacement, from, to, origin) {
this.codeMirror.replaceRange(replacement, from, to, origin);
}
getTokenAt(pos, precise) {
return this.codeMirror.getTokenAt(pos, precise);
}
loadHints(validator) {
this.amphtmlHints.then((hints) => {
for (let key of Object.keys(CodeMirror.htmlSchema)) {
delete CodeMirror.htmlSchema[key];
}
Object.assign(CodeMirror.htmlSchema, hints[validator]);
});
}
setRuntime(runtime) {
const runtimeData = runtimes.get(runtime.id);
this.loadHints(runtimeData.validator);
}
fetchHintsData() {
return new Promise((resolve, reject) => {
window.requestIdleCallback(() => {
fetch(HINTS_URL).then((response) => {
if (response.status !== 200) {
return reject(new Error(`Error code ${response.status}`));
}
resolve(response.json());
}).catch((err) => {
reject(err);
});
});
});
}
}
| JavaScript | 0.000043 | @@ -5845,16 +5845,30 @@
alidator
+.toLowerCase()
%5D);%0A
|
13273fb632b3148e1d075b6a044c6befd8a2d433 | Add explicit type casts for options.duration | src/ol/animation.js | src/ol/animation.js | goog.provide('ol.animation');
goog.require('ol');
goog.require('ol.PreRenderFunction');
goog.require('ol.ViewHint');
goog.require('ol.coordinate');
goog.require('ol.easing');
/**
* Generate an animated transition that will "bounce" the resolution as it
* approaches the final value.
* @param {olx.animation.BounceOptions} options Bounce options.
* @return {ol.PreRenderFunction} Pre-render function.
* @api
*/
ol.animation.bounce = function(options) {
var resolution = options.resolution;
var start = options.start ? options.start : goog.now();
var duration = ol.isDef(options.duration) ? options.duration : 1000;
var easing = options.easing ?
options.easing : ol.easing.upAndDown;
return (
/**
* @param {ol.Map} map Map.
* @param {?olx.FrameState} frameState Frame state.
*/
function(map, frameState) {
if (frameState.time < start) {
frameState.animate = true;
frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
return true;
} else if (frameState.time < start + duration) {
var delta = easing((frameState.time - start) / duration);
var deltaResolution = resolution - frameState.viewState.resolution;
frameState.animate = true;
frameState.viewState.resolution += delta * deltaResolution;
frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
return true;
} else {
return false;
}
});
};
/**
* Generate an animated transition while updating the view center.
* @param {olx.animation.PanOptions} options Pan options.
* @return {ol.PreRenderFunction} Pre-render function.
* @api
*/
ol.animation.pan = function(options) {
var source = options.source;
var start = options.start ? options.start : goog.now();
var sourceX = source[0];
var sourceY = source[1];
var duration = ol.isDef(options.duration) ? options.duration : 1000;
var easing = options.easing ?
options.easing : ol.easing.inAndOut;
return (
/**
* @param {ol.Map} map Map.
* @param {?olx.FrameState} frameState Frame state.
*/
function(map, frameState) {
if (frameState.time < start) {
frameState.animate = true;
frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
return true;
} else if (frameState.time < start + duration) {
var delta = 1 - easing((frameState.time - start) / duration);
var deltaX = sourceX - frameState.viewState.center[0];
var deltaY = sourceY - frameState.viewState.center[1];
frameState.animate = true;
frameState.viewState.center[0] += delta * deltaX;
frameState.viewState.center[1] += delta * deltaY;
frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
return true;
} else {
return false;
}
});
};
/**
* Generate an animated transition while updating the view rotation.
* @param {olx.animation.RotateOptions} options Rotate options.
* @return {ol.PreRenderFunction} Pre-render function.
* @api
*/
ol.animation.rotate = function(options) {
var sourceRotation = options.rotation ? options.rotation : 0;
var start = options.start ? options.start : goog.now();
var duration = ol.isDef(options.duration) ? options.duration : 1000;
var easing = options.easing ?
options.easing : ol.easing.inAndOut;
var anchor = options.anchor ?
options.anchor : null;
return (
/**
* @param {ol.Map} map Map.
* @param {?olx.FrameState} frameState Frame state.
*/
function(map, frameState) {
if (frameState.time < start) {
frameState.animate = true;
frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
return true;
} else if (frameState.time < start + duration) {
var delta = 1 - easing((frameState.time - start) / duration);
var deltaRotation =
(sourceRotation - frameState.viewState.rotation) * delta;
frameState.animate = true;
frameState.viewState.rotation += deltaRotation;
if (!goog.isNull(anchor)) {
var center = frameState.viewState.center;
ol.coordinate.sub(center, anchor);
ol.coordinate.rotate(center, deltaRotation);
ol.coordinate.add(center, anchor);
}
frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
return true;
} else {
return false;
}
});
};
/**
* Generate an animated transition while updating the view resolution.
* @param {olx.animation.ZoomOptions} options Zoom options.
* @return {ol.PreRenderFunction} Pre-render function.
* @api
*/
ol.animation.zoom = function(options) {
var sourceResolution = options.resolution;
var start = options.start ? options.start : goog.now();
var duration = ol.isDef(options.duration) ? options.duration : 1000;
var easing = options.easing ?
options.easing : ol.easing.inAndOut;
return (
/**
* @param {ol.Map} map Map.
* @param {?olx.FrameState} frameState Frame state.
*/
function(map, frameState) {
if (frameState.time < start) {
frameState.animate = true;
frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
return true;
} else if (frameState.time < start + duration) {
var delta = 1 - easing((frameState.time - start) / duration);
var deltaResolution =
sourceResolution - frameState.viewState.resolution;
frameState.animate = true;
frameState.viewState.resolution += delta * deltaResolution;
frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
return true;
} else {
return false;
}
});
};
| JavaScript | 0.000001 | @@ -588,33 +588,62 @@
ions.duration) ?
-
+%0A /** @type %7Bnumber%7D */ (
options.duration
@@ -634,32 +634,33 @@
options.duration
+)
: 1000;%0A var e
@@ -1918,33 +1918,62 @@
ions.duration) ?
-
+%0A /** @type %7Bnumber%7D */ (
options.duration
@@ -1964,32 +1964,33 @@
options.duration
+)
: 1000;%0A var e
@@ -3343,33 +3343,62 @@
ions.duration) ?
-
+%0A /** @type %7Bnumber%7D */ (
options.duration
@@ -3389,32 +3389,33 @@
options.duration
+)
: 1000;%0A var e
@@ -4980,17 +4980,46 @@
ation) ?
-
+%0A /** @type %7Bnumber%7D */ (
options.
@@ -5026,16 +5026,17 @@
duration
+)
: 1000;
|
9324fd028260e39231d125fbe9e15b46e14456f5 | Rename "IMAP Sync" - fix js tests | src/Oro/Bundle/ImapBundle/Resources/public/js/app/views/imap-gmail-view.js | src/Oro/Bundle/ImapBundle/Resources/public/js/app/views/imap-gmail-view.js | define(function(require) {
'use strict';
var ImapGmailView;
var _ = require('underscore');
var BaseView = require('oroui/js/app/views/base/view');
ImapGmailView = BaseView.extend({
events: {
'click button[name$="[userEmailOrigin][check]"]': 'onClickConnect',
'click button[name$="[userEmailOrigin][checkFolder]"]': 'onCheckFolder',
'click button.removeRow': 'onResetEmail'
},
$googleErrorMessage: null,
errorMessage: '',
type: '',
html: '',
token: '',
expiredAt: '',
email: '',
googleAuthCode: '',
/**
* @constructor
*
* @param {Object} options
*/
initialize: function(options) {
this.$googleErrorMessage = this.$el.find(options.googleErrorMessage);
this.type = options.type;
},
render: function() {
if (this.html && this.html.length > 0) {
this.$el.html(this.html);
}
this.$el.find('input[name$="[userEmailOrigin][accessToken]"]').val(this.token);
this.$el.find('input[name$="[userEmailOrigin][user]"]').val(this.email);
this.$el.find('input[name$="[userEmailOrigin][accessTokenExpiresAt]"]').val(this.expiredAt);
this.$el.find('input[name$="[userEmailOrigin][googleAuthCode]"]').val(this.googleAuthCode);
if (this.errorMessage.length > 0) {
this.showErrorMessage();
} else {
this.hideErrorMessage();
}
this._deferredRender();
this.initLayout().done(_.bind(this._resolveDeferredRender, this));
},
/**
* Set error message
* @param {string} message
*/
setErrorMessage: function(message) {
this.errorMessage = message;
},
/**
* Clear error message
*/
resetErrorMessage: function() {
this.errorMessage = '';
},
/**
* Set html template
* @param {string} html
*/
setHtml: function(html) {
this.html = html;
},
/**
* Handler event of click on the button Connection
* @param e
*/
onClickConnect: function() {
this.trigger('checkConnection', this.getData());
},
/**
* Handler event of click on the button Retrieve Folders
*/
onCheckFolder: function() {
this.trigger('getFolders', this.getData());
},
/**
* Handler event of click 'x' button
*/
onResetEmail: function() {
$('select[name$="[accountType]"]').val('').trigger('change');
},
/**
* Return values from types of form
* @returns {{type: string, accessToken: *, clientId: *, user: *, imapPort: *, imapHost: *, imapEncryption: *, smtpPort: *, smtpHost: *, smtpEncryption: *, accessTokenExpiresAt: *, googleAuthCode: *}}
*/
getData: function() {
var token = this.$el.find('input[name$="[userEmailOrigin][accessToken]"]').val();
if (!token) {
token = this.token;
}
return {
type: this.type,
accessToken: token,
clientId: this.$el.find('input[name$="[userEmailOrigin][clientId]"]').val(),
user: this.$el.find('input[name$="[userEmailOrigin][user]"]').val(),
imapPort: this.$el.find('input[name$="[userEmailOrigin][imapPort]"]').val(),
imapHost: this.$el.find('input[name$="[userEmailOrigin][imapHost]"]').val(),
imapEncryption: this.$el.find('input[name$="[userEmailOrigin][imapEncryption]"]').val(),
smtpPort: this.$el.find('input[name$="[userEmailOrigin][smtpPort]"]').val(),
smtpHost: this.$el.find('input[name$="[userEmailOrigin][smtpHost]"]').val(),
smtpEncryption: this.$el.find('input[name$="[userEmailOrigin][smtpEncryption]"]').val(),
accessTokenExpiresAt: this.$el.find('input[name$="[userEmailOrigin][accessTokenExpiresAt]"]').val(),
googleAuthCode: this.$el.find('input[name$="[userEmailOrigin][googleAuthCode]"]').val()
};
},
/**
* Set token
* @param {string} value
*/
setToken: function(value) {
this.token = value;
},
/**
* Set email
* @param {string} value
*/
setEmail: function(value) {
this.email = value;
},
/**
* Set expiredAt
* @param {string} value
*/
setExpiredAt: function(value) {
this.expiredAt = value;
},
/**
* set googleAuthCode
* @param {string} value
*/
setGoogleAuthCode: function(value) {
this.googleAuthCode = value;
},
/**
* Change style for block with error message to show
*/
showErrorMessage: function() {
this.$googleErrorMessage.html(this.errorMessage);
this.$googleErrorMessage.show();
},
/**
* Change style for block with error message to hide
*/
hideErrorMessage: function() {
this.$googleErrorMessage.hide();
},
/**
* Try to load folders tree if it is not loaded
*/
autoRetrieveFolders: function() {
if (!this.$el.find('input.folder-tree').length) {
this.trigger('getFolders', this.getData());
}
}
});
return ImapGmailView;
});
| JavaScript | 0 | @@ -156,16 +156,47 @@
/view');
+%0A var $ = require('jquery');
%0A%0A Im
|
aabfa974291b8bb3b841171a29045049f36adaca | Use the new notify() function | uptrack/static/js/status.js | uptrack/static/js/status.js | var make_popover = function() {
var pkgid = $(this).attr("data-pkg");
return $("#popover_content_" + pkgid).html();
}
var make_popovers = function(popover_class) {
$(popover_class).popover({animation: true, container: "body", html: true,
placement: "bottom", title: "Actions",
content: make_popover});
$(popover_class).on("shown.bs.popover", function() {
$(".popover-content").find("li").each(function() {
var pkgid = $(this).attr("data-pkgid");
var action = $(this).attr("data-action");
if (action === "downstream") {
$(this).click({pkgid: pkgid, value: true},
mark_downstream_clicked);
} else if (action === "nodownstream") {
$(this).click({pkgid: pkgid, value: false},
mark_downstream_clicked);
} else if (action === "renamed") {
var pkgname = $(this).attr("data-pkgname");
var upstream_pkgname = $(this).attr("data-upstream-pkgname");
$(this).click({pkgid: pkgid, pkgname: pkgname,
upstream_pkgname: upstream_pkgname},
mark_renamed_clicked);
} else {
console.log("ERROR: Can't handle '" + action + "' action");
}
});
});
}
var mark_downstream_clicked = function(e) {
var pkgid = e.data.pkgid;
var value = e.data.value;
var url = "/packages/" + pkgid + "/markdownstream";
$("#popover_button_" + pkgid).popover("hide");
$.get(url, $.param({value: value}), function(data) {
var notif = $("#alert_placeholder");
if (data.error !== undefined) {
$(notif).html('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><span>' + data.error + '</span></div>');
} else {
$(notif).html('<div class="alert alert-success"><a class="close" data-dismiss="alert">×</a><span>' + data.msg + '</span></div>');
}
}, 'json');
return false;
}
var mark_renamed_clicked = function(e) {
var pkgid = e.data.pkgid;
var pkgname = e.data.pkgname;
var upstream_pkgname = e.data.upstream_pkgname;
if (upstream_pkgname === undefined) {
upstream_pkgname = "";
}
$("#popover_button_" + pkgid).popover("hide");
$("#uptrack_rename_package_modal").modal({backdrop: true, keyboard: true,
show: true});
$("#uptrack_rename_package_modal").on("shown.bs.modal", function() {
$("#uptrack_rename_package_upstream_pkgname").val(upstream_pkgname);
$("#uptrack_rename_package_current_name").text(pkgname);
$("#uptrack_rename_package_submit").off("click");
$("#uptrack_rename_package_submit").click(function() {
var url = "/packages/" + pkgid + "/markrenamed";
var upstream_pkgname = $("#uptrack_rename_package_upstream_pkgname").val();
var options = {upstream_pkgname: upstream_pkgname};
$.get(url, $.param(options), function(data) {
$("#uptrack_rename_package_modal").modal("hide");
var notif = $("#alert_placeholder");
if (data.error !== undefined) {
$(notif).html('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><span>' + data.error + '</span></div>');
} else {
$(notif).html('<div class="alert alert-success"><a class="close" data-dismiss="alert">×</a><span>' + data.msg + '</span></div>');
}
}, 'json');
});
});
return false;
}
| JavaScript | 0 | @@ -1795,306 +1795,185 @@
-$(notif).html('%3Cdiv class=%22alert alert-error%22%3E%3Ca class=%22close%22 data-dismiss=%22alert%22%3E%C3%97%3C/a%3E%3Cspan%3E' + data.error + '%3C/span%3E%3C/div%3E');%0A %7D else %7B%0A $(notif).html('%3Cdiv class=%22alert alert-success%22%3E%3Ca class=%22close%22 data-dismiss=%22alert%22%3E%C3%97%3C/a%3E%3Cspan%3E' + data.msg + '%3C/span%3E%3C/div%3E');%0A %7D
+var msg = data.error;%0A var level = %22error%22;%0A %7D else %7B%0A var msg = data.msg;%0A var level = %22success%22;%0A %7D%0A%0A notify(msg, level);
%0A
|
983963ccc4c50671b8ce09ae45410977ef32e5ad | return false from inCurrentMonth method if there is no selectedMonth | source/common/res/features/highlight-current-month/main.js | source/common/res/features/highlight-current-month/main.js | (function poll() {
// Waits until an external function gives us the all clear that we can run (at /shared/main.js)
if (typeof ynabToolKit !== 'undefined' && ynabToolKit.pageReady === true) {
ynabToolKit.currentMonthIndicator = (function () {
// Determine whether the selected month is the current month
function inCurrentMonth() {
var today = new Date();
var selectedMonth = ynabToolKit.shared.parseSelectedMonth();
if (selectedMonth === null) return;
return selectedMonth.getMonth() === today.getMonth() && selectedMonth.getYear() === today.getYear();
}
return {
invoke() {
// check if header bar is current month, if so, change background color
if (inCurrentMonth()) {
$('.budget-header .budget-header-calendar').addClass('toolkit-highlight-current-month');
} else {
$('.budget-header .budget-header-calendar').removeClass('toolkit-highlight-current-month');
}
},
observe(changedNodes) {
if (changedNodes.has('budget-header-totals-cell-value user-data') ||
changedNodes.has('budget-content resizable') ||
changedNodes.has('layout user-logged-in')) {
ynabToolKit.currentMonthIndicator.invoke();
}
}
};
}()); // Keep feature functions contained within this object
if (ynabToolKit.shared.getCurrentRoute() === 'budget.index') {
ynabToolKit.currentMonthIndicator.invoke();
}
} else {
setTimeout(poll, 250);
}
}());
| JavaScript | 0.000009 | @@ -487,16 +487,22 @@
) return
+ false
;%0A
|
919f324a7f77f4d74d62851c7a5a7fb2a191ad70 | add guidelines parallel to those added to datetime utils | src/utils/format.js | src/utils/format.js | /*
* == BSD2 LICENSE ==
* Copyright (c) 2016, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
import _ from 'lodash';
import { format } from 'd3-format';
// using d3-time-format because time is time of data access in
// user’s browser time, not PwD’s configured timezone
import { utcFormat } from 'd3-time-format';
import { convertToMmolL } from './bloodglucose';
import { BG_HIGH, BG_LOW, MMOLL_UNITS } from './constants';
/**
* displayDecimal
* @param {Number} val numeric value to format
* @param {Number} places number of decimal places to displayDecimal
* @return {String} val formatted to places decimal places
*/
export function displayDecimal(val, places) {
if (places === null || places === undefined) {
return format('d')(val);
}
return format(`.${places}f`)(val);
}
/**
* displayBgValue
* @param {Number} val - integer or float blood glucose value in either mg/dL or mmol/L
* @param {String} units - 'mg/dL' or 'mmol/L'
* @param {Object} outOfRangeThresholds - specifies thresholds for `low` and `high` values
*
* @return {String} stringBgValue
*/
export function displayBgValue(val, units, outOfRangeThresholds) {
if (!_.isEmpty(outOfRangeThresholds)) {
let lowThreshold = outOfRangeThresholds.low;
let highThreshold = outOfRangeThresholds.high;
if (units === MMOLL_UNITS) {
if (lowThreshold) {
lowThreshold = convertToMmolL(lowThreshold);
}
if (highThreshold) {
highThreshold = convertToMmolL(highThreshold);
}
}
if (lowThreshold && val < lowThreshold) {
return BG_LOW;
}
if (highThreshold && val > highThreshold) {
return BG_HIGH;
}
}
if (units === MMOLL_UNITS) {
return format('.1f')(val);
}
return format('d')(val);
}
/**
* patientFullName
* @param {Object} patient the patient object that contains the profile
* @return {String} fullName of patient or empty if there is none
*/
export function patientFullName(patient) {
const profile = _.get(patient, ['profile'], {});
const patientInfo = profile.patient || {};
if (patientInfo.isOtherPerson) {
return patientInfo.fullName;
}
return profile.fullName;
}
/**
* birthday
* @param {Object} patient the patient object that contains the profile
* @return {String} MMM D, YYYY formated birthday or empty if none
*/
export function birthday(patient) {
const bday = _.get(patient, ['profile', 'patient', 'birthday'], '');
if (bday) {
return utcFormat('%b %-d, %Y')(Date.parse(bday));
}
return '';
}
/**
* diagnosisDate
* @param {Object} patient the patient object that contains the profile
* @return {String} MMM D, YYYY formated diagnosisDate or empty if none
*/
export function diagnosisDate(patient) {
const diagnosis = _.get(patient, ['profile', 'patient', 'diagnosisDate'], '');
if (diagnosis) {
return utcFormat('%b %-d, %Y')(Date.parse(diagnosis));
}
return '';
}
| JavaScript | 0 | @@ -694,16 +694,894 @@
==%0A */%0A%0A
+/*%0A * Guidelines for these utilities:%0A *%0A * 1. Only %22workhorse%22 functions used in 2+ places should be here.%0A * 1a. A function used in multiple components for one view should live%0A * in view-specific utils: src/utils/%5Bview%5D/format.js%0A * 1b. A function used in only one component should just be part of that component,%0A * potentially as a named export if tests are deemed important to have.%0A * 1c. This set of utilities is ONLY for NON-datetime related formatting. Any functions%0A * used for formatting dates and/or times should go in src/utils/datetime.js%0A *%0A * 2. Function naming scheme: the main verb here is %60format%60. Start all function names with that.%0A *%0A * 3. Try to be consistent in how params are used:%0A * (e.g., always pass in %60bgPrefs%60) rather than some (subset) of bgUnits and/or bgBounds%0A * and try to copy & paste JSDoc @param descriptions for common params.%0A *%0A */%0A%0A
import _
|
bc69048610978fd44a162f185219912e5127d9d8 | Fix register dialog title | web/app/view/Register.js | web/app/view/Register.js | /*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
*
* 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.
*/
Ext.define('Traccar.view.Register', {
extend: 'Traccar.view.BaseDialog',
requires: [
'Traccar.view.RegisterController'
],
controller: 'register',
items: {
xtype: 'form',
reference: 'form',
jsonSubmit: true,
items: [{
xtype: 'textfield',
name: 'name',
fieldLabel: Strings.userName,
allowBlank: false
}, {
xtype: 'textfield',
name: 'email',
fieldLabel: Strings.userEmail,
vtype: 'email',
allowBlank: false
}, {
xtype: 'textfield',
name: 'password',
fieldLabel: Strings.userPassword,
inputType: 'password',
allowBlank: false
}]
},
buttons: [{
text: Strings.sharedSave,
handler: 'onCreateClick'
}, {
text: Strings.sharedCancel,
handler: 'closeView'
}]
});
| JavaScript | 0.000001 | @@ -788,24 +788,59 @@
register',%0A%0A
+ title: Strings.loginRegister,%0A%0A
items: %7B
|
d16ed462c1d00f79feb3032c8bed4534a46c40fd | Use pointer cursor for topic map. [rev: none] | find-core/src/main/public/static/js/find/app/util/topic-map-view.js | find-core/src/main/public/static/js/find/app/util/topic-map-view.js | /*
* Copyright 2016 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'backbone',
'underscore',
'find/app/vent',
'i18n!find/nls/bundle',
'topicmap/js/topicmap'
], function(Backbone, _, vent, i18n) {
/**
* Wraps the topic map in a resize-aware Backbone view. If the view element is not visible when resized, draw must be
* called when the view is visible to update the SVG size.
*/
return Backbone.View.extend({
initialize: function(options) {
this.data = options.data || [];
this.clickHandler = options.clickHandler || _.noop;
this.render();
this.listenTo(vent, 'vent:resize', function() {
if (this.$el.is(':visible')) {
this.draw();
}
});
},
render: function() {
this.$el.topicmap({
hideLegend: false,
skipAnimation: false,
i18n: {
'autn.vis.topicmap.noResultsAvailable': i18n['search.topicMap.noResults']
},
onLeafClick: _.bind(function(node) {
this.clickHandler(node.name);
}, this)
});
this.draw();
},
/**
* Set the data for the topic map. Call draw to update the SVG.
*/
setData: function(data) {
this.data = data || [];
},
/**
* Draw the current data as a topic map in the SVG.
*/
draw: function() {
this.$el.topicmap('renderData', {
size: 1.0,
children: this.data
});
}
});
});
| JavaScript | 0 | @@ -711,18 +711,8 @@
dler
- %7C%7C _.noop
;%0A%0A
@@ -965,34 +965,38 @@
-this.$el.
+var
topic
-map(
+MapOptions =
%7B%0A
@@ -1197,17 +1197,118 @@
%7D
-,
+%0A %7D;%0A%0A if (this.clickHandler) %7B%0A this.$el.addClass('clickable');%0A
%0A
@@ -1316,16 +1316,32 @@
+topicMapOptions.
onLeafCl
@@ -1343,17 +1343,18 @@
eafClick
-:
+ =
_.bind(
@@ -1444,16 +1444,17 @@
%7D, this)
+;
%0A
@@ -1459,20 +1459,66 @@
%7D
+%0A%0A this.$el.topicmap(topicMapOptions
);%0A
-%0A
|
b9e24fb96bbf6cd0fab09f34899262433ea0f8c2 | Exclude name tag when validating whether a feature has tags (closes #3091) | js/id/validations/missing_tag.js | js/id/validations/missing_tag.js | iD.validations.MissingTag = function() {
var validation = function(changes, graph) {
var warnings = [];
for (var i = 0; i < changes.created.length; i++) {
var change = changes.created[i],
geometry = change.geometry(graph);
if ((geometry === 'point' || geometry === 'line' || geometry === 'area') && !change.isUsed(graph)) {
warnings.push({
id: 'missing_tag',
message: t('validations.untagged_' + geometry),
tooltip: t('validations.untagged_' + geometry + '_tooltip'),
entity: change
});
}
}
return warnings;
};
return validation;
};
| JavaScript | 0.000001 | @@ -35,16 +35,254 @@
on() %7B%0A%0A
+ // Slightly stricter check than Entity#isUsed (#3091)%0A function hasTags(entity, graph) %7B%0A return _.without(Object.keys(entity.tags), 'area', 'name').length %3E 0 %7C%7C%0A graph.parentRelations(entity).length %3E 0;%0A %7D%0A%0A
var
@@ -597,22 +597,24 @@
&& !
-change.isUsed(
+hasTags(change,
grap
|
79848197534b76432fa123a9b324529b0260ea6f | update the octaves when changing the baseFrequency | Tone/effect/AutoFilter.js | Tone/effect/AutoFilter.js | define(["Tone/core/Tone", "Tone/effect/Effect", "Tone/component/LFO", "Tone/component/Filter"], function(Tone){
"use strict";
/**
* @class Tone.AutoFilter is a Tone.Filter with a Tone.LFO connected to the filter cutoff frequency.
* Setting the LFO rate and depth allows for control over the filter modulation rate
* and depth.
*
* @constructor
* @extends {Tone.Effect}
* @param {Time|Object} [frequency] The rate of the LFO.
* @param {Frequency=} baseFrequency The lower value of the LFOs oscillation
* @param {Frequency=} octaves The number of octaves above the baseFrequency
* @example
* //create an autofilter and start it's LFO
* var autoFilter = new Tone.AutoFilter("4n").toMaster().start();
* //route an oscillator through the filter and start it
* var oscillator = new Tone.Oscillator().connect(autoFilter).start();
*/
Tone.AutoFilter = function(){
var options = this.optionsObject(arguments, ["frequency", "baseFrequency", "octaves"], Tone.AutoFilter.defaults);
Tone.Effect.call(this, options);
/**
* the lfo which drives the filter cutoff
* @type {Tone.LFO}
* @private
*/
this._lfo = new Tone.LFO({
"frequency" : options.frequency,
"amplitude" : options.depth,
});
/**
* The range of the filter modulating between the min and max frequency.
* 0 = no modulation. 1 = full modulation.
* @type {NormalRange}
* @signal
*/
this.depth = this._lfo.amplitude;
/**
* How fast the filter modulates between min and max.
* @type {Frequency}
* @signal
*/
this.frequency = this._lfo.frequency;
/**
* The filter node
* @type {Tone.Filter}
*/
this.filter = new Tone.Filter(options.filter);
/**
* The octaves placeholder
* @type {Positive}
* @private
*/
this._octaves = 0;
//connections
this.connectEffect(this.filter);
this._lfo.connect(this.filter.frequency);
this.type = options.type;
this._readOnly(["frequency", "depth"]);
this.octaves = options.octaves;
this.baseFrequency = options.baseFrequency;
};
//extend Effect
Tone.extend(Tone.AutoFilter, Tone.Effect);
/**
* defaults
* @static
* @type {Object}
*/
Tone.AutoFilter.defaults = {
"frequency" : 1,
"type" : "sine",
"depth" : 1,
"baseFrequency" : 200,
"octaves" : 2.6,
"filter" : {
"type" : "lowpass",
"rolloff" : -12,
"Q" : 1,
}
};
/**
* Start the effect.
* @param {Time} [time=now] When the LFO will start.
* @returns {Tone.AutoFilter} this
*/
Tone.AutoFilter.prototype.start = function(time){
this._lfo.start(time);
return this;
};
/**
* Stop the effect.
* @param {Time} [time=now] When the LFO will stop.
* @returns {Tone.AutoFilter} this
*/
Tone.AutoFilter.prototype.stop = function(time){
this._lfo.stop(time);
return this;
};
/**
* Sync the filter to the transport.
* @param {Time} [delay=0] Delay time before starting the effect after the
* Transport has started.
* @returns {Tone.AutoFilter} this
*/
Tone.AutoFilter.prototype.sync = function(delay){
this._lfo.sync(delay);
return this;
};
/**
* Unsync the filter from the transport.
* @returns {Tone.AutoFilter} this
*/
Tone.AutoFilter.prototype.unsync = function(){
this._lfo.unsync();
return this;
};
/**
* Type of oscillator attached to the AutoFilter.
* Possible values: "sine", "square", "triangle", "sawtooth".
* @memberOf Tone.AutoFilter#
* @type {string}
* @name type
*/
Object.defineProperty(Tone.AutoFilter.prototype, "type", {
get : function(){
return this._lfo.type;
},
set : function(type){
this._lfo.type = type;
}
});
/**
* The minimum value of the filter's cutoff frequency.
* @memberOf Tone.AutoFilter#
* @type {Frequency}
* @name min
*/
Object.defineProperty(Tone.AutoFilter.prototype, "baseFrequency", {
get : function(){
return this._lfo.min;
},
set : function(freq){
this._lfo.min = this.toFrequency(freq);
}
});
/**
* The maximum value of the filter's cutoff frequency.
* @memberOf Tone.AutoFilter#
* @type {Positive}
* @name octaves
*/
Object.defineProperty(Tone.AutoFilter.prototype, "octaves", {
get : function(){
return this._octaves;
},
set : function(oct){
this._octaves = oct;
this._lfo.max = this.baseFrequency * Math.pow(2, oct);
}
});
/**
* Clean up.
* @returns {Tone.AutoFilter} this
*/
Tone.AutoFilter.prototype.dispose = function(){
Tone.Effect.prototype.dispose.call(this);
this._lfo.dispose();
this._lfo = null;
this.filter.dispose();
this.filter = null;
this._writable(["frequency", "depth"]);
this.frequency = null;
this.depth = null;
return this;
};
return Tone.AutoFilter;
});
| JavaScript | 0 | @@ -4009,16 +4009,70 @@
(freq);%0A
+%09%09%09//and set the max%0A%09%09%09this.octaves = this._octaves;%0A
%09%09%7D%0A%09%7D);
|
4b458460deebac7f5bcfad793e371a9845368c99 | fix for Bug 334696 | src/ui-scripts/ui-actions.js | src/ui-scripts/ui-actions.js | var EventHandler = function(type, is_capturing, handler_key)
{
handler_key = handler_key ? handler_key : 'handler';
if(!window.eventHandlers)
{
window.eventHandlers = {};
}
if(window.eventHandlers[type])
{
return;
}
window.eventHandlers[type] = {};
var handler = function(event)
{
var ele = event.target, handler = null, container = null;
if( ele.nodeType != 1 )
{
return;
}
handler = ele.getAttribute(handler_key);
while( !handler && ( ele = ele.parentElement ) )
{
handler = ele.getAttribute(handler_key);
}
if( handler && eventHandlers[type][handler] )
{
if( type == 'click' && /toolbar-buttons/.test(ele.parentNode.nodeName) )
{
container =
document.getElementById(ele.parentNode.parentNode.id.replace('toolbar', 'container'));
}
eventHandlers[type][handler](event, ele, container);
}
}
this.post = function(handler, event)
{
if(eventHandlers[type][handler])
{
eventHandlers[type][handler](event);
}
}
document.addEventListener(type, handler, is_capturing ? is_capturing : false);
}
new EventHandler('click');
new EventHandler('change');
new EventHandler('input');
new EventHandler('keyup');
new EventHandler('keydown');
new EventHandler('keypress');
new EventHandler('mousedown');
new EventHandler('focus', true, 'focus-handler');
new EventHandler('blur', true, 'blur-handler');
/***** click handler *****/
eventHandlers.click['tab'] = function(event, target)
{
target = target.parentElement;
var tabs = UIBase.getUIById(target.parentElement.getAttribute('ui-id'));
var view_id = target.getAttribute('ref-id');
if( tabs )
{
tabs.setActiveTab(view_id);
}
else
{
opera.postError("tabs is missing in eventHandlers.click['tab'] in ui-actions");
}
}
eventHandlers.click['close-tab'] = function(event, target)
{
target = target.parentElement;
var container = target.parentElement;
var tabs = UIBase.getUIById(target.parentElement.getAttribute('ui-id'));
tabs.removeTab(target.getAttribute('ref-id'));
}
eventHandlers.click['settings-tabs'] = function(event, target)
{
var tabs = UIBase.getUIById(target.parentElement.getAttribute('ui-id'));
windows.showWindow('window-3', 'Settings', templates.settings(tabs), 200, 200, 200, 200);
}
eventHandlers.click['toggle-setting'] = function(event)
{
var target = event.target;
var old_setting = target.parentElement.parentElement;
var view_id = target.getAttribute('view-id');
var view = views[view_id];
var setting = document.render(templates.setting( view_id, view.name, !target.hasClass('unfolded') ));
old_setting.parentElement.replaceChild(setting, old_setting);
}
eventHandlers.click['show-window'] = function(event)
{
var target = event.target;
var view_id = target.getAttribute('view-id');
target.parentNode.parentNode.parentNode.removeChild(target.parentNode.parentNode);
UIWindowBase.showWindow(view_id);
}
eventHandlers.click['top-settings'] = function(event)
{
UIWindowBase.showWindow('settings_view');
}
eventHandlers.click['documentation'] = function(event)
{
window.open(event.target.getAttribute('param'), '_info_window').focus();
}
eventHandlers.click['top-window-close'] = function(event)
{
window.close();
}
eventHandlers.click['top-window-toggle-attach'] = function(event)
{
if( window.opera.attached = !window.opera.attached )
{
event.target.addClass('attached');
}
else
{
event.target.removeClass('attached');
}
client.setupTopCell();
}
eventHandlers.mousedown['toolbar-switch'] = function(event)
{
var target = event.target;
var arr = target.getAttribute('key').split('.');
var setting = arr[0], key = arr[1];
var is_active = !( target.getAttribute('is-active') == 'true' && true || false );
settings[setting].set(key, is_active);
views.settings_view.syncSetting(setting, key, is_active);
views[setting].update();
messages.post("setting-changed", {id: setting, key: key});
target.setAttribute('is-active', is_active ? 'true' : 'false');
}
/***** change handler *****/
eventHandlers.change['checkbox-setting'] = function(event)
{
var ele = event.target;
var view_id = ele.getAttribute('view-id');
settings[view_id].set(ele.name, ele.checked, true);
views[view_id].update();
var host_view = ele.getAttribute('host-view-id');
if( host_view )
{
views.settings_view.syncSetting(view_id, ele.name, ele.checked);
}
messages.post("setting-changed", {id: view_id, key: ele.name});
}
eventHandlers.focus['focus'] = function(event, target)
{
var parent = event.target.parentNode;
if( parent.nodeName == 'filter' )
{
parent.firstChild.textContent = '';
parent.addClass('focus');
if(event.target.value)
{
event.target.selectionStart = 0;
event.target.selectionEnd = event.target.value.length;
}
}
}
eventHandlers.blur['blur'] = function(event, target)
{
var parent = event.target.parentNode;
if( parent.nodeName == 'filter' )
{
if( !event.target.value )
{
parent.firstChild.textContent = event.target.getAttribute('default-text');
}
parent.removeClass('focus');
}
}
| JavaScript | 0 | @@ -3527,16 +3527,27 @@
;%0A %7D%0A
+setTimeout(
client.s
@@ -3557,17 +3557,19 @@
pTopCell
-(
+, 0
);%0A%7D%0A%0Aev
|
4fa84934bf614895b258eca5a4d09d789fb93dd8 | Fix sharedPromiseTo jsdoc types | src/utils/sharedPromiseTo.js | src/utils/sharedPromiseTo.js | /**
* @param { () => Promise<void> } [func]
* @returns { (() => Promise<void>?) => Promise<void> }
*/
module.exports = defaultFunc => {
let promise = null
return func => {
if (promise == null)
promise = (defaultFunc ? defaultFunc() : func()).finally(() => (promise = null))
return promise
}
}
| JavaScript | 0 | @@ -1,12 +1,27 @@
/**%0A
+ * @template T%0A
* @para
@@ -42,18 +42,22 @@
ise%3C
-void
+T
%3E %7D %5B
-f
+defaultF
unc%5D
@@ -72,16 +72,23 @@
urns %7B (
+func?:
() =%3E Pr
@@ -97,14 +97,10 @@
ise%3C
-void%3E?
+T%3E
) =%3E
@@ -112,12 +112,9 @@
ise%3C
-void
+T
%3E %7D%0A
|
2028f1f722586aa0653db7a662d11e834d58d4e5 | remove angry error message output when caught gracefully | core/lib/annotation_exporter.js | core/lib/annotation_exporter.js | "use strict";
var annotations_exporter = function (pl) {
var path = require('path'),
fs = require('fs-extra'),
JSON5 = require('json5'),
_ = require('lodash'),
md = require('markdown-it')(),
paths = pl.config.paths;
/*
Returns the array of comments that used to be wrapped in raw JS.
*/
function parseAnnotationsJS() {
//attempt to read the file
try {
var oldAnnotations = fs.readFileSync(path.resolve(paths.source.annotations, 'annotations.js'), 'utf8');
} catch (ex) {
console.log(ex, 'annotations.js file missing from ' + paths.source.annotations + '. This may be expected.');
}
//parse as JSON by removing the old wrapping js syntax. comments and the trailing semi-colon
oldAnnotations = oldAnnotations.replace('var comments = ', '');
try {
var oldAnnotationsJSON = JSON5.parse(oldAnnotations.trim().slice(0, -1));
} catch (ex) {
console.log('There was an error parsing JSON for ' + paths.source.annotations + 'annotations.js');
console.log(ex);
}
return oldAnnotationsJSON.comments;
}
/*
Converts the annotations.md file yaml list into an array of annotations
*/
function parseAnnotationsMD() {
var annotations = [];
//attempt to read the file
var annotationsMD = '';
try {
annotationsMD = fs.readFileSync(path.resolve(paths.source.annotations, 'annotations.md'), 'utf8');
} catch (ex) {
console.log(ex, 'annotations.md file missing from ' + paths.source.annotations + '. This may be expected.');
}
//take the annotation snippets and split them on our custom delimiter
var annotationsYAML = annotationsMD.split('~*~');
for (var i = 0; i < annotationsYAML.length; i++) {
var annotation = {};
//for each annotation process the yaml frontmatter and markdown
var annotationSnippet = annotationsYAML[i];
var annotationsRE = /---\r?\n{1}([\s\S]*)---\r?\n{1}([\s\S]*)+/gm;
var chunks = annotationsRE.exec(annotationSnippet);
if (chunks && chunks[1] && chunks[2]) {
//convert each yaml frontmatter key into an object key
var frontmatter = chunks[1];
var frontmatterLines = frontmatter.split(/\n/gm);
for (var j = 0; j < frontmatterLines.length; j++) {
var frontmatterLine = frontmatterLines[j];
if (frontmatterLine.length > 0) {
var frontmatterLineChunks = frontmatterLine.split(':'); //test this
var frontmatterKey = frontmatterLineChunks[0].toLowerCase().trim();
var frontmatterValueString = frontmatterLineChunks[1].trim();
var frontmatterValue = frontmatterValueString.substring(1, frontmatterValueString.length - 1);
if (frontmatterKey === 'el' || frontmatterKey === 'selector') {
annotation.el = frontmatterValue;
}
if (frontmatterKey === 'title') {
annotation.title = frontmatterValue;
}
}
}
//set the comment to the parsed markdown
var annotationMarkdown = chunks[2];
annotation.comment = md.render(annotationMarkdown);
annotations.push(annotation);
} else {
console.log('annotations.md file not formatted as expected. Error parsing frontmatter and markdown out of ' + annotationSnippet);
}
}
return annotations;
}
function gatherAnnotations() {
var annotationsJS = parseAnnotationsJS();
var annotationsMD = parseAnnotationsMD();
var mergedAnnotations = _.unionBy(annotationsJS, annotationsMD, 'el');
return mergedAnnotations;
}
return {
gather: function () {
return gatherAnnotations();
},
gatherJS: function () {
return parseAnnotationsJS();
},
gatherMD: function () {
return parseAnnotationsMD();
}
};
};
module.exports = annotations_exporter;
| JavaScript | 0.00008 | @@ -525,36 +525,32 @@
console.log(
-ex,
'annotations.js
@@ -1448,12 +1448,8 @@
log(
-ex,
'ann
|
8c02a8511d774019f4ccd48f93e4bf01137192be | update capsules to async | src/v2-routes/v2-capsules.js | src/v2-routes/v2-capsules.js | // Dragon Endpoints
const express = require("express")
const v2 = express.Router()
// Returns all capsule data
v2.get("/", (req, res, next) => {
global.db.collection("dragon").find({},{"_id": 0 }).toArray((err, doc) => {
if (err) {
return next(err)
}
res.json(doc)
})
})
// Returns Dragon data
v2.get("/:capsule", (req, res, next) => {
const capsule = req.params.capsule
global.db.collection("dragon").find({"id": capsule},{"_id": 0 }).toArray((err, doc) => {
if (err) {
return next(err)
}
res.json(doc)
})
})
module.exports = v2
| JavaScript | 0 | @@ -76,16 +76,69 @@
Router()
+%0Aconst asyncHandle = require(%22express-async-handler%22)
%0A%0A// Ret
@@ -146,23 +146,22 @@
rns all
-capsule
+Dragon
data%0Av2
@@ -169,16 +169,34 @@
get(%22/%22,
+ asyncHandle(async
(req, r
@@ -189,38 +189,32 @@
(async (req, res
-, next
) =%3E %7B%0A global.
@@ -206,16 +206,35 @@
=%3E %7B%0A
+const data = await
global.d
@@ -226,32 +226,37 @@
await global.db
+%0A
.collection(%22dra
@@ -256,24 +256,29 @@
on(%22dragon%22)
+%0A
.find(%7B%7D,%7B%22_
@@ -278,32 +278,37 @@
(%7B%7D,%7B%22_id%22: 0 %7D)
+%0A
.toArray((err, d
@@ -304,92 +304,29 @@
ray(
-(err, doc) =%3E %7B%0A if (err) %7B%0A return next(err)%0A %7D%0A res.json(doc)%0A %7D)%0A%7D
+)%0A res.json(data)%0A%7D)
)%0A%0A/
@@ -335,16 +335,25 @@
Returns
+specific
Dragon d
@@ -375,16 +375,34 @@
apsule%22,
+ asyncHandle(async
(req, r
@@ -407,14 +407,8 @@
res
-, next
) =%3E
@@ -448,16 +448,29 @@
apsule%0A
+ const data =
global.
@@ -471,16 +471,21 @@
lobal.db
+%0A
.collect
@@ -497,16 +497,21 @@
dragon%22)
+%0A
.find(%7B%22
@@ -536,16 +536,21 @@
d%22: 0 %7D)
+%0A
.toArray
@@ -554,92 +554,29 @@
ray(
-(err, doc) =%3E %7B%0A if (err) %7B%0A return next(err)%0A %7D%0A res.json(doc)%0A %7D)%0A%7D
+)%0A res.json(data)%0A%7D)
)%0A%0Am
|
0fa782f52419fe1338803ffeb91a25f2d45410ff | Update banner.js | next/modules/banner.js | next/modules/banner.js | {
"mixins": ["isDisplayComponent", "hasPaper"],
"module_type": "core",
"init": function() {
var self = this;
self.border = 0;
self.minimum_height = self.minimum_height || 20;
self.minimum_width = self.minimum_width || 20;
eve("interface.request_handle.overlay_paper.overlay_paper0", function(oo) {
self.paper = oo.paper;
});
self.handleEvent("window.resize", function() {
var d = getViewportDimensions();
if (.1 * d.h > 50 && self.minimum_height != .1 * d.h) {
self.minimum_height = .1 * d.h;
self.optimal_height = .1 * d.h;
self._dirty = true;
eve("buffered.100.interface.layout_request_root." + self._id + "." + self.name, false);
}
});
},
"doLayout": function() {
var self = this;
if (isUndefinedOrNull(self.paper)) return;
this.lock.acquire().addCallback(function() {
if (isUndefinedOrNull(self.shapes.rect)) {
self.shapes.rect = self.paper.rect(0, 0, 100, 100, 10).attr({
"fill": "30-black-#263613",
"fill-opacity": 0,
"stroke-opacity": 1,
"stroke-width": 0,
"stroke": "white"
});
self.shapes.title = self.paper.print(0, 0, "XCAYP 0.2", self.paper.getFont("whoa"), 500).attr({
fill: "30-#fff-yellow",
"stroke": "gray",
"stroke-width": 4
});
self.shapes.subtext = self.paper.print(0, 0, "Sync rules all", self.paper.getFont("whoa"), 70).attr({
fill: "30-#fff-yellow",
"stroke": "white",
"stroke-width": 0
});
self.title_bbox = self.shapes.title.getBBox();
self.subtext_bbox = self.shapes.subtext.getBBox();
self.original_width = self.width;
self.original_height = self.height;
//Set minimas
self.minimum_width = self.minimum_width || 20;
self.minimum_height = self.minimum_height || 20;
}
self.shapes.rect.animate({
x: self.x + self.border,
y: self.y + self.border,
width: self.width - self.border * 2,
height: self.height - self.border * 2,
"stroke-width": self.border,
"fill-opacity": 1,
"stroke-opacity": 1
}, self.raphAnimDelay, self.raphAnimType);
//Height of title should be less than 80% of height
//Width of title should be less than 80% of width
//Calculate highest ratio
var xratio = self.width * 0.7 / self.title_bbox.width;
var yratio = self.height * 0.7 / self.title_bbox.height;
var ratio = xratio <= yratio ? xratio : yratio;
var previous_title_transform = self.shapes.title.attr("transform");
var previous_sub_transform = self.shapes.subtext.attr("transform");
self.shapes.title.attr({
"transform": "S" + ratio + "," + ratio
});
self.shapes.subtext.attr({
"transform": "S" + ratio + "," + ratio
});
var bb_title = self.shapes.title.getBBox();
var bb_subtext = self.shapes.subtext.getBBox();
self.shapes.title.attr({
"transform": previous_title_transform
});
self.shapes.subtext.attr({
"transform": previous_sub_transform
});
self.shapes.title.animate({
"transform": "S" + ratio + "," + ratio + "T" + (self.x - bb_title.x + self.width / 2 - bb_title.width / 2) + "," + (self.y - bb_title.y + self.height / 2.4 - bb_title.height / 2)
}, self.raphAnimDelay, self.raphAnimType);
self.shapes.subtext.animate({
"transform": "S" + ratio + "," + ratio + "T" + (self.x - bb_subtext.x + self.width / 2 - bb_subtext.width / 2) + "," + (self.y - bb_subtext.y + self.height * .95 - bb_subtext.height)
}, self.raphAnimDelay, self.raphAnimType);
eve("delayed.0.interface.response_do_layout." + self._id + "." + self.name);
self.lock.release();
});
}
}
| JavaScript | 0.000001 | @@ -1240,12 +1240,8 @@
CAYP
- 0.2
%22, s
|
73b02ac026b6a9230eafbbbc004c4d52167ff120 | fix #340 | src/view/get-prop-handler.js | src/view/get-prop-handler.js | /**
* @file 获取属性处理对象
* @author errorrik(errorrik@gmail.com)
*/
var contains = require('../util/contains');
var empty = require('../util/empty');
var svgTags = require('../browser/svg-tags');
var evalExpr = require('../runtime/eval-expr');
var getANodeProp = require('./get-a-node-prop');
var NodeType = require('./node-type');
/**
* HTML 属性和 DOM 操作属性的对照表
*
* @inner
* @const
* @type {Object}
*/
var HTML_ATTR_PROP_MAP = {
'readonly': 'readOnly',
'cellpadding': 'cellPadding',
'cellspacing': 'cellSpacing',
'colspan': 'colSpan',
'rowspan': 'rowSpan',
'valign': 'vAlign',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'for': 'htmlFor'
};
/**
* 默认的元素的属性设置的变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandler = {
prop: function (el, value, name, element) {
var propName = HTML_ATTR_PROP_MAP[name] || name;
value = value == null ? '' : value;
// input 的 type 是个特殊属性,其实也应该用 setAttribute
// 但是 type 不应该运行时动态改变,否则会有兼容性问题
// 所以这里直接就不管了
if (propName in el) {
el[propName] = value;
}
else {
el.setAttribute(name, value);
}
// attribute 绑定的是 text,所以不会出现 null 的情况,这里无需处理
// 换句话来说,san 是做不到 attribute 时有时无的
// if (value == null) {
// el.removeAttribute(name);
// }
},
output: function (element, bindInfo, data) {
data.set(bindInfo.expr, element.el[bindInfo.name], {
target: {
id: element.id,
prop: bindInfo.name
}
});
}
};
var svgPropHandler = {
prop: function (el, value, name) {
el.setAttribute(name, value);
}
};
var boolPropHandler = {
prop: function (el, value, name, element, prop) {
var propName = HTML_ATTR_PROP_MAP[name] || name;
el[propName] = !!(prop && prop.raw === ''
|| value && value !== 'false' && value !== '0');
}
};
/* eslint-disable fecs-properties-quote */
/**
* 默认的属性设置变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandlers = {
style: {
prop: function (el, value) {
el.style.cssText = value;
}
},
'class': { // eslint-disable-line
prop: function (el, value) {
el.className = value;
}
},
slot: {
prop: empty
},
draggable: boolPropHandler
};
/* eslint-enable fecs-properties-quote */
var analInputChecker = {
checkbox: contains,
radio: function (a, b) {
return a === b;
}
};
function analInputCheckedState(element, value, oper) {
var bindValue = getANodeProp(element.aNode, 'value');
var bindType = getANodeProp(element.aNode, 'type');
if (bindValue && bindType) {
var type = evalExpr(bindType.expr, element.scope, element.owner);
if (analInputChecker[type]) {
var bindChecked = getANodeProp(element.aNode, 'checked');
if (!bindChecked.hintExpr) {
bindChecked.hintExpr = bindValue.expr;
}
return !!analInputChecker[type](
value,
evalExpr(bindValue.expr, element.scope, element.owner)
);
}
}
}
var elementPropHandlers = {
input: {
multiple: boolPropHandler,
checked: {
prop: function (el, value, name, element) {
var state = analInputCheckedState(element, value);
boolPropHandler.prop(
el,
state != null ? state : value,
'checked',
element
);
},
output: function (element, bindInfo, data) {
var el = element.el;
var bindValue = getANodeProp(element.aNode, 'value');
var bindType = getANodeProp(element.aNode, 'type') || {};
if (bindValue && bindType) {
switch (el.type.toLowerCase()) {
case 'checkbox':
data[el.checked ? 'push' : 'remove'](bindInfo.expr, el.value);
return;
case 'radio':
el.checked && data.set(bindInfo.expr, el.value, {
target: {
id: element.id,
prop: bindInfo.name
}
});
return;
}
}
defaultElementPropHandler.output(element, bindInfo, data);
}
},
readonly: boolPropHandler,
disabled: boolPropHandler,
autofocus: boolPropHandler,
required: boolPropHandler
},
option: {
value: {
prop: function (el, value, name, element) {
defaultElementPropHandler.prop(el, value, name, element);
if (isOptionSelected(element, value)) {
el.selected = true;
}
}
}
},
select: {
value: {
prop: function (el, value) {
el.value = value || '';
},
output: defaultElementPropHandler.output
},
readonly: boolPropHandler,
disabled: boolPropHandler,
autofocus: boolPropHandler,
required: boolPropHandler
},
textarea: {
readonly: boolPropHandler,
disabled: boolPropHandler,
autofocus: boolPropHandler,
required: boolPropHandler
},
button: {
disabled: boolPropHandler,
autofocus: boolPropHandler
}
};
function isOptionSelected(element, value) {
var parentSelect = element.parent;
while (parentSelect) {
if (parentSelect.tagName === 'select') {
break;
}
parentSelect = parentSelect.parent;
}
if (parentSelect) {
var selectValue = null;
var prop;
var expr;
if ((prop = getANodeProp(parentSelect.aNode, 'value'))
&& (expr = prop.expr)
) {
selectValue = parentSelect.nodeType === NodeType.CMPT
? evalExpr(expr, parentSelect.data, parentSelect)
: evalExpr(expr, parentSelect.scope, parentSelect.owner)
|| '';
}
if (selectValue === value) {
return 1;
}
}
}
/**
* 获取属性处理对象
*
* @param {string} tagName 元素tag
* @param {string} attrName 属性名
* @return {Object}
*/
function getPropHandler(tagName, attrName) {
if (svgTags[tagName]) {
return svgPropHandler;
}
var tagPropHandlers = elementPropHandlers[tagName];
if (!tagPropHandlers) {
tagPropHandlers = elementPropHandlers[tagName] = {};
}
var propHandler = tagPropHandlers[attrName];
if (!propHandler) {
propHandler = defaultElementPropHandlers[attrName] || defaultElementPropHandler;
tagPropHandlers[attrName] = propHandler;
}
return propHandler;
}
exports = module.exports = getPropHandler;
| JavaScript | 0 | @@ -923,17 +923,16 @@
value;%0A
-%0A
@@ -5714,24 +5714,160 @@
lPropHandler
+,%0A type: %7B%0A prop: function (el, value) %7B%0A el.setAttribute('type', value %7C%7C '');%0A %7D%0A %7D
%0A %7D%0A%7D;%0A%0Af
|
2273685f9a8c934b6476faaad112313a7f8af813 | add selectize handlers only once | webroot/js/app/lib/AttachmentsWidget.js | webroot/js/app/lib/AttachmentsWidget.js | App.Lib.AttachmentsWidget = Class.extend({
$element: null,
$input: null,
$progress: null,
$fileList: null,
$hiddenSelect: null,
$dropZone: null,
$attachmentsTable: null,
$attachmentId: null,
config: {
uploadUrl: null
},
init: function($element, config) {
this.$element = $element;
if(config) {
this.config = $.extend(this.config, config);
}
this.$input = this.$element.find('.fileupload-input');
this.$fileList = this.$element.find('.fileupload-file-list');
this.$progress = this.$element.find('.fileupload-progress');
this.$progress.hide();
var tagsSelect = this.$element.find('.tags-container div.select');
// make the tag multi select wider if in a form context (edit page)
tagsSelect.find('.col-md-6').removeClass('col-md-6').addClass('col-md-11');
tagsSelect.hide();
if(this.$element.find('select.hidden-attachments-select').length > 0) {
this.$hiddenSelect = this.$element.find('select.hidden-attachments-select');
}
this.$attachmentsTable = this.$element.find('table.attachments');
this.$dropZone = this.$element.find('.dropzone');
this.$dropZone.bind('dragenter', function() {
this.$dropZone.addClass('btn-success');
}.bind(this));
this.$dropZone.bind('dragleave', function() {
this.$dropZone.removeClass('btn-success');
}.bind(this));
this.$dropZone.bind('drop', function() {
this.$dropZone.removeClass('btn-success');
}.bind(this));
if(this.$hiddenSelect) {
// Populate the unsaved file uploads ul if the form is rendered after a validation failure
this.$hiddenSelect.find('option').each(function (i, option) {
var parts = option.value.split('/'); // remove the tmp subfolder
$('<li/>').text(parts[1]).appendTo(this.$fileList);
}.bind(this));
}
this.$attachmentsTable.find('td.actions a.edit-btn').click(function(e) {
var $tr = $(e.currentTarget).parents('tr');
var tagsList = $tr.find('.tags-container .tags');
var tagsInput = $tr.find('.tags-container div.select');
// FIXME move out of this click handler to prevent multiple listener
var selectize = tagsInput.find('select.selectize')[0].selectize;
var contextThis = this;
selectize.on('focus', function () {
contextThis.$attachmentId = this.$wrapper.parents('tr').data('attachment-id');
});
selectize.on('item_add', this._onTagAdded.bind(this));
selectize.on('item_remove', this._onTagRemoved.bind(this));
tagsList.toggle();
tagsInput.toggle();
}.bind(this));
this.$attachmentsTable.find('td.actions a.delete-btn').click(function(e) {
var $tr = $(e.currentTarget).parents('tr');
var attachmentId = $tr.data('attachment-id');
var url = {
plugin: 'attachments',
controller: 'attachments',
action: 'delete',
pass: [attachmentId]
};
if(confirm("Do you really want to delete this file? This action cannot be undone. Click Cancel if you're unsure.")) {
App.Main.UIBlocker.blockElement($tr);
App.Main.request(url, null, function(response) {
App.Main.UIBlocker.unblockElement($tr);
$tr.remove();
});
}
}.bind(this));
var uuid = guid();
this.$input.fileupload({
url: this.config.uploadUrl + '/' + uuid,
dataType: 'json',
dropZone: this.$dropZone,
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<li/>').text(file.name).appendTo(this.$fileList);
}.bind(this));
if(this.$hiddenSelect) {
$.each(data.result.files, function (index, file) {
var filePath = uuid + '/' + file.name;
$('<option/>')
.text(filePath)
.attr('value', filePath)
.attr('selected', true)
.appendTo(this.$hiddenSelect);
}.bind(this));
}
setTimeout(function() {
this.$progress.hide();
}.bind(this), 10000);
}.bind(this),
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
this.$progress.find('.fileupload-progress-bar').css(
'width',
progress + '%'
);
}.bind(this),
start: function (e, data) {
this.$progress.show();
}.bind(this)
})
.prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
},
_onTagAdded: function(tag, $item) {
var $tr = $item.parents('tr');
console.log($tr);
var attachmentId = $tr.data('attachment-id');
var url = {
plugin: 'attachments',
controller: 'attachments',
action: 'addTag',
pass: [attachmentId, tag]
};
App.Main.UIBlocker.blockElement($tr);
App.Main.request(url, null, function(response) {
App.Main.UIBlocker.unblockElement($tr);
});
},
_onTagRemoved: function(tag, $item) {
var $tr = $item.parents('tr');
var url = {
plugin: 'attachments',
controller: 'attachments',
action: 'removeTag',
pass: [this.$attachmentId, tag]
};
App.Main.UIBlocker.blockElement($tr);
App.Main.request(url, null, function(response) {
App.Main.UIBlocker.unblockElement($tr);
});
}
});
| JavaScript | 0 | @@ -2281,24 +2281,85 @@
.select');%0A%0A
+ if (!tagsInput.data('tag-handlers-added')) %7B%0A
@@ -2435,24 +2435,28 @@
+
+
var selectiz
@@ -2516,24 +2516,28 @@
+
var contextT
@@ -2552,32 +2552,36 @@
is;%0A
+
+
selectize.on('fo
@@ -2596,24 +2596,28 @@
nction () %7B%0A
+
@@ -2703,32 +2703,36 @@
');%0A
+
%7D);%0A
@@ -2723,32 +2723,36 @@
%7D);%0A
+
+
selectize.on('it
@@ -2782,32 +2782,36 @@
ed.bind(this));%0A
+
sele
@@ -2857,32 +2857,106 @@
ved.bind(this));
+%0A tagsInput.data('tag-handlers-added', true);%0A %7D
%0A%0A ta
|
1b30da6cd28170b554b5fa906f0ff456e3388dda | Return 400 instead of 500 errors for problems with the request | nodejs/s3/s3handler.js | nodejs/s3/s3handler.js | /**
* NodeJs Server-Side Example for Fine Uploader S3.
* Maintained by Widen Enterprises.
*
* This example:
* - handles non-CORS environments
* - handles delete file requests assuming the method is DELETE
* - Ensures again the file size does not exceed the max (after file is in S3)
* - signs policy documents (simple uploads) and REST requests
* (chunked/multipart uploads)
*
* Requirements:
* - express 3.3.5+ (for handling requests)
* - crypto 0.0.3+ (for signing requests)
* - Amazon Node SDK 1.5.0+ (only if utilizing the AWS SDK for deleting files or otherwise examining them)
*
*/
var express = require("express"),
crypto = require("crypto"),
aws = require("aws-sdk"),
app = express(),
clientSecretKey = process.env.CLIENT_SECRET_KEY,
// These two keys are only needed if you plan on using the AWS SDK
serverPublicKey = process.env.SERVER_PUBLIC_KEY,
serverSecretKey = process.env.SERVER_SECRET_KEY,
// Set these two values to match your environment
expectedBucket = "fineuploadertest",
expectedMaxSize = 15000000,
s3;
// Init S3, given your server-side keys. Only needed if using the AWS SDK.
aws.config.update({
accessKeyId: serverPublicKey,
secretAccessKey: serverSecretKey
});
s3 = new aws.S3();
app.use(express.bodyParser());
app.use(express.static(__dirname)); //only needed if serving static content as well
app.listen(8000);
// Handles all signature requests and the success request FU S3 sends after the file is in S3
// You will need to adjust these paths/conditions based on your setup.
app.post("/s3handler", function(req, res) {
if (req.query.success !== undefined) {
verifyFileInS3(req, res);
}
else {
signRequest(req, res);
}
});
// Handles the standard DELETE (file) request sent by Fine Uploader S3.
// Omit if you don't want to support this feature.
app.delete("/s3handler/*", function(req, res) {
deleteFile(req.query.bucket, req.query.key, function(err) {
if (err) {
console.log("Problem deleting file: " + err);
res.status(500);
}
res.end();
});
});
// Signs any requests. Delegate to a more specific signer based on type of request.
function signRequest(req, res) {
if (req.body.headers) {
signRestRequest(req, res);
}
else {
signPolicy(req, res);
}
}
// Signs multipart (chunked) requests. Omit if you don't want to support chunking.
function signRestRequest(req, res) {
var stringToSign = req.body.headers,
signature = crypto.createHmac("sha1", clientSecretKey)
.update(stringToSign)
.digest("base64");
var jsonResponse = {
signature: signature
};
res.setHeader("Content-Type", "application/json");
if (isValidRestRequest(stringToSign)) {
res.end(JSON.stringify(jsonResponse));
}
else {
res.status(500);
res.end(JSON.stringify({invalid: true}));
}
}
// Signs "simple" (non-chunked) upload requests.
function signPolicy(req, res) {
var base64Policy = new Buffer(JSON.stringify(req.body)).toString("base64"),
signature = crypto.createHmac("sha1", clientSecretKey)
.update(base64Policy)
.digest("base64");
var jsonResponse = {
policy: base64Policy,
signature: signature
};
res.setHeader("Content-Type", "application/json");
if (isPolicyValid(req.body)) {
res.end(JSON.stringify(jsonResponse));
}
else {
res.status(500);
res.end(JSON.stringify({invalid: true}));
}
}
// Ensures the REST request is targeting the correct bucket.
// Omit if you don't want to support chunking.
function isValidRestRequest(headerStr) {
return new RegExp("\/" + expectedBucket + "\/.+$").exec(headerStr) != null;
}
// Ensures the policy document associated with a "simple" (non-chunked) request is
// targeting the correct bucket and the max-size is as expected.
// Omit the parsedMaxSize-related code if you don't have a max file size.
function isPolicyValid(policy) {
var bucket, parsedMaxSize;
policy.conditions.forEach(function(condition) {
if (condition.bucket) {
bucket = condition.bucket;
}
else if (condition instanceof Array && condition[0] === "content-length-range") {
parsedMaxSize = condition[2];
}
});
return bucket === expectedBucket && parsedMaxSize === expectedMaxSize.toString();
}
// After the file is in S3, make sure it isn't too big.
// Omit if you don't have a max file size, or add more logic as required.
function verifyFileInS3(req, res) {
function headReceived(err, data) {
if (err) {
res.status(500);
console.log(err);
res.end(JSON.stringify({error: "Problem querying S3!"}));
}
else if (data.ContentLength > expectedMaxSize) {
res.status(500);
res.write(JSON.stringify({error: "Too big!"}));
deleteFile(req.body.bucket, req.body.key, function(err) {
if (err) {
console.log("Couldn't delete invalid file!");
}
res.end();
});
}
else {
res.end();
}
}
callS3("head", {
bucket: req.body.bucket,
key: req.body.key
}, headReceived);
}
function deleteFile(bucket, key, callback) {
callS3("delete", {
bucket: bucket,
key: key
}, callback);
}
function callS3(type, spec, callback) {
s3[type + "Object"]({
Bucket: spec.bucket,
Key: spec.key
}, callback)
}
| JavaScript | 0.000001 | @@ -2904,33 +2904,33 @@
res.status(
-5
+4
00);%0A res
@@ -3517,33 +3517,33 @@
res.status(
-5
+4
00);%0A res
@@ -4917,33 +4917,33 @@
res.status(
-5
+4
00);%0A
|
824343706c15000118260f2f7818235cc524a4dc | make chat responsive | app/client/views/homes/singleHomeActivityStatus/singleHomeActivityStatus.js | app/client/views/homes/singleHomeActivityStatus/singleHomeActivityStatus.js | Template.singleHomeActivityStatus.onCreated(function () {
const templateInstance = this;
// Get ID of current home
templateInstance.homeId = templateInstance.data.home._id;
// Add variable to hold activity counts
templateInstance.activityLevelCounts = new ReactiveVar();
templateInstance.autorun(function () {
// Get count of home current residents (not departed or on hiatus)
templateInstance.homeCurrentResidentsCount = ReactiveMethod.call("getHomeCurrentAndActiveResidentCount", templateInstance.homeId);
// Retrieve home resident activity level counts from server
const activityLevelCounts = ReactiveMethod.call("getHomeActivityLevelCounts", templateInstance.homeId);
// Make sure activity level counts exist
if (activityLevelCounts && templateInstance.homeCurrentResidentsCount !== undefined) {
/*
Re-structure activity level counts data to an object containing:
type: the type of activity level (inactive, semiActive, active)
count: the number of residents with a given activity level
homePercentage: percentage of home residents with the activity level
*/
const activityLevelTypes = _.keys(activityLevelCounts);
const activityLevelData = _.map(activityLevelTypes, function (type) {
// Default value is 0
let homePercentage = 0;
// Avoid dividing by 0
if (templateInstance.homeCurrentResidentsCount !== 0) {
// Calculate the percentage of home residents in activity level class
homePercentage = Math.round(activityLevelCounts[type] / templateInstance.homeCurrentResidentsCount * 100);
}
// Construct an object with the type and count keys
const activityLevelCountObject = {
// Activity level class (inactive, semi-active, active)
type: type,
// Number of residents in activity class
count: activityLevelCounts[type],
// Percentage of home residents fallint into activity level class
homePercentage: homePercentage
};
return activityLevelCountObject;
});
// Update the reactive variable, to trigger the graph to render
templateInstance.activityLevelCounts.set(activityLevelData);
}
});
});
Template.singleHomeActivityStatus.onRendered(function () {
const colors = ['#d9534f', '#e6c829', '#5cb85c'];
// Get reference to template instance
const templateInstance = this;
// Get home ID
const homeId = templateInstance.homeId;
templateInstance.autorun(function () {
// Get activity level counts
const activityLevelCounts = templateInstance.activityLevelCounts.get();
if (activityLevelCounts) {
// Render chart then data is ready
const data = _.map(activityLevelCounts, (dataset, index) => {
return {
type: 'bar',
orientation: 'h',
// Activity type
name: dataset.type,
// Activity count
x: [dataset.homePercentage],
marker: { color: colors[index]},
width: [0.8],
hoverinfo: 'x+'
}
});
// Add plot layout configuration
const layout = {
autosize: true,
paper_bgcolor: 'transparent',
plot_bgcolor: 'transparent',
height: 50,
xaxis: {
showline: true,
automargin: true,
showticklabels: true,
tickfont: {
size: 10,
},
ticklen: 4,
ticksuffix: '%',
range: [0, 100]
},
yaxis: {
showline: false,
automargin: true,
showticklabels: false,
},
margin: {
r: 10,
t: 10,
b: 5,
l: 10
},
barmode: 'stack',
showlegend: false,
};
// Render plot
Plotly.newPlot(`activityLevelCountsChart-${homeId}`, data, layout, { displayModeBar: false });
}
});
});
| JavaScript | 0 | @@ -3762,17 +3762,17 @@
r: 1
-0
+5
,%0A
@@ -4005,16 +4005,34 @@
r: false
+, responsive: true
%7D);%0A
|
729e7e30e522f5354f916daccd3d01177b6f29b4 | Change notation for object | week-7/eloquent.js | week-7/eloquent.js | // Eloquent JavaScript
// Run this file in your terminal using `node my_solution.js`. Make sure it works before moving on!
// Program Structure
// Write your own variable and do something to it.
var number_of kitties = 1;
var number_of_kitties = number_of_kitties + 100;
console.log(number_of_kitties);
prompt("What is your favorite food?");
alert("Hey, that's my favorite, too! :D");
// Complete one of the exercises: Looping a Triangle, FizzBuzz, or Chess Board
// FizzBuzz
for(var counter=1; counter <= 100; counter++)
{
if (counter % 15 == 0)
console.log("FizzBuzz");
else if (counter % 5 == 0)
console.log("Buzz");
else if (counter % 3 == 0)
console.log("Fizz");
else console.log(counter);
}
// Functions
// Complete the `minimum` exercise.
function min(a, b) {
if (a < b)
console.log(a);
else (a > b)
console.log(b);
}
var me = {
name: ["Sabrina"]
age: [22]
favorite_foods: ["chocolate", "sushi", "peanut butter"]
quirk: ["reads over 100 books each year"]
}
// Data Structures: Objects and Arrays
// Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below.
// Did you learn anything new about JavaScript or programming in general?
// I learned some history of JavaScript, which is always helpful information to have.
// Are there any concepts you feel uncomfortable with?
// Having never seen JavaScript before, it is something that I am completely uncomfortable with. The syntax is what's tripping me up right now.
// Identify two similarities and two differences between JavaScript and Ruby syntax with regard to numbers, arithmetic, strings, booleans, and various operators.
// JS uses + - / * and %, which is the same as in Ruby.
// Null functions very similarly to nil.
// What is an expression?
// A fragment of code that produces a value
// What is the purpose of semicolons in JavaScript? Are they always required?
// They let you know the end of a statement. This is reminding me of CSS. While not always required, they are used almost all of the time, so it is probably good practice to use them.
// What causes a variable to return undefined?
// If you do not assign a value to a variable.
// What does console.log do and when would you use it? What Ruby method(s) is this similar to?
// console.log returns a value to the console. This is similar to the Ruby methods p, puts and print.
// Describe while and for loops
// While and for loops are ways of repeating code without needing to type it all out. You can preform previously written actions on updated values.
// What other similarities or differences between Ruby and JavaScript did you notice in this section?
// Uses {}, but also has syntax that circumvents the need to use them
// Boolean operators operate basically the same way
// Reassinging variables works very similarly, too.
// What are the differences between local and global variables in JavaScript?
// Local variables are variables defined within a function. Global variables are variables defined outside of fuctions.
// When should you use functions?
// Functions seem to be somewhat similar to methods and creating and defining new methods in Ruby. It helps to prevent a block of code from repeating itself.
// What is a function declaration?
// A function declaration defines a variable but also gives it something to do.
// What is the difference between using a dot and a bracket to look up a property? Ex. array.max vs array["max"]
// Using a dot is referring to a variable, using bracket notation is referring to a value by property name. If the string you are trying to access does not have a valid variable name, you want to use bracket notation.
// What is a JavaScript object with a name and value property similar to in Ruby?
// This reminds me a lot of a Hash, just with different notation, but a similar concept. | JavaScript | 0.000001 | @@ -891,17 +891,16 @@
%0A%09name:
-%5B
%22Sabrina
@@ -904,20 +904,19 @@
ina%22
-%5D
+,
%0A%09age:
-%5B
22
-%5D
+,
%0A%09fa
@@ -968,16 +968,17 @@
butter%22%5D
+,
%0A%09quirk:
@@ -978,17 +978,16 @@
%09quirk:
-%5B
%22reads o
@@ -1010,17 +1010,16 @@
ch year%22
-%5D
%0A%7D%0A%0A// D
|
edf65d80e5ca3f5d16aeec1e9c54c8e6e9fe00a5 | Tweak correspondence short name | project/src/js/lichess/perfs.js | project/src/js/lichess/perfs.js | export const perfTypes = [
['bullet', 'Bullet', 'Bullet'],
['blitz', 'Blitz', 'Blitz'],
['classical', 'Classical', 'Classic'],
['correspondence', 'Correspondence', 'Corres'],
['chess960', 'Chess960', '960'],
['kingOfTheHill', 'King Of The Hill', 'KotH'],
['threeCheck', 'Three-check', '3check'],
['antichess', 'Antichess', 'Antichess'],
['atomic', 'Atomic', 'Atomic'],
['horde', 'Horde', 'Horde'],
['racingKings', 'Racing Kings', 'Racing']
];
export default function userPerfs(user) {
var res = perfTypes.map(function(p) {
var perf = user.perfs[p[0]];
if (perf) return {
key: p[0],
name: p[1],
perf
};
});
if (user.perfs.puzzle) res.push({
key: 'puzzle',
name: 'Training',
perf: user.perfs.puzzle
});
return res;
}
export function perfTitle(perf) {
return perfTypes.reduce((prev, curr) => {
if (curr[0] === perf) return curr[1];
else return prev;
}, '');
}
export function shortPerfTitle(perf) {
return perfTypes.reduce((prev, curr) => {
if (curr[0] === perf) return curr[2];
else return prev;
}, '');
}
// https://github.com/ornicar/lila/blob/master/modules/rating/src/main/Glicko.scala#L31
export const provisionalDeviation = 110;
| JavaScript | 0.000001 | @@ -172,16 +172,18 @@
'Corres
+p.
'%5D,%0A %5B'
|
1bb1feec14a9bab2cabf51b2bf7224549a34e418 | Comment about to return false or use preventDefault | spn-drag-drop.js | spn-drag-drop.js | 'use strict';
angular.module('spnDragDrop', []).
directive('spnDraggable', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.attr('draggable', attrs.spnDraggable);
/*
dragstart
drag
dragenter
dragleave
dragover
drop
dragend
*/
function handleDragStart(e) {
element.addClass('spn-drag');
e.originalEvent.dataTransfer.setData('text', 'foo');
return true;
}
function handleDragEnd(e) {
element.removeClass('spn-drag');
return true;
}
element.bind('dragstart', handleDragStart);
element.bind('dragend', handleDragEnd);
}
};
})
.directive('spnDroppable', function() {
return {
restrict: 'A',
scope: {
onDropCallback: '=?spnOnDrop'
},
link: function(scope, element) {
function handleDragEnter(e) {
element.addClass('spn-drag-over');
}
function handleDragLeave(e) {
element.removeClass('spn-drag-over');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop
}
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
console.log(e.originalEvent.dataTransfer.getData('text'));
if (scope.onDropCallback) {
scope.onDropCallback(e);
}
return false;
}
element.bind('drop', handleDrop);
element.bind('dragenter', handleDragEnter);
element.bind('dragover', handleDragOver);
element.bind('dragleave', handleDragLeave);
}
};
});
| JavaScript | 0 | @@ -1632,16 +1632,75 @@
n false;
+ // Maybe we should use a e.preventDefault at the beginning
%0A
|
b10b00be91922e4b4baf4c3edcffcdab4c613c10 | ensure options to path.resolve are strings | tasks/lib/jshint.js | tasks/lib/jshint.js | /*
* grunt-contrib-jshint
* http://gruntjs.com/
*
* Copyright (c) 2013 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
var path = require('path');
var jshintcli = require('jshint/src/cli');
exports.init = function(grunt) {
var exports = {
usingGruntReporter: false
};
var pad = function(msg,length) {
while (msg.length < length) {
msg = ' ' + msg;
}
return msg;
};
// Select a reporter (if not using the default Grunt reporter)
// Copied from jshint/src/cli/cli.js until that part is exposed
exports.selectReporter = function(options) {
switch (true) {
// JSLint reporter
case options.reporter === 'jslint':
case options['jslint-reporter']:
options.reporter = 'jshint/src/reporters/jslint_xml.js';
break;
// CheckStyle (XML) reporter
case options.reporter === 'checkstyle':
case options['checkstyle-reporter']:
options.reporter = 'jshint/src/reporters/checkstyle.js';
break;
// Reporter that displays additional JSHint data
case options['show-non-errors']:
options.reporter = 'jshint/src/reporters/non_error.js';
break;
// Custom reporter
case options.reporter !== undefined:
options.reporter = path.resolve(process.cwd(), options.reporter);
}
var reporter;
if (options.reporter) {
try {
reporter = require(options.reporter).reporter;
exports.usingGruntReporter = false;
} catch (err) {
grunt.fatal(err);
}
}
// Use the default Grunt reporter if none are found
if (!reporter) {
reporter = exports.reporter;
exports.usingGruntReporter = true;
}
return reporter;
};
// Default Grunt JSHint reporter
exports.reporter = function(results, data) {
// Dont report empty data as its an ignored file
if (data.length < 1) {
grunt.log.error('0 files linted. Please check your ignored files.');
return;
}
if (results.length === 0) {
// Success!
grunt.verbose.ok();
return;
}
var options = data[0].options;
grunt.log.writeln();
var lastfile = null;
// Iterate over all errors.
results.forEach(function(result) {
// Only print file name once per error
if (result.file !== lastfile) {
grunt.log.writeln((result.file ? ' ' + result.file : '').bold);
}
lastfile = result.file;
var e = result.error;
// Sometimes there's no error object.
if (!e) { return; }
if (e.evidence) {
// Manually increment errorcount since we're not using grunt.log.error().
grunt.fail.errorcount++;
// No idea why JSHint treats tabs as options.indent # characters wide, but it
// does. See issue: https://github.com/jshint/jshint/issues/430
// Replacing tabs with appropriate spaces (i.e. columns) ensures that
// caret will line up correctly.
var evidence = e.evidence.replace(/\t/g,grunt.util.repeat(options.indent,' '));
grunt.log.writeln((pad(e.line.toString(),7) + ' |') + evidence.grey);
grunt.log.write(grunt.util.repeat(9,' ') + grunt.util.repeat(e.character -1,' ') + '^ ');
grunt.verbose.write('[' + e.code + '] ');
grunt.log.writeln(e.reason);
} else {
// Generic "Whoops, too many errors" error.
grunt.log.error(e.reason);
}
});
grunt.log.writeln();
};
// Run JSHint on the given files with the given options
exports.lint = function(files, options, done) {
var cliOptions = {
verbose: grunt.option('verbose'),
extensions: '',
};
// A list of non-dot-js extensions to check
if (options.extensions) {
cliOptions.extensions = options.extensions;
delete options.extensions;
}
// A list ignored files
if (options.ignores) {
if (typeof options.ignores === 'string') {
options.ignores = [options.ignores];
}
cliOptions.ignores = options.ignores;
delete options.ignores;
}
// Option to extract JS from HTML file
if (options.extract) {
cliOptions.extract = options.extract;
delete options.extract;
}
// Get reporter output directory for relative paths in reporters
if (options.hasOwnProperty('reporterOutput')) {
var reporterOutputDir = path.dirname(options.reporterOutput);
delete options.reporterOutput;
}
// Select a reporter to use
var reporter = exports.selectReporter(options);
// Remove bad options that may have came in from the cli
['reporter', 'jslint-reporter', 'checkstyle-reporter', 'show-non-errors'].forEach(function(opt) {
if (options.hasOwnProperty(opt)) {
delete options[opt];
}
});
if (options.jshintrc === true) {
// let jshint find the options itself
delete cliOptions.config;
} else if (options.jshintrc) {
// Read JSHint options from a specified jshintrc file.
cliOptions.config = jshintcli.loadConfig(options.jshintrc);
} else {
// Enable/disable debugging if option explicitly set.
if (grunt.option('debug') !== undefined) {
options.devel = options.debug = grunt.option('debug');
// Tweak a few things.
if (grunt.option('debug')) {
options.maxerr = Infinity;
}
}
// pass all of the remaining options directly to jshint
cliOptions.config = options;
}
// Run JSHint on all file and collect results/data
var allResults = [];
var allData = [];
cliOptions.args = files;
cliOptions.reporter = function(results, data) {
results.forEach(function(datum) {
datum.file = reporterOutputDir ? path.relative(reporterOutputDir, datum.file) : datum.file;
});
reporter(results, data, options);
allResults = allResults.concat(results);
allData = allData.concat(data);
};
jshintcli.run(cliOptions);
done(allResults, allData);
};
return exports;
};
| JavaScript | 0.998513 | @@ -1304,16 +1304,27 @@
reporter
+.toString()
);%0A %7D
|
fd819bcba00fc83dcc35d01972597b8598e5fc3c | add context and params for willQuery and didQuery hooks | addon/modules/object-browser-serializer.js | addon/modules/object-browser-serializer.js | import Ember from 'ember'
const {on} = Ember
import offsetPagination from './pagination/offset'
// import cursorPagination from './pagination/cursor'
export default Ember.Object.extend({
initContext: on('init', function () {
Ember.defineProperty(this, 'pagination', undefined, (function () {
let pagination = this.get('config.page')
if (typeof pagination === 'undefined') {
return offsetPagination
} else {
return this.get('pagination.strategy')
}
}).call(this))
}),
// normalization methods
normalizeFilter: function (filter) {
// normalize processing
let keys = Object.keys(filter)
if (!Ember.isPresent(keys)) {
return []
}
// get rid of junks prop from component output
let processedFilter = {}
keys.forEach((key) => {
processedFilter[key] = filter[key]
})
return processedFilter
},
normalizeSort: function (sort) {
if (!Ember.isPresent(sort)) {
return []
}
return sort.map(function (item) {
let key = item.value
let direction = item.direction === ':desc' ? '-' : ''
return `${direction}${key}`
})
},
normalizePage: function (page) {
return page
},
// hooks that can be overwritten
serializeQueryParams: function (queryObject) {
return queryObject
},
didReceiveResponse: function (response) {
return response
},
willQuery: function () {
},
didQuery: function () {
},
// query related
query(params) {
const context = this.get('context')
console.log(params.filterQueryParam)
console.log(params.sortQueryParam)
console.log(params.pageQueryParam)
let queryObject = {
filter: params && params.filterQueryParam,
sort: params && params.sortQueryParam,
page: params && params.pageQueryParam
}
const serializedQueryObject = this.serializeQueryParams(queryObject)
this.willQuery()
if (true) {
return this.serverQuery(serializedQueryObject, context).then(response => {
// get pagination module
let paginationHelper = this.get('pagination')
return paginationHelper ? paginationHelper.processPageResponse(response, context, queryObject) : response
})
} else {
let dataKey = context.get('objectBrowserConfig.listConfig.items')
let result = context.get(dataKey)
if (this.get('config.filter.client')) {
result = this.clientFilter(result, queryObject.filter)
}
if (this.get('config.sort.client')) {
result = this.clientSort(result, queryObject.sort)
}
this.didQuery()
return Ember.RSVP.resolve(result)
}
},
serverQuery(queryObject, context) {
let promise = context.get('store').query(this.get('config.model'), queryObject).then(
(response) => {
let meta = response.get('meta')
let processedResponse = this.didReceiveResponse(response)
if (this.get('config.filter.client')) {
processedResponse = this.clientFilter(processedResponse, queryObject.filter)
}
if (this.get('config.sort.client') && queryObject.sort.length > 0) {
processedResponse = this.clientSort(processedResponse, queryObject.sort)
}
Ember.set(processedResponse, 'meta', meta)
return processedResponse
}
)
this.didQuery()
return promise
},
clientFilter(items, filter) {
const context = this.get('context')
const config = context.get('objectBrowserConfig.serializerConfig.filter.client')
if (config) {
if(config && typeof config === 'function') {
console.log('run custom client filter')
return config(items, filter)
} else {
console.log('run default client filter')
return context.objectBrowserDefaultFilter(items, filter)
}
}
return items
},
clientSort(items, sortProperties) {
const context = this.get('context')
const config = context.get('objectBrowserConfig.serializerConfig.sort.client')
if (config) {
if(config && typeof config === 'function') {
console.log('run custom client sort')
return config(items, sortProperties)
} else {
console.log('run default client sort')
return context.objectBrowserDefaultSort(items, sortProperties)
}
}
return items
}
})
| JavaScript | 0 | @@ -1912,25 +1912,60 @@
is.willQuery
-(
+.call(context, serializedQueryObject
)%0A if (tr
@@ -2629,25 +2629,60 @@
his.didQuery
-(
+.call(context, serializedQueryObject
)%0A retu
|
25ae19ce517540d58f63aa05028ce42e2a120cff | Change word | src/BoardView.js | src/BoardView.js | import React, { Component } from 'react';
import ReactPaginate from 'react-paginate';
import BoardThreadList from './BoardThreadList';
import SubmitForm from './SubmitForm';
import Endpoints from './Endpoints';
import './styles/BoardView.css';
class BoardView extends Component {
constructor(props) {
super(props);
this.state = {
threads: [],
totalThreadsOnServer: 0,
offset: this.offsetFromPage(props.params.page)
};
}
offsetFromPage(page) {
return page * 10;
}
componentDidMount() {
this.fetchThreads(this.props.params.board, this.state.offset);
}
componentWillReceiveProps(nextProps) {
this.fetchThreads(nextProps.params.board, this.offsetFromPage(nextProps.params.page));
}
componentDidUpdate(prevProps, prevState) {
const currPage = parseInt(this.props.params.page, 10);
const thereAreNoThreadsAndWeAreOnOnlyPage = this.state.pageNum <= 0 && currPage === 0;
if (currPage >= this.state.pageNum && !thereAreNoThreadsAndWeAreOnOnlyPage) {
// don't let people go over the limit
this.navigateToPage(0);
}
}
getAmountOfPostsElem() {
const amountOfPostsElem =
this.state.totalThreadsOnServer > 0
? (<p>Threads: {this.state.totalThreadsOnServer}</p>)
: (<p>No threads yet! Submit a new thread with the form above.</p>);
return (
<div className="BoardView__totalPostsCounter">
{amountOfPostsElem}
</div>
);
}
render() {
let content = <BoardThreadList threads={this.state.threads} board={this.props.params.board} />;
if (this.state.threads.length < 1) {
// no threads here yet
content = "";
}
return (
<div className="BoardView">
<SubmitForm title="Submit new thread" submit={this.submitResponse.bind(this)} />
{this.getAmountOfPostsElem()}
<ReactPaginate previousLabel={"<previous"}
nextLabel={"next>"}
pageNum={this.state.pageNum}
initialSelected={parseInt(this.props.params.page, 10)}
pageRangeDisplayed={5}
marginPagesDisplayed={2}
clickCallback={this.handlePageClick.bind(this)}
breakLabel={<a href="">...</a>}
containerClassName={"Pagination"}
subContainerClassName={"Pagination__pages Pagination"}
activeClassName={"Pagination__active"}
/>
{content}
</div>
);
}
submitResponse(formData) {
Endpoints.Threads(this.props.params.board).postData(formData)
.then(data => {
console.log("BoardView::submitResponse", data);
window.location.reload();
})
.catch(err => {
console.error("BoardView::submitResponse", "Error while submitting new topic", err);
});
}
fetchThreads(board, offset) {
Endpoints.Threads(board).getData('?start=' + offset)
.then(data => {
data.board = board; // silly reply links need this
this.setState({
threads: data.posts,
pageNum: Math.ceil(data.total_count / 10),
totalThreadsOnServer: data.total_count
});
})
.catch(err => {
console.error(this.constructor.name, 'Error while fetching threads!', err);
});
}
handlePageClick(data) {
const selectedIndex = data.selected;
const offset = Math.ceil(selectedIndex * 10);
this.navigateToPage(selectedIndex);
this.setState({
offset: offset
});
}
navigateToPage(page) {
const currentPath = this.props.router.location.pathname;
const lastSlash = currentPath.lastIndexOf('/');
const newPath = currentPath.substring(0, lastSlash + 1) + page;
this.props.router.push(newPath);
}
}
export default BoardView; | JavaScript | 0.002402 | @@ -1321,22 +1321,20 @@
? (%3Cp%3E
-Thread
+Post
s: %7Bthis
|
a603e1defd25851f2661e1e266ce7c081fceb0f0 | add missing campaign api methods | src/Campaigns.js | src/Campaigns.js | 'use strict'
const {encode} = require('./helpers')
module.exports = class Campaigns {
constructor (client) {
this.client = client
}
addVoucher (campaignName, voucher, callback) {
return this.client.post(
`/campaigns/${encode(campaignName)}/vouchers`,
// TODO if voucher is optional, secure against callback version
voucher || {},
callback
)
}
}
| JavaScript | 0.000002 | @@ -136,16 +136,218 @@
nt%0A %7D%0A%0A
+ create (campaign, callback) %7B%0A return this.client.post('/campaigns', campaign, callback)%0A %7D%0A%0A get (name, callback) %7B%0A return this.client.get(%60/campaigns/$%7Bencode(name)%7D%60, null, callback)%0A %7D%0A%0A
addVou
@@ -584,11 +584,163 @@
)%0A %7D
+%0A%0A importVouchers (campaignName, vouchers, callback) %7B%0A return this.client.post(%60/campaigns/$%7Bencode(campaignName)%7D/import%60, vouchers, callback)%0A %7D
%0A%7D%0A
|
48d5e37e9db7786c39c6b595319de5874cdec427 | dest task cwd | tasks/src/common.js | tasks/src/common.js | import gulp from 'gulp'
import plugins from 'gulp-load-plugins'
function src({ src, cwd, plumber = false }) {
return gulp.src(src, { cwd })
.pipe(_.plumber(plumber ?
null : { errorHandler: fail }))
}
function emit(o, stream) {
return dest(o, stream)
.pipe(_.connect.reload())
}
function dest({ dest }, stream) {
return stream.pipe(gulp.dest(dest))
}
function fail(error) {
console.error(error.toString())
process.exit(1)
}
function logError(error) {
_.util.log('[' + _.util.colors.red('ERROR') + ']', error.message)
this.emit('end')
}
const _ = plugins()
Object.assign(_, { src, emit, dest, fail, logError })
export default _
| JavaScript | 0.999565 | @@ -301,16 +301,21 @@
t(%7B dest
+, cwd
%7D, stre
@@ -354,16 +354,25 @@
est(dest
+, %7B cwd %7D
))%0A%7D%0A%0Afu
|
a938337912d228592e755f868a7132880ae23e97 | Fix jsdoc | src/DateUtils.js | src/DateUtils.js | /**
* Clone a date object.
*
* @export
* @param {Date} d The date to clone
* @return {Date} The cloned date
*/
export function clone(d) {
return new Date(d.getTime());
}
/**
* Return `true` if the passed value is a valid JavaScript Date object.
*
* @export
* @param {any} value
* @returns {Boolean}
*/
export function isDate(value) {
return value instanceof Date && !isNaN(value.valueOf());
}
/**
* Return `d` as a new date with `n` months added.
*
* @export
* @param {[type]} d
* @param {[type]} n
*/
export function addMonths(d, n) {
const newDate = clone(d);
newDate.setMonth(d.getMonth() + n);
return newDate;
}
/**
* Return `true` if two dates are the same day, ignoring the time.
*
* @export
* @param {Date} d1
* @param {Date} d2
* @return {Boolean}
*/
export function isSameDay(d1, d2) {
if (!d1 || !d2) {
return false;
}
return (
d1.getDate() === d2.getDate() &&
d1.getMonth() === d2.getMonth() &&
d1.getFullYear() === d2.getFullYear()
);
}
/**
* Return `true` if two dates fall in the same month.
*
* @export
* @param {Date} d1
* @param {Date} d2
* @return {Boolean}
*/
export function isSameMonth(d1, d2) {
if (!d1 || !d2) {
return false;
}
return (
d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear()
);
}
/**
* Returns `true` if the first day is before the second day.
*
* @export
* @param {Date} d1
* @param {Date} d2
* @returns {Boolean}
*/
export function isDayBefore(d1, d2) {
const day1 = clone(d1).setHours(0, 0, 0, 0);
const day2 = clone(d2).setHours(0, 0, 0, 0);
return day1 < day2;
}
/**
* Returns `true` if the first day is after the second day.
*
* @export
* @param {Date} d1
* @param {Date} d2
* @returns {Boolean}
*/
export function isDayAfter(d1, d2) {
const day1 = clone(d1).setHours(0, 0, 0, 0);
const day2 = clone(d2).setHours(0, 0, 0, 0);
return day1 > day2;
}
/**
* Return `true` if a day is in the past, e.g. yesterday or any day
* before yesterday.
*
* @export
* @param {Date} d
* @return {Boolean}
*/
export function isPastDay(d) {
const today = new Date();
today.setHours(0, 0, 0, 0);
return isDayBefore(d, today);
}
/**
* Return `true` if a day is in the future, e.g. tomorrow or any day
* after tomorrow.
*
* @export
* @param {Date} d
* @return {Boolean}
*/
export function isFutureDay(d) {
const tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
tomorrow.setHours(0, 0, 0, 0);
return d >= tomorrow;
}
/**
* Return `true` if day `d` is between days `d1` and `d2`,
* without including them.
*
* @export
* @param {Date} d
* @param {Date} d1
* @param {Date} d2
* @return {Boolean}
*/
export function isDayBetween(d, d1, d2) {
const date = clone(d);
date.setHours(0, 0, 0, 0);
return (
(isDayAfter(date, d1) && isDayBefore(date, d2)) ||
(isDayAfter(date, d2) && isDayBefore(date, d1))
);
}
/**
* Add a day to a range and return a new range. A range is an object with
* `from` and `to` days.
*
* @export
* @param {Date} day
* @param {Object} range
* @return {Object} Returns a new range object
*/
export function addDayToRange(day, range = { from: null, to: null }) {
let { from, to } = range;
if (!from) {
from = day;
} else if (from && to && isSameDay(from, to) && isSameDay(day, from)) {
from = null;
to = null;
} else if (to && isDayBefore(day, from)) {
from = day;
} else if (to && isSameDay(day, to)) {
from = day;
to = day;
} else {
to = day;
if (isDayBefore(to, from)) {
to = from;
from = day;
}
}
return { from, to };
}
/**
* Return `true` if a day is included in a range of days.
*
* @export
* @param {Date} day
* @param {Object} range
* @return {Boolean}
*/
export function isDayInRange(day, range) {
const { from, to } = range;
return (
(from && isSameDay(day, from)) ||
(to && isSameDay(day, to)) ||
(from && to && isDayBetween(day, from, to))
);
}
/**
* Return the year's week number (as per ISO, i.e. with the week starting from monday)
* for the given day.
*
* @export
* @param {Date} day
* @returns {Number}
*/
export function getWeekNumber(day) {
const date = clone(day);
date.setHours(0, 0, 0);
date.setDate(date.getDate() + 4 - (date.getDay() || 7));
return Math.ceil(
((date - new Date(date.getFullYear(), 0, 1)) / 8.64e7 + 1) / 7
);
}
export default {
addDayToRange,
addMonths,
clone,
getWeekNumber,
isDate,
isDayAfter,
isDayBefore,
isDayBetween,
isDayInRange,
isFutureDay,
isPastDay,
isSameDay,
isSameMonth,
};
| JavaScript | 0.00006 | @@ -485,22 +485,20 @@
@param %7B
-%5Btype%5D
+Date
%7D d%0A * @
@@ -508,14 +508,14 @@
am %7B
-%5Btype%5D
+number
%7D n%0A
|
ac4ac496f826bbdaaabcc9ad794f19509511e273 | Fix openings resource on request error | src/FullSlate.js | src/FullSlate.js | import request from 'superagent';
/**
* FullSlate API class
* @class
*/
class FullSlate {
/**
* FullSlate API path
* @member {string} API path, the `{key}` string will be replaced with
* with the real key on construction
*/
path = 'https://{key}.fullslate.com/api/'
/**
* @constructs FullSlate
* @param {object} options FullSlate API options
* @param {string} options.key FullSlate key (e.g {key}.fullslate.com)
* @param {string} [options.token] FullSlate API token
* @throws Will throw error if the FullSlate key isn't defined
*/
constructor(options = {}) {
const { key, token } = options;
if (typeof key === 'undefined') {
throw new Error('No key defined');
}
this.key = key;
this.token = token;
// Build new path based off of `key`
this.path = this.path.replace('{key}', this.key);
}
/**
* Employees resource
* @param {number} [id] Employee ID to limit details to a single
* employee
* @throws Will throw error if employee id is not a number
* @return {Promise.<(Array|Object), Error>} Resolve with the API
* response: if `id` provided, an object of the employee will be
* returned, if no `id` provided, an array of all employees will
* be returned. Reject with request or API error.
*/
employees(id) {
if (typeof id !== 'undefined' && !Number.isInteger(id)) {
throw new Error('Invalid employee id');
}
return new Promise((resolve, reject) => {
let endpoint = 'employees';
// Update endpoint if `id` is provided
if (id) {
endpoint = endpoint + `/${id}`;
}
request.get(this.path + endpoint)
.query({
'auth': this.token
})
.end((err, res) => {
if (res.body.failure) {
reject(res.body);
} else if (err) {
reject(err);
}
resolve(res.body);
});
});
}
/**
* Services resource
* @param {number} [id] Service ID to limit details to a single service
* @throws Will throw error if service id is not a number
* @return {Promise.<(Array|Object), Error>} Resolve with the API
* response: if `id` provided, an object of the service will be
* returned, if no `id` provided, an array of all services will
* be returned. Reject with request or API error.
*/
services(id) {
if (typeof id !== 'undefined' && !Number.isInteger(id)) {
throw new Error('Invalid service id');
}
return new Promise((resolve, reject) => {
let endpoint = 'services';
// Update endpoint if `id` is provided
if (id) {
endpoint = endpoint + `/${id}`;
}
request.get(this.path + endpoint)
.query({
'auth': this.token
})
.end((err, res) => {
if (res.body.failure) {
reject(res.body);
} else if (err) {
reject(err);
}
resolve(res.body);
});
});
}
/**
* Openings resource
* @param {number|number[]} services A single service id or an array
* of service ids
* @param {object} [options] Optional opening options
* @param {string} [options.before] Openings before this date (RFC 3339
* formatted date)
* @param {string} [options.after] Openings after this date (RFC 3339
* formatted date)
* @param {string} [options.window] Valid window values are 'week' or 'month'
* @throws Error will be thrown if `services` is invalid or missing
* @return {Promise.<Object, Error>} Resolve with the API response
* Reject with request or API error.
*/
openings(services, options = {}) {
// Validate `service` parameter
if (Array.isArray(services)) {
services.forEach((service) => {
if (!Number.isInteger(service)) {
throw new Error('Invalid services specified');
}
});
} else if (!Number.isInteger(services)) {
throw new Error('Invalid services specified');
}
return new Promise((resolve, reject) => {
const endpoint = 'openings';
let params = {
auth: this.token,
...options
};
// Build services array
params['services[]'] = Array.isArray(services)
? services.join(',')
: services;
request.get(this.path + endpoint)
.query(params)
.end((err, res) => {
if (res.body.failure) {
reject(res.body);
} else {
resolve(res.body);
}
});
});
}
};
export default FullSlate;
| JavaScript | 0.000001 | @@ -3549,21 +3549,30 @@
Object,
+(Object%7C
Error
+)
%3E%7D Resol
@@ -4477,16 +4477,25 @@
%7D else
+ if (err)
%7B%0A
@@ -4495,32 +4495,68 @@
%7B%0A re
+ject(err);%0A %7D%0A%0A re
solve(res.body);
@@ -4555,28 +4555,16 @@
s.body);
-%0A %7D
%0A
|
b58371b4dac3aab4489e6526080341b66e41ddae | remove primary key on $delete | src/FuryModel.js | src/FuryModel.js | (function() {
'use strict';
function FuryModel(pk) {
this._isLoaded = false;
this._isLoading = false;
this._remoteData = null;
this._eventQueue = {
'loaded': [],
'created': [],
'deleted': []
};
this._filteredProperties = [
'_pk',
'_isLoaded',
'_isLoading',
'_remoteData',
'_eventQueue',
'_filteredProperties',
'_load',
'_init',
'_create',
'_update',
'_delete',
'_process',
'_unprocess',
'$exists',
'$isLoaded',
'$isLoading',
'$load',
'$reset',
'$save',
'$delete',
'$raw',
'$once'
];
if (typeof pk === 'undefined') {
this._pk = null;
}
else {
this._pk = pk;
}
if (this._pk === null) {
this._isLoaded = true;
this._init();
}
else {
this.$load();
}
}
FuryModel.prototype._init = function() {
// may inherit
// responsability: define default values
};
FuryModel.prototype._load = function() {
// to inherit
// should return a promise with raw data resolved
};
FuryModel.prototype._create = function(data) {
// to inherit
// should return a promise with the primary key and created raw data as resolved values
};
FuryModel.prototype._update = function(data) {
// to inherit
// should return a promise
};
FuryModel.prototype._delete = function() {
// to inherit
// should return a promise
};
FuryModel.prototype._process = function(data) {
// may inherit
// convert some raw values to something else
// return processed datas
return data;
};
FuryModel.prototype._unprocess = function(object) {
// may inherit
// should return a raw object
return object;
};
FuryModel.prototype.$isLoaded = function() {
return this._isLoaded;
};
FuryModel.prototype.$isLoading = function() {
return this._isLoading;
};
FuryModel.prototype.$exists = function() {
return this._pk !== null;
};
FuryModel.prototype.$load = function() {
var self = this;
if (this.$isLoaded()) {
return when.resolve(this);
}
else if (this.$isLoading()) {
return when.promise(function(resolve) {
self.$once('loaded', function() {
resolve(self);
}); // @todo manage loading error
});
}
else {
self._isLoading = true;
return this
._load()
.then(function(raw) {
self._isLoading = false;
self._isLoaded = true;
self._remoteData = raw;
_setProperties(self, self._process(raw));
return _callEventsOnce(self._eventQueue, 'loaded', self);
});
}
};
FuryModel.prototype.$reset = function() {
Object.keys(this)
.filter(function(prop) {
return this._filteredProperties.indexOf(prop) === -1;
}, this)
.forEach(function(prop) {
if (!this._remoteObject || typeof this._remoteObject[prop] === 'undefined') {
delete this[prop];
}
else {
this[prop] = this._remoteObject[prop]; // @todo deep copy
}
}, this);
};
FuryModel.prototype.$save = function(data) {
var self = this;
if (!this.$exists()) {
return this
._create(data || this.$raw())
.then(function(result) {
var pk = result[0],
raw = result[1];
self._pk = pk;
self._remoteData = raw;
_setProperties(self, self._process(raw));
return _callEventsOnce(self._eventQueue, 'created', self)
.then(_callEventsOnce.bind(undefined, self._eventQueue, 'loaded', self));
});
}
else {
return this
._update(data || this.$raw())
.then(function() {
self._remoteData = self.$raw(true); // @todo optimize
return when.resolve(self);
});
}
};
FuryModel.prototype.$delete = function() {
var self = this;
return this
._delete()
.then(function() {
self._remoteData = null;
return _callEventsOnce(self._eventQueue, 'deleted');
});
};
FuryModel.prototype.$raw = function(enableUnprocess) {
var rawObject;
if (typeof enableUnprocess === 'undefined') {
enableUnprocess = true;
}
if (enableUnprocess) {
rawObject = this._unprocess(this);
}
else {
rawObject = {};
}
Object
.keys(this)
.filter(function(key) {
return this._filteredProperties.indexOf(key) === -1 && !rawObject.hasOwnProperty(key);
}, this)
.forEach(function (key) {
if (this[key] instanceof Array) {
rawObject[key] = this[key].slice();
}
else {
rawObject[key] = this[key];
}
}, this);
return rawObject;
};
FuryModel.prototype.$once = function(eventName, fn) {
if (!this._eventQueue[eventName]) {
throw new Error(eventName + ' is not a valid event');
}
this._eventQueue[eventName].push(fn);
};
function _callEventsOnce(eventQueue, eventName, param) {
var queue = eventQueue[eventName];
var result = when
.sequence(queue, param)
.then(function() {
return when.resolve(param);
});
eventQueue[eventName] = [];
return result;
}
function _setProperties(object, properties) {
Object.keys(properties).forEach(function(prop) {
object[prop] = properties[prop];
});
}
FuryModel.define = function(opts) {
var definableProperties = [
'_constructor',
'_init',
'_load',
'_create',
'_update',
'_delete',
'_process',
'_unprocess'
];
var FuryModelExtended;
if (typeof opts._constructor !== 'undefined') {
FuryModelExtended = opts._constructor;
}
else {
FuryModelExtended = function(pk) {
FuryModel.call(this, pk);
};
}
FuryModelExtended.prototype = Object.create(FuryModel.prototype);
FuryModelExtended.prototype.constructor = FuryModelExtended;
Object
.keys(opts)
.filter(function(prop) {
if (definableProperties.indexOf(prop) === -1) {
throw new Error('property ' + prop + ' is not definable');
}
if (typeof opts[prop] !== 'function') {
throw new Error('property ' + prop + ' should be a function');
}
return prop !== '_constructor';
})
.forEach(function(prop) {
FuryModelExtended.prototype[prop] = opts[prop];
});
return FuryModelExtended;
};
if (typeof exports !== 'undefined') {
exports = FuryModel;
}
else {
window.FuryModel = FuryModel;
}
})(); | JavaScript | 0.000042 | @@ -3995,32 +3995,57 @@
en(function() %7B%0A
+ self._pk = null;%0A
self._re
|
002bdda92fa952916f6c7b847eaa75e50cb5bfa3 | disable satellite view | public/javascript/map_helper.js | public/javascript/map_helper.js | (function() {
this.geocoder = new google.maps.Geocoder();
this.markers = [];
function makeMarker(coordinateArray, map, tweet, color){
var marker = new google.maps.Marker({
position: { lat: coordinateArray[0], lng: coordinateArray[1] },
map: map,
animation: google.maps.Animation.DROP,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 4,
fillOpacity: 0,
strokeColor: color,
strokeWeight: 2
}
});
markers.push(marker);
setMarkerTweetProperties(tweet, marker, map);
};
this.makeMarker = makeMarker;
function prepareTweetContent(marker, content, infowindow, map){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
}
this.prepareTweetContent = prepareTweetContent;
function setMarkerTweetProperties(tweet, marker, map){
var content = tweet;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', prepareTweetContent(marker,content,infowindow, map));
google.maps.event.addListener(marker, 'mouseout', function(){
infowindow.close();
});
}
this.setMarkerTweetProperties = setMarkerTweetProperties;
// Sets the map on all markers in the array. This is necessary so that we can
//clear the map later by setting the map for each Marker as null.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
this.setAllMap = setAllMap;
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
this.clearMarkers = clearMarkers;
function geocoding(address, callback) {
this.geocoder.geocode({"address": address}, function(results, status){
if (status == google.maps.GeocoderStatus.OK){
//take first set of coordinates returned.
var location = results[0].geometry.location
var lat = location.G
var lng = location.K
callback([lat, lng]);
}
});
};
this.geocoding = geocoding;
function initializeMap(){
var mapOptions = {
center: { lat: 20, lng: 0},
zoom: 3
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map.setOptions({styles: styles});
return map; //to make map available for use in application.
}
// this.exports.initializeMap = initializeMap;
this.initializeMap = initializeMap;
}).call(this)
| JavaScript | 0 | @@ -2190,16 +2190,47 @@
zoom: 3
+,%0A mapTypeControl: false
%0A %7D;%0A
|
118788a0a8ed061c0a01a17933a8acf179a96583 | Remove console.log call | public/javascripts/visualize.js | public/javascripts/visualize.js | var visualize = (function() {
return (function(widget, name, reduce) {
var params = {};
if (reduce) {
params['group_level'] = 1;
}
else {
params['reduce'] = false;
}
console.log(params);
$.ajax({
url: "/couchdb/" + name,
type: 'get',
data: { arguments: params},
dataType: 'json',
success: function(data) {
adapter(data['rows']);
var d = new Date();
$("#last_update").html(d.toTimeString());
}
});
});
})();
| JavaScript | 0.000003 | @@ -231,36 +231,8 @@
%7D%0A
- console.log(params);
%0A
|
002d4b4e23aa94a40c35d068115bdb8d1837c7ce | Fix for using non-ascii category name as a link in top_menu | app/assets/javascripts/discourse/models/nav_item.js | app/assets/javascripts/discourse/models/nav_item.js | /**
A data model representing a navigation item on the list views
@class InviteList
@extends Discourse.Model
@namespace Discourse
@module Discourse
**/
var validNavNames = ['latest', 'hot', 'categories', 'category', 'favorited', 'unread', 'new', 'read', 'posted'];
var validAnon = ['latest', 'hot', 'categories', 'category'];
Discourse.NavItem = Discourse.Model.extend({
topicTrackingState: function() {
return Discourse.TopicTrackingState.current();
}.property(),
categoryName: function() {
var split = this.get('name').split('/');
return split[0] === 'category' ? split[1] : null;
}.property('name'),
// href from this item
href: function() {
var name = this.get('name'),
href = Discourse.getURL("/") + name.replace(' ', '-');
if (name === 'category') href += "/" + this.get('categoryName');
return href;
}.property('name'),
count: function() {
var state = this.get('topicTrackingState');
if (state) {
return state.lookupCount(this.get('name'));
}
}.property('topicTrackingState.messageCount'),
excludeCategory: function() {
if (parseInt(this.get('filters.length'), 10) > 0) {
return this.get('filters')[0].substring(1);
}
}.property('filters.length')
});
Discourse.NavItem.reopenClass({
// create a nav item from the text, will return null if there is not valid nav item for this particular text
fromText: function(text, opts) {
var countSummary = opts.countSummary,
split = text.split(","),
name = split[0],
testName = name.split("/")[0];
if (!opts.loggedOn && !validAnon.contains(testName)) return null;
if (!Discourse.Category.list() && testName === "categories") return null;
if (!validNavNames.contains(testName)) return null;
opts = {
name: name,
hasIcon: name === "unread" || name === "favorited",
filters: split.splice(1)
};
// if (countSummary && countSummary[name]) opts.count = countSummary[name];
return Discourse.NavItem.create(opts);
}
});
| JavaScript | 0.000001 | @@ -641,37 +641,20 @@
%0A%0A
-// href from this item%0A href
+categorySlug
: fu
@@ -672,20 +672,21 @@
var
-name
+split
= this.
@@ -700,69 +700,333 @@
me')
-,%0A href = Discourse.getURL(%22/%22) + name.replace(' ', '-
+.split('/');%0A if (split%5B0%5D === 'category' && split%5B1%5D) %7B%0A var cat = Discourse.Site.instance().categories.findProperty('name', split%5B1%5D);%0A return cat ? Discourse.Category.slugFor(cat) : null;%0A %7D%0A return null;%0A %7D.property('name'),%0A%0A // href from this item%0A href: function() %7B%0A var name = this.get('name
');%0A
@@ -1035,14 +1035,28 @@
if
-
(
+
name
+.split('/')%5B0%5D
===
@@ -1070,21 +1070,61 @@
ory'
+
)
-href += %22/%22
+%7B%0A return Discourse.getURL(%22/%22) + 'category/'
+ t
@@ -1144,20 +1144,20 @@
gory
-Name
+Slug
');%0A
retu
@@ -1156,20 +1156,83 @@
-return href;
+%7D else %7B%0A return Discourse.getURL(%22/%22) + name.replace(' ', '-');%0A %7D
%0A %7D
|
a507d756b730f4597d24627151f8dd3d233024d1 | repair the js slugify method | app/assets/javascripts/locomotive/utils/core_ext.js | app/assets/javascripts/locomotive/utils/core_ext.js | (function() {
String.prototype.trim = function() {
return this.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
String.prototype.repeat = function(num) {
for (var i = 0, buf = ""; i < num; i++) buf += this;
return buf;
}
String.prototype.truncate = function(length) {
if (this.length > length) {
return this.slice(0, length - 3) + "...";
} else {
return this;
}
}
String.prototype.slugify = function(sep) {
if (typeof sep == 'undefined') sep = '_';
var alphaNumRegexp = new RegExp('[^\w\\' + sep + ']', 'g');
var avoidDuplicateRegexp = new RegExp('[\\' + sep + ']{2,}', 'g');
return this.replace(/\s/g, sep).replace(alphaNumRegexp, '').replace(avoidDuplicateRegexp, sep).toLowerCase()
}
window.addParameterToURL = function(key, value, context) { // code from http://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript
if (typeof context == 'undefined') context = document;
key = encodeURIComponent(key); value = encodeURIComponent(value);
var kvp = context.location.search.substr(1).split('&');
var i = kvp.length; var x; while(i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key,value].join('='); }
//this will reload the page, it's likely better to store this until finished
context.location.search = kvp.join('&');
}
window.addJavascript = function(doc, src, options) {
var script = doc.createElement('script');
script.type = 'text/javascript';
script.src = src;
if (options && options.onload) {
script.onload = options.onload;
delete(options.onload);
}
for (var key in options) {
script.setAttribute(key, options[key]);
}
doc.body.appendChild(script);
}
window.addStylesheet = function(doc, src, options) {
var stylesheet = doc.createElement('link');
stylesheet.style = 'text/css';
stylesheet.href = src;
stylesheet.media = 'screen';
stylesheet.rel = 'stylesheet';
doc.head.appendChild(stylesheet);
}
})();
| JavaScript | 0.001598 | @@ -535,16 +535,17 @@
Exp('%5B%5E%5C
+%5C
w%5C%5C' + s
@@ -743,16 +743,17 @@
erCase()
+;
%0A %7D%0A%0A
|
8302735a4254393ff04b6a8e1196b20a632abe9c | domain url | app/components/board-audio/board-audio.component.js | app/components/board-audio/board-audio.component.js | (function () {
angular
.module('mysoundboard')
.component('boardAudio', {
controller: boardAudioController,
templateUrl: 'board-audio/board-audio.html',
bindings: {
audio: '='
}
});
function boardAudioController($scope, $mdToast, ResourceFactory, HotkeysService) {
const vm = this;
vm.vars = {
editing: 0,
playing: false,
keyBackup: null,
audio: new Audio(`http://localhost:3000/api/audiodata/${vm.audio.file}/stream`)
};
vm.vars.audio.onended = () => {
vm.vars.playing = false;
};
vm.edit = edit;
vm.save = save;
vm.cancel = cancel;
vm.delete = deletefn;
activate();
///////////////
function activate() {
register();
}
function register() {
if (vm.audio.key && !vm.audio.disabled) {
HotkeysService.register({
type: 'audio',
id: vm.audio._id,
hotkey: vm.audio.key,
play,
stop
});
}
}
function unregister() {
HotkeysService.unregister({
type: 'audio',
id: vm.audio._id
});
}
function edit() {
vm.vars.keyBackup = vm.audio.key;
vm.vars.editing = true;
}
function save() {
vm.vars.editing = false;
vm.audio.key = vm.audio.key || '';
ResourceFactory
.audio
.update({
audioId: vm.audio._id
}, vm.audio);
unregister();
register();
}
function cancel() {
vm.audio.key = vm.vars.keyBackup;
vm.vars.editing = false;
}
function deletefn() {
ResourceFactory
.audio
.delete({
audioId: vm.audio._id
});
$mdToast.show($mdToast.simple().textContent('Audio Deleted!'));
vm.audio.deleted = true;
}
function play() {
if (!vm.vars.playing && !vm.vars.editing && !vm.audio.disabled) {
vm.vars.playing = true;
vm.vars.audio.play();
}
}
function stop() {
if (vm.vars.playing) {
vm.vars.playing = false;
vm.vars.audio.pause();
vm.vars.audio.load();
}
}
}
})();
| JavaScript | 0.999821 | @@ -444,22 +444,35 @@
p://
-localhost:3000
+my-soundboard.herokuapp.com
/api
|
b445265f5785a73aa1e5bf165f8081015908c886 | Change visible param for widgets | app/components/createEditWidget/createEditWidget.js | app/components/createEditWidget/createEditWidget.js | createEditWidget.$inject = ['api'];
function createEditWidget(api) {
return {
restrict: 'AE',
scope: {},
templateUrl: 'app/components/createEditWidget/createEditWidget.html',
link: function(scope, elem, attr, ctrl) {
scope.action = scope.$parent.subroute.action;
scope.type = scope.$parent.subroute.type.toLowerCase();
if (scope.$parent.subroute.hasOwnProperty('widget')) {
// had to create new object bcs api rejects extra fields
scope.widget = {
'id' : angular.copy(scope.$parent.subroute.widget.id),
'name' : angular.copy(scope.$parent.subroute.widget.name),
'type' : angular.copy(scope.$parent.subroute.widget.type),
'visible' : true,
'parameters' : angular.copy(scope.$parent.subroute.widget.parameters)
};
} else {
scope.widget = {
'name' : '',
'visible' : true,
'type' : scope.type,
'parameters' : {}
};
}
scope.availableMenus = [];
scope.availableContentLists = [];
scope.getMenus = () => {
api.get('menus').then((response) => {
scope.availableMenus = response._embedded._items;
});
};
scope.getContentLists = () => {
api.get('content/lists').then((response) => {
scope.availableContentLists = response._embedded._items;
});
};
scope.setRoute = (route) => {
scope.widget = {};
scope.$parent.setRoute(route);
};
scope.toggleModal = () => {
scope.widget = {};
scope.$parent.toggleModal();
};
scope.save = () => {
let id = scope.widget.id ? scope.widget.id : '';
// api throws error when extra params are included. Temp hack
delete scope.widget.id;
api.save('templates/widgets', {widget: scope.widget}, id).then((response) => {
if (id) {
scope.setRoute('main');
} else {
scope.setRoute('linkWidget');
}
});
};
scope.cancel = () => {
scope.setRoute('main');
};
// temp hack until they standardize type in api widget object
if (/menu/.test(scope.type)) {
scope.type = "menu";
scope.readableType = "Menu";
scope.widget.type = 3;
scope.getMenus();
} else if (/html/.test(scope.type)) {
scope.type = "html";
scope.readableType = "HTML Block";
scope.widget.type = 1;
} else if (/adsense/.test(scope.type)) {
scope.type = "adsense";
scope.readableType = "AdSense";
scope.widget.type = 2;
} else if (/contentlist/.test(scope.type)) {
scope.type = "contentList";
scope.readableType = "Content List";
scope.widget.type = 4;
scope.getContentLists();
}
}
};
}
function capitalize() {
return function(input) {
return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : '';
};
}
angular.module('livesite-management.components.createEditWidget', [])
.directive('swpCreateEditWidget', createEditWidget)
.filter('capitalize', capitalize);
| JavaScript | 0 | @@ -804,36 +804,38 @@
'visible' :
+'
true
+'
,%0A
@@ -1048,20 +1048,22 @@
ible' :
+'
true
+'
,%0A
|
d4fee24194158a5b13b59cadf468f40bc849227a | fix multi-batch code durations | app/frontend/app/controllers/organization/extras.js | app/frontend/app/controllers/organization/extras.js | import Ember from 'ember';
import Controller from '@ember/controller';
import persistence from '../../utils/persistence';
import modal from '../../utils/modal';
import i18n from '../../utils/i18n';
export default Controller.extend({
refresh_lists: function() {
this.load_blocked_emails();
this.load_gifts();
},
load_gifts: function(more) {
var _this = this;
_this.set('gifts', {loading: true});
_this.store.query('gift', {}).then(function(list) {
_this.set('gifts', list);
}, function(err) {
_this.set('gifts', {error: true});
});
},
load_blocked_emails: function() {
var _this = this;
_this.set('blocked_emails', {loading: true});
persistence.ajax('/api/v1/organizations/' + this.get('model.id') + '/blocked_emails', {type: 'GET'}).then(function(res) {
_this.set('blocked_emails', res.emails);
}, function(err) {
_this.set('blocked_emails', {error: true});
});
},
gift_types: [
{name: i18n.t('select_type', "[ Select Type ]"), id: ""},
{name: i18n.t('single_user_gift_code', "Single User Gift Code"), id: "user_gift"},
{name: i18n.t('bulk_purchase', "Bulk License Purchase"), id: "bulk_purchase"},
{name: i18n.t('gift_code_batch', "Gift Code Batch"), id: "multi_code"},
{name: i18n.t('discount_code', "Discount Code"), id: "discount"},
],
current_gift_type: function() {
var res = {};
res[this.get('gift_type')] = true;
return res;
}.property('gift_type'),
actions: {
block_email: function() {
var email = this.get('blocked_email_address');
var _this = this;
if(email) {
persistence.ajax('/api/v1/organizations/' + this.get('model.id') + '/extra_action', {
type: 'POST',
data: {
extra_action: 'block_email',
email: email
}
}).then(function(res) {
if(res.success === false) {
modal.error(i18n.t('blocking_email_failed', "Email address was not blocked"));
} else {
_this.set('blocked_email_address', null);
_this.load_blocked_emails();
}
}, function(err) {
modal.error(i18n.t('error_blocking_email', "There was an unexpected error while trying to add the blocked email address"));
});
}
},
add_gift: function(type) {
var gift = this.store.createRecord('gift');
if(type == 'purchase') {
gift.set('amount', parseFloat(this.get('amount')));
gift.set('licenses', parseInt(this.get('licenses'), 10));
gift.set('organization', this.get('org'));
gift.set('email', this.get('email'));
gift.set('memo', this.get('memo'));
} else if(type == 'multi_code') {
gift.set('org_id', this.get('org_id'));
gift.set('total_codes', parseInt(this.get('total_codes'), 10));
gift.set('organization', this.get('org'));
gift.set('email', this.get('email'));
gift.set('memo', this.get('memo'));
var years = parseFloat(this.get('duration')) || 5;
gift.set('seconds', years * 365.25 * 24 * 60 * 60);
} else if(type == 'discount') {
var amount = parseFloat(this.get('discount_pct'));
if(amount <= 0 || isNaN(amount)) { return; }
if(amount > 1.0) { amount = amount / 100; }
gift.set('discount', amount);
gift.set('organization', this.get('org'));
gift.set('email', this.get('email'));
if(this.get('expires') && this.get('expires').length > 0) {
gift.set('expires', window.moment(this.get('expires'))._d);
}
gift.set('code', this.get('code'));
gift.set('limit', this.get('limit'));
} else {
var years = parseFloat(this.get('duration')) || 3;
gift.set('seconds', years * 365.25 * 24 * 60 * 60);
gift.set('gift_name', this.get('gift_name'));
}
var _this = this;
gift.save().then(function() {
_this.load_gifts();
}, function(err) {
if(err && err.error == 'code is taken') {
modal.error(i18n.t('code_taken', "There was an error creating the custom purchase, that code has already been taken"));
} else {
modal.error(i18n.t('error_creating_gift', "There was an error creating the custom purchase"));
}
});
}
}
});
| JavaScript | 0.000333 | @@ -3020,32 +3020,29 @@
t(this.get('
-duration
+years
')) %7C%7C 5;%0A
|
288f7e678ae3096aeda138bf3a07fa3f2e40553a | Update prdt_detl_controller.js | app/modules/product_details/prdt_detl_controller.js | app/modules/product_details/prdt_detl_controller.js | 'use strict';
angular.module('tgtApp.prdt_detl').controller('prdt_detl_ctrl', ["dataService","$scope",function(dataService,$scope) {
//scope object to store product information
$scope.product = [];
//call webservice to load product information from json file
var promise=dataService.getItems();
promise.then(function(data){
if(data.length==1){
//load all product details into scope object and variables
$scope.product = data[0];
$scope.primaryImage = $scope.product.Images[0].PrimaryImage[0].image;
//data for configuration of rating widget
$scope.overallRating = $scope.product.CustomerReview[0].consolidatedOverallRating;
$scope.proRating = $scope.product.CustomerReview[0].Pro[0].overallRating;
$scope.conRating = $scope.product.CustomerReview[0].Con[0].overallRating;
//convert timestamp into js date format
$scope.conDate = new Date($scope.product.CustomerReview[0].Con[0].datePosted);
$scope.proDate = new Date($scope.product.CustomerReview[0].Pro[0].datePosted);
}
else if(data.length>1){
console.log("Multiple products found. Please check");
}
else{
console.log("No product information found");
}
}, function(error){
console.log("Error occurred while fetching product information: "+error);
});
//data for configuration of rating widget
$scope.max = 5;
$scope.isReadonly = true;
//carousel thumbnail onclick handler - change primary image to thumbnail image
$scope.changePrimaryImage = function(img){
$scope.primaryImage = img;
}
}]); | JavaScript | 0.000001 | @@ -1565,10 +1565,706 @@
%0A %7D
+%0A %0A //initialization of data and logic for quantity control%0A $scope.qty = 1;%0A $scope.minQty = 1;%0A $scope.maxQty = 10;%0A%0A $scope.plus = function()%0A %7B%0A if($scope.qty%3C$scope.maxQty)%7B%0A $scope.qty= $scope.qty+1;%0A %7D%0A %7D%0A $scope.minus = function()%0A %7B%0A if($scope.qty%3E$scope.minQty)%7B%0A $scope.qty= $scope.qty-1;%0A %7D%0A %7D%0A%0A $scope.$watch('qty', function() %0A %7B%0A if($scope.qty%3E$scope.minQty)%7B%0A $scope.minusActive = false;%0A %7D%0A else if($scope.qty==$scope.minQty)%7B%0A $scope.minusActive = true;%0A %7D%0A%0A if($scope.qty%3C$scope.maxQty)%7B%0A $scope.plusActive = false;%0A %7D%0A else if($scope.qty==$scope.maxQty)%7B%0A $scope.plusActive = true;%0A %7D%0A %7D, true);
%0A%0A%7D%5D);
+%0A
|
5046da534cf5928e8ed092ad05ba36665264662e | Add tanura.eventHandler.check(). | public/javascripts/app.js | public/javascripts/app.js | 'use strict';
/*
* Tanura main script.
*
* This script defines Tanura's high level features.
*/
/*
* Fire an event.
*
* When given an event name, this function will run all callbacks for that
* event. Exit is true on success, false otherwise.
*/
tanura.eventHandler.fire = (x) =>
((_) =>
! (! _[x]
|| ! _[x].forEach
|| _[x].forEach((i) => i())))(tanura.eventHandler.events);
/*
* Register a callback for an event.
*
* This will add a function to be called whenever a given event occurs. Exit is
* true on success, false otherwise.
*/
tanura.eventHandler.register = (x, f) =>
((_) =>
! (! _[x] || ! _[x].push || _[x].push(f)))(tanura.eventHandler.events);
| JavaScript | 0 | @@ -95,16 +95,320 @@
s.%0A */%0A%0A
+/*%0A * Check if an event exists.%0A *%0A * When given an event name, this function will check, if there is an entry in %0A * tanura.eventHandler.events for that name, that has the methods required.%0A */%0Atanura.eventHandler.check = (x) =%3E%0A ((_) =%3E !! _%5Bx%5D && Array.isArray(_%5Bx%5D))(tanura.eventHandler.events);%0A%0A
/*%0A * Fi
@@ -416,24 +416,24 @@
e an event.%0A
-
*%0A * When g
@@ -597,106 +597,50 @@
-((_) =%3E%0A ! (! _%5Bx%5D%0A %7C%7C ! _%5Bx%5D.forEach%0A %7C%7C _%5Bx%5D.forEach((i) =%3E i())))(
+tanura.eventHandler.check(x)%0A && !
tanu
@@ -653,32 +653,54 @@
ntHandler.events
+%5Bx%5D.forEach((i) =%3E i()
);%0A%0A/*%0A * Regist
@@ -901,67 +901,42 @@
-((_) =%3E%0A ! (! _%5Bx%5D %7C%7C ! _%5Bx%5D.push %7C%7C _%5Bx%5D.push(f)))(
+tanura.eventHandler.check(x) && !
tanu
@@ -941,28 +941,38 @@
nura.eventHandler.events
+%5Bx%5D.push(f
);%0A%0A
|
33121629a7d5cf377d157bbd522f64454dd690e0 | add notes on map.js | public/javascripts/map.js | public/javascripts/map.js | document.addEventListener('DOMContentLoaded', function () {
var location = document.getElementById("location");
function showPosition(position) {
location.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
initialize(position.coords.latitude, position.coords.longitude);
};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
location.innerHTML = "Geolocation is not supported by this browser.";
}
};
var map;
function initialize(lat, lng) {
var mapOptions = {
zoom: 12,
center:{lat: lat, lng: lng}
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
draggable: false,
map: map,
icon: "http://www.4smileys.com/smileys/food-smileys/hungry_boy.gif",
animation: google.maps.Animation.DROP
});
// set geocode so we can identify truck stops with address
var geocoder = new google.maps.Geocoder();
var showTrucks = document.getElementById("showTrucks");
showTrucks.addEventListener('click', function(e){
e.preventDefault();
geocodeAddress(geocoder, map);
});
}
function geocodeAddress(geocoder, resultsMap) {
for (i = 0; i < objArr.length; i++) {
var address = JSON.stringify(objArr[i].address + " San Francisco, CA")
console.log(address)
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
// resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
icon: "http://www.localsconnected.com/wp-content/uploads/2014/11/Food-Truck-Icon.png",
draggable: false,
map: map,
});
}; // if
}); // geocode
}; // for
}; // geocodeAddress
getLocation();
}); // document
| JavaScript | 0.000001 | @@ -1,16 +1,51 @@
+// equivilant to $(document).ready%0A
document.addEven
@@ -87,16 +87,70 @@
ion () %7B
+%0A%0A // displays location from the getlocation function
%0A var l
@@ -427,16 +427,46 @@
e);%0A %7D;
+%0A%0A // html5 gets geo location
%0A funct
@@ -694,17 +694,46 @@
%7D%0A %7D;%0A
+ // initializing google maps
%0A
-
var ma
@@ -1660,35 +1660,9 @@
CA%22)
-%0A console.log(address)
+;
%0A
@@ -2102,32 +2102,32 @@
aggable: false,%0A
-
map:
@@ -2124,32 +2124,82 @@
map: map,%0A
+ animation: google.maps.Animation.DROP%0A
%7D);%0A
|
ac38014106b17df9186c27e6cf1a197f9ad8dbbc | Test for loader passing query.cli | test/loader.test.js | test/loader.test.js | var expect = require("expect");
var installer = require("../src/installer");
var loader = require("../src/loader");
var path = require("path");
describe("loader", function() {
beforeEach(function() {
expect.spyOn(console, "info");
this.callback = expect.createSpy();
this.check = expect.spyOn(installer, "check").andCallThrough();
this.install = expect.spyOn(installer, "install");
this.map = "map";
this.source = [
"require('mocha')",
"import expect from 'expect'",
"import * as missing from 'missing'",
].join("\n");
this.options = {
context: process.cwd(),
resolve: {
root: ["test"],
modulesDirectories: ["node_modules"],
},
};
loader.call(this, this.source, this.map);
});
afterEach(function() {
expect.restoreSpies();
});
it("should check resolve.root & resolve.modulesDirectories", function() {
expect(this.check).toHaveBeenCalled();
expect(this.check.calls[0].arguments).toEqual([
["mocha", "expect", "missing"],
[
path.join(this.options.context, "test"),
path.join(this.options.context, "node_modules"),
],
]);
});
it("should install missing", function() {
expect(this.install).toHaveBeenCalled();
expect(this.install.calls[0].arguments).toEqual([
["missing"],
]);
});
it("should callback source & map", function() {
expect(this.callback).toHaveBeenCalled();
expect(this.callback.calls[0].arguments).toEqual([
null,
this.source,
this.map,
]);
});
});
| JavaScript | 0 | @@ -228,24 +228,60 @@
, %22info%22);%0A%0A
+ this.cacheable = function() %7B%7D;%0A
this.cal
@@ -304,24 +304,24 @@
reateSpy();%0A
-
this.che
@@ -755,16 +755,77 @@
%7D;%0A%0A
+ this.query = '?%7B%22cli%22:%7B%22save%22:true,%22saveExact%22:true%7D%7D';%0A%0A
load
@@ -1281,34 +1281,108 @@
%0A%0A
-it(%22should install missing
+context(%22when calling .install%22, function() %7B%0A it(%22should pass dependencies as the first argument
%22, f
@@ -1389,32 +1389,34 @@
unction() %7B%0A
+
expect(this.inst
@@ -1436,32 +1436,34 @@
enCalled();%0A
+
expect(this.inst
@@ -1476,32 +1476,35 @@
lls%5B0%5D.arguments
+%5B0%5D
).toEqual(%5B%0A
@@ -1502,33 +1502,259 @@
al(%5B
-%0A %5B%22missing%22%5D,%0A %5D
+%22missing%22%5D);%0A %7D);%0A%0A it(%22should pass args as the second argument%22, function() %7B%0A expect(this.install).toHaveBeenCalled();%0A expect(this.install.calls%5B0%5D.arguments%5B1%5D).toEqual(%7B%0A save: true,%0A saveExact: true,%0A %7D);%0A %7D
);%0A
@@ -1751,32 +1751,33 @@
%0A %7D);%0A %7D);%0A%0A
+%0A
it(%22should cal
|
fec580b327da8a1bcd2ed994f15c7c7e1a09e690 | set site title and heading upon loading a directory | public_html/assets/app.js | public_html/assets/app.js | var uri_map = {
dir_id: '/d/',
file_id: '/f/',
dir_api: '/a/dir/'
};
var link_map = {
"URI:CHK:": uri_map.file_id,
"URI:DIR2:": uri_map.dir_id,
"URI:DIR2-RO:": uri_map.dir_id + 'ro/'
};
function get_link(lafs_uri) {
for (var k in link_map) {
if (lafs_uri.substr(0, k.length) == k)
return link_map[k] + lafs_uri.substr(k.length).replace(/:/g, '/');
}
return '';
}
function gen_unlink_button(filename, post_uri, return_to) {
var link_a = new Array();
link_a.push('<a href="#" class="unlink_button" data-return-to="' + return_to + '"');
link_a.push(' data-filename="' + filename + '"');
link_a.push(' data-post-uri="' + post_uri + '"');
link_a.push('>delete</a>');
return ' ' + link_a.join('');
}
function fill_grid_rows(children, currentId) {
var filename = null;
var size = null;
var obj_uri = null;
var type = null;
var name_link = null;
var ctime = null;
var child_rows = new Array;
// for each filenode or dirnode fill Array with rows
$.each(children, function(name, child_d) {
size = child_d[1].size;
if (size == null)
size = 0;
obj_uri = child_d[1].rw_uri;
if (obj_uri == null)
obj_uri = child_d[1].ro_uri;
filename = '';
if (child_d[0] == 'filenode')
filename = '/' + name;
type = (child_d[0] == 'filenode') ? 'file' : 'directory';
name_link = '<a href="' + escape(get_link(obj_uri) + filename) + '">' + name + '</a>';
ctime = new Date(Math.round(child_d[1].metadata.tahoe.linkcrtime*1000));
ctime = ctime.toISOString();
ctime = '<abbr class="timeago" title="' + ctime + '">' + ctime + '</abbr>';
// add delete link if its not ro
if (currentId.substr(0,3) == "ro/") {
child_rows.push([name_link, type, size, ctime]);
}
else {
child_rows.push([name_link, type, size, ctime, gen_unlink_button(name, uri_map.dir_api + currentId, uri_map.dir_id + currentId)]);
}
});
return child_rows;
}
function light_up_table(child_rows, currentId) {
var table_config = {
"sDom": "firt",
"aaData": child_rows,
"aoColumns": [
{ "sTitle": "Filename", "sWidth": "70%" },
{ "sTitle": "Type", "sClass": "text-right" },
{ "sTitle": "Size", "sClass": "text-right" },
{ "sTitle": "Created", "sClass": "text-right" }
],
"aLengthMenu": [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
"iDisplayLength" : -1,
"aoColumnDefs": []
};
if (currentId.substr(0,3) != "ro/") {
// options for additional column in datatable
table_config.aoColumns.push({"sTitle": "Options"});
table_config.aoColumnDefs.push({ "sWidth": "5%", "aTargets": [ -1 ] });
table_config.aoColumnDefs.push({ "bSortable": false, "aTargets": [ -1 ] });
table_config.aoColumnDefs.push({ "bSearchable": false, "aTargets": [ -1 ] });
table_config.aoColumnDefs.push({ "sClass": 'text-right', "aTargets": [ -1 ] });
}
// init table and form attributes
$("table.directory").dataTable(table_config);
return true;
}
function make_directory_grid(currentId) {
// make a call for json data at api uri
$.getJSON(uri_map.dir_api + currentId, function(data) {
var child_rows = fill_grid_rows(data[1].children, currentId);
// if nothing in array dont make table or show upload stuffs
if (child_rows.index != 0) {
$("h3.heading").text("Directory: " + data[1].verify_uri.substr(18, 5)).show();
light_up_table(child_rows, currentId); // init table
$("form").attr("action", uri_map.dir_api + currentId);
$("input.return_to").attr("value", location.pathname);
$("abbr.timeago").timeago();
var ro_link = get_link(data[1].ro_uri);
$("a.current-ro-link").attr("href", ro_link);
// do stuff with non-read only links after table is generated
if (currentId.substr(0,3) != "ro/") {
$("a.unlink_button").click(function() {
var post_data = {};
post_data.t = 'unlink';
post_data.name = $(this).attr("data-filename");
post_data.when_done = $(this).attr("data-return-to");
$.post($(this).attr("data-post-uri"), post_data, function(data) {
window.location.href = post_data.when_done;
});
});
// dont need to show upload form if ro link
$("div.upload-form").show();
}
}
});
return true;
}
$(document).ready(function() {
// dynamically create regex for matching view (dirs) uris
var re = new RegExp("^" + uri_map.dir_id.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1") + "((?:ro/)?\\w{26}\\/\\w{52})\\/?$","g");
var matched_id = re.exec(location.pathname);
if ( matched_id != null ) {
make_directory_grid(matched_id[1]);
}
});
| JavaScript | 0 | @@ -3329,30 +3329,21 @@
-$(%22h3.heading%22).text(%22
+var title = '
Dire
@@ -3349,17 +3349,17 @@
ectory:
-%22
+'
+ data%5B
@@ -3385,16 +3385,144 @@
r(18, 5)
+;%0A title += (currentId.substr(0,3) == 'ro/') ? ' (ro)' : '';%0A document.title = title;%0A $(%22h3.heading%22).text(title
).show()
|
777ed91489e33c9a14621d9e9d5abee31ac083cb | Update test_helper.js | test/test_helper.js | test/test_helper.js | var chai = require('chai');
global.expect = chai.expect;
global.fbp = require('..');
global.MockSender = function(inputArray) {
return function() {
var outport = fbp.OutputPort.openOutputPort('OUT');
inputArray.forEach(function(item) {
outport.send(fbp.IP.create(item));
});
}
}
global.MockReceiver = function(outputArray) {
return function() {
var inport = fbp.InputPort.openInputPort('IN');
var ip;
while ((ip = inport.receive()) !== null) {
outputArray.push(ip.contents);
fbp.IP.drop(ip);
}
}
}
| JavaScript | 0.000003 | @@ -1,12 +1,27 @@
+'use strict';%0A%0A
var chai = r
@@ -70,37 +70,216 @@
ct;%0A
-global.fbp = require('..
+%0Avar InputPort = require('../core/InputPort')%0A , InputPortArray = require('../core/InputPortArray')%0A , OutputPort = require('../core/OutputPort')%0A , OutputPortArray = require('../core/OutputPortArray
');%0A%0A
+%0A
glob
@@ -357,20 +357,16 @@
tport =
-fbp.
OutputPo
@@ -450,20 +450,16 @@
rt.send(
-fbp.
IP.creat
@@ -568,20 +568,16 @@
nport =
-fbp.
InputPor
@@ -705,12 +705,8 @@
-fbp.
IP.d
|
f1806a52ef3854801b89dfbae86fa2e3071b4318 | Fix FladeServer updateCurrentFlade crashing when callback is null | services/flade.service.js | services/flade.service.js | var htmlparser = require('htmlparser2');
var https = require('https');
var models = require('../models/index');
const FladeService = {};
FladeService.getAndSaveCurrentFlade = function(callback){
isFladeFromToday(function(fromToday){
if(!fromToday){
updateFlade(callback);
} else {
FladeService.getCurrentFlade(callback);
}
});
};
function isFladeFromToday(callback){
FladeService.getCurrentFlade(function(flade){
if(!flade){
callback(false);
} else {
callback(new Date(flade.timestamp).toDateString() === new Date().toDateString());
}
})
}
function updateFlade(callback){
https.get({
host: 'fladerei.com',
path: '/dyn_inhalte/tagesflade.html'
}, function(res){
var content = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
content += chunk;
});
res.on('end', function(){
parseContentToFlade(content, function(result){
updateCurrentFlade(result, callback);
});
});
});
}
function parseContentToFlade(content, callback){
var berggasse = false;
var tagesflade = false;
var Parser = new htmlparser.Parser({
onopentag: function(name, attribs){
if(name === 'a' && attribs.href.indexOf('berggasse') !== -1){
berggasse = true;
} else if (name === 'span' && berggasse){
tagesflade = true;
}
},
ontext: function(text){
if(tagesflade){
callback(text.replace(/ /gi,''));
}
},
onclosetag: function(tagname){
if(tagname === 'span' && berggasse && tagesflade){
berggasse = tagesflade = false;
}
}
});
Parser.write(content);
Parser.end();
}
function updateCurrentFlade(text, callback){
models.Flade.remove({}, function(){
var flade = new models.Flade({
text: text,
timestamp: new Date()
});
flade.save(function(err, flade){
callback(flade);
});
});
}
FladeService.getCurrentFlade = function(callback){
models.Flade.findOne({}).then(function(flade){
callback && callback(flade);
})
};
module.exports = FladeService;
| JavaScript | 0 | @@ -1882,32 +1882,44 @@
r, flade)%7B%0A
+ callback &&
callback(flade)
|
7d1fb96cd6ebb0f61325fb50501fe72ffb49c6da | Change utility item title. | views/navigation/utility.js | views/navigation/utility.js | import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import count from '/views/accounts/notifications';
import Canvas from '/views/canvas/canvas';
import Toast from '/views/components/toasts';
import './utility.html';
// Populate Profile tab under Account Overview
const utilityNavigationHelpers = {
// Notifications
items: [{
// Readable Title
title: '<span class="mobile">Notifications</span>',
// Icon class to be applied (see icons.less)
icon: 'bell',
// default is false. Will place the icon :after instead of :before
// iconAfter: true,
// Sets Link type. (Accepts: sidebar, external, null) *Required
type: 'sidebar',
// which sidebar to activate. *required if type=sidebar (Should be same as sidebars.item.id).
sidebar: 'notifications',
// default is left (accepts: 'left', 'right')
// position: 'right',
// Set If item should only be active when logged in/out (accepts: 'active','inactive')
user: 'active',
// Set to true to add notification element
alerts: true,
// *required if type=external
// url: 'wcasa.org',
// If list item has additional elements within. Get the template
// more: 'getHelp'
}, {
// Accounts
icon: 'caret-right',
iconAfter: true,
type: 'sidebar',
sidebar: 'account',
user: 'active',
}, {
// Sign In
title: 'Sign In',
icon: 'caret-right',
iconAfter: true,
type: 'sidebar',
sidebar: 'sign-in',
user: 'inactive',
}, {
// Register
title: 'Create an Account',
icon: 'caret-right',
iconAfter: true,
type: 'sidebar',
sidebar: 'register',
user: 'inactive',
}, {
// Sign Out
title: 'Sign Out',
icon: 'caret-right',
iconAfter: true,
type: 'null',
user: 'active',
action: 'signout',
}, {
// Language
title: 'Obtener Ayuda',
sidebar: 'espanol',
type: 'sidebar',
icon: 'flag',
position: 'right',
user: 'public',
classes: 'transparent',
}, {
// Get Help
title: 'Get Help',
type: 'link',
url: '/service-providers',
icon: 'important',
position: 'right',
more: 'help',
user: 'public',
}, {
// Donate
title: 'Donate',
icon: 'heart',
type: 'sidebar',
sidebar: 'donate',
position: 'right',
user: 'public',
}, {
// Resource Center
title: 'Resource Center',
icon: 'institution',
type: 'sidebar',
sidebar: 'resource-center',
position: 'right',
user: 'public',
}, {
// News
title: 'News',
icon: 'news',
type: 'sidebar',
sidebar: 'news',
position: 'right',
user: 'public',
}, {
// Twitter
title: 'Twitter',
icon: 'twitter',
type: 'sidebar',
sidebar: 'twitter',
position: 'right',
user: 'public',
}, {
// TODO(eoghanTadhg, michickenburger): need to create a function to open
// sidebars not requiring a click of said button Payments (Not displayed)
title: 'Payments',
icon: 'ticket',
type: 'sidebar',
sidebar: 'payments',
position: 'right',
user: 'public',
}, {
title: 'Privacy Policy',
icon: 'eye',
type: 'sidebar',
sidebar: 'legal-privacy-policy',
position: 'right',
user: 'public',
}, {
// Youtube
title: '<span class="mobile">Youtube</span>',
icon: 'youtube',
type: 'link',
url: 'https://www.youtube.com/user/WCASAVPCC',
position: 'right',
target: '_blank',
user: 'public',
}, {
// Facebook
title: '<span class="mobile">Facebook</span>',
icon: 'facebook',
type: 'link',
url: 'https://www.facebook.com/wcasa',
position: 'right',
target: '_blank',
user: 'public',
}],
};
Template.utilityItem.helpers({
name: () => {
const user = Meteor.user();
if (user && user.profile) return `${user.profile.firstname} ${user.profile.lastname}`;
return '';
},
// Show notifications on bell icon
show: () => {
if (Meteor.user()) return true;
return false;
},
// Show notification count
count: () => count.get(),
});
Template.utility.helpers(utilityNavigationHelpers);
// Handle sign out
Template.utilityItem.events({
'click [data-action="signout"]'(event) {
event.preventDefault();
Meteor.logout();
Canvas.closeSidebars();
Toast({ text: 'You are no longer signed in.', classes: 'neg' });
},
});
export default utilityNavigationHelpers;
| JavaScript | 0 | @@ -1880,21 +1880,15 @@
e: '
-Obtener Ayuda
+Espa%C3%B1ol
',%0A
|
d214147a161d2e82feff53f7173ed4f1ec9be54a | Add remote open | www/bridge.open.js | www/bridge.open.js | /**
* @title Open - cordova.plugins.bridge.open
* @overview Open documents with compatible apps.
* @copyright © 2014 cordova-bridge
* @license GPLv2
* @author Carlos Antonio
*/
var exec = require('cordova/exec');
/**
* open
*
* @param {String} args File URI
* @param {Function} success Success callback
* @param {Function} error Failure callback
*/
exports.open = function(uri, success, error) {
if (!uri || arguments.length === 0) return false;
function onSuccess(path) {
if (typeof success === 'function') success(path);
return path;
}
function onError(code) {
code = code || 0;
if (typeof error === 'function') error(code);
return code;
}
uri = encodeURI(uri);
exec(onSuccess, onError, 'Open', 'open', [uri]);
};
| JavaScript | 0.000001 | @@ -706,16 +706,589 @@
(uri);%0A%0A
+ function onDeviceReady() %7B%0A var dir = (cordova.file.tempDirectory) ? 'tempDirectory' : 'externalCacheDirectory',%0A ft = new FileTransfer(),%0A filename = uri.substring(uri.lastIndexOf('/') + 1),%0A path = cordova.file%5Bdir%5D + filename;%0A%0A ft.download(uri, path,%0A function done(entry) %7B%0A var file = entry.toURL();%0A exec(onSuccess, onError, 'Open', 'open', %5Bfile%5D);%0A %7D,%0A onError,%0A false%0A );%0A %7D%0A%0A if (uri.match('http')) %7B%0A document.addEventListener('deviceready', onDeviceReady, false);%0A %7D else %7B%0A
exec(o
@@ -1330,11 +1330,15 @@
%5Buri%5D);%0A
+ %7D%0A
%7D;%0A
|
7cfc3267f99a82f00a51e8ea5adf2f274cac271e | Fix first empty line ignore string | PurePO2JSON.js | PurePO2JSON.js | /*
* PurePO2JSON v2.0.1
* by André Zanghelini (An_dz)
*
* with previous contributions by Roland Reck (QuHno)
*/
function specialChars(match, linefeed, special) {
"use strict";
// get rid of new lines
if (linefeed === "n") {
return "_10_";
}
if (linefeed === "r") {
return "_13_";
}
// convert special chars to their code
if (special !== undefined) {
return "_" + match.charCodeAt(0) + "_";
}
}
function purePO2JSON(file, minify) {
"use strict";
// Check line feed
var lf = file.match(/(\r\n)|(\n)|(\r)/);
lf = lf[1] || lf[2] || lf[3];
file = file.split(lf);
var space = " ";
var tab = "\t";
if (minify === true) {
lf = "";
space = "";
tab = "";
}
var msgid = false;
var msgstr = false;
var msgctxt = "";
var newFile = ["{"];
var msg;
var ignoreline = null;
file.forEach(function choose(line) {
// if the line has any text and does not begin with '#' (comment)
if (line.length > 0 && line.charCodeAt(0) !== 35) {
/* RegExp IDs and their meanings:
0: msg*
1: anything after msg
2: msgid
3: msgid_plural
4: msgstr
5: msgstr[]
6: number in msgstr[#]
7: msgctxt
8: the text
*/
msg = line.match(/msg((id)(_plural)?|(str)(\[(\d)\])?|(ctxt))\s"(.*)"$/);
// First msgid found, start ignoring all lines
if (ignoreline === null && msg[2] !== undefined) {
ignoreline = true;
return;
}
// Ignore all lines while msg* is not match
if (ignoreline === true && (msg === null || msg[4])) {
return;
}
ignoreline = false;
// Just append strings to either msgid or msgstr
if (msg === null) {
msg = line.substring(1, line.length - 1);
if (msgid !== false) {
msgid += msg;
} else {
msgstr += msg;
}
return;
}
// msgid_plural
if (msg[3]) {
return;
}
// msgstr[*]
else if (msg[6]) {
if (msg[8].length < 1) {
msgstr = false;
return;
}
if (msg[6] === "0") {
// commit msgid
if (msgctxt.length > 0) {
// context and id are separated by _4_
msgctxt = msgctxt.replace(/\\(n|r)|([^a-z0-9])/g, specialChars) + "_4_";
}
// We change the special characters
msgid = msgid.replace(/\\(n|r)|([^a-z0-9])/g, specialChars);
msgctxt = msgctxt + msgid;
}
line = "\"" + msgctxt + msg[6] + "\":" + space + "{";
if (msg[6] !== "0") {
line = tab + "\"message\":" + space + "\"" + msgstr.replace(/\\n/g, "\n") + "\"" + lf + "}," + lf + line;
}
msgstr = msg[8];
}
// msgstr
else if (msg[4]) {
if (msg[8].length < 1) {
msgstr = false;
return;
}
// commit msgid
if (msgctxt.length > 0) {
// context and id are separated by _4_
msgctxt = msgctxt.replace(/\\(n|r)|([^a-z0-9])/g, specialChars) + "_4_";
}
// We change the special characters
msgid = msgid.replace(/\\(n|r)|([^a-z0-9])/g, specialChars);
msgctxt = msgctxt + msgid;
line = "\"" + msgctxt + "0\":" + space + "{";
msgstr = msg[8];
msgid = false;
msgctxt = "";
}
// msgid
else if (msg[2]) {
msgid = msg[8];
if (msgstr) {
// commit msgstr
// Convert literal \n to real line breaks in msgstr
line = tab + "\"message\":" + space + "\"" + msgstr.replace(/\\n/g, "\n") + "\"" + lf + "},";
msgstr = false;
msgctxt = "";
} else {
return;
}
}
// msgctxt
else if (msg[7]) {
msgctxt = msg[8];
// In case it's the first one
if (msgstr) {
// commit msgstr
// Convert literal \n to real line breaks in msgstr
line = tab + "\"message\":" + space + "\"" + msgstr.replace(/\\n/g, "\n") + "\"" + lf + "},";
msgstr = false;
} else {
return;
}
}
// add line to file
newFile.push(line);
}
});
// The last one is not commited
if (msgstr) {
newFile.push(tab + "\"message\":" + space + "\"" + msgstr.replace(/\\n/g, "\n") + "\"" + lf + "}");
} else {
var l = newFile.length - 1;
newFile[l] = newFile[l].substr(0, newFile[l].length - 1);
}
newFile.push("}");
console.log("All done, just copy the content of the page now. ;D");
// Join all lines again with the original line feed
return newFile.join(lf);
}
| JavaScript | 0.997871 | @@ -16,17 +16,17 @@
ON v2.0.
-1
+4
%0A * by A
@@ -902,16 +902,39 @@
= null;
+%0A var empty = false;
%0A%0A fi
@@ -1969,24 +1969,55 @@
=== null) %7B%0A
+ empty = false;%0A
@@ -2466,50 +2466,20 @@
-msgstr = false;%0A return
+empty = true
;%0A
@@ -3420,50 +3420,20 @@
-msgstr = false;%0A return
+empty = true
;%0A
@@ -4139,35 +4139,259 @@
if (msgstr
-) %7B
+ !== false) %7B%0A if (empty === true) %7B%0A newFile.pop();%0A msgstr = false;%0A empty = false;%0A return;%0A %7D
%0A
@@ -4906,35 +4906,259 @@
if (msgstr
-) %7B
+ !== false) %7B%0A if (empty === true) %7B%0A newFile.pop();%0A msgstr = false;%0A empty = false;%0A return;%0A %7D
%0A
@@ -5893,11 +5893,12 @@
ole.
-log
+info
(%22Al
|
a39f7888a4f0caf483c52c11a7ada944dc8c5e46 | fix callback bug | www/js/app/main.js | www/js/app/main.js | // global application setting
var jQT = new $.jQTouch({
icon:'img/jqtouch.png',
addGlossToIcon:false,
startupScreen:'img/jqt_startup.png',
statusBar:'black'
});
$(function() {
// video plugin definition
var vp;
// Step 1: initialize plugins
$(document).bind("deviceready", function() {
vp = window.plugins.videoPlayer;
});
// Step 2: prepare callback function for videoplugin
var videoplayerCallBack = function(param) { // callback function should be: pluginname + CallBack
if (param == 'finish') {
$('#status').html("finish playing");
navigator.notification.alert("finish");
}
};
var helper = {
// Step 3: utility wrap function used by this page
// play video helper function
play:function(movie, portrait) {
vp.show(movie, portrait);
},
// info helper function
info:function() {
var data = {
getInfo:function() {
return "eiffel qiu"
}
};
$("#info").html("").append($("#info-template").tmpl(data));
}
};
// Step 4: application logic
var app = $.sammy(function() {
this.use(Sammy.Tmpl);
this.get('#/info', function() {
helper.info();
});
this.get('#/play1', function() {
helper.play('movie.mp4', 'YES'); // 'YES' for portrait video
});
this.get('#/play2', function() {
helper.play('http://easyhtml5video.com/images/happyfit2.mp4', 'NO'); // 'NO' for landscape video
});
});
$(function() {
app.run('#/');
});
}); | JavaScript | 0.000001 | @@ -175,28 +175,9 @@
);%0A%0A
-$(function() %7B%0A%0A
+%0A
// v
@@ -199,20 +199,16 @@
inition%0A
-
var vp;%0A
@@ -208,20 +208,16 @@
ar vp;%0A%0A
-
// Step
@@ -239,20 +239,16 @@
plugins%0A
-
$(docume
@@ -288,20 +288,16 @@
) %7B%0A
-
-
vp = win
@@ -321,29 +321,21 @@
Player;%0A
-
%7D);%0A%0A
-
// Step
@@ -379,20 +379,16 @@
oplugin%0A
-
var vide
@@ -481,20 +481,16 @@
ack%0A
-
-
if (para
@@ -502,28 +502,24 @@
'finish') %7B%0A
-
$('#
@@ -559,20 +559,16 @@
-
-
navigato
@@ -599,38 +599,26 @@
nish%22);%0A
-
%7D%0A
- %7D;%0A%0A
+%7D;%0A%0A
var help
@@ -620,28 +620,24 @@
helper = %7B%0A
-
// Step
@@ -680,20 +680,16 @@
s page%0A%0A
-
// p
@@ -718,20 +718,16 @@
ion%0A
-
-
play:fun
@@ -747,28 +747,24 @@
portrait) %7B%0A
-
vp.s
@@ -793,20 +793,12 @@
- %7D,%0A%0A
+%7D,%0A%0A
@@ -821,20 +821,16 @@
unction%0A
-
info
@@ -851,20 +851,16 @@
-
var data
@@ -864,20 +864,16 @@
ata = %7B%0A
-
@@ -913,20 +913,16 @@
-
return %22
@@ -949,25 +949,18 @@
-
- %7D%0A
+%7D%0A
%7D;%0A
@@ -959,16 +959,11 @@
-
%7D;%0A
-
@@ -1034,26 +1034,14 @@
-
- %7D%0A %7D;%0A%0A
+%7D%0A%7D;%0A%0A
// S
@@ -1065,20 +1065,16 @@
n logic%0A
-
var app
@@ -1092,28 +1092,24 @@
unction() %7B%0A
-
this.use
@@ -1119,28 +1119,24 @@
mmy.Tmpl);%0A%0A
-
this.get
@@ -1163,28 +1163,24 @@
) %7B%0A
-
-
helper.info(
@@ -1182,20 +1182,16 @@
info();%0A
-
%7D);%0A
@@ -1183,36 +1183,32 @@
nfo();%0A %7D);%0A%0A
-
this.get('#/
@@ -1228,36 +1228,32 @@
ion() %7B%0A
-
-
helper.play('mov
@@ -1293,28 +1293,24 @@
trait video%0A
-
%7D);%0A%0A
@@ -1306,20 +1306,16 @@
%7D);%0A%0A
-
this
@@ -1347,28 +1347,24 @@
) %7B%0A
-
-
helper.play(
@@ -1456,29 +1456,17 @@
- %7D);%0A
+%7D);%0A
%7D);%0A%0A
-
$(fu
@@ -1472,28 +1472,24 @@
unction() %7B%0A
-
app.run(
@@ -1499,16 +1499,9 @@
');%0A
-
%7D);%0A%0A
-%7D);
|
08879fcbdce4651f0d93a49a3cbea9bd42264e45 | split bindSelectorChanged | js/tinymce/themes/inlight/src/main/js/tinymce/inlight/ui/Toolbar.js | js/tinymce/themes/inlight/src/main/js/tinymce/inlight/ui/Toolbar.js | /**
* Toolbar.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
define('tinymce/inlight/ui/Toolbar', [
'global!tinymce.util.Tools',
'global!tinymce.ui.Factory'
], function (Tools, Factory) {
var setActiveItem = function (item, name) {
return function(state, args) {
var nodeName, i = args.parents.length;
while (i--) {
nodeName = args.parents[i].nodeName;
if (nodeName == 'OL' || nodeName == 'UL') {
break;
}
}
item.active(state && nodeName == name);
};
};
var bindSelectorChanged = function (editor, itemName, item) {
return function () {
var selection = editor.selection;
if (itemName == 'bullist') {
selection.selectorChanged('ul > li', setActiveItem(item, 'UL'));
}
if (itemName == 'numlist') {
selection.selectorChanged('ol > li', setActiveItem(item, 'OL'));
}
if (item.settings.stateSelector) {
selection.selectorChanged(item.settings.stateSelector, function(state) {
item.active(state);
}, true);
}
if (item.settings.disabledStateSelector) {
selection.selectorChanged(item.settings.disabledStateSelector, function(state) {
item.disabled(state);
});
}
};
};
var create = function (editor, name, items) {
var toolbarItems = [], buttonGroup;
if (!items) {
return;
}
Tools.each(items.split(/[ ,]/), function(item) {
var itemName;
if (item == '|') {
buttonGroup = null;
} else {
if (Factory.has(item)) {
item = {type: item};
toolbarItems.push(item);
buttonGroup = null;
} else {
if (!buttonGroup) {
buttonGroup = {type: 'buttongroup', items: []};
toolbarItems.push(buttonGroup);
}
if (editor.buttons[item]) {
itemName = item;
item = editor.buttons[itemName];
if (typeof item == 'function') {
item = item();
}
item.type = item.type || 'button';
item = Factory.create(item);
item.on('postRender', bindSelectorChanged(editor, itemName, item));
buttonGroup.items.push(item);
}
}
}
});
return Factory.create({
type: 'toolbar',
layout: 'flow',
name: name,
items: toolbarItems
});
};
return {
create: create
};
});
| JavaScript | 0 | @@ -647,28 +647,27 @@
;%0A%0A%09var
-bind
+get
Selector
Changed
@@ -658,23 +658,27 @@
Selector
-Changed
+StateResult
= funct
@@ -682,24 +682,16 @@
nction (
-editor,
itemName
@@ -706,68 +706,264 @@
%7B%0A%09%09
-return function () %7B%0A%09%09%09var selection = editor.selection;%0A%0A%09
+var result = function (selector, handler) %7B%0A%09%09%09return %7B%0A%09%09%09%09selector: selector,%0A%09%09%09%09handler: handler%0A%09%09%09%7D;%0A%09%09%7D;%0A%0A%09%09var activeHandler = function(state) %7B%0A%09%09%09item.active(state);%0A%09%09%7D;%0A%0A%09%09var disabledHandler = function (state) %7B%0A%09%09%09item.disabled(state);%0A%09%09%7D;%0A%0A
%09%09if
@@ -996,34 +996,21 @@
%0A%09%09%09
-%09selection.selectorChanged
+return result
('ul
@@ -1039,37 +1039,35 @@
item, 'UL'));%0A%09%09
-%09
%7D%0A%0A
-%09
%09%09if (itemName =
@@ -1088,34 +1088,21 @@
%0A%09%09%09
-%09
-selection.selectorChanged
+return result
('ol
@@ -1135,29 +1135,27 @@
, 'OL'));%0A%09%09
-%09
%7D%0A%0A
-%09
%09%09if (item.s
@@ -1186,34 +1186,21 @@
%0A%09%09%09
-%09selection.selectorChanged
+return result
(ite
@@ -1229,72 +1229,29 @@
or,
-function(state) %7B%0A%09%09%09%09%09item.active(state);%0A%09%09%09%09%7D, true
+activeHandler
);%0A%09%09
-%09
%7D%0A%0A
-%09
%09%09if
@@ -1298,34 +1298,21 @@
%0A%09%09%09
-%09selection.selectorChanged
+return result
(ite
@@ -1349,58 +1349,287 @@
or,
-function(sta
+disabledHandler);%0A%09%09%7D%0A%0A%09%09return null;%0A%09%7D;%0A%0A%09var bindSelectorChanged = function (editor, itemName, i
te
+m
) %7B%0A%09%09
-%09%09%09item.disabled(sta
+return function () %7B%0A%09%09%09var result = getSelectorStateResult(itemName, i
te
+m
);%0A%09%09%09
-%09%7D
+if (result !== null) %7B%0A%09%09%09%09editor.selection.selectorChanged(result.selector, result.handler
);%0A%09
|
e1b08390d047482a5dda2ed37f3f215cb6d5df74 | remove double '/' from url | healthCheckService.js | healthCheckService.js | /* jslint node: true, esnext: true */
"use strict";
const path = require('path'),
service = require('kronos-service'),
route = require('koa-route');
module.exports.registerWithManager = function (manager) {
const adminService = manager.serviceDeclare('koa', {
name: 'health-check',
autostart: true,
get path() {
return "/health";
},
get url() {
return `http://localhost:${this.port}/${this.path}`;
}
});
adminService.koa.use(route.get(adminService.path, ctx => {
// TODO always ok ?
ctx.body = "OK";
}));
};
| JavaScript | 0.000596 | @@ -212,21 +212,27 @@
%0A%09const
-admin
+healthCheck
Service
@@ -308,16 +308,29 @@
: true,%0A
+%09%09port: 9856,
%0A%09%09get p
@@ -418,17 +418,16 @@
is.port%7D
-/
$%7Bthis.p
@@ -444,21 +444,90 @@
%0A%09%7D);%0A%0A%09
-admin
+healthCheckService.info(%7B%0A%09%09url: healthCheckService.url%0A%09%7D);%0A%0A%09healthCheck
Service.
@@ -548,13 +548,19 @@
get(
-admin
+healthCheck
Serv
|
74f59fd5b0f4c02aee74a12fc3976a98dbfb38c2 | Fix comment hiding and unhiding | kuulemma/static/app/components/comment-list/comment-list-service.js | kuulemma/static/app/components/comment-list/comment-list-service.js | /* Kuulemma
* Copyright (C) 2014, Fast Monkeys Oy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
angular.module('kuulemmaApp')
.factory('CommentListService', function ($http) {
function get(params) {
return $http.get('/hearings/' + params.hearingId + '/links/comments', {
params: {
order_by: params.orderBy || 'created_at',
page: params.page || 1,
per_page: params.perPage || 20
}
});
}
function getUserLikes(userId) {
return $http.get('/users/' + userId + '/links/likes');
}
function like(params) {
return $http.post('/users/' + params.userId + '/links/likes', { comment_id: params.commentId });
}
function unlike(params) {
return $http.delete('/users/' + params.userId + '/links/likes', {
data: {
comment_id: params.commentId
}
});
}
function hideComment(params) {
var forcedParams = _.extend(params, {is_hidden: true});
return editComment(forcedParams);
}
function unhideComment(params) {
var forcedParams = _.extend(params, {is_hidden: false});
return editComment(forcedParams);
}
function editComment(params) {
return $http.put('/hearings/' + params.hearingId + '/links/comments/' + params.comment.id, {
is_hidden: params.comment.is_hidden,
body: params.comment.body,
title: params.comment.title,
username: params.comment.username
});
}
return {
get: get,
like: like,
unlike: unlike,
getUserLikes: getUserLikes,
hideComment: hideComment,
unhideComment: unhideComment,
editComment: editComment
};
});
| JavaScript | 0.000001 | @@ -1589,32 +1589,63 @@
extend(params, %7B
+%7D);%0A forcedParams.comment.
is_hidden: true%7D
@@ -1641,16 +1641,15 @@
dden
-:
+ =
true
-%7D)
;%0A
@@ -1773,16 +1773,47 @@
arams, %7B
+%7D);%0A forcedParams.comment.
is_hidde
@@ -1817,17 +1817,16 @@
dden
-:
+ =
false
-%7D)
;%0A
|
32f0ca15bdf38608874b67b1c4929e6cf8e08e16 | Remove pat-packery and add pat-masonry to patterns config. | src/patterns.js | src/patterns.js | /* Patterns bundle configuration.
*
* This file is used to tell r.js which Patterns to load when it generates a
* bundle. This is only used when generating a full Patterns bundle, or when
* you want a simple way to include all patterns in your own project. If you
* only want to use selected patterns you will need to pull in the patterns
* directly in your RequireJS configuration.
*/
define([
"pat-registry", // Keep separate as first argument to callback
// "modernizr", // replaced that by an inline reference to load it for speed
"pat-ajax",
"pat-autofocus",
"pat-autoscale",
"pat-autosubmit",
"pat-autosuggest",
"pat-breadcrumbs",
"pat-bumper",
"pat-calendar",
"pat-carousel",
"pat-checkedflag",
"pat-checklist",
"pat-chosen",
"pat-collapsible",
"pat-depends",
"pat-depends_parse",
"pat-dependshandler",
"pat-equaliser",
"pat-expandable",
"pat-focus",
"pat-formstate",
"pat-forward",
"pat-gallery",
"pat-htmlparser",
"pat-image-crop",
"pat-inject",
"pat-input-change-events",
"pat-legend",
"pat-markdown",
// "pat-masonry",
"pat-menu",
"pat-modal",
"pat-navigation",
"pat-notification",
"pat-parser",
"pat-packery",
"pat-placeholder",
"pat-skeleton",
"pat-sortable",
"pat-polyfill-date",
"pat-resourcepolling",
"pat-stacks",
"pat-store",
"pat-subform",
"pat-switch",
"pat-toggle",
"pat-tooltip",
"pat-content-mirror",
"pat-upload",
"pat-url",
"pat-validate",
"pat-zoom"
], function(registry) {
window.patterns = registry;
// workaround this MSIE bug :
// https://dev.plone.org/plone/ticket/10894
if ($.browser.msie) {
$("#settings").remove();
}
window.Browser = {};
window.Browser.onUploadComplete = function () {};
registry.init();
return registry;
});
| JavaScript | 0 | @@ -1132,18 +1132,16 @@
kdown%22,%0A
-//
%22pat
@@ -1252,27 +1252,8 @@
r%22,%0A
- %22pat-packery%22,%0A
|
706acfa8edae5b75c88a54d026ebec028ef7e82c | update check | app/javascript/components/widgets/widgets/forest-change/fao-reforest/actions.js | app/javascript/components/widgets/widgets/forest-change/fao-reforest/actions.js | import { getFAOExtent } from 'services/forest-data';
export const getData = ({ params, dispatch, setWidgetData, widget, state }) => {
getFAOExtent({ ...params })
.then(response => {
const data = response.data.rows;
const hasCountryData =
(data.length &&
data.find(d => d.iso === state().location.payload.country)) ||
null;
dispatch(
setWidgetData({
data: hasCountryData || params.type === 'global' ? data : {},
widget
})
);
})
.catch(error => {
dispatch(setWidgetData({ widget, error: true }));
console.info(error);
});
};
export default {
getData
};
| JavaScript | 0 | @@ -116,15 +116,8 @@
dget
-, state
%7D)
@@ -242,24 +242,16 @@
ryData =
-%0A
(data.l
@@ -258,26 +258,16 @@
ength &&
-%0A
data.fi
@@ -283,58 +283,13 @@
.iso
- === state().location.payload.country)) %7C%7C%0A
+)) %7C%7C
nul
@@ -366,47 +366,19 @@
ata
-%7C%7C params.type === 'global' ? data : %7B%7D
+? %7B%7D : data
,%0A
|
17b0495b1f398a65a290a49846d7afa4a414e353 | Add CRA preset to MDX template | lib/cli/generators/REACT_SCRIPTS/template-mdx/.storybook/presets.js | lib/cli/generators/REACT_SCRIPTS/template-mdx/.storybook/presets.js | module.exports = [
{
name: '@storybook/addon-docs/react/preset',
options: {
configureJSX: true,
},
},
];
| JavaScript | 0 | @@ -12,16 +12,56 @@
rts = %5B%0A
+ '@storybook/preset-create-react-app',%0A
%7B%0A
|
e6e4c1603ad952158e66f408631d40cc3a3d4acc | Add jQuery-QueryBuilder sortable plugin | doorman/static/js/plugins.js | doorman/static/js/plugins.js | // place any jQuery/helper plugins in here, instead of separate, slower script files.
$(function() {
$(".tagsinput").tagsinput({
tagClass: "label label-default",
trimValue: true
});
$('.tagsinput').on('itemAdded', function(event) {
var data = JSON.stringify([]);
if ($(this).val() != null)
data = JSON.stringify($(this).val());
$.ajax({
url: $(this).data('uri'),
contentType: "application/json",
data: data,
dataType: "json",
type: "POST"
}).done(function (data, textStatus, jqXHR) {
console.log(jqXHR.status);
})
});
$('.tagsinput').on('itemRemoved', function(event) {
var data = JSON.stringify([]);
if ($(this).val() != null)
data = JSON.stringify($(this).val());
$.ajax({
url: $(this).data('uri'),
contentType: "application/json",
data: data,
dataType: "json",
type: "POST"
}).done(function (data, textStatus, jqXHR) {
console.log(jqXHR.status);
})
});
$('.glyphicon-trash').on('click', function(event) {
var tr = $(this).parents('tr');
$.ajax({
url: $(this).data('uri'),
contentType: "application/json",
type: "DELETE"
}).done(function (data, textStatus, jqXHR) {
$(tr).remove();
console.log(jqXHR.status);
})
})
$('body').scrollspy({
target: '.bs-docs-sidebar',
offset: 70
})
$('#sidebar').affix({
offset: {
top: 0
}
})
// --------------------------------------------------------------------------------
var $queryBuilder = $('#query-builder');
if ($queryBuilder.length) {
var QueryBuilder = $.fn.queryBuilder.constructor;
var SUPPORTED_OPERATOR_NAMES = [
'equal',
'not_equal',
'begins_with',
'not_begins_with',
'contains',
'not_contains',
'ends_with',
'not_ends_with',
'is_empty',
'is_not_empty',
'less',
'less_or_equal',
'greater',
'greater_or_equal',
];
var SUPPORTED_OPERATORS = SUPPORTED_OPERATOR_NAMES.map(function (operator) {
return QueryBuilder.OPERATORS[operator];
});
var COLUMN_OPERATORS = SUPPORTED_OPERATOR_NAMES.map(function (operator) {
return {
type: 'column_' + operator,
nb_inputs: QueryBuilder.OPERATORS[operator].nb_inputs + 1,
multiple: true,
apply_to: ['string'], // Currently, all column operators are strings
};
});
var SUPPORTED_COLUMN_OPERATORS = SUPPORTED_OPERATOR_NAMES.map(function (operator) {
return 'column_' + operator;
});
// Copy existing names
var CUSTOM_LANG = {};
SUPPORTED_OPERATOR_NAMES.forEach(function (op) {
CUSTOM_LANG['column_' + op] = QueryBuilder.regional.en.operators[op];
});
// Get existing rules, if any.
var existingRules;
try {
var v = $('#rules-hidden').val();
if (v) {
existingRules = JSON.parse(v);
}
} catch (e) {
// Do nothing.
}
$queryBuilder.queryBuilder({
filters: [
{
id: 'query_name',
type: 'string',
label: 'Query Name',
operators: SUPPORTED_OPERATOR_NAMES,
},
{
id: 'action',
type: 'string',
label: 'Action',
operators: SUPPORTED_OPERATOR_NAMES,
},
{
id: 'host_identifier',
type: 'string',
label: 'Host Identifier',
operators: SUPPORTED_OPERATOR_NAMES,
},
{
id: 'timestamp',
type: 'integer',
label: 'Timestamp',
operators: SUPPORTED_OPERATOR_NAMES,
},
{
id: 'column',
type: 'string',
label: 'Column',
operators: SUPPORTED_COLUMN_OPERATORS,
placeholder: 'value',
},
],
operators: SUPPORTED_OPERATORS.concat(COLUMN_OPERATORS),
lang: {
operators: CUSTOM_LANG,
},
plugins: {
'bt-tooltip-errors': {
delay: 100,
placement: 'bottom',
},
},
// Existing rules (if any)
rules: existingRules,
});
// Set the placeholder of the first value for all 'column_*' rules to
// 'column name'. A bit hacky, but this seems to be the only way to
// accomplish this.
$queryBuilder.on('getRuleInput.queryBuilder.filter', function (evt, rule, name) {
if (rule.operator.type.match(/^column_/) && name.match(/value_0$/)) {
var el = $(evt.value);
$(el).attr('placeholder', 'column name');;
evt.value = el[0].outerHTML;
}
});
$('#submit-button').on('click', function(e) {
var $builder = $queryBuilder;
if (!$builder) {
return true;
}
if (!$builder.queryBuilder('validate')) {
e.preventDefault();
return false;
}
var rules = JSON.stringify($builder.queryBuilder('getRules'));
$('#rules-hidden').val(rules);
return true;
});
}
})
| JavaScript | 0 | @@ -4937,32 +4937,135 @@
%7D,%0A
+ 'sortable': %7B%0A icon: 'glyphicon glyphicon-move',%0A %7D,%0A
%7D,%0A%0A
|
eb1cde6a9ec2170b4420e8d3b8d3b0688b1aa3f1 | Use default padding parameter | lib/themes/dosomething/paraneue_dosomething/js/takeover/Takeover.js | lib/themes/dosomething/paraneue_dosomething/js/takeover/Takeover.js | import Validation from 'dosomething-validation';
import setting from '../utilities/Setting';
const $ = require('jquery');
const template = require('lodash/string/template');
class Takeover {
constructor($takeoverContainer, tpl) {
this.$el = $takeoverContainer;
this.template = tpl;
this.baseUrl = window.location.origin;
this.spinner = '<div class="spinner"></div>';
this.activeClass = 'is-active';
const data = {
'shareLink': Drupal.settings.dosomethingUser.shareLink,
'shareButtonMarkup': Drupal.settings.dosomethingUser.shareButtonMarkup,
}
this.addTemplate($takeoverContainer, this.template, data);
}
/*
* Stores all the screens in an array based on the indexes in template. Store the first/last screen.
*/
screenInit($screens) {
this.screenIndexes = this.setScreenIndexes();
this.firstScreen = this.screens.first();
this.lastScreen = this.screens.last();
}
/*
* Store the indexes of each of the screens provided in the template.
*/
setScreenIndexes() {
let indexes = [];
this.screens.each((key, scr) => indexes.push($(scr).data('index')));
return indexes;
}
/**
* Handles makeing a new scren active based on the direction passed.
*
* @param {string} direction
*/
changeScreens(direction) {
// Check if an allowed direction was passed in.
if ($.inArray(direction, ['next', 'previous']) === -1) {
return;
}
const $current = $(`.takeover__screen.${this.activeClass}`);
const currentIndex = $current.data('index');
const newIndex = (direction === 'next') ? currentIndex + 1 : currentIndex - 1;
// Check if the new screen exists, if so, go there, otherwise we need to loop back.
if ($.inArray(newIndex, this.screenIndexes) !== -1) {
$current.removeClass(this.activeClass);
this.$el.find(`.takeover__screen[data-index="${newIndex}"]`).addClass(this.activeClass);
} else {
if (direction === 'next') {
this.firstScreen.addClass(this.activeClass);
} else {
this.lastScreen.addClass(this.activeClass);
}
}
this.set();
}
/**
* Sends a request using the provided information in the request object that is passed in.
*
* @param {request} The object containing the details about the request i.e URL, method, data
* @return {object} Promise
*/
sendRequest(request) {
return fetch(request.url, {
method: request.method,
credentials: 'same-origin',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
})
.then(response => response.json());
}
/**
* Toggles the display of a spinner to signify a request is in the works.
*
* @param {jQuery} $element
*/
toggleSpinner($element) {
if (this.$el.find('.spinner').length) {
this.$el.find('.spinner').parent().html($element);
} else {
$element.parent().html(this.spinner);
}
}
/**
* Checks if a screen is active
*
* @param {jQuery} $element
*/
isActive($element) {
return $element.hasClass(this.activeClass);
}
/**
* Adds validation message to an element
*
* @param {jQuery} $element
* @param {string} msg
*/
showValidationMessage($element, msg) {
Validation.showValidationMessage($element, {message: msg});
}
/**
* Prepare fields for validation.
*
* @param {jQuery} $fields
*/
prepareFieldValidation($fields) {
Validation.prepareFields($fields);
}
/*
* Handles back buttons.
*/
goBack() {
const $backButton = this.$el.find('.takeover__screen .back-button');
if ($backButton.length) {
$backButton.click(e => {
e.preventDefault();
this.changeScreens('previous');
});
}
}
/*
* Load a specific screen in the modal flow.
*
* @param {jQuery} $screen
*/
loadScreen($screen) {
this.$el.find(`.takeover__screen.${this.activeClass}`).removeClass(this.activeClass);
$screen.addClass(this.activeClass);
}
/*
* Add a compiled lodash template to a container element.
*
* @param {jQuery} $container
* @param {string} tpl
* @param {object} data
*/
addTemplate($container, tpl, data) {
data = (data) ? data : {};
const markup = template(tpl);
$container.html(markup(data))
}
/*
* Resize an elemen based on the height of it's contents
*
* @param {jQuery} $container
* @param {jQuery} $referenceHeight
* @param {int} padding
*/
resizeContainerHeight($container, $referenceHeight, padding = null) {
padding = (padding === null) ? 100 : padding;
$container.height($referenceHeight.height() + 100);
}
}
export default Takeover;
| JavaScript | 0.000001 | @@ -4618,66 +4618,14 @@
g =
-null) %7B%0A padding = (padding === null) ? 100 : padding;%0A
+100) %7B
%0A
@@ -4671,19 +4671,23 @@
ght() +
-100
+padding
);%0A %7D%0A%7D
|
867922f97e85e5631bfef2b4a6ab4089f166ca00 | Implement callback function to handle user cursor drag event. | js/constructors.js | js/constructors.js | // DO WE EVEN USER THIS.FAVORITES????
function User(userData) {
this.uid = userData.id,
this.userId = userData.userId,
this.position = userData.position,
this.name = userData.name,
this.img = userData.profileImageURL,
this.marker = null,
this.currentPark = userData.currentPark,
this.skateparks = userData.skateparks
}
User.prototype.saveCurrentLocation = function() {
currentUser.marker.position = this.position;
userMarkerRef.child(currentUser.uid).set({
url: currentUser.marker.url,
uid: currentUser.uid,
position: currentUser.marker.position,
icon: currentUser.marker.icon
});
}
User.prototype.initializeGeofence = function() {
var geofence = new google.maps.Circle({
map: map,
radius: 9001,
fillColor: '#336688',
fillOpacity: .22,
strokeColor: '#D48817',
strokeWeight: 1.75
});
geofence.bindTo('center', this.marker, 'position');
this.geofence = geofence;
}
User.prototype.bindDragListener = function() {
// google.maps.event.addListener(this.marker, 'dragend', this.handleDragListener.bind(this));
google.maps.event.addListener(this.marker, 'dragend', this.saveCurrentLocation);
// google.maps.event.addListener(this.marker, 'dragend', this.populateCarousel.bind(this));
}
User.prototype.handleDragListener = function(){
this.saveCurrentLocation();
this.populateCarousel();
}
User.prototype.populateCarousel = function() {
var bounds = this.geofence.getBounds();
allSkateparks.forEach(function(park){
if(bounds.contains(park.marker.position)){
console.log(park)
}
})
}
// User.prototype.bindDragListener = function() {
// var user = this;
// google.maps.event.addListener(this.marker, 'dragend', function(){
// user.saveCurrentLocation();
//take the geofence bounds and compare it against the markers here
// var bounds = user.geofence.getBounds();
// if(bounds.contains())
// allSkateparks.forEach(function(park){
// if(bounds.contains(park.marker.position)){
// console.log('we gawt 1')
// }
// })
// });
// }
// Skateparks should load once and only once, make sure
// that this is happening
function Skatepark(serverData, options) {
this.id = serverData.id,
this.name = serverData.name,
this.address = serverData.address,
this.position = new google.maps.LatLng(serverData.lat,serverData.lon),
this.marker = new google.maps.Marker({
position: this.position,
title: this.name,
map: map,
// icon: './imgs/skatepark.png'
icon: './imgs/new-skatepark-icon.png'
}),
this.attendees = 0
}
Skatepark.prototype.buildInfoWindow = function() {
// ***** Refactor infoWindow content string
var infoWindow = new google.maps.InfoWindow({
content: '<p class="park-id" hidden>'+this.id+'</p><p class="center info-w-name">'+this.name+'</p><p class="center info-w-address">'+this.address+'</p><a class="skatepark-link center" href='+baseURL+'api/skateparks/'+this.id+'>check it</a><button class="attend center">Attend</button><p class="center center-img"><img src="https://maps.googleapis.com/maps/api/streetview?size=300x100&location='+this.position.G+','+this.position.K+'&fov=70&heading=235&pitch=0"/></p><p class="skater_count">Skaters Here: <span class="attendee-count">'+this.attendees+'</span></p>',
position: this.position
});
return infoWindow;
}
Skatepark.prototype.incrementAttendees = function() {
this.attendees++;
this.refreshAttendees();
}
Skatepark.prototype.decrementAttendees = function() {
this.attendees--;
this.refreshAttendees();
}
Skatepark.prototype.refreshAttendees = function() {
var content = $('p:contains('+this.id+')').parent().children('.skater_count').children();
content.text(this.attendees);
} | JavaScript | 0 | @@ -381,16 +381,38 @@
ion() %7B%0A
+ //this may not work%0A
curren
@@ -436,24 +436,31 @@
tion = this.
+marker.
position;%0A%0A
@@ -1012,19 +1012,16 @@
on() %7B%0A
- //
google.
@@ -1105,16 +1105,19 @@
his));%0A
+ //
google.
@@ -1485,16 +1485,42 @@
nds();%0A%0A
+ console.log('batch em')%0A
allSka
|
84b0a9626b81ab24e2a113047c14843fd71e826a | fix eslint error #511 | js/echo_newline.js | js/echo_newline.js | /**@license
* __ _____ ________ __
* / // _ /__ __ _____ ___ __ _/__ ___/__ ___ ______ __ __ __ ___ / /
* __ / // // // // // _ // _// // / / // _ // _// // // \/ // _ \/ /
* / / // // // // // ___// / / // / / // ___// / / / / // // /\ // // / /__
* \___//____ \\___//____//_/ _\_ / /_//____//_/ /_/ /_//_//_/ /_/ \__\_\___/
* \/ /____/
* http://terminal.jcubic.pl
*
* Monkey patch to add newlinew option for echo method inside jQuery Terminal
*
* Copyright (c) 2014-2019 Jakub Jankiewicz <https://jcubic.pl/me>
* Released under the MIT license
*
*/
/* global define, global, require, module */
(function(factory) {
var root = typeof window !== 'undefined' ? window : global;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
// istanbul ignore next
define(['jquery', 'jquery.terminal'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function(root, jQuery) {
if (jQuery === undefined) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if (typeof window !== 'undefined') {
jQuery = require('jquery');
} else {
jQuery = require('jquery')(root);
}
}
if (!jQuery.fn.terminal) {
if (typeof window !== 'undefined') {
require('jquery.terminal');
} else {
require('jquery.terminal')(jQuery);
}
}
factory(jQuery);
return jQuery;
};
} else {
// Browser
// istanbul ignore next
factory(root.jQuery);
}
})(function($) {
var init = $.fn.terminal;
$.fn.terminal = function(interpreter, options) {
return init.call(this, interpreter, patch_options(options)).each(function() {
patch_term($(this).data('terminal'), should_echo_command(options));
});
};
var last;
var prompt;
function should_echo_command(options) {
return options && options.echoCommand !== false || !options;
}
function patch_options(options) {
var keymap = {
'ENTER': function(e, original) {
var term = this;
if (!last) {
if (should_echo_command(options)) {
term.echo_command();
}
} else {
this.__echo(last + prompt + this.get_command());
this.set_prompt(prompt);
last = '';
}
if (options && options.keymap && options.keymap.ENTER) {
options.keymap.ENTER.call(this, e, original);
} else {
original.call(this, e);
}
}
};
var settings = {
echoCommand: false,
keymap: $.extend({}, options && options.keymap || {}, keymap)
};
return $.extend({}, options || {}, settings);
}
function patch_term(term, echo_command) {
term.__echo = term.echo;
term.__exec = term.exec;
term.exec = function() {
last = '';
if (echo_command) {
this.settings().echoCommand = true;
}
var ret = term.__exec.apply(this, arguments);
if (echo_command) {
this.settings().echoCommand = false;
}
return ret;
};
term.echo = function(arg, options) {
var settings = $.extend({
newline: true
}, options);
function process(prompt) {
// this probably can be simplify because terminal handle
// newlines in prompt
var last_line;
last += arg;
arg = last + prompt;
var arr = arg.split('\n');
if (arr.length === 1) {
last_line = arg;
} else {
term.__echo(arr.slice(0, -1).join('\n'), options);
last_line = arr[arr.length - 1];
}
term.set_prompt(last_line);
}
if (settings.newline === false) {
if (!prompt) {
prompt = term.get_prompt();
}
if (typeof prompt === 'string') {
process(prompt);
} else {
prompt(process);
}
} else {
if (prompt) {
term.set_prompt(prompt);
}
if (last) {
term.__echo(last + arg, options);
} else {
// original echo check length to test if someone call echo
// with value that is undefined
if (!arguments.length) {
term.__echo();
} else {
term.__echo(arg, options);
}
}
last = '';
prompt = '';
}
return term;
};
}
});
| JavaScript | 0.000001 | @@ -5149,35 +5149,58 @@
%7D else
+ if (!arguments.length)
%7B%0A
-
@@ -5318,57 +5318,8 @@
ned%0A
- if (!arguments.length) %7B%0A
@@ -5357,36 +5357,32 @@
-
-
%7D else %7B%0A
@@ -5366,36 +5366,32 @@
%7D else %7B%0A
-
@@ -5421,38 +5421,16 @@
tions);%0A
- %7D%0A
|
fe8c64bda0bde3f6597302238df8a8d876c69776 | Update default gebo-server address | app/scripts/controllers/main.js | app/scripts/controllers/main.js | /**
* This controller was inspired by:
* enginous/angular-oauth
* https://github.com/enginous/angular-oauth
*/
'use strict';
angular.module('geboClientApp')
.controller('MainCtrl', function ($scope, Token, $location) {
$scope.verified = false;
/**
* Configure OAuth2 for interaction with gebo-server
*/
var baseUrl = window.location.origin;
Token.setEndpoints({
// gebo: 'http://192.168.1.25:3000/dialog/authorize',
gebo: 'http://localhost:3000',
redirect: baseUrl + '/oauth2callback.html',
});
/**
* See if this client already has a token
*/
$scope.accessToken = Token.get();
if ($scope.accessToken) {
Token.verifyAsync($scope.accessToken).
then(function(data) {
$scope.agentName = data.agentName;
$scope.verified = true;
}, function() {
window.alert('You have an expired or invalid token.');
});
}
/**
* Allow gebo-client access to the gebo user's resources
*/
$scope.authenticate = function() {
var extraParams = {};//$scope.askApproval ? { approval_prompt: 'force' } : {};
Token.getTokenByPopup(extraParams)
.then(function(params) {
// Success getting token from popup.
// Verify the token before setting it, to avoid
// the confused deputy problem (uh, what's the
// confused deputy problem?)
Token.verifyAsync(params.access_token).
then(function(data) {
$scope.accessToken = params.access_token;
$scope.agentName = data.agentName;
$scope.verified = true;
Token.set(params.access_token);
}, function() {
window.alert('Cannot verify token.');
});
}, function() {
// Failure getting token from popup.
window.alert('Failed to get token from popup.');
});
};
/**
* Disallow gebo-client access to the gebo user's resources
*/
$scope.deauthenticate = function () {
delete $scope.agentName;
delete $scope.accessToken;
$scope.verified = false;
Token.clear();
$location.path('/');
};
});
| JavaScript | 0 | @@ -410,16 +410,17 @@
o: 'http
+s
://192.1
@@ -428,19 +428,19 @@
8.1.25:3
-000
+443
/dialog/
@@ -468,16 +468,17 @@
o: 'http
+s
://local
@@ -487,11 +487,11 @@
st:3
-000
+443
',%0A
|
cd42c14eb58c32c63e784795fa2b666a111da643 | Update room.js | app/scripts/controllers/room.js | app/scripts/controllers/room.js | 'use strict';
angular.module('chatterApp')
.controller('RoomCtrl', function ($scope, $rootScope, $firebaseObject, $firebaseArray, $routeParams, $mdSidenav) {
var roomRef = new Firebase("https://chatter-bzu.firebaseio.com/rooms/" + $routeParams.id);
var messagesRef = new Firebase("https://chatter-bzu.firebaseio.com/messages/" + $routeParams.id);
$scope.room = $firebaseObject(roomRef);
$scope.messages = $firebaseArray(messagesRef);
$scope.toggleMenu = function(menu) {
$mdSidenav(menu).toggle();
};
$scope.sendMessage = function (event, message) {
if (event.keyCode === 13) {
messagesRef.push({
user: $rootScope.currentUser,
message: message,
when: Firebase.ServerValue.TIMESTAMP
});
$scope.newMessage = '';
}
}
});
| JavaScript | 0.000001 | @@ -190,35 +190,31 @@
se(%22https://
-chatter-bzu
+msports
.firebaseio.
@@ -293,19 +293,15 @@
s://
-chatter-bzu
+msports
.fir
|
8d1dd565486c02f7bf75068cb140253fa1598745 | fix workspace filter to resolve internal server error | app/scripts/services/summary.js | app/scripts/services/summary.js | 'use strict';
/**
* @ngdoc service
* @name ng311.Summary
* @description
* # Summary
* Factory in ng311
* //TODO rename to reports
*/
angular
.module('ng311')
.factory('Summary', function ($http, $resource, Utils) {
var Summary = {};
/**
* @description find roles with pagination
* @param {Object} params [description]
*/
Summary.issues = function (params) {
return $http.get(Utils.asLink('summaries'), {
params: params
})
.then(function (response) {
return response.data;
});
};
/**
* @description load all api endpoint in singe request to improve
* ui responsiveness
* @param {Object} params additional params
* @return {Object}
*/
Summary.endpoints = function (params) {
return $http.get(Utils.asLink('endpoints'), {
params: params
})
.then(function (response) {
return response.data;
});
};
/**
* @description load current overview/pipeline
* @param {Object} params additional params
* @return {Object}
*/
Summary.overviews = function (params) {
return $http.get(Utils.asLink(['reports', 'overviews']), {
params: params
})
.then(function (response) {
return response.data;
});
};
/**
* @description load current standings
* @param {Object} params additional params
* @return {Object}
*/
Summary.standings = function (params) {
return $http.get(Utils.asLink(['reports', 'standings']), {
params: params
})
.then(function (response) {
return response.data;
});
};
/**
* Build params as per API filtering, sorting and paging
* @param {Object} [params] reports filters
* @return {Object}
*/
Summary.prepareQuery = function (params) {
//ensure params
params = _.merge({}, params);
//initialize query
var query = {};
//1. ensure start and end dates
//1.0 ensure start date
params.startedAt =
(params.startedAt ? moment(new Date(params.startedAt)).utc().startOf(
'date') : moment().utc().startOf('date'));
//1.1 ensure end date
params.endedAt =
(params.endedAt ? moment(new Date(params.endedAt)).utc().endOf(
'date') : moment().utc().endOf('date'));
//1.2 ensure start is less than end
var startedAt = params.startedAt;
if (params.startedAt.isAfter(params.endedAt)) {
params.startedAt = params.endedAt;
params.endedAt = startedAt;
}
//1.3 build start & end date criteria
query.createdAt = {
$gte: params.startedAt.startOf('date').toDate(),
$lte: params.endedAt.endOf('date').toDate()
};
//2. ensure jurisdictions
//2.0 normalize & compact jurisdictions
params.jurisdictions = _.uniq(_.compact([].concat(params.jurisdictions)));
//2.1 build jurisdiction criteria
if (params.jurisdictions.length >= 1) {
if (params.jurisdictions.length > 1) {
//use $in criteria
query.jurisdiction = { $in: params.jurisdictions };
} else {
//use $eq criteria
query.jurisdiction = _.first(params.jurisdictions);
}
}
//ensure service groups
//3. ensure servicegroups
//3.0 normalize & compact servicegroups
params.servicegroups = _.uniq(_.compact([].concat(params.servicegroups)));
//3.1 build group criteria
if (params.servicegroups.length >= 1) {
if (params.servicegroups.length > 1) {
//use $in criteria
query.group = { $in: params.servicegroups };
} else {
//use $eq criteria
query.group = _.first(params.servicegroups);
}
}
//ensure services
//4. ensure services
//4.0 normalize & compact services
params.services = _.uniq(_.compact([].concat(params.services)));
//4.1 build service criteria
if (params.services.length >= 1) {
if (params.services.length > 1) {
//use $in criteria
query.service = { $in: params.services };
} else {
//use $eq criteria
query.service = _.first(params.services);
}
}
//ensure statuses
//5. ensure statuses
//5.0 normalize & compact statuses
params.statuses = _.uniq(_.compact([].concat(params.statuses)));
//5.1 build status criteria
if (params.statuses.length >= 1) {
if (params.statuses.length > 1) {
//use $in criteria
query.status = { $in: params.statuses };
} else {
//use $eq criteria
query.status = _.first(params.statuses);
}
}
//ensure priorities
//6. ensure priorities
//6.0 normalize & compact priorities
params.priorities = _.uniq(_.compact([].concat(params.priorities)));
//6.1 build priority criteria
if (params.priorities.length >= 1) {
if (params.priorities.length > 1) {
//use $in criteria
query.priority = { $in: params.priorities };
} else {
//use $eq criteria
query.priority = _.first(params.priorities);
}
}
//ensure workspaces
//7. ensure workspaces
//7.0 normalize & compact workspaces
params.workspaces = _.uniq(_.compact([].concat(params.workspaces)));
//7.1 build priority criteria
if (params.workspaces.length >= 1) {
query.method = {};
if (params.workspaces.length > 1) {
//use $in criteria
query.method.workspace = { $in: params.workspaces };
} else {
//use $eq criteria
query.method.workspace = _.first(params.workspaces);
}
}
return query;
};
return Summary;
});
| JavaScript | 0 | @@ -5602,24 +5602,27 @@
1) %7B%0A
+ //
query.metho
@@ -5629,16 +5629,16 @@
d = %7B%7D;%0A
-
@@ -5709,33 +5709,34 @@
%0A query
-.
+%5B'
method.workspace
@@ -5735,16 +5735,18 @@
orkspace
+'%5D
= %7B $in
@@ -5825,25 +5825,26 @@
query
-.
+%5B'
method.works
@@ -5847,16 +5847,18 @@
orkspace
+'%5D
= _.fir
|
245061f4eee8be0a1ed0fa896be5703113116878 | resolve last pinned project is not saved due to async setState | app/src/common/app-container.js | app/src/common/app-container.js | import firstBy from 'thenby';
import { ipcRenderer } from 'electron';
import { Container } from 'unstated';
import debounce from 'lodash.debounce';
import Fuse from 'fuse.js';
import formatPath from '~/common/format-path';
import createStore from '~/common/preferences-store';
import Channels from '~/common/channels';
const FAILED_DEBOUNCE_WAIT = 250;
const DEFAULT_STATE = {
ready: false,
projects: [],
selected: null,
search: null,
failed: [],
};
// Custom sort function for unfiltered projects
const sortFn = firstBy('pinned', { direction: -1 })
.thenBy('name', { ignoreCase: true })
.thenBy('path');
// This state container keeps key info about projects
export default class AppState extends Container {
state = DEFAULT_STATE;
searchInputRef = null;
preferences = createStore();
constructor(...args) {
super(...args);
// Subscribe to main process replies
ipcRenderer.on(Channels.PROJECT_OPEN_SUCCESS, (_, payload) =>
this.proceedValidProject(payload)
);
ipcRenderer.on(Channels.PROJECT_OPEN_ERROR, (_, payload) =>
this.proceedInvalidProject(payload)
);
ipcRenderer.on(Channels.PROJECTS_LOADED, () => {
this.setState({ ready: true });
});
// Load added projects
ipcRenderer.send(Channels.PROJECTS_LOAD);
}
syncPreferences() {
this.preferences.set(
'projects',
this.state.projects.map(project => project.path)
);
this.preferences.set(
'pinned',
this.state.projects
.filter(project => project.pinned)
.map(project => project.path)
);
}
resetPreferences() {
this.preferences.clear();
this.preferences.ensureDefaults();
this.setState({ ...DEFAULT_STATE, ready: true });
}
editPreferences() {
this.preferences.openInEditor();
}
getTerminalApp() {
return this.state.terminal;
}
isReady() {
return this.state.ready;
}
hasProjects() {
return this.state.projects.length > 0;
}
getFilteredProjects() {
const { search, projects } = this.state;
return search
? new Fuse(projects, { keys: ['name', 'path'] }).search(search)
: projects.sort(sortFn);
}
refreshProjects() {
this.state.projects.forEach(project => {
ipcRenderer.send(Channels.PROJECT_OPEN_REQUEST, project.path);
});
}
setSelected(project) {
this.setState({ selected: project });
}
getSelected(code) {
return this.state.selected;
}
proceedValidProject(newProject) {
// Check if project already exist in list
const existingProject = this.state.projects.find(
p => p.path === newProject.path
);
// Replace old project with a new data, or append it if new one
const nextProjects = existingProject
? this.state.projects.map(p => (p === existingProject ? newProject : p))
: [...this.state.projects, newProject];
this.setState({ projects: nextProjects });
this.syncPreferences();
}
// Since adding projects is async, we need to make sure send notification once
notifyAboutFailedProjects = debounce(() => {
const failedCount = this.state.failed.length;
const message =
failedCount > 1
? `Failed to load ${failedCount} projects.`
: `Failed to load project. Make sure ${formatPath(
this.state.failed[0]
)} is a valid npm module.`;
const nextProjects = this.state.projects.filter(
p => !this.state.failed.includes(p.path)
);
this.setState({ failed: [], projects: nextProjects });
ipcRenderer.send(Channels.NOTIFICATION_SHOW, { body: message });
}, FAILED_DEBOUNCE_WAIT);
proceedInvalidProject(project) {
const nextFailed = [...this.state.failed, project.path];
this.setState({ failed: nextFailed });
this.notifyAboutFailedProjects();
}
setPinned(project, value) {
const nextProjects = this.state.projects.map(
p => (p === project ? { ...p, pinned: value } : p)
);
this.setState({ projects: nextProjects });
this.syncPreferences();
}
pin(project) {
this.setPinned(project, true);
}
unpin(project) {
this.setPinned(project, false);
}
removeProject(project) {
const nextProjects = this.state.projects.filter(p => p !== project);
this.setState({ projects: nextProjects });
this.syncPreferences();
}
setSearchInputRef(node) {
this.searchInputRef = node;
}
getSearch() {
return this.state.search;
}
hasSearch() {
return this.state.search !== null;
}
setSearch(keyword) {
this.setSelected(null);
this.setState({ search: keyword });
if (this.searchInputRef) {
this.searchInputRef.focus();
}
}
clearSearch() {
this.setState({ search: null });
}
fileDragEnter() {
this.setState({ entered: true });
}
fileDragLeave() {
this.setState({ entered: false });
}
fileDrop(files) {
Array.from(files).forEach(file =>
ipcRenderer.send(Channels.PROJECT_OPEN_REQUEST, file.path)
);
}
checkForUpdates() {
ipcRenderer.send(Channels.CHECK_FOR_UPDATE);
}
}
| JavaScript | 0 | @@ -346,10 +346,10 @@
T =
-2
5
+0
0;%0Ac
@@ -847,16 +847,114 @@
.args);%0A
+ // Auto sync state changes with preferences%0A this.subscribe(() =%3E this.syncPreferences());%0A
// S
@@ -2793,36 +2793,47 @@
one%0A
-const nextP
+this.setState(%7B%0A p
rojects
- =
+:
existin
@@ -2841,16 +2841,18 @@
Project%0A
+
?
@@ -2928,16 +2928,18 @@
)%0A
+
: %5B...th
@@ -2972,82 +2972,15 @@
ect%5D
-;
+,
%0A
-this.setState(%7B projects: nextProjects %7D);%0A this.syncPreferences(
+%7D
);%0A
@@ -3692,26 +3692,38 @@
-const nextF
+this.setState(%0A %7B f
ailed
- =
+:
%5B..
@@ -3759,53 +3759,14 @@
ath%5D
-;
+ %7D,
%0A
- this.setState(%7B failed: nextFailed %7D);%0A
@@ -3795,17 +3795,21 @@
Projects
-(
+%0A
);%0A %7D%0A%0A
@@ -3842,36 +3842,47 @@
) %7B%0A
-const nextP
+this.setState(%7B%0A p
rojects
- =
+:
this.st
@@ -3899,16 +3899,18 @@
ts.map(%0A
+
p
@@ -3966,83 +3966,18 @@
-);%0A this.setState(%7B projects: nextProjects %7D);%0A this.syncPreferences(
+ ),%0A %7D
);%0A
@@ -4128,36 +4128,47 @@
) %7B%0A
-const nextP
+this.setState(%7B%0A p
rojects
- =
+:
this.st
@@ -4210,82 +4210,15 @@
ect)
-;
+,
%0A
-this.setState(%7B projects: nextProjects %7D);%0A this.syncPreferences(
+%7D
);%0A
|
6a3df56adbe31a00aec82ed582af739915317b49 | Convert SimLauncher to es6 class, rename to simLauncher.js, https://github.com/phetsims/joist/issues/630 | js/griddle-main.js | js/griddle-main.js | // Copyright 2014-2020, University of Colorado Boulder
/**
* Main file for the Griddle library demo.
*/
import Screen from '../../joist/js/Screen.js';
import Sim from '../../joist/js/Sim.js';
import SimLauncher from '../../joist/js/SimLauncher.js';
import GriddleDemoScreenView from './demo/GriddleDemoScreenView.js';
import griddleStrings from './griddleStrings.js';
const griddleTitleString = griddleStrings.griddle.title;
const simOptions = {
credits: {
leadDesign: 'PhET'
}
};
SimLauncher.launch( function() {
// Create and start the sim
new Sim( griddleTitleString, [
new Screen( function() {return {};}, function() {return new GriddleDemoScreenView();}, {
name: 'Griddle Demo'
} )
], simOptions ).start();
} ); | JavaScript | 0.001867 | @@ -196,17 +196,17 @@
%0Aimport
-S
+s
imLaunch
@@ -229,17 +229,17 @@
oist/js/
-S
+s
imLaunch
@@ -489,17 +489,17 @@
%7D%0A%7D;%0A%0A
-S
+s
imLaunch
|
8adf81bdeabd36f0d4bbdaf82fa2c99817da3371 | Allow passing material to model construction | js/models/model.js | js/models/model.js | var Material = require('./material');
var math = require('../math/math');
/**
* Basic model. A model useful high-level representation
* of a transform, geometry and material which can be rendered.
* Models can be organized hierarchically (see add, remove).
*
* @param ctx the context.
* @param name the name of the model.
* @param options options.
* @constructor
*/
function Model(ctx, name, options) {
/** The name. */
this.name = name;
/** The material (see Material). */
this.material = new Material(ctx);
/**
* The parent (or null). Do not set this directly,
* use add/remove instead.
*/
this.parent = null;
/**
* The children. Do not set this directly, use add/remove instead.
*/
this.children = [];
/** The transform. */
this.transform = math.transform.create();
/** The full transform (i.e. to world coordinates). This will
* be computed and cached as needed when rendering.
*/
this.fullTransform = (function() {
return this.transform;
}).bind(this);
/** The geometry to render. This is usually a RenderGroup or
* RenderGroups, but may be anything with a .renderParts()
* function, returning an array of elements containing:
* 1) a .geometry field containing a Geometry.
* 2) a .render(ctx) function.
*/
this.renderer = null;
}
/**
* Render the model in the given context. Rendering will use the current view
* set in the context.
*
* @param ctx the context.
*/
Model.prototype.render = function(ctx) {
if (this.material.visible === Material.INVISIBLE) {
return;
}
var view = ctx.view();
var fullTransform = this.fullTransform();
for (var i = 0; i < this.children.length; i++) {
this.children[i].render(ctx);
}
if (this.material.visible === Material.ONLY_CHILDREN || this.renderer === null) {
return;
}
var uniforms = {
model: math.mat4.fromTransform(math.mat4.create(), fullTransform),
view: null,
modelView: null,
projection: null,
modelViewProjection: null
};
if (view) {
uniforms.view = math.mat4.fromTransform(math.mat4.create(), view.transform.clone().invert());
uniforms.modelView = math.mat4.mul(math.mat4.create(), uniforms.view, uniforms.model);
uniforms.projection = view.projection();
uniforms.modelViewProjection = math.mat4.mul(math.mat4.create(), uniforms.projection, uniforms.modelView);
} else {
uniforms.view = math.mat4.create();
uniforms.modelView = uniforms.model;
uniforms.projection = math.mat4.create();
uniforms.modelViewProjection = uniforms.model;
}
var p = ctx.findProgram(this.material.program);
var parts = this.renderer.renderParts();
var prevGeometry = null;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
var geometry = part.geometry;
var needsRebind = false;
if (p !== null) {
// Reconcile geometry attributes with program attributes
for (var attrname in geometry.attributes) {
var attr = geometry.attributes[attrname];
if (!(attrname in p.attributes) || p.attributes[attrname] !== attr.id) {
needsRebind = true;
break;
}
}
if (needsRebind) {
var gl = ctx.gl;
p.attributes = {};
p.uniforms = {};
for (var attrname in geometry.attributes) {
var attr = geometry.attributes[attrname];
gl.bindAttribLocation(p.program, attr.id, attrname);
p.attributes[attrname] = attr.id;
}
gl.linkProgram(p.program);
}
}
if (geometry !== prevGeometry) {
geometry.bind(ctx);
prevGeometry = geometry;
}
if (needsRebind || i === 0) {
this.material.bind(ctx, uniforms);
}
part.render(ctx);
}
if (prevGeometry !== null) {
prevGeometry.unbind(ctx);
}
}
/**
* Remove a child model.
*
* @param child the model to remove.
*/
Model.prototype.remove = function(child) {
if (child.parent === this) {
child.parent = null;
child.fullTransform = (function() {
return this.transform;
}).bind(child);
}
var i = this.children.indexOf(child);
if (i !== -1) {
this.children.splice(i, 1);
}
}
/**
* Add a child model.
*
* @param child the model to add.
*/
Model.prototype.add = function(child) {
if (child.parent === this) {
return;
}
if (child.parent !== null) {
child.parent.remove(child);
}
child.parent = this;
this.children.push(child);
child.fullTransform = math.transform.track(math.transform.create(), this, 'fullTransform', function(out, tr) {
return child.transform.preMul(tr());
});
}
module.exports = Model;
var objloader = require('./objloader');
Model.load = objloader.load;
// vi:ts=4:et
| JavaScript | 0 | @@ -446,24 +446,159 @@
me = name;%0A%0A
+ var mat;%0A%0A if (options && options.material) %7B%0A mat = options.material;%0A %7D else %7B%0A mat = new Material();%0A %7D%0A%0A
/** The
@@ -649,25 +649,11 @@
l =
-new Material(ctx)
+mat
;%0A%0A
|
33279e28aa1f06fb6ee749e13e1f9ad6274dd591 | Update the example in Tempo guide. Fixes #86 | demo/guide.tempo_progress.js | demo/guide.tempo_progress.js | // Source code licensed under Apache License 2.0.
// Copyright © 2019 William Ngan. (https://github.com/williamngan/pts)
window.demoDescription = "Progress demo in Tempo guide.";
//// Demo code starts (anonymous function wrapper is optional) ---
(function() {
Pts.quickStart( "#pt", "#e2e6ef" );
// Create tempo instance
let tempo = new Tempo(60);
let colors = ["#62E", "#FFF", "#123"];
let counter = 0;
// for every 1 beat, change the center's count
tempo.every(1).start( (count) => {
counter = count;
// console.log( count );
})
// for every 2 beat, rotate the line around once and change the color of the other circle
tempo.every( 2 ).progress( (count, t) => {
let ln = Line.fromAngle( space.center, Const.two_pi*t - Const.half_pi, space.size.y/3 );
let c = colors[ count%colors.length ];
// hand
form.strokeOnly( c, 10, "round", "round" ).line( ln );
form.fillOnly( c ).point( ln.p2, 20, "circle" );
// square
form.fillOnly( c ).point( space.center, 20 );
form.fillOnly( "#e2e6ef" ).font(20, "bold").text( space.center.$subtract(11, -8), (counter < 10 ? "0"+counter : counter) );
});
// Add tempo instance as a player to track animation
space.add( tempo );
//// ----
space.bindMouse().bindTouch().play();
})(); | JavaScript | 0 | @@ -418,150 +418,8 @@
= 0;
-%0A%0A // for every 1 beat, change the center's count%0A tempo.every(1).start( (count) =%3E %7B%0A counter = count;%0A // console.log( count );%0A %7D)
%0A %0A
@@ -816,16 +816,181 @@
cle%22 );%0A
+ %7D);%0A%0A // for every 1 beat, change the center's count and background color%0A tempo.every(1).start( (count) =%3E %7B%0A counter = count;%0A %7D).progress( (count, t) =%3E %7B
%0A //
@@ -1008,32 +1008,60 @@
form.fillOnly( c
+olors%5B count%25colors.length %5D
).point( space.
@@ -1206,17 +1206,16 @@
);%0A %7D)
-;
%0A %0A //
|
32139346630330d48743c9292f34ee16f46a757b | fix demo | demo/pages/progress/index.js | demo/pages/progress/index.js | Controller.$inject = ['$http', '$timeout', 'qgrid'];
export default function Controller($http, $timeout, qgrid) {
const ctrl = this;
ctrl.gridModel = qgrid.model();
ctrl.gridModel.progress({isBusy: true});
$timeout(() =>
$http.get('data/people/100.json')
.then(function (response) {
ctrl.gridModel.data({
rows: response.data
});
ctrl.gridModel.progress({isBusy: false});
}), 1000);
} | JavaScript | 0.000001 | @@ -166,45 +166,87 @@
;%0A%09c
-trl.gridModel.progress(%7BisBusy: true%7D
+onst service = qgrid.service(ctrl.gridModel);%0A%09const cancelBusy = service.busy(
);%0A%0A
@@ -396,46 +396,18 @@
%09%09%09c
-trl.gridModel.progress(%7BisBusy: false%7D
+ancelBusy(
);%0A%09
|
3fc5a9e300ecfc0cff035381d13a499ff9e027e3 | fix typo | src/sap.ui.core/test/sap/ui/core/qunit/odata/v4/testsuite.odatav4.qunit.js | src/sap.ui.core/test/sap/ui/core/qunit/odata/v4/testsuite.odatav4.qunit.js | sap.ui.define(function () {
"use strict";
return {
name : "TestSuite for sap.ui.core: GTP testcase CORE/ODATAV4",
defaults : {
group : "OData V4",
qunit : {
version : "edge",
reorder : false
},
sinon : {
version : "edge"
},
ui5 : {
language : "en-US",
rtl : false,
libs : null,
"xx-waitForTheme" : true
},
coverage : {
only : "[sap/ui/model/odata/v4]",
branchTracking : true
},
loader : {
paths : {
"sap/ui/core/sample" : "test-resources/sap/ui/core/demokit/sample"
}
},
autostart : true
},
tests : {
"_AnnotationHelperExpression" : {},
"AnnotationHelper" : {},
"Context" : {},
"ODataBinding" : {},
"ODataContextBinding" : {},
"ODataListBinding" : {},
"ODataMetaModel" : {},
"ODataModel" : {},
"ODataModel.integration" : {},
"ODataParentBinding" : {},
"ODataPropertyBinding" : {},
"ODataUtils" : {},
"lib/_AggregationCache" : {},
"lib/_AggregationHelper" : {},
"lib/_Batch" : {},
"lib/_Cache" : {},
"lib/_GroupLock" : {},
"lib/_Helper" : {},
"lib/_MetadataConverter" : {},
"lib/_MetadataRequestor" : {},
"lib/_Parser" : {},
"lib/_Requestor" : {},
"lib/_V2MetadataConverter" : {},
"lib/_V2Requestor" : {},
"lib/_V4MetadataConverter" : {},
// the following tests set autostart=false because they require modules asynchronously
// and start QUnit on their own
"OPA.LateProperties" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/Lateproperties/Opa.qunit"]
},
"OPA.ListBinding" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/ListBinding/Opa.qunit"]
},
"OPA.ListBindingTemplate" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/ListBindingTemplate/Opa.qunit"]
},
"OPA.Products" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/Products/Opa.qunit"]
},
"OPA.SalesOrders" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/SalesOrders/Opa.qunit"]
},
"OPA.SalesOrdersTemplate" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/SalesOrdersTemplate/Opa.qunit"]
},
"OPA.SalesOrderTP100_V2" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/SalesOrderTP100_V2/Opa.qunit"]
},
"OPA.SalesOrderTP100_V4" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/SalesOrderTP100_V4/Opa.qunit"]
},
"OPA.ServerDrivenPaging" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/ServerDrivenPaging/Opa.qunit"]
},
"OPA.Sticky" : {
autostart : false,
module : ["sap/ui/core/sample/odata/v4/Sticky/Opa.qunit"]
},
"OPA.ViewTemplate.Types" : {
autostart : false,
module : ["sap/ui/core/sample/ViewTemplate/types/Opa.qunit"]
}
}
};
});
| JavaScript | 0.000032 | @@ -1525,17 +1525,17 @@
/v4/Late
-p
+P
ropertie
|
aca5316181455100b468949ed510d9ce150f2cda | Update exports and stop exposing the internal CalendarResource class | DeprecatedClient.js | DeprecatedClient.js | /*!
* google-apps-admin-sdk
* MIT Licensed
*/
var request = require('request');
module.exports = {
Client: Client
, CalendarResource: CalendarResource
}
function Client(appDomain, accessToken, refreshToken, clientId, clientSecret) {
this.appDomain = appDomain
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.protocol = 'https://';
this.host = 'apps-apis.google.com';
this.endpoint = '/a/feeds/';
this.headers = {
'Authorization': 'Bearer ' + this.accessToken
};
this.calendarResource = new CalendarResource(this);
}
Client.prototype.setAccessToken = function (accessToken) {
this.accessToken = accessToken
this.headers = {
'Authorization': 'Bearer ' + this.accessToken
};
}
function CalendarResource(client) {
this.client = client;
this.apiPath = 'calendar/resource/2.0/'
}
// API Methods matching https://developers.google.com/admin-sdk/calendar-resource/
//https://apps-apis.google.com/a/feeds/calendar/resource/2.0/example.com/
CalendarResource.prototype.list = function(qs, cb) {
return this.client.request('GET', this.apiPath + this.client.appDomain + '/', null, qs, cb);
};
/**
* The main function that does all the work. The client really shouldn't call this.
* @param method {String} HTTP method
* @param resource {String} the resource
* @param body {Object} entity body for POST and PUT requests. Must be buffer or string.
* @param {Object} qs object containing querystring values to be appended to the uri
* @param cb {Function} callback for the request
* @return
*/
Client.prototype.request = function (method, resource, body, qs, cb) {
var self = this;
if (typeof cb === 'undefined') {
cb = qs;
qs = {};
}
if (typeof body === 'function' && !cb) {
cb = body;
body = null;
} else if (body !== null && typeof body === 'object') {
body = JSON.stringify(body);
}
var url = '';
url = url.concat(
this.protocol,
this.host,
this.endpoint,
resource);
qs.alt = 'json'
var opts = {
url: url,
method: method,
headers: this.headers,
qs: qs
};
if (body) {
opts.body = body
}
// Response cb handles json responses as well as refreshing token if possible
var responseCb = function (error, response, body) {
console.log('responseCb', error, response && response.statusCode, response && response.headers, body)
// console.log('responseCb', error, response.headers, body)
// Try to parse json responses, and creates an error if response code is not 200
if (response && response.headers['content-type'] && (response.headers['content-type'].indexOf('application/json') !== -1)) {
try {
body = JSON.parse(body)
if (!error && response.statusCode !== 200) {
error = new Error(body.error.message);
}
} catch (e) {
}
}
return cb(error, response, body);
};
console.log('making request with opts', opts)
return request(opts, responseCb);
};
| JavaScript | 0 | @@ -98,66 +98,15 @@
ts =
- %7B%0A
Client
-: Client%0A, CalendarResource: CalendarResource%0A%7D
%0A%0Afu
|
91929aebbd3d7a1fb692a713c73537c50094afbf | Update app.js | RC/uart/app.js | RC/uart/app.js | var redis = require('redis');
var SerialPort = require('serialport');
var fs = require('fs');
var files = fs.readdirSync('/dev/');
//console.log('files=<',files,'>');
var uartDevice = false;
files.forEach(function(file) {
//console.log('file=<',file,'>');
if(file.startsWith('ttyUSB')) {
//console.log('file=<',file,'>');
uartDevice = '/dev/' +file;
}
});
console.log('uartDevice=<',uartDevice,'>');
function writeMotor(motor) {
console.log('JSON.stringify(motor)=<',JSON.stringify(motor),'>');
serialPort.write(JSON.stringify(motor),function(err) {
if (err) {
console.log('err=<',err,'>');
} else {
console.log('message written');
}
});
}
var subscriber = redis.createClient(6379, 'localhost');
subscriber.subscribe('/dbc/webui2uart');
subscriber.on("message", function(channel, message) {
console.log('message=<',message,'>');
if(message === 'forword') {
var motor = {sp:50,ff:true,mt:'FL'};
writeMotor(motor);
motor.mt = 'FR';
writeMotor(motor);
motor.mt = 'BL';
writeMotor(motor);
motor.mt = 'BR';
writeMotor(motor);
}
if(message === 'back') {
var motor = {sp:50,ff:false,mt:'FL'};
writeMotor(motor);
motor.mt = 'FR';
writeMotor(motor);
motor.mt = 'BL';
writeMotor(motor);
motor.mt = 'BR';
writeMotor(motor);
}
if(message === 'left') {
var motor = {sp:50,ff:false,mt:'FL'};
writeMotor(motor);
motor.ff = true;
motor.mt = 'FR';
writeMotor(motor);
motor.ff = false;
motor.mt = 'BL';
writeMotor(motor);
motor.ff = true;
motor.mt = 'BR';
writeMotor(motor);
}
if(message === 'right') {
var motor = {sp:50,ff:true,mt:'FL'};
writeMotor(motor);
motor.ff = false;
motor.mt = 'FR';
writeMotor(motor);
motor.ff = true;
motor.mt = 'BL';
writeMotor(motor);
motor.ff = false;
motor.mt = 'BR';
writeMotor(motor);
}
if(message === 'stop') {
var motor = {sp:255,ff:true,mt:'FL'};
writeMotor(motor);
motor.mt = 'FR';
writeMotor(motor);
motor.mt = 'BL';
writeMotor(motor);
motor.mt = 'BR';
writeMotor(motor);
}
});
var serialPort = new SerialPort(uartDevice, {
baudrate: 112500
});
serialPort.on("open", function () {
console.log('open');
});
serialPort.on('data', function(data) {
console.log('received data =<',data,'>');
console.log('received data.toString(utf8) =<',data.toString('utf8'),'>');
});
serialPort.on('error', function(err) {
console.log('err =<',err,'>');
});
| JavaScript | 0.000002 | @@ -999,32 +999,40 @@
eMotor(motor);%0D%0A
+/* %0D%0A
motor.mt = '
@@ -1145,32 +1145,36 @@
eMotor(motor);%0D%0A
+*/%0D%0A
%7D%0D%0A if(messag
|
8f331e218c57021c5b272e4b7f64b63e937bbb43 | Fix scheduler datacontext | src/scheduler.datacontext.js | src/scheduler.datacontext.js |
(function() {
'use strict';
angular.module('freeants').factory('schedulerDataContext', ['$http', 'helpers', 'path', function ($http, helpers, path) {
//End points
function SchedulerUrl() {
return path.api + "/Scheduler";
}
return {
schedule: function (schedulerObject) {
var req = $http({
method: 'POST',
headers: helpers.getSecurityHeaders(),
url: SchedulerUrl(),
data: schedulerObject
}).then(function (response) {
return response.data;
});
return req;
},
update: function (schedulerObject, schedulerId) {
var req = $http({
method: 'PUT',
headers: helpers.getSecurityHeaders(),
url: SchedulerUrl() + "/" + schedulerId,
data: schedulerObject
}).then(function (response) {
return response.data;
});
return req;
},
delete: function (thingId, schedulerId) {
var req = $http({
method: 'DELETE',
headers: helpers.getSecurityHeaders(),
url: SchedulerUrl() + "/" + schedulerId,
data: {thingId: thingId}
}).then(function (response) {
return response.data;
});
return req;
}
}
}]);
}()); | JavaScript | 0.000166 | @@ -1146,14 +1146,12 @@
d: '
-DELETE
+POST
',%0A
@@ -1284,23 +1284,25 @@
data: %7B
+%22
thingId
+%22
: thingI
|
3d07c2f83e43565fff7abfbcbad7d81283b3712b | Update ozController.js | adopt4k_server/STATIC/scripts/ozController.js | adopt4k_server/STATIC/scripts/ozController.js | var ozController = {
$tooltip: null,
map: null,
base_layer: null,
oz_layer: null,
api_url: '/api/adoptions/?format=json&page_size=5000',
adoptions: {},
oz_url_lq: 'https://services1.arcgis.com/DnZ5orhsUGGdUZ3h/ArcGIS/rest/services/OZ2013_LowRes/FeatureServer/0',
oz_url_hq: 'https://services1.arcgis.com/DnZ5orhsUGGdUZ3h/ArcGIS/rest/services/OZ2014/FeatureServer/0',
oz_url: this.oz_url_lq,
lq_oz_start_at_level: 1,
hq_oz_start_at_level: 100, //no hq!
init: function(){
this.$tooltip = $('#tooltip');
this.fetchAdoptions();
this.connectToServer();
this.map = L.map('map', {
minZoom: 2,
// zoomControl: false,
reuseTiles: true
// }).setView([52.3667, 4.9000], 7), // NL zoomed in
}).setView([39.9167, 32.8333], 5), // turkey focused
// }).setView([0, 0], 2), //entire world center
/*
Available basemaps;
-------------------
- Streets
- Topographic
- NationalGeographic - ugly
- Oceans - busy?
-> Gray - too light?
-> DarkGray - too dark?
- Imagery - busy
- ShadedRelief - ugly
*/
// load basemap
// this.base_layer = L.esri.basemapLayer('Topographic').addTo(this.map) ;
// L.tileLayer('http://a{s}.acetate.geoiq.com/tiles/acetate-base/{z}/{x}/{y}.png', {
// attribution: 'Tiles © Esri — Source: USGS, Esri, TANA, DeLorme, and NPS',
// maxZoom: 13
// }).addTo(this.map);
L.tileLayer('http://api.tiles.mapbox.com/v4/{mapid}/{z}/{x}/{y}.jpg90?access_token=pk.eyJ1Ijoiam9zaHVhZGVsYW5nZSIsImEiOiJ3RU1SemNzIn0.CyG3f36Z16ov1JEDHw2gDQ', {
mapid: 'joshuadelange.j5igjfc7',
}).addTo(this.map);
this.map.on('zoomend', $.proxy(this.zoomend, this)) ;
// this.addOzLayer() ;
this.setAppropiateOzQuality() ;
return this ;
},
connectToServer: function(){
var socket = io('http://' + window.location.hostname + '.org:4000');
socket.on('connect', function (data) {
console.log('connected');
socket.on('newAdoptions', function(newAdoptions){
console.log('new adoptions!', newAdoptions);
for (var i in newAdoptions) {
var adoption = newAdoptions[i];
$('.oz-' + adoption['worldid']).attr('class', 'oz-' + adoption['worldid'] + ' adopted adopted-' + adoption['targetyear']);
};
});
});
},
fetchAdoptions: function(){
// fetching from the api
// proxy to retain 'this' context
$.getJSON(this.api_url, $.proxy(function(response){
/*
reformatting data like below for quick access when rendering the map
{
'NLD-NOH': 2013,
'NLD-FRI': 2020
}
*/
for (var i = response.results.length - 1; i >= 0; i--) {
//shortcut for clarity
var adoption = response.results[i] ;
this.adoptions[adoption['worldid']] = adoption['targetyear'];
};
}, this));
},
addOzLayer: function(){
this.oz_layer = L.esri.featureLayer(this.oz_url, {
// only load specific fields to reduce redundant data being sent back and forth
// 'WorldID', 'OBJECTID' are for HQ OZ2014 layer
// ''OBJECTID_1', 'World', 'FID' are for LQ OZ2008 layer
fields: ['WorldID', 'OBJECTID', 'OBJECTID_1', 'World', 'FID'],
// esri's library smartly 'uglifies' polygons for us for performance
// reduce for prettier maps, increase for faster ugly
simplifyFactor: 1,
// adds hover thing
onEachFeature: $.proxy(function(feature, layer){
if(this.adoptions.hasOwnProperty(feature.properties.WorldID)){
layer.on({
'mousemove': $.proxy(function(e) {
this.$tooltip.css({
left: e.originalEvent.pageX - 25,
top: e.originalEvent.pageY- 35
});
}, this),
'mouseover': $.proxy(function(e) {
this.$tooltip.html(this.adoptions[feature.properties.WorldID]);
this.$tooltip.show();
}, this),
'mouseout': $.proxy(function(e) {
this.$tooltip.hide();
}, this)
});
}
}, this),
// initially style adopted oz's + give world id class name for later lookup
style: $.proxy(function(feature){
// give it a class name we can look up later
var style = {
// eg; oz-NLD-NOH
className: 'oz-' + feature.properties.WorldID
} ;
// if oz is adopted already, give class
if(this.adoptions.hasOwnProperty(feature.properties.WorldID)){
style['className'] = style['className'] + ' adopted-' + this.adoptions[feature.properties.WorldID]
}
return style ;
}, this)
});
this.oz_layer.addTo(this.map);
},
removeOzLayer: function(){
if(this.oz_layer !== null){
this.map.removeLayer(this.oz_layer) ;
}
},
reloadOzLayer: function(){
this.removeOzLayer() ;
this.addOzLayer() ;
},
zoomend: function(ev){
this.setAppropiateOzQuality() ;
},
setAppropiateOzQuality: function(){
var z = this.map.getZoom() ;
if(z >= this.lq_oz_start_at_level
&& z < this.hq_oz_start_at_level) {
//only if something changes, or else pointless/ugly reload
if(this.oz_url !== this.oz_url_lq) {
this.oz_url = this.oz_url_lq ;
this.reloadOzLayer() ;
}
}
if(z >= this.hq_oz_start_at_level) {
//only if this is new
if(this.oz_url !== this.oz_url_hq) {
this.oz_url = this.oz_url_hq ;
this.reloadOzLayer() ;
}
}
//#yolo!
if(z < this.lq_oz_start_at_level) {
this.oz_url = null ;
this.removeOzLayer() ;
}
}
} ;
| JavaScript | 0.000001 | @@ -1925,12 +1925,8 @@
+ '
-.org
:400
|
1034d8e1dfdff7c0780264144292c22c6f0c5904 | Fix empty value for @use() | src/property.js | src/property.js | import parse_value_group from './parser/parse-value-group';
import parse_grid from './parser/parse-grid';
import Shapes from './shapes';
import prefixer from './prefixer';
import { memo } from './utils';
export default {
['@size'](value, { is_special_selector }) {
let [w, h = w] = parse_value_group(value);
return `
width: ${ w };
height: ${ h };
${ is_special_selector ? '' : `
--internal-cell-width: ${ w };
--internal-cell-height: ${ h };
`}
`;
},
['@min-size'](value) {
let [w, h = w] = parse_value_group(value);
return `min-width: ${ w }; min-height: ${ h };`;
},
['@max-size'](value) {
let [w, h = w] = parse_value_group(value);
return `max-width: ${ w }; max-height: ${ h };`;
},
['@place-cell']: (() => {
let map_left_right = {
'center': '50%', '0': '0%',
'left': '0%', 'right': '100%',
'top': '50%', 'bottom': '50%'
};
let map_top_bottom = {
'center': '50%', '0': '0%',
'top': '0%', 'bottom': '100%',
'left': '50%', 'right': '50%',
};
return value => {
let [left, top = '50%'] = parse_value_group(value);
left = map_left_right[left] || left;
top = map_top_bottom[top] || top;
const cw = 'var(--internal-cell-width, 25%)';
const ch = 'var(--internal-cell-height, 25%)';
return `
position: absolute;
left: ${ left };
top: ${ top };
width: ${ cw };
height: ${ ch };
margin-left: calc(${ cw } / -2) !important;
margin-top: calc(${ ch } / -2) !important;
grid-area: unset !important;
`;
}
})(),
['@grid'](value, options) {
let [grid, size] = value.split('/').map(s => s.trim());
return {
grid: parse_grid(grid),
size: size ? this['@size'](size, options) : ''
};
},
['@shape']: memo('shape-property', value => {
let [type, ...args] = parse_value_group(value);
let prop = 'clip-path';
if (!Shapes[type]) return '';
let rules = `${ prop }: ${ Shapes[type].apply(null, args) };`;
return prefixer(prop, rules) + 'overflow: hidden;';
}),
['@use'](rules) {
return rules;
}
}
| JavaScript | 0.002932 | @@ -2157,24 +2157,54 @@
'%5D(rules) %7B%0A
+ if (rules.length %3E 2) %7B%0A
return r
@@ -2209,15 +2209,21 @@
rules;%0A
+ %7D%0A
%7D%0A%0A%7D%0A
|
7fc59bbd61e9f76fe271a12523b62272dc1a38c5 | remove lingering console.log | app/assets/javascripts/backend/datepickers.js | app/assets/javascripts/backend/datepickers.js | var datepickers = datepickers || {
init: function() {
this.load_ranges();
this.load_regulars();
$('.date_picker, .date_range_picker').find('.input-group-addon').on(
'click',
this.icon_click_listener
);
},
icon_click_listener: function(e) {
e.preventDefault();
$(this).parents('.input-group').find('input').trigger('focus');
},
load_ranges: function() {
if(typeof this.starts_on === 'undefined' || typeof this.stops_on === 'undefined') return;
$('.date_range_picker input').each(function(){
var input = $(this);
if(input.data('start') !== null) {
datepickers.starts_on(input.data('start')).datepicker().on(
'changeDate',
datepickers.starts_on_change_date_listener
);
}
if(input.data('stop') !== null) {
datepickers.stops_on(input.data('stop')).datepicker({
weekStart: 1,
autoclose: true
}).on('changeDate', datepickers.stops_on_change_date_listener);
}
});
},
load_regulars: function() {
var inputs = $('.date_picker input');
if(typeof inputs.datepicker !== 'function') return;
inputs.datepicker();
},
starts_on: function(id) {
return $('.date_range_picker input[data-start="'+ id +'"]');
},
starts_on_change_date_listener: function(selected) {
var input = $(this);
var date = new Date(selected.date.valueOf());
date.setDate(date.getDate(new Date(selected.date.valueOf())));
datepickers.stops_on(input.data('start')).datepicker('setStartDate', date);
},
stops_on: function(id) {
return $('.date_range_picker input[data-stop="'+ id +'"]');
},
stops_on_change_date_listener: function(selected) {
var input = $(this);
var date = new Date(selected.date.valueOf());
console.log(date);
date.setDate(date.getDate(new Date(selected.date.valueOf())));
datepickers.starts_on(input.data('stop')).datepicker('setEndDate', date);
}
};
$(function(){ datepickers.init(); });
| JavaScript | 0.000001 | @@ -1791,31 +1791,8 @@
));%0A
- console.log(date);%0A
|
698e12d1b0b2dac20e9da77d3737efa45b611fc9 | fix linkedin url | data/SiteConfig.js | data/SiteConfig.js | const config = {
siteTitle: "Mildronize", // Site title.
siteTitleShort: "Mildronize", // Short site title for homescreen (PWA). Preferably should be under 12 characters to prevent truncation.
siteTitleAlt: "Mildronize", // Alternative site title for SEO.
siteLogo: "/logos/android-chrome-512x512.png", // Logo used for SEO and manifest.
siteUrl: "https://mildronize.com", // Domain of your website without pathPrefix.
pathPrefix: "/", // Prefixes all links. For cases when deployed to example.github.io/gatsby-advanced-starter/.
nodePrefix: "/b", // Prefixes for only post created by createNodeField from `gastby-node.js`
siteDescription: "You can find almost stuff about me: sharing ideas, programming techniques, web technology and others.", // Website description used for RSS feeds/meta description tag.
siteRss: "/rss.xml", // Path to the RSS file.
siteRssTitle: "Mildronize.com RSS feed", // Title of the RSS feed
siteFBAppID: "xxxxx", // FB Application ID for using app insights
googleAnalyticsID: "UA-62565035-1", // GA tracking ID.
disqusShortname: "https-vagr9k-github-io-gatsby-advanced-starter", // Disqus shortname.
dateFromFormat: "YYYY-MM-DD", // Date format used in the frontmatter.
dateFormat: "DD/MM/YYYY", // Date format for display.
// postsPerPage: 4, // Amount of posts displayed per listing page.
userName: "Thada Wangthammang", // Username to display in the author segment.
userEmail: "mildronize@gmail.com", // Email used for RSS feed's author segment
userTwitter: "mildronize", // Optionally renders "Follow Me" in the UserInfo segment.
userLocation: "Songkhla, Thailand", // User location to display in the author segment.
userAvatar: "https://api.adorable.io/avatars/150/test.png", // User avatar to display in the author segment.
userDescription:
"Yeah, I like animals better than people sometimes... Especially dogs. Dogs are the best. Every time you come home, they act like they haven't seen you in a year. And the good thing about dogs... is they got different dogs for different people.", // User description to display in the author segment.
// Links to social profiles/projects you want to display in the author segment/navigation bar.
userLinks: [
{
label: "GitHub",
url: "https://github.com/mildronize",
iconClassName: "fab fa-github",
},
{
label: "Twitter",
url: "https://twitter.com/mildronize",
iconClassName: "fab fa-twitter",
},
{
label: "Email",
url: "mailto:mildronize@gmail.com",
iconClassName: "fas fa-envelope",
},
{
label: "Linkedin",
url: "mailto:https://www.linkedin.com/in/thada-wangthammang-281894a6/",
iconClassName: "fab fa-linkedin",
},
{
label: "Medium",
url: "https://medium.com/@mildronize",
iconClassName: "fab fa-medium",
},
{
label: "RSS",
url: "/rss.xml",
iconClassName: "fas fa-rss",
}
],
copyright: "Copyright © 2020. Advanced User", // Copyright string for the footer of the website and RSS feed.
themeColor: "#c62828", // Used for setting manifest and progress theme colors.
backgroundColor: "#e0e0e0", // Used for setting manifest background color.
};
// Validate
// Make sure pathPrefix is empty if not needed
if (config.pathPrefix === "/") {
config.pathPrefix = "";
} else {
// Make sure pathPrefix only contains the first forward slash
config.pathPrefix = `/${config.pathPrefix.replace(/^\/|\/$/g, "")}`;
}
// Make sure siteUrl doesn't have an ending forward slash
if (config.siteUrl.substr(-1) === "/")
config.siteUrl = config.siteUrl.slice(0, -1);
// Make sure nodePrefix doesn't have an ending forward slash
if (config.nodePrefix.substr(-1) === "/")
config.nodePrefix = config.nodePrefix.slice(0, -1);
// Make sure siteRss has a starting forward slash
if (config.siteRss && config.siteRss[0] !== "/")
config.siteRss = `/${config.siteRss}`;
module.exports = config;
| JavaScript | 0.998334 | @@ -2630,23 +2630,16 @@
url: %22
-mailto:
https://
|
2fef9bdade7d21de4c8992472106a11c31290584 | Fix webdriver bridge bug | node-src/webdriverBridge.js | node-src/webdriverBridge.js |
var fs = require('fs');
var nextClientActionId = 1;
var exportMethods = ['dragStart', 'dragOver', 'dragLeave', 'drop', 'delay'];
// using this ugly hack, since selenium seems to not pass arguments given to the execute() method
function webdriverExecuteAsync(self, script, parameters, callback) {
var parameterAssignments = '';
for (var paramName in parameters) {
var paramValue = parameters[paramName];
parameterAssignments += 'var ' + paramName + ' = ' + JSON.stringify(paramValue) + ';';
}
var scriptBody =
parameterAssignments +
'return (' +
script +
')(done);';
self.webdriver.executeAsync(new Function('done', scriptBody), callback);
}
var DragMockClientActionBridge = function(webdriver, actionId) {
this.webdriver = webdriver;
this.actionId = actionId;
};
exportMethods.forEach(function(methodName) {
DragMockClientActionBridge.prototype[methodName] = function() {
var self = this;
var args = Array.prototype.slice.call(arguments);
var callback = function () {};
if (typeof args[args.length - 1] === 'function') {
callback = args.pop();
}
var browserScript = function(done) {
// executed in browser context
window._dragMockActions = window._dragMockActions || {};
var action = window._dragMockActions[actionId] || dragMock;
args[0] = document.querySelector(args[0]);
action = action[methodName].apply(action, args);
window._dragMockActions[actionId] = action;
action.then(done);
};
var parameters = {
methodName: methodName,
actionId: self.actionId,
args: args
};
webdriverExecuteAsync(self, browserScript, parameters, function(err) {
// back in node.js context
callback(err, self);
});
return self;
};
});
function extendWebdriverPrototype(webdriverPrototype) {
function createActionAndCallMethod(methodName) {
return function() {
var clientAction = new DragMockClientActionBridge(this, nextClientActionId++);
clientAction[methodName].apply(clientAction, arguments);
return clientAction;
};
}
exportMethods.forEach(function(methodName) {
webdriverPrototype[methodName] = createActionAndCallMethod(methodName);
});
}
function extendWebdriverFactory(webdriver) {
var originalMethod = webdriver.remote;
webdriver.remote = function() {
var instance = originalMethod.apply(webdriver, arguments);
extendWebdriverPrototype(instance.constructor.prototype);
return instance;
}
}
var webdriverBridge = {
init: function(webdriver) {
if (webdriver.version && webdriver.remote) {
extendWebdriverFactory(webdriver);
} else {
extendWebdriverPrototype(webdriver.constructor.prototype);
}
},
loadLibrary: function(webdriver, done) {
var dragMockLib = fs.readFileSync(__dirname + '/../dist/drag-mock.js', { encoding: 'utf-8' });
webdriver.execute(dragMockLib, function (error) {
if (typeof done === 'function') { done(error); }
});
}
};
module.exports = webdriverBridge;
| JavaScript | 0.000001 | @@ -28,50 +28,22 @@
var
-nextClientActionId = 1;%0A%0Avar exportMethods
+EXPORT_METHODS
= %5B
@@ -98,16 +98,86 @@
elay'%5D;%0A
+var WEBDRIVER_ASYNC_EXEC_TIMEOUT = 2000;%0A%0Avar nextClientActionId = 1;%0A
%0A%0A// usi
@@ -650,32 +650,92 @@
self.webdriver
+%0A .timeoutsAsyncScript(WEBDRIVER_ASYNC_EXEC_TIMEOUT)%0A
.executeAsync(ne
@@ -909,29 +909,30 @@
d;%0A%7D;%0A%0A%0A
-exportMethods
+EXPORT_METHODS
.forEach
@@ -1261,24 +1261,135 @@
ion(done) %7B%0A
+ var stringStartsWith = function(string, prefix) %7B%0A return string.indexOf(prefix) === 0;%0A %7D;%0A%0A
// exe
@@ -1543,16 +1543,154 @@
gMock;%0A%0A
+ if (stringStartsWith(methodName, 'drag') %7C%7C stringStartsWith(methodName, 'drop')) %7B%0A // first argument is element selector%0A
ar
@@ -1730,16 +1730,24 @@
gs%5B0%5D);%0A
+ %7D%0A
ac
@@ -2484,21 +2484,22 @@
%0A%0A
-exportMethods
+EXPORT_METHODS
.for
|
5ea287772e965b9c0eff96695c60f6d648bec405 | Add separate alpha values for room state so that the states can be referenced without string literals. | states/main/entities/room.js | states/main/entities/room.js | /**
* This file defines the room for the game.
* A room consists of a tiled floor, several walls to block player entry, and a lighting state.
* Rooms may be either lit or unlit.
*/
var LightsOut = (function(lightsOut){
lightsOut.Room = function(game, zDepthManager,
navPointIndex, x, y, width, height) {
this.game = game;
this.navPointIndex = navPointIndex;
/**
* The lighting for the room sets the level of visibility, an alpha value of 1.0 indicates an unlit room,
* and a value of 0.0 indicates full visibility.
*/
this.lighting = game.add.tileSprite(x, y, width, height, lightsOut.Room.lightingKey);
this.lighting.z = lightsOut.ZDepth.LIGHTING;
zDepthManager.lighting.add(this.lighting);
/**
* The min and max alpha values for the lighting in this room.
*/
this.lightingAlphaMin = 1.0;
this.lightingAlphaMax = 1.0;
this.lightingFlickerPeriodSeconds = 5;
game.time.events.loop(Phaser.Timer.SECOND * this.lightingFlickerPeriodSeconds / 50, this.updateLightingAlpha, this);
game.time.events.start();
this.setState("LIT", 1000);
};
/**
* Describes the lighting values of the room.
* The values for the enum keys are the max alpha
* the lighting element should have when the room
* is in that state.
*/
lightsOut.Room.State = {
/**
* Indicates that the room is currently illuminated.
*/
LIT : 0.8,
/**
* Indicates that the room is dark, but partially illuminated
* by the player.
*/
SEMI_LIT : 0.95,
/**
* Indicates that the room is dark.
*/
UNLIT : 1.0
};
/** Factory function for creating a room group. */
lightsOut.Room.createRoom = function(game, zDepthManager, navPointIndex, x, y, width, height) {
return new lightsOut.Room(game, zDepthManager, navPointIndex,
x, y, width, height);
};
/**
* Unique key by which room resources may be referenced.
*/
lightsOut.Room.lightingKey = "lighting";
lightsOut.Room.load = function(game) {
game.load.spritesheet(lightsOut.Room.lightingKey, "assets/sprites/lighting.png", 10, 10);
};
lightsOut.Room.prototype.constructor = lightsOut.Room;
/**
* @return the index of the nav point corresponding to the
* central point of this room.
*/
lightsOut.Room.prototype.getNavPointIndex = function() {
return this.navPointIndex;
};
/**
* @return true if the room contains the specified point.
*/
lightsOut.Room.prototype.containsPoint = function(x, y) {
return this.lighting.getBounds().contains(x, y);
};
/**
* Returns the current illumination of the room. This value should
* always be one of: lightsOut.Room.State.
*/
lightsOut.Room.prototype.getIllumination = function(state) {
return this.state;
};
/**
* Sets the current illumination of the room. A tween is used to
* smooth the transition, however the state transition is instant.
* @param state one of : lightsOut.Room.State.
*/
lightsOut.Room.prototype.setIllumination = function(state) {
this.setState(state, 1000);
};
/**
* @param State must be one of lightsOut.Room.State.
* @param tweenTimeMs the amount of time (in milliseconds) to take
* to perform the visual state transition.
*/
lightsOut.Room.prototype.setState = function(state, tweenTimeMs) {
if (lightsOut.Room.State[state] == undefined) {
throw "State: " + state + " is not a valid room state.";
}
this.state = state;
var alphaVal = lightsOut.Room.State[state];
var lightingTween = this.game.add.tween(this);
lightingTween.to( { lightingAlphaMin: alphaVal * 0.95, lightingAlphaMax: alphaVal }, tweenTimeMs, Phaser.Easing.Linear.None);
lightingTween.start();
};
lightsOut.Room.prototype.updateLightingAlpha = function() {
var time = this.game.time.totalElapsedSeconds();
var lightingLerp = (Math.sin(2 * Math.PI * time / this.lightingFlickerPeriodSeconds) + 1) / 2;
this.lighting.alpha = this.lightingAlphaMin + (this.lightingAlphaMax - this.lightingAlphaMin) * lightingLerp;
};
return lightsOut;
}(LightsOut || {}));
| JavaScript | 0 | @@ -1462,11 +1462,13 @@
T :
-0.8
+%22LIT%22
,%0D%0A%0D
@@ -1591,20 +1591,26 @@
I_LIT :
-0.95
+%22SEMI_LIT%22
,%0D%0A%0D%0A
@@ -1677,19 +1677,120 @@
UNLIT :
-1.0
+%22UNLIT%22%0D%0A %7D;%0D%0A%0D%0A lightsOut.Room.State.Alpha = %7B%0D%0A LIT : 0.8,%0D%0A SEMI_LIT : 0.1,%0D%0A UNLIT : 0.95
%0D%0A %7D;%0D%0A
@@ -3758,24 +3758,30 @@
t.Room.State
+.Alpha
%5Bstate%5D;%0D%0A%0D%0A
|
b6da99a7a1ac34a0d2b9f4a429bdb4a2be741a52 | Remove obsolete TODO | wcfsetup/install/files/js/WoltLabSuite/Core/Form/Builder/Field/ItemList.js | wcfsetup/install/files/js/WoltLabSuite/Core/Form/Builder/Field/ItemList.js | /**
* Data handler for an item list form builder field in an Ajax form.
*
* @author Matthias Schmidt
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/Form/Builder/Field/ItemList
* @since 5.2
*/
define(['Core', './Field', 'WoltLabSuite/Core/Ui/ItemList/Static'], function(Core, FormBuilderField, UiItemListStatic) {
"use strict";
/**
* @constructor
*/
function FormBuilderFieldItemList(fieldId) {
this.init(fieldId);
};
Core.inherit(FormBuilderFieldItemList, FormBuilderField, {
/**
* @see WoltLabSuite/Core/Form/Builder/Field/Field#_getData
*/
_getData: function() {
var data = {};
data[this._fieldId] = [];
var values = UiItemListStatic.getValues(this._fieldId);
for (var i = 0, length = values.length; i < length; i++) {
// TODO: data[this._fieldId] is an array but if code assumes object
if (values[i].objectId) {
data[this._fieldId][values[i].objectId] = values[i].value;
}
else {
data[this._fieldId].push(values[i].value);
}
}
return data;
}
});
return FormBuilderFieldItemList;
});
| JavaScript | 0.00087 | @@ -878,80 +878,8 @@
) %7B%0A
-%09%09%09%09// TODO: data%5Bthis._fieldId%5D is an array but if code assumes object%0A
%09%09%09%09
|
694669d476be60a2e91681f5aaeae703e7b925bd | Initialize child object | src/quo.core.js | src/quo.core.js | /*
QuoJS 1.0
(c) 2011, 2012 Javi Jiménez Villar (@soyjavi)
http://quojs.tapquo.com
*/
(function($$) {
var OBJ_PROTO = Object.prototype;
var EMPTY_ARRAY = [];
/**
* Determine the internal JavaScript [[Class]] of an object.
*
* @param {object} obj to get the real type of itself.
* @return {string} with the internal JavaScript [[Class]] of itself.
*/
$$.toType = function(obj) {
return OBJ_PROTO.toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
};
/**
* ?
*/
$$.isOwnProperty = function(object, property) {
return OBJ_PROTO.hasOwnProperty.call(object, property);
};
/**
* ?
*/
$$.getDomainSelector = function(selector) {
var domain = null;
var elementTypes = [1, 9, 11];
var type = $$.toType(selector);
if (type === 'array') {
domain = _compact(selector);
} else if (type === 'string') {
domain = $$.query(document, selector);
} else if (elementTypes.indexOf(selector.nodeType) >= 0 || selector === window) {
domain = [selector];
selector = null;
}
return domain;
};
/**
* ?
*/
$$.map = function(elements, callback) {
//@TODO: Refactor!!!
var values = [];
var i;
var key;
if ($$.toType(elements) === 'array') {
for (i = 0; i < elements.length; i++) {
var value = callback(elements[i], i);
if (value != null) values.push(value);
}
} else {
for (key in elements) {
value = callback(elements[key], key);
if (value != null) values.push(value);
}
}
return _flatten(values);
};
/**
* ?
*/
$$.each = function(elements, callback) {
var i, key;
if ($$.toType(elements) === 'array')
for(i = 0; i < elements.length; i++) {
if(callback.call(elements[i], i, elements[i]) === false) return elements;
}
else
for(key in elements) {
if(callback.call(elements[key], key, elements[key]) === false) return elements;
}
return elements;
};
/**
* ?
*/
$$.mix = function() {
for (var arg = 0, len = arguments.length; arg < len; arg++) {
var argument = arguments[arg];
for (var prop in argument) {
if ($$.isOwnProperty(argument, prop)) {
child[prop] = argument[prop];
}
}
}
return child;
};
/**
* ?
*/
$$.fn.forEach = EMPTY_ARRAY.forEach;
/**
* ?
*/
$$.fn.indexOf = EMPTY_ARRAY.indexOf;
/**
* ?
*/
$$.fn.map = function(fn){
return $$.map(this, function(el, i){ return fn.call(el, i, el) });
};
/**
* ?
*/
/*
$$.fn.slice = function(){
return $$(slice.apply(this, arguments));
};
*/
/**
* ?
*/
$$.fn.instance = function(property) {
return this.map(function() {
return this[property];
});
};
/**
* ?
*/
$$.fn.filter = function(selector) {
return $$([].filter.call(this, function(element) {
return element.parentNode && $$.query(element.parentNode, selector).indexOf(element) >= 0;
}));
};
function _compact(array) {
return array.filter(function(item) {
return item !== undefined && item !== null
});
}
function _flatten(array) {
return array.length > 0 ? [].concat.apply([], array) : array
}
})(Quo); | JavaScript | 0.000036 | @@ -2334,32 +2334,56 @@
= function() %7B%0A
+ var child = %7B%7D;%0A
for (var
|
ac7b636a065fc90f41faedb3b0af7da0dfaee274 | load the event binding only once | static/javascripts/custom.js | static/javascripts/custom.js | function viewDidLoad() {
// 总
$("#n-post-wrapper").load("view/create-post.html", function () {
// $('.n-main .n-container').css('margin-left', $('#n-nav .n-container').css('width'));
});
// $("#n-home-wrapper").load("view/home.html", function () {
// // $('.n-main .n-container').css('margin-left', $('#n-nav .n-container').css('width'));
// });
// $("#n-account-wrapper").load("view/account.html", function () {
// // $('.n-main .n-container').css('margin-left', $('#n-nav .n-container').css('width'));
// });
$('[data-toggle="tooltip"]').tooltip()
currentUser = getUser(currentUserID);
angular.element("body").scope().currentUser = currentUser;
angular.element("body").scope().currentUserPastPostFilter = { sid: currentUserID };
angular.element("body").scope().currentUserFavoriteFilter = function (book) {
return favorites.filter(function (b) {
var bool = (b.uid === currentUserID) && (b.pid === book.pid);
if (bool) {
console.log("True: " + b.uid + " " + book.pid)
} else {
console.log("False: " + b.uid + " " + book.pid)
}
return bool;
});
};
// 总完
// 王狗
$("#n-home .sort-button").click(function() {
var moreOptionBar = $("#n-home .n-more-option-bar");
if (moreOptionBar.css("display") == "none") {
moreOptionBar.show();
$(this).html('<i class="fa fa-chevron-up">');
updateTableContainerHeight(235 + moreOptionBar.height());
} else {
moreOptionBar.hide();
$(this).html('<i class="fa fa-chevron-down">');
updateTableContainerHeight(70);
}
});
$("#n-home .grand-checkbox").click(function() {
$("#n-home .col-selection input").each(function(index) {
$(this).prop('checked', $("#n-home .grand-checkbox").prop('checked'));
var row = $(this).closest("tr");
var newValue = $(this).prop("checked");
var bookID = row.attr("book-id");
$.each(books, function() {
if (this.id == bookID) {
this.isSelected = newValue;
}
});
})
updateBookList();
})
$("#selected-only-button").click(function() {
if ($(this).hasClass("highlight-button")) {
$(this).removeClass("highlight-button");
angular.element("body").scope().search.isSelected = ""
} else {
$(this).addClass("highlight-button");
angular.element("body").scope().search.isSelected = true
}
angular.element("body").scope().$apply();
})
$("#n-home .col-selection input").click(function() {
var row = $(this).closest("tr");
var newValue = $(this).prop("checked");
var bookID = row.attr("book-id");
$.each(books, function() {
if (this.pid == bookID) {
this.isSelected = newValue;
}
});
updateBookList();
})
function updateTableContainerHeight(height) {
var windowHeight = $(window).height();
var tableContainer = $(".n-book-list-table").css("height", (windowHeight - height) + "px");
}
var table = $(".n-book-list-table table");
table.floatThead({
scrollContainer: function($table){
return $('.n-book-list-table');
}
});
// 王狗完
// 林狗
$(".fancybox").fancybox();
$(document).on("click", ".like", function() {
if ($(this).hasClass("on")) {
$(this).removeClass("on");
$(this).addClass("off");
} else {
$(this).removeClass("off");
$(this).addClass("on");
}
})
// 林狗完
// 孙狗
// $(document).on("click",".n-account-nav a",function(e){
// e.preventDefault();
// $(".n-account-toggle").hide();
// var toShow = $(this).attr('href');
// $(toShow).show();
// });
// $(document).on("click",".n-account-edit-button", function(){
// var $this = $(this);
// var text = $this.text();
// if(text=="Edit"){
// $this.text("Cancel");
// }
// else{
// $this.text("Edit");
// }
// $(".account-label").toggle();
// });
// $("input.account-label").change(function(){
// $(this).prev().text($(this).text());
// });
$(document).on("click", "#n-account .content h4 span", function() {
$("#n-account .content h4 span").removeClass("selected");
$(this).addClass("selected")
var showContentID = $(this).attr("href");
$("#n-account .content .content-block").css("display", "none");
console.log("#n-account .content .content-block " + showContentID)
$("#n-account .content .content-block" + showContentID).css("display", "block");
})
// 孙狗完
// 雷狗
var textTimeout = 200;
$(document).on("click", "#n-hamburger-icon", function() {
$(".n-container").toggleClass('active');
$(this).toggleClass('active');
setTimeout(function (){
$(".n-nav-text").toggleClass('active');
}, textTimeout);
textTimeout = 200 - textTimeout;
return false;
});
$(document).on("click", "div[id^='n-nav-']", function() {
var section = $(this).attr('id').substr(6);
$(".n-nav-icon").removeClass("active");
$(this).addClass("active");
$(".n-main >div:visible").fadeOut(200, 'swing', function() {
$("#n-" + section + "-wrapper").fadeIn(200);
});
return false;
});
// 雷狗完
}
$(document).ready(viewDidLoad)
| JavaScript | 0 | @@ -4341,16 +4341,51 @@
%0A%0A%0A%0A%0A%0A%0A%0A
+%7D%0A%0A$(document).ready(viewDidLoad)%0A%0A
// %E9%9B%B7%E7%8B%97%0Ava
@@ -4998,38 +4998,4 @@
%E9%9B%B7%E7%8B%97%E5%AE%8C%0A
-%7D%0A%0A$(document).ready(viewDidLoad)%0A
|
220e00e0365001497782df08aaf0dd5ced37fc2f | Change || to && | cron/disabled/expiring-cards.js | cron/disabled/expiring-cards.js | #!/usr/bin/env node
import '../../server/env';
import logger from '../../server/lib/logger';
import models from '../../server/models';
import * as libPayments from '../../server/lib/payments';
// Run on the 7th and 21st of the month
const today = new Date();
const date = today.getDate();
const month = today.getMonth() + 1;
const year = today.getFullYear();
if (process.env.NODE_ENV === 'production' && (date !== 7 || date !== 21) && !process.env.OFFCYCLE) {
console.log('NODE_ENV is production and today is not the 7th or 21st of month, script aborted!');
process.exit();
}
// link payment method id in Orders to payment method id in the payment method we're updating
const fetchExpiringCreditCards = async (month, year) => {
const expiringCards = await models.PaymentMethod.findAll({
where: {
type: 'creditcard',
data: {
expMonth: month,
expYear: year,
},
},
include: [
{
model: models.Order,
where: { status: 'ACTIVE' },
},
],
});
return expiringCards;
};
const run = async () => {
const cards = await fetchExpiringCreditCards(month, year);
const reminder = date === 21 ? true : false;
for (const card of cards) {
try {
const { id, CollectiveId, name } = card;
const brand = card.data.brand || 'credit card';
// Sometime, CollectiveId is missing, we'll need to see what to do for these
if (!CollectiveId) {
logger.info(`Missing CollectiveId for card ${id}, ignoring.`);
continue;
}
const collective = await models.Collective.findByPk(CollectiveId);
if (!collective) {
logger.info(`Missing collective for card ${id}, ignoring.`);
continue;
}
const adminUsers = await collective.getAdminUsers();
for (const adminUser of adminUsers) {
const { slug } = collective;
const collectiveName = collective.name;
const { email } = adminUser;
const userId = adminUser.id;
const data = {
id,
brand,
name,
userId,
CollectiveId,
collectiveName,
slug,
email,
reminder,
};
logger.info(
`Payment method ${data.id} for collective '${data.slug}' is expiring, sending an email to ${data.email}, reminder = ${reminder}`,
);
if (!process.env.DRY_RUN) {
await libPayments.sendExpiringCreditCardUpdateEmail(data);
}
}
} catch (e) {
console.log(e);
}
}
logger.info('Done sending credit card update emails.');
process.exit();
};
if (require.main === module) {
run();
}
| JavaScript | 0.000004 | @@ -400,17 +400,16 @@
ion' &&
-(
date !==
@@ -411,18 +411,18 @@
e !== 7
-%7C%7C
+&&
date !=
@@ -425,17 +425,16 @@
e !== 21
-)
&& !pro
|
8d0f979154506b2abe3fe8e414544650f929736e | disable the Normalize option on TopWord page | static/js/scripts_topword.js | static/js/scripts_topword.js | $(function() {
var totalGroups = 2, groupID;
$("#addOneGroup").click(function() {
var $block = $("#group-2");
var selected = [];
console.log($("#group-2 input:checked"));
$("#group-2 input:checked").each(function() {
selected.push($(this).attr('name'));
});
for(var i=0; i<selected.length;i++){
$("#"+selected[i]).removeAttr('checked');
}
var $clone = $block.clone();
$clone.appendTo("#addGroups");
totalGroups++;
groupID = "group-" + String(totalGroups);
var newGroup = $("#addGroups :last-child");
newGroup.attr("id", groupID);
$("#addGroups :last-child :nth-child(2)").contents().first().replaceWith("Group "+String(totalGroups));
console.log($(".groupLabels").css("position"));
});
$("#deleteOneGroup").click(function() {
if (totalGroups > 2) {
var newLastGroup = document.getElementById("group-" + String(totalGroups-1));
newLastGroup.nextElementSibling.remove();
totalGroups--;
}
});
document.getElementById("gettopword").disabled = true;
});
| JavaScript | 0 | @@ -953,16 +953,18 @@
%0A%09%7D);%0A%0A%09
+//
document
@@ -1010,12 +1010,239 @@
= true;%0A
+%0A%09%09function updateTokenizeCheckbox() %7B%0A%09%09%09$('input%5Btype=radio%5D%5Bname=normalizeType%5D').attr('disabled', 'true');%0A%09%09%09$('input%5Btype=radio%5D%5Bname=normalizeType%5D').parent('label').addClass('disabled');%0A%09%7D%0A%0A%09updateTokenizeCheckbox();%0A%0A
%7D);%0A
|
5c3297776b009f63a34bd483024d8482d6883968 | remove duplicate line from merge | src/SplitPane.js | src/SplitPane.js | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import Pane from './Pane';
import Resizer from './Resizer';
import VendorPrefix from 'react-vendor-prefix';
export default React.createClass({
propTypes: {
primary: React.PropTypes.oneOf(['first', 'second']),
minSize: React.PropTypes.number,
defaultSize: React.PropTypes.number,
size: React.PropTypes.number,
allowResize: React.PropTypes.bool,
split: React.PropTypes.oneOf(['vertical', 'horizontal'])
split: React.PropTypes.oneOf(['vertical', 'horizontal']),
onDragStarted: React.PropTypes.func,
onDragFinished: React.PropTypes.func,
},
getInitialState() {
return {
active: false,
resized: false
};
},
getDefaultProps() {
return {
split: 'vertical',
minSize: 0,
allowResize: true,
primary: 'first'
};
},
componentDidMount() {
this.setSize(this.props, this.state);
document.addEventListener('mouseup', this.onMouseUp);
document.addEventListener('mousemove', this.onMouseMove);
},
componentWillReceiveProps(props) {
this.setSize(props, this.state);
},
setSize(props, state) {
const ref = this.props.primary === 'first' ? this.refs.pane1 : this.refs.pane2;
let newSize;
if (ref) {
newSize = props.size || (state && state.draggedSize) || props.defaultSize || props.minSize;
ref.setState({
size: newSize
});
}
},
componentWillUnmount() {
document.removeEventListener('mouseup', this.onMouseUp);
document.removeEventListener('mousemove', this.onMouseMove);
},
onMouseDown(event) {
if(this.props.allowResize && !this.props.size) {
this.unFocus();
let position = this.props.split === 'vertical' ? event.clientX : event.clientY;
if (typeof this.props.onDragStarted === 'function') {
this.props.onDragStarted();
}
this.setState({
active: true,
position: position
});
}
},
onMouseMove(event) {
if(this.props.allowResize && !this.props.size) {
if (this.state.active) {
this.unFocus();
const ref = this.props.primary === 'first' ? this.refs.pane1 : this.refs.pane2;
if (ref) {
const node = ReactDOM.findDOMNode(ref);
if (node.getBoundingClientRect) {
const width = node.getBoundingClientRect().width;
const height = node.getBoundingClientRect().height;
const current = this.props.split === 'vertical' ? event.clientX : event.clientY;
const size = this.props.split === 'vertical' ? width : height;
const position = this.state.position;
const newPosition = this.props.primary === 'first' ? (position - current) : (current - position);
let newSize = size - newPosition;
if (newSize < this.props.minSize) {
newSize = this.props.minSize;
} else {
this.setState({
position: current,
resized: true
});
}
if (this.props.onChange) {
this.props.onChange(newSize);
}
this.setState({
draggedSize: newSize
});
ref.setState({
size: newSize
});
}
}
}
}
},
onMouseUp() {
if(this.props.allowResize && !this.props.size) {
if (this.state.active) {
if (typeof this.props.onDragFinished === 'function') {
this.props.onDragFinished();
}
this.setState({
active: false
});
}
}
},
unFocus() {
if (document.selection) {
document.selection.empty();
} else {
window.getSelection().removeAllRanges()
}
},
merge: function (into, obj) {
for (let attr in obj) {
into[attr] = obj[attr];
}
},
render() {
const {split, allowResize} = this.props;
let disabledClass = allowResize ? '' : 'disabled';
let style = {
display: 'flex',
flex: 1,
position: 'relative',
outline: 'none',
overflow: 'hidden',
MozUserSelect: 'text',
WebkitUserSelect: 'text',
msUserSelect: 'text',
userSelect: 'text'
};
if (split === 'vertical') {
this.merge(style, {
flexDirection: 'row',
height: '100%',
position: 'absolute',
left: 0,
right: 0
});
} else {
this.merge(style, {
flexDirection: 'column',
height: '100%',
minHeight: '100%',
position: 'absolute',
top: 0,
bottom: 0,
width: '100%'
});
}
const children = this.props.children;
const classes = ['SplitPane', this.props.className, split, disabledClass];
const prefixed = VendorPrefix.prefix({styles: style});
return (
<div className={classes.join(' ')} style={prefixed.styles} ref="splitPane">
<Pane ref="pane1" key="pane1" className="Pane1" split={split}>{children[0]}</Pane>
<Resizer ref="resizer" key="resizer" className={disabledClass} onMouseDown={this.onMouseDown} split={split} />
<Pane ref="pane2" key="pane2" className="Pane2" split={split}>{children[1]}</Pane>
</div>
);
}
});
| JavaScript | 0.000005 | @@ -464,73 +464,8 @@
ol,%0A
- split: React.PropTypes.oneOf(%5B'vertical', 'horizontal'%5D)%0A
@@ -611,25 +611,24 @@
opTypes.func
-,
%0A %7D,%0A%0A
|
ea8fcde444cc0db51c1186252d64447ff5c497fd | fix build | app/containers/AccountProvider/sagas/index.js | app/containers/AccountProvider/sagas/index.js | import { takeLatest, fork, takeEvery } from 'redux-saga/effects';
import { WEB3_CONNECT, WEB3_METHOD_CALL, CONTRACT_METHOD_CALL, SET_AUTH, CONTRACT_TX_SENDED } from '../actions';
import { injectedWeb3ListenerSaga } from './injectedWeb3ListenerSaga';
import { accountLoginSaga } from './accountLoginSaga';
import { websocketSaga } from './websocketSaga';
import { web3ConnectSaga } from './web3ConnectSaga';
import { unsupportedNetworkDetectSaga } from './unsupportedNetworkDetectSaga';
import { updateLoggedInStatusSaga } from './updateLoggedInStatusSaga';
import { web3MethodCallSaga, contractMethodCallSaga } from './web3CallsSagas';
import { contractTransactionSendSaga } from './txSagas';
import { txMonitoringSaga } from './txMonitoringSaga';
import intercomSaga from './intercomSagas';
export { getWeb3 } from '../utils';
// The root saga is what is sent to Redux's middleware.
export function* accountSaga() {
yield takeLatest(WEB3_CONNECT, web3ConnectSaga);
yield takeEvery(WEB3_METHOD_CALL, web3MethodCallSaga);
yield takeEvery(CONTRACT_METHOD_CALL, contractMethodCallSaga);
yield takeEvery(CONTRACT_TX_SENDED, txMonitoringSaga);
yield takeEvery(SET_AUTH, updateLoggedInStatusSaga);
yield fork(websocketSaga);
yield fork(accountLoginSaga);
yield fork(contractTransactionSendSaga);
yield fork(injectedWeb3ListenerSaga);
yield fork(unsupportedNetworkDetectSaga);
}
export default [
accountSaga,
];
| JavaScript | 0.000001 | @@ -746,52 +746,8 @@
ga';
-%0Aimport intercomSaga from './intercomSagas';
%0A%0Aex
|
c19e7d473f72a0b555c503ecd642e3ebea38a868 | add failing test for showFlat() | src/Util.test.js | src/Util.test.js | import { bitCount, adjustOctave, showFlat, prettyAccidental, SHARP, FLAT} from './Util';
test('bitCount(i)', () => {
expect(bitCount(0b0)).toEqual(0)
expect(bitCount(0b1)).toEqual(1)
expect(bitCount(0b01)).toEqual(1)
expect(bitCount(0b1111111111111)).toEqual(13)
expect(bitCount(0b1010101010101)).toEqual(7)
expect(bitCount(0b0101010101010)).toEqual(6)
});
test('adjustOctave(note, roller)', () => {
expect(adjustOctave("c", 0)).toEqual("c")
expect(adjustOctave("d#", 1)).toEqual("d#'")
expect(adjustOctave("eb", 2)).toEqual("eb''")
expect(adjustOctave("f", -1)).toEqual("F")
expect(adjustOctave("gb", -2)).toEqual("Gb,")
expect(adjustOctave("a#", -3)).toEqual("A#,,")
expect(adjustOctave("B", 1)).toEqual("b")
expect(adjustOctave("c'", -1)).toEqual("c")
})
test('showFlat(note)', () => {
expect(showFlat('d#')).toEqual('eb')
expect(showFlat('A#')).toEqual('Bb')
})
test('prettyAccidental(note)', () => {
expect(prettyAccidental('c#')).toEqual('c' + SHARP)
expect(prettyAccidental('bb')).toEqual('b' + FLAT)
})
| JavaScript | 0 | @@ -893,16 +893,55 @@
l('Bb')%0A
+ expect(showFlat('g#')).toEqual('ab')%0A
%7D)%0A%0Atest
|
26a871e3c4249e73531d297bd93064ddcb3f2648 | Update ember-i18n-cp-validations.js | app/initializers/ember-i18n-cp-validations.js | app/initializers/ember-i18n-cp-validations.js | import Ember from 'ember';
import ValidatorsMessages from '../validators/messages';
const {
Handlebars,
Logger:logger,
computed,
isPresent,
isEmpty,
inject,
get,
String: {
isHTMLSafe
}
} = Ember;
function unwrap(input) {
if ((typeof isHTMLSafe === 'function' && isHTMLSafe(input)) || (input instanceof Handlebars.SafeString)) {
return input.toString();
}
return input;
}
export function initialize() {
ValidatorsMessages.reopen({
i18n: inject.service(),
_regex: /\{{(\w+)\}}/g,
_prefix: computed('prefix', 'i18n.locale', function() {
const prefix = get(this, 'prefix');
if (typeof prefix === 'string') {
if (prefix.length) {
return prefix + '.';
}
return prefix;
}
return 'errors.';
}),
getDescriptionFor(attribute, options = {}) {
const i18n = get(this, 'i18n');
const prefix = get(this, '_prefix');
let key = `${prefix}description`;
let foundCustom;
if (!isEmpty(options.descriptionKey)) {
key = options.descriptionKey;
foundCustom = true;
} else if (!isEmpty(options.description)) {
return options.description;
}
if (i18n) {
if (i18n.exists(key)) {
return unwrap(i18n.t(key, options));
} else if (foundCustom) {
logger.warn(`Custom descriptionKey ${key} provided but does not exist in i18n translations.`);
}
}
return this._super(...arguments);
},
getMessageFor(type, options = {}) {
const i18n = get(this, 'i18n');
const prefix = get(this, '_prefix');
const key = isPresent(options.messageKey) ? options.messageKey : `${prefix}${type}`;
if (i18n && i18n.exists(key)) {
return this.formatMessage(unwrap(i18n.t(key, options)));
}
logger.warn(`[ember-i18n-cp-validations] Missing translation for validation key: ${key}\nhttp://offirgolan.github.io/ember-cp-validations/docs/messages/index.html`);
return this._super(...arguments);
}
});
}
export default {
name: 'ember-i18n-cp-validations',
initialize
};
| JavaScript | 0 | @@ -552,23 +552,8 @@
ix',
- 'i18n.locale',
fun
|
955897ddf6330d8cfde0ef78846cdcaf941c5d05 | use sendChannel instead of reload | src/api/index.js | src/api/index.js | import 'whatwg-fetch'
import {isEqual} from 'lodash'
import Action from '../action'
import Codec from './codec'
export default function API() {
return ({getState, dispatch}) => (next) => {
const api = (() => {
const app = `${location.protocol}//${location.host}`
const server = __env.production ? app : (
__env.server || 'http://localhost:5000'
)
const auth = () => location.href = `${server}/oauth/google?redirectUri=${
encodeURIComponent(app)
}`
const http = async (method, endpoint, data) => {
const response = await fetch(server + endpoint, {
method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
mode: __env.production ? 'same-origin' : 'cors',
credentials: __env.production ? 'same-origin' : 'include',
cache: 'default',
redirect: 'manual',
referrer: 'no-referrer'
})
if (response.ok) {
const data = await response.text()
if (data) {
return JSON.parse(data)
}
} else if (response.status == 401) {
auth()
} else {
throw new Error(`${method} ${endpoint}: ${response.statusText}`)
}
}
const websocket = (endpoint, handler) => {
const socket = new WebSocket(server.replace(/^http/i, 'ws') + endpoint)
const emit = handler({
send(data) {
socket.send(JSON.stringify(data))
}
})
socket.onclose = event => {
setTimeout(() => websocket(endpoint, handler), 5000)
}
socket.onerror = event => {
location.reload()
throw new Error('WebSocket failed')
}
socket.onopen = event => {
emit('ready', event)
}
socket.onmessage = event => {
if (event.data) {
const {eventName, ...eventData} = JSON.parse(event.data)
emit(eventName, eventData)
}
}
}
return {http, websocket}
})()
const fetchUser = async () => {
const user = await api.http('GET', '/api/user/userinfo')
next(Action.User.profile.create(
Codec.User.decode(user)
))
}
const fetchPlaylist = async () => {
const state = getState()
const sync = state.user.sync
if (!sync) return
const urls = sync.split('\n').filter(line => line)
if (!urls.length) return
const lists = await Promise.all(urls.map(url =>
api.http('POST', '/provider/songListWithUrl', {
url,
withCookie: state.user.cookie
})
))
const songs = [].concat(...lists.map(list => list.songs || []))
next(Action.Song.assign.create(
songs.map(Codec.Song.decode)
))
}
const sendChannel = async prevState => {
const state = getState()
const channel = state.user.channel
if (!channel) return
const prevChannel = prevState && prevState.user.channel
if (channel == prevChannel) return
await api.http('POST', `/api/channel/join/${channel}`)
}
const sendUpnext = async prevState => {
const state = getState()
const channel = state.user.channel
if (!channel) return
const song = Codec.Song.encode(
state.user.listenOnly ? undefined : state.song.playlist[0]
)
const prevSong = Codec.Song.encode(prevState && (
prevState.user.listenOnly ? undefined : prevState.song.playlist[0]
))
if (prevState && isEqual(song, prevSong)) return
await api.http('POST', `/api/channel/updateNextSong/${channel}`, {
...song,
withCookie: state.user.cookie
})
}
const sendSync = async () => {
const state = getState()
const channel = state.user.channel
if (!channel) return
const song = Codec.Song.encode(state.song.playing)
await api.http('POST', `/api/channel/finished/${channel}`,
song.songId ? song : null
)
}
const sendDownvote = async () => {
const state = getState()
const channel = state.user.channel
if (!channel) return
const song = Codec.Song.encode(state.song.playing)
await api.http('POST', `/api/channel/downVote/${channel}`,
song.songId ? song : null
)
}
const sendSearch = async () => {
const state = getState()
const keyword = state.search.keyword
if (keyword) {
const results = await api.http('POST', '/api/song/search', {
key: keyword,
withCookie: state.user.cookie
})
next(Action.Search.results.create(
results.map(Codec.Song.decode)
))
} else {
next(Action.Search.results.create([]))
}
}
(async () => {
await fetchUser()
await sendChannel()
api.websocket('/api/ws', ({send}) => (event, data) => {
switch (event) {
case 'ready':
sendUpnext()
break
case 'UserListUpdated':
next(Action.Channel.status.create({
members: data.users.map(Codec.User.decode)
}))
break
case 'Play':
next(Action.Song.play.create(data.song && {
...Codec.Song.decode(data.song),
player: data.user || '',
time: (Date.now() / 1000) - (data.elapsed || 0)
}))
if (data.downvote) {
next(Action.Song.downvote.create())
}
break
case 'NextSongUpdate':
next(Action.Song.preload.create(data.song && {
...Codec.Song.decode(data.song)
}))
break
}
})
})()
return async action => {
const prevState = getState()
next(action)
switch (action.type) {
case Action.User.profile.type:
await sendChannel(prevState)
await sendUpnext()
break
case Action.User.sync.type:
await fetchPlaylist()
await sendUpnext()
break
case Action.Song.prepend.type:
case Action.Song.append.type:
case Action.Song.remove.type:
case Action.Song.move.type:
case Action.Song.assign.type:
case Action.Song.shuffle.type:
await sendUpnext(prevState)
break
case Action.Song.ended.type:
await sendSync()
break
case Action.Song.downvote.type:
await sendDownvote()
break
case Action.Search.keyword.type:
await sendSearch()
break
}
}
}
}
| JavaScript | 0 | @@ -1647,16 +1647,60 @@
ut(() =%3E
+ %7B%0A emit('reconnect')%0A
websock
@@ -1720,16 +1720,28 @@
handler)
+%0A %7D
, 5000)%0A
@@ -1790,36 +1790,8 @@
%3E %7B%0A
- location.reload()%0A
@@ -5031,24 +5031,96 @@
h (event) %7B%0A
+ case 'reconnect':%0A sendChannel()%0A break%0A
ca
|
f30dabde7aa191a53fcd31e643e7e0f23f5ed624 | Fix typo [WAL-638] | app/scripts/components/cost-planning/utils.js | app/scripts/components/cost-planning/utils.js | // @ngInject
export default class CostPlanningFormatter {
constructor($filter) {
this.$filter = $filter;
}
formatFlavor(flavor) {
return `${flavor.name} (${this.$filter('formatFlavor')(flavor)})`;
}
formatPreset(preset) {
return `${preset.category} / ${preset.variant} ${preset.name}`;
}
formatPlan(item) {
const price = this.$filter('defaultCurrency')(item.price);
const preset = this.formatPreset(item.preset);
const flavor = this.formatFlavor(item.size);
return `${preset} — ${flavor} — ${price}`;
}
formatPresets(plan) {
return plan.optimized_presets.map(this.formatPlan.bind(this)).join('<br/>');
}
}
| JavaScript | 0.001012 | @@ -489,12 +489,14 @@
tem.
-size
+flavor
);%0A
|
93f264aad5aa407d74e260b8d5d4f44e0ca769b8 | extend tests | tests/services/manager.spec.js | tests/services/manager.spec.js |
"use strict";
import {Manager} from '../../src/services/Manager';
import {Collection} from '../../src/classes/Collection';
import {Model} from '../../src/classes/Model';
describe('service: Manager', () => {
let mngr;
let http;
angular.module('tests').service('testsServiceManager', Manager);
beforeEach(inject((testsServiceManager, $httpBackend) => {
mngr = testsServiceManager;
http = $httpBackend;
http.when('GET', '/tests/service/').respond([
{id: 1, foo: 'bar'},
{id: 2, foo: 'baz'},
{id: 3, foo: 'buz'}
]);
http.when('GET', '/tests/service/1/').respond({id: 1, foo: 'bar'});
}));
it("should list a Collection", () => {
http.expectGET('/tests/service/');
let coll;
mngr.list('/tests/service/').success(c => coll = c);
http.flush();
expect(coll instanceof Collection).toEqual(true);
expect(coll.length).toBe(3);
expect(coll.$dirty).toBe(false);
});
it("should find a Model", () => {
http.expectGET('/tests/service/1/');
let model;
mngr.find('/tests/service/1/').success(m => model = m);
http.flush();
expect(model instanceof Model).toEqual(true);
expect(model.$dirty).toBe(false);
model.foo = 'buz';
expect(model.$dirty).toBe(true);
});
});
| JavaScript | 0.000001 | @@ -1374,13 +1374,359 @@
%7D);%0A%0A
+ it('should not attempt to save pristine models', () =%3E %7B%0A let m = new Model();%0A m.$load(%7Bfoo: 'bar'%7D);%0A mngr.save(m);%0A %7D);%0A%0A it('should throw an exception when saving', () =%3E %7B%0A let m = new Model();%0A m.$load(%7Bfoo: 'bar'%7D);%0A m.foo = 'baz';%0A expect(() =%3E mngr.save(m)).toThrow();%0A %7D);%0A%0A
%7D);%0A%0A
|
b27958349517c421ca4170bbccc6482c2ce682d3 | add license header | src/refactor.js | src/refactor.js | 'use strict';
var refactor = require('esrefactor');
var esprima = require('esprima');
var estraverse = require('estraverse');
function getIdentifiers(source) {
var identifiers = [];
var ast = esprima.parse(source, {range: true});
// Get the identifiers for each of the variables in the first function expression
estraverse.traverse(ast, {
enter: function (node, parent) {
if ((parent && (parent.type === 'FunctionDeclaration' || parent.type === 'FunctionExpression'))) {
if (node.type === 'Identifier') {
identifiers.push(node.range);
} else {
this.break();
}
}
}
});
return identifiers;
}
module.exports = function (source, options) {
if (!source) {
throw new Error('No sourcecode');
}
if (!options) {
throw new Error('Missing options');
}
if (typeof source !== 'string' || !Array.isArray(options.replacements)) {
throw new Error('Invalid options');
}
var identifiers = getIdentifiers(source);
if (identifiers.length !== options.replacements.length) {
throw new Error('First function arguments count is not the same as replacements: ' + identifiers.length);
}
var ctx; //= new refactor.Context(source);
for (var i = 0; i < options.replacements.length; i++) {
var replacement = options.replacements[i];
var identifier = identifiers[i].slice(-1).pop();
ctx = new refactor.Context(source);
var node = ctx.identify(identifier);
source = ctx.rename(node, replacement);
identifiers = getIdentifiers(source);
}
//replace consecutive new lines
source = source.replace(/\n\s*\n/g, '\n');
// kill the use strict comment
source = source.replace(/"use strict";/, '');
return source;
};
| JavaScript | 0 | @@ -1,8 +1,625 @@
+/**%0A Copyright (c) 2016 Null Lines Pte Ltd%0A%0A Permission is hereby granted, free of charge, to any person obtaining a copy%0A of this software and associated documentation files (the %22Software%22), to deal%0A in the Software without restriction, including without limitation the rights%0A to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A copies of the Software, and to permit persons to whom the Software is%0A furnished to do so, subject to the following conditions:%0A%0A The above copyright notice and this permission notice shall be included in%0A all copies or substantial portions of the Software.%0A*/%0A%0A
'use str
|
6ed160942902ebf91dd4f3732b2982f06c8f3674 | declare loop variable in loop again | src/registry.js | src/registry.js | /*
* changes to previous patterns.register/scan mechanism
* - if you want initialised class, do it in init
* - init returns set of elements actually initialised
* - handle once within init
* - no turnstile anymore
* - set pattern.jquery_plugin if you want it
*/
define([
"jquery",
"./core/logger",
"./transforms",
"./utils",
// below here modules that are only loaded
"./compat"
], function($, logger, transforms, utils) {
var log = logger.getLogger('registry'),
jquery_plugin = utils.jquery_plugin;
var registry = {
patterns: {},
scan: function(content) {
var $content = $(content),
all = [], allsel,
pattern, $match, plog, name;
transforms.transformContent($content);
// selector for all patterns and patterns stored by their trigger
for (name in registry.patterns) {
pattern = registry.patterns[name];
if (pattern.trigger) {
all.push(pattern.trigger);
}
}
allsel = all.join(',');
// find all elements that belong to any pattern
$match = $content.filter(allsel);
$match = $match.add($content.find(allsel));
$match = $match.filter(':not(.cant-touch-this)');
// walk list backwards and initialize patterns inside-out.
//
// XXX: If patterns would only trigger via classes, we
// could iterate over an element classes and trigger
// patterns in order.
//
// Advantages: Order of pattern initialization controled
// via order of pat-classes and more efficient.
$match.toArray().reduceRight(function(acc, el) {
var $el = $(el);
for (name in registry.patterns) {
pattern = registry.patterns[name];
plog = logger.getLogger("pat." + name);
if ($el.is(pattern.trigger)) {
plog.debug('Initialising:', $el);
try {
pattern.init($el);
plog.debug('done.');
} catch (e) {
plog.error("Caught error:", e);
}
}
}
}, null);
},
// XXX: differentiate between internal and custom patterns
// _register vs register
register: function(pattern) {
if (!pattern.name) {
log.error("Pattern lacks name:", pattern);
return false;
}
if (registry.patterns[pattern.name]) {
log.error("Already have a pattern called: " + pattern.name);
return false;
}
// register pattern to be used for scanning new content
registry.patterns[pattern.name] = pattern;
// register pattern as jquery plugin
if (pattern.jquery_plugin) {
var pluginName = ("pattern-" + pattern.name)
.replace(/-([a-zA-Z])/g, function(match, p1) {
return p1.toUpperCase();
});
// XXX: here the pattern used to be jquery_plugin wrapped
$.fn[pluginName] = jquery_plugin(pattern);
}
log.debug('Registered pattern:', pattern.name, pattern);
return true;
}
};
$(document).on('patterns-injected.patterns', function(ev) {
registry.scan(ev.target);
$(ev.target).trigger('patterns-injected-scanned');
});
return registry;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
| JavaScript | 0 | @@ -728,14 +728,8 @@
plog
-, name
;%0A%0A
@@ -866,32 +866,36 @@
for (
+var
name in registry
@@ -1850,16 +1850,20 @@
for (
+var
name in
|
701359834084a595a7783a0e802a85d9fa6a1eb9 | Add Missing Logger to Rehasher | src/rehasher.js | src/rehasher.js | var FileSystemHelper = require('./filesystem_helper');
var FileSystem = require('fs');
var Url = require('url');
var Util = require('./util');
var HeaderUtil = require('./header_util');
var CacheClient = require('./cache_client');
var Rehashser = function (options) {
this.logger = options.logger;
this.options = options;
if (!FileSystemHelper.directoryExists(options.cacheDir)) {
this.logger.warn('Sorry, Looks like the cache directory does not exist!');
this.logger.warn('We can not rehash if there are no cache files available. Check the path and try again.');
this.logger.warn('Remember to use an absolute path to the cache directory.');
process.exit(1);
}
this.cacheClient = new CacheClient(options);
}
Rehashser.prototype.process = function () {
var self = this;
FileSystemHelper
.findDirectories(this.options.cacheDir)
.forEach(this.rehashWithOptions(this.options))
}
Rehashser.prototype.rehashWithOptions = function(options) {
var self = this;
return function (root) {
var notADirectory = function(file) {return !FileSystemHelper.directoryExists(file)};
FileSystemHelper
.findFileType(root, notADirectory)
.forEach(function (file) {
self.getContents(file)
.then(function(cachedContents) {
var originalCachedContents = Util.parseJSON(Util.stringify(cachedContents));
self.updateResponseWithOptions(cachedContents);
self.updateRequestWithOptions(cachedContents);
self.updateFile(file, cachedContents, originalCachedContents);
});
});
}
}
Rehashser.prototype.getContents = function(file) {
return new Promise(function(resolve, reject) {
FileSystem.readFile(file, function (err, data) {
if (err) {
reject(err);
} else {
var cachedData = Util.parseJSON(data);
resolve(cachedData);
}
});
});
}
Rehashser.prototype.updateResponseWithOptions = function(cacheContent) {
var reducedHeaders = HeaderUtil.removeHeaders(this.options.responseHeaderBlacklist, cacheContent.headers);
cacheContent.headers = reducedHeaders;
}
Rehashser.prototype.updateRequestWithOptions = function(cacheContent) {
var filteredHeaders = HeaderUtil.filterHeaders(this.options.cacheHeaders, cacheContent.request.headers);
cacheContent.request.headers = filteredHeaders;
// Update Base Server URL
var urlInfo = Url.parse(this.options.serverBaseUrl);
cacheContent.request.hostname = urlInfo.hostname;
cacheContent.request.headers = filteredHeaders;
cacheContent.request.port = Util.determinePort(urlInfo);
}
Rehashser.prototype.updateFile = function(filePath, cacheContent, originalCachedContents) {
var cacheClient = this.cacheClient;
if (cacheClient.isCached(cacheContent.request)) {
this.logger.info('Updating Contents for for File:', filePath);
cacheClient.record(cacheContent.request, cacheContent);
} else {
this.logger.info('Hash Changed for Request. Renaming File for Request: ', cacheContent.request.path);
cacheClient
.record(cacheContent.request, cacheContent)
.then(function() {
cacheClient.remove(originalCachedContents.request, filePath);
});
}
}
module.exports = Rehashser;
| JavaScript | 0 | @@ -223,16 +223,50 @@
lient');
+%0Avar Logger = require('./logger');
%0A%0Avar Re
@@ -316,22 +316,20 @@
r =
-options.l
+new L
ogger
+()
;%0A
|
0f16ee612863684fb8190ca8c542f52c107d3592 | Multiply depth by 18px | src/renderer.js | src/renderer.js | import { buildHTML, classNames, quoteattr } from './utils';
const defaultRowRenderer = (node) => {
const { id, label, children, state } = node;
const { depth, open, path, total, selected = false } = state;
const childrenLength = Object.keys(children).length;
const more = node.hasChildren();
let togglerContent = '';
if (more && open) {
togglerContent = '▼';
}
if (more && !open) {
togglerContent = '►';
}
const toggler = buildHTML('a', togglerContent, {
'class': (() => {
if (more && open) {
return classNames(
'tree-toggler'
);
}
if (more && !open) {
return classNames(
'tree-toggler',
'tree-closed'
);
}
return '';
})()
});
const title = buildHTML('span', quoteattr(label), {
'class': classNames('tree-title')
});
const treeNode = buildHTML('div', toggler + title, {
'class': 'tree-node',
'style': 'margin-left: ' + depth * 12 + 'px'
});
const treeItem = buildHTML('div', treeNode, {
'aria-id': id,
'aria-expanded': more && open,
'aria-depth': depth,
'aria-path': path,
'aria-selected': selected,
'aria-children': childrenLength,
'aria-total': total,
'class': classNames(
'tree-item',
{ 'tree-selected': selected }
)
});
return treeItem;
};
export {
defaultRowRenderer
};
| JavaScript | 0.999544 | @@ -1123,9 +1123,9 @@
* 1
-2
+8
+ '
|
feeb957e780aaf46f7dc8d084d108fceae806acc | Fix typo in docs | src/response.js | src/response.js | import { lowerCaseObjectKeys, assign } from './utils'
const REGEXP_CONTENT_TYPE_JSON = /^application\/json/
/**
* @typedef Response
* @param {Request} originalRequest, for auth it hides the password
* @param {Integer} responseStatus
* @param {String} responseData, defaults to null
* @param {Object} responseHeaders, defaults to an empty object ({})
* @param {Array<Error>} errors, defaults to an empty array ([])
*/
function Response (originalRequest, responseStatus, responseData, responseHeaders, errors) {
if (originalRequest.requestParams && originalRequest.requestParams.auth) {
const maskedAuth = assign({}, originalRequest.requestParams.auth, { password: '***' })
this.originalRequest = originalRequest.enhance({ auth: maskedAuth })
} else {
this.originalRequest = originalRequest
}
this.responseStatus = responseStatus
this.responseData = responseData !== undefined ? responseData : null
this.responseHeaders = responseHeaders || {}
this.errors = errors || []
this.timeElapsed = null
}
Response.prototype = {
/**
* @return {Request}
*/
request () {
return this.originalRequest
},
/**
* @return {Integer}
*/
status () {
// IE sends 1223 instead of 204
if (this.responseStatus === 1223) {
return 204
}
return this.responseStatus
},
/**
* Returns true if status is greater or equal 200 or lower than 400
*
* @return {Boolean}
*/
success () {
const status = this.status()
return status >= 200 && status < 400
},
/**
* Returns an object with the headers. Header names are converted to
* lowercase
*
* @return {Object}
*/
headers () {
return lowerCaseObjectKeys(this.responseHeaders)
},
/**
* Utility method to get a header value by name
*
* @param {String} name
*
* @return {String|Undefined}
*/
header (name) {
return this.headers()[name.toLowerCase()]
},
/**
* Returns the original response data
*/
rawData () {
return this.responseData
},
/**
* Returns the response data, if "Content-Type" is "application/json"
* it parses the response and returns an object
*
* @return {String|Object}
*/
data () {
let data = this.responseData
if (this.isContentTypeJSON()) {
try { data = JSON.parse(this.responseData) } catch (e) {}
}
return data
},
isContentTypeJSON () {
return REGEXP_CONTENT_TYPE_JSON.test(this.headers()['content-type'])
},
/**
* Returns the last error instance that caused the request to fail
*
* @return {Error|null}
*/
error () {
const lastError = this.errors[this.errors.length - 1] || null
if (typeof lastError === 'string') {
return new Error(lastError)
}
return lastError
},
/**
* Enhances current Response returning a new Response
*
* @param {Object} extras
* @param {Integer} extras.status - it will replace the current status
* @param {String} extras.rawData - it will replace the current rawStatus
* @param {Object} extras.headers - it will be merged with current headers
* @param {Error} extras.error - it will be added to the list of errors
*
* @return {Response}
*/
enhance (extras) {
return new Response(
this.request(),
extras.status || this.status(),
extras.rawData || this.rawData(),
assign({}, this.headers(), extras.headers),
[...this.errors, extras.error]
)
}
}
export default Response
| JavaScript | 0.001431 | @@ -3018,22 +3018,20 @@
rent raw
-Status
+Data
%0A *
|
3b3c1dbdfb1f74c80c3c4db333803fc918a8eedf | Document FrequencyMap with YUIDoc comments. | src/scripts/FrequencyMap.es6 | src/scripts/FrequencyMap.es6 | class FrequencyMap {
constructor () {
this.frequencies = [ ];
for (let i=0; i < 128; i++) {
this.frequencies.push(this.calculateFrequency(i));
}
}
getNoteIndex(octave, note) {
if (note >= 0 && note <= 12) {
return octave*12 + note;
}
return 0;
}
getFrequency(note) {
if (note >= 0 && note < 128) {
return this.frequencies[note];
}
return 0;
}
generateOctave(startingNote) {
let octave = []
for (let i=startingNote; i <= startingNote+12; i++)
octave.push(this.calculateFrequency(i))
return octave;
}
calculateFrequency(note) {
const twelveRoot2 = 1.0594630943592952645
const a = 440
let relativeNote = note - 69
return a * Math.pow(twelveRoot2, relativeNote);
}
}
| JavaScript | 0 | @@ -1,340 +1,1213 @@
-class FrequencyMap %7B%0A%0A constructor () %7B%0A this.frequencies = %5B %5D;%0A for (let i=0; i %3C 128; i++) %7B%0A this.frequencies.push(this.calculateFrequency(i));%0A %7D%0A %7D%0A%0A getNoteIndex(octave, note) %7B%0A if (note %3E= 0 && note %3C= 12) %7B%0A return octave*12 + note;%0A %7D%0A return 0;%0A %7D%0A
+/**%0A* FrequencyMap converts notes into frequencies needed for synth oscillators.%0A*%0A* @class FrequencyMap%0A*/%0Aclass FrequencyMap %7B%0A%0A /**%0A * Creates a new FrequencyMap object.%0A *%0A * Look, we need an object here because what we really want is a lookup table.%0A * Calculating the frequencies is sloooow because it involves Math.pow, so we%0A * precompute them and store them in this object.%0A *%0A * @constructor%0A */%0A constructor () %7B%0A this.frequencies = %5B %5D;%0A for (let i=0; i %3C 128; i++) %7B%0A this.frequencies.push(this.calculateFrequency(i));%0A %7D%0A %7D%0A%0A /**%0A * Returns the MIDI note index for a given octave/note combination.%0A *%0A * @param %7BNumber%7D octave the octave offset. For example, Middle C is Octave 5%0A * @param %7BNumber%7D note The note, a number between 0 and 12, starting with C.%0A */%0A getNoteIndex(octave, note) %7B%0A if (note %3E= 0 && note %3C= 12) %7B%0A return octave*12 + note;%0A %7D%0A return 0;%0A %7D%0A%0A /**%0A * Returns the frequency for a note index.%0A * The note indices should be the same as what General MIDI uses.%0A *%0A * @param %7Bnumber%7D note A note index between 0 and 127%0A */
%0A
@@ -1542,24 +1542,144 @@
ave;%0A %7D%0A%0A
+ /**%0A * Calculates a frequency for a given note.%0A * You should use getFrequency instead.%0A * @private%0A */%0A
calculat
|
53d6be8e7279b5c572fd77bf592120d80aa06363 | Fix bug when pushing event to events list | src/schedule.js | src/schedule.js | import {WeekDate} from './suppClasses'
export class Schedule{
/*
solution = { event1 : [eventOption choosen],
event2 : [eventOption choosen],
...
}
schedule = {
'Monday' : [eventOption1, eventOption2],
...
}
*/
constructor(solution) {
this.schedule = this.processWorkdays(solution);
this.events = this.getEvents(solution);
}
parse(solution){
let shedule = [];
for (var event of solution.keys())
shedule.push(solution.get(event[0]));
}
/*
returns {
'Monday' : [EventOption1, EventOption2],
...
}
*/
processWorkdays(solution){
let temp_workdays = new Map();
const week_days = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
for (var week_day of week_days)
temp_workdays.set(week_day, []);
for (var event of solution.keys())
for (var instance of solution.get(event)[0].instances)
temp_workdays.get(week_days[instance.start.day]).push(solution.get(event)[0]);
let workdays = new Map();
for (var day of temp_workdays.keys())
workdays.set(day, new Workday(temp_workdays.get(day)));
return workdays;
}
/*
return {
'title' : event name,
'start' : start week date,
'end' : end week date
}
*/
getEvents(solution){
let events = []
var event;
for (var eventOption of solution.keys()){
event = new Map();
event.set('title', solution.get(eventOption)[0].event.name);
event.set('start', solution.get(eventOption)[0].instances[0].start);
event.set('end', solution.get(eventOption)[0].instances[0].end);
events.push()
}
return events;
}
}
// todo: how to handle with events that starts in one day but ends in another
export class Workday{
constructor(events){
this.events = events;
//this.daily_workload = this.daily_workload();
//this.begin_morning = ;
//this.end_morning = ;
//this.begin_afternoon = ;
//this.end_afternoon = ;
}
daily_workload(){
let workload = 0;
for (var event of this.events)
workload += WeekDate.interval(event.start, event.end);
return workload;
}
}
| JavaScript | 0 | @@ -1692,17 +1692,23 @@
ts.push(
-)
+event);
%0A %09%7D%0A
|
a48b3c263b019f6f8efac0b4531cbd01be2ae668 | Use https URL for bing | src/bing/Bing.js | src/bing/Bing.js | /*
* MapEmAll is licensed under the conditions of the MIT License (MIT)
*
* Copyright (c) 2015-2016 Philip Stöhrer
* All rights reserved.
*
* See https://raw.githubusercontent.com/stophi-dev/MapEmAll/master/LICENSE for details.
*/
define(['JSLoader', 'bing/BingMap'], function (loader, BingMap) {
'use strict';
function preventMapToBeGloballyAbsolute(htmlElement) {
var style = window.getComputedStyle(htmlElement, null);
if (style.position === 'static') {
htmlElement.style.position = 'relative';
}
}
return {
loadMap: function (options, callback) {
var callbackName = 'initBingMap_' + loader.makeId(10);
// Bing maps positions the map absolute.
// To prevent overlaps and to get a similar behavior like
// other providers, we adjust the position of htmlContainer:
preventMapToBeGloballyAbsolute(options.htmlContainer);
window[callbackName] = function () {
delete window[callbackName];
callback(new BingMap(options));
};
loader.loadjsfile('http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&onscriptload=' + callbackName);
}
};
}); | JavaScript | 0.000008 | @@ -1138,19 +1138,24 @@
le('http
+s
://
+ecn.
dev.virt
@@ -1200,16 +1200,20 @@
x?v=7.0&
+s=1&
onscript
|
39a80743adc8b3fd04a58445c449b6ba242b1120 | refresh page after logout | stores/AccountStore/index.js | stores/AccountStore/index.js | /*
* AccountStore store
*
*/
import { types as t, getParent } from 'mobx-state-tree'
import R from 'ramda'
import store from 'store'
import { markStates, makeDebugger, stripMobx, BStore } from '../../utils'
import { User, EmptyUser } from '../SharedModel'
/* eslint-disable no-unused-vars */
const debug = makeDebugger('S:AccountStore')
/* eslint-enable no-unused-vars */
const AccountStore = t
.model('AccountStore', {
user: t.optional(User, {}),
isValidSession: t.optional(t.boolean, false),
// subscribedCommunites: ...
})
.views(self => ({
get root() {
return getParent(self)
},
get accountInfo() {
return {
...stripMobx(self.user),
}
},
get subscribedCommunities() {
const {
user: { subscribedCommunities },
} = self
return {
...stripMobx(subscribedCommunities),
}
},
get isLogin() {
return self.isValidSession
},
}))
.actions(self => ({
afterCreate() {
const user = BStore.get('user')
console.log('AccountStore get user: ', user)
if (user) {
console.log('AccountStore afterCreate: ', user)
/* self.updateAccount(user) */
}
},
logout() {
self.user = EmptyUser
self.root.preview.close()
store.remove('user')
store.remove('token')
self.isValidSession = false
},
updateAccount(sobj) {
const user = R.merge(self.user, { ...sobj })
self.markState({ user })
},
updateSessionState(sessionState) {
const { isValid, user } = sessionState
if (isValid) {
self.isValidSession = isValid
return self.updateAccount(user)
}
// if not valid then empty user data
self.user = EmptyUser
},
loadSubscribedCommunities(data) {
self.user.subscribedCommunities = data
},
addSubscribedCommunity(community) {
const {
user: {
subscribedCommunities: { entries },
},
} = self
self.user.subscribedCommunities.entries = R.insert(0, community, entries)
self.user.subscribedCommunities.totalCount += 1
self.root.communitiesContent.toggleSubscribe(community)
},
removeSubscribedCommunity(community) {
const {
user: {
subscribedCommunities: { entries },
},
} = self
const index = R.findIndex(R.propEq('id', community.id), entries)
self.user.subscribedCommunities.entries = R.remove(index, 1, entries)
self.user.subscribedCommunities.totalCount -= 1
self.root.communitiesContent.toggleSubscribe(community)
},
markState(sobj) {
markStates(sobj, self)
},
}))
export default AccountStore
| JavaScript | 0.000001 | @@ -139,16 +139,18 @@
import %7B
+%0A
markSta
@@ -153,16 +153,18 @@
kStates,
+%0A
makeDeb
@@ -169,16 +169,18 @@
ebugger,
+%0A
stripMo
@@ -186,16 +186,29 @@
obx,
+%0A
BStore
-
+,%0A Global,%0A
%7D fr
@@ -1056,137 +1056,27 @@
-console.log('AccountStore get user: ', user)%0A if (user) %7B%0A console.log('AccountStore afterCreate: ', user)%0A /*
+if (user) %7B%0A
sel
@@ -1096,19 +1096,16 @@
nt(user)
- */
%0A %7D
@@ -1275,16 +1275,53 @@
= false
+%0A%0A Global.location.reload(false)
%0A %7D,%0A
|
4f61b1e4b70bcd804fe98abddc84b46622b0e085 | Make MAX_CHARACTERS configurable | usability/limit_output/main.js | usability/limit_output/main.js | // Restrict output in a codecell to a maximum length
define([
'base/js/namespace',
'jquery',
'notebook/js/outputarea',
'base/js/dialog',
'notebook/js/codecell',
'services/config'
], function(IPython, $, oa, dialog, cc, config) {
"use strict";
var config = new configmod.ConfigSection('limit_output');
config.load();
config.loaded.then(function() {
if (config.data.limit_output) {
var maxc = Object.getOwnPropertyNames(config.data.limit_output);
console.log('limit_output', limit_output)
}
});
var MAX_CHARACTERS = 10000; // maximum number of characters the output area is allowed to print
oa.OutputArea.prototype._handle_output = oa.OutputArea.prototype.handle_output;
oa.OutputArea.prototype.handle_output = function (msg){
if(!this.count){this.count=0}
if(!this.max_count){ this.max_count = MAX_CHARACTERS }
this.count = this.count+String(msg.content.text).length;
if(this.count > this.max_count){
if(!this.drop){
console.log("Output exceeded", this.max_count, "characters. Further output muted.");
msg.content.text = msg.content.text + "**OUTPUT MUTED**";
this.drop=true;
return this._handle_output(msg);
}
return
}
return this._handle_output(msg);
}
cc.CodeCell.prototype._execute = cc.CodeCell.prototype.execute;
cc.CodeCell.prototype.execute = function(){
// reset counter on execution.
this.output_area.count = 0;
this.output_area.drop = false;
return this._execute();
}
});
| JavaScript | 0.998637 | @@ -196,16 +196,37 @@
/config'
+,%0A 'base/js/utils'
%0A%5D, func
@@ -264,16 +264,26 @@
, config
+mod, utils
) %7B%0A
@@ -296,16 +296,167 @@
trict%22;%0A
+ var MAX_CHARACTERS = 10000; // maximum number of characters the output area is allowed to print%0A%0A var base_url = utils.get_body_data(%22baseUrl%22)
%0A var
@@ -494,29 +494,47 @@
ection('
-limit_output'
+notebook', %7Bbase_url: base_url%7D
);%0A c
@@ -596,24 +596,88 @@
-if (config.data.
+console.log(%22config.data:%22,config.data)%0A if (config.data.hasOwnProperty('
limi
@@ -684,18 +684,20 @@
t_output
+'
)
+)
%7B%0A
@@ -706,46 +706,25 @@
-var maxc = Object.getOwnPropertyNames(
+MAX_CHARACTERS =
conf
@@ -743,17 +743,16 @@
t_output
-)
;%0A
@@ -786,144 +786,63 @@
tput
-', limit_output)%0A %7D%0A %7D);%0A%0A var MAX_CHARACTERS = 10000; // maximum number of characters the output area is allowed to print
+ to ', MAX_CHARACTERS, 'characters')%0A %7D%0A %7D);%0A
%0A
@@ -1577,16 +1577,35 @@
;%0A %7D%0A
+console.log(%22AAA%22);
%0A cc.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.