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
|
---|---|---|---|---|---|---|---|
a4a46aef9a958837c026cae957e05f6ff88d02c7
|
Set virtual cursor position on click as well as move
|
unmaze-ui.js
|
unmaze-ui.js
|
/* unmaze canvas user interface
Copyright 2017 Mariusz Skoneczko
Licensed under the MIT license
*/
const TILE_SIZE = 20;
const UI_MODE = {
WATCHING: 0,
EDITING: 1
};
const TYPE2COLOR = {};
TYPE2COLOR[MAZE.FREE] = "white";
TYPE2COLOR[MAZE.WALL] = "black";
TYPE2COLOR[MAZE.START] = "yellow";
TYPE2COLOR[MAZE.END] = "green";
TYPE2COLOR[MAZE.TRAIL] = "orange";
const CURSOR_COLOR = "gray";
const ROBOT_COLOR = "red";
let canvas, ctx, ui_maze, ui_mode;
let cursor_pos = {x: null, y: null};
canvas = document.getElementById("unmaze-canvas");
ctx = canvas.getContext("2d");
const MAZE_WIDTH = canvas.width / TILE_SIZE;
const MAZE_HEIGHT = canvas.height / TILE_SIZE;
function maze_setup() {
ui_maze = new Maze(MAZE_WIDTH, MAZE_HEIGHT);
ui_maze.setStart(0, 0);
ui_maze.setEnd(MAZE_WIDTH - 1, MAZE_HEIGHT - 1);
ui_maze.robotToStart();
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < MAZE_WIDTH; i++) {
for (let j = 0; j < MAZE_HEIGHT; j++) {
ctx.fillStyle = TYPE2COLOR[ui_maze.maze[i][j].type];
ctx.fillRect(i * TILE_SIZE, j * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
ctx.fillStyle = ROBOT_COLOR;
ctx.fillRect(ui_maze.robot.x * TILE_SIZE, ui_maze.robot.y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
if (cursor_pos.x !== null && cursor_pos.y !== null) {
ctx.strokeStyle = CURSOR_COLOR;
ctx.strokeRect(cursor_pos.x * TILE_SIZE, cursor_pos.y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
function move_mouse(e) {
let rect = canvas.getBoundingClientRect();
cursor_pos.x = Math.floor((e.clientX - rect.left) / TILE_SIZE);
cursor_pos.y = Math.floor((e.clientY - rect.top) / TILE_SIZE);
render();
}
function toggle_tile() {
if (ui_maze.maze[cursor_pos.x][cursor_pos.y].type === MAZE.FREE) {
ui_maze.maze[cursor_pos.x][cursor_pos.y].type = MAZE.WALL;
} else if (ui_maze.maze[cursor_pos.x][cursor_pos.y].type === MAZE.WALL) {
ui_maze.maze[cursor_pos.x][cursor_pos.y].type = MAZE.FREE;
}
render();
}
function no_cursor() {
cursor_pos = {x: null, y: null};
render();
}
function editing_mode() {
ui_mode = UI_MODE.EDITING;
canvas.addEventListener("mousemove", move_mouse);
canvas.addEventListener("click", toggle_tile);
canvas.addEventListener("mouseout", no_cursor);
}
function watching_mode() {
ui_mode = UI_MODE.WATCHING;
canvas.removeEventListener("mousemove", move_mouse);
canvas.removeEventListener("click", toggle_tile);
canvas.removeEventListener("mouseout", no_cursor);
}
function full_reset() {
maze_setup();
render();
}
document.getElementById("reset-button").addEventListener("click", full_reset);
maze_setup();
editing_mode();
render();
|
JavaScript
| 0 |
@@ -1535,26 +1535,30 @@
unction
-move_mouse
+set_cursor_pos
(e) %7B%0A
@@ -1733,24 +1733,75 @@
TILE_SIZE);%0A
+%7D%0A%0Afunction move_mouse(e) %7B%0A set_cursor_pos(e);%0A
render()
@@ -1826,20 +1826,44 @@
le_tile(
+e
) %7B%0A
+ set_cursor_pos(e);%0A
if (
|
d3b48e536f0c0107401ae36d51c93c338844be7c
|
Remove Edge test from SauceLabs temporarily
|
karma.ci.conf.js
|
karma.ci.conf.js
|
module.exports = function (config) {
config.set({
frameworks: ['mocha', 'karma-typescript'],
concurrency: 3,
colors: true,
logLevel: config.LOG_INFO,
files: [
{ pattern: 'src/js/**/*.js' },
{ pattern: 'test/**/*.spec.js' }
],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: "ChromeHeadless",
flags: [ "--no-sandbox" ]
},
/*
'SL_WINDOWS_IE10': {
base: 'SauceLabs',
browserName: 'Internet Explorer',
version: '10.0',
platform: 'Windows 8',
},
'SL_WINDOWS_IE11': {
base: 'SauceLabs',
browserName: 'Internet Explorer',
version: '11.0',
platform: 'Windows 10',
},
*/
'SL_WINDOWS_EDGE': {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
version: 'latest',
platform: 'Windows 10',
},
'SL_WINDOWS_FIREFOX': {
base: 'SauceLabs',
browserName: 'Firefox',
version: 'latest',
platform: 'Windows 10',
},
'SL_WINDOWS_CHROME': {
base: 'SauceLabs',
browserName: 'Chrome',
version: 'latest',
platform: 'Windows 10',
},
'SL_LINUX_FIREFOX': {
base: 'SauceLabs',
browserName: 'Firefox',
version: 'latest',
platform: 'Linux',
},
'SL_MACOS_CHROME': {
base: 'SauceLabs',
browserName: 'Chrome',
version: 'latest',
platform: 'macOS 10.13',
},
/*
'SL_MACOS_SAFARI': {
base: 'SauceLabs',
browserName: 'Safari',
version: 'latest',
platform: 'macOS 10.13',
},
*/
},
// Chrome, ChromeCanary, Firefox, Opera, Safari, IE
browsers: ['ChromeHeadlessNoSandbox',
'SL_WINDOWS_EDGE', 'SL_WINDOWS_FIREFOX', 'SL_WINDOWS_CHROME',
'SL_LINUX_FIREFOX', 'SL_MACOS_CHROME',
],
sauceLabs: {
testName: 'unit tests for summernote',
startConnect: false,
username: 'summernoteis',
accessKey: '3d57fd7c-72ea-4c79-8183-bbd6bfa11cc3',
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
build: process.env.TRAVIS_BUILD_NUMBER,
tags: [process.env.TRAVIS_BRANCH, process.env.TRAVIS_PULL_REQUEST],
},
preprocessors: {
'src/js/**/*.js': ['karma-typescript'],
'test/**/*.spec.js': ['karma-typescript']
},
reporters: ['dots', 'karma-typescript', 'coverage', 'coveralls'],
coverageReporter: {
type: 'lcov',
dir: 'coverage/',
includeAllSources: true
},
browserNoActivityTimeout: 60000,
karmaTypescriptConfig: {
tsconfig: './tsconfig.json',
include: [
'test/**/*.spec.js'
],
bundlerOptions: {
entrypoints: /\.spec\.js$/,
transforms: [require("karma-typescript-es6-transform")()],
exclude: [
'node_modules'
],
sourceMap: true,
addNodeGlobals: false
},
compilerOptions: {
"module": "commonjs"
}
}
});
};
|
JavaScript
| 0 |
@@ -384,33 +384,24 @@
%5D%0A %7D,%0A
- /*%0A
'SL_WI
@@ -707,33 +707,24 @@
',%0A %7D,%0A
- */%0A
'SL_WI
@@ -1491,17 +1491,8 @@
%7D,%0A
- /*%0A
@@ -1510,24 +1510,24 @@
_SAFARI': %7B%0A
+
base
@@ -1645,17 +1645,8 @@
%7D,%0A
- */%0A
@@ -1704,16 +1704,16 @@
ari, IE%0A
+
brow
@@ -1750,76 +1750,8 @@
x',%0A
- 'SL_WINDOWS_EDGE', 'SL_WINDOWS_FIREFOX', 'SL_WINDOWS_CHROME',%0A
|
a9abdad5bdfdf5f578e93a812b41a092596cf083
|
update demo description
|
examples/direct-calls/index.js
|
examples/direct-calls/index.js
|
"use strict";
/**
*
*/
let path = require("path");
let { ServiceBroker } = require("moleculer");
let ApiService = require("../../index");
// Create broker
let broker = new ServiceBroker({
nodeID: "api",
transporter: "NATS",
});
// Load API Gateway
broker.createService(ApiService, {
settings: {
routes: [
{
path: "/node-1",
aliases: {
"GET /where": "test.where"
},
callOptions: {
nodeID: "node-1"
}
},
{
path: "/node-2",
aliases: {
"GET /where": "test.where"
},
callOptions: {
nodeID: "node-2"
}
},
]
}
});
const node1 = new ServiceBroker({
nodeID: "node-1",
transporter: "NATS",
});
node1.loadService(path.join(__dirname, "..", "test.service.js"));
const node2 = new ServiceBroker({
nodeID: "node-2",
transporter: "NATS",
});
node2.loadService(path.join(__dirname, "..", "test.service.js"));
// Start server
broker.Promise.all([broker.start(), node1.start(), node2.start()]).then(() => broker.repl());
|
JavaScript
| 0 |
@@ -14,16 +14,320 @@
%0A%0A/**%0A *
+ This example demonstrate to lock route aliases to a dedicated nodeID.%0A * The nodeID can be defined in the %60route.callOptions%60.%0A *%0A * Example:%0A *%0A * Call service only on %60node-1%60%0A * %09%09GET http://localhost:3000/node-1/where%0A *%0A * Call service only on %60node-2%60%0A * %09%09GET http://localhost:3000/node-2/where
%0A */%0A%0Ale
|
fc7a3b45f248ffc22f6ea466ef9b2cfa1068c33d
|
Update unit tests for basic-culture-selector
|
src/basic-culture-selector/test/basic.tests.js
|
src/basic-culture-selector/test/basic.tests.js
|
suite('basic', function() {
this.timeout(2000);
var container = document.getElementById('container');
teardown(function () {
container.innerHTML = '';
});
test('instantiation', function(done) {
var fixture = document.createElement('basic-culture-selector');
container.appendChild(fixture);
flush(function() {
assert(fixture);
done();
});
});
test('default name', function(done) {
var fixture = document.createElement('basic-culture-selector');
container.appendChild(fixture);
assert.equal(fixture.name, 'en');
done();
});
test('set name', function(done) {
var fixture = document.createElement('basic-culture-selector');
container.appendChild(fixture);
fixture.addEventListener("basic-culture-changed", function(event) {
var culture = event.detail.culture;
// Skip the default setting notification
if (fixture.name == 'en') {
fixture.name = 'fr';
return;
}
assert.equal(fixture.name, 'fr');
assert(culture);
assert(culture.cldr);
assert(culture.cldr.locale);
var locale = culture.cldr.locale;
var numberFormatter = Globalize(locale).numberFormatter();
var dateFormatter = Globalize(locale).dateFormatter();
var currencyFormatter = Globalize(locale).currencyFormatter('USD');
assert.equal(dateFormatter(new Date('May 6, 1994')), '6/5/1994');
assert.equal(numberFormatter(1234567.89), '1 234 567,89');
assert.equal(currencyFormatter(1234.56), '1 234,56 $US');
done();
});
});
});
|
JavaScript
| 0 |
@@ -318,13 +318,57 @@
f
-lush(
+ixture.addEventListener('basic-culture-changed',
func
@@ -368,24 +368,29 @@
', function(
+event
) %7B%0A as
@@ -573,24 +573,98 @@
d(fixture);%0A
+ fixture.addEventListener('basic-culture-changed', function(event) %7B%0A
assert.e
@@ -693,24 +693,26 @@
');%0A
+
done();%0A
%7D);%0A%0A
@@ -703,16 +703,24 @@
done();%0A
+ %7D);%0A
%7D);%0A%0A
@@ -887,17 +887,17 @@
istener(
-%22
+'
basic-cu
@@ -913,9 +913,9 @@
nged
-%22
+'
, fu
|
08fa478b9dba6dfd79f88350e221966e8e8e9a26
|
Tweak random channel with new suffixes.
|
src/behaviors/random-channel/random-channel.js
|
src/behaviors/random-channel/random-channel.js
|
import Behavior from '../behavior.js';
class RandomChannel extends Behavior {
constructor(settings = {}) {
settings.name = 'Random Channel';
super(settings);
}
initialize(bot) {
super.initialize(bot);
this.scheduleJob('* * * * *', () => {
bot.say(this.settings.sayInChannel, 'Once a minute, I\'ll say a random room name');
this.sayRandomChannel(bot);
});
}
sayRandomChannel(bot) {
const channels = bot._api('channels.list', { token: bot.token, exclude_archived: 1 });
channels.then(data => {
let randomChannel;
do {
randomChannel = data.channels[Math.floor(Math.random() * data.channels.length)];
} while (['all-staff', 'announcements'].includes(randomChannel.name));
const purposeless = '[no purpose set, but it\'s probably pretty good anyway]',
channelPurpose = randomChannel.purpose.value === '' ? purposeless
: randomChannel.purpose.value,
period = ['.', '!', '?'].includes(channelPurpose.slice(-1)) ? '' : '.',
randomChannelMessage = `The random channel of the day is ` +
`<#${randomChannel.id}|${randomChannel.name}>: ` +
`${channelPurpose}${period} Check it out, yo!`;
bot.say(this.settings.sayInChannel, randomChannelMessage, {
icon_emoji: ':slack:'
});
}, error => {
bot.log(error, true);
});
}
}
export default RandomChannel;
|
JavaScript
| 0 |
@@ -31,16 +31,218 @@
ior.js';
+%0Aimport _sample from 'lodash/sample';%0A%0A// Series of ways to end the random channel statement.%0Aconst CHECK_IT_OUT = %5B%0A 'Check it out, yo!',%0A 'Join in on the fun!',%0A 'Come see what you%5C're missing!'%0A%5D;
%0A%0Aclass
@@ -440,19 +440,19 @@
uleJob('
-* *
+0 9
* * *',
@@ -464,99 +464,8 @@
%3E %7B%0A
- bot.say(this.settings.sayInChannel, 'Once a minute, I%5C'll say a random room name');%0A%0A
@@ -942,16 +942,57 @@
yway%5D',%0A
+ checkIt = _sample(CHECK_IT_OUT),%0A
@@ -1348,33 +1348,26 @@
period%7D
-C
+$%7Bc
heck
- it out, yo!
+It%7D
%60;%0A%0A
|
812f07b96c2d05a1aaa0a90bc5a847d3da6bbe7c
|
add multiple audio source support for TagLoader class.
|
modules/Preload/TagLoader.js
|
modules/Preload/TagLoader.js
|
/**
* @module Preload
* @namespace Preload
*/
var TW = TW || {};
define(['../Utils/inherit', '../Event/EventProvider', '../Utils/Polyfills'], function(inherit, EventProvider) {
TW.Preload = TW.Preload || {};
/**
* TagLoader is a loader using HTML tags. It hides differences between each tags and keep one way
* to load all types of elements.
*
* For each request, yuo are assured than a `complete` or `error` event is called, only one time.
*
* The resulting tag is availlable even before the loading was done.
*
* TagLoader support many objects types:
*
* - `"image"`
* an `<img>` HTML tag is returned.
* - `"sound"`
* an `<audio>` HTML tag is created and returned.
* - `"script"`
* A HTML script element is returned, and can be added to the DOM.
* **Note: Scripts are called automatically, before the complete event.
* For loading the script whithout execute it, you should use
* the {{#crossLink "Preload.XHRLoader"}}XHRLoader{{/crossLink}} class**
* - `"css"`
* A link tag is created and returned.
* **Note: style tags are inserted automatically in the DOM, before the complete event.
* For loading the script whithout insert it to the DOM, you should use
* the {{#crossLink "Preload.XHRLoader"}}XHRLoader{{/crossLink}} class**
*
*
* @class TagLoader
* @param path Url to the remote file
* @param {String} [type="text"] type of the ressource.
* @extends Event.EventProvider
* @constructor
*/
function TagLoader(path, type) {
EventProvider.call(this);
/**
* Determine if this loader has completed already.
* @property loaded
* @type Boolean
* @default false
*/
this.loaded = false;
/**
* Type given to constructor.
*
* @property {String} type
*/
this.type = type;
/**
* URL of the ressource
*
* @property {String} _path
* @private
*/
this._path = path;
var tag;
switch(type) {
case 'image':
tag = document.createElement('img');
break;
case 'svg':
tag = document.createElement('TODO');//TODO: implémenter le bon format !!!
break;
case 'sound':
tag = document.createElement('audio');
break;
case 'css':
tag = document.createElement('link');
tag.rel = "stylesheet";
tag.type = "text/css";
break;
case 'script':
tag = document.createElement('script');
tag.type = 'text/javascript';
break;
default:
throw "Type not supported: " + type;
}
/**
* HTML tag
*
* @property {HTMLElement} _tag
* @private
*/
this._tag = tag;
/**
* Event called when the loading is fully done.
*
* @event complete
* @param {HTMLElement} result the HTMLElement object resulting
*/
/**
* Event called when an error occurs.
* The download is stopped after error.
*
* @event error
* @param {*} error object describling the error. It's generally an Error or an Event object.
*/
}
inherit(TagLoader, EventProvider);
/**
* Start the laoding of the ressource.
* @method load
*/
TagLoader.prototype.load = function() {
this._tag.onload = function() {
this.loaded = true;
this.emit('complete', this._tag);
}.bind(this);
this._tag.onerror = this.emit.bind(this, 'error');
if (this.type === "css") {
this._tag.href = this._path;
} else {
this._tag.src = this._path;
}
if (this.type === "css" || this.type === "script") {
document.head.appendChild(this._tag);
}
};
/**
* Return the tag corresponding to the ressource.
* Note that the tag can be used before the ressource was fully loaded.
* Images will be displayed automatically when the loading is completed.
*
* @method getResult
* @return {HTMLElement}
*/
TagLoader.prototype.getResult = function() {
return this._tag;
};
TW.Preload.TagLoader = TagLoader;
return TagLoader;
});
|
JavaScript
| 0 |
@@ -1332,16 +1332,34 @@
* @param
+ %7BString%7CString%5B%5D%7D
path Ur
@@ -1378,16 +1378,134 @@
ote file
+.%0A%09 * You can pass many urls in an array. In this case, the first compatible url is used (useful for audio loading).
%0A%09 * @pa
@@ -1981,16 +1981,25 @@
%7BString
+%7CString%5B%5D
%7D _path%0A
@@ -3382,26 +3382,30 @@
error');%0A%0A%09%09
-if
+switch
(this.type
@@ -3407,22 +3407,28 @@
type
- ===
+) %7B%0A%09%09%09case
%22css%22
-) %7B%0A
+:%0A%09
%09%09%09t
@@ -3457,21 +3457,381 @@
path
-;%0A%09%09%7D else %7B%0A
+ instanceof Array ? this._path%5B0%5D : this._path;%0A%09%09%09%09break;%0A%09%09%09case %22sound%22:%0A%09%09%09%09if (this._path instanceof Array) %7B%0A%09%09%09%09%09for (var i = 0; i %3C this._path.length; i++) %7B%0A%09%09%09%09%09%09var source = document.createElement('source');%0A%09%09%09%09%09%09source.src = this._path%5Bi%5D;%0A%09%09%09%09%09%09this._tag.appendChild(source);%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D else %7B%0A%09%09%09%09%09this._tag.src = this._path;%0A%09%09%09%09%7D%0A%09%09%09%09break;%0A%09%09%09default:%0A%09
%09%09%09t
|
50985a08ed044dfa82b2ebbf0613ab2c3c7f9dc5
|
Fix for bug: 667 - fixed the first part of the bug for IE7, where the hight of the box would get smaller every time the hover event being envoked
|
web/src/main/webapp/js/manage-period/activity-notes.js
|
web/src/main/webapp/js/manage-period/activity-notes.js
|
if (!window.SC) { window.SC = { } }
if (!SC.MP) { SC.MP = { } }
Object.extend(SC.MP, {
NOTE_TYPES: $w("details condition labels weight"),
DEFAULT_NOTE_TYPE: "details",
selectDisplayedNotes: function(evt) {
var srcHref;
if (evt && evt.type == 'click') {
srcHref = Event.element(evt).href
} else {
srcHref = location.href
}
var anchorStart = srcHref.indexOf('#')
var selectedNoteType = SC.MP.DEFAULT_NOTE_TYPE
if (anchorStart >= 0) {
var anchorName = srcHref.substring(anchorStart + 1)
if (SC.MP.NOTE_TYPES.include(anchorName)) {
selectedNoteType = anchorName
}
}
SC.MP.NOTE_TYPES.
reject(function(t) { return t == selectedNoteType }).
each(SC.MP.hideNoteType)
SC.MP.showNoteType(selectedNoteType)
},
flipNoteType: function(type, show) {
$$("#notes span." + type).invoke(show)
},
showNoteType: function(type) {
SC.MP.flipNoteType(type, "show")
$$("#notes-heading li." + type).first().addClassName("selected")
},
hideNoteType: function(type) {
SC.MP.flipNoteType(type, "hide")
$$("#notes-heading li." + type).first().removeClassName("selected")
},
registerNotePreviewHandler: function(editButton) {
$(editButton).observe('mouseout', SC.MP.hideNotePreview)
$(editButton).observe('mouseover', SC.MP.updateNotePreview)
$('notes-preview').observe('mouseover', function() { $('notes-preview').show() })
$('notes-preview').observe('mouseout', SC.MP.hideNotePreview)
},
hideNotePreview: function(evt) {
var box = $('notes-preview')
box.hide()
},
updateNotePreview: function(evt) {
var editButton = Event.element(evt)
var notesRow = Event.findElement(evt, "tr")
var rowClass = SC.MP.findRowIndexClass(notesRow)
var box = $('notes-preview')
$w(box.className).each(function(clz) {
if (clz.substring(0, 4) == "row-") {
box.removeClassName(clz)
}
})
box.addClassName(rowClass)
// update contents
box.select('h2').first().innerHTML =
$$("#activities ." + rowClass + " td").first().title
SC.MP.NOTE_TYPES.each(function(noteKind) {
var content = notesRow.select("." + noteKind).first().innerHTML.strip()
var elt = $(noteKind + "-preview")
if (content.length == 0) {
elt.innerHTML = "None"
elt.addClassName("none")
} else {
elt.innerHTML = content
elt.removeClassName("none")
}
})
// reposition box
var boxHeight = box.getDimensions().height
box.style.top = ($('notes').scrollTop + 18) + "px"
box.style.height = boxHeight + "px"
box.show()
},
clickEditButton: function(evt) {
Event.stop(evt)
var editButton = Event.element(evt)
SC.MP.editNotes(editButton.up("tr"))
},
clickNotesPreview: function(evt) {
Event.stop(evt)
var rowClass = SC.MP.findRowIndexClass($('notes-preview'))
SC.MP.editNotes($$("#notes tr." + rowClass).first())
},
editNotes: function(notesRow) {
var rowClass = SC.MP.findRowIndexClass(notesRow)
var activity = SC.MP.findActivity(rowClass.substring(4))
$$(".column ." + rowClass).invoke("addClassName", "emphasized")
$$("#edit-notes-lightbox .activity-name").invoke("update", activity.name)
SC.MP.NOTES_OBSERVERS = { }
$w("details condition labels weight").each(function(noteKind) {
var noteSpan = notesRow.select(".notes-content ." + noteKind).first();
var noteInput = $('edit-notes-' + noteKind);
// copy in current values from spans
noteInput.value = noteSpan.innerHTML.unescapeHTML().strip().replace(/\s+/g, " ")
SC.applyInputHint(noteInput)
// observe the text field and update the span
SC.MP.NOTES_OBSERVERS[noteKind] = new Form.Element.Observer(
noteInput,
0.4,
function(e, value) {
if (noteInput.hasClassName("input-hint")) {
noteSpan.innerHTML = ""
} else {
noteSpan.innerHTML = value.strip()
}
}
)
})
$('edit-notes-lightbox').addClassName(rowClass)
$('edit-notes-lightbox').show()
$$("#edit-notes-lightbox input").invoke("enable")
LB.Lightbox.activate()
},
finishEditingNotes: function(evt) {
$$("#edit-notes-lightbox input").invoke("disable")
Object.values(SC.MP.NOTES_OBSERVERS).invoke("stop")
var rowClass = SC.MP.findRowIndexClass($('edit-notes-lightbox'))
$('edit-notes-lightbox').removeClassName(rowClass)
var rowIndex = rowClass.substring(4)
var cells = $$("#days ." + rowClass + " .cell")
var success = function(r, c) {
return function() {
SC.MP.reportInfo("Successfully updated notes for " + r + ", " + c)
}
}
for (var col = 0 ; col < cells.length ; col++) {
var cell = cells[col]
var marker = cell.select(".marker").first()
if (marker) {
cell.addClassName("pending")
SC.MP.putPlannedActivity(marker.getAttribute("resource-href"), rowIndex, col,
SC.MP.plannedActivityAjaxOptions(success(rowIndex, col), cell)
)
}
}
$$(".column ." + rowClass).invoke("removeClassName", "emphasized")
LB.Lightbox.deactivate()
}
})
$(document).observe("dom:loaded", function() {
SC.MP.selectDisplayedNotes();
$$("#notes-heading ul a").each(function(a) {
$(a).observe("click", SC.MP.selectDisplayedNotes)
})
$$(".notes-edit").each(SC.MP.registerNotePreviewHandler)
$$(".notes-edit").each(function(button) { button.observe("click", SC.MP.clickEditButton) })
$('notes-preview').observe("click", SC.MP.clickNotesPreview)
$('edit-notes-done').observe('click', SC.MP.finishEditingNotes)
})
|
JavaScript
| 0.000003 |
@@ -2515,55 +2515,8 @@
box%0A
- var boxHeight = box.getDimensions().height%0A
@@ -2570,53 +2570,8 @@
px%22%0A
- box.style.height = boxHeight + %22px%22%0A %0A
|
d7d6a65a81b50343a5a09856a3e622c7ec018d31
|
Update right button behavior to link to add item page.
|
frontend/src/App.js
|
frontend/src/App.js
|
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
import firebase from 'firebase';
import GlobalFont from 'react-native-global-font';
import { Header, Footer, ItemsList, Spinner } from './components/common';
import AddItem from './components/AddItem';
import LoginForm from './components/LoginForm';
import { Scene, Router, Actions, NavBar } from 'react-native-router-flux';
import AddItem from './components/AddItem';
import MainNavBar from './components/MainNavBar';
import Main from './components/Main';
class App extends Component {
state = { loggedIn: null };
static renderRightButton(props) {
return <Text>Right Button</Text>;
}
componentWillMount() {
let renogare = 'Renogare';
GlobalFont.applyGlobal(renogare);
// firebase.initializeApp({
// apiKey: 'AIzaSyCNqlXMbg2il8Rq-vSeHYWONM32EaYQyGc',
// authDomain: 'costpers-50fd6.firebaseapp.com',
// databaseURL: 'https://costpers-50fd6.firebaseio.com',
// projectId: 'costpers-50fd6',
// storageBucket: 'costpers-50fd6.appspot.com',
// messagingSenderId: '121755312308'
// });
//
// firebase.auth().onAuthStateChanged((user) => {
// if (user) {
// this.setState({ loggedIn: true });
// } else {
// this.setState({ loggedIn: false });
// }
// });
}
render() {
return (
<Router
NavBar={MainNavBar}
sceneStyle={{ paddingTop: 65 }}
onRight={() => console.log('hi')}
rightButtonImage={source={uri: 'https://facebook.github.io/react/img/logo_og.png' }}
rightTitle="Add Item"
>
<Scene key="root">
<Scene key="login" component={LoginForm} title="CostPers" />
<Scene
key="itemsList"
component={ItemsList}
navigationBarStyle={styles.navBar}
initial />
{/* itemsList inital={loggedIn} <- boolean method to determine loggedin/authenication */}
<Scene key="main" component={Main} title="test" />
<Scene key="addItem" component={AddItem} title="Add An Item"/>
</Scene>
</Router>
);
}
}
const styles = {
navBar: {
backgroundColor: '#F0F0F0'
},
image: {
width: 50,
height: 50
}
}
export default App;
|
JavaScript
| 0 |
@@ -282,52 +282,8 @@
n';%0A
-import AddItem from './components/AddItem';%0A
impo
@@ -1469,181 +1469,16 @@
%7D%7D%0A
- onRight=%7B() =%3E console.log('hi')%7D%0A rightButtonImage=%7Bsource=%7Buri: 'https://facebook.github.io/react/img/logo_og.png' %7D%7D%0A rightTitle=%22Add Item%22%0A
%3E%0A
@@ -1473,16 +1473,16 @@
%3E%0A
+
@@ -1693,24 +1693,201 @@
les.navBar%7D%0A
+ onRight=%7B() =%3E Actions.addItem()%7D%0A rightButtonImage=%7Bsource=%7Buri: 'https://facebook.github.io/react/img/logo_og.png' %7D%7D%0A rightTitle=%22Add Item%22%0A
@@ -2055,24 +2055,24 @@
e=%22test%22 /%3E%0A
+
%3CS
@@ -2125,11 +2125,8 @@
Add
-An
Item
|
ffb588d0da48571d3e68fce94c5999245712a834
|
Add setOnChange that allows a controller to set a function to call when the currentTask changes.
|
website/src/app/project/experiments/experiment/components/tasks/current-task.service.js
|
website/src/app/project/experiments/experiment/components/tasks/current-task.service.js
|
class CurrentTask {
constructor() {
this.currentTask = null;
}
get() {
return this.currentTask;
}
set(task) {
this.currentTask = task;
}
}
angular.module('materialscommons').service('currentTask', CurrentTask);
|
JavaScript
| 0 |
@@ -66,16 +66,107 @@
= null;%0A
+ this.onChangeFN = null;%0A %7D%0A%0A setOnChange(fn) %7B%0A this.onChangeFN = fn;%0A
%7D%0A%0A
@@ -261,24 +261,96 @@
ask = task;%0A
+ if (this.onChangeFN) %7B%0A this.onChangeFN();%0A %7D%0A
%7D%0A%7D%0A%0Aang
|
0914daf441829abeaeeb6277f059b5443c1cbd33
|
clear the service dragdrop rereference
|
modules/dragdrop/dragdrop.js
|
modules/dragdrop/dragdrop.js
|
(function() {
"use strict";
angular.module('common.dragdrop', [])
.factory('DragDropHandler', [function() {
return {
dragObject: {},
addObject: function(object, objects, to) {
objects.splice(to, 0, object);
},
updateObjects: function(objects, to, from) {
objects.splice(to, 0, objects.splice(from, 1)[0]);
}
};
}])
.directive('draggable', ['DragDropHandler', function(DragDropHandler) {
return {
scope: {
draggable: '='
},
link: function(scope, element, attrs){
element.draggable({
connectToSortable: attrs.draggableTarget,
helper: "clone",
revert: "invalid",
start: function(event, ui) {
DragDropHandler.dragObject = scope.draggable;
}
});
element.disableSelection();
}
};
}])
.directive('droppable', ['DragDropHandler', function(DragDropHandler) {
return {
scope: {
ngUpdate: '&',
ngCreate: '&'
},
link: function(scope, element, attrs){
element.sortable();
element.disableSelection();
element.on("sortdeactivate", function(event, ui) {
var from = angular.element(ui.item).scope().$index;
var to = element.children().index(ui.item);
if (to >= 0 ){
scope.$apply(function(){
if (from >= 0) {
scope.ngUpdate({
from: from,
to: to
});
} else {
scope.ngCreate({
object: DragDropHandler.dragObject,
to: to
});
ui.item.remove();
}
});
}
});
}
};
}])
;})();
|
JavaScript
| 0 |
@@ -886,25 +886,16 @@
unction(
-event, ui
) %7B%0A
@@ -960,16 +960,145 @@
ggable;%0A
+ %7D,%0A stop: function() %7B%0A DragDropHandler.dragObject = undefined; %0A
|
b12ee4f6e433e9c0592e2a6e7c31c115d9d070c1
|
fix bad link
|
frontend/src/App.js
|
frontend/src/App.js
|
import React, { Component } from 'react';
//import Suggest from './Suggest.js';
import Select from 'react-select';
import Slider, {Handle} from 'rc-slider';
import Tooltip from 'rc-tooltip';
const queryString = require('query-string');
import 'react-select/dist/react-select.css';
import 'rc-slider/assets/index.css';
import './App.css';
var isLoadingExternally = true;
const updateHash = (param, value) => {
var hash = queryString.parse(location.hash);
hash[param] = value;
location.hash = "#" + queryString.stringify(hash);
}
const handle = (props) => {
const { value, dragging, index, ...restProps } = props;
return (
<Tooltip
prefixCls="rc-slider-tooltip"
overlay={value}
visible={dragging}
placement="top"
key={index}
>
<Handle {...restProps} />
</Tooltip>
);
};
const getSimfiles = (input) => {
return fetch(`/api/v1/simfiles`)
.then((response) => {
return response.json();
}).then((json) => {
return { options: json };
});
}
class SongInfo extends Component {
renderStops() {
return this.props.songInfo.result.stops ? (
<div>
<strong>Stops: {this.props.songInfo.result.stops}</strong>
<br /><br />
</div>
) : null;
}
renderSpeedChanges() {
return this.props.songInfo.result.speed_changes.length ? (
<div className="App-speedwarning">
{
this.props.songInfo.result.speed_changes.map(function(message) {
return (
<div key={message}>
{message}
<br />
</div>
);
})
}
</div>
) : null;
}
render() {
return this.props.songInfo ? (
<div className="App-songinfo">
{this.renderStops()}
{
this.props.songInfo.result.bpm_list.map(function(message) {
return <div key={message}>
{message}
<br />
</div>;
})
}
<p className="App-speedsuggestion">{this.props.songInfo.result.suggestion}</p>
{this.renderSpeedChanges()}
</div>
) : null;
}
}
class App extends Component {
constructor() {
super();
var hash = queryString.parse(location.hash);
this.state = {
selectedSong: null,
songInfo: null,
preferredReadSpeed: (hash.readSpeed) ? hash.readSpeed : 573,
};
if (hash.song) {
this.fetchSuggestions({'label': hash.song});
}
this.fetchSuggestions = this.fetchSuggestions.bind(this);
this.onSliderChange = this.onSliderChange.bind(this);
this.onSliderSelect = this.onSliderSelect.bind(this);
}
onSliderChange(value) {
this.setState({'preferredReadSpeed': value});
}
onSliderSelect(value) {
if (this.state.selectedSong) {
this.fetchSuggestions(this.state.selectedSong);
}
}
fetchSuggestions(song) {
this.setState({'selectedSong': song});
updateHash('song', song.label);
updateHash('readSpeed', this.state.preferredReadSpeed);
return fetch(`/api/v1/simfiles/` + song.label + `?style=Single&difficulty=Hard&preferred_rate=` + this.state.preferredReadSpeed + `&speed_change_threshold=4`)
.then((response) => {
return response.json();
}).then(function(info) {
this.setState({'songInfo': info});
}.bind(this));
}
render() {
return (
<div className="App">
<div className="App-header">
<h3>true BPM</h3>
</div>
<div className="Content">
<p className="description">
figure out the actual BPM of a chart on DDR.
</p>
<small><i>preferred read speed:</i></small>
<Slider
min={50}
max={800}
defaultValue={573}
value={this.state.preferredReadSpeed}
handle={handle}
step={5}
onChange={this.onSliderChange}
onAfterChange={this.onSliderSelect}
/>
<br />
<Select.Async
name="form-field-name"
value="one"
loadOptions={getSimfiles}
isLoading={isLoadingExternally}
onChange={this.fetchSuggestions}
/>
</div>
<SongInfo songInfo={this.state.songInfo} />
<div className="github">
<br />
<sub><small><a href='https://github.com/zachwalton/truebpm/issues/new<Paste>'>problem?</a></small></sub>
</div>
</div>
);
}
}
export default App;
|
JavaScript
| 0.000001 |
@@ -3452,16 +3452,28 @@
%3Ch3%3E
+%3Ca href='/'%3E
true BPM
@@ -3474,16 +3474,20 @@
ue BPM%3C/
+a%3E%3C/
h3%3E%0A
@@ -4424,15 +4424,8 @@
/new
-%3CPaste%3E
'%3Epr
|
ea82fd9ed90020d595651f2c6ed2d3e907e9f52a
|
remove caching `Function#name`, fix #296
|
modules/es6.function.name.js
|
modules/es6.function.name.js
|
var dP = require('./_object-dp').f;
var createDesc = require('./_property-desc');
var has = require('./_has');
var FProto = Function.prototype;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name';
var isExtensible = Object.isExtensible || function () {
return true;
};
// 19.2.4.2 name
NAME in FProto || require('./_descriptors') && dP(FProto, NAME, {
configurable: true,
get: function () {
try {
var that = this;
var name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch (e) {
return '';
}
}
});
|
JavaScript
| 0.000001 |
@@ -416,41 +416,14 @@
-var that = this;%0A var name =
+return
(''
@@ -427,18 +427,18 @@
('' + th
-at
+is
).match(
@@ -453,112 +453,8 @@
1%5D;%0A
- has(that, NAME) %7C%7C !isExtensible(that) %7C%7C dP(that, NAME, createDesc(5, name));%0A return name;%0A
|
4bf7a007fb1c80929dd4537c5a33d7c97970a5d1
|
fix a typo in variable name
|
frontend/src/app.js
|
frontend/src/app.js
|
"use strict"
var util = require('./util');
var view = require('./view');
var backendQuery = require('./backendQuery');
import Cookies from './lib/js-cookie';
export var a = Cookies;
var REWARDS = [1,100,10000]
export var courses = {}
var loadedCourseCodes = {}
var selectedOptions = {}
loadFromCookies();
view.initHandlebars(selectedOptions);
view.renderCourseList(courses)
export function clearAll() {
if(window.confirm("Opravdu smazat vše?")) {
courses = {}
loadedCourseCodes = {}
selectedOptions = {}
saveToCookies()
}
view.renderCourseList();
return false
}
export function addCourse() {
var courseCode = document.getElementById("course_code").value
if (loadedCourseCodes[courseCode]) {
view.setStatusMessage("Předmět " + courseCode + " už je přidán")
return false
}
backendQuery.addCourse(courseCode, function(res, err) {
if (err) {
view.setStatusMessage("Chyba: " + err)
} else {
res.forEach(addGroup)
view.renderCourseList(courses)
loadedCourseCodes[courseCode] = true
saveToCookies()
view.setStatusMessage("Přidán předmět " + courseCode)
}
})
view.setStatusMessage("Hledám předmět " + courseCode)
return false // prevents default form submission behavior (refreshing the page)
}
function addGroup(group) {
if (group.length == 0) {
return
}
var type = group[0].type
var name = group[0].name
var id = type + ";" + name
if (courses[id] === undefined) {
courses[id] = {
id: id,
name: name + " (" + ((type==='P') ? "přednáška" : "seminář") + ")",
options: [],
allowed: true,
}
}
group.allowed = true
// We remember the index so that we can get back to this group when passing a filtered version
// of options to the solver
group.optionId = courses[id].options.length
courses[id].options.push(group)
}
// Called when the "sestavit rozvrh" button is pressed
export function createSchedule() {
view.setStatusMessage("Sestavuji rozvrh")
var queryArray =
Object.values(courses).filter(function(c) {
return c.allowed && c.options.some(function(o){return o.allowed})}
).map(function(c) {
return {
id: c.id,
name: c.name,
reward: REWARDS[(c.priority || 2) - 1],
options: c.options.filter(function(o) {
return o.allowed
})
}
})
backendQuery.createSchedule(queryArray, function(res, err) {
if (err) {
view.setStatusMessage("Chyba: " + err)
} else {
var nSelected = res.filter(function(x){return x !== null}).length
view.setStatusMessage("Rozvrh sestaven (počet předmětů: " + nSelected + ")")
for (var course in courses) {
delete selectedOptions[course]
}
for (var i = 0; i < queryArray.length; i++) {
if (res[i] !== null) { // if null, the course is not selected
selectedOptions[queryArray[i].id] = queryArray[i].options[res[i]].optionId
}
}
view.renderCourseList(courses)
view.renderSchedule(getNonOverlappingGroups())
}
})
return false // prevents default form submission behavior (refreshing the page)
}
export function handleCheckbox(checkboxId, courseId, index) {
if (index === undefined) { // Checkbox for the whole course
// If something is checked, uncheck everything, otherwise check everything
var checkAll = !courses[courseId].options.some(function(o) {return o.allowed})
courses[courseId].options.forEach(function(o, i) {
document.getElementById(checkboxId + "-" + i).checked = checkAll
courses[courseId].options[i].allowed = checkAll
})
document.getElementById(checkboxId).checked = checkAll
} else {
courses[courseId].options[index].allowed = document.getElementById(checkboxId).checked
document.getElementById(checkboxId.substring(0, checkboxId.length - 2)).checked =
courses[courseId].options.some(function(o) {return o.allowed})
}
saveToCookies()
}
export function handlePriorityChange(courseId, priority) {
courses[courseId].priority = priority
saveToCookies()
}
function getNonOverlappingGroups() {
// For rendering purposes, we split the events into groups with no overlap.
// Perhaps premature optimization, this is in case we want to allow the solver
// to let some events overlap.
var eventsByDay = [[],[],[],[],[]]
for (var course in selectedOptions) {
courses[course].options[selectedOptions[course]].forEach(function(event) {
eventsByDay[event.day].push(event)
})
}
return eventsByDay.map(function(eventsOfDay) {
eventsOfDay.sort(function(a, b) {
return util.timeToInt(a.time_from) - util.timeToInt(b.time_from)
})
var groups = []
eventsOfDay.forEach(function(event) {
var validGroup = null
groups.forEach(function(group) {
if (util.timeToInt(group[group.length - 1].time_to) <= util.timeToInt(event.time_from)) {
validGroup = group
}
})
if (validGroup) {
validGroup.push(event)
} else {
groups.push([event])
}
})
return groups
})
}
function loadFromCookies() {
var loadedFromCookies = Cookies.getJSON("loadedCourseCodes")
if (loadFromCookies === undefined) {
return
}
loadedCourseCodes = loadedFromCookies
var after = function() {
var priorities = Cookies.getJSON("priorities")
var allowed = Cookies.getJSON("allowed")
if(priorities === undefined) return
if(allowed === undefined) return
var sorted = util.sortCourses(courses)
sorted.forEach(function(c, i) {
c.priority = priorities[i]
c.options.forEach(function(o, j) {
o.allowed = allowed[i][j]
})
})
}
var remain = Object.keys(loadedCourseCodes).length // A primitive Promise substitute.
for (var code in loadedCourseCodes) {
backendQuery.addCourse(code, function(res, err) {
remain--
if (!err) {
res.forEach(addGroup)
} else {
console.error("Error in loading from cookies")
console.error(err)
}
if (remain == 0) {
after()
}
view.renderCourseList(courses)
})
}
}
function saveToCookies() {
var COOKIE_DAYS = 100
Cookies.set("loadedCourseCodes", loadedCourseCodes, { expires: COOKIE_DAYS })
var sorted = util.sortCourses(courses)
var priorities = sorted.map(function(c) { return c.priority || 2 })
Cookies.set("priorities", priorities, { expires: COOKIE_DAYS })
var allowed = sorted.map(function(c) {
return c.options.map(function(o) { return o.allowed })
})
Cookies.set("allowed", allowed, { expires: COOKIE_DAYS })
}
|
JavaScript
| 0.998129 |
@@ -5751,24 +5751,26 @@
if (load
+ed
FromCookies
|
ac70b9e192bd948231bf3f8d0042bf69095c5715
|
exclude invalid data from date chart
|
src/main/javascript_source/org/jboss/search/page/filter/DateFilter.js
|
src/main/javascript_source/org/jboss/search/page/filter/DateFilter.js
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Date filter.
* @author Lukas Vlcek ([email protected])
*/
goog.provide('org.jboss.search.page.filter.DateFilter');
goog.require('org.jboss.search.visualization.Histogram');
goog.require('org.jboss.search.visualization.IntervalSelected');
goog.require('org.jboss.search.LookUp');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.KeyHandler');
goog.require('goog.events.KeyHandler.EventType');
goog.require('goog.array');
goog.require('goog.Disposable');
/**
*
* @param {!HTMLElement} element to host the date filter
* @param {!HTMLElement} date_histogram_element to host the date histogram chart
* @param {function(): boolean} opt_isCollapsed a function that is used to learn if filter is collapsed
* @param {Function=} opt_expandFilter a function that is used to show/expand the filter DOM elements
* @param {Function=} opt_collapseFilter a function that is used to hide/collapse the filter DOM elements
* @constructor
* @extends {goog.Disposable}
*/
org.jboss.search.page.filter.DateFilter = function(element, date_histogram_element, opt_isCollapsed, opt_expandFilter, opt_collapseFilter) {
goog.Disposable.call(this);
/**
* @type {HTMLElement}
* @private
*/
this.element_ = element;
/**
* @type {HTMLElement}
* @private
*/
this.date_histogram_element_ = date_histogram_element;
/**
* @type {!Function}
* @private
*/
this.expandFilter_ = /** @type {!Function} */ (goog.isFunction(opt_expandFilter) ? opt_expandFilter : goog.nullFunction());
/**
* @type {!Function}
* @private
*/
this.collpaseFilter_ = /** @type {!Function} */ (goog.isFunction(opt_collapseFilter) ? opt_collapseFilter : goog.nullFunction());
/**
* @type {function(): boolean}
* @private
*/
this.isCollapsed_ = /** @type {function(): boolean} */ (goog.isFunction(opt_isCollapsed) ? opt_isCollapsed : function(){ return true });
/** @private */
this.keyHandler_ = new goog.events.KeyHandler(goog.dom.getDocument());
// We can not use this.element_ but document - because <DIV> may not be focused.
// this.keyHandler_ = new goog.events.KeyHandler(this.element_);
// listen for key strokes
this.keyListenerId_ = goog.events.listen(this.keyHandler_,
goog.events.KeyHandler.EventType.KEY,
goog.bind(function(e) {
var keyEvent = /** @type {goog.events.KeyEvent} */ (e);
if (!keyEvent.repeat) {
if (!this.isCollapsed_()) {
if (keyEvent.keyCode == goog.events.KeyCodes.ESC) {
// keyEvent.preventDefault();
this.collapseFilter();
}
}
}
}, this)
);
/**
* @type {org.jboss.search.visualization.Histogram}
* @private
*/
this.histogram_chart_ = new org.jboss.search.visualization.Histogram(this.date_histogram_element_);
this.histogram_chart_.initialize('histogram', 420, 200); // TODO add size to configuration
};
goog.inherits(org.jboss.search.page.filter.DateFilter, goog.Disposable);
/** @inheritDoc */
org.jboss.search.page.filter.DateFilter.prototype.disposeInternal = function() {
org.jboss.search.page.filter.ProjectFilter.superClass_.disposeInternal.call(this);
goog.dispose(this.histogram_chart_);
goog.dispose(this.keyHandler_);
goog.events.unlistenByKey(this.keyListenerId_);
this.element_ = null;
this.date_histogram_element_ = null;
delete this.expandFilter_;
delete this.collpaseFilter_;
delete this.isCollapsed_;
};
/**
* Calls opt_expandFilter function.
* @see constructor
*/
org.jboss.search.page.filter.DateFilter.prototype.expandFilter = function() {
this.expandFilter_();
this.refreshChart(false);
};
/**
* Refresh chart (meaning update to the latest search result histogram facet data). By default
* this does nothing if the filter is collapsed.
* @param {boolean=} opt_force refresh even if filter is collapsed. Defaults to false.
*/
org.jboss.search.page.filter.DateFilter.prototype.refreshChart = function(opt_force) {
var force = !!(opt_force || false);
if (!this.isCollapsed_() || force) {
var data = org.jboss.search.LookUp.getInstance().getRecentQueryResultData();
if (data && data.activity_dates_histogram_interval && data.facets &&
data.facets.activity_dates_histogram && data.facets.activity_dates_histogram.entries) {
/** @type {Array.<{time: number, count: number}>} */
var entries_ = data.facets.activity_dates_histogram.entries;
var requestParams = org.jboss.search.LookUp.getInstance().getRequestParams();
var from_ = goog.isDateLike(requestParams.getFrom()) ? requestParams.getFrom().getTime() : null;
var to_ = goog.isDateLike(requestParams.getTo()) ? requestParams.getTo().getTime() : null;
if (!goog.isNull(from_) || !goog.isNull(to_)) {
entries_ = goog.array.filter(entries_, function(entry){
if (!goog.isNull(to_) && entry.time > to_) { return false }
if (!goog.isNull(from_) && entry.time < from_) { return false }
return true;
});
}
this.histogram_chart_.update(entries_, data.activity_dates_histogram_interval);
} else {
this.histogram_chart_.update([],"month");
}
}
};
/**
* Calls opt_collapseFilter function.
* @see constructor
*/
org.jboss.search.page.filter.DateFilter.prototype.collapseFilter = function() {
this.collpaseFilter_();
};
/**
* @return {org.jboss.search.visualization.Histogram}
*/
org.jboss.search.page.filter.DateFilter.prototype.getHistogramChart = function() {
return this.histogram_chart_;
};
|
JavaScript
| 0.000013 |
@@ -5397,16 +5397,223 @@
entries;
+%0A // TODO: move this check to response data normalization%0A entries_ = goog.array.filter(entries_, function(entry)%7B%0A return entry.time == 0 ? false : true;%0A %7D);
%0A%0A
|
ce3f26e8876a7251df0a1284a69f6e0fe5c20af8
|
Update draw.js
|
game/js/lib/draw.js
|
game/js/lib/draw.js
|
"use strict";
var draw = function(world) {
//world.drawRectangle("#EEE", 0, 0, world.width, world.height);
world.drawSprite("turtleWithACrown", 0, 0, world.width, world.height);
[world.enemies,
world.players,
world.bullets,
world.boss
].forEach (
function (gameElementArray) {
gameElementArray.forEach(function(gameElement) {
gameElement.draw();
});
}
);
}
|
JavaScript
| 0.000001 |
@@ -348,16 +348,48 @@
ent) %7B%0D%0A
+%09%09%09%09world.ctx.globalAlpha = 1;%0D%0A
%09%09%09%09game
@@ -424,8 +424,10 @@
%0D%0A%09);%0D%0A%7D
+%0D%0A
|
22020aa63c79a392f3d5c0fd42e8064be0ea3d86
|
Fix state mutations
|
src/components/fragments/fragments-reducers.js
|
src/components/fragments/fragments-reducers.js
|
import { combineReducers } from 'redux';
import {
ADD_PILES,
DISPERSE_PILES,
RECOVER_PILES,
REMOVE_PILES,
STACK_PILES,
SET_ANIMATION,
SET_ARRANGE_MEASURES,
SET_CELL_SIZE,
SET_COVER_DISP_MODE,
SET_LASSO_IS_ROUND,
SET_MATRIX_FRAME_ENCODING,
SET_MATRIX_ORIENTATION,
SET_PILES,
SET_SHOW_SPECIAL_CELLS,
TRASH_PILES,
UPDATE_FGM_CONFIG
} from 'components/fragments/fragments-actions';
import {
ANIMATION,
ARRANGE_MEASURES,
CELL_SIZE,
CONFIG,
LASSO_IS_ROUND,
MATRIX_FRAME_ENCODING,
MATRIX_ORIENTATION_INITIAL,
MODE_MEAN,
PILES,
SHOW_SPECIAL_CELLS
} from 'components/fragments/fragments-defaults';
import deepClone from 'utils/deep-clone';
export function piles (state = PILES, action) {
switch (action.type) {
case ADD_PILES: {
const newState = { ...state };
Object.keys(action.payload.piles).forEach((pileId) => {
newState[pileId] = action.payload.piles[pileId];
});
return newState;
}
case DISPERSE_PILES: {
const newState = { ...state };
// Disperse matrices
action.payload.piles
.map(pileId => newState[pileId].slice(1)) // Always keep one matrix
.reduce((a, b) => a.concat(b), [])
.forEach((pileId) => {
newState[pileId] = [pileId];
});
// Update original pile
action.payload.piles
.forEach((pileId) => {
newState[pileId] = newState[pileId].slice(0, 1);
});
return newState;
}
case REMOVE_PILES: {
const newState = { ...state };
action.payload.piles
.forEach((pileId) => {
newState[`__${pileId}`] = [...newState[pileId]];
newState[pileId] = [];
});
return newState;
}
case RECOVER_PILES: {
const newState = { ...state };
action.payload.piles
.forEach((pileId) => {
newState[pileId.slice(1)] = [...newState[pileId]];
newState[pileId] = undefined;
delete newState[pileId];
});
return newState;
}
case SET_PILES: {
return action.payload.piles;
}
case STACK_PILES: {
const newState = { ...state };
Object.keys(action.payload.pileStacks).forEach((targetPile) => {
const sourcePiles = action.payload.pileStacks[targetPile];
// Add piles of source piles onto the target pile
newState[targetPile]
.push(
...sourcePiles
.map(pileId => newState[pileId])
.reduce((a, b) => a.concat(b), [])
);
// Reset the source piles
sourcePiles.forEach(
(pileId) => { newState[pileId] = []; }
);
});
return newState;
}
case TRASH_PILES: {
const newState = { ...state };
action.payload.piles
.forEach((pileId) => {
newState[`_${pileId}`] = [...newState[pileId]];
newState[pileId] = undefined;
delete newState[pileId];
});
return newState;
}
default:
return state;
}
}
export function animation (state = ANIMATION, action) {
switch (action.type) {
case SET_ANIMATION:
return action.payload.animation;
default:
return state;
}
}
export function arrangeMeasures (state = ARRANGE_MEASURES, action) {
switch (action.type) {
case SET_ARRANGE_MEASURES:
return action.payload.arrangeMeasures.slice();
default:
return state;
}
}
export function cellSize (state = CELL_SIZE, action) {
switch (action.type) {
case SET_CELL_SIZE:
return action.payload.cellSize;
default:
return state;
}
}
export function config (state = { ...CONFIG }, action) {
switch (action.type) {
case UPDATE_FGM_CONFIG:
return { ...state, ...deepClone(action.payload.config) };
default:
return state;
}
}
export function coverDispMode (state = MODE_MEAN, action) {
switch (action.type) {
case SET_COVER_DISP_MODE:
return action.payload.coverDispMode;
default:
return state;
}
}
export function lassoIsRound (state = LASSO_IS_ROUND, action) {
switch (action.type) {
case SET_LASSO_IS_ROUND:
return action.payload.lassoIsRound;
default:
return state;
}
}
export function matrixFrameEncoding (state = MATRIX_FRAME_ENCODING, action) {
switch (action.type) {
case SET_MATRIX_FRAME_ENCODING:
return action.payload.frameEncoding;
default:
return state;
}
}
export function matrixOrientation (state = MATRIX_ORIENTATION_INITIAL, action) {
switch (action.type) {
case SET_MATRIX_ORIENTATION:
return action.payload.orientation;
default:
return state;
}
}
export function showSpecialCells (state = SHOW_SPECIAL_CELLS, action) {
switch (action.type) {
case SET_SHOW_SPECIAL_CELLS:
return action.payload.showSpecialCells;
default:
return state;
}
}
export default combineReducers({
animation,
arrangeMeasures,
cellSize,
config,
coverDispMode,
lassoIsRound,
matrixFrameEncoding,
matrixOrientation,
piles,
showSpecialCells
});
|
JavaScript
| 0.000573 |
@@ -2140,40 +2140,191 @@
-const newState = %7B ...state
+// Create copy of old state%0A const newState = %7B%7D;%0A%0A Object.keys(state).forEach((prop) =%3E %7B%0A newState%5Bprop%5D = state%5Bprop%5D.slice();%0A
%7D
+)
;%0A%0A
+ // Adust new state%0A
|
48e64ff3c5f5e47fcfb7348e5eb2fa427efa2b08
|
Add editproxies perm check
|
lib/EditSections/EditProxy/EditProxy.js
|
lib/EditSections/EditProxy/EditProxy.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { Accordion } from '@folio/stripes-components/lib/Accordion';
import { Row, Col } from '@folio/stripes-components/lib/LayoutGrid';
import Badge from '@folio/stripes-components/lib/Badge';
import ProxyEditList from '../../ProxyGroup/ProxyEditList';
import ProxyEditItem from '../../ProxyGroup/ProxyEditItem';
const EditProxy = (props) => {
const { expanded, onToggle, accordionId, initialValues: { sponsors, proxies } } = props;
return (
<Accordion
open={expanded}
id={accordionId}
onToggle={onToggle}
label={
<h2>Proxy</h2>
}
displayWhenClosed={
<Badge>{sponsors.length + proxies.length}</Badge>
}
>
<Row>
<Col xs={8}>
<ProxyEditList itemComponent={ProxyEditItem} label="Sponsors" name="sponsors" {...props} />
<br />
<ProxyEditList itemComponent={ProxyEditItem} label="Proxy" name="proxies" {...props} />
<br />
</Col>
</Row>
</Accordion>
);
};
EditProxy.propTypes = {
expanded: PropTypes.bool,
onToggle: PropTypes.func,
accordionId: PropTypes.string.isRequired,
initialValues: PropTypes.object,
};
export default EditProxy;
|
JavaScript
| 0 |
@@ -250,16 +250,87 @@
/Badge';
+%0Aimport IfPermission from '@folio/stripes-components/lib/IfPermission';
%0A%0Aimport
@@ -578,16 +578,65 @@
eturn (%0A
+ %3CIfPermission perm=%22ui-users.editproxies%22%3E%0A
%3CAcc
@@ -642,16 +642,18 @@
cordion%0A
+
op
@@ -672,16 +672,18 @@
%7D%0A
+
id=%7Bacco
@@ -697,16 +697,18 @@
%7D%0A
+
+
onToggle
@@ -725,16 +725,18 @@
%7D%0A
+
label=%7B%0A
@@ -743,16 +743,18 @@
+
+
%3Ch2%3EProx
@@ -760,16 +760,18 @@
xy%3C/h2%3E%0A
+
%7D%0A
@@ -776,16 +776,18 @@
%7D%0A
+
displayW
@@ -798,16 +798,18 @@
losed=%7B%0A
+
@@ -868,16 +868,22 @@
+
%7D%0A
+
+
%3E%0A
+
@@ -886,24 +886,26 @@
%3CRow%3E%0A
+
%3CCol
@@ -913,16 +913,18 @@
xs=%7B8%7D%3E%0A
+
@@ -1019,39 +1019,43 @@
s%7D /%3E%0A
+
%3Cbr /%3E%0A
+
%3CProxy
@@ -1128,32 +1128,34 @@
%22 %7B...props%7D /%3E%0A
+
%3Cbr /%3E
@@ -1167,15 +1167,19 @@
+
%3C/Col%3E%0A
+
@@ -1191,16 +1191,18 @@
ow%3E%0A
+
%3C/Accord
@@ -1206,16 +1206,36 @@
ordion%3E%0A
+ %3C/IfPermission%3E%0A
);%0A%7D;%0A
|
a768a7d0b81c16f91ef9c3109fb2e4adf1491cc8
|
Task for creating Migration table
|
gen/jakelib/db.jake
|
gen/jakelib/db.jake
|
// Load the basic Geddy toolkit
require('../../lib/geddy')
var cwd = process.cwd()
, fs = require('fs')
, path = require('path')
, utils = require('../../lib/utils')
, Adapter = require('../../lib/template/adapters');
namespace('db', function () {
task('createTable', ['env:init'], function (name) {
var modelName
, createTable
, adapters
, adapter;
if (typeof name == 'string') {
if (name.indexOf('%') > -1) {
modelNames = name.split('%');
}
else {
modelNames = [name];
}
}
else {
modelNames = name;
}
createTable = function () {
if ((m = modelNames.shift())) {
// Make sure this is a correct model-name
m = utils.string.getInflections(m).constructor.singular;
if (!geddy.model[m]) {
throw new Error(m + ' is not a known model.');
}
adapter = geddy.model.adapters[m];
if (adapter) {
console.log('Creating table for ' + m);
adapter.createTable(m, function (err, data) {
if (err) { throw err }
createTable();
});
}
else {
createTable();
}
}
else {
complete();
}
};
// Defer until associations are set up
setTimeout(function () {
createTable();
}, 0);
}, {async: true});
task('init', ['env:init'], function () {
var modelNames = Object.keys(geddy.model.descriptionRegistry)
, createTask = jake.Task['db:createTable'];
createTask.once('complete', function () {
complete();
});
createTask.invoke(modelNames);
}, {async: true});
});
|
JavaScript
| 0.999342 |
@@ -162,24 +162,72 @@
lib/utils')%0A
+ , modelInit = require('../../lib/init/model')%0A
, Adapter
@@ -299,16 +299,601 @@
on () %7B%0A
+%0A task('createMigrationModel', %5B'env:init'%5D, %7Basync: true%7D, function () %7B%0A var Migration = function () %7B%0A this.property('migration', 'string');%0A %7D;%0A // Create a model definition for Migrations%0A Migration = geddy.model.register('Migration', Migration);%0A // Get a DB adapter for this new model, and create its table%0A modelInit.loadAdapterForModel(Migration, function () %7B%0A var createTask = jake.Task%5B'db:createTable'%5D;%0A createTask.once('complete', function () %7B%0A complete();%0A %7D);%0A createTask.invoke('Migration');%0A %7D);%0A %7D);%0A%0A
task('
@@ -911,32 +911,47 @@
', %5B'env:init'%5D,
+ %7Basync: true%7D,
function (name)
@@ -1994,39 +1994,24 @@
%7D, 0);%0A
-%7D, %7Basync: true
%7D);%0A%0A task(
@@ -2029,17 +2029,56 @@
nv:init'
-%5D
+, 'createMigrationModel'%5D, %7Basync: true%7D
, functi
@@ -2319,30 +2319,83 @@
es);%0A %7D
-, %7Basync: true
+);%0A%0A task('migrate', %5B'env:init'%5D, %7Basync: true%7D, function () %7B%0A
%7D);%0A%0A%7D);
|
28dc7d18380835996b5edca16e991727150fcd86
|
Move logout to the last position
|
src/client/app/states/logout/logout.state.js
|
src/client/app/states/logout/logout.state.js
|
(function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper, navigationHelper) {
routerHelper.configureStates(getStates());
navigationHelper.navItems(navItems());
navigationHelper.sidebarItems(sidebarItems());
}
function getStates() {
return {
'logout': {
url: '/logout',
controller: StateController,
controllerAs: 'vm',
title: 'Logout'
}
};
}
function navItems() {
return {};
}
function sidebarItems() {
return {
'logout': {
type: 'state',
state: 'logout',
label: 'Logout',
style: 'logout',
isVisible: isVisible,
order: 99
}
};
}
/** @ngInject */
function isVisible() {
// Visibility can be conditional
return true;
}
/** @ngInject */
function StateController($state, AuthenticationService, logger, lodash) {
var vm = this;
vm.AuthService = AuthenticationService;
vm.title = '';
vm.AuthService.logout().success(lodash.bind(function() {
logger.info('You have been logged out.');
$state.transitionTo('login');
}, vm)).error(lodash.bind(function() {
logger.info('An error has occured at logout.');
}, vm));
}
})();
|
JavaScript
| 0.000001 |
@@ -728,16 +728,18 @@
rder: 99
+99
%0A %7D
|
8432b57bd71194fccce591ea6d9105a267193c40
|
Update app sample
|
app/angular/controller.js
|
app/angular/controller.js
|
(function() { 'use strict';
angular.module('webcam').controller('webcamController', webcamController);
webcamController.$inject = ['$scope', '$log'];
function webcamController($scope, $log) {
/* jshint validthis: true */
var vm = this;
vm.config = {
delay: 2,
shots: 3,
flashFallbackUrl: 'bower_components/webcamjs/webcam.swf',
shutterUrl: 'shutter.mp3',
flashNotDetectedText: 'Seu browser não atende os requisitos mínimos para utilização da camera. ' +
'Instale o ADOBE Flash player ou utilize os browsers (Google Chrome, Firefox ou Edge)'
};
vm.showButtons = false;
vm.captureButtonEnable = false;
vm.onCaptureComplete = function(src) {
$log.log('webcamController.onCaptureComplete : ', src);
};
vm.onError = function(err) {
$log.error('webcamController.onError : ', err);
vm.showButtons = false;
};
vm.onLoad = function() {
$log.info('webcamController.onLoad');
vm.showButtons = true;
};
vm.onLive = function() {
$log.info('webcamController.onLive');
vm.captureButtonEnable = true;
};
vm.onCaptureProgress = function(src, progress) {
var result = {
src: src,
progress: progress
}
$log.info('webcamController.onCaptureProgress : ', result);
};
vm.capture = function() {
$scope.$broadcast('ngWebcam_capture'); };
vm.on = function() {
$scope.$broadcast('ngWebcam_on');
};
vm.off = function() {
$scope.$broadcast('ngWebcam_off');
vm.captureButtonEnable = false;
};
}
})();
|
JavaScript
| 0 |
@@ -293,16 +293,65 @@
ots: 3,%0A
+ viewerWidth: 480,%0A viewerHeight: 320,%0A
fl
|
8334ad4d09e73b8813faadf25960a7eea1a27b25
|
Use correct collection moethods instead of referencing internals
|
app/client/views/table.js
|
app/client/views/table.js
|
define([
'extensions/views/table',
'modernizr'
],
function (TableView, Modernizr) {
return TableView.extend({
initialize: function () {
this.$table = this.$('table');
this.tableCollection = new this.collection.constructor(this.collection.models, this.collection.options);
this.listenTo(this.tableCollection, 'sort', this.renderSort);
this.listenTo(this.collection, 'sync', this.syncToTableCollection);
TableView.prototype.initialize.apply(this, arguments);
},
events: {
'click th a': 'sortCol'
},
syncToTableCollection: function () {
this.tableCollection.models = _.clone(this.collection.models);
},
renderSort: function () {
if (this.$table.find('tbody')) {
this.$table.find('tbody').remove();
}
$(this.renderBody(this.tableCollection)).appendTo(this.$table);
this.render();
},
sortCol: function (e) {
e.preventDefault();
var th = $(e.target).parent(),
ths = this.$table.find('th'),
column = ths.index(th),
isSorted = th.hasClass('desc') || th.hasClass('asc'),
isDescending = isSorted && th.hasClass('desc') || false,
columns = this.getColumns(),
sortBy = columns[column].key;
if (_.isArray(sortBy)) {
sortBy = sortBy[0];
}
ths.removeClass('asc');
ths.removeClass('desc');
ths.attr('aria-sort', 'none');
if (isDescending) {
th.addClass('asc');
th.attr('aria-sort', 'ascending');
} else {
th.addClass('desc');
th.attr('aria-sort', 'descending');
}
this.tableCollection.comparator = function (a, b) {
var firstVal = a.get(sortBy),
firstTime = a.get('_timestamp') || a.get('_start_at'),
secondVal = b.get(sortBy),
secondTime = b.get('_timestamp') || b.get('_start_at'),
nullValues = (firstVal !== null || secondVal !== null),
ret;
if (nullValues && firstVal < secondVal) {
ret = -1;
} else if (nullValues && firstVal > secondVal) {
ret = 1;
} else {
if (nullValues) {
if (firstVal === null) {
ret = -1;
}
if (secondVal === null) {
ret = 1;
}
} else {
if (firstTime < secondTime) {
ret = -1;
} else if (firstTime > secondTime) {
ret = 1;
} else {
ret = 0;
}
}
}
if (!isDescending) {
ret = -ret;
}
return ret;
};
this.tableCollection.sort();
},
render: function () {
if (Modernizr.touch) {
this.$table.addClass('touch-table');
}
this.$table.removeClass('floated-header');
var headers = this.$table.find('thead th'),
headerLinks = this.$table.find('thead th a'),
body = this.$table.find('tbody td');
headers.attr('width', '');
if (headerLinks.length === 0) {
headers.each(function () {
$(this).attr('aria-sort', 'none');
$(this).wrapInner('<a href="#"></a>');
});
}
body.attr('width', '');
if (body.length > headers.length) {
_.each(headers, function (th, index) {
th.width = th.offsetWidth;
body[index].width = th.offsetWidth;
}, this);
this.$('table').addClass('floated-header');
}
}
});
});
|
JavaScript
| 0 |
@@ -628,24 +628,13 @@
ion.
-models = _.clone
+reset
(thi
@@ -646,22 +646,24 @@
lection.
-models
+toJSON()
);%0A %7D
|
b768ad690ac0e6b0323e436d366d7321e4840223
|
fix heatmap toggle bug
|
app/components/MapPane.js
|
app/components/MapPane.js
|
import React, {Component, PropTypes} from 'react'
import { Panel } from 'react-bootstrap'
import { Map, Marker, Popup, TileLayer, CircleMarker, Polyline, GeoJson, FeatureGroup } from 'react-leaflet';
import HeatmapLayer from 'react-leaflet-heatmap-layer'
import moment from 'moment'
import isRetina from 'is-retina'
import ProjectListing from './ProjectListing'
import routes from '../../routes.json'
export default class MapPane extends Component {
constructor (props) {
super(props)
}
componentDidMount () {
// this.timer = setInterval(() => {
// this.setState({hour: (this.state.hour + 1) % 24})
// }, 5000)
}
componentWillUnmount () {
// clearInterval(this.timer)
}
getProjectLayer (project) {
if(!project.geojson) return null
const popup = (
<Popup>
<ProjectListing
project={project}
inverse={true}
projectToggled={() => this.props.projectToggled(project)}
/>
</Popup>
)
const color = project.selected ? '#df691a' : 'gray'
switch(project.geojson.geometry.type) {
case 'Point':
return (
<CircleMarker
center={[project.geojson.geometry.coordinates[1], project.geojson.geometry.coordinates[0]]}
color={color}
radius={project.selected ? 10 : 8}
weight={4}
key={project.id}
>
{popup}
</CircleMarker>
)
case 'LineString':
const positions = project.geojson.geometry.coordinates.map(coord => {
return [coord[1], coord[0]]
})
return (
<Polyline
positions={positions}
color={color}
weight={project.selected ? 10 : 8}
key={project.id}
>
{popup}
</Polyline>
)
}
}
getHighlightLayer (projectId) {
const project = this.props.projects.all.find(p => p.id === projectId)
const color = 'yellow'
switch(project.geojson.geometry.type) {
case 'Point':
return (
<CircleMarker
center={[project.geojson.geometry.coordinates[1], project.geojson.geometry.coordinates[0]]}
color={color}
radius={16}
stroke={false}
key={project.id}
/>
)
case 'LineString':
const positions = project.geojson.geometry.coordinates.map(coord => {
return [coord[1], coord[0]]
})
return (
<Polyline
positions={positions}
color={color}
weight={project.selected ? 16 : 14}
key={project.id}
/>
)
}
}
render () {
console.log(this.props.hour)
console.log(APC_AM[0])
console.log(routes)
// console.log(APC_DATA[0])
// let dataSegments = {}
// APC_DATA.map(d => {
// // const time = moment(d.timemin, 'h:mmA')
// if (!dataSegments[d.timemin]) {
// dataSegments[d.timemin] = []
// }
// dataSegments[d.timemin].push(d)
// })
// console.log(dataSegments)
const position = [MM_CONFIG.map.start_location.lat, MM_CONFIG.map.start_location.lon]
const style = {
position: 'fixed',
padding: '20px',
top: '40px',
bottom: '80px',
left: '400px',
right: '0px'
}
return (
<Map center={position} id='map' style={style} zoom={13}>
{MM_CONFIG.map && MM_CONFIG.map.mapbox
// Use MapBox tiles if provided in config
? <TileLayer
url={`https://api.mapbox.com/styles/v1/${MM_CONFIG.map.mapbox.tileset}/tiles/{z}/{x}/{y}?access_token=${MM_CONFIG.map.mapbox.access_token}`}
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
// Otherwise default to Carto Positron
: <TileLayer
url={`http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}${isRetina() ? '@2x' : ''}.png`}
attribution='© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://carto.com/attributions">CARTO</a>'
/>
}
{!this.props.hideHeatmap &&
<HeatmapLayer
points={this.props.am ? APC_AM : APC_PM}
longitudeExtractor={m => parseFloat(m.longitude) || 33}
latitudeExtractor={m => parseFloat(m.latitude) || -87}
intensityExtractor={m => this.props.ons ? parseFloat(m.ons) / 20 : parseFloat(m.offs) / 20}
/>
}
<FeatureGroup>
{!this.props.hideRoutes && routes.features.map(r => {
return (
<GeoJson
data={r.geometry}
weight={2}
color={'#777'}
// onEachFeature={}
>
<Popup>
<div>
<p style={{color: '#777'}}><strong>{r.properties.shortName}</strong> {r.properties.agency === 'Metropolitan Atlanta Rapid Transit Authority' ? 'MARTA' : r.properties.agency}</p>
</div>
</Popup>
</GeoJson>
)
})}
</FeatureGroup>
{this.props.projects.highlighted ? this.getHighlightLayer(this.props.projects.highlighted) : null}
{this.props.projects.all.map(project => this.getProjectLayer(project))}
</Map>
)
}
}
|
JavaScript
| 0.000001 |
@@ -1836,16 +1836,429 @@
%7D%0A %7D%0A
+ getHeapMap () %7B%0A const points = this.props.hideHeatmap%0A ? %5B%5D%0A : this.props.am ? APC_AM : APC_PM%0A return (%0A %3CHeatmapLayer%0A points=%7Bpoints%7D%0A longitudeExtractor=%7Bm =%3E parseFloat(m.longitude) %7C%7C 33%7D%0A latitudeExtractor=%7Bm =%3E parseFloat(m.latitude) %7C%7C -87%7D%0A intensityExtractor=%7Bm =%3E this.props.ons ? parseFloat(m.ons) / 20 : parseFloat(m.offs) / 20%7D%0A /%3E%0A )%0A %7D
%0A getHi
@@ -4605,372 +4605,25 @@
%7B
-!
this.
-props.hideHeatmap &&%0A %3CHeatmapLayer%0A points=%7Bthis.props.am ? APC_AM : APC_PM%7D%0A longitudeExtractor=%7Bm =%3E parseFloat(m.longitude) %7C%7C 33%7D%0A latitudeExtractor=%7Bm =%3E parseFloat(m.latitude) %7C%7C -87%7D%0A intensityExtractor=%7Bm =%3E this.props.ons ? parseFloat(m.ons) / 20 : parseFloat(m.offs) / 20%7D%0A /%3E%0A
+getHeapMap()
%7D%0A
|
6929e3a139b2af1c2e74e06d9412730c59a1e177
|
check for updates immediately
|
app/components/Updater.js
|
app/components/Updater.js
|
const { lt } = require('semver');
const { get } = require('https');
const { autoUpdater } = require('electron');
class Updater {
constructor(options = {}) {
const {
checkEvery = 1000 * 60 * 60,
currentVersion,
feedUrl,
logger,
onUpdateDownloaded,
} = options;
this.feedUrl = feedUrl;
this.logger = logger;
autoUpdater.on('error', this.onError.bind(this));
autoUpdater.on('update-downloaded', onUpdateDownloaded);
setInterval(this.onTick.bind(this, currentVersion), checkEvery);
this.logger.debug('Updater module created.');
this.logger.debug(`Checking “${feedUrl}” every ${checkEvery / 1000} seconds for updates.`);
}
async fetchJson() {
return new Promise((resolve, reject) => {
const request = get(this.feedUrl, (response) => {
const { statusCode } = response;
const json = [];
if (statusCode !== 200) {
reject(new Error(`Feed url is not reachable. Response status code is ${statusCode}.`));
} else {
response.on('data', json.push.bind(json));
response.on('end', () => {
try {
resolve(JSON.parse(json.join()));
} catch (e) {
this.logger.error('Couldn’t parse feed response.');
}
});
}
});
request.on('error', reject);
});
}
quitAndInstall() {
autoUpdater.quitAndInstall();
return this;
}
async onTick(currentVersion) {
try {
const { version } = await this.fetchJson();
if (lt(currentVersion, version) === false) {
return;
}
autoUpdater.setFeedURL(this.feedUrl);
autoUpdater.checkForUpdates();
this.logger.debug(`Update available. (${currentVersion} -> ${version})`);
} catch ({ message }) {
this.logger.warning(message);
}
}
onError({ message }) {
this.logger.warning(message);
return this;
}
}
module.exports = Updater;
|
JavaScript
| 0 |
@@ -681,16 +681,36 @@
ates.%60);
+%0A%0A this.onTick();
%0A %7D%0A%0A
|
df8cdf40bf1d9a7fc989b99493e7eade860f5f56
|
make these local vars
|
drivers/status/pubsub.js
|
drivers/status/pubsub.js
|
/*******************
* This is the pubsub driver that should tell caspa about the melted status
*
*******************/
events = require('events');
utils = require('utils');
_ = require('underscore');
mbc = require('mbc-common');
defaults = { // copied from caspa/models.App.Status
_id: 1,
piece: {
previous: null,
curent: null,
next: null
},
show: {
previous: null,
current: null,
next: null,
},
source: null,
no_air: false
};
function CaspaDriver() {
events.EventEmitter.call(this);
var self = this;
this.status = _.clone(defaults);
this.channel = "mostoStatus";
this.publisher = mbc.pubsub();
var setups = [
self.setupStatus
];
var sendReady = _.times(setups.length, function() {
self.emit('ready');
});
setups.forEach(function(setup){
setup(sendReady);
});
CaspaDriver.prototype.setupStatus = function(callback) {
var db = mbc.db();
var col = db.collection('status');
col.findOne({_id: 1}, function(err, res) {
if( err )
// err.. do something?
return;
if( !res ) {
// the status doesn't exist, create it
col.create(self.status, function(err, itm) {
callback();
});
} else {
// res existed, just signal as ready
callback();
}
});
};
CaspaDriver.prototype.setStatus = function(status) {
// this overrides this.status with the values passed by status
this.status = _.extend(this.status, status);
this.publish(status);
};
CaspaDriver.prototype.publish = function(status) {
this.publisher.publish({backend: this.channel, model: status});
};
CaspaDriver.prototype.publishStatus = function(status) {
this.publisher.publish({backend: "mostoStatus", model: status})
};
}
util.inherits(CaspaDriver, events.EventEmitter);
exports = module.exports = function() {
driver = new CaspaDriver();
return driver;
};
|
JavaScript
| 0.001892 |
@@ -115,16 +115,20 @@
******/%0A
+var
events =
@@ -147,21 +147,24 @@
ents');%0A
+var
util
-s
= requi
@@ -171,21 +171,24 @@
re('util
-s
');%0A
+var
_ = requ
@@ -206,16 +206,20 @@
core');%0A
+var
mbc = re
|
d814ef15799f5874dfe312712aaa5da0d474d04a
|
Define global symbol which to be exported, by "var" instead of "const".
|
modules/lib/WindowManager.js
|
modules/lib/WindowManager.js
|
/**
* @fileOverview Window manager module for restartless addons
* @author YUKI "Piro" Hiroshi
* @version 5
*
* @license
* The MIT License, Copyright (c) 2010-2014 YUKI "Piro" Hiroshi.
* https://github.com/piroor/restartless/blob/master/license.txt
* @url http://github.com/piroor/restartless
*/
const EXPORTED_SYMBOLS = ['WindowManager'];
var _WindowWatcher = Cc['@mozilla.org/embedcomp/window-watcher;1']
.getService(Ci.nsIWindowWatcher);
var _WindowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
.getService(Ci.nsIWindowMediator);
var _gListener = {
observe : function(aSubject, aTopic, aData)
{
if (
aTopic == 'domwindowopened' &&
!aSubject
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell)
.QueryInterface(Ci.nsIDocShellTreeNode || Ci.nsIDocShellTreeItem) // nsIDocShellTreeNode is merged to nsIDocShellTreeItem by https://bugzilla.mozilla.org/show_bug.cgi?id=331376
.QueryInterface(Ci.nsIDocShellTreeItem)
.parent
)
aSubject
.QueryInterface(Ci.nsIDOMWindow)
.addEventListener('DOMContentLoaded', this, false);
},
handleEvent : function(aEvent)
{
aEvent.currentTarget.removeEventListener(aEvent.type, this, false);
var window = aEvent.target.defaultView;
this.listeners.forEach(function(aListener) {
try {
if (aListener.handleEvent &&
typeof aListener.handleEvent == 'function')
aListener.handleEvent(aEvent);
if (aListener.handleWindow &&
typeof aListener.handleWindow == 'function')
aListener.handleWindow(window);
if (typeof aListener == 'function')
aListener(window);
}
catch(e) {
dump(e+'\n');
}
});
},
listeners : []
};
_WindowWatcher.registerNotification(_gListener);
/**
* @class
* Provides features to get existing chrome windows, etc.
*/
var WindowManager = {
/**
* Registers a handler for newly opened chrome windows. Handlers will
* be called when DOMContentLoaded events are fired in newly opened
* windows.
*
* @param {Object} aHandler
* A handler for new windows. If you specify a function, it will be
* called with the DOMWindow object as the first argument. If the
* specified object has a method named "handleWindow", then the
* method will be called with the DOMWindow. If the object has a
* method named "handleEvent", then it will be called with the
* DOMContentLoaded event object (not DOMWindow object.)
*/
addHandler : function(aListener)
{
if (!_gListener) return;
if (
aListener &&
(
typeof aListener == 'function' ||
(aListener.handleWindow && typeof aListener.handleWindow == 'function') ||
(aListener.handleEvent && typeof aListener.handleEvent == 'function')
) &&
_gListener.listeners.indexOf(aListener) < 0
)
_gListener.listeners.push(aListener);
},
/**
* Unregisters a handler.
*/
removeHandler : function(aListener)
{
if (!_gListener) return;
let index = _gListener.listeners.indexOf(aListener);
if (index > -1)
_gListener.listeners.splice(index, 1);
},
/**
* Returns the most recent chrome window (DOMWindow).
*
* @param {string=} aWindowType
* The window type you want to get, ex. "navigator:browser". If you
* specify no type (null, blank string, etc.) then this returns
* the most recent window of any type.
*
* @returns {nsIDOMWindow}
* A found DOMWindow.
*/
getWindow : function(aType)
{
return _WindowMediator.getMostRecentWindow(aType || null);
},
/**
* Returns an array of chrome windows (DOMWindow).
*
* @param {string=} aWindowType
* The window type you want to filter, ex. "navigator:browser". If
* you specify no type (null, blank string, etc.) then this returns
* an array of all chrome windows.
*
* @returns {Array}
* An array of found DOMWindows.
*/
getWindows : function(aType)
{
var array = [];
var windows = _WindowMediator.getZOrderDOMWindowEnumerator(aType || null, true);
// By the bug 156333, we cannot find windows by their Z order on Linux.
// https://bugzilla.mozilla.org/show_bug.cgi?id=156333
if (!windows.hasMoreElements())
windows = _WindowMediator.getEnumerator(aType || null);
while (windows.hasMoreElements())
{
array.push(windows.getNext().QueryInterface(Ci.nsIDOMWindow));
}
return array;
}
};
for (let i in WindowManager)
{
exports[i] = (function(aSymbol) {
return function() {
return WindowManager[aSymbol].apply(WindowManager, arguments);
};
})(i);
}
/** A handler for bootstrap.js */
function shutdown()
{
_WindowWatcher.unregisterNotification(_gListener);
_WindowWatcher = void(0);
_gListener.listeners = [];
}
|
JavaScript
| 0.000011 |
@@ -329,13 +329,11 @@
%0D%0A%0D%0A
-const
+var
EXP
|
ac810028c27f10889f390870f7eb1793c14540aa
|
add organization router
|
cabrini-server/server.js
|
cabrini-server/server.js
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var User = require('./models/User');
var ToDoList = require('./models/ToDoList');
var ToDoListItem = require('./models/ToDoListItem');
app.use(bodyParser.json());
app.use('/users', require('./controllers/users'));
mongoose.connect('mongodb://localhost/test');
/*
User.remove({}, function(err) {
console.log('collection removed') ;
});
*/
/*
var toDoList = new ToDoList({ _id: 0, title: 'Test to-do List', age: 100 });
toDoList.save(function (err) {
if (err) throw err;
var toDoListItem = new ToDoListItem({_todo_list_id: toDoList._id, text: 'Get your birth certificate'});
toDoListItem.save(function (err) {
if (err) throw err;
});
toDoList.items.push(toDoListItem);
toDoList.save();
});
*/
var port = process.env.PORT || 1337;
app.get('/', function (req, res) {
/*
// get all the users
User.find({}, function(err, users) {
if (err) throw err;
// object of all the users
res.send(users);
});
*/
ToDoList.find({}).populate('items').exec(function (err, toDoList) {
if (err) throw err;
res.send(toDoList);
});
});
var server = app.listen(port, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
|
JavaScript
| 0 |
@@ -340,16 +340,82 @@
ers'));%0A
+app.use('/organizations', require('./controllers/organizations'));
%0A%0Amongoo
|
6ba3298693735cb943e31f2b52b98f083df0835b
|
add stub releaseTile method
|
modules/lib/mmap_app/bing.js
|
modules/lib/mmap_app/bing.js
|
// namespacing!
if (!MM) {
MM = { };
}
MM.BingProvider = function(key, style, onready) {
this.key = key;
this.style = style;
// hit the imagery metadata service
// http://msdn.microsoft.com/en-us/library/ff701716.aspx
// Aerial, AerialWithLabels, Road
var script = document.createElement('script');
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
script.src = 'http://dev.virtualearth.net/REST/V1/Imagery/Metadata/'+style+'/?key='+key+'&jsonp=onBingComplete';
function toMicrosoft(column, row, zoom) {
// generate zoom string by interleaving row/col bits
// NB:- this assumes you're only asking for positive row/cols
var quadKey = "";
for (var i = 1; i <= zoom; i++) {
var rowBit = (row >> zoom-i) & 1;
var colBit = (column >> zoom-i) & 1;
quadKey += (rowBit << 1) + colBit;
}
return quadKey;
}
var provider = this;
window.onBingComplete = function(data) {
var resourceSets = data.resourceSets;
for (var i = 0; i < resourceSets.length; i++) {
var resources = data.resourceSets[i].resources;
for (var j = 0; j < resources.length; j++) {
var resource = resources[j];
var serverSalt = Math.floor(Math.random() * 4);
provider.getTile = function(coord) {
var quadKey = toMicrosoft(coord.column, coord.row, coord.zoom);
// this is so that requests will be consistent in this session, rather than totally random
var server = Math.abs(serverSalt + coord.column + coord.row + coord.zoom) % 4;
return resource.imageUrl
.replace('{quadkey}',quadKey)
.replace('{subdomain}', resource.imageUrlSubdomains[server]);
};
// TODO: use resource.imageWidth
// TODO: use resource.imageHeight
}
}
// TODO: display data.brandLogoUri
// TODO: display data.copyright
if (onready) {
onready(provider);
}
};
};
MM.BingProvider.prototype = {
key: null,
style: null,
subdomains: null,
getTileUrl: null
};
MM.extend(MM.BingProvider, MM.MapProvider);
|
JavaScript
| 0 |
@@ -1934,16 +1934,76 @@
%7D;%0A
+ provider.releaseTile = function(coord) %7B %7D;%0A
|
ff67dd44419a17bbc405cfb0a7997f600709313d
|
fix transcoded non English characters
|
assets/js/app.js
|
assets/js/app.js
|
(function($) {
function init() {
/* Sidebar height set */
$sidebarStyles = $('.sidebar').attr('style') || "";
$sidebarStyles += ' min-height: ' + $(document).height() + 'px;';
$('.sidebar').attr('style', $sidebarStyles);
/* Secondary contact links */
var $scontacts = $('#contact-list-secondary');
var $contactList = $('#contact-list');
$scontacts.hide();
$contactList.mouseenter(function(){ $scontacts.fadeIn(); });
$contactList.mouseleave(function(){ $scontacts.fadeOut(); });
/**
* Tags & categories tab activation based on hash value. If hash is undefined then first tab is activated.
*/
function activateTab() {
if(['/tags.html', '/categories.html'].indexOf(window.location.pathname) > -1) {
var hash = window.location.hash;
if(hash)
$('.tab-pane').length && $('a[href="' + hash + '"]').tab('show');
else
$('.tab-pane').length && $($('.cat-tag-menu li a')[0]).tab('show');
}
}
// watch hash change and activate relevant tab
$(window).on('hashchange', activateTab);
// initial activation
activateTab();
};
// run init on document ready
$(document).ready(init);
})(jQuery);
|
JavaScript
| 0.999246 |
@@ -778,16 +778,35 @@
hash =
+decodeURIComponent(
window.l
@@ -817,16 +817,17 @@
ion.hash
+)
;%0A
@@ -1238,8 +1238,9 @@
jQuery);
+%0A
|
b38d8b2e2b0f9f5e062ca48cc37b1c70279c7dd8
|
Elimina console.log shit...
|
assets/js/app.js
|
assets/js/app.js
|
window.events = window.events || [];
var triggerNav = function() {
document.querySelector('.resToggle').addEventListener('click', function() {
document.querySelector('.smx-navigation').classList.toggle('active')
});
}
function appendFrameListener(config) {
var el = document.getElementById(config.button);
if (el) {
el.addEventListener('click', function() {
document.getElementById(config.container).innerHTML = config.frame;
});
}
}
var loadCSS = function() {
// <link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono" rel="stylesheet">
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono';
link.media = 'all';
head.appendChild(link);
}
function addEventListeners() {
// Map Lazy Loading
var mapFrame = '<iframe src="https://www.google.com/maps/d/u/0/embed?mid=13B_gbt3e5RWk_6xQoQ15xxhGOFs&ll=19.373256300000023%2C-99.13833979999998&z=11&hootPostID=1f18a5617f5da88fa1f7bff84bf31a46" width="100%" height="480"></iframe>';
var criticalMapFrame = '<iframe src="https://www.google.com/maps/d/u/0/embed?hl=en&mid=1PwJrCIjz5PNfKAFrY-EX-iEkWH8&ll=19.372169291390605%2C-99.16998963041652&z=14" width="100%" height="480"></iframe>';
// Spreadsheet lazy loading
var reportsFrame = '<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vQ6CChYk0cXlp_R_L2r9Enkar8qmDdGtu2CCE6dYYdU391PBt6zzePYQAkTJ5zJ6DHvkPsWu3Oty206/pubhtml?widget=true&headers=false" width="100%" height="480"></iframe>';
var mappingFrame = '<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vQ6CChYk0cXlp_R_L2r9Enkar8qmDdGtu2CCE6dYYdU391PBt6zzePYQAkTJ5zJ6DHvkPsWu3Oty206/pubhtml?widget=true&headers=false" width="100%" height="480"></iframe>';
var rescuedFrame = '<iframe src="https://docs.google.com/spreadsheets/d/1-17hTtd6ft1CmEut-cb-brm7C1JA_lUgpoiVsPN2kkE/pubhtml?widget=true&headers=false&gid=0" width="100%" height="480"></iframe>';
var sheetsConfig = [
{
button: 'map-container-btn',
container: 'map-container',
frame: mapFrame
}, {
button: 'critical-zones-btn',
container: 'critical-zones-container',
frame: criticalMapFrame
}, {
button: 'reports-sheet-container-btn',
container: 'reports-sheet-container',
frame: reportsFrame
}, {
button: 'mapping-sheet-container-btn',
container: 'mapping-sheet-container',
frame: mappingFrame
}, {
button: 'rescued-sheet-container-btn',
container: 'rescued-sheet-container',
frame: rescuedFrame
}
];
for (var i = 0; i < sheetsConfig.length; i++) {
appendFrameListener(sheetsConfig[i]);
}
$(document).on('click', '.open_as_iframe', function(event) {
event.preventDefault();
var me = $(event.target);
var parent = me.parent();
var iframeEL = '<iframe src="' + me.attr('href') + '" width="100%" height="480"></iframe>'
parent.append(iframeEL);
me.detach();
});
}
window.events.push(addEventListeners);
window.events.push(triggerNav);
window.events.push(loadCSS);
$(document).ready(function() {
console.log('shit');
window.events.forEach(function(event) {
event();
});
});
|
JavaScript
| 0 |
@@ -3144,30 +3144,8 @@
) %7B%0A
-%09console.log('shit');%0A
%09win
|
8d33f05e73a61b65c2958e7b5c8c0a8d9ed44ee1
|
Update to app.js
|
assets/js/app.js
|
assets/js/app.js
|
var app = angular.module("CornerStoneApp", ['angucomplete']); // module init
app.controller("MainController", function($scope, $http) { // controller init
$scope.autocomplete = [];
$scope.testimonies = [];
$scope.imageData = [];
$scope.imageRow2 = [];
$scope.searching = false;
$http.get("assets/data/autocomplete.json").then(function(response) {
$scope.autocomplete = response.data;
});
$http.get("assets/data/testimonies.json").then(function(response) {
$scope.testimonies = response.data;
});
// instagram images
$http.get("//www.instagram.com/JoinCornerstone/media/").then(function(response) {
var half_length = Math.ceil(response.data.items.length / 2);
$scope.imageData = response.data.items.splice(0, half_length);
$scope.imageRow2 = response.data.items;
console.log($scope.imageRow2);
}, function(response) {
//Second function handles error
alert('Network Error Occurred');
});
$scope.searchBar = function() {
$scope.searching = !$scope.searching;
};
});
|
JavaScript
| 0.000001 |
@@ -966,15 +966,26 @@
-alert('
+console.log('CORS
Netw
|
14623126c4e33aa90a195e05e6bf516672e3e804
|
Fix network creation heisenbug
|
src/include/container-manager-docker-helper.js
|
src/include/container-manager-docker-helper.js
|
/*jshint esversion: 6 */
var Docker = require('dockerode');
var DockerEvents = require('docker-events');
var docker = new Docker();
var dockerEmitter = new DockerEvents({docker:docker});
exports.getDockerEmitter = function () {
return dockerEmitter;
};
exports.getDocker = function () {
return docker;
};
//kill a container without updating the slastore
exports.kill = function (id) {
return new Promise( (resolve, reject) => {
container = docker.getContainer(id);
container.stop({},(err,data) => {
resolve();
});
});
}
//force container removal
exports.remove = function (id) {
return new Promise( (resolve, reject) => {
container = docker.getContainer(id);
container.remove({force: true},(err,data) => {
if(err) {
console.log("[remove]" + err);
reject(err);
return;
}
resolve();
});
});
}
exports.createNetwork = function(name, external) {
return new Promise( (resolve, reject) => {
docker.createNetwork({
Name: name,
Driver: 'bridge',
Internal: !external
}, (err,data) => {
if(err) {
reject("[createNetwork] Can't list networks");
return;
}
resolve(data);
})
});
}
var listNetworks = function() {
return new Promise( (resolve, reject) => {
docker.listNetworks({}, (err,data) => {
if(err) reject("[listNetworks] Can't list networks");
resolve(data);
})
});
}
exports.listNetworks = listNetworks;
var getNetwork = function(networks, name, external) {
return new Promise( (resolve, reject) => {
for(i in networks) {
var net = networks[i];
if(net.Name === name) {
var n = docker.getNetwork(net.Id)
resolve(n)
return;
}
}
docker.createNetwork({
Name: name,
Driver: 'bridge',
Internal: !external
}, (err,data) => {
if(err) reject("[getNetwork] Can't create networks")
resolve(data);
})
});
}
exports.getNetwork = getNetwork;
exports.connectToNetwork = function (container, networkName) {
return new Promise( (resolve, reject) => {
console.log('[' + container.name + '] Connecting to ' + networkName);
listNetworks({})
.then( (nets) => { return getNetwork(nets,networkName)})
.then( (net) => {
net.connect({'Container':container.id}, (err,data) => {
if(err) {
reject("Can't connect to network" + err);
return;
}
resolve(container);
});
})
.catch(err => reject('[connectToNetwork]' + err))
});
};
exports.disconnectFromNetwork = function (container, networkName) {
return new Promise( (resolve, reject) => {
listNetworks({})
.then( (nets) => { return getNetwork(nets,networkName)})
.then( (net) => {
net.disconnect({'Container':container.id}, (err,data) => {
if(err) {
reject("Can't disconnect from network" + err);
return;
}
resolve(container);
});
})
.catch(err => reject('[disconnectFromNetwork]' + err))
});
};
exports.createContainer = function(opts) {
return new Promise( (resolve, reject) => {
//TODO: check opts
docker.createContainer(opts,(err ,cont) => {
if(err) {
reject('createContainer'+err);
return;
}
resolve(cont);
})
});
}
exports.inspectContainer = function(cont) {
return new Promise( (resolve, reject) => {
//TODO: check cont
cont.inspect((err ,data, cont) => {
if(err) {
reject('inspectContainer::'+err);
return;
}
resolve(data);
})
});
}
|
JavaScript
| 0.000044 |
@@ -1108,32 +1108,34 @@
ata) =%3E %7B%0A
+
if(err) %7B%0A
@@ -1120,32 +1120,34 @@
if(err) %7B%0A
+
reject(%22
@@ -1173,33 +1173,39 @@
't list networks
-%22
+:%22, err
);%0A retur
@@ -1191,32 +1191,34 @@
, err);%0A
+
return;%0A %7D%0A
@@ -1211,32 +1211,34 @@
turn;%0A
+
%7D%0A
resolve(data
@@ -1217,32 +1217,34 @@
%7D%0A
+
+
resolve(data);%0A
@@ -1238,34 +1238,37 @@
olve(data);%0A
+
%7D)
+;
%0A %7D);%0A%7D%0A%0Avar li
@@ -1959,31 +1959,47 @@
%3E %7B%0A
+
if(err)
+ %7B%0A
reject(%22%5Bge
@@ -2033,11 +2033,52 @@
orks
-%22)%0A
+:%22, err);%0A return;%0A %7D%0A
@@ -2098,26 +2098,29 @@
ata);%0A
+
%7D)
+;
%0A %7D);%0A%7D%0Aexp
|
3eadbc1a2a7c1bd285c5f5f31396d83df738cbde
|
Fix exception on api login
|
auth/passport.js
|
auth/passport.js
|
"use strict";
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const usr = require('../models/user');
// Passport session set-up
passport.serializeUser((user, done) => {
done(null, user.user_id);
});
passport.deserializeUser(async (req, id, done) => {
const queryRes = await usr.getUserByField('user_id', id);
if (queryRes.rowCount === 0) {
done(null, {});
} else {
done(null, queryRes.rows[0]);
}
});
passport.use(new LocalStrategy({usernameField: 'username', passwordField: 'password', passReqToCallback: true},
async (req, username, password, done) => {
const queryRes = await usr.getUserByField('username', username);
if (queryRes.rowCount === 0) {
req.flash('error', 'No such user');
req.session.save(() => {
return done(null, false);
});
} else {
const authOK = await usr.checkPassword(queryRes.rows[0], password);
if (authOK) {
return done(null, queryRes.rows[0]);
} else {
req.flash('error', 'Wrong password');
req.session.save(() => {
return done(null, false);
});
}
}
})
);
module.exports = passport;
|
JavaScript
| 0.000003 |
@@ -744,32 +744,145 @@
wCount === 0) %7B%0A
+ // No sessions with API logins, so don't store flash message and save sessions%0A try %7B%0A
req.
@@ -917,32 +917,36 @@
');%0A
+
req.session.save
@@ -946,32 +946,126 @@
on.save(() =%3E %7B%0A
+ return done(null, false);%0A %7D);%0A %7D catch (err) %7B%0A
@@ -1095,34 +1095,32 @@
);%0A %7D
-);
%0A %7D else
@@ -1293,32 +1293,153 @@
%7D else %7B%0A
+ // No sessions with API logins, so don't store flash message and save sessions%0A try %7B%0A
@@ -1484,32 +1484,36 @@
+
req.session.save
@@ -1513,32 +1513,138 @@
on.save(() =%3E %7B%0A
+ return done(null, false);%0A %7D);%0A %7D catch (err) %7B%0A
@@ -1665,32 +1665,32 @@
e(null, false);%0A
+
@@ -1682,34 +1682,32 @@
%7D
-);
%0A %7D%0A
|
687ca5854021d086c596c0069ffd7ffb23b1ddf2
|
Implement collection editor / viewer (mantis 452)
|
src/main/webapp/resources/js/collections/edit.js
|
src/main/webapp/resources/js/collections/edit.js
|
var editor;
$(document).ready(function() {
editor = new CollectionEditor();
$("#btn-add-description").click(function() { editor.triggerAddTableElement(); return false;});
});
var CollectionEditor = function() {};
CollectionEditor.prototype.triggerAddTableElement = function() {
$.ajax({
url: __util.getBaseUrl() + "collections/includes/editDescription",
type: "GET",
dataType: "html",
success: function(data) {
// Hide placeholder row
$("#tbl-collection-description-sets .collection-editor-table-empty-placeholder").hide();
// Hide all existing form-rows
$("#tbl-collection-description-sets tr.edit").hide();
$("#tbl-collection-description-sets tbody").append(data);
},
error: function(textStatus) { }
});
};
CollectionEditor.prototype.editEntry = function(btn) {
var expand = $(btn).closest("tr").next().css("display")=="none";
$(btn).closest("table").find("tr.edit").hide();
if (expand) {
$(btn).closest("tr").next().show();
}
};
CollectionEditor.prototype.removeEntry = function(btn) {
$(btn).closest("tr").next().remove();
$(btn).closest("tr").remove();
};
|
JavaScript
| 0 |
@@ -170,13 +170,75 @@
%7D);%0A
+%09%0A%09$(%22form%22).submit(function(event) %7B editor.submit(event);
%7D);%0A
-%0A
+%7D);
%0A%0Ava
@@ -1256,12 +1256,137 @@
remove();%0A%7D;
+%0A%0ACollectionEditor.prototype.submit = function(event) %7B%0A%09%0A%09event.preventDefault();%09// Assume error for now%0A%09return false; %0A%7D;
|
5e29c86bb7cb6a921c8b5df7b431a7e4b8d5f852
|
Solve bug editor - You should be connected
|
src/marknotes/plugins/page/html/editor/editor.js
|
src/marknotes/plugins/page/html/editor/editor.js
|
/**
* $params is a JSON object initiliazed by the /assets/js/marknotes.js file.
*/
function fnPluginButtonEdit($params) {
/*<!-- build:debug -->*/
if (marknotes.settings.debug) {
console.log(' Plugin Page html - Editor');
}
/*<!-- endbuild -->*/
if (marknotes.note.url == '') {
Noty({
message: $.i18n('error_select_first'),
type: 'error'
});
} else {
ajaxify({
task: 'task.edit.form',
param: marknotes.note.md5,
callback: 'afterEdit($data)',
useStore: false,
target: 'CONTENT'
});
}
return true;
}
/**
* EDIT MODE - Render the textarea in an editor
*/
function afterEdit($data) {
/*<!-- build:debug -->*/
if (marknotes.settings.debug) {
console.log(' Plugin Page html - Editor - afterEdit');
}
/*<!-- endbuild -->*/
if (document.getElementById("sourceMarkDown") !== null) {
afterEditInitMDE($data);
} else {
Noty({
message: $.i18n('not_authenticated'),
type: 'error'
});
}
return true;
}
function afterEditInitMDE($data) {
/*<!-- build:debug -->*/
if (marknotes.settings.debug) {
console.log(' Plugin Page html - Editor - afterEdit');
console.log($data);
}
/*<!-- endbuild -->*/
filename = $data.param;
// Create the Simple Markdown Editor
// @link https://github.com/NextStepWebs/simplemde-markdown-editor
var simplemde = new SimpleMDE({
autoDownloadFontAwesome: false,
autofocus: true,
autosave: {
enabled: false
},
codeSyntaxHighlighting: true,
element: document.getElementById("sourceMarkDown"),
indentWithTabs: true,
insertTexts: {
horizontalRule: ["", "\n\n---\n\n"],
image: [""],
link: ["[", "](https://)"],
table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| --- | --- | --- |\n| Text | Text | Text |\n\n"],
},
spellChecker: true,
status: ["autosave", "lines", "words", "cursor"], // Optional usage
styleSelectedText: false,
tabSize: 4,
toolbar: [
{
// Add a custom button for saving
name: "Save",
action: function customFunction(editor) {
buttonSave(filename, simplemde.value());
},
className: "fa fa-floppy-o",
title: $.i18n('button_save')
},
{
// Encrypt
name: "Encrypt",
action: function customFunction(editor) {
buttonEncrypt(editor);
},
className: "fa fa-user-secret",
title: $.i18n('button_encrypt')
},
{
// Table of content
name: "AddTOC",
action: function customFunction(editor) {
buttonAddTOC(editor);
},
className: "fa fa-map-o",
title: $.i18n('button_addTOC')
},
"|",
{
// Add a custom button for saving
name: "Exit",
action: function customFunction(editor) {
$('#sourceMarkDown').parent().hide();
ajaxify({
task: 'task.export.html',
param: filename,
callback: 'afterDisplay($data.param)',
target: 'CONTENT'
});
},
className: "fa fa-sign-out",
title: $.i18n('button_exit_edit_mode')
},
"|", "preview", "side-by-side", "fullscreen", "|",
"bold", "italic", "strikethrough", "|", "heading", "heading-smaller", "heading-bigger", "|", "heading-1", "heading-2", "heading-3", "|",
"code", "quote", "unordered-list", "ordered-list", "clean-block", "|", "link", "image", "table", "horizontal-rule"
] // toolbar
});
// $('.editor-toolbar').addClass('fa-2x');
return true;
}
/**
* EDIT MODE - Save the new content. Called by the "Save" button
* of the simplemde editor, initialized in the afterEdit function)
*
* @param {type} $fname Filename
* @param {type} $markdown The new content
* @returns {boolean}
*/
function buttonSave($fname, $markdown) {
/*<!-- build:debug -->*/
if (marknotes.settings.debug) {
console.log(' Plugin Page html - Editor - Save');
}
/*<!-- endbuild -->*/
var $data = {};
$data.task = 'task.edit.save';
$data.param = $fname;
$data.markdown = window.btoa(encodeURIComponent(JSON.stringify($markdown)));
$.ajax({
async: true,
// GET can't be used because note's content can be too big for URLs
type: 'POST',
url: marknotes.url,
data: $data,
datatype: 'json',
success: function (data) {
Noty({
message: data.message,
type: (data.status == 1 ? 'success' : 'error')
});
var $useStore = (typeof store === 'object');
if ($useStore) {
// Be sure the localStorage array is up-to-date and willn't
// contains the previous content
fnPluginTaskOptimizeStore_Remove({
"name": $fname
});
}
}
}); // $.ajax()
return true;
}
/**
* EDIT MODE - Encrypt the selection. Add the <encrypt> tag
*
* @returns {boolean}
*/
function buttonEncrypt(editor) {
/*<!-- build:debug -->*/
if (marknotes.settings.debug) {
console.log(' Plugin Page html - Editor - Encrypt');
}
/*<!-- endbuild -->*/
var cm = editor.codemirror;
var output = '';
var selectedText = cm.getSelection();
var text = selectedText || 'your_confidential_info';
output = '<encrypt>' + text + '</encrypt>';
cm.replaceSelection(output);
}
/**
* ADD TOC - Add the %TOC_3% tag
*
* @returns {boolean}
*/
function buttonAddTOC(editor) {
/*<!-- build:debug -->*/
if (marknotes.settings.debug) {
console.log(' Plugin Page html - Editor - Add TOC tag');
}
/*<!-- endbuild -->*/
var cm = editor.codemirror;
// Just add the tag where the cursor is located
cm.replaceSelection('%TOC_5%');
}
|
JavaScript
| 0.000004 |
@@ -471,16 +471,22 @@
it($
+data,
data)',%0A
%09%09%09u
@@ -481,16 +481,16 @@
data)',%0A
-
%09%09%09useSt
@@ -625,20 +625,35 @@
erEdit($
-data
+ajax_request, $form
) %7B%0A%0A%09/*
@@ -793,24 +793,53 @@
uild --%3E*/%0A%0A
+%09$('#CONTENT').html($form);%0A%0A
%09if (documen
@@ -905,20 +905,28 @@
nitMDE($
-data
+ajax_request
);%0A%09%7D el
|
a39e866e97f908debef43f321d3bce56d461fe6a
|
fix lint errors
|
src/mixin/__tests__/StoreDependencyMixin-test.js
|
src/mixin/__tests__/StoreDependencyMixin-test.js
|
jest.dontMock('../StoreDependencyMixin.js');
describe('StoreDependencyMixin', () => {
let StoreDependencyMixin;
beforeEach(() => {
StoreDependencyMixin = require('../StoreDependencyMixin.js');
});
describe('propTypes', () => {
it('has propTypes if a dependency specifices them');
});
describe('componentWillMount', () => {
it('registers a callback with the dispatcher');
it('calculates and sets initial state');
});
describe('componentWillReceiveProps', () => {
it('calculates and sets state');
it('doesnt recalculate fields that dont use props');
});
describe('componentDidUpdate', () => {
it('has a componentDidUpdate if a field uses state');
it('bails out if only store state changed');
it('only recalculates fields that use state');
});
describe('handleDispatch', () => {
it('waits for all stores affected by the actionType');
it('only updates fields affected by the actionType');
});
describe('componentWillUnmount', () => {
it('unregisters its dispatcher callback');
});
});
|
JavaScript
| 0.000037 |
@@ -81,16 +81,19 @@
) =%3E %7B%0A
+ //
let Sto
@@ -136,16 +136,19 @@
=%3E %7B%0A
+ //
StoreDe
|
5b3cf0c082f7e0d2d7ccf8780cb9bb75ec3b8894
|
call fetchData instead of refresh in StoprintNotice and Error views
|
source/views/stoprint/print-jobs.js
|
source/views/stoprint/print-jobs.js
|
// @flow
import React from 'react'
import {SectionList} from 'react-native'
import {connect} from 'react-redux'
import {type ReduxState} from '../../flux'
import {updatePrintJobs} from '../../flux/parts/stoprint'
import {type PrintJob, STOPRINT_HELP_PAGE} from '../../lib/stoprint'
import {
ListRow,
ListSeparator,
ListSectionHeader,
Detail,
Title,
} from '../components/list'
import type {TopLevelViewPropsType} from '../types'
import delay from 'delay'
import openUrl from '../components/open-url'
import {StoprintErrorView, StoprintNoticeView} from './components'
import groupBy from 'lodash/groupBy'
import toPairs from 'lodash/toPairs'
import sortBy from 'lodash/sortBy'
type ReactProps = TopLevelViewPropsType
type ReduxStateProps = {
jobs: Array<PrintJob>,
error: ?string,
loading: boolean,
loginState: string,
}
type ReduxDispatchProps = {
updatePrintJobs: () => Promise<any>,
}
type Props = ReactProps & ReduxDispatchProps & ReduxStateProps
class PrintJobsView extends React.PureComponent<Props> {
static navigationOptions = {
title: 'Print Jobs',
headerBackTitle: 'Jobs',
}
componentDidMount() {
this.refresh()
}
refresh = async (): any => {
let start = Date.now()
await this.fetchData()
// console.log('data returned')
// wait 0.5 seconds – if we let it go at normal speed, it feels broken.
let elapsed = start - Date.now()
if (elapsed < 500) {
await delay(500 - elapsed)
}
}
fetchData = () => this.props.updatePrintJobs()
keyExtractor = (item: PrintJob) => item.id.toString()
openSettings = () => this.props.navigation.navigate('SettingsView')
handleJobPress = (job: PrintJob) => {
if (job.statusFormatted === 'Pending Release') {
this.props.navigation.navigate('PrinterListView', {job: job})
} else {
this.props.navigation.navigate('PrintJobReleaseView', {job: job})
}
}
renderItem = ({item}: {item: PrintJob}) => (
<ListRow onPress={() => this.handleJobPress(item)}>
<Title>{item.documentName}</Title>
<Detail>
{item.usageTimeFormatted} • {item.usageCostFormatted} •{' '}
{item.totalPages} pages • {item.statusFormatted}
</Detail>
</ListRow>
)
renderSectionHeader = ({section: {title}}: any) => (
<ListSectionHeader title={title} />
)
render() {
if (this.props.error) {
return (
<StoprintErrorView
navigation={this.props.navigation}
refresh={this.refresh}
/>
)
}
if (this.props.loginState !== 'logged-in') {
return (
<StoprintNoticeView
buttonText="Open Settings"
header="You are not logged in"
onPress={this.openSettings}
text="You must be logged in to your St. Olaf student account to access this feature"
/>
)
} else if (this.props.jobs.length === 0) {
return (
<StoprintNoticeView
buttonText="Install Stoprint"
header="Nothing to Print!"
onPress={() => openUrl(STOPRINT_HELP_PAGE)}
refresh={this.refresh}
text="Need help getting started?"
/>
)
}
const grouped = groupBy(this.props.jobs, j => j.statusFormatted || 'Other')
let groupedJobs = toPairs(grouped).map(([title, data]) => ({
title,
data,
}))
let sortedGroupedJobs = sortBy(groupedJobs, [
group => group.title !== 'Pending Release', // puts 'Pending Release' jobs at the top
])
return (
<SectionList
ItemSeparatorComponent={ListSeparator}
keyExtractor={this.keyExtractor}
onRefresh={this.refresh}
refreshing={this.props.loading}
renderItem={this.renderItem}
renderSectionHeader={this.renderSectionHeader}
sections={sortedGroupedJobs}
/>
)
}
}
function mapStateToProps(state: ReduxState): ReduxStateProps {
return {
jobs: state.stoprint ? state.stoprint.jobs : [],
error: state.stoprint ? state.stoprint.error : null,
loading: state.stoprint ? state.stoprint.loadingJobs : false,
loginState: state.settings ? state.settings.loginState : 'logged-out',
}
}
function mapDispatchToProps(dispatch): ReduxDispatchProps {
return {
updatePrintJobs: () => dispatch(updatePrintJobs()),
}
}
export const ConnectedPrintJobsView = connect(
mapStateToProps,
mapDispatchToProps,
)(PrintJobsView)
|
JavaScript
| 0 |
@@ -2370,31 +2370,33 @@
fresh=%7Bthis.
-refresh
+fetchData
%7D%0A%09%09%09%09/%3E%0A%09%09%09
@@ -2899,31 +2899,33 @@
fresh=%7Bthis.
-refresh
+fetchData
%7D%0A%09%09%09%09%09text=
|
3a42822b6b45bb4d346a4f5d8ce44873dc078bcb
|
Fix clip
|
sources/js/graphics/scene-object.js
|
sources/js/graphics/scene-object.js
|
import is_nil from 'lodash.isnil';
import is_number from 'lodash.isnumber';
import noop from 'lodash.noop';
function normalize_scale(scale) {
if (is_nil(scale)) {
scale = 1;
}
return is_number(scale) ? {x: scale, y: scale} : scale;
}
export default (coordinates, options = {}) => {
const onRender = is_nil(options.onRender) ? noop : options.onRender;
const onSceneChanged = is_nil(options.onSceneChanged) ? noop : options.onSceneChanged;
let scale = normalize_scale(options.scale);
let scene = null;
let visible = is_nil(options.visible) ? true : options.visible;
let zIndex = is_nil(options.zIndex) ? 0 : options.zIndex;
return {
zIndex() {
return zIndex;
},
setZIndex(value) {
if (zIndex !== value) {
zIndex = value;
if (!is_nil(scene)) {
// make the scene to sort its children
scene.add(this);
}
}
return this;
},
scene() {
return scene;
},
setScene(s) {
if (!is_nil(scene)) {
const tmp = scene;
scene = null;
tmp.remove(this);
}
if (!is_nil(s) && scene !== s) {
scene = s;
scene.add(this);
onSceneChanged.call(this, scene);
}
return this;
},
scale() {
return scale;
},
setScale(f) {
scale = is_number(f) ? {x: f, y: f} : f;
return this;
},
show() {
visible = true;
return this;
},
hide() {
visible = false;
return this;
},
visible() {
return visible;
},
setVisible(visibility) {
visible = visibility;
return this;
},
render(screen) {
if (visible) {
screen.save();
screen.setScale(scale);
screen.clipRect(coordinates.rect());
screen.translate(coordinates.position());
onRender.call(this, screen, scene, coordinates.localRect());
screen.restore();
}
return this;
}
};
}
|
JavaScript
| 0.000001 |
@@ -1573,16 +1573,17 @@
een.
-clipRect
+translate
(coo
@@ -1595,12 +1595,16 @@
tes.
-rect
+position
());
@@ -1611,33 +1611,32 @@
%0A%09%09%09%09screen.
-translate
+clipRect
(coordinates
@@ -1632,32 +1632,33 @@
coordinates.
-position
+localRect
());%0A%09%09%09%09onR
|
f096f3e2081a3e5591957e1e56415e69ab646786
|
Fix test, sort function always needs to return an integer
|
observe/sort/sort_test.js
|
observe/sort/sort_test.js
|
steal('can/util', 'can/observe/sort', 'can/view/mustache', function(can) {
module("can/observe/sort");
test("list events", 12, function(){
var list = new can.Observe.List([
{name: 'Justin'},
{name: 'Brian'},
{name: 'Austin'},
{name: 'Mihael'}])
list.comparator = 'name';
list.sort();
// events on a list
// - move - item from one position to another
// due to changes in elements that change the sort order
// - add (items added to a list)
// - remove (items removed from a list)
// - reset (all items removed from the list)
// - change something happened
// a move directly on this list
list.bind('move', function(ev, item, newPos, oldPos){
ok(true,"move called");
equals(item.name, "Zed");
equals(newPos, 3);
equals(oldPos, 0);
});
// a remove directly on this list
list.bind('remove', function(ev, items, oldPos){
ok(true,"remove called");
equals(items.length,1);
equals(items[0].name, 'Alexis');
equals(oldPos, 0, "put in right spot")
})
list.bind('add', function(ev, items, newLength){
ok(true,"add called");
equals(items.length,1);
equals(items[0].name, 'Alexis');
// .push returns the new length not the current position
equals(newLength, 4, "got new length");
});
list.push({name: 'Alexis'});
// now lets remove alexis ...
list.splice(0,1);
list[0].attr('name',"Zed")
});
test("list sort with func", 1, function(){
var list = new can.Observe.List([
{priority: 4, name: "low"},
{priority: 1, name: "high"},
{priority: 2, name: "middle"},
{priority: 3, name: "mid"}])
list.sort(function(a, b){
return a.priority > b.priority;
});
equals(list[0].name, 'high');
});
test("live binding with comparator (#170)", function() {
var renderer = can.view.mustache('<ul>{{#items}}<li>{{text}}</li>{{/items}}</ul>'),
el = document.createElement('div'),
items = new can.Observe.List([{
text : 'First'
}]);
el.appendChild(renderer({
items : items
}));
equals(el.getElementsByTagName('li').length, 1, "Found one li");
items.push({
text : 'Second'
});
equals(el.getElementsByTagName('li').length, 2, "Live binding rendered second li");
});
})();
|
JavaScript
| 0.00021 |
@@ -1578,16 +1578,128 @@
(a, b)%7B%0A
+%09%09// Sort functions always need to return the -1/0/1 integers%0A%09%09if(a.priority %3C b.priority) %7B%0A%09%09%09return -1;%0A%09%09%7D%0A
%09%09return
@@ -1722,16 +1722,24 @@
priority
+ ? 1 : 0
;%0A%09%7D);%0A%09
|
64cc94b68adaeb83954b91f0a6197f2e46ce6687
|
add new event changes
|
source/server/controllers/events-controller.js
|
source/server/controllers/events-controller.js
|
/**
* Created by admin on 2.12.2016 г..
*/
/* globals module require */
'use strict';
const passport = require('passport');
module.exports = (data) => {
return {
getCreateEventPage(req, res) {
let categoryName = req.params.categoryName;
if(!categoryName) {
categoryName = 'ski';
}
console.log(categoryName);
if (req.isAuthenticated()) {
res.render('./events/add-event-page', {
user: req.user,
category: categoryName
});
return;
}
res.render('auth-not-authorised-page');
},
getEventsPage(req, res){
let categoryName=req.params.category;
let eventId=req.params.id;
console.log('categoryName ' + categoryName);
console.log('eventId ' + eventId);
if(!categoryName && !eventId){
data.getAllEvents(req, res)
.then((events) => {
// TODO remove before production :)
console.log(events);
res.render('./events/all-categories-page', {
user: req.user,
events: events
});
})
.catch((error) => {
throw error;
});
} else if (categoryName && !eventId) {
data.getEventByCategoryName(categoryName)
.then((events) => {
// TODO remove before production :)
//console.log(events);
res.render('./events/single-category-page', {
user: req.user,
category: categoryName,
events: events
});
})
.catch((error) => {
throw error;
});
} else if (categoryName && eventId) {
data.getEventByCategoryAndId(categoryName, eventId)
.then((event) => {
// TODO remove before production :)
//console.log(event);
res.render('./events/single-event-page', {
user: req.user,
category: categoryName,
event: event
});
})
.catch((error) => {
throw error;
});
}
},
createEvent(req, res) {
let body = req.body,
nowDt = new Date(),
eventIsHidden = false,
categoryName = req.params.categoryName,
pictureUrl = req.body.eventPicture;
var _category = 'ski';
if(!(categoryName == undefined) && !(categoryName==='')){
_category = categoryName;
}
var _picture = { src: '/res/images/default-picture.png' };
if(!(pictureUrl == undefined) || !(pictureUrl==='')){
_picture.src = pictureUrl;
}
// TODO remove before production :)
console.log('picture-'+_picture);
console.log('category-'+_category);
data.eventCreateAndSave(body.title, categoryName, _picture, req.user, body.body, nowDt, eventIsHidden)
.then((dbEvent) => {
res.render('error-page', {
user: req.user,
error: dbEvent
});
})
.catch((error) => {
res.render('error-page', {
user: req.user,
error: error
});
});
// if (req.isAuthenticated()) {
// data.eventCreateAndSave(body.title, categoryName, _picture, req.user, body.body, nowDt, eventIsHidden)
// .then(() => {
// //res.status(201).redirect('http://localhost:3001/categories/201', { user: req.user }).end();
// //res.status(201).send('The request has been fulfilled and resulted in a new resource being created. OK!');
// // res.redirect('/categories/201', {
// // user: req.user
// // });
// //console.log('thenthen');
// res.render('all-categories-page', {
// user: req.user,
// category: categoryName,
// event: event
// });
// })
// .catch((err) => {
// // The request could not be completed due to a conflict with the current state of the resource.
// // {"code":11000,"index":0,"errmsg":"E11000 duplicate key error collection...
// if(err.code == 11000){
// // TODO delete duplicated key and try again
//
// var EventModel = data.EventModel;
// // mongoose.connection.db.executeDbCommand({ dropIndexes: EventModel, index: 'a*' },
// // var db = mongoose.connection;
// mongoose.connection.executeDbCommand({ dropIndexes: EventModel, index: 'a*' },
// function(err, result) {
// console.log('index is dropped');
// res.status(201).location('/categories/2011', { user: req.user }).end();
// });
//
// console.log('index error');
// res.status(409).location('/categories/409', { user: req.user }).end();
// }
//
// res.status(400).location('/categories/400', { user: req.user }).end();
//
// //res.status(409).send(err);
// //res.redirect('/', { user: req.user });
//
// //return;
// });
// }
//res.render('auth-not-authorised-page');
}
}
};
|
JavaScript
| 0.000001 |
@@ -2982,531 +2982,31 @@
-var _category = 'ski';%0A if(!(categoryName == undefined) && !(categoryName===''))%7B%0A _category = categoryName;%0A %7D%0A%0A var _picture = %7B src: '/res/images/default-picture.png' %7D;%0A if(!(pictureUrl == undefined) %7C%7C !(pictureUrl===''))%7B%0A _picture.src = pictureUrl;%0A %7D%0A%0A // TODO remove before production :)%0A console.log('picture-'+_picture);%0A console.log('category-'+_category);%0A%0A data.eventCreateAndSave
+data.createAndSaveEvent
(bod
@@ -3024,32 +3024,34 @@
tegoryName,
-_
picture
+Url
, req.user,
|
b3042cd07ab785de7c28b41a6a026d45e2bf5534
|
Fix for missing descriptions and defaults.
|
packages/gluegun-core/src/domain/runtime.js
|
packages/gluegun-core/src/domain/runtime.js
|
const parseCommandLine = require('../cli/parse-command-line')
const autobind = require('autobind-decorator')
const {
clone,
merge,
when,
equals,
always,
join,
split,
trim,
pipe,
replace,
find,
append,
forEach,
isNil,
map
} = require('ramda')
const { findByProp, startsWith, isNilOrEmpty } = require('ramdasauce')
const { isBlank } = require('../utils/string-utils')
const { subdirectories, isDirectory } = require('../utils/filesystem-utils')
const RunContext = require('./run-context')
const loadPluginFromDirectory = require('../loaders/toml-plugin-loader')
// core extensions
const addTemplateExtension = require('../core-extensions/template-extension')
const addPrintExtension = require('../core-extensions/print-extension')
const addFilesystemExtension = require('../core-extensions/filesystem-extension')
const addSystemExtension = require('../core-extensions/system-extension')
const addPromptExtension = require('../core-extensions/prompt-extension')
const addHttpExtension = require('../core-extensions/http-extension')
const addStringsExtension = require('../core-extensions/strings-extension')
const COMMAND_DELIMITER = ' '
/**
* Strips the command out of the args returns an array of the rest.
*
* @param {string} args The full arguments including command.
* @param {string} commandName The name of the command to strip.
*/
const extractSubArguments = (args, commandName) =>
pipe(
replace(commandName, ''),
trim,
split(COMMAND_DELIMITER),
when(equals(['']), always([]))
)(args)
/**
* Runs a command.
*
* @param {{}} options Additional options use to execute a command.
* If nothing is passed, it will read from the command line.
* @return {RunContext} The RunContext object indicating what happened.
*/
async function run (options) {
// prepare the run context
const context = new RunContext()
// attach the runtime
context.runtime = this
// prepare the context parameters
if (isNilOrEmpty(options)) {
// grab the params from the command line
const { first, rest, options } = parseCommandLine(process.argv)
context.parameters.pluginName = first
context.parameters.rawCommand = rest
context.parameters.options = options
} else {
// grab the options that were passed in
context.parameters.pluginName = options.pluginName
context.parameters.rawCommand = options.rawCommand
context.parameters.options = options.options
}
// bring them back out for convenience
const { pluginName, rawCommand } = context.parameters
// try finding the command in the default plugin first
const defaultPlugin = this.findCommand(this.defaultPlugin, rawCommand) && this.defaultPlugin
// find the plugin
const plugin = defaultPlugin || this.findPlugin(pluginName)
if (!plugin) {
return context
}
context.plugin = plugin
// setup the config
context.config = clone(this.defaults)
context.config[plugin.name] = merge(plugin.defaults, this.defaults[plugin.pluginName] || {})
// find the command
const command = this.findCommand(plugin, rawCommand)
if (command) {
context.command = command
// setup the rest of the parameters
const subArgs = extractSubArguments(rawCommand, trim(command.name))
context.parameters.array = subArgs
context.parameters.first = subArgs[0]
context.parameters.second = subArgs[1]
context.parameters.third = subArgs[2]
context.parameters.string = join(COMMAND_DELIMITER, subArgs)
// kick it off
if (command.run) {
// attach extensions
forEach(
extension => {
context[extension.name] = extension.setup(plugin, command, context)
},
this.extensions
)
try {
context.result = await command.run(context)
} catch (e) {
console.dir(e)
context.error = e
}
}
}
return context
}
/**
* Loads plugins an action through the gauntlet.
*/
class Runtime {
/**
* Create and initialize an empty Runtime.
*/
constructor (brand) {
this.brand = brand
this.run = run // awkward because node.js doesn't support async-based class functions yet.
this.plugins = []
this.extensions = []
this.defaults = {}
this.defaultPlugin = null
this.events = {}
this.addCoreExtensions()
}
/**
* Adds the core extensions. These provide the basic features
* available in gluegun, but follow the exact same method
* for extending the core as 3rd party extensions do.
*/
addCoreExtensions () {
this.addExtension('strings', addStringsExtension)
this.addExtension('print', addPrintExtension)
this.addExtension('template', addTemplateExtension)
this.addExtension('filesystem', addFilesystemExtension)
this.addExtension('system', addSystemExtension)
this.addExtension('http', addHttpExtension)
this.addExtension('prompt', addPromptExtension)
}
/**
* Adds an extension so it is available when commands run. They live
* as the given name on the context object passed to commands. The
* 2nd parameter is a function that, when called, creates that object.
*
* @param {string} name The context property name.
* @param {object} setup The setup function.
*/
addExtension (name, setup) {
this.extensions.push({ name, setup })
return this
}
/**
* Loads a plugin from a directory.
*
* @param {string} directory The directory to load from.
* @return {Plugin} A plugin.
*/
load (directory) {
const { extensionNameToken, commandNameToken, commandDescriptionToken } = this
const plugin = loadPluginFromDirectory(directory, {
extensionNameToken,
commandNameToken,
commandDescriptionToken
})
this.plugins = append(plugin, this.plugins)
return plugin
}
/**
* Loads a plugin from a directory and sets it as the default.
*
* @param {string} directory The directory to load from.
* @return {Plugin} A plugin.
*/
loadDefault (directory) {
const plugin = this.load(directory)
this.defaultPlugin = plugin
return plugin
}
/**
* Loads a bunch of plugins from the immediate sub-directories of a directory.
*
* @param {string} directory The directory to grab from.
* @return {Plugin[]} A bunch of plugins
*/
loadAll (directory) {
if (isBlank(directory) || !isDirectory(directory)) return []
return pipe(
subdirectories,
map(this.load)
)(directory)
}
/**
* The list of commands registered.
*
* @return {[]} A list of [{plugin, command}]
*/
listCommands () {
const commands = []
const eachPlugin = plugin => {
const eachCommand = command => {
commands.push({ plugin, command })
}
forEach(eachCommand, plugin.commands)
}
forEach(eachPlugin, this.plugins)
return commands
}
/**
* Find the plugin for this name.
*
* @param {string} name The name to search through.
* @returns {*} A Plugin otherwise null.
*/
findPlugin (name) {
return findByProp('name', name || '', this.plugins)
}
/**
* Find the command for this pluginName & command.
*
* @param {Plugin} plugin The plugin in which the command lives.
* @param {string} rawCommand The command arguments to parse.
* @returns {*} A Command otherwise null.
*/
findCommand (plugin, rawCommand) {
if (isNil(plugin) || isBlank(rawCommand)) return null
if (isNilOrEmpty(plugin.commands)) return null
return find(
(command) => startsWith(command.name, rawCommand)
, plugin.commands
)
}
}
module.exports = autobind(Runtime)
|
JavaScript
| 0 |
@@ -5535,16 +5535,23 @@
const %7B
+ brand,
extensi
@@ -5750,16 +5750,29 @@
ionToken
+,%0A brand
%0A %7D)%0A
|
d6a74db2b957a76966b653b6b3270df3fbc7a659
|
Create report folder if it does not exist
|
jenkins-build/e2e/config.servoy.js
|
jenkins-build/e2e/config.servoy.js
|
var startDate;
var find = require('find');
var fs = require('fs-extra');
var jsonDir = 'reports/cucumber_reports/';
var screenshotDir = 'screenshots/';
exports.config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
framework: 'custom',
params: {
testDomainURL: 'http://localhost:8080/solutions/sampleGallery/index.html?f=galleryMain'
},
// path relative to the current config file
frameworkPath: require.resolve('protractor-cucumber-framework'),
multiCapabilities: [{
'browserName': 'chrome'
}],
// resultJsonOutputFile: 'reports//cucumber_reports//report.json',
// Spec patterns are relative to this directory.
specs: [
'features/sample_application/*.feature'
],
cucumberOpts: {
require: ['features/step_definitions/servoy_step_definitions.js',
'env.js',
'features/step_definitions/hooks.js'],
tags: false,
// format: 'pretty',
format: ['json:reports/cucumber_reports/report.json', 'pretty'],
profile: false,
keepAlive: false,
'no-source': true
},
beforeLaunch: () => {
console.log('beforeLaunch');
removeJsonReports(); //removes reports from previous tests
removeScreenshots(); //remove screenshots from previous tests
startDate = new Date();
},
onPrepare: () => {
console.log('onPrepare');
browser.driver.executeScript(function () {
return {
width: window.screen.availWidth,
height: window.screen.availHeight
};
}).then(function (result) {
browser.driver.manage().window().setSize(result.width, result.height);
});
},
onComplete: () => {
console.log('onComplete');
},
onCleanUp: () => {
console.log('onCleanUp');
},
afterLaunch: () => {
console.log('afterLaunch');
}
};
function removeJsonReports() {
var files = find.fileSync(/\.json/, jsonDir);
files.map(function (file) {
fs.unlinkSync(file);
});
}
function removeScreenshots() {
var files = find.fileSync(/\.png/, jsonDir);
files.map(function (file) {
fs.unlinkSync(file);
});
}
|
JavaScript
| 0.000001 |
@@ -1089,20 +1089,42 @@
aunch');
+%0A
+createReportFolder();
%0A rem
@@ -2049,28 +2049,432 @@
fs.unlinkSync(file);%0A %7D);%0A%7D
+%0A%0Afunction createReportFolder() %7B%0A var path = require('path');%0A var proc = require('process');%0A var fs = require('fs');%0A var pathToCreate = proc.cwd() + '/reports/cucumber_reports';%0A pathToCreate.split(path.sep).reduce(function(currentPath, folder)%7B%0A currentPath += folder + path.sep;%0A if(!fs.existsSync(currentPath)) %7B%0A fs.mkdirSync(currentPath);%0A %7D%0A return currentPath;%0A %7D,'');%0A%7D
|
c926085331ba13562ddd6178fe60f633d16d9641
|
comment out stupid command
|
chat-plugins/big-talk.js
|
chat-plugins/big-talk.js
|
exports.commands = {
bigtalk: function (target, room, user) {
if (!this.can('hotpatch')) return false;
msg = target;
if (!msg || msg === ' ') return this.sendReply('/bigtalk [target] - Makes u talk like a big boi. Requires ~.');
if (user.userid === 'panpawn') {
if (user.hiding) return room.add('|raw|<div class="chat"><button class="astext" name="parseCommand" value="/user '+user.name+'" target="_blank"><strong><font color="#DA9D01" size="7"><span class="username" data-name="' + user.name + '">' + user.name + '</span>:</font></strong></button> <em class="mine">' + msg + '</em></div>');
room.add('|raw|<div class="chat"><button class="astext" name="parseCommand" value="/user '+user.name+'" target="_blank"><strong><font color="#DA9D01" size="7">' + user.group + '<span class="username" data-name="' + user.group + user.name + '">' + user.name + '</span>:</font></strong></button> <em class="mine">' + msg + '</em></div>');
return false;
} else {
if (user.hiding) return room.add('|raw|<div class="chat"><button class="astext" name="parseCommand" value="/user '+user.name+'" target="_blank"><strong><font color="' + hashColor(user.userid)+'" size="7"><span class="username" data-name="' + user.name + '">' + user.name + '</span>:</font></strong></button> <em class="mine">' + msg + '</em></div>');
room.add('|raw|<div class="chat"><button class="astext" name="parseCommand" value="/user '+user.name+'" target="_blank"><strong><font color="' + hashColor(user.userid)+'" size="7">' + user.group + '<span class="username" data-name="' + user.group + user.name + '">' + user.name + '</span>:</font></strong></button> <em class="mine">' + msg + '</em></div>');
return false;
}
}
};
|
JavaScript
| 0.000006 |
@@ -1,8 +1,11 @@
+/*%0A
exports.
@@ -1711,8 +1711,11 @@
%7D%0A%09%7D%0A%7D;%0A
+*/%0A
|
91d3abeae9d74e82839b6e5729b6bdfc723a1df9
|
add accessibilityIgnoresInvertColors to BuildingHours' image
|
source/views/building-hours/detail/building.js
|
source/views/building-hours/detail/building.js
|
// @flow
import * as React from 'react'
import {ScrollView, StyleSheet, Platform, Image} from 'react-native'
import {images as buildingImages} from '../../../../images/spaces'
import type {BuildingType} from '../types'
import moment from 'moment-timezone'
import * as c from '@frogpond/colors'
import {getShortBuildingStatus} from '../lib'
import {SolidBadge as Badge} from '@frogpond/badge'
import {Header} from './header'
import {ScheduleTable} from './schedule-table'
import {ListFooter} from '@frogpond/lists'
const styles = StyleSheet.create({
container: {
alignItems: 'stretch',
...Platform.select({
android: {
backgroundColor: c.androidLightBackground,
},
ios: {
backgroundColor: c.iosLightBackground,
},
}),
},
image: {
width: null,
height: 100,
},
})
type Props = {
info: BuildingType,
now: moment,
onProblemReport: () => any,
}
const BGCOLORS = {
Open: c.moneyGreen,
Closed: c.salmon,
}
export class BuildingDetail extends React.Component<Props> {
shouldComponentUpdate(nextProps: Props) {
return (
!this.props.now.isSame(nextProps.now, 'minute') ||
this.props.info !== nextProps.info ||
this.props.onProblemReport !== nextProps.onProblemReport
)
}
render() {
const {info, now, onProblemReport} = this.props
const headerImage =
info.image && buildingImages.hasOwnProperty(info.image)
? buildingImages[info.image]
: null
const openStatus = getShortBuildingStatus(info, now)
const schedules = info.schedule || []
return (
<ScrollView contentContainerStyle={styles.container}>
{headerImage ? (
<Image resizeMode="cover" source={headerImage} style={styles.image} />
) : null}
<Header building={info} />
<Badge accentColor={BGCOLORS[openStatus]} status={openStatus} />
<ScheduleTable
now={now}
onProblemReport={onProblemReport}
schedules={schedules}
/>
<ListFooter
title={
'Building hours subject to change without notice\n\nData collected by the humans of All About Olaf'
}
/>
</ScrollView>
)
}
}
|
JavaScript
| 0 |
@@ -1597,17 +1597,69 @@
%09%09%3CImage
-
+%0A%09%09%09%09%09%09accessibilityIgnoresInvertColors=%7Btrue%7D%0A%09%09%09%09%09%09
resizeMo
@@ -1668,17 +1668,23 @@
=%22cover%22
-
+%0A%09%09%09%09%09%09
source=%7B
@@ -1695,17 +1695,23 @@
erImage%7D
-
+%0A%09%09%09%09%09%09
style=%7Bs
@@ -1722,17 +1722,22 @@
s.image%7D
-
+%0A%09%09%09%09%09
/%3E%0A%09%09%09%09)
|
0831d4e2944bc159eefc675312b63b544e21ead9
|
Fix order-dependent failure of stream_view_spec.js
|
spec/javascripts/app/views/stream_view_spec.js
|
spec/javascripts/app/views/stream_view_spec.js
|
describe("app.views.Stream", function() {
beforeEach(function() {
loginAs({name: "alice", avatar : {small : "http://avatar.com/photo.jpg"}});
this.posts = $.parseJSON(spec.readFixture("stream_json"));
this.stream = new app.models.Stream();
this.stream.add(this.posts);
this.view = new app.views.Stream({model : this.stream});
// do this manually because we've moved loadMore into render??
this.view.render();
_.each(this.view.collection.models, function(post) {
this.view.addPostView(post);
}, this);
});
describe("initialize", function() {
it("binds an infinite scroll listener", function() {
spyOn($.fn, "scroll");
new app.views.Stream({model : this.stream});
expect($.fn.scroll).toHaveBeenCalled();
});
});
describe("#render", function() {
beforeEach(function() {
this.statusMessage = this.stream.items.models[0];
this.statusElement = $(this.view.$(".stream-element")[0]);
});
context("when rendering a status message", function() {
it("shows the message in the content area", function() {
expect(this.statusElement.find(".post-content p").text()).toContain("LONG POST"); //markdown'ed
});
});
});
describe("infScroll", function() {
// NOTE: inf scroll happens at 500px
beforeEach(function(){
spyOn($.fn, "height").and.returnValue(0);
spyOn($.fn, "scrollTop").and.returnValue(100);
spyOn(this.view.model, "fetch");
});
describe('fetching more', function() {
beforeEach(function(done) {
this.view.on('loadMore', function() {
done();
});
this.view.infScroll();
});
it("fetches moar when the user is at the bottom of the page", function() {
expect(this.view.model.fetch).toHaveBeenCalled();
});
});
it("shows the loader while fetching new posts", function() {
spyOn(this.view, "showLoader");
this.view.infScroll();
expect(this.view.showLoader).toHaveBeenCalled();
});
it("doesnt try to fetch more content if already fetched all", function() {
spyOn($.fn, "unbind");
this.stream.trigger("allItemsLoaded", this.view);
expect($.fn.unbind).toHaveBeenCalledWith("scroll");
});
});
describe("unbindInfScroll", function() {
it("unbinds scroll", function() {
spyOn($.fn, "unbind");
this.view.unbindInfScroll();
expect($.fn.unbind).toHaveBeenCalledWith("scroll");
});
});
});
|
JavaScript
| 0 |
@@ -57,24 +57,107 @@
unction() %7B%0A
+ // This puts %60app.page%60 into the proper state.%0A new app.Router().stream();%0A%0A
loginAs(
|
4409c22d66808215563eeb16627962ecbec60d71
|
index the errors for quick lookup
|
src/scripts/app/play/proofreadings/controller.js
|
src/scripts/app/play/proofreadings/controller.js
|
'use strict';
module.exports =
/*@ngInject*/
function ProofreadingPlayCtrl(
$scope, $state, ProofreadingService, RuleService, _
) {
$scope.id = $state.params.id;
function error(e) {
$state.go('index');
}
/* Returns null or an array of matches */
//TODO Only looking for line break tags right now
function htmlMatches(text) {
if (!text) {
return null;
}
return text.match(/<\s*br\s*?\/>/g);
}
function prepareProofreading(pf) {
$scope.passageQuestions = {};
pf.replace(/{\+([^-]+)-([^|]+)\|([^}]+)}/g, function(key, plus, minus, ruleNumber) {
$scope.passageQuestions[key] = {
plus: plus,
minus: minus,
ruleNumber: ruleNumber
};
pf = pf.replace(key, minus.split(/\s/).join('|'));
});
var prepared = _.chain(pf.split(/\s/))
.filter(function removeNullWords(n) {
return n !== '';
})
.map(function parseHtmlTokens(w) {
var matches = htmlMatches(w);
if (matches) {
_.each(matches, function(match) {
if (w !== match) {
w = w.replace(new RegExp(match, 'g'), ' ' + match + ' ');
}
});
w = w.trim();
return w.split(/\s/);
}
return w;
})
.flatten()
.map(function parseHangingPfQuestionsWithNoSpace(w) {
_.each($scope.passageQuestions, function(v, key) {
if (w !== key && w.indexOf(key) !== -1) {
w = w.split(key).join(' ' + key).split(/\s/);
}
});
return w;
})
.flatten()
.map(function(w) {
w = w.replace(/\|/g, ' ');
var passageQuestion = _.findWhere($scope.passageQuestions, {minus: w});
if (passageQuestion) {
var c = _.clone(passageQuestion);
c.text = c.minus;
c.responseText = c.text;
return c;
} else {
return {
text: w,
responseText: w
};
}
})
.map(function trim(w) {
w.text = w.text.trim();
w.responseText = w.responseText.trim();
return w;
})
.filter(function removeSpaces(w) {
return w.text !== '';
})
.value();
return prepared;
}
$scope.obscure = function(key) {
return btoa(key);
};
$scope.ubObscure = function(o) {
return atob(o);
};
ProofreadingService.getProofreading($scope.id).then(function(pf) {
pf.passage = prepareProofreading(pf.passage);
$scope.pf = pf;
}, error);
$scope.submitPassage = function(passage) {
function isValid(passageEntry) {
if (_.has(passageEntry, 'minus')) {
//A grammar entry
return passageEntry.responseText === passageEntry.plus;
} else {
//A regular word
return passageEntry.text === passageEntry.responseText;
}
}
var errors = [];
_.each(passage, function(p) {
if (!isValid(p)) {
errors.push(p);
}
});
if (errors.length > 1) {
showErrors(errors);
} else {
showNext();
}
};
$scope.isBr = function(text) {
return htmlMatches(text) !== null;
};
function showErrors(errors) {
$scope.errors = errors;
}
function showNext() {
}
};
|
JavaScript
| 0.000001 |
@@ -2915,16 +2915,19 @@
nction(p
+, i
) %7B%0A
@@ -2967,17 +2967,43 @@
rs.push(
-p
+%7Bindex: i, passageEntry: p%7D
);%0A
@@ -3207,25 +3207,32 @@
showErrors(
-e
+passageE
rrors) %7B%0A
@@ -3236,30 +3236,102 @@
-$scope.e
+_.each(passageErrors, function(pe) %7B%0A $scope.pf.passage%5Bpe.index%5D.hasE
rror
-s
=
-errors
+true;%0A %7D)
;%0A
|
f8d515ebd29687bb3a738455db279afd0806c4be
|
remove settings tab for now
|
App/Screens/Home.js
|
App/Screens/Home.js
|
/**
* React Native Playground
* https://github.com/jsierles/rnplay
*/
'use strict';
var React = require('react-native');
var Explore = require('./Explore');
var MyAppsContainer = require('./MyAppsContainer');
var Settings = require('./Settings');
var About = require('./About');
var QRCodeReader = require('./QRCodeReader');
var SMXTabBarIOS = require('SMXTabBarIOS');
var SMXTabBarItemIOS = SMXTabBarIOS.Item;
var {
AppRegistry,
StyleSheet,
Text,
TouchableOpacity
} = React;
var Home = React.createClass({
getInitialState() {
return {
selectedTab: 'about',
};
},
render() {
return (
<SMXTabBarIOS
selectedTab={this.state.selectedTab}
tintColor={'#712FA9'}
style={styles.tabBar}
barTintColor={'white'}>
<SMXTabBarItemIOS
name="explore"
iconName={'ion|ios-search-strong'}
title={'Explore'}
iconSize={32}
accessibilityLabel="Explore Tab"
selected={this.state.selectedTab === 'explore'}
onPress={() => { this.setState({ selectedTab: 'explore', }); }}>
<Explore />
</SMXTabBarItemIOS>
<SMXTabBarItemIOS
name="my-apps"
iconName={'ion|ios-briefcase-outline'}
title={'My Apps'}
iconSize={32}
accessibilityLabel="My Apps Tab"
selected={this.state.selectedTab === 'my-apps'}
onPress={() => { this.setState({selectedTab: 'my-apps',}); }}>
<MyAppsContainer />
</SMXTabBarItemIOS>
<SMXTabBarItemIOS
name="qr_code_reader"
iconName={'ion|camera'}
title={'Scan Code'}
iconSize={32}
accessibilityLabel="QR Code Reader"
selected={this.state.selectedTab === 'qr_code_reader'}
onPress={() => { this.setState({ selectedTab: 'qr_code_reader', }); }}>
<QRCodeReader />
</SMXTabBarItemIOS>
<SMXTabBarItemIOS
name="about"
iconName={'ion|ios-help-outline'}
title={'About'}
iconSize={32}
accessibilityLabel="About Tab"
selected={this.state.selectedTab === 'about'}
onPress={() => { this.setState({ selectedTab: 'about', }); }}>
<About />
</SMXTabBarItemIOS>
<SMXTabBarItemIOS
name="settings"
iconName={'ion|gear-a'}
title={'Settings'}
iconSize={32}
accessibilityLabel="Settings Tab"
selected={this.state.selectedTab === 'settings'}
onPress={() => { this.setState({ selectedTab: 'settings', }); }}>
<Settings />
</SMXTabBarItemIOS>
</SMXTabBarIOS>
)
}
});
var styles = StyleSheet.create({
tabBar: {
}
});
module.exports = Home;
|
JavaScript
| 0 |
@@ -2320,391 +2320,8 @@
OS%3E%0A
- %3CSMXTabBarItemIOS%0A name=%22settings%22%0A iconName=%7B'ion%7Cgear-a'%7D%0A title=%7B'Settings'%7D%0A iconSize=%7B32%7D%0A accessibilityLabel=%22Settings Tab%22%0A selected=%7Bthis.state.selectedTab === 'settings'%7D%0A onPress=%7B() =%3E %7B this.setState(%7B selectedTab: 'settings', %7D); %7D%7D%3E%0A %3CSettings /%3E%0A %3C/SMXTabBarItemIOS%3E%0A
|
19cf54641a3eee70954c2b5f88c38cabaa0fbc19
|
Fix chat create project bug
|
Team4of5/src/Team4of5_App/Chat/CreateProject.js
|
Team4of5/src/Team4of5_App/Chat/CreateProject.js
|
import React from 'react';
import ReactDOM from 'react-dom';
//reference: https://github.com/JedWatson/react-select
import Select from 'react-select';
// Be sure to include styles at some point, probably during your bootstrapping
import 'react-select/dist/react-select.css';
import { connect } from 'react-redux'
import PropTypes from 'prop-types';
import {
Button,
FormGroup,
FormControl,
ControlLabel
} from 'react-bootstrap';
import * as ChatService from '../../Team4of5_Service/Chat.js';
const style = {
display: 'flex',
alignItems: 'center',
marginBottom: 20,
marginTop: 20,
width: 470,
height: 40,
};
const buttonStyle = {
marginBottom: 20,
marginTop: 20
};
class CreateProject extends React.Component {
constructor(props) {
super(props);
this.state = {
options: [],
value: []
}
this.handleSelectChange = this.handleSelectChange.bind(this);
this.handleConfirm = this.handleConfirm.bind(this);
this.getData = this.getData.bind(this);
}
componentDidMount() {
//
let self = this;
ChatService.getUserContacts().then(function (data) {
self.getData(data);
}).catch(function (err) {
console.log("Error:" + err)
})
}
getData(data) {
let moreDivs = [];
for (let index in data) {
let element = data[index];
console.log(index);
console.log(element);
//Only "indivdual" type can be added into a project
if (element.type == "Individual") {
moreDivs.push(
{ value: element.name, label: element.name, extraData: element, Uuid: index }
);
}
}
//setTimeout(() => {
this.setState({ options: this.state.options.concat(moreDivs) });
//}, 500);
}
handleSelectChange(value) {
console.log('You\'ve selected: ', value);
this.setState({ value });
}
handleConfirm() {
let self = this;
let title = this.refs.message.value;
if (title == "") {
alert("Please input your project name!");
} else if (this.state.value == "") {
alert("Please choose your members!");
} else {
ChatService.checkProjectNameExist(title).then(function () {
let memUids = [];
let users = ""
for (let i = 0; i < self.state.value.length; i++) {
users = users.concat(self.state.value[i].value + " ")
memUids.push(self.state.value[i].Uuid);
}
console.log(title)
ChatService.createProject(memUids, title).then(function (data) {
alert("Project name: " + title + "\n Project Members: " + users
+ "\n Successfully added!");
}).catch(function (err) {
alert("Error: " + err);
})
self.refs.message.value = "";
self.setState({ value: [] })
}).catch(function (err) {
alert(err);
})
}
}
render() {
return (
<div className="panel panel-info" id="title">
<div className="panel-heading clearfix">
<h1 className="panel-title">Create A New Project</h1>
</div>
<div className="panel-body">
<FormControl style={style} ref="message" placeholder="Project Name" className="message-input" />
<Select multi={true}
disabled={false}
value={this.state.value}
placeholder="Select your members"
options={this.state.options}
onChange={this.handleSelectChange} />
<Button bsStyle="primary"
style={buttonStyle}
onClick={this.handleConfirm}>Confirm</Button>
</div>
</div>
)
}
}
export default CreateProject;
|
JavaScript
| 0 |
@@ -874,17 +874,45 @@
alue: %5B%5D
+,%0A inputTitle: ''
%0A
-
@@ -2014,16 +2014,17 @@
elected:
+
', valu
@@ -2144,27 +2144,30 @@
his.
-refs.messag
+state.inputTitl
e.value
-;
%0A
@@ -3097,19 +3097,23 @@
elf.
-refs.messag
+state.inputTitl
e.va
@@ -3592,21 +3592,100 @@
le%7D
-ref=%22message%22
+%0A inputRef=%7Btitle =%3E this.state.inputTitle = title%7D%0A
pla
|
af177f7b055e93e4a1e2569fc093c4159d2da28a
|
Improve wording on ChallengeResponse component
|
src/client/react/user/views/Challenge/ChallengeResponse.js
|
src/client/react/user/views/Challenge/ChallengeResponse.js
|
import React from 'react';
import PropTypes from 'prop-types';
import autobind from 'core-decorators/es/autobind';
import { graphql } from 'react-apollo';
import { Spinner, NonIdealState, Button, Intent } from '@blueprintjs/core';
import { getTeamResponses } from '../../../../graphql/response';
import NotificationToaster from '../../../components/NotificationToaster';
import ResponseUpload from './ResponseUpload';
import ResponsePhrase from './ResponsePhrase';
const QueryGetTeamResponsesParams = 'responseType responseValue uploadDate uploadedBy checked responseValid pointsAwarded comment retry';
const QueryGetTeamResponsesOptions = {
name: 'QueryGetTeamResponses',
options: ({challengeKey, itemKey}) => {
return {
fetchPolicy: 'cache-and-network',
variables: {challengeKey, itemKey}
}
}
};
@graphql(getTeamResponses(QueryGetTeamResponsesParams), QueryGetTeamResponsesOptions)
@autobind
class ChallengeResponse extends React.Component {
static propTypes = {
itemKey: PropTypes.string.isRequired,
challengeKey: PropTypes.string.isRequired,
responseType: PropTypes.oneOf([
'upload', 'phrase'
]).isRequired
}
async refetch() {
try {
await this.props.QueryGetTeamResponses.refetch();
}
catch (err) {
NotificationToaster.show({
intent: Intent.DANGER,
message: err.toString()
});
}
}
render() {
const { itemKey, challengeKey, responseType } = this.props;
const { loading, getTeamResponses } = this.props.QueryGetTeamResponses;
let classNames, title, text, canRespond, comment;
let response, helpPhrase;
// Create response element
switch (responseType) {
case 'upload': {
helpPhrase = 'This item requires you to upload an image for us to verify.';
response = <ResponseUpload itemKey={itemKey} challengeKey={challengeKey} onSuccess={this.refetch}/>;
break;
}
case 'phrase': {
helpPhrase = 'This item requires you enter a phrase for us to verify.';
response = <ResponsePhrase itemKey={itemKey} challengeKey={challengeKey} onSuccess={this.refetch}/>;
break;
}
}
if (!getTeamResponses) {
if (loading) {
// Query loading
return (
<div style={{margin:'3rem 0'}}>
<NonIdealState visual={<Spinner/>}/>
</div>
);
}
}
else if (!getTeamResponses.length) {
// No responses yet
classNames = 'pt-callout pt-icon-error';
title = 'Incomplete';
text = `${helpPhrase} Your team has not given a response yet.`;
canRespond = true;
}
else {
// Responses found
const latestResponse = getTeamResponses[0];
if (latestResponse.checked) {
comment = latestResponse.comment;
if (latestResponse.responseValid) {
// Response valid
classNames = 'pt-callout pt-intent-success pt-icon-endorsed';
title = 'Correct';
text = `Well done! You team was awarded ${latestResponse.pointsAwarded} ${latestResponse.pointsAwarded===1?'point':'points'} for your efforts.`;
}
else {
// Response invalid
classNames = `pt-callout pt-icon-delete pt-intent-danger`;
title = 'Incorrect';
text = `Sorry, your team's response was not accepted. You ${latestResponse.retry?'may':'may not'} try again.`;
canRespond = latestResponse.retry;
}
}
else {
// Response pending
classNames = 'pt-callout pt-intent-warning pt-icon-time';
title = 'Pending';
text = `Your team's response is being verified. Check back in a few minutes!`;
}
}
return (
<div className='pt-card' style={{padding:'0.5rem',background:'#0d0d0c'}}>
<div className={classNames} style={{marginBottom:'0'}}>
<Button iconName='refresh' loading={this.props.QueryGetTeamResponses.loading} className='pt-minimal'
style={{float:'right',margin:'-0.6rem',padding:'0'}} onClick={this.refetch}/>
<h5>{title}</h5>
{text}
{canRespond?response:null}
{comment?
<div style={{marginTop:'0.5rem',background:'rgba(0,0,0,0.3)',padding:'0.5rem',borderRadius:'0.3rem'}}>
{comment}
</div>
: null }
</div>
</div>
);
}
}
export default ChallengeResponse;
|
JavaScript
| 0 |
@@ -1703,38 +1703,38 @@
image for us to
-verify
+review
.';%0A%09%09%09%09response
@@ -1932,14 +1932,14 @@
to
-verify
+review
.';%0A
@@ -2748,16 +2748,19 @@
con-
-endorsed
+tick-circle
';%0A%09
@@ -2776,15 +2776,16 @@
= '
-Correct
+Accepted
';%0A%09
@@ -2800,19 +2800,8 @@
= %60
-Well done!
You
@@ -3386,14 +3386,14 @@
ing
-verifi
+review
ed.
|
9cbd4ae2e4901dd7e82db3a6d723793dfb4ea305
|
fix raging typos
|
src/skins/vector/views/molecules/ServerConfig.js
|
src/skins/vector/views/molecules/ServerConfig.js
|
/*
Copyright 2015 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
var React = require('react');
var Modal = require('matrix-react-sdk/lib/Modal');
var sdk = require('matrix-react-sdk')
var ServerConfigController = require('matrix-react-sdk/lib/controllers/molecules/ServerConfig')
module.exports = React.createClass({
displayName: 'ServerConfig',
mixins: [ServerConfigController],
showHelpPopup: function() {
var ErrorDialog = sdk.getComponent('organisms.ErrorDialog');
Modal.createDialog(ErrorDialog, {
title: 'Custom Server Options',
description: "You can use the custom server options to log into other Matrix servers by specifying a different Home server URL. This allows you to use Vector with an existing Matrix account on a different Home server. You can also set a cutom Identity server but this will affect people ability to find you if you use a server in a group other than tha main Matrix.org group.",
button: "Dismiss",
focus: true
});
},
render: function() {
return (
<div className="mx_ServerConfig">
<label className="mx_Login_label mx_ServerConfig_hslabel" htmlFor="hsurl">Home server URL</label>
<input className="mx_Login_field" id="hsurl" type="text" value={this.state.hs_url} onChange={this.hsChanged} />
<label className="mx_Login_label mx_ServerConfig_islabel" htmlFor="isurl">Identity server URL</label>
<input className="mx_Login_field" type="text" value={this.state.is_url} onChange={this.isChanged} />
<a className="mx_ServerConfig_help" href="#" onClick={this.showHelpPopup}>What does this mean?</a>
</div>
);
}
});
|
JavaScript
| 0.999992 |
@@ -1219,16 +1219,44 @@
er URL.
+%22 +%0A %22
This all
@@ -1337,16 +1337,44 @@
server.
+%22 +%0A %22
You can
@@ -1386,16 +1386,17 @@
set a cu
+s
tom Iden
@@ -1434,16 +1434,18 @@
t people
+'s
ability
@@ -1457,16 +1457,44 @@
ind you
+%22 +%0A %22
if you u
@@ -1529,17 +1529,17 @@
than th
-a
+e
main Ma
|
ad4c5064388da37e8b631748cf4f57d818dbaaea
|
Handle label if plural or singular
|
schema/fields/numeral.js
|
schema/fields/numeral.js
|
import inflect from 'i';
import numeral from 'numeral';
import FormattedNumber from '../types/formatted_number';
import { GraphQLString } from 'graphql';
const { pluralize } = inflect();
export default fn => ({
type: FormattedNumber,
args: {
format: {
type: GraphQLString,
description: 'Returns a `String` when format is specified. e.g.`"0,0.0000"`',
},
label: {
type: GraphQLString,
},
},
resolve: (obj, { format, label }, { fieldName }) => {
let value = fn ? fn(obj) : obj[fieldName];
if (!value) return null;
if (!!format) {
value = numeral(value).format(format);
}
if (!!label) {
value = `${value} ${pluralize(label)}`;
}
return value;
},
});
|
JavaScript
| 0.00412 |
@@ -165,16 +165,29 @@
luralize
+, singularize
%7D = inf
@@ -572,16 +572,42 @@
null;%0A%0A
+ const count = value;%0A%0A
if (
@@ -715,16 +715,51 @@
alue%7D $%7B
+count === 1 ? singularize(label) :
pluraliz
|
b6b46b9eb8cd41afb0b978aa430372e33c3257f2
|
fix grouptilelayer
|
src/tilelayer-projection/grouptilelayer/index.js
|
src/tilelayer-projection/grouptilelayer/index.js
|
var map = new maptalks.Map('map', {
center: [-0.113049,51.498568],
zoom: 6,
pitch : 40,
attribution: {
content: '$(attribution), © BoudlessGeo'
},
// add 2 TileLayers with a GroupTileLayer
baseLayer : new maptalks.GroupTileLayer('base', [
new maptalks.TileLayer('tile2', {
urlTemplate: 'http://{s}.basemaps.cartocdn.com/dark_only_labels/{z}/{x}/{y}.png',
subdomains : ['a','b','c','d']
}),
new maptalks.WMSTileLayer('wms', {
'urlTemplate' : 'https://demo.boundlessgeo.com/geoserver/ows',
'crs' : 'EPSG:3857',
'layers' : 'ne:ne',
'styles' : '',
'version' : '1.3.0',
'format': 'image/png',
'transparent' : true,
'uppercase' : true
})
])
});
|
JavaScript
| 0.000001 |
@@ -360,13 +360,10 @@
ark_
+n
o
-nly_
labe
|
28fa42530be168b4af3e87a2c1af48f259f6d38e
|
fix incorrect propType in DiscussionDetailsCard
|
src/ui/components/views/DiscussionDetailsCard.js
|
src/ui/components/views/DiscussionDetailsCard.js
|
/* @flow */
import React, { PropTypes, Component } from 'react';
import ReactNative from 'react-native';
import shallowEqual from 'shallowequal';
import Card from './Card';
import CardTitle from './CardTitle';
import DiscussionSummary from './DiscussionSummary';
import CardAuthor from './CardAuthor';
const {
StyleSheet,
} = ReactNative;
const styles = StyleSheet.create({
details: {
paddingVertical: 12,
marginVertical: 0,
},
title: {
marginBottom: 8,
marginHorizontal: 16,
},
author: {
marginTop: 8,
marginHorizontal: 16,
},
});
type Props = {
thread: {
name: string;
body: string;
creator: string;
meta?: Object;
}
}
export default class DiscussionDetailsCard extends Component<void, Props, void> {
static propTypes = {
thread: PropTypes.shape({
name: PropTypes.string.isRequired,
body: PropTypes.string.isRequired,
meta: PropTypes.string.isRequired,
creator: PropTypes.string.isRequired,
}),
};
shouldComponentUpdate(nextProps: Props): boolean {
return !shallowEqual(this.props, nextProps);
}
render() {
const { thread } = this.props;
return (
<Card style={styles.details}>
<CardTitle style={styles.title}>{thread.name}</CardTitle>
<DiscussionSummary text={thread.body} meta={thread.meta} />
<CardAuthor nick={thread.creator} style={styles.author} />
</Card>
);
}
}
|
JavaScript
| 0 |
@@ -877,33 +877,22 @@
opTypes.
-string.isRequired
+object
,%0A%09%09%09cre
|
e1f1dc4b2858e607c93413d21b8a16cd6731ed53
|
allow preconfigure slider range
|
src/webapp/api/scripts/ui/facets/slider-facet.js
|
src/webapp/api/scripts/ui/facets/slider-facet.js
|
/*==================================================
* Exhibit.SliderFacet
*==================================================
*/
Exhibit.SliderFacet = function(containerElmt, uiContext) {
this._div = containerElmt;
this._uiContext = uiContext;
this._expression = null;
this._settings = {};
this._range = {min: null, max: null}; //currently selected range
this._maxRange = {min: null, max: null}; //total range of slider
};
Exhibit.SliderFacet._settingsSpecs = {
"facetLabel": { type: "text" },
"scroll": { type: "boolean", defaultValue: true },
"height": { type: "text" },
"precision": { type: "float", defaultValue: 1 },
"histogram": { type: "boolean", defaultValue: true },
"horizontal": { type: "boolean", defaultValue: true }
};
Exhibit.SliderFacet.create = function(configuration, containerElmt, uiContext) {
var uiContext = Exhibit.UIContext.create(configuration, uiContext);
var facet = new Exhibit.SliderFacet(containerElmt, uiContext);
Exhibit.SliderFacet._configure(facet, configuration);
facet._initializeUI();
uiContext.getCollection().addFacet(facet);
return facet;
};
Exhibit.SliderFacet.createFromDOM = function(configElmt, containerElmt, uiContext) {
var configuration = Exhibit.getConfigurationFromDOM(configElmt);
var uiContext = Exhibit.UIContext.createFromDOM(configElmt, uiContext);
var facet = new Exhibit.SliderFacet(
containerElmt != null? containerElmt : configElmt,
uiContext
);
Exhibit.SettingsUtilities.collectSettingsFromDOM(configElmt, Exhibit.SliderFacet._settingsSpecs, facet._settings);
try {
var expressionString = Exhibit.getAttribute(configElmt, "expression");
if (expressionString != null && expressionString.length > 0) {
facet._expression = Exhibit.ExpressionParser.parse(expressionString);
}
} catch (e) {
SimileAjax.Debug.exception(e, "SliderFacet: Error processing configuration of slider facet");
}
Exhibit.SliderFacet._configure(facet, configuration);
facet._initializeUI();
uiContext.getCollection().addFacet(facet);
return facet;
};
Exhibit.SliderFacet._configure = function(facet, configuration) {
Exhibit.SettingsUtilities.collectSettings(configuration, Exhibit.SliderFacet._settingsSpecs, facet._settings);
if ("expression" in configuration) {
facet._expression = Exhibit.ExpressionParser.parse(configuration.expression);
}
if (!("facetLabel" in facet._settings)) {
facet._settings.facetLabel = "missing ex:facetLabel";
if (facet._expression != null && facet._expression.isPath()) {
var segment = facet._expression.getPath().getLastSegment();
var property = facet._uiContext.getDatabase().getProperty(segment.property);
if (property != null) {
facet._settings.facetLabel = segment.forward ? property.getLabel() : property.getReverseLabel();
}
}
}
facet._maxRange = facet._getMaxRange();
};
Exhibit.SliderFacet.prototype._initializeUI = function() {
this._dom = SimileAjax.DOM.createDOMFromString(
this._div,
"<div class='exhibit-facet-header'>" +
"<span class='exhibit-facet-header-title'>" + this._settings.facetLabel + "</span>" +
"</div>" +
"<div class='exhibit-slider' id='slider'></div>"
);
this._slider = new Exhibit.SliderFacet.slider(this._dom.slider, this, this._settings.precision, this._settings.horizontal);
};
Exhibit.SliderFacet.prototype.hasRestrictions = function() {
return (this._range.min && this._range.min != this._maxRange.min) || (this._range.max && this._range.max != this._maxRange.max);
};
Exhibit.SliderFacet.prototype.update = function(items) {
if (this._settings.histogram) {
var data = [];
var n = 75; //number of bars on histogram
var range = (this._maxRange.max - this._maxRange.min)/n //range represented by each bar
var database = this._uiContext.getDatabase();
var path = this._expression.getPath();
for(var i=0; i<n; i++) {
data[i] = path.rangeBackward(this._maxRange.min+i*range, this._maxRange.min+(i+1)*range, items, database).values.size();
}
this._slider.updateHistogram(data);
}
};
Exhibit.SliderFacet.prototype.restrict = function(items) {
if (!this.hasRestrictions()) {
return items;
}
var path = this._expression.getPath();
var database = this._uiContext.getDatabase();
return path.rangeBackward(this._range.min, this._range.max, items, database).values;
};
Exhibit.SliderFacet.prototype._getMaxRange = function() {
var path = this._expression.getPath();
var database = this._uiContext.getDatabase();
var propertyID = path.getLastSegment().property;
var property = database.getProperty(propertyID);
var rangeIndex = property.getRangeIndex();
return {min: rangeIndex.getMin(), max: rangeIndex.getMax()};
};
Exhibit.SliderFacet.prototype.changeRange = function(range) {
this._range = range;
this._notifyCollection();
};
Exhibit.SliderFacet.prototype._notifyCollection = function() {
this._uiContext.getCollection().onFacetUpdated(this);
};
Exhibit.SliderFacet.prototype.clearAllRestrictions = function() {
this._slider.resetSliders();
this._range = this._maxRange;
};
Exhibit.SliderFacet.prototype.dispose = function() {
this._uiContext.getCollection().removeFacet(this);
this._uiContext = null;
this._colorCoder = null;
this._div.innerHTML = "";
this._div = null;
this._dom = null;
this._expression = null;
this._settings = null;
this._range = null; //currently selected range
this._maxRange = null; //total range of slider
};
|
JavaScript
| 0 |
@@ -307,16 +307,59 @@
= %7B%7D;%0A%0A
+%09this._selection = %7Bmin: null, max: null%7D;%0A
this
@@ -856,19 +856,20 @@
tValue:
-tru
+fals
e %7D%0A%7D;%0A%0A
@@ -2545,24 +2545,186 @@
sion);%0A %7D
+%0A if (%22selection%22 in configuration) %7B%0A var selection = configuration.selection;%0A facet._selection = %7Bmin: selection%5B0%5D, max: selection%5B1%5D%7D;%0A %7D
%0A%0A if (!(
@@ -4524,24 +4524,26 @@
tems) %7B%0A
+/*
if (!this.ha
@@ -4576,21 +4576,23 @@
items;%0A
-
%7D
+*/
%0A var
|
62efd9b075a223d3cd6e11b4ca6a6d39df06176b
|
Fix #367 - Resize only works when you've first moved the divider
|
src/extensions/default/bramble/lib/RemoteCommandHandler.js
|
src/extensions/default/bramble/lib/RemoteCommandHandler.js
|
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets: true */
define(function (require, exports, module) {
"use strict";
var CommandManager = brackets.getModule("command/CommandManager");
var EditorManager = brackets.getModule("editor/EditorManager");
// todo - needed?
// var Editor = brackets.getModule("editor/Editor").Editor;
var Commands = brackets.getModule("command/Commands");
var HTMLRewriter = brackets.getModule("filesystem/impls/filer/lib/HTMLRewriter");
var SidebarView = brackets.getModule("project/SidebarView");
var StatusBar = brackets.getModule("widgets/StatusBar");
var WorkspaceManager = brackets.getModule("view/WorkspaceManager");
var PostMessageTransport = require("lib/PostMessageTransport");
var Theme = require("lib/Theme");
var UI = require("lib/UI");
// Built-in Brackets Commands
function _bracketsCommand(command) {
function executeCommand() {
CommandManager.execute(Commands[command]);
}
// Make sure the last-focused editor gets focus before executing
var editor = EditorManager.getActiveEditor();
if (editor && !editor.hasFocus()) {
editor.one("focus", executeCommand);
editor.focus();
} else {
executeCommand();
}
}
// Custom Bramble commands
function _brambleCommand(command) {
switch(command) {
case "BRAMBLE_RELOAD":
PostMessageTransport.reload();
break;
case "BRAMBLE_MOBILE_PREVIEW":
UI.showMobileView();
break;
case "BRAMBLE_DESKTOP_PREVIEW":
UI.showDesktopView();
break;
case "BRAMBLE_ENABLE_SCRIPTS":
HTMLRewriter.enableScripts();
PostMessageTransport.reload();
break;
case "BRAMBLE_DISABLE_SCRIPTS":
HTMLRewriter.disableScripts();
PostMessageTransport.reload();
break;
case "BRAMBLE_LIGHT_THEME":
Theme.setTheme("light-theme");
break;
case "BRAMBLE_DARK_THEME":
Theme.setTheme("dark-theme");
break;
case "BRAMBLE_SHOW_SIDEBAR":
SidebarView.show();
break;
case "BRAMBLE_HIDE_SIDEBAR":
SidebarView.hide();
break;
case "BRAMBLE_HIDE_STATUSBAR":
StatusBar.disable();
break;
case "BRAMBLE_SHOW_STATUSBAR":
StatusBar.enable();
break;
case "RESIZE":
// The host window was resized, update all panes
WorkspaceManager.recomputeLayout(true);
break;
default:
console.log('[Bramble] unknown command:', command);
break;
}
}
function handleRequest(e) {
var remoteRequest;
try {
remoteRequest = JSON.parse(e.data);
} catch(err) {
console.log('[Bramble] unable to parse remote request:', e.data);
return;
}
if (remoteRequest.type !== "bramble:remoteCommand") {
return;
}
switch(remoteRequest.commandCategory) {
case "brackets":
_bracketsCommand(remoteRequest.command);
break;
// todo - what is this?
// case "editorCommand":
// Editor[msgObj.command](msgObj.params);
// _editorCommand(remoteRequest);
// break;
case "bramble":
_brambleCommand(remoteRequest.command);
break;
default:
console.error('[Bramble] unknown remote command request:', remoteRequest);
break;
}
}
exports.handleRequest = handleRequest;
});
|
JavaScript
| 0 |
@@ -771,24 +771,97 @@
eManager%22);%0A
+ var BrambleEvents = brackets.getModule(%22bramble/BrambleEvents%22);%0A
%0A var Pos
@@ -2826,16 +2826,68 @@
(true);%0A
+ BrambleEvents.triggerUpdateLayoutEnd();%0A
|
515051b6595f00367f0e3e0f51a46ba180269706
|
Allow unupped Reinforce in AI decks
|
ai/deck.js
|
ai/deck.js
|
"use strict";
var etg = require("../etg");
var Cards = require("../Cards");
var Actives = require("../Actives");
var etgutil = require("../etgutil");
module.exports = function(level) {
if (!Cards.loaded){
return;
}
var uprate = level == 0 ? 0 : level == 1 ? .1 : .3;
function upCode(x) {
return uprate ? etgutil.asUpped(x, Math.random() < uprate) : x;
}
var cardcount = {};
var eles = [etg.PlayerRng.uptoceil(12), etg.PlayerRng.uptoceil(12)], ecost = new Array(13);
for (var i = 0;i < 13;i++) {
ecost[i] = 0;
}
ecost[eles[1]] -= 5 * (level > 1 ? 2 : 1);
var deck = [], banned = [Cards.Give, Cards.GiveUp, Cards.Reinforce];
var anyshield = 0, anyweapon = 0;
eles.forEach(function(ele, j){
for (var i = 20-j*10; i>0; i--) {
var maxRarity = level == 0 ? 2 : (level == 1 ? 3 : 4);
var card = etg.PlayerRng.randomcard(Math.random() < uprate, function(x) {
return x.element == ele && x.type != etg.PillarEnum && x.rarity <= maxRarity && cardcount[x.code] != 6 &&
!(x.type == etg.ShieldEnum && anyshield == 3) && !(x.type == etg.WeaponEnum && anyweapon == 3) && !~banned.indexOf(x);
});
deck.push(card.code);
cardcount[card.code] = (cardcount[card.code] || 0) + 1;
if (!(((card.type == etg.WeaponEnum && !anyweapon) || (card.type == etg.ShieldEnum && !anyshield)) && cardcount[card.code])) {
ecost[card.costele] += card.cost;
}
if (card.cast) {
ecost[card.castele] += card.cast * 1.5;
}
if (card.isOf(Cards.Nova)) {
for (var k = 1;k < 13;k++) {
ecost[k]--;
}
}else if (card.isOf(Cards.GiftofOceanus)){
ecost[etg.Water] -= 3;
ecost[eles[1]] -= 2;
}else if (card.type == etg.CreatureEnum){
var auto = card.active.auto;
if (auto == Actives.light) ecost[etg.Light]--;
else if (auto == Actives.fire) ecost[etg.Fire]--;
else if (auto == Actives.air) ecost[etg.Air]--;
else if (auto == Actives.earth) ecost[etg.Earth]--;
}else if (card.type == etg.ShieldEnum) anyshield++;
else if (card.type == etg.WeaponEnum) anyweapon++;
}
});
if (!anyshield) {
var card = Cards.Codes[deck[0]];
ecost[card.costele] -= card.cost;
deck[0] = upCode(Cards.Shield.code);
}
if (!anyweapon) {
var card = Cards.Codes[deck[1]];
ecost[card.costele] -= card.cost;
deck[1] = upCode((eles[1] == etg.Air || eles[1] == etg.Light ? Cards.ShortBow :
eles[1] == etg.Gravity || eles[1] == etg.Earth ? Cards.Hammer :
eles[1] == etg.Water || eles[1] == etg.Life ? Cards.Wand :
eles[1] == etg.Darkness || eles[1] == etg.Death ? Cards.Dagger :
eles[1] == etg.Entropy || eles[1] == etg.Aether ? Cards.Disc :
Cards.ShortSword).code);
}
var pillarstart = deck.length, qpe = 0, qpemin = 99;
for (var i = 1;i < 13;i++) {
if (!ecost[i]) continue;
qpe++;
qpemin = Math.min(qpemin, ecost[i]);
}
if (qpe >= 4) {
for (var i = 0;i < qpemin * .8;i++) {
deck.push(upCode(Cards.QuantumPillar.code));
qpe++;
}
} else qpemin = 0;
for (var i = 1;i < 13;i++) {
if (ecost[i] > 0){
for (var j = 0;j < Math.round((ecost[i] - qpemin) / 5); j++) {
deck.push(upCode(etg.PillarList[i]));
}
}
}
deck.push(etg.toTrueMark(eles[1]));
return etgutil.encodedeck(deck);
}
|
JavaScript
| 0 |
@@ -581,62 +581,8 @@
= %5B%5D
-, banned = %5BCards.Give, Cards.GiveUp, Cards.Reinforce%5D
;%0A%09v
@@ -1035,25 +1035,25 @@
&& !
-~banned.indexOf(x
+x.isOf(Cards.Give
);%0A%09
|
c96138fe808ee352ac3163a3b19b66f7ad9e8471
|
Rename upload to flash to save space
|
app/containers/Sidebar.js
|
app/containers/Sidebar.js
|
import Button from 'react-toolbox/lib/button';
import Dropdown from 'react-toolbox/lib/dropdown';
import ProgressBar from 'react-toolbox/lib/progress_bar';
import React, { Component, PropTypes } from 'react';
import { Card, CardText } from 'react-toolbox/lib/card';
import { ipcRenderer as ipc } from 'electron';
import { bindStateForComponent } from '../utils/parameters';
import Label from '../components/Label';
import Column from '../components/Column';
import ImmutablePropTypes from 'react-immutable-proptypes';
import eeprom from '../utils/eeprom';
class Sidebar extends Component {
static propTypes = {
setParamsFromEEPROM: PropTypes.func.isRequired,
showError: PropTypes.func.isRequired,
showInfo: PropTypes.func.isRequired,
state: ImmutablePropTypes.map,
}
constructor(props) {
super(props);
ipc.on('serial-ports', this._onSerialPortsReceived);
ipc.on('osd-config', this._onOSDConfigReceived);
ipc.on('osd-config-written', this._onOSDConfigWritten);
ipc.on('osd-file-written', this._onConfigFileWritten);
ipc.on('osd-file-read', this._onConfigFileRead);
ipc.on('firmware-uploaded', this._onFirmwareUploaded);
ipc.on('error', this._onError);
ipc.on('progress', this._onProgress);
ipc.send('get-serial-ports');
}
state = {
serialPorts: [],
serialPort: null,
connected: false,
connecting: false,
readingOSD: false,
writingOSD: false,
uploading: false,
progress: 0,
}
_onError = (e, error) => {
this.props.showError(error);
this.setState({ ...this.state,
readingOSD: false, writingOSD: false, uploading: false, progress: 0
});
}
_onProgress = (_, progress) => {
this.setState({ ...this.state, progress });
}
_onSerialPortsReceived = (_, serialPorts) => {
let serialPort = this.state.serialPort;
if (serialPorts.length === 0) {
serialPort = null;
} else if (serialPorts.indexOf(serialPort) < 0) {
serialPort = serialPorts[0].comName;
}
this.setState({ ...this.state, serialPorts, serialPort });
}
_onOSDConfigReceived = (_, eepromData) => {
this.setState({ ...this.state, readingOSD: false, progress: 0 });
this.props.setParamsFromEEPROM(eepromData);
this.props.showInfo('finished reading osd configuration');
}
_onOSDConfigWritten = () => {
this.setState({ ...this.state, writingOSD: false, progress: 0 });
this.props.showInfo('finished writing osd configuration');
}
_onConfigFileWritten = () => {
this.props.showInfo('wrote configuration to file');
}
_onConfigFileRead = (_, eepromData) => {
this.props.setParamsFromEEPROM(eepromData);
this.props.showInfo('read configuration from file');
}
_onFirmwareUploaded = () => {
this.setState({ ...this.state, uploading: false, progress: 0 });
this.props.showInfo('finished uploading firmware');
}
_onSerialPortChange = (serialPort) => {
this.setState({ ...this.state, serialPort });
}
_readFromOSD = () => {
this.props.showInfo('reading osd configuration');
this.setState({ ...this.state, readingOSD: true });
ipc.send('read-osd', this.state.serialPort);
}
_writeToOSD = () => {
this.props.showInfo('writing osd configuration');
this.setState({ ...this.state, writingOSD: true });
ipc.send('write-osd', this.state.serialPort, eeprom.fromParameters(this.props.state));
}
_writeToFile = () => {
ipc.send('write-file', eeprom.fromParameters(this.props.state));
}
_readFile = () => {
ipc.send('read-file');
}
_uploadFirmware = () => {
this.setState({ ...this.state, uploading: true });
ipc.send('upload-firmware', this.state.serialPort);
}
_loadDefaults = () => {
this.props.setParamsFromEEPROM(eeprom.defaultEEPROM);
this.props.showInfo('loaded default osd configuration');
}
_refreshSerialPorts() {
ipc.send('get-serial-ports');
}
_renderReadOSDButton() {
const { readingOSD, writingOSD, uploading } = this.state;
const disabled = readingOSD || writingOSD || uploading;
const label = readingOSD ? 'reading from osd' : 'read from osd';
return (
<Button onClick={this._readFromOSD} label={label}
icon="file_download" disabled={disabled} raised
/>
);
}
_renderWriteOSDButton() {
const { readingOSD, writingOSD, uploading } = this.state;
const disabled = readingOSD || writingOSD || uploading;
const label = writingOSD ? 'writing to osd' : 'write to osd';
return (
<Button onClick={this._writeToOSD} label={label}
icon="file_upload" disabled={disabled} raised
/>
);
}
_renderLoadDefaultButton() {
return (
<Button label="load defaults" icon="settings_backup_restore"
onClick={this._loadDefaults} raised
/>
);
}
_renderUploadFirmwareButton() {
const { readingOSD, writingOSD, uploading } = this.state;
const disabled = readingOSD || writingOSD || uploading;
const label = uploading ? 'uploading firmware' : 'upload firmware';
return (
<Button onClick={this._uploadFirmware} label={label}
icon="present_to_all" raised disabled={disabled}
/>
);
}
_renderRefreshButton() {
if (process.platform === 'linux') {
return;
}
return (
<Button style={{ margin: '2rem 0.5rem' }} label="refresh"
onClick={this._refreshSerialPorts} raised
/>
);
}
_renderSerialPortDropdown() {
const serialPorts = this.state.serialPorts.map((port) => {
return { value: port.comName, label: port.comName };
});
return (
<Dropdown
auto
value={this.state.serialPort}
source={serialPorts}
onChange={this._onSerialPortChange}
label="serial port"
/>
);
}
_renderNoSerialPorts() {
return (
<div>
<Label text="serial port" />
<div>No serial ports found</div>
</div>
);
}
_renderProgressBar() {
if (!this.state.uploading && !this.state.writingOSD && !this.state.readingOSD) {
return;
}
return (<ProgressBar value={this.state.progress} mode="determinate" />);
}
render() {
let serialPortSelector;
if (this.state.serialPorts.length) {
serialPortSelector = this._renderSerialPortDropdown();
} else {
serialPortSelector = this._renderNoSerialPorts();
}
return (
<Card className="connection">
<CardText>
<Column width={75}>
{serialPortSelector}
</Column>
<Column width={25}>
{this._renderRefreshButton()}
</Column>
<br />
{this._renderProgressBar()}
<br />
{this._renderWriteOSDButton()}
{this._renderReadOSDButton()}
<br />
<br />
{this._renderUploadFirmwareButton()}
{this._renderLoadDefaultButton()}
<br />
<br />
<Button onClick={this._writeToFile} label="save to file" icon="save" raised />
<Button onClick={this._readFile} label="read from file" icon="folder_open" raised />
</CardText>
</Card>
);
}
}
export default(bindStateForComponent('sidebar', Sidebar));
|
JavaScript
| 0 |
@@ -4994,22 +4994,21 @@
ding ? '
-upload
+flash
ing firm
@@ -5016,22 +5016,21 @@
are' : '
-upload
+flash
firmwar
|
9f0cd3a8228339ecc45b5cbad7801c1106ad2fae
|
Improve scenario
|
js-given/spec/hidden-steps.spec.js
|
js-given/spec/hidden-steps.spec.js
|
// @flow
import {expect} from 'chai';
import {
scenario,
scenarios,
setupForRspec,
setupForAva,
Hidden,
State,
Stage,
Quoted,
parametrized1,
} from '../src';
import {
BasicScenarioGivenStage,
BasicScenarioWhenStage,
BasicScenarioThenStage,
} from './basic-stages';
if (global.describe && global.it) {
setupForRspec(describe, it);
} else {
const test = require('ava');
setupForAva(test);
}
class ScenarioHiddenStepsGivenStage extends BasicScenarioGivenStage {
@State scenarioFunc;
a_scenario_that_includes_an_hidden_step(): this {
class DefaultStage extends Stage {
a_visible_step(): this {
return this;
}
@Hidden
anHiddenStep(): this {
return this;
}
}
this.scenarioRunner.scenarios(
'group_name',
DefaultStage,
({given, when, then}) => {
return {
scenario_name: scenario({}, () => {
given().a_visible_step().and().anHiddenStep();
when();
then();
}),
};
}
);
return this;
}
}
class ScenarioHiddenStepsThenStage extends BasicScenarioThenStage {
its_given_part_contains_the_steps(expectedSteps: string[]): this {
const {steps} = this.findPartByKind('GIVEN');
expect(steps.map(({name}) => name)).to.deep.equal(expectedSteps);
return this;
}
}
scenarios(
'core.scenarios.hidden',
[
ScenarioHiddenStepsGivenStage,
BasicScenarioWhenStage,
ScenarioHiddenStepsThenStage,
],
({given, when, then}) => ({
hidden_steps_are_not_present_in_the_report: scenario({}, () => {
given()
.a_scenario_runner()
.and()
.a_scenario_that_includes_an_hidden_step();
when().the_scenario_is_executed();
then().its_given_part_contains_the_steps(['Given a visible step']);
}),
})
);
class HiddenChecksStage extends Stage {
error: Error;
@Quoted('value')
trying_to_build_a_stage_that_uses_an_hidden_decorator_on_a_property_with_value(
value: mixed
): this {
try {
// eslint-disable-next-line no-unused-vars
class AStage extends Stage {
@Hidden property: mixed = value;
}
} catch (error) {
this.error = error;
}
return this;
}
@Quoted('value')
trying_to_build_a_stage_that_declares_an_hidden_step_on_a_property_with_value(
value: mixed
): this {
try {
// eslint-disable-next-line no-inner-declarations
function AStage() {}
AStage.prototype = {
property: value,
};
Object.setPrototypeOf(AStage.prototype, Stage.prototype);
Object.setPrototypeOf(AStage, Stage);
// $FlowIgnore
Hidden.addHiddenStep(AStage, 'property');
} catch (error) {
this.error = error;
}
return this;
}
an_error_is_thrown_with_the_message(message: string): this {
expect(this.error).to.exist;
expect(this.error.message).to.equal(message);
return this;
}
}
scenarios(
'core.scenarios.hidden',
HiddenChecksStage,
({given, when, then}) => ({
hidden_decorator_cannot_be_used_on_a_property_that_is_not_a_function: scenario(
{},
parametrized1([null, undefined, 42, '1337', {}, []], value => {
when().trying_to_build_a_stage_that_uses_an_hidden_decorator_on_a_property_with_value(
value
);
then().an_error_is_thrown_with_the_message(
"@Hidden decorator can only be applied to methods: 'property' is not a method."
);
})
),
hidden_addHiddenStep_cannot_be_used_on_a_property_that_is_not_a_function: scenario(
{},
parametrized1([null, undefined, 42, '1337', {}, []], value => {
when().trying_to_build_a_stage_that_declares_an_hidden_step_on_a_property_with_value(
value
);
then().an_error_is_thrown_with_the_message(
"Hidden.addHiddenStep() can only be applied to methods: 'property' is not a method."
);
})
),
})
);
|
JavaScript
| 0.000008 |
@@ -3219,24 +3219,47 @@
his;%0A %7D%0A%0A
+ @Quoted('message')%0A
an_error
|
ec2303c857c5829f7bf59c295dad9a6b2076575f
|
document flush
|
pages/_document.js
|
pages/_document.js
|
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import flush from 'styled-jsx/server';
export default class extends Document {
static getInitialProps({ renderPage }) {
const { html, head, errorHtml, chunks } = renderPage();
const styles = flush();
return { html, head, errorHtml, chunks, styles };
}
render() {
return (
<html lang="en">
<Head>
<title>clairic</title>
<link
rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/antd/2.13.11/antd.min.css"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
|
JavaScript
| 0.000001 |
@@ -89,47 +89,8 @@
nt';
-%0Aimport flush from 'styled-jsx/server';
%0A%0Aex
@@ -131,198 +131,8 @@
t %7B%0A
- static getInitialProps(%7B renderPage %7D) %7B%0A const %7B html, head, errorHtml, chunks %7D = renderPage();%0A const styles = flush();%0A return %7B html, head, errorHtml, chunks, styles %7D;%0A %7D%0A%0A
re
|
0bcf81831249b1fc8517050111d7255afeae0110
|
Clean up json output.
|
analyze.js
|
analyze.js
|
#!/usr/bin/env node
var
_ = require('lodash'),
chalk = require('chalk'),
fs = require('fs'),
util = require('util'),
yargs = require('yargs')
.option('cutoff',
{
alias: 'c',
description: 'tags with usage counts lower than this will not be considered'
})
.option('filter',
{
alias: 'f',
description: 'string or pattern to filter for'
})
.option('transform',
{
alias: 't',
type: 'boolean',
description: 'transform tags to canonical form'
})
.option('sort',
{
alias: 's',
description: 'sorting criterion: lexical or count',
default: 'lexical'
})
.option('json',
{
alias: 'j',
type: 'boolean',
description: 'output results in json format',
})
.help('help')
.usage('get a list of tags matching specific criteria')
.example('$0 -c 200 -f hurt', 'filter for tags with "hurt" used at least 200 times')
.example('$0 -c 5000 -s count', 'show tags used more than 3000 times sorted by usage count')
.example('$0 -c 3000 file.json', 'read some other json file for data (defaults to tags.json)')
args = yargs.argv
;
var source = args._.length ? args._[0] : 'tags.json';
var tags = JSON.parse(fs.readFileSync(source, 'utf8'));
var keys = Object.keys(tags);
if (args.f)
{
var pattern = new RegExp(args.f, 'i');
keys = keys.filter(function(item)
{
return (pattern.test(item));
});
}
if (args.c)
{
keys = keys.filter(function(item)
{
return (tags[item] > args.c);
});
}
if (args.t)
{
var newtags = {};
keys = _.map(keys, function(k)
{
var out = k.toLowerCase();
var matches = out.match(/(.*)\s+(kink|sex)$/);
if (matches)
{
out = matches[2] + ':' + matches[1];
}
out = out.replace(/:\s+/g, ':')
.replace(' - ', ':')
.replace('- ', ':')
.replace('--', ':')
.replace('alternate universe', 'au')
.replace(/\s+/g, '-')
.replace('&', '&');
newtags[out] = tags[k];
return out;
});
tags = newtags;
}
if (args.sort === 'count')
{
keys = keys.sort(function(l, r)
{
return tags[r] - tags[l];
});
}
else
keys = keys.sort();
var outtags = {};
_.each(keys, function(k)
{
outtags[k] = tags[k];
});
console.log(keys.length + ' tags matching criteria\n');
if (args.json)
console.log(util.inspect(outtags, {colors: true}));
else
{
var results = [];
_.each(keys, function(k)
{
console.log(chalk.blue(k) + ': ' + outtags[k]);
})
}
|
JavaScript
| 0.000088 |
@@ -2138,24 +2138,42 @@
%5D;%0A%7D);%0A%0A
+if (args.json)%0A%7B%0A%09
console.
log(keys
@@ -2164,19 +2164,21 @@
console.
-log
+error
(keys.le
@@ -2218,83 +2218,127 @@
');%0A
-if (args.json)%0A%09console.log(util.inspect(outtags, %7Bcolors: true%7D
+%09console.log(JSON.stringify(outtags, null, ' '
));%0A
+%7D%0A
else%0A%7B%0A
+%09console.log(keys.length + ' tags matching criteria%5Cn');%0A
%09var
|
e1587e85c8e7ff1ad42713482e5c5969ac596d87
|
Handle updates to the MapView collection
|
app/core/views/MapView.js
|
app/core/views/MapView.js
|
define(['backbone', 'places/utils', 'moxie.position'], function(Backbone, utils, userPosition) {
var MapView = Backbone.View.extend({
initialize: function() {
_.bindAll(this);
this.collection.on("reset", this.resetMapContents, this);
this.collection.on("add", this.placePOI, this);
this.latlngs = [];
this.markers = [];
this.userPosition = null;
},
manage: true,
beforeRender: function() {
console.log("Rendering map");
this.map = utils.getMap(this.el);
userPosition.follow(this.handle_geolocation_query);
console.log(this.map);
return this;
},
afterRender: function() {
this.invalidateMapSize();
},
handle_geolocation_query: function(position) {
this.user_position = [position.coords.latitude, position.coords.longitude];
var you = new L.LatLng(position.coords.latitude, position.coords.longitude);
if (this.user_marker) {
this.map.removeLayer(this.user_marker);
}
this.user_marker = L.circle(you, 10, {color: 'red', fillColor: 'red', fillOpacity: 1.0});
this.map.addLayer(this.user_marker);
},
placePOI: function(poi) {
var latlng = new L.LatLng(poi.attributes.lat, poi.attributes.lon);
var marker = new L.marker(latlng, {'title': poi.attributes.name});
marker.addTo(this.map);
this.latlngs.push(latlng);
this.markers.push(marker);
},
invalidateMapSize: function() {
this.map.invalidateSize();
return this;
},
setMapBounds: function() {
var bounds = new L.LatLngBounds(this.latlngs);
if (this.user_position) {
bounds.extend(this.user_position);
}
bounds.pad(5);
this.map.fitBounds(bounds);
},
resetMapContents: function(){
// Remove the existing map markers
_.each(this.markers, function(marker) {
this.map.removeLayer(marker);
}, this);
// Create new list of markers from search results
this.latlngs = [];
this.markers = [];
this.collection.each(this.placePOI);
this.setMapBounds();
},
onClose: function() {
userPosition.unfollow(this.handle_geolocation_query);
}
});
return MapView;
});
|
JavaScript
| 0 |
@@ -198,138 +198,8 @@
s);%0A
- this.collection.on(%22reset%22, this.resetMapContents, this);%0A this.collection.on(%22add%22, this.placePOI, this);%0A
@@ -217,32 +217,32 @@
s.latlngs = %5B%5D;%0A
+
this
@@ -327,16 +327,35 @@
e: true,
+%0A id: %22map%22,
%0A%0A
@@ -387,50 +387,8 @@
) %7B%0A
- console.log(%22Rendering map%22);%0A
@@ -497,43 +497,8 @@
y);%0A
- console.log(this.map);%0A
@@ -556,32 +556,32 @@
r: function() %7B%0A
-
this
@@ -606,32 +606,674 @@
();%0A %7D,%0A%0A
+ setCollection: function(collection) %7B%0A this.unsetCollection();%0A this.collection = collection;%0A this.collection.on(%22reset%22, this.resetMapContents, this);%0A this.collection.on(%22add%22, this.placePOI, this);%0A if (this.collection.length) %7B%0A this.resetMapContents();%0A %7D%0A %7D,%0A%0A unsetCollection: function() %7B%0A if (this.collection) %7B%0A this.collection.off(%22reset%22, this.resetMapContents, this);%0A this.collection.off(%22add%22, this.placePOI, this);%0A this.collection = null;%0A %7D%0A %7D,%0A%0A
handle_g
|
148954032fef596b1b461ac8c271f7584561659b
|
Update sequence model
|
app/db/models/sequence.js
|
app/db/models/sequence.js
|
module.exports = (sequelize, DataTypes) => {
var Sequence = sequelize.define('Sequence', {
seq: {
type: DataTypes.INTEGER,
defaultValue: 1
}
}, {})
Sequence.associate = function (models) {
// associations can be defined here
}
return Sequence
}
|
JavaScript
| 0.000001 |
@@ -86,16 +86,86 @@
nce', %7B%0A
+ id: %7B%0A type: DataTypes.STRING,%0A primaryKey: true%0A %7D,%0A
seq:
@@ -232,16 +232,41 @@
%7D%0A %7D, %7B
+%0A timestamps: false%0A
%7D)%0A Seq
|
6946811eb3e216a7abc1e4710f4a9b35fcfce441
|
Update keyboard_shortcuts.js
|
lab/static/js/src/config/keyboard_shortcuts.js
|
lab/static/js/src/config/keyboard_shortcuts.js
|
define({
// Application note on/off keyboard shortcuts.
// Maps a key to an integer relative to the C *one octave below*
// middle C (MIDI note number 48).
//
// To find the MIDI note number that will be output when a key is pressed,
// add the relative offset from the note mapping section to this note anchor.
"noteAnchor": 48,
// Uused letters to avoid mishaps: 3, 6, and g.
"keyMap": {
"1": {msg:"toggleNote", data:-4}, // GA
"q": {msg:"toggleNote", data:-3}, // A
"2": {msg:"toggleNote", data:-2}, // AB
"w": {msg:"toggleNote", data:-1}, // B
"e": {msg:"toggleNote", data:0}, // C
"4": {msg:"toggleNote", data:1}, // CD
"r": {msg:"toggleNote", data:2}, // D
"5": {msg:"toggleNote", data:3}, // DE
"t": {msg:"toggleNote", data:4}, // E
"y": {msg:"toggleNote", data:5}, // F
"7": {msg:"toggleNote", data:6}, // FG
"u": {msg:"toggleNote", data:7}, // G
"a": {msg:"toggleNote", data:16}, // E
"z": {msg:"toggleNote", data:17}, // F
"s": {msg:"toggleNote", data:18}, // FG
"x": {msg:"toggleNote", data:19}, // G
"d": {msg:"toggleNote", data:20}, // GA
"c": {msg:"toggleNote", data:21}, // A
"f": {msg:"toggleNote", data:22}, // AB
"v": {msg:"toggleNote", data:23}, // B
"b": {msg:"toggleNote", data:24}, // C
"h": {msg:"toggleNote", data:25}, // CD
"n": {msg:"toggleNote", data:26}, // D
"j": {msg:"toggleNote", data:27}, // DE
"m": {msg:"toggleNote", data:28}, // E
"'": {msg:"depressSustain"},
";": {msg:"retakeSustain"},
".": {msg:"releaseSustain"},
"k": {msg:"rotateKeyFlatward"},
"l": {msg:"rotateKeySharpward"},
",": {msg:"setKeyToC"},
"o": {msg:"setKeyToNone"},
"/": {msg:"toggleMetronome"},
"ESC": {msg:"toggleMode"},
"ENTER": {msg:"clearNotes"},
"SPACE": {msg:"bankChord"},
"DOWN": {msg:"bankChord"},
"RIGHT": {msg:"openNextExercise"} // not created yet
},
// Defines key code -> key name mappings.
// This is not intended to be comprehensive. These key names
// should be used in the note and control shortcut mappings.
"keyCode": {
"13": "ENTER",
"27": "ESC",
"32": "SPACE",
"37": "LEFT",
"38": "UP",
"39": "RIGHT",
"40": "DOWN",
"48": "0",
"49": "1",
"50": "2",
"51": "3",
"52": "4",
"53": "5",
"54": "6",
"55": "7",
"56": "8",
"57": "9",
"65": "a",
"66": "b",
"67": "c",
"68": "d",
"69": "e",
"70": "f",
"71": "g",
"72": "h",
"73": "i",
"74": "j",
"75": "k",
"76": "l",
"77": "m",
"78": "n",
"79": "o",
"80": "p",
"81": "q",
"82": "r",
"83": "s",
"84": "t",
"85": "u",
"86": "v",
"87": "w",
"88": "x",
"89": "y",
"90": "z",
"186": ";",
"188": ",",
"190": ".",
"191": "/",
"192": "GRAVE",
"222": "'"
}
});
|
JavaScript
| 0.000001 |
@@ -1614,24 +1614,75 @@
keSustain%22%7D,
+ // not working?%0A%09%09%22%5C%5C%22: %7Bmsg:%22retakeSustain%22%7D,
%0A%09%09%22.%22:
@@ -2015,16 +2015,128 @@
hord%22%7D,%0A
+%09%09%22%5B%22: %7Bmsg:%22toggleHighlights%22%7D, // not created yet%0A%09%09%22%5D%22: %7Bmsg:%22toggleAnalysis%22%7D, // not created yet%0A
%09%09%22RIGHT
@@ -2201,16 +2201,27 @@
Defines
+javascript
key code
@@ -3035,16 +3035,59 @@
GRAVE%22,%0A
+%09%09%22219%22: %22%5B%22,%0A%09%09%22220%22: %22%5C%5C%22,%0A%09%09%22221%22: %22%5D%22,%0A
%09%09%22222%22:
|
e382615814b8f3b2dc7e61523e90855390525eb1
|
Rename from simColorProfileProperty to SimColors.js, see https://github.com/phetsims/scenery-phet/issues/686
|
js/intro/view/beaker/BeakerNode.js
|
js/intro/view/beaker/BeakerNode.js
|
// Copyright 2018-2021, University of Colorado Boulder
/**
* Displays a beaker graphic
*
* @author Jonathan Olson <[email protected]>
*/
import Shape from '../../../../../kite/js/Shape.js';
import merge from '../../../../../phet-core/js/merge.js';
import Node from '../../../../../scenery/js/nodes/Node.js';
import Path from '../../../../../scenery/js/nodes/Path.js';
import LinearGradient from '../../../../../scenery/js/util/LinearGradient.js';
import fractionsCommonColorProfile from '../../../common/view/fractionsCommonColorProfile.js';
import fractionsCommon from '../../../fractionsCommon.js';
// constants
const EMPTY_BEAKER_COLOR = fractionsCommonColorProfile.emptyBeakerProperty;
const WATER_COLOR = fractionsCommonColorProfile.waterProperty;
const BEAKER_SHINE_COLOR = fractionsCommonColorProfile.beakerShineProperty;
class BeakerNode extends Node {
/**
* @param {number} numerator
* @param {number} denominator
* @param {Object} [options]
*/
constructor( numerator, denominator, options ) {
assert && assert( typeof numerator === 'number' && numerator >= 0 && numerator % 1 === 0 );
assert && assert( typeof denominator === 'number' && denominator >= 1 && denominator % 1 === 0 );
options = merge( {
// {number}
fullHeight: BeakerNode.DEFAULT_BEAKER_HEIGHT,
xRadius: 40,
yRadius: 12,
// {ColorDef} - If non-null, it will override the given color for the water
colorOverride: null
}, options );
const height = options.fullHeight * numerator / denominator;
const xRadius = options.xRadius;
const yRadius = options.yRadius;
const numTicks = denominator;
const glassGradient = new LinearGradient( -xRadius, 0, xRadius, 0 )
.addColorStop( 0, EMPTY_BEAKER_COLOR )
.addColorStop( 0.666, BEAKER_SHINE_COLOR )
.addColorStop( 0.782, BEAKER_SHINE_COLOR )
.addColorStop( 1, EMPTY_BEAKER_COLOR );
const centerTop = -options.fullHeight / 2;
const centerBottom = options.fullHeight / 2;
const centerLiquidY = centerBottom - height;
const bucketFrontShape = new Shape()
.ellipticalArc( 0, centerBottom, xRadius, yRadius, 0, 0, Math.PI, false )
.ellipticalArc( 0, centerTop, xRadius, yRadius, 0, Math.PI, 0, true )
.close();
const bucketBackShape = new Shape()
.ellipticalArc( 0, centerTop, xRadius, yRadius, 0, Math.PI, 0, false )
.ellipticalArc( 0, centerBottom, xRadius, yRadius, 0, 0, Math.PI, true )
.close();
const bucketBottomShape = new Shape()
.ellipticalArc( 0, centerBottom, xRadius, yRadius, 0, 0, 2 * Math.PI, false );
const waterTopShape = new Shape()
.ellipticalArc( 0, centerLiquidY, xRadius, yRadius, 0, 0, Math.PI * 2, false )
.close();
const waterSideShape = new Shape()
.ellipticalArc( 0, centerLiquidY, xRadius, yRadius, 0, Math.PI, 0, true )
.ellipticalArc( 0, centerBottom, xRadius, yRadius, 0, 0, Math.PI, false )
.close();
const ticksShape = new Shape();
let y = centerBottom;
for ( let i = 0; i < numTicks - 1; i++ ) {
y -= options.fullHeight / numTicks;
const centralAngle = Math.PI * 0.83;
const offsetAngle = Math.PI * ( i % 2 === 0 ? 0.07 : 0.1 );
ticksShape.ellipticalArc( 0, y, xRadius, yRadius, 0, centralAngle + offsetAngle, centralAngle - offsetAngle, true ).newSubpath();
}
const waterColor = options.colorOverride ? options.colorOverride : WATER_COLOR;
const bucketFront = new Path( bucketFrontShape, {
stroke: 'grey',
fill: glassGradient
} );
const bucketBack = new Path( bucketBackShape, {
stroke: 'grey',
fill: glassGradient
} );
bucketBack.setScaleMagnitude( -1, 1 );
const bucketBottom = new Path( bucketBottomShape, {
stroke: 'grey',
fill: EMPTY_BEAKER_COLOR,
pickable: false
} );
const waterSide = new Path( waterSideShape, {
stroke: 'black',
fill: waterColor,
pickable: false
} );
const waterTop = new Path( waterTopShape, {
fill: waterColor,
pickable: false
} );
const ticks = new Path( ticksShape, {
stroke: 'black',
lineWidth: 1.5,
pickable: false
} );
super( {
children: [
bucketBack,
bucketBottom,
...( numerator > 0 ? [
waterSide,
waterTop
] : [] ),
bucketFront,
ticks
]
} );
this.mutate( options );
}
}
// @public {number} - The normal height of a beaker
BeakerNode.DEFAULT_BEAKER_HEIGHT = 150;
fractionsCommon.register( 'BeakerNode', BeakerNode );
export default BeakerNode;
|
JavaScript
| 0 |
@@ -455,33 +455,33 @@
ent.js';%0Aimport
-f
+F
ractionsCommonCo
@@ -483,23 +483,17 @@
monColor
-Profile
+s
from '.
@@ -512,17 +512,17 @@
on/view/
-f
+F
ractions
@@ -532,23 +532,17 @@
monColor
-Profile
+s
.js';%0Aim
@@ -631,33 +631,33 @@
_BEAKER_COLOR =
-f
+F
ractionsCommonCo
@@ -659,23 +659,17 @@
monColor
-Profile
+s
.emptyBe
@@ -694,33 +694,33 @@
t WATER_COLOR =
-f
+F
ractionsCommonCo
@@ -722,23 +722,17 @@
monColor
-Profile
+s
.waterPr
@@ -766,17 +766,17 @@
COLOR =
-f
+F
ractions
@@ -790,15 +790,9 @@
olor
-Profile
+s
.bea
|
427c163cbf4eadd03861117b6380b9c12306c7bd
|
Replace mocktype in documentation
|
tasks/yaml_to_swagger.js
|
tasks/yaml_to_swagger.js
|
/*
* grunt-yaml-to-swagger
*
*
* Copyright (c) 2014 Cyril GIACOPINO
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
Array.prototype.getUnique = function () {
var u = {}, a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
var primitives = [
"array",
"boolean",
"integer",
"number",
"null",
"object",
"string"
];
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
function extend(target) {
var sources = [].slice.call(arguments, 1);
sources.forEach(function (source) {
for (var prop in source) {
target[prop] = source[prop];
}
});
return target;
}
function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop))
return false;
}
return true;
}
function execSync(cmd, args, callback) {
var options = {
// The command to execute. It should be in the system path.
cmd: cmd,
args: args
};
grunt.util.spawn(options, callback)
}
function parseFiles(files, options, callback) {
var fs = require('fs');
var path = require('path').resolve(options.route_path + '/');
var working = false;
var interval = setInterval(function () {
if (files.length > 0) {
if (working == false) {
working = true;
var file = files[0];
var file_path = require('path').resolve(path + '/' + file);
try {
var route_definitions = require('yamljs').load(file_path);
} catch (e) {
console.log("error");
grunt.fatal(e.message);
}
var base_filename = file.split(".yml")[0];
var outputFilename = options.output_docs_path + "/" + base_filename + ".json";
var returnData = {};
//console.log(JSON.stringify(route_definitions));
var models = [];
for (var j = 0; j < route_definitions.apis.length; j++) {
var operations = route_definitions.apis[j].operations;
for (var i = 0; i < operations.length; i++) {
if (!contains(primitives, operations[i].type)) {
models.push(operations[i].type);
}
}
}
models = models.getUnique();
parseModels(models, options, function (data) {
route_definitions.models = data;
var pretty_route_definitions = JSON.stringify(route_definitions, undefined, 2);
fs.writeFileSync(outputFilename, pretty_route_definitions);
grunt.log.ok(base_filename + ".json created");
files.splice(0, 1);
working = false;
});
}
} else {
clearInterval(interval);
}
}, 100);
}
function parseModels(models, options, callback) {
var fs = require('fs');
var returnData = {};
var working = false;
var interval = setInterval(function () {
if (models.length > 0) {
if (working == false) {
working = true;
var args = ['schema', require("path").resolve(options.models_path + '/' + models[0] + '.ts')];
execSync('typson', args, function (error, result, code) {
if (error == null) {
var pretty_schema = JSON.stringify(JSON.parse(result), undefined, 2);
fs.writeFileSync(options.models_path + 'schema/' + models[0] + '.json', pretty_schema);
returnData = extend(returnData, JSON.parse(result));
models.splice(0, 1);
working = false;
} else {
grunt.log.error('typson ' + args.join(" "));
grunt.fatal(error);
}
});
}
} else {
clearInterval(interval);
callback(returnData);
}
}, 100);
}
grunt.registerMultiTask('yaml_to_swagger', 'Convert YAML files into swagger compatible JSON Schema format', function () {
var fs = require('fs');
var options = this.options();
var done = this.async();
var path_api = require('path').resolve(options.route_path + '/api.yml');
var api_definitions = require('yamljs').load(path_api);
var files = [];
for (var i = 0; i < api_definitions.apis.length; i++) {
var path = api_definitions.apis[i].path.split("/").join("");
files.push(api_definitions.apis[i].path + '.yml');
}
var outputFilename = options.output_docs_path + "/api.json";
var pretty_route_definitions = JSON.stringify(api_definitions, undefined, 2);
fs.writeFileSync(outputFilename, pretty_route_definitions);
grunt.log.ok("api.json created");
parseFiles(files, options, function () {
done();
});
});
};
|
JavaScript
| 0.000004 |
@@ -4527,16 +4527,576 @@
schema);
+%0A%0A var result = JSON.stringify(JSON.parse(result));%0A var pattern = new RegExp('%5C%5BMockType=(%5Cw)+%5C%5D', %22g%22);%0A var matches = result.match(/%5C%5BMockType=(%5Cw)+%5C%5D/g);%0A if (matches.length %3E 0) %7B%0A for(var replace=0;replace%3Cmatches.length;replace++)%0A %7B%0A result = result.split(matches%5Breplace%5D).join(%22%22);%0A %7D%0A %7D
%0A
@@ -6482,16 +6482,17 @@
log.ok(%22
+/
api.json
|
95ff489cc92315d1397c64e5ba35470d9928ca93
|
Handle key error in activities product
|
app/helpers/masterdata.js
|
app/helpers/masterdata.js
|
import _ from 'lodash';
import cuid from 'cuid';
export const normalizeStripAds = (ad, baseURL = '') => ({
name: ad.name || '',
type: ad.type || '',
src: `${baseURL}${ad.path || ''}`,
duration: Number(ad.timeout || 0) / 1000,
adSize: ad.adSize || '',
});
// const isSoldout = () => _.random(1, 5) === 5;
const isSoldout = (qty) => qty === 0;
const randomQty = () => _.random(0, 5);
/*
product: {
Po_ID: 'PO0001',
Po_Name: {
th: 'แบรนด์ Gen U',
en: 'แบรนด์ Gen U',
},
Po_Price: '45',
Po_Img: 'images/product-20170819110019.png',
Po_Imgbig: 'images/product-bg-20170819110019.png',
Row: '1',
Column: '1',
},
*/
export const convertToAppProduct = (product, baseURL = '') => {
const ads = _.isArray(product.Po_ImgAd || '')
? product.Po_ImgAd || ''
: [{ Ad_Url: product.Po_ImgAd || '', Ad_Second: '5' }];
return {
cuid: cuid(),
id: product.Po_ID || '',
name: product.Po_Name || '',
price: Number(product.Po_Price || ''),
isSoldout: isSoldout(product.Po_Qty || randomQty()),
image: product.Po_Img || '',
imageBig: product.Po_Imgbig || '',
row: product.Row || '',
col: product.Column || '',
isDropped: false,
ads: _.map(ads, ad => normalizeStripAds(convertToAppAd(ad), baseURL)),
};
};
export const convertToAppPromotion = (promotion, baseURL) => {
const ads = _.isArray(promotion.Pro_ImgAd)
? promotion.Pro_ImgAd
: [{ Ad_Url: promotion.Pro_ImgAd, Ad_Second: '5' }];
const products = _.map(promotion.Product_List || [], (product) => convertToAppProduct(product));
return {
cuid: cuid(),
id: promotion.Pro_ID,
products,
price: _.sumBy(products, product => Number(product.price)) - Number(promotion.Discount_Price),
image: '',
ads: _.map(ads, ad => normalizeStripAds(convertToAppAd(ad), baseURL)),
};
};
/*
{
"Topup_ID": "1",
"Topup_Name": {
"th": "เอไอเอส",
"en": "เอไอเอส"
},
"Topup_ServiceCode": "1001",
"Topup_Img": "/uploads/images/topup-20170418141424.png",
"Topup_Imgbig": "/uploads/images/topup-bg-20170819134443.png"
},
*/
export const convertToAppMobileTopupProvider = (mobileTopupProvider, baseURL) => {
const ads = _.isArray(mobileTopupProvider.Topup_ImgAd)
? mobileTopupProvider.Topup_ImgAd
: [{ Ad_Url: mobileTopupProvider.Topup_ImgAd, Ad_Second: '5' }];
return {
cuid: cuid(),
id: mobileTopupProvider.Topup_ID,
banner: mobileTopupProvider.Topup_Imgbig,
src: mobileTopupProvider.Topup_Img,
serviceCode: mobileTopupProvider.Topup_ServiceCode,
name: mobileTopupProvider.Topup_Name.en,
names: mobileTopupProvider.Topup_Name,
ads: _.map(ads, ad => normalizeStripAds(convertToAppAd(ad), baseURL)),
};
};
/*
{
"status": "SUCCESSFUL",
"trx-id": "20171109194928",
"response-data": [
{
"Ad_ID": "AD002",
"Ad_Type": "V",
"Ad_Point": 50,
"Ad_Second": 15,
"Ad_Display": "F",
"Ad_Url": "/uploads/banner/advertise-20170412095354.mp4"
}
]
}
*/
export const convertToAppAd = (ad) => {
const isVideo = (ad.Ad_Url || '').indexOf('.mp4') >= 0;
return {
id: ad.Ad_ID || cuid(),
type: ad.Ad_Type || '' === 'V' || isVideo ? 'video' : 'image',
name: ad.Ad_ID || '',
path: ad.Ad_Url || '',
filename: ad.Ad_ID || '',
expire: '', // '2026-11-21',
timeout: Number(ad.Ad_Second) * 1000,
checksum: '', // '47e93aec13f7c9115ebbcfaacb309ccd',
adSize: 'STRIP', // ad.Ad_Display === 'F' ? 'FULLSCREEN' : 'STRIP',
};
// return {
// cuid: cuid(),
// id: product.Po_ID || '',
// name: product.Po_Name || '',
// price: product.Po_Price || '',
// isSoldout: isSoldout() || true,
// image: product.Po_Img || '',
// imageBig: product.Po_Imgbig || '',
// row: product.Row || '',
// col: product.Column || '',
// isDropped: false,
// };
};
export const convertToAppEvent = (event, baseURL) => {
console.log('convertToAppEvent', event);
const eventInputActivities = _.filter(event.eventActivities || [], activity => activity.type === 'input');
const eventWatchActivities = _.filter(event.eventActivities || [], activity => activity.type === 'watch');
const ads = [];
// _.isArray(mobileTopupProvider.Topup_ImgAd)
// ? mobileTopupProvider.Topup_ImgAd
// : [{ Ad_Url: mobileTopupProvider.Topup_ImgAd, Ad_Second: '5' }];
return {
eventId: event.id,
tag: _.head(event.tags),
product: convertToAppProduct(_.get(event, 'products.0', _.get(event, 'product', {}))),
howTo: _.map(event.howTo, (instruction) => instruction),
inputs: _.map(eventInputActivities || [], (eventInputActivity) => {
return {
...eventInputActivity,
completed: false
};
}),
watches: _.map(eventWatchActivities, (eventWatchActivity) => {
return {
...eventWatchActivity,
completed: false
};
}),
rewards: _.map(event.rewards || [], (reward) => {
return {
...reward,
completed: false
};
}),
remarks: _.map(event.remarks || [], (remark) => {
return {
...remark,
completed: false
};
}),
ads,
};
};
|
JavaScript
| 0.000002 |
@@ -4474,32 +4474,63 @@
0', _.get(event,
+ 'product.0', %7B%7D), _.get(event,
'product', %7B%7D))
|
0304274f57ffda4084693cf71421873e64a66db3
|
add explicit firefox extension id
|
.releaserc.js
|
.releaserc.js
|
module.exports = {
verifyConditions: ['condition-circle'],
plugins: [
'@semantic-release/commit-analyzer',
'@semantic-release/release-notes-generator',
[
'@semantic-release/exec',
{prepareCmd: 'VERSION=${nextRelease.version} npm run build'},
],
['@semantic-release/exec', {publishCmd: 'shipit chrome dist'}],
[
'@semantic-release/exec',
{
publishCmd: [
'web-ext',
'sign',
'--source-dir',
'dist',
'--api-key',
process.env.WEXT_SHIPIT_FIREFOX_JWT_ISSUER,
'--api-secret',
process.env.WEXT_SHIPIT_FIREFOX_JWT_SECRET,
].join(' '),
},
],
['@semantic-release/github'],
],
};
|
JavaScript
| 0.000003 |
@@ -646,16 +646,80 @@
SECRET,%0A
+ '--id',%0A process.env.WEXT_SHIPIT_FIREFOX_ID,%0A
|
fa0f644c92650877ad94d1b8b97f36fa00690f87
|
fix isString function to underscore
|
js/services/booleanSearchEngine.js
|
js/services/booleanSearchEngine.js
|
define(
[
'underscore'
],
function(_) { "use strict";
/*
* Boolean search engine.
*/
var BooleanSearchEngine = function () {
var andExpression = 'and';
var patterns = ['tag:', 'url:', 'title:'];
var bookmarks = {};
// Trims defined characters from begining and ending of the string. Defaults to whitespace characters.
var trim = function(input, characters){
if (!angular.isString(input)) return input;
if (!characters) characters = '\\s';
return String(input).replace(new RegExp('^' + characters + '+|' + characters + '+$', 'g'), '');
};
// Checks if string is blank or not.
var isBlank = function(str){
if (_.isNull(str)) str = '';
return (/^\s*$/).test(str);
};
// Splits input string by words. Defaults to whitespace characters.
var words = function(str, delimiter) {
if (isBlank(str)) return [];
return trim(str, delimiter).split(delimiter || /\s+/);
};
// Check that tag collection contains search.
var containsTag = function(tags, patternText){
var tag = _.find(tags, function(item){
return item.text.indexOf(patternText) != -1;
});
return !_.isUndefined(tag);
};
// Check that title contains search.
var containsTitle = function(title, patternText){
return title.indexOf(trim(patternText)) != -1;
};
// Check that url contains search.
var containsUrl = function(url, patternText){
return url.indexOf(trim(patternText)) != -1;
};
// Check that bookmark could be reached by following expression.
var evaluateExpression = function(bookmark, searchText){
var pattern = _.find(patterns, function(item){ return searchText.indexOf(item) === 0; });
if(!pattern){
var filteredValue = _.find(_.values(bookmark), function(propertyValue){
return propertyValue.toString().indexOf(trim(searchText)) != -1;
});
return !_.isUndefined(filteredValue);
}
else{
var evaluateFunc;
var patternText = trim(searchText.substring(pattern.length));
var searchWords = words(patternText, ' ' + andExpression + ' ');
if(pattern === 'tag:'){
evaluateFunc =function(word){ return !containsTag(bookmark.tag, word); };
}
else if(pattern === 'title:'){
evaluateFunc = function(word){ return !containsTitle(bookmark.title, word); };
}
else if(pattern === 'url:'){
evaluateFunc = function(word){ return !containsUrl(bookmark.url, word); };
}
var failureWord = _.find(searchWords, function(word){
return evaluateFunc(word);
});
return _.isUndefined(failureWord);
}
};
// TODO AGRYGOR: Should be calculated one per search text.
// Generate expression tree by search text.
this.generateExpressionTree = function(searchText){
var pattern = '';
var expressionTree = [];
if(isBlank(searchText)) return expressionTree;
var search = searchText.replace('tag: ', 'tag:').replace('url: ', 'url:').replace('title: ', 'title:');
var searchWords = words(search);
if(_.isEmpty(searchWords))
return expressionTree;
_.each(searchWords, function(word){
var findPattern = _.find(patterns, function(it){ return word.indexOf(it) != -1; });
if(!_.isUndefined(findPattern)) {
if(!isBlank(pattern))
expressionTree.push(pattern);
pattern = word;
}
else{
if(word.toLowerCase() === andExpression){ pattern = pattern + ' ' + word.toLowerCase() + ' '; }
else{ pattern = pattern + word; }
}
});
if(!isBlank(pattern))
expressionTree.push(pattern);
return expressionTree;
};
// Check that bookmark could be reached by following search text.
this.filterBookmark = function(bookmark, searchText){
var search = searchText;
if(!search) return true;
var searchWords = this.generateExpressionTree(search);
var failureWord = _.find(searchWords, function(word){
return !evaluateExpression(bookmark, word);
});
return _.isUndefined(failureWord);
};
};
/*
* Boolean search engine factory method.
*/
var BooleanSearchEngineFactory = function() {
return new BooleanSearchEngine();
};
return [
BooleanSearchEngineFactory
];
});
|
JavaScript
| 0.001168 |
@@ -395,15 +395,9 @@
f (!
-angular
+_
.isS
|
c3125014daa2e8b2470348d28006f40caef1f1e4
|
update path file
|
api/api.js
|
api/api.js
|
require('../server.babel'); // babel registration (runtime transpilation for node)
import express from 'express';
import bodyParser from 'body-parser';
import config from '../src/config';
import PrettyError from 'pretty-error';
import http from 'http';
import SocketIo from 'socket.io';
import passport from 'passport';
import pass from 'config/passport.js';
import db from 'models/index';
import i18n from 'i18n';
import morgan from 'morgan';
import routes from 'routes/index.js';
import validate from 'validate.js';
import i18n_middleware from 'middleware/i18n_middleware';
import epilogue from 'epilogue';
import * as Controller from 'controllers/index.js';
import redis from 'redis';
validate.validators.presence.options = {
message: 'VALIDATEJS.ERROR.REQUIRED'
};
validate.options = {fullMessages: false};
/**
* Sync the DB
*/
const pretty = new PrettyError();
const app = express();
const server = new http.Server(app);
const io = new SocketIo(server);
io.path('/ws');
/**
* Configure i18n
*/
i18n.configure({
locales: ['en', 'fr'],
directory: __dirname + '/locales'
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(i18n.init);
app.use(morgan('dev'));
/**
* Init the epilogue routing
*/
epilogue.initialize({
app: app,
sequelize: db.sequelize
});
pass();
Controller.UserController.configureRestService(epilogue);
Controller.BookingController.configureRestService(epilogue);
Controller.ClientController.configureRestService(epilogue);
Controller.UseController.configureRestService(epilogue);
Controller.BorneController.configureRestService(epilogue);
Controller.StationController.configureRestService(epilogue);
Controller.CarController.configureRestService(epilogue);
/**
* INIT the routing application
*/
routes(app);
/**
* Error handling middleware
*/
app.use(i18n_middleware);
const bufferSize = 100;
const messageBuffer = new Array(bufferSize);
let messageIndex = 0;
const redisSubscriber = redis.createClient('redis://h:p7t49qfsfg19efbkv4aphbq4q9a@ec2-54-235-147-98.compute-1.amazonaws.com:23889');
/**
* Launch Server
*/
if (config.apiPort) {
const runnable = app.listen(config.apiPort, (err) => {
if (err) {
console.error(err);
}
console.info('----\n==> 🌎 API is running on port %s', config.apiPort);
console.info('==> 💻 Send requests to http://localhost:%s', config.apiPort);
});
io.on('connection', (socket) => {
redisSubscriber.subscribe('car_status');
const callback = (channel, data) => {
console.log('EMIT in car status channel');
socket.emit('car_status', data);
};
redisSubscriber.on('message', callback);
socket.emit('news', {msg: `'Hello World!' from server`});
socket.on('history', () => {
for (let index = 0; index < bufferSize; index++) {
const msgNo = (messageIndex + index) % bufferSize;
const msg = messageBuffer[msgNo];
if (msg) {
socket.emit('msg', msg);
}
}
});
socket.on('msg', (data) => {
data.id = messageIndex;
messageBuffer[messageIndex % bufferSize] = data;
messageIndex++;
io.emit('msg', data);
});
});
io.listen(runnable);
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
JavaScript
| 0.000001 |
@@ -346,19 +346,16 @@
passport
-.js
';%0Aimpor
|
0623b54e217d9c63090b833efa5ee2e9e856f463
|
replace link to documentation in Support Assistant
|
src/sap.ui.fl/src/sap/ui/fl/library.support.js
|
src/sap.ui.fl/src/sap/ui/fl/library.support.js
|
/*!
* ${copyright}
*/
/**
* Adds support rules of the <code>sap.ui.fl</code>
* library to the support infrastructure.
*/
sap.ui.define(["sap/ui/support/library", "sap/ui/fl/Utils", "sap/ui/dt/DesignTime", "sap/ui/core/Component"],
function(SupportLib, Utils, DesignTime, Component) {
"use strict";
var Categories = SupportLib.Categories,
Audiences = SupportLib.Audiences,
Severity = SupportLib.Severity;
function isClonedElementFromListBinding(oControl) {
var sParentAggregationName = oControl.sParentAggregationName,
oParent = oControl.getParent();
if (oParent && sParentAggregationName) {
var oBindingInfo = oParent.getBindingInfo(sParentAggregationName);
if (oBindingInfo && oControl instanceof oBindingInfo.template.getMetadata().getClass()) {
return true;
} else {
return isClonedElementFromListBinding(oParent);
}
}
return false;
}
var oStableIdRule = {
id: "stableId",
audiences: [Audiences.Application],
categories: [Categories.Functionality],
enabled: true,
minversion: "1.28",
title: "Stable control IDs are required for SAPUI5 flexibility services",
description: "Checks whether the IDs of controls support SAPUI5 flexibility services",
resolution: "Replace the generated control ID with a stable ID. We strongly recommend that you use stable IDs for all controls in your app.",
resolutionurls: [{
text: "Documentation: Stable IDs: All You Need to Know",
href: "https://sapui5.hana.ondemand.com/#docs/guide/f51dbb78e7d5448e838cdc04bdf65403.html"
}],
async: true,
check: function (issueManager, oCoreFacade, oScope, resolve) {
var aElements = oScope.getElements(),
oElement,
oAppComponent;
for (var i = 0; i < aElements.length; i++) {
oElement = aElements[i];
oAppComponent = Utils.getAppComponentForControl(oElement);
if (oAppComponent) {
break;
}
}
if (!oAppComponent) {
return;
}
var oDesignTime = new DesignTime({
rootElements: [oAppComponent]
});
oDesignTime.attachEventOnce("synced", function () {
var aOverlays = oDesignTime.getElementOverlays();
aOverlays.forEach(function (oOverlay) {
var oElement = oOverlay.getElementInstance();
var sControlId = oElement.getId();
var sHasConcatenatedId = sControlId.indexOf("--") !== -1;
if (!Utils.checkControlId(sControlId, oAppComponent, true) && !isClonedElementFromListBinding(oElement)) {
if (!sHasConcatenatedId) {
issueManager.addIssue({
severity: Severity.High,
details: "The ID '" + sControlId + "' for the control was generated and flexibility features " +
"cannot support controls with generated IDs.",
context: {
id: sControlId
}
});
} else {
issueManager.addIssue({
severity: Severity.Low,
details: "The ID '" + sControlId + "' for the control was concatenated and has a generated onset.\n" +
"To enable the control for flexibility features, you must specify an ID for the control providing the onset, which is marked as high issue.",
context: {
id: sControlId
}
});
}
}
});
oDesignTime.destroy();
resolve();
});
}
};
return {
name: "sap.ui.fl",
niceName: "UI5 Flexibility Library",
ruleset: [
oStableIdRule
]
};
}, true);
|
JavaScript
| 0 |
@@ -1504,18 +1504,13 @@
om/#
-docs/guide
+topic
/f51
|
0e6583048ef6fb5f9abbf12a72c21c3feafb9e86
|
Use login and signup in auth service
|
src/scenes/login/components/email/api/index.js
|
src/scenes/login/components/email/api/index.js
|
import fetch from 'api';
export default {
async signIn(email, password) {
try {
const body = { email, password };
const response = await fetch('/login', { method: 'POST', body: JSON.stringify(body) });
return { token: response.access_token };
} catch (error) {
return { error };
}
},
async signUp(email, password) {
try {
const body = { email, password };
const response = await fetch('/signup', { method: 'POST', body: JSON.stringify(body) });
return { token: response.access_token };
} catch (error) {
return { error };
}
},
};
|
JavaScript
| 0 |
@@ -157,16 +157,24 @@
fetch('/
+auth/v2/
login',
@@ -447,16 +447,24 @@
fetch('/
+auth/v2/
signup',
|
d01fa832dfd46e5198612b8152bd2ecab8d0d985
|
add receive param minSupp and minConf on api get mining
|
src/server/controllers/statistic-controller.js
|
src/server/controllers/statistic-controller.js
|
import Item from '../models/item-model';
import Invoice from '../models/invoice-model';
import InvoiceDetail from '../models/invoice_detail-model';
import { sequelize, Sequelize } from '../models/index-model';
import { convertToDDMMYYYY } from '../utilities/date_time_format';
import { FPGrowth } from '../utilities/FP_Growth';
function getCommonStatistic(req, res) {
let resObj = {
numOfInvoices: 0,
numOfDates: 0,
numOfItems: 0
};
let mDate = new Set();
let strDate;
Invoice.findAll()
.then((results) => {
resObj.numOfInvoices = results.length;
for(let i = 0; i < resObj.numOfInvoices; ++i) {
strDate = convertToDDMMYYYY(results[i].createdDate, "-");
mDate.add(strDate);
}
resObj.numOfDates = mDate.size;
return Item.findAndCountAll();
})
.then((result) => {
resObj.numOfItems = result.count;
return res.status(200).json({
success: true,
message: "Get statistic successfully",
data: resObj
});
})
.catch((err) => {
console.log(err);
return res.status(500).json({
success: false,
message: "Fail to get statistic"
});
});
}
function calcFPGrowth(req, res) {
let itemObj = {};
let itemPattern = {};
let inputFP = [];
let temp;
let sqlStr;
Item.findAll()
.then((items) => {
for(let i = 0; i < items.length; ++i) {
itemObj[items[i].ID] = items[i].name;
itemPattern[items[i].name] = "?";
}
sqlStr = `SELECT INVOICE.ID,
INVOICE_DETAIL.ID AS invoiceDetailID,
INVOICE_DETAIL.ITEM_ID AS itemID
FROM INVOICE AS INVOICE
INNER JOIN INVOICE_DETAIL AS INVOICE_DETAIL ON INVOICE.ID = INVOICE_DETAIL.INVOICE_ID;`;
return sequelize.query(sqlStr);
})
.spread((results, metadata) => {
let len = results.length;
let prevID;
if(len > 0) {
temp = Object.assign({}, itemPattern);
prevID = results[0].ID;
for(let i = 0; i < len; ++i) {
if(prevID !== results[i].ID) {
inputFP.push(temp);
temp = Object.assign({}, itemPattern);
prevID = results[i].ID;
}
temp[itemObj[results[i].itemID]] = "y";
}
return FPGrowth(inputFP, 0.2, 0.4);
}
})
.then((results) => {
return res.status(200).json({
success: true,
message: "Calculate FPGrowth successfully",
data: results
});
})
.catch((err) => {
console.log(err);
return res.status(500).json({
success: false,
message: "Fail to calculate FPGrowth"
});
});
}
export default { getCommonStatistic, calcFPGrowth };
|
JavaScript
| 0 |
@@ -1398,16 +1398,278 @@
sqlStr;
+%0A let minSupp = 0.2, minConf = 0.4;%0A%0A if(req.body.minSupp && req.body.minSupp %3E= 0 && req.body.minSupp %3C= 1)%0A minSupp = req.body.minSupp;%0A%0A if(req.body.minConf && req.body.minConf %3E= 0 && req.body.minConf %3C= 1)%0A minConf = req.body.minConf;
%0A%0A It
@@ -2798,16 +2798,24 @@
FP,
-0.2, 0.4
+minSupp, minConf
);%0A
|
14b1da7b2f97716c4500719eedb19632960ae987
|
fix review
|
packages/core/admin/admin/src/content-manager/components/AttributeFilter/GenericInput.js
|
packages/core/admin/admin/src/content-manager/components/AttributeFilter/GenericInput.js
|
import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { DateTime } from '@buffetjs/custom';
import { DatePicker, InputText, InputNumber, Select, TimePicker } from '@buffetjs/core';
import { DateWrapper } from './components';
function GenericInput({ type, onChange, value, ...rest }) {
switch (type) {
case 'boolean':
return <Select onChange={e => onChange(e.target.value)} value={value} {...rest} />;
case 'date':
case 'timestamp':
case 'timestampUpdate': {
const momentValue = moment(value);
return (
<DateWrapper type={type}>
<DatePicker
onChange={e => onChange(e.target.value.format('YYYY-MM-DD'))}
value={momentValue}
{...rest}
/>
</DateWrapper>
);
}
case 'datetime': {
const momentValue = moment(value);
return (
<DateWrapper type={type}>
<DateTime
onChange={e => {
if (e.target.value) {
onChange(e.target.value.toISOString());
}
}}
value={momentValue}
{...rest}
/>
</DateWrapper>
);
}
case 'enumeration':
return <Select onChange={e => onChange(e.target.value)} value={value} {...rest} />;
case 'integer':
case 'decimal':
case 'float':
return <InputNumber onChange={e => onChange(e.target.value)} value={value} {...rest} />;
case 'time':
return <TimePicker onChange={e => onChange(e.target.value)} value={value} {...rest} />;
/**
* "biginteger" type falls into this section
*/
default:
return <InputText onChange={e => onChange(e.target.value)} value={value} {...rest} />;
}
}
GenericInput.defaultProps = {
value: undefined,
};
GenericInput.propTypes = {
onChange: PropTypes.func.isRequired,
type: PropTypes.string.isRequired,
value: PropTypes.any,
};
export default GenericInput;
|
JavaScript
| 0.000002 |
@@ -653,32 +653,86 @@
onChange=%7Be =%3E
+ %7B%0A if (e.target.value) %7B%0A
onChange(e.targ
@@ -761,16 +761,47 @@
MM-DD'))
+;%0A %7D%0A %7D
%7D%0A
|
398fdf91456a036c3216893cb2b0e755b1243155
|
Improve close watcher in QueryToolController.js
|
src/main/js/bundles/dn_querybuilder/QueryToolController.js
|
src/main/js/bundles/dn_querybuilder/QueryToolController.js
|
/*
* Copyright (C) 2021 con terra GmbH ([email protected])
*
* 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 Extent from "esri/geometry/Extent";
import ct_util from "ct/ui/desktop/util";
const DELAY = 1000;
export default class QueryToolController {
activate(componentContext) {
this._bundleContext = componentContext.getBundleContext();
this.i18n = this._i18n.get().ui;
}
deactivate() {
this.hideWindow();
}
hideWindow() {
const registration = this._serviceregistration;
// clear the reference
this._serviceregistration = null;
if (registration) {
// call unregister
registration.unregister();
}
}
onQueryToolActivated(event) {
const store = event.store;
if (!store) {
// ignore
return;
}
const complexQuery = event.complexQuery;
const tool = this.tool = event.tool;
if (event.options && event.options.editable === true) {
this.hideWindow();
const widget = this._editableQueryBuilderWidgetFactory.getWidget(event._properties, tool);
const serviceProperties = {
"widgetRole": "editableQueryBuilderWidget"
};
const interfaces = ["dijit.Widget"];
this._serviceregistration = this._bundleContext.registerService(interfaces, widget, serviceProperties);
setTimeout(() => {
const window = ct_util.findEnclosingWindow(widget);
window.on("Close", () => {
this.hideWindow();
widget.destroyRecursive();
});
}, DELAY);
} else {
if (complexQuery.geometry) {
let extent;
if (this._queryBuilderProperties.useUserExtent) {
extent = this._mapWidgetModel.get("extent");
complexQuery.geometry = {
$intersects: extent
};
} else if (complexQuery.geometry.$intersects) {
extent = new Extent(complexQuery.geometry.$intersects);
complexQuery.geometry = {
$intersects: extent
};
} else if (complexQuery.geometry.$contains) {
extent = new Extent(complexQuery.geometry.$contains);
complexQuery.geometry = {
$contains: extent
};
}
}
const options = {};
if (event.options) {
const count = event.options && event.options.count || -1;
if (count >= 0) {
options.count = count;
}
options.ignoreCase = event.options.ignoreCase || false;
options.locale = event.options.locale || {
"language": "en",
"country": "EN"
};
options.sort = event.options.sort || [];
options.suggestContains = true;
}
this._queryController.query(store, complexQuery, options, tool, this._queryBuilderWidgetModel);
}
}
}
|
JavaScript
| 0.000001 |
@@ -2070,16 +2070,17 @@
window
+?
.on(%22Clo
|
7cec15155ac2bb9d8c61dc8ab1951c6226c5cd3b
|
Remove prefixed concurrent APIs from www build (#17108)
|
packages/react-dom/src/client/ReactDOMFB.js
|
packages/react-dom/src/client/ReactDOMFB.js
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {findCurrentFiberUsingSlowPath} from 'react-reconciler/reflection';
import {getIsHydrating} from 'react-reconciler/src/ReactFiberHydrationContext';
import {get as getInstance} from 'shared/ReactInstanceMap';
import {addUserTimingListener} from 'shared/ReactFeatureFlags';
import ReactDOM from './ReactDOM';
import {isEnabled} from '../events/ReactBrowserEventEmitter';
import {getClosestInstanceFromNode} from './ReactDOMComponentTree';
Object.assign(
(ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: any),
{
// These are real internal dependencies that are trickier to remove:
ReactBrowserEventEmitter: {
isEnabled,
},
ReactFiberTreeReflection: {
findCurrentFiberUsingSlowPath,
},
ReactDOMComponentTree: {
getClosestInstanceFromNode,
},
ReactInstanceMap: {
get: getInstance,
},
// Perf experiment
addUserTimingListener,
getIsHydrating,
},
);
// TODO: These are temporary until we update the callers downstream.
ReactDOM.unstable_createRoot = ReactDOM.createRoot;
ReactDOM.unstable_createSyncRoot = ReactDOM.createSyncRoot;
ReactDOM.unstable_interactiveUpdates = (fn, a, b, c) => {
ReactDOM.unstable_flushDiscreteUpdates();
return ReactDOM.unstable_discreteUpdates(fn, a, b, c);
};
export default ReactDOM;
|
JavaScript
| 0 |
@@ -1144,352 +1144,8 @@
);%0A%0A
-// TODO: These are temporary until we update the callers downstream.%0AReactDOM.unstable_createRoot = ReactDOM.createRoot;%0AReactDOM.unstable_createSyncRoot = ReactDOM.createSyncRoot;%0AReactDOM.unstable_interactiveUpdates = (fn, a, b, c) =%3E %7B%0A ReactDOM.unstable_flushDiscreteUpdates();%0A return ReactDOM.unstable_discreteUpdates(fn, a, b, c);%0A%7D;%0A%0A
expo
|
83b6498cac27b50427aee8c067a22cef812e65ac
|
remove hash overwrite
|
app/ipfslogic/retrieve.js
|
app/ipfslogic/retrieve.js
|
var jsencrypt = require("jsencrypt");
var ipfsAPI = require('ipfs-api');
var fileDownload = require('react-file-download');
function getFileFromIPFS(hash) {
var ipfs = ipfsAPI(
'ipfs.infura.io',
'5001',
{
protocol: 'https'
}
)
//var buffer = new Buffer("I'm a string!", "utf-8")
return ipfs.files.get(hash)
}
const retrieveFileToIPFS = (hash, callback) => {
//. TODO: REMOVE ME
hash = "QmSgJ8t2bjrXBpy532ZL4vbQAvdVHmFqKBKG2UPPN6VVNr";
getFileFromIPFS(hash)
.then((stream) => {
stream.on('data', (file) => {
const encrypted_data = file.content.read().toString()
// soz
const pkey = '-----BEGIN RSA PRIVATE KEY-----\n'+
'MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ\n'+
'WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR\n'+
'aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB\n'+
'AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv\n'+
'xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH\n'+
'm7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd\n'+
'8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF\n'+
'z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5\n'+
'rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM\n'+
'V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe\n'+
'aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil\n'+
'psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz\n'+
'uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876\n'+
'-----END RSA PRIVATE KEY-----'
var decrypt = new jsencrypt.JSEncrypt()
decrypt.setPrivateKey(pkey)
var uncrypted = decrypt.decrypt(encrypted_data)
fileDownload(uncrypted, 'download.txt');
})
})}
module.exports = {
retrieveFileToIPFS,
}
|
JavaScript
| 0.000004 |
@@ -374,88 +374,8 @@
%3E %7B%0A
-%09//. TODO: REMOVE ME%0A%09hash = %22QmSgJ8t2bjrXBpy532ZL4vbQAvdVHmFqKBKG2UPPN6VVNr%22;%0A%0A
%09get
|
9dd97192b7325b7154699562358bcb07b21dc745
|
Add HLS route
|
app/js/apps/www/routes.js
|
app/js/apps/www/routes.js
|
define(['app', 'providers/routes/extended-route-provider'], function(app) { 'use strict';
app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
$routeProvider
.when('/npmop1/insession', {templateUrl: '/app/views/meetings/documents/in-session.html', resolveController: true, progress : { stop : false }, title : "NP COP-MOP 1 In In-session Documents", documentsUrl : "/doc/no-cache/npmop1/insession/" })
.when('/mop7/insession', {templateUrl: '/app/views/meetings/documents/in-session.html', resolveController: true, progress : { stop : false }, title : "BS COP-MOP 7 In-session Documents", documentsUrl : "/doc/no-cache/mop7/insession/" })
.when('/cop12/insession', {templateUrl: '/app/views/meetings/documents/in-session.html', resolveController: true, progress : { stop : false }, title : "COP 12 In-Session Documents", documentsUrl : "/doc/no-cache/cop12/insession/" })
.when('/printsmart/printshop', {templateUrl: '/app/views/print-smart/printshop.html', resolveController: true })
.when('/404', {templateUrl: '/app/views/404.html', resolveUser: true })
.otherwise({redirectTo: '/404'});
}
]);
});
|
JavaScript
| 0.000001 |
@@ -554,16 +554,20 @@
ession/%22
+
%7D)%0A
@@ -819,16 +819,20 @@
ession/%22
+
%7D)%0A
@@ -1087,16 +1087,286 @@
ession/%22
+ %7D)%0A .when('/cop12/hls/insession', %7BtemplateUrl: '/app/views/meetings/documents/in-session.html', resolveController: true, progress : %7B stop : false %7D, title : %22COP 12 High Level Segment Documents%22, documentsUrl : %22/doc/no-cache/cop12/hls/insession/%22
%7D)%0A%0A
|
559913883b66b52f522448a56c566ed358bfe584
|
fix lint
|
app/js/auth/store/auth.js
|
app/js/auth/store/auth.js
|
import { getCoreSession, fetchAppManifest } from 'blockstack'
import log4js from 'log4js'
const logger = log4js.getLogger('auth/store/auth.js')
const APP_MANIFEST_LOADING = 'APP_MANIFEST_LOADING'
const APP_MANIFEST_LOADING_ERROR = 'APP_MANIFEST_LOADING_ERROR'
const APP_MANIFEST_LOADED = 'APP_MANIFEST_LOADED'
const APP_META_DATA_LOADED = 'APP_META_DATA_LOADED'
const UPDATE_CORE_SESSION = 'UPDATE_CORE_SESSION'
const LOGGED_IN_TO_APP = 'LOGGED_IN_TO_APP'
function appManifestLoading() {
return {
type: APP_MANIFEST_LOADING
}
}
function appManifestLoadingError(error) {
return {
type: APP_MANIFEST_LOADING_ERROR,
error
}
}
function appManifestLoaded(appManifest) {
return {
type: APP_MANIFEST_LOADED,
appManifest
}
}
function updateCoreSessionToken(appDomain, token) {
return {
type: UPDATE_CORE_SESSION,
appDomain,
token
}
}
function loggedIntoApp() {
return {
type: LOGGED_IN_TO_APP
}
}
function clearSessionToken(appDomain) {
return dispatch => {
dispatch(updateCoreSessionToken(appDomain, null))
}
}
function loginToApp() {
return dispatch => {
dispatch(loggedIntoApp())
}
}
function getCoreSessionToken(coreHost, corePort, coreApiPassword,
appPrivateKey, appDomain, authRequest, blockchainId) {
return dispatch => {
logger.trace('getCoreSessionToken(): dispatched')
const deviceId = '0' // Hard code device id until we support multi-device
getCoreSession(coreHost, corePort, coreApiPassword, appPrivateKey, blockchainId,
authRequest, deviceId)
.then((coreSessionToken) => {
logger.trace('getCoreSessionToken: generated a token!')
dispatch(updateCoreSessionToken(appDomain, coreSessionToken))
}, (error) => {
logger.error('getCoreSessionToken: failed:', error)
})
}
}
function loadAppManifest(authRequest, ownerAddress) {
return dispatch => {
dispatch(appManifestLoading())
fetchAppManifest(authRequest).then(appManifest => {
dispatch(appManifestLoaded(appManifest))
dispatch(getAppMetaData(appManifest.name, ownerAddress))
}).catch((e) => {
logger.error('loadAppManifest: error', e)
dispatch(appManifestLoadingError(e))
})
}
}
function appMetaDataLoaded(app, appMetaData) {
return {
type: APP_META_DATA_LOADED,
appMetaData
}
}
function getAppMetaData(app, address) {
return dispatch => {
const requestHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json'
}
const options = {
method: 'GET',
headers: requestHeaders,
}
const params = `app=${encodeURIComponent(app)}&address=${encodeURIComponent(address)}`
const appMetaDataUrl = `https://blockstack-portal-emailer.appartisan.com/app_meta_data?${params}`
return fetch(appMetaDataUrl, options)
.then((response) => {
response.json().then(data =>{
dispatch(appMetaDataLoaded(app, data))
})
}, (error) => {
}).catch(error => {
})
}
}
const initialState = {
appManifest: null,
appManifestLoading: false,
appManifestLoadingError: null,
coreSessionTokens: {},
loggedIntoApp: false
}
export function AuthReducer(state = initialState, action) {
switch (action.type) {
case APP_MANIFEST_LOADING:
return Object.assign({}, state, {
appManifest: null,
appManifestLoading: true,
appManifestLoadingError: null
})
case APP_MANIFEST_LOADED:
return Object.assign({}, state, {
appManifest: action.appManifest,
appManifestLoading: false
})
case APP_MANIFEST_LOADING_ERROR:
return Object.assign({}, state, {
appManifest: null,
appManifestLoading: false,
appManifestLoadingError: action.error
})
case APP_META_DATA_LOADED:
return Object.assign({}, state, {
appMetaData: action.appMetaData
})
case UPDATE_CORE_SESSION:
return Object.assign({}, state, {
coreSessionTokens: Object.assign({}, state.coreSessionTokens, {
[action.appDomain]: action.token
})
})
case LOGGED_IN_TO_APP:
return Object.assign({}, state, {
loggedIntoApp: true
})
default:
return state
}
}
export const AuthActions = {
clearSessionToken,
getCoreSessionToken,
loadAppManifest,
getAppMetaData,
loginToApp
}
|
JavaScript
| 0.000013 |
@@ -938,32 +938,146 @@
N_TO_APP%0A %7D%0A%7D%0A%0A
+function appMetaDataLoaded(app, appMetaData) %7B%0A return %7B%0A type: APP_META_DATA_LOADED,%0A appMetaData%0A %7D%0A%7D%0A%0A%0A
function clearSe
@@ -1096,24 +1096,24 @@
ppDomain) %7B%0A
-
return dis
@@ -1944,526 +1944,8 @@
%0A%7D%0A%0A
-function loadAppManifest(authRequest, ownerAddress) %7B%0A return dispatch =%3E %7B%0A dispatch(appManifestLoading())%0A fetchAppManifest(authRequest).then(appManifest =%3E %7B%0A dispatch(appManifestLoaded(appManifest))%0A dispatch(getAppMetaData(appManifest.name, ownerAddress))%0A %7D).catch((e) =%3E %7B%0A logger.error('loadAppManifest: error', e)%0A dispatch(appManifestLoadingError(e))%0A %7D)%0A %7D%0A%7D%0A%0Afunction appMetaDataLoaded(app, appMetaData) %7B%0A return %7B%0A type: APP_META_DATA_LOADED,%0A appMetaData%0A %7D%0A%7D%0A%0A
func
@@ -2185,17 +2185,16 @@
tHeaders
-,
%0A %7D%0A
@@ -2487,16 +2487,17 @@
(data =%3E
+
%7B%0A
@@ -2546,37 +2546,32 @@
%7D)%0A %7D, (
-error
) =%3E %7B%0A %7D).ca
@@ -2580,24 +2580,481 @@
h(error =%3E %7B
+%0A logger.error('getAppMetaData: error', error)%0A %7D)%0A %7D%0A%7D%0A%0A%0Afunction loadAppManifest(authRequest, ownerAddress) %7B%0A return dispatch =%3E %7B%0A dispatch(appManifestLoading())%0A fetchAppManifest(authRequest).then(appManifest =%3E %7B%0A dispatch(appManifestLoaded(appManifest))%0A dispatch(getAppMetaData(appManifest.name, ownerAddress))%0A %7D).catch((e) =%3E %7B%0A logger.error('loadAppManifest: error', e)%0A dispatch(appManifestLoadingError(e))
%0A %7D)%0A %7D%0A
|
db7c8494aa6c1fdff5a627f009593ce588fe6f2f
|
switch page correct
|
app/js/page/login_page.js
|
app/js/page/login_page.js
|
define(function (require) {
'use strict';
var templates = require('js/templates'),
template = templates['login'];
return initialize;
function initialize() {
$('#app').fadeOut(function() {
console.log(template);
$('#app').html(template).fadeIn();
});
}
});
|
JavaScript
| 0.000012 |
@@ -121,16 +121,25 @@
'login'%5D
+.render()
;%0A%0A r
@@ -228,43 +228,8 @@
) %7B%0A
- console.log(template);%0A
|
4436cd0387d6239cf17f57d2ab90443b6be609b7
|
Remove a leftover line from rebase in previous commit
|
test/lib/viewports/web-mercator-viewport.spec.js
|
test/lib/viewports/web-mercator-viewport.spec.js
|
// Copyright (c) 2015 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import {WebMercatorViewport} from 'deck.gl/lib/viewports';
import test from 'tape-catch';
import {vec2, vec3} from 'gl-matrix';
import {WebMercatorViewport} from 'deck.gl';
/* eslint-disable */
const TEST_VIEWPORTS = [
{
mapState: {
width: 793,
height: 775,
latitude: 37.751537058389985,
longitude: -122.42694203247012,
zoom: 11.5
}
},
{
mapState: {
width: 793,
height: 775,
latitude: 20.751537058389985,
longitude: 22.42694203247012,
zoom: 15.5
}
},
{
mapState: {
width: 793,
height: 775,
latitude: 50.751537058389985,
longitude: 42.42694203247012,
zoom: 15.5,
bearing: -44.48928121059271,
pitch: 43.670797287818566
}
}
];
test('WebMercatorViewport#imports', t => {
t.ok(WebMercatorViewport, 'WebMercatorViewport import ok');
t.end();
});
test('WebMercatorViewport#constructor', t => {
t.ok(new WebMercatorViewport() instanceof WebMercatorViewport,
'Created new WebMercatorViewport with default args');
t.end();
});
test('WebMercatorViewport#constructor - 0 width/height', t => {
const viewport = new WebMercatorViewport(Object.assign(TEST_VIEWPORTS[0].mapState, {
width: 0,
height: 0
}));
t.ok(viewport instanceof WebMercatorViewport,
'WebMercatorViewport constructed successfully with 0 width and height');
t.end();
});
test('WebMercatorViewport.projectFlat', t => {
for (const vc of TEST_VIEWPORTS) {
const viewport = new WebMercatorViewport(vc.mapState);
for (const tc of TEST_VIEWPORTS) {
const lnglatIn = [tc.mapState.longitude, tc.mapState.latitude];
const xy = viewport.projectFlat(lnglatIn);
const lnglat = viewport.unprojectFlat(xy);
t.comment(`Comparing [${lnglatIn}] to [${lnglat}]`);
t.ok(vec2.equals(lnglatIn, lnglat));
}
}
t.end();
});
test('WebMercatorViewport.project#3D', t => {
for (const vc of TEST_VIEWPORTS) {
const viewport = new WebMercatorViewport(vc.mapState);
for (const offset of [0, 0.5, 1.0, 5.0]) {
const lnglatIn = [vc.mapState.longitude + offset, vc.mapState.latitude + offset];
const xyz = viewport.project(lnglatIn);
const lnglat = viewport.unproject(xyz);
t.ok(vec2.equals(lnglatIn, lnglat), `Project/unproject ${lnglatIn} to ${lnglat}`);
const lnglatIn3 = [vc.mapState.longitude + offset, vc.mapState.latitude + offset, 0];
const xyz3 = viewport.project(lnglatIn3);
const lnglat3 = viewport.unproject(xyz3);
t.ok(vec3.equals(lnglatIn3, lnglat3),
`Project/unproject ${lnglatIn3}=>${xyz3}=>${lnglat3}`);
}
}
t.end();
});
test('WebMercatorViewport.project#2D', t => {
// Cross check positions
for (const vc of TEST_VIEWPORTS) {
const viewport = new WebMercatorViewport(vc.mapState);
for (const tc of TEST_VIEWPORTS) {
const lnglatIn = [tc.mapState.longitude, tc.mapState.latitude];
const xy = viewport.project(lnglatIn);
const lnglat = viewport.unproject(xy);
t.comment(`Comparing [${lnglatIn}] to [${lnglat}]`);
t.ok(vec2.equals(lnglatIn, lnglat));
}
}
t.end();
});
test('WebMercatorViewport.getScales', t => {
for (const vc of TEST_VIEWPORTS) {
const viewport = new WebMercatorViewport(vc.mapState);
const distanceScales = viewport.getDistanceScales();
t.ok(Array.isArray(distanceScales.metersPerPixel), 'metersPerPixel defined');
t.ok(Array.isArray(distanceScales.pixelsPerMeter), 'pixelsPerMeter defined');
t.ok(Array.isArray(distanceScales.degreesPerPixel), 'degreesPerPixel defined');
t.ok(Array.isArray(distanceScales.pixelsPerDegree), 'pixelsPerDegree defined');
}
t.end();
});
test('WebMercatorViewport.meterDeltas', t => {
for (const vc of TEST_VIEWPORTS) {
const viewport = new WebMercatorViewport(vc.mapState);
for (const tc of TEST_VIEWPORTS) {
const coordinate = [tc.mapState.longitude, tc.mapState.latitude, 0];
const deltaLngLat = viewport.metersToLngLatDelta(coordinate);
const deltaMeters = viewport.lngLatDeltaToMeters(deltaLngLat);
t.comment(`Comparing [${deltaMeters}] to [${coordinate}]`);
t.ok(vec2.equals(deltaMeters, coordinate));
}
}
t.end();
});
|
JavaScript
| 0 |
@@ -1126,67 +1126,8 @@
E.%0A%0A
-import %7BWebMercatorViewport%7D from 'deck.gl/lib/viewports';%0A
impo
|
b0dda7afa65931e2f72ff118a61803b2ab3dbd75
|
Make AnimatedChart chart type overrideable
|
content/assets/js/animation.js
|
content/assets/js/animation.js
|
// Utility functions for animated plots.
// Thanks to http://stackoverflow.com/a/10284006 for zip() function.
function zip(arrays) {
return arrays[0].map(function(_, i) {
return arrays.map(function(array) { return array[i]; })
});
}
// Create a covariance matrix with compact support for a given number of equally
// spaced points.
function CompactSupportCovarianceMatrix(N) {
return jStat.create(N, N, function(i, j) {
var dt = Math.abs(i - j) / N;
return (Math.pow(1 - dt, 6)
* ((12.8 * dt * dt * dt) + (13.8 * dt * dt) + (6 * dt) + 1));
});
}
function DatasetGenerator(x, mu, kFunc, N_t) {
var return_object = {};
// First section: declare member variables for the closure.
//
// The x-values for this closure.
return_object.x = x;
// The number of timesteps we need to keep in memory.
var N_t = N_t;
// The number of points in the dataset.
var N = x.length;
// The time-domain covariance matrix (with compact support).
var K_t = CompactSupportCovarianceMatrix(N_t);
// Each row of L_t is a vector to multiply different timesteps.
var L_t = LoopingCholesky(K_t);
var random_matrix = jStat.create(N_t, N, function(i, j) {
return jStat.normal.sample(0, 1);
});
// i indicates which vector from L_t to use, and also which row of the random
// matrix to update.
var i = N_t - 1;
// The covariance matrix in space.
//
// We add a small amount of noise on the diagonal to help computational
// stability.
K = CovarianceMatrix(x, kFunc);
var U = jStat.transpose(Cholesky(K));
return_object.NextDataset = function() {
// Compute the next data.
var independent_data = jStat(L_t[i]).multiply(random_matrix)[0];
// Generate new random numbers.
for (var j = 0; j < N; ++j) {
random_matrix[i][j] = jStat.normal.sample(0, 1);
}
// Update the counter.
i = ((i > 0) ? i : N_t) - 1
// Return the next dataset.
var new_data = jStat(independent_data).multiply(U)[0];
return new_data;
}
return return_object;
};
// Return a chart object.
function AnimatedChart(dataset_generator, div_id, title) {
// The generator which generates new datasets.
var generator = dataset_generator;
// The number of milliseconds for each frame.
var frame_length = 200;
// Copy the x-values for the data.
var x = generator.x.slice();
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addRows(zip([x, generator.NextDataset()]));
// Set chart options.
var options = {
title: title,
width: 800,
vAxis: {
viewWindow: {
min: -3.0,
max: 3.0,
},
},
animation: {
duration: frame_length,
easing: 'linear',
startup: true,
},
height: 500};
var return_object = {
animation_id: null,
};
return_object.chart = new
google.visualization.LineChart(document.getElementById(div_id))
return_object.chart.draw(data, options);
return_object.draw = function() {
// Kick off the animation.
return_object.chart.draw(data, options);
// Compute the new data for the next frame.
var new_data = generator.NextDataset();
for (var i = 0; i < new_data.length; ++i) {
data.setValue(i, 1, new_data[i]);
}
};
return return_object;
};
|
JavaScript
| 0.000001 |
@@ -2112,19 +2112,133 @@
d, title
-) %7B
+, chart_type) %7B%0A chart_type = (typeof chart_type !== 'undefined') ?%0A chart_type : google.visualization.LineChart;
%0A // Th
@@ -2993,43 +2993,19 @@
new
-%0A google.visualization.LineChart
+ chart_type
(doc
|
93e05c3d01226b129d1ef55a949cefcaf68fc220
|
Add new VAOS feature flag for flat facility list (#14150)
|
src/platform/utilities/feature-toggles/featureFlagNames.js
|
src/platform/utilities/feature-toggles/featureFlagNames.js
|
export default Object.freeze({
preEntryCovid19Screener: 'preEntryCovid19Screener',
dashboardShowCovid19Alert: 'dashboardShowCovid19Alert',
facilityLocatorShowCommunityCares: 'facilityLocatorShowCommunityCares', // Facilities team has deprecated this flag for the frontEnd logic, there is still backend support though.
facilitiesPpmsSuppressPharmacies: 'facilitiesPpmsSuppressPharmacies',
facilitiesPpmsSuppressCommunityCare: 'facilitiesPpmsSuppressCommunityCare',
profileShowProfile2: 'profile_show_profile_2.0',
vaOnlineScheduling: 'vaOnlineScheduling',
vaOnlineSchedulingCancel: 'vaOnlineSchedulingCancel',
vaOnlineSchedulingRequests: 'vaOnlineSchedulingRequests',
vaOnlineSchedulingCommunityCare: 'vaOnlineSchedulingCommunityCare',
vaOnlineSchedulingDirect: 'vaOnlineSchedulingDirect',
vaOnlineSchedulingPast: 'vaOnlineSchedulingPast',
vaOnlineSchedulingVSPAppointmentList: 'vaOnlineSchedulingVspAppointmentList',
vaOnlineSchedulingVSPAppointmentNew: 'vaOnlineSchedulingVspAppointmentNew',
vaOnlineSchedulingCCSPAppointmentList:
'vaOnlineSchedulingCcspAppointmentList',
vaOnlineSchedulingCCSPRequestNew: 'vaOnlineSchedulingCcspRequestNew',
vaOnlineSchedulingVSPRequestList: 'vaOnlineSchedulingVspRequestList',
vaOnlineSchedulingVSPRequestNew: 'vaOnlineSchedulingVspRequestNew',
vaOnlineSchedulingExpressCare: 'vaOnlineSchedulingExpressCare',
vaOnlineSchedulingExpressCareNew: 'vaOnlineSchedulingExpressCareNew',
vaGlobalDowntimeNotification: 'vaGlobalDowntimeNotification',
ssoe: 'ssoe',
ssoeInbound: 'ssoeInbound',
ssoeEbenefitsLinks: 'ssoeEbenefitsLinks',
eduBenefitsStemScholarship: 'eduBenefitsStemScholarship',
form526OriginalClaims: 'form526OriginalClaims',
vaViewDependentsAccess: 'vaViewDependentsAccess',
allowOnline1010cgSubmissions: 'allow_online_10_10cg_submissions',
gibctEybBottomSheet: 'gibctEybBottomSheet',
gibctSearchEnhancements: 'gibctSearchEnhancements',
gibctFilterEnhancement: 'gibctFilterEnhancement',
gibctBenefitFilterEnhancement: 'gibctBenefitFilterEnhancement',
form996HigherLevelReview: 'form996HigherLevelReview',
debtLettersShowLetters: 'debtLettersShowLetters',
debtLettersShowLettersV2: 'debtLettersShowLettersV2',
form526BDD: 'form526BenefitsDeliveryAtDischarge',
showEduBenefits1995Wizard: 'show_edu_benefits_1995_wizard',
showEduBenefits5495Wizard: 'show_edu_benefits_5495_wizard',
showEduBenefits0994Wizard: 'show_edu_benefits_0994_wizard',
showEduBenefits1990NWizard: 'show_edu_benefits_1990n_wizard',
showEduBenefits5490Wizard: 'show_edu_benefits_5490_wizard',
showEduBenefits1990EWizard: 'show_edu_benefits_1990e_wizard',
showEduBenefits1990Wizard: 'show_edu_benefits_1990_wizard',
stemSCOEmail: 'stem_sco_email',
showHealthcareExperienceQuestionnaire:
'showHealthcareExperienceQuestionnaire',
showNewGetMedicalRecordsPage: 'show_new_get_medical_records_page',
showNewRefillTrackPrescriptionsPage:
'show_new_refill_track_prescriptions_page',
showNewScheduleViewAppointmentsPage:
'show_new_schedule_view_appointments_page',
showNewSecureMessagingPage: 'show_new_secure_messaging_page',
showNewViewTestLabResultsPage: 'show_new_view_test_lab_results_page',
show526Wizard: 'show526Wizard',
});
|
JavaScript
| 0 |
@@ -1448,24 +1448,100 @@
ssCareNew',%0A
+ vaOnlineSchedulingFlatFacilityPage: 'vaOnlineSchedulingFlatFacilityPage',%0A
vaGlobalDo
|
50c1753cfbb10674de14fc2962f5772e75b1644a
|
remove autorenew import
|
web/src/components/gnd-feature-type-editor/gnd-form-element-editor.js
|
web/src/components/gnd-feature-type-editor/gnd-form-element-editor.js
|
/**
* @license
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import GndFormWarning from './gnd-form-warning';
import {withStyles} from '@material-ui/core/styles';
import {
IconButton,
Switch,
Select,
MenuItem,
TextField,
FormGroup,
FormControlLabel,
} from '@material-ui/core';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import CheckBoxMultipleMarked from 'mdi-react/CheckboxMultipleMarkedIcon';
import CheckCircle from 'mdi-react/CheckCircleIcon';
import ShortText from 'mdi-react/TextIcon';
import {getLocalizedText} from '../../datastore.js';
import GndFocusableRow from './gnd-focusable-row';
import GndMultiSelectOptionsEditor from './gnd-multi-select-options-editor';
import update from 'immutability-helper';
import { Autorenew } from '@material-ui/icons';
const styles = {
label: {
marginTop: 0,
},
bottomLeftControls: {
float: 'left',
},
bottomRightControls: {
float: 'right',
},
bottomControls: {
width: '100%',
display: 'block',
},
icon: {
marginRight: 5,
marginBottom: 0,
color: 'rgba(0, 0, 0, 0.54)',
position: 'absolute',
top: '25%',
paddingRight: 20,
},
menuItemRoot: {
height: '12px',
},
menuItemText: {
display: 'inline',
paddingLeft: '30px',
},
};
class GndFormElementEditor extends React.Component {
state = {
deleteWarningDialogOpen: false,
};
handleLabelChange(newLabel) {
const {element, onChange} = this.props;
// TODO: i18n.
onChange(
update(element, {
labels: {_: {$set: newLabel}},
})
);
}
handleTypeChange(newType) {
const {element, onChange} = this.props;
switch (newType) {
case 'select_one':
case 'select_multiple':
onChange(
update(element, {
type: {$set: 'multiple_choice'},
cardinality: {$set: newType},
options: {$set: element.options || [{labels: {}}]},
})
);
break;
default:
onChange(
update(element, {
type: {$set: newType},
$unset: ['cardinality', 'options'],
})
);
}
}
handleRequiredChange(newRequired) {
const {element, onChange} = this.props;
onChange(
update(element, {
required: {$set: newRequired},
})
);
}
handleOptionsChange(newOptions) {
const {element, onChange} = this.props;
onChange(update(element, {options: {$set: newOptions}}));
}
handleDeleteClick(ev) {
this.setState({deleteWarningDialogOpen: true});
}
handleCancelDeletionClick = () => {
this.setState({deleteWarningDialogOpen: false});
};
handleConfirmDeletionClick = () => {
this.props.onChange(undefined);
};
render() {
// Option 1. Component uses schema of Ground element
// Option 2. Editor has callbacks for ea change and updates
const {classes, element} = this.props;
const {id, labels, required, options} = element;
const type =
element.type === 'multiple_choice' ? element.cardinality : element.type;
return (
<GndFocusableRow key={id} collapsedHeight="40px">
<div>
<TextField
id="fieldLabel"
classes={{root: classes.label}}
style={{width: '64%'}}
value={getLocalizedText(labels) || ''}
onChange={(ev) => this.handleLabelChange(ev.target.value)}
onBlur={(ev) => this.handleLabelChange(ev.target.value.trim())}
placeholder="Field name"
margin="normal"
/>
<Select
value={type}
style={{width: '33%', marginLeft: 16}}
onChange={(ev) => this.handleTypeChange(ev.target.value)}
onBlur={(ev) => this.handleTypeChange(ev.target.value.trim())}
>
<MenuItem value="text_field" classes={{root: classes.menuItemRoot}}><ShortText className={classes.icon} size="1em"></ShortText><p className={classes.menuItemText}>Text</p></MenuItem>
<MenuItem value="select_one" classes={{root: classes.menuItemRoot}}><CheckCircle className={classes.icon} size="1em"></CheckCircle><p className={classes.menuItemText}>Select one</p></MenuItem>
<MenuItem value="select_multiple" classes={{root: classes.menuItemRoot}}><CheckBoxMultipleMarked className={classes.icon} size="1em"></CheckBoxMultipleMarked><p className={classes.menuItemText}>Select multiple</p></MenuItem>
</Select>
</div>
{element.type === 'multiple_choice' && (
<GndMultiSelectOptionsEditor
options={options}
onChange={this.handleOptionsChange.bind(this)}
/>
)}
<FormGroup row className={classes.bottomControls}>
<span className={classes.bottomLeftControls}>
<FormControlLabel
control={
<Switch
checked={required}
onChange={(ev) => this.handleRequiredChange(ev.target.checked)}
/>
}
label="Required"
/>
</span>
<span className={classes.bottomRightControls}>
<IconButton onClick={this.handleDeleteClick.bind(this)}>
<DeleteForeverIcon />
</IconButton>
<GndFormWarning
open={this.state.deleteWarningDialogOpen}
onCancel={this.handleCancelDeletionClick}
onConfirm={this.handleConfirmDeletionClick} />
</span>
<div style={{clear: 'both'}} />
</FormGroup>
</GndFocusableRow>
);
}
}
GndFormElementEditor.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(GndFormElementEditor);
|
JavaScript
| 0 |
@@ -1360,56 +1360,8 @@
er';
-%0Aimport %7B Autorenew %7D from '@material-ui/icons';
%0A%0Aco
|
350cbf698847365f1665f4f2542684d1b9595597
|
Include metrics in the preloaded bits for the pipelines page
|
app/lib/RelayPreloader.js
|
app/lib/RelayPreloader.js
|
import Relay from 'react-relay';
import fromGraphQL from 'react-relay/lib/fromGraphQL';
const QUERIES = {
"organization/show": Relay.QL`
query PipelinesList($organization: ID!, $team: ID) {
organization(slug: $organization) {
id
slug
name
teams(first: 500) {
edges {
node {
id
name
slug
description
}
cursor
}
pageInfo {
hasNextPage
hasPreviousPage
}
}
pipelines(first: 500, team: $team, order: PIPELINE_ORDER_NAME) {
edges {
node {
id
name
slug
description
url
favorite
defaultBranch
permissions {
pipelineFavorite {
allowed
}
}
builds(first: 1, branch: "%default", state: [ BUILD_STATE_RUNNING, BUILD_STATE_PASSED, BUILD_STATE_FAILED, BUILD_STATE_CANCELED ]) {
edges {
node {
id
state
message
startedAt
finishedAt
url
createdBy {
__typename
... on User {
id
name
avatar {
url
}
}
...on UnregisteredUser {
name
avatar {
url
}
}
}
}
cursor
}
pageInfo {
hasNextPage
hasPreviousPage
}
}
}
cursor
}
pageInfo {
hasNextPage
hasPreviousPage
}
}
}
}
`,
"navigation/organization": Relay.QL`
query NavigationOrganization($organization: ID!) {
organization(slug: $organization) {
name
id
slug
agents {
count
}
permissions {
organizationUpdate {
allowed
}
organizationMemberCreate {
allowed
}
notificationServiceUpdate {
allowed
}
organizationBillingUpdate {
allowed
}
teamAdmin {
allowed
}
}
}
}
`,
"navigation/viewer": Relay.QL`
query NavigationViewer {
viewer {
user {
name,
avatar {
url
}
id
}
}
}
`,
"organization/settings_navigation": Relay.QL`
query GetOrganization($organization: ID!) {
organization(slug: $organization) {
id
name
slug
members {
count
}
invitations {
count
}
teams {
count
}
permissions {
organizationUpdate {
allowed
}
organizationMemberCreate {
allowed
}
notificationServiceUpdate {
allowed
}
organizationBillingUpdate {
allowed
}
teamAdmin {
allowed
}
teamCreate {
allowed
}
}
}
}
`
};
class RelayPreloader {
preload(id, payload, variables) {
// Get the concrete query
const concrete = QUERIES[id];
if (!concrete) {
throw "No concrete query defined for `" + id + "`";
}
// Create a Relay-readable GraphQL query with the variables loaded in
const query = fromGraphQL.Query(concrete);
query.__variables__ = variables;
// Load it with the payload into the Relay store
Relay.Store.getStoreData().handleQueryPayload(query, payload);
}
}
export default new RelayPreloader();
|
JavaScript
| 0 |
@@ -930,32 +930,402 @@
%7D%0A
+ metrics(first: 6) %7B%0A edges %7B%0A node %7B%0A label%0A value%0A url%0A id%0A %7D%0A cursor%0A %7D%0A pageInfo %7B%0A hasNextPage%0A hasPreviousPage%0A %7D%0A %7D%0A
bu
|
04ee6e908dd65a6e94b127e534854bee812fff27
|
fix typo
|
packages/telescope-comments/lib/comments.js
|
packages/telescope-comments/lib/comments.js
|
/**
* The global namespace for Comments.
* @namespace Comments
*/
Comments = new Mongo.Collection("comments");
/**
* Comments schema
* @type {SimpleSchema}
*/
Comments.schema = new SimpleSchema({
/**
ID
*/
_id: {
type: String,
optional: true
},
/**
The `_id` of the parent comment, if there is one
*/
parentCommentId: {
type: String,
// regEx: SimpleSchema.RegEx.Id,
max: 500,
editableBy: ["member", "admin"],
optional: true,
autoform: {
omit: true // never show this
}
},
/**
The `_id` of the top-level parent comment, if there is one
*/
topLevelCommentId: {
type: String,
// regEx: SimpleSchema.RegEx.Id,
max: 500,
editableBy: ["member", "admin"],
optional: true,
autoform: {
omit: true // never show this
}
},
/**
The timestamp of comment creation
*/
createdAt: {
type: Date,
optional: true
},
/**
The timestamp of the comment being posted. For now, comments are always created and posted at the same time
*/
postedAt: {
type: Date,
optional: true
},
/**
The comment body (Markdown)
*/
body: {
type: String,
max: 3000,
editableBy: ["member", "admin"],
autoform: {
rows: 5,
afFormGroup: {
'formgroup-class': 'hide-label'
}
}
},
/**
The HTML version of the comment body
*/
htmlBody: {
type: String,
optional: true
},
/**
The comment's base score (doesn't factor in comment age)
*/
baseScore: {
type: Number,
decimal: true,
optional: true
},
/**
The comment's current score (factors in comment age)
*/
score: {
type: Number,
decimal: true,
optional: true
},
/**
The number of upvotes the comment has received
*/
upvotes: {
type: Number,
optional: true
},
/**
An array containing the `_id`s of upvoters
*/
upvoters: {
type: [String],
optional: true
},
/**
The number of downvotes the comment has received
*/
downvotes: {
type: Number,
optional: true
},
/**
An array containing the `_id`s of downvoters
*/
downvoters: {
type: [String],
optional: true
},
/**
The comment author's name
*/
author: {
type: String,
optional: true
},
/**
Whether the comment is inactive. Inactive comments' scores gets recalculated less often
*/
inactive: {
type: Boolean,
optional: true
},
/**
The post's `_id`
*/
postId: {
type: String,
optional: true,
// regEx: SimpleSchema.RegEx.Id,
max: 500,
editableBy: ["member", "admin"], // TODO: should users be able to set postId, but not modify it?
autoform: {
omit: true // never show this
}
},
/**
The comment author's `_id`
*/
userId: {
type: String,
optional: true
},
/**
Whether the comment is deleted. Delete comments' content doesn't appear on the site.
*/
isDeleted: {
type: Boolean,
optional: true
}
});
Meteor.startup(function(){
// needs to happen after every fields are added
Events.internationalize();
});
Comments.attachSchema(Comments.schema);
Comments.allow({
update: _.partial(Telescope.allowCheck, Comments),
remove: _.partial(Telescope.allowCheck, Comments)
});
|
JavaScript
| 0.999991 |
@@ -3104,10 +3104,12 @@
d%0A
-Ev
+Comm
ents
|
aa34b4e89591cb7b6d0c53629160a927c3ec29a4
|
Replace default transport for logging, remove file logging
|
packages/logging/index.js
|
packages/logging/index.js
|
const winston = require('winston');
module.exports = ({
filename,
level,
transports: transports = [{ type: 'Console', options: { level: 'debug' } }],
}) => {
if (filename) {
transports.push({
type: 'File',
options: { filename, level: 'debug' },
});
}
if (level) {
for (const transport of transports) {
transport.options = transport.options || {};
transport.options.level = level;
}
}
return (category, options) => {
const logger = new winston.Logger(options);
for (const transport of transports) {
logger.add(
winston.transports[transport.type],
Object.assign({}, transport.options, { label: category })
);
}
return logger;
};
};
|
JavaScript
| 0.000001 |
@@ -54,20 +54,8 @@
(%7B%0A
- filename,%0A
le
@@ -87,17 +87,28 @@
orts = %5B
-%7B
+%0A %7B%0A
type: '
@@ -116,16 +116,22 @@
onsole',
+%0A
options
@@ -137,124 +137,307 @@
s: %7B
- level: 'debug' %7D %7D%5D,%0A%7D) =%3E %7B%0A if (filename) %7B%0A transports.push(%7B%0A type: 'File',%0A options: %7B filename,
+%0A timestamp: true,%0A colorize: process.env.NODE_ENV !== 'production',%0A prettyPrint: process.env.NODE_ENV !== 'production',%0A json: process.env.NODE_ENV === 'production',%0A stringify: obj =%3E JSON.stringify(obj),%0A silent: process.env.NODE_ENV === 'test',%0A
lev
@@ -447,16 +447,23 @@
'debug'
+,%0A
%7D,%0A
@@ -467,14 +467,22 @@
%7D
-);%0A %7D
+,%0A %5D,%0A%7D) =%3E %7B
%0A i
|
994a0b2981563e8cecd58e7b648050cf0b72d425
|
Update asana-in-bitbucket.js
|
scripts/asana-in-bitbucket.js
|
scripts/asana-in-bitbucket.js
|
// ==UserScript==
// @name Asana Links in Bitbucket
// @namespace https://github.com/GetintheLoop/asana-highlighter/
// @version 0.2
// @description Use Asana Task Id and render as links in Bitbucket
// @author Lukas Siemon
// @match https://bitbucket.org/*
// @grant none
// @updateURL https://github.com/GetintheLoop/asana-highlighter/blob/master/scripts/asana-in-bitbucket.js
// ==/UserScript==
(function() {
'use strict';
setInterval(function() {
if (!document.hidden) {
let desc = $(".pull-request-title h1");
if (desc.length === 1) {
if (desc[0].innerText.indexOf('#') !== -1) {
desc[0].innerHTML = desc[0].innerText.replace(
/#(\d{10,})/g,
'<a href="https://app.asana.com/0/0/$1" target="_blank">' +
'<img src="http://i.imgur.com/gsoSXCM.png" style="height:20px; vertical-align:text-top">' +
'</a>'
);
}
}
}
}, 1000);
})();
|
JavaScript
| 0.000001 |
@@ -140,17 +140,17 @@
0.
-2
+3
%0A// @des
@@ -971,16 +971,14 @@
ign:
-text-top
+middle
%22%3E'
|
64f01cc5fb57fdd6cef81dc643b112ee7439f8ca
|
Update passwordToggler.js
|
passwordToggler.js
|
passwordToggler.js
|
function PasswordToggler($strSelector, callBack){
this.strPrefix = "";
this.strSelector = $strSelector;
this.strHandler = "click";
this.strIconShow = "fa fa-eye";
this.strIconHide = "fa fa-eye-slash";
this.strTextShow = "Show password";
this.strTextHide = "Hide password";
this.strBtnClass = "btn btn-default";
}
PasswordToggler.prototype = {
blnCreated : false,
objSelector: null,
objIcon: null,
objButton: null,
init: function(){
var $objSelector = this.setSelector();
//Bail early if selector is undefined or null
if(typeof $objSelector != "undefined" || $objSelector == null){
//Bail early if selector not of type password
if($objSelector.type !== "password"){
//console.log("Error: selector is not of type password");
return false;
}else{
if (this.blnCreated === true) {
return this;
}else{
//console.time('htmlApi');
this.htmlApi();
//console.timeEnd("htmlApiEnd");
//console.time('createMarkup');
this.createMarkup();
//console.timeEnd("createMarkupEnd");
}
}
}
//console.log('Error: selector is undefined || null');
return false;
//console.log(PasswordToggler.prototype.blnCreated, this.blnCreated);
},
htmlApi: function(){
//Cache the selector
var objSelector = this.setSelector();
if (typeof (objSelector) != "undefined" || objSelector != null) {
//Supporting some HTML API
this.strPrefix = objSelector.hasAttribute("data-prefix") ? objSelector.getAttribute("data-prefix") : this.strPrefix;
this.strHandler = objSelector.hasAttribute("data-handler") ? objSelector.getAttribute("data-handler") : this.strHandler;
this.strIconShow = objSelector.hasAttribute("data-icon-show") ? objSelector.getAttribute("data-icon-show") : this.strIconShow;
this.strIconHide = objSelector.hasAttribute("data-icon-hide") ? objSelector.getAttribute("data-icon-hide") : this.strIconHide;
this.strTextShow = objSelector.hasAttribute("data-text-show") ? objSelector.getAttribute("data-text-show") : this.strTextShow;
this.strTextHide = objSelector.hasAttribute("data-text-hide") ? objSelector.getAttribute("data-text-hide") : this.strTextHide;
this.strBtnClass = objSelector.hasAttribute("data-button-class") ? objSelector.getAttribute("data-button-class") : this.strBtnClass;
}
return this;
},
createMarkup: function() {
//reference the selector
var $objSelector = this.setSelector();
//console.log($objSelector,'asdasd');
//Create aditional markup
var objElement = document.createElement("div");
var objElementChild = document.createElement("span");
var objButton = document.createElement("button");
var objIcon = document.createElement("i");
if (typeof objElement != "undefined" && $objSelector != null) {
//Populate the object
this.objSelector = $objSelector;
//Insert into DOM
this.objSelector.parentNode.insertBefore(objElement, this.objSelector);
objElement.appendChild(this.objSelector);
objElement.appendChild(objElementChild);
objElementChild.appendChild(objButton);
objButton.appendChild(objIcon);
//Apply some styles
objElement.setAttribute("class", this.strPrefix+"input-group");
objElementChild.setAttribute("class", this.strPrefix+"input-group-btn");
objButton.setAttribute("type", "button");
objButton.setAttribute("id", this.strPrefix+"button_"+this.strSelector);
objButton.setAttribute("class", this.strBtnClass);
objButton.setAttribute("title", this.strTextShow);
objIcon.setAttribute("class", this.strIconShow);
objIcon.setAttribute("aria-hidden", "true");
//We have created the layout if we got here
this.blnCreated = true;
//populate the object
this.objIcon = objIcon;
this.objButton = objButton;
//adding eventListener
//console.time('addListener');
this.addListener(this.objSelector, this.strHandler);
//console.timeEnd('addListenerEnd');
}
//console.log(this, $objSelector, objElement, this.objButton, this.objIcon);
return this;
},
setSelector: function() {
return document.getElementById(this.strSelector);
},
togglePassword: function($element, $blnActive) {
try{
if ($element.type === "password") {
$element.type = "text";
this.objIcon.setAttribute("class", this.strIconHide);
this.objButton.setAttribute("title", this.strTextHide);
$blnActive = true;
} else {
$element.type = "password";
this.objIcon.setAttribute("class", this.strIconShow);
this.objButton.setAttribute("title", this.strTextShow);
$blnActive = false;
}
}catch(e){
console.log(e.message);
}
return false;
},
addListener: function($element, $strListener) {
var self = this;
var objSelector = document.getElementById(this.strPrefix+"button_"+this.strSelector);
if(this.blnCreated === true){
//console.time('addEventListener');
//If the browser supports EventLIstener use it, else fall to attach event (IE)
if (objSelector.addEventListener) {
//console.log(objSelector.addEventListener);
objSelector.addEventListener(
$strListener, function(){
//console.time('togglePassword');
self.togglePassword($element);
//console.timeEnd('togglePasswordEnd');
});
}else{
objSelector.attachEvent($strListener, function(){
//console.time('togglePassword');
self.togglePassword($element);
//console.timeEnd('togglePasswordEnd');
});
}
return false;
//console.timeEnd('addEventListenerEnd');
}
}
};
|
JavaScript
| 0 |
@@ -5797,17 +5797,17 @@
-c
+C
onsole.l
|
4fec073c3f59f7b853ec0d4f2d7eb17d80c8b9ac
|
update list on changes
|
src/MultiSelect/MultiSelectPopup.js
|
src/MultiSelect/MultiSelectPopup.js
|
import React from 'react';
import PropTypes from 'prop-types';
import find from 'lodash/find';
import trim from 'lodash/trim';
import Fuse from 'fuse.js';
import Link from '../Link/Link';
import { compare, findIdentifiables, isDefined } from '../util/utils';
import IconInput from '../InputIcon/IconInput';
import CheckBoxList from '../Select/CheckBoxList';
import keyNav from '../Select/KeyBoardNav';
import fuseConfig from '../Select/fuseSearchConfig';
const PROPERTY_TYPES = {
placeholder: PropTypes.string,
options: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number.isRequired,
displayString: PropTypes.string.isRequired
})
),
onChange: PropTypes.func,
value: PropTypes.arrayOf(PropTypes.number.isRequired),
compare: PropTypes.func,
showSearch: PropTypes.boolean,
showClear: PropTypes.boolean,
popupHeader: PropTypes.element
};
const DEFAULT_PROPS = {
placeHolder: 'Search ...',
compare: compare,
showSearch: true,
showClear: true,
popupHeader: null
};
class MultiSelectPopup extends React.Component {
constructor(props) {
super(props);
this._sortSelectedOnTop = this._sortSelectedOnTop.bind(this);
this.getOptions = this.getOptions.bind(this);
this.state = {
selected: findIdentifiables(this.props.options, props.value)
};
this.fuse = new Fuse(props.options, fuseConfig);
this.state.filtered = this.getAllSorted();
}
componentDidMount() {
if (this.refs.searchInput && this.refs.searchInput.focus) {
setTimeout(() => this.refs.searchInput.focus(), 0);
}
}
getAllSorted() {
let result = this.props.options.slice(0);
result.sort(this._sortSelectedOnTop);
return result;
}
componentWillReceiveProps(nextProps) {
this.fuse.setCollection(nextProps.options);
let isValueChanged = nextProps.value !== this.props.value;
if (isValueChanged) {
this.setState({ selected: findIdentifiables(nextProps.options, nextProps.value) });
}
}
isSelected(option) {
return this.findOptionInList(this.state.selected, option);
}
findOptionInList(list, option) {
return find(list, item => item.id === option.id);
}
mergeSelectedOptions(selected) {
return this.state.selected
.filter(item => {
let found = this.findOptionInList(this.state.filtered, item);
return !found;
})
.concat(selected);
}
select(option) {
let beforeLen = this.state.selected.length;
let selected = this.state.selected.filter(item => {
return item.id !== option.id;
});
if (beforeLen === selected.length) {
selected.push(option);
}
this._selectOptions(selected);
}
_selectOptions(selected) {
let selectedMerged = this.mergeSelectedOptions(selected);
if (!this._isControlled()) {
this.setState({
selected: selectedMerged
});
}
if (this.getInput()) {
this.getInput().focus();
}
if (this.props.onChange) {
this.props.onChange(
selectedMerged.map(option => {
return option.id;
}),
selectedMerged
);
}
}
_sortSelectedOnTop(option1, option2) {
let isOption1Selected = this.isSelected(option1);
let isOption2Selected = this.isSelected(option2);
if (isOption1Selected && !isOption2Selected) {
return -1;
} else if (isOption2Selected && !isOption1Selected) {
return 1;
} else {
return this.props.compare(option1.displayString, option2.displayString);
}
}
_isControlled() {
return isDefined(this.props.value);
}
_applySearch = value => {
this.resetNav();
let filtered = trim(value).length === 0 ? this.props.options : this.fuse.search(value);
filtered.sort(this._sortSelectedOnTop);
this.setState({
filtered: filtered
});
};
getOptions() {
return this.state.filtered;
}
getSelectedOptionEl() {
return this._checkBoxList.getFocusedEl();
}
getInput() {
return this._searchInput;
}
render() {
return this.props.renderOptions ? this.props.renderOptions() : this.renderOptions();
}
renderOptions = () => {
return (
<div className="select__popup">
{this.props.popupHeader ? this.props.popupHeader : null}
{this.props.showSearch ? (
<div className="select__search-container">
<IconInput
inputRef={input => (this._searchInput = input)}
onKeyDown={e => this.navigate(e)}
ref="searchInput"
fluid={true}
placeholder={this.props.placeholder}
size="sm"
onChange={this._applySearch}
className="select__search"
iconClassName="im icon-search"
/>
</div>
) : null}
{this.props.showClear ? (
<div>
<div className="select__clear-btn">
<Link
className="select__clear-btn"
onClick={() => {
this._selectOptions([]);
}}
>
Clear all selected
</Link>
</div>
</div>
) : null}
<div className="select__options">
<CheckBoxList
ref={checkBoxList => (this._checkBoxList = checkBoxList)}
focus={this.state.tempSelection}
options={this.state.filtered}
onChange={selected => this._selectOptions(selected)}
value={this.state.selected.map(selected => {
return selected.id;
})}
/>
</div>
</div>
);
};
}
MultiSelectPopup.propTypes = PROPERTY_TYPES;
MultiSelectPopup.defaultProps = DEFAULT_PROPS;
export default keyNav(true)(MultiSelectPopup);
|
JavaScript
| 0 |
@@ -2011,24 +2011,137 @@
eChanged) %7B%0A
+ if (this.props.options !== nextProps.options) %7B%0A this._applySearch('');%0A %7D%0A
@@ -4118,24 +4118,96 @@
value =%3E %7B%0A
+ if (this.state.query === value) %7B%0A return;%0A %7D%0A
this
@@ -4419,16 +4419,42 @@
filtered
+,%0A query: value
%0A
|
29153be07ec67046bdcaa9f88250f3d79e86e935
|
add resolve path to webpack config
|
packages/xod-client-browser/webpack/base.js
|
packages/xod-client-browser/webpack/base.js
|
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const autoprefixer = require('autoprefixer');
const pkgpath = subpath => path.join(__dirname, '..', subpath);
const assetsPath = fs.realpathSync(pkgpath('node_modules/xod-client/src/core/assets'));
module.exports = {
devtool: 'source-map',
entry: [
'babel-polyfill',
pkgpath('node_modules/xod-client/src/core/styles/main.scss'),
pkgpath('src/shim.js'),
pkgpath('src/index.jsx'),
],
output: {
filename: 'bundle.js',
path: pkgpath('dist'),
publicPath: '',
},
resolve: {
modulesDirectories: [
pkgpath('node_modules'),
pkgpath('node_modules/xod-client/node_modules'),
pkgpath('node_modules/xod-client/node_modules/xod-core/node_modules'),
],
extensions: ['', '.js', '.jsx', '.scss'],
},
module: {
loaders: [
{
include: pkgpath('src'),
test: /\.jsx?$/,
loaders: [
'babel?presets[]=react,presets[]=es2015',
],
},
{
test: /\.scss$/,
loaders: [
'style',
'css',
'postcss',
'sass?outputStyle=expanded',
],
},
{
test: /assets\/.*\.(jpe?g|png|gif|svg|ttf|eot|svg|woff|woff2)?$/,
loaders: [
`file?name=assets/[path][name].[ext]?[hash:6]&context=${assetsPath}`,
],
},
{
test: /node_modules\/font-awesome\/.*\.(jpe?g|png|gif|svg|ttf|eot|svg|woff|woff2)(\?\S*)?$/,
loaders: [
'file?name=assets/font-awesome/[name].[ext]?[hash:6]',
],
},
{
test: /\.json5$/,
loader: 'json5-loader',
},
{
test: /json5\/lib\/require/,
loader: 'null',
}
],
},
plugins: [
new webpack.NoErrorsPlugin(),
new CopyWebpackPlugin([
{ from: pkgpath('src/index.html') },
]),
],
postcss: function postCssPlugins() { return [autoprefixer]; },
};
|
JavaScript
| 0.000001 |
@@ -838,24 +838,75 @@
_modules'),%0A
+ pkgpath('node_modules/xod-js/node_modules'),%0A
%5D,%0A e
|
672799e345e4a173c1dab040f0cf3c8f18fbfe07
|
Revert "fix up SPA route dir creation + casing"
|
scripts/generate-redirects.js
|
scripts/generate-redirects.js
|
#!/usr/bin/env node
// Generates redirects for legacy MozVR.com site.
// (Useful script for generating directory structure for a SPA too!)
var fs = require('fs');
var path = require('path');
var urllib = require('url');
require('shelljs/global');
var DESTINATION_DIR = '_prod';
var ROOT_DIR = path.join(__dirname, '..');
var SPA_ROUTES = JSON.parse(getFileContents('spa_routes.json'));
var toMakeFiles = {};
var toMakeDirs = {};
var bodies = {};
function getBody (fn) {
var ret = bodies[fn];
if (fn in bodies) {
return ret;
}
bodies[fn] = getFileContents(fn);
return bodies[fn];
}
function getPathRelative () {
var args = Array.apply(null, arguments).sort();
return path.join.apply(this, [ROOT_DIR].concat(args));
}
function getDirname (fn) {
// Collapse multiple `/` to a single `/`.
// Add a single `/` if one doesn't exist.
fn = fn.replace(/\/+$/, '/');
if (fn.substr(-1) !== '/') { fn += '/'; }
return fn;
}
function getFileContents (fn) {
return String(fs.readFileSync(getPathRelative(fn)));
}
function writePlaceholderIfEmpty (fn, fallback) {
var exists = test('-e', fn);
console.log(exists ? '[ SKIP ]' : '[ OK ] ', fn);
if (exists) { return; }
String(fallback).to(fn);
}
function addRoute (uri, fallback) {
var pathname = urllib.parse(uri).pathname;
pathname = path.normalize(pathname); // Removes any leading `/`.
var fn = urllib.resolve('/', pathname);
if (fn[0] === '/') {
fn = fn.substr(1);
}
if (!fn) {
fn = 'index.html';
}
if (path.extname(fn)) {
if (!(fn in toMakeFiles)) {
toMakeFiles[fn] = getBody(fallback);
}
} else {
if (!(fn in toMakeDirs)) {
toMakeDirs[getDirname(fn)] = getBody(fallback);
}
}
}
if (!test('-d', getPathRelative(DESTINATION_DIR))) {
return;
}
pushd(getPathRelative(DESTINATION_DIR));
Object.keys(SPA_ROUTES).forEach(function (fallback) {
var routeList = SPA_ROUTES[fallback];
routeList.forEach(function (uri) {
if (!uri) { return; }
addRoute(uri.toLowerCase(), fallback);
});
});
Object.keys(toMakeFiles).forEach(function (fn) {
var dest = getPathRelative(DESTINATION_DIR, fn);
if (test('-e', dest)) { return; }
mkdir('-p', path.dirname(dest));
var contents = toMakeFiles[fn];
writePlaceholderIfEmpty(dest, contents);
});
Object.keys(toMakeDirs).forEach(function (fn) {
var dest = getPathRelative(DESTINATION_DIR, fn);
if (test('-d', dest)) { return; }
mkdir('-p', dest);
var contents = toMakeDirs[fn];
writePlaceholderIfEmpty(path.join(dest, 'index.html'), contents);
writePlaceholderIfEmpty(dest.slice(0, -1) + '.html', contents);
});
popd();
|
JavaScript
| 0 |
@@ -1971,60 +1971,20 @@
-if (!uri) %7B return; %7D%0A addRoute(uri.toLowerCase()
+addRoute(uri
, fa
|
6b182990cf3f7e94b8db4830efdb89de4948bfe5
|
add more PhET related bad texts, https://github.com/phetsims/phet-io/issues/1472
|
eslint/rules/bad-text.js
|
eslint/rules/bad-text.js
|
// Copyright 2018-2019, University of Colorado Boulder
/* eslint-disable */
/**
* Lint detector for invalid text. Checks the entire file and does not correctly report line number.
* Lint is disabled for this file so the bad texts aren't themselves flagged.
*
* @author Sam Reid (PhET Interactive Simulations)
*/
module.exports = function( context ) {
'use strict';
const getBadTextTester = require( './getBadTextTester' );
var badTexts = [
// Proper casing for *boxes
'toolBox',
'ToolBox',
'CheckBox',
'checkBox',
'Combobox',
'combobox',
// In ES6, extending object causes methods to be dropped
'extends Object',
// Forbid common duplicate words
' the the ',
' a a ',
// For phet-io use PHET_IO in constants
'PHETIO',
'phetio element', // use "phet-io element" or "PhET-iO element"
'@return '
];
return {
Program: getBadTextTester( badTexts, context )
};
};
module.exports.schema = [
// JSON Schema for rule options goes here
];
|
JavaScript
| 0 |
@@ -786,16 +786,45 @@
HETIO',%0A
+ 'Phet-iO',%0A ' Phet ',%0A
'phe
|
e2476f6866a5d0da801ee5a5e5ff3d502cdcf392
|
Fix #230 for CORS
|
tasks/grunticon/static/grunticon.embed.cors.js
|
tasks/grunticon/static/grunticon.embed.cors.js
|
/*global grunticon:true*/
(function(grunticon, window){
"use strict";
var document = window.document;
// x-domain get (with cors if available)
var ajaxGet = function( url, cb ) {
var xhr = new window.XMLHttpRequest();
if ( "withCredentials" in xhr ) {
xhr.open( "GET", url, true );
} else if ( typeof window.XDomainRequest !== "undefined" ) { //IE
xhr = new window.XDomainRequest();
xhr.open( "GET", url );
}
if( cb ){
xhr.onload = cb;
}
xhr.send();
return xhr;
};
var svgLoadedCORSCallback = function(callback){
if( grunticon.method !== "svg" ){
return;
}
grunticon.ready(function(){
ajaxGet( grunticon.href, function() {
var style = document.createElement( "style" );
style.innerHTML = this.responseText;
var ref = grunticon.getCSS( grunticon.href );
ref.parentNode.insertBefore( style, ref );
ref.parentNode.removeChild( ref );
grunticon.embedIcons( grunticon.getIcons( style ) );
if( callback ){
callback();
}
} );
});
};
grunticon.ajaxGet = ajaxGet;
grunticon.svgLoadedCORSCallback = svgLoadedCORSCallback; //TODO: Deprecated
grunticon.embedSVGCors = svgLoadedCORSCallback;
}(grunticon, this));
|
JavaScript
| 0.000002 |
@@ -802,24 +802,40 @@
con.href );%0A
+%09%09%09%09if( ref )%7B%0A%09
%09%09%09%09ref.pare
@@ -869,24 +869,25 @@
ref );%0A%09%09%09%09
+%09
ref.parentNo
@@ -905,24 +905,25 @@
ild( ref );%0A
+%09
%09%09%09%09gruntico
@@ -967,23 +967,31 @@
le ) );%0A
+%09
%09%09%09%09if(
+ typeof
callbac
@@ -991,20 +991,36 @@
callback
+ === %22function%22
)%7B%0A
+%09
%09%09%09%09%09cal
@@ -1028,16 +1028,23 @@
back();%0A
+%09%09%09%09%09%7D%0A
%09%09%09%09%7D%0A%09%09
|
4d0cd622bd1997e3587d41480de34e17c20a3aca
|
optimize script
|
scripts/mdl-variables-copy.js
|
scripts/mdl-variables-copy.js
|
/* eslint-disable */
var fs = require('fs');
function copyFileSync(srcFile, destFile) {
try {
var BUF_LENGTH, buff, bytesRead, fdr, fdw, pos;
BUF_LENGTH = 64 * 1024;
buff = new Buffer(BUF_LENGTH);
fdr = fs.openSync(srcFile, 'r');
fdw = fs.openSync(destFile, 'w');
bytesRead = 1;
pos = 0;
while (bytesRead > 0) {
bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
fs.writeSync(fdw, buff, 0, bytesRead);
pos += bytesRead;
}
fs.closeSync(fdr);
return fs.closeSync(fdw);
} catch(error) {
console.log(error);
}
};
var overridenVariablesFilePath = __dirname + '/../src/style/_mdl_variables.scss';
var oldMdlVariablesFilePath = __dirname + '/../node_modules/material-design-lite/src/_variables.scss'
var newMdlVariablesFilePath = __dirname + '/../../node_modules/material-design-lite/src/_variables.scss'
fs.access(oldMdlVariablesFilePath, fs.constants.W_OK, (err) => {
var path = err ? newMdlVariablesFilePath : oldMdlVariablesFilePath;
console.log('Override MDL variables... into path : ' + path);
copyFileSync(overridenVariablesFilePath, path);
console.log('Material design lite SASS variables overriden !');
});
|
JavaScript
| 0.000002 |
@@ -835,16 +835,17 @@
es.scss'
+;
%0Avar new
@@ -941,16 +941,17 @@
es.scss'
+;
%0A%0Afs.acc
|
63c704da4544d3a9dcce9651925ea2a13c3a4717
|
set BoardView height/width
|
app/src/views/GameView.js
|
app/src/views/GameView.js
|
/* globals define */
/**
* GameView contains all the gameplay views, i.e. GameHeaderView and BoardView
*/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var ContainerSurface = require('famous/surfaces/ContainerSurface');
var GameHeaderView = require('./GameHeaderView');
var HeaderFooterLayout = require("famous/views/HeaderFooterLayout");
// ## Views
var BoardView = require('./BoardView');
function _createBoardView() {
var layout = new HeaderFooterLayout({
headerSize: 44
});
this.boardView = new BoardView();
this.gameHeaderView = new GameHeaderView();
layout.header.add(this.gameHeaderView);
layout.content.add(this.boardView);
this.add(layout);
// Setup event listeners
this.boardView.pipe(this.gameHeaderView);
}
function GameView() {
View.apply(this, arguments);
_createBoardView.call(this);
}
GameView.prototype = Object.create(View.prototype);
GameView.prototype.constructor = GameView;
GameView.DEFAULT_OPTIONS = {};
module.exports = GameView;
});
|
JavaScript
| 0.000001 |
@@ -650,24 +650,25 @@
ardView() %7B%0A
+%0A
var layo
@@ -719,10 +719,31 @@
ze:
-44
+this.options.headerSize
%0A
@@ -783,19 +783,131 @@
ardView(
+%7B%0A viewHeight: window.innerHeight - this.options.headerSize,%0A viewWidth: window.innerWidth - 10%0A %7D
);%0A
+%0A
this
@@ -1361,16 +1361,38 @@
IONS = %7B
+%0A headerSize: 44%0A
%7D;%0A%0A mo
|
dfbc127c20bc1107cf510710a7c4c1aa895ab893
|
Use the right i18n string in setup store
|
app/stores/setup-store.js
|
app/stores/setup-store.js
|
let Promise = require('bluebird')
let path = require('path')
let partial = require('underscore').partial
let ibrew = require('../util/ibrew')
let xdg_mime = require('../util/xdg-mime')
let Logger = require('../util/log').Logger
let log = require('../util/log')('setup-store')
let Store = require('./store')
let AppDispatcher = require('../dispatcher/app-dispatcher')
let AppConstants = require('../constants/app-constants')
let AppActions = require('../actions/app-actions')
let path_done = false
let ready = false
function augment_path () {
let bin_path = ibrew.bin_path()
if (!path_done) {
path_done = true
process.env.PATH = `${bin_path}${path.delimiter}` + process.env.PATH
}
return bin_path
}
async function install_deps (opts) {
let fetch = partial(ibrew.fetch, opts)
// 7-zip is a simple binary
await fetch('7za')
// these are .7z archives
let compressed = ['butler', 'elevate', 'file'].map(fetch)
await Promise.all(compressed)
}
async function run () {
augment_path()
let opts = {
logger: new Logger(),
onstatus: AppActions.setup_status
}
try {
await xdg_mime.register_if_needed(opts)
await install_deps(opts)
ready = true
AppActions.setup_done()
} catch (err) {
log(opts, `Setup failed: ${err.stack || err}`)
// only unrecoverable errors should get here
AppActions.setup_status('login.status.error', 'error', {error: err.stack || err})
}
}
let SetupStore = Object.assign(new Store('setup-store'), {
is_ready: () => ready
})
AppDispatcher.register('setup-store', Store.action_listeners(on => {
on(AppConstants.WINDOW_READY, run)
}))
module.exports = SetupStore
|
JavaScript
| 0.000001 |
@@ -1383,21 +1383,29 @@
.status.
-error
+setup_failure
', 'erro
|
30ce16515f1ac36215d7f1e368c88db5dc204b2b
|
fix local storage namespace
|
src/app/buildvolume/models/model.js
|
src/app/buildvolume/models/model.js
|
/**
* @class AppBuildvolumeModel
* @extends GuiPanelModel
*/
var AppBuildvolumeModel = GuiPanelModel.extend(
{
/**
* Panel target id.
*
* @protected
* @property target
* @type {String}
* @default 'columnOne'
*/
target: 'columnOne',
/**
* Panel position index.
*
* @protected
* @property index
* @type {Integer}
* @default 1
*/
index: 2,
/**
* Model setup.
*
* Called by GuiModule, immediately after Module create().
*
* @method setup
* @return {Mixed}
*/
setup: function() {
// self alias
var self = this;
// panel color and icon
self.color('gray');
self.icon('cube');
// size
self.size = self.module.getLocal('AppViewer3d.size', {
x: ko.observable(200),
y: ko.observable(200),
z: ko.observable(200)
});
// texts
self.texts = {
floor: self.module.getText('floor'),
grid : self.module.getText('grid'),
axes : self.module.getText('axes'),
box : self.module.getText('box')
};
// after render
self.afterRender = function(elements, self) {
var $self = $('#appbuildvolume-size input');
self.$sizeX = $($self.get(0));
self.$sizeY = $($self.get(1));
self.$sizeZ = $($self.get(2));
};
// public events
self.onSizeChange = function(size) {};
self.onToggleElement = function(name) {};
// on size change
self.sizeChange = function(self, event) {
self.onSizeChange({
x: parseInt(self.$sizeX.val()),
y: parseInt(self.$sizeY.val()),
z: parseInt(self.$sizeZ.val()),
});
};
// toggle element
self.toggleElement = function(self, event) {
$(event.target).toggleClass('active');
self.onToggleElement(event.target.value);
};
}
});
|
JavaScript
| 0.000005 |
@@ -788,20 +788,8 @@
al('
-AppViewer3d.
size
@@ -906,16 +906,31 @@
%7D
+, 'AppViewer3d'
);%0A%0A
|
c64cf9912e17dfeaafa6dccb2bde3a6644b0c745
|
Fix flow issue
|
src/app/components/YouTube/index.js
|
src/app/components/YouTube/index.js
|
// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { loadScript } from 'redux-scripts-manager';
import cx from 'classnames';
import { noop } from 'lodash-es';
import Spacer from 'app/components/Spacer';
import styles from './styles.styl';
type Props = {
className: ?string,
videoId: string,
autoplay: boolean,
onReady: null | () => void,
onStateChange: null | (event: {}) => void,
loadScript: (src: string, callbackName: string) => Promise<void>,
};
@connect(null, { loadScript })
export default class YouTube extends Component<Props, void> {
static defaultProps = {
autoplay: false,
onReady: noop,
onStateChange: noop,
};
componentDidMount() {
this.props.loadScript('https://www.youtube.com/iframe_api', 'onYouTubeIframeAPIReady')
.then(() => {
const { videoId, autoplay } = this.props;
this.player = new window.YT.Player(this._container, {
videoId,
playerVars: {
autoplay: autoplay ? 1 : 0,
},
events: {
onReady: this.onPlayerReady,
onStateChange: this.onPlayerStateChange,
},
});
});
}
componentDidUpdate(prevProps: Props) {
if (!this.player) return;
if (prevProps.videoId !== this.props.videoId) {
const method = this.props.autoplay ? 'loadVideoById' : 'cueVideoById';
this.player && this.player[method](this.props.videoId);
}
}
componentWillUnmount() {
this.player && this.player.destroy();
}
onPlayerReady = () => {
this.props.onReady();
};
onPlayerStateChange = (event) => {
this.props.onStateChange(event);
};
_container: ?HTMLDivElement;
player: null | {
loadVideoById: (videoId: string) => void,
cueVideoById: (videoId: string) => void,
};
render() {
return (
<div className={cx(styles.root, this.props.className)}>
<Spacer className={styles.spacer} ratio={16 / 9} />
<div className={styles.player} ref={ref => (this._container = ref)} />
</div>
);
}
}
|
JavaScript
| 0.000001 |
@@ -369,23 +369,16 @@
onReady:
- null %7C
() =%3E v
@@ -398,23 +398,16 @@
eChange:
- null %7C
(event:
|
af1b70a724ad614cac971f070c50dd9acc0010c3
|
update slack-msg-callback.js
|
scripts/slack-msg-callback.js
|
scripts/slack-msg-callback.js
|
//var slackToken = process.env.HUBOT_SLACK_VERIFY_TOKEN;
module.exports = (robot) => {
// robot.router.post('/hubot/slack-msg-callback', (req, res) => {
// var data = null;
// if(req.body.payload) {
// try {
// data = JSON.parse(req.body.payload);
// } catch(e) {
// robot.logger.error("Invalid JSON submitted to Slack message callback");
// //res.send(422)
// res.send('You supplied invalid JSON to this endpoint.');
// return;
// }
// } else {
// robot.logger.error("Non-JSON submitted to Slack message callback");
// //res.send(422)
// res.send('You supplied invalid JSON to this endpoint.');
// return;
// }
// if(data.token === slackToken) {
// robot.logger.info("Request is good");
// } else {
// robot.logger.error("Token mismatch on Slack message callback");
// //res.send(403)
// res.send('You are not authorized to use this endpoint.');
// return;
// }
// var handled = robot.emit(`slack:msg_action:${data.callback_id}`, data, res);
// if (!handled) {
// //res.send(500)
// res.send('No scripts handled the action.');
// }
// });
};
|
JavaScript
| 0.000001 |
@@ -72,16 +72,24 @@
s =
+function
(robot)
=%3E %7B
@@ -84,18 +84,16 @@
(robot)
-=%3E
%7B%0A //
|
6e5939c7a44ab31ced1f10ec8bfd251f53ab99c0
|
Add DevTools to Context Menu
|
app/utils/context-menu.js
|
app/utils/context-menu.js
|
import Ember from 'ember';
import config from '../config/environment';
function Menu() {
var gui = window.requireNode('nw.gui');
var menu = new gui.Menu();
// Commands
var cut = new gui.MenuItem({
label: 'Cut',
click: function () {
document.execCommand('cut');
}
});
var copy = new gui.MenuItem({
label: 'Copy',
click: function () {
document.execCommand('copy');
}
});
var paste = new gui.MenuItem({
label: 'Paste',
click: function () {
document.execCommand('paste');
}
});
var emberInspector = new gui.MenuItem({
label: 'Ember Inspector',
click: function () {
var s = document.createElement('script');
s.src = 'http://ember-extension.s3.amazonaws.com/dist_bookmarklet/load_inspector.js';
document.body.appendChild(s);
}
});
menu.append(cut);
menu.append(copy);
menu.append(paste);
if (config.environment === 'development') {
menu.append(emberInspector);
}
// Mac Menu
if (process && process.platform === 'darwin') {
var mb = new gui.Menu({type: 'menubar'});
mb.createMacBuiltin('Azure Storage Explorer');
gui.Window.get().menu = mb;
}
return menu;
}
var contextMenu = {
setup: function () {
var menu = new Menu();
Ember.$(document).on('contextmenu', function (e) {
e.preventDefault();
menu.popup(e.originalEvent.x, e.originalEvent.y);
});
}
};
export default contextMenu;
|
JavaScript
| 0 |
@@ -931,16 +931,187 @@
%0A %7D);
+%0A var devTools = new gui.MenuItem(%7B%0A label: 'DevTools',%0A click: function () %7B%0A require('nw.gui').Window.get().showDevTools();%0A %7D%0A %7D);
%0A%0A me
@@ -1259,16 +1259,47 @@
ector);%0A
+ menu.append(devTools);%0A
%7D%0A%0A
|
a5621a41ab0db534a8995aa9f8909fcdddd62718
|
test course patch permissions
|
test/services/courses/services/courses.test.js
|
test/services/courses/services/courses.test.js
|
const assert = require('assert');
const chai = require('chai');
const app = require('../../../../src/app');
const courseService = app.service('courses');
// const testObjects = require('../helpers/testObjects')(app);
describe('course service', () => {
it('registered the courses service', () => {
assert.ok(courseService);
});
it('creates a course', () => courseService.create({
name: 'testCourse',
schoolId: '0000d186816abba584714c5f',
userIds: [],
classIds: [],
teacherIds: [],
ltiToolIds: [],
})
.then((course) => {
chai.expect(course.name).to.equal('testCourse');
chai.expect(course.userIds).to.have.lengthOf(0);
}));
});
|
JavaScript
| 0 |
@@ -3,46 +3,18 @@
nst
-assert = require('assert');%0Aconst chai
+%7B expect %7D
= r
@@ -126,11 +126,8 @@
);%0A%0A
-//
cons
@@ -154,16 +154,19 @@
ire('../
+../
helpers/
@@ -273,17 +273,14 @@
%7B%0A%09%09
-assert.ok
+expect
(cou
@@ -290,16 +290,36 @@
Service)
+.to.not.be.undefined
;%0A%09%7D);%0A%0A
@@ -342,21 +342,52 @@
ourse',
-() =%3E
+async () =%3E %7B%0A%09%09const course = await
courseS
@@ -402,16 +402,17 @@
reate(%7B%0A
+%09
%09%09name:
@@ -427,16 +427,17 @@
rse',%0A%09%09
+%09
schoolId
@@ -468,16 +468,17 @@
c5f',%0A%09%09
+%09
userIds:
@@ -482,16 +482,17 @@
ds: %5B%5D,%0A
+%09
%09%09classI
@@ -501,16 +501,17 @@
: %5B%5D,%0A%09%09
+%09
teacherI
@@ -518,16 +518,17 @@
ds: %5B%5D,%0A
+%09
%09%09ltiToo
@@ -541,144 +541,1575 @@
%5B%5D,%0A
+%09
%09%7D)
+;
%0A%09%09
-.then((course) =%3E %7B%0A%09%09%09chai.expect(course.name).to.equal('testCourse');%0A%09%09%09chai.expect(course.userIds).to.have.lengthOf(0);%0A%09%09%7D));
+expect(course.name).to.equal('testCourse');%0A%09%09expect(course.userIds).to.have.lengthOf(0);%0A%09%7D);%0A%0A%09it('teacher can PATCH course', async () =%3E %7B%0A%09%09const teacher = await testObjects.createTestUser(%7B roles: %5B'teacher'%5D %7D);%0A%09%09const course = await testObjects.createTestCourse(%7B name: 'courseNotChanged', teacherIds: %5Bteacher._id%5D %7D);%0A%09%09const params = await testObjects.generateRequestParamsFromUser(teacher);%0A%0A%09%09const result = await courseService.patch(course._id, %7B name: 'courseChanged' %7D, params);%0A%09%09expect(result.name).to.equal('courseChanged');%0A%09%7D);%0A%0A%09it('substitution teacher can not PATCH course', async () =%3E %7B%0A%09%09try %7B%0A%09%09%09const teacher = await testObjects.createTestUser(%7B roles: %5B'teacher'%5D %7D);%0A%09%09%09const course = await testObjects.createTestCourse(%7B%0A%09%09%09%09name: 'courseNotChanged', substitutionIds: %5Bteacher._id%5D,%0A%09%09%09%7D);%0A%09%09%09const params = await testObjects.generateRequestParamsFromUser(teacher);%0A%09%09%09await courseService.patch(course._id, %7B name: 'courseChanged' %7D, params);%0A%09%09%09throw new Error('should have failed');%0A%09%09%7D catch (err) %7B%0A%09%09%09expect(err.message).to.not.equal('should have failed');%0A%09%09%09expect(err.code).to.eq(403);%0A%09%09%7D%0A%09%7D);%0A%0A%09/* it('teacher can DELETE course', async () =%3E %7B%0A%09%09const teacher = await testObjects.createTestUser(%7B roles: %5B'teacher'%5D %7D);%0A%09%09const course = await testObjects.createTestCourse(%7B name: 'course', teacherIds: %5Bteacher._id%5D %7D);%0A%09%09const params = await testObjects.generateRequestParamsFromUser(teacher);%0A%0A%09%09const result = await courseService.remove(course._id, params);%0A%09%09expect(result.name).to.equal('courseChanged');%0A%09%7D); */
%0A%7D);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.