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
|
---|---|---|---|---|---|---|---|
2f231fe951422207df1146540166f6881fc6071f
|
fix ajax erroring
|
static/javascript/tba_js/gameday_mytba.js
|
static/javascript/tba_js/gameday_mytba.js
|
$(function() {
// Setup redirect after login
$('#mytba-login').click(function() {
window.location.href = '/account?redirect=' + escape(document.URL);
});
updateFavoritesList(); // Setup
// Setup typeahead
$('#add-favorite-team-input').attr('autocomplete', 'off');
$('#add-favorite-team-input').typeahead([
{
prefetch: {
url: '/_/typeahead/teams-all',
filter: unicodeFilter
},
}
]);
// Submit form when entry chosen
function doAction(obj, datum) {
var team_re = datum.value.match(/(\d+) [|] .+/);
if (team_re != null) {
team_key = 'frc' + team_re[1];
$('#add-favorite-team-model-key').attr('value', team_key);
$('#add-favorite-team-form').submit();
}
}
$('#add-favorite-team-input').bind('typeahead:selected', doAction);
$('#add-favorite-team-input').bind('typeahead:autocompleted', doAction);
// Form for adding favorites
$('#add-favorite-team-form').on('submit', function(e) {
e.preventDefault();
var data = $("#add-favorite-team-form :input").serializeArray();
$.ajax({
type: 'POST',
dataType: 'json',
url: '/_/account/favorites/add',
data: data,
success: function(msg) {
updateFavoritesList();
$('#add-favorite-team-input').typeahead('setQuery', '');
},
error: function(xhr, textStatus, errorThrown) {
$('#mytba-alert-container').append('<div class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>Oops! Failed to add favorite.</strong><br>Something went wrong on our end. Please try again later.</div>');
}
});
});
});
// For getting favorites from server
function updateFavoritesList() {
$.ajax({
type: 'GET',
dataType: 'json',
url: '/_/account/favorites/1',
success: function(favorites) {
for (var key in favorites) {
insertFavoriteTeam(favorites[key]);
}
updateAllMatchbars();
},
error: function(xhr, textStatus, errorThrown) {
if (xhr.status == 401) { // User not logged in
var last_login_prompt = $.cookie("tba-gameday-last-login-prompt");
var cur_epoch_ms = new Date().getTime();
if (last_login_prompt == null || parseInt(last_login_prompt) + 1000*60*60*24 < cur_epoch_ms) { // Show prompt at most once per day
$('#login-modal').modal('show');
$.cookie("tba-gameday-last-login-prompt", cur_epoch_ms);
}
$('#settings-button').attr('href', '#login-modal');
}
$('#mytba-alert-container').append('<div class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>Oops! Unable to get favorites.</strong><br>Something went wrong on our end. Please try again later.</div>');
}
});
}
function insertFavoriteTeam(favorite_team) {
var team_number = favorite_team['model_key'].substring(3);
var existing_favorites = $("#favorite-teams")[0].children;
// Insert team sorted by team number. Don't re-add if the team is already listed.
var added = false;
var element = $("<li id=favorite-" + team_number + " class='favorite-team'>" + team_number + " <a data-team-number='" + team_number + "' class='remove-favorite' title='Remove'><span class='glyphicon glyphicon-remove'></span></a></li>");
for (var i=0; i<existing_favorites.length; i++) {
var existing_team_number = parseInt(existing_favorites[i].id.replace(/[A-Za-z$-]/g, ""));
if (existing_team_number > team_number) {
element.insertBefore($("#" + existing_favorites[i].id));
added = true;
break;
} else if (existing_team_number == team_number) {
added = true;
break;
}
}
if (!added) {
$("#favorite-teams").append(element);
}
// Attach deletion callback
$(".remove-favorite").click(function() {
var teamNum = $(this).attr("data-team-number");
var data = {
'action': 'delete',
'model_type': 1,
'model_key': 'frc' + teamNum
};
$.ajax({
type: 'POST',
dataType: 'json',
url: '/_/account/favorites/delete',
data: data,
success: function(msg) {
$("#favorite-" + teamNum).remove();
updateAllMatchbars();
},
error: function(xhr, textStatus, errorThrown) {
$('#mytba-alert-container').append('<div class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>Oops! Failed to delete favorite.</strong><br>Something went wrong on our end. Please try again later.</div>');
}
});
});
}
|
JavaScript
| 0.000007 |
@@ -1177,36 +1177,8 @@
T',%0A
- dataType: 'json',%0A
@@ -1258,35 +1258,53 @@
ccess: function(
-msg
+data, textStatus, xhr
) %7B%0A
@@ -2033,32 +2033,49 @@
nction(favorites
+, textStatus, xhr
) %7B%0A for (v
@@ -4334,32 +4334,8 @@
T',%0A
- dataType: 'json',%0A
@@ -4418,11 +4418,29 @@
ion(
-msg
+data, textStatus, xhr
) %7B%0A
|
ba1e53dccb734cd677665350ca545f817b024f3d
|
fix new user time and mods bug
|
client/app/services/Student/Student.service.js
|
client/app/services/Student/Student.service.js
|
'use strict';
angular.module('hrr10MjbeApp')
.service('Student', function($http, Auth, Skills, Badges, Util) {
var user;
var defaultUser;
//TODO indexOf _id helper method
var getUser = function(cb) {
if (user) return cb(user);
Auth.isLoggedIn(function(is) {
if (is) {
Auth.getCurrentUser(function(res) {
user = res;
cb(user);
})
} else {
if (defaultUser) return cb(null);
$http({
method: 'GET',
url: '/api/defaultuser'
}).then(function(res) {
defaultUser = res.data;
console.log(defaultUser);
cb(null);
})
}
})
}
var save = function(cb) {
getUser(function(student) {
student.$update({}, function(res) {
console.log('Saved and got: ');
console.log(res.studentData);
user.studentData = res.studentData;
Util.safeCb(cb)();
}, function(err) {
Util.safeCb(cb)();
console.log(err);
})
})
}
this.acceptRequest = function(req, cb) {
console.log('accepting');
console.log(req);
$http({
method: 'POST',
url: '/api/users/accept',
data: {
request: req
}
}).then(function successCallback(response) {
getUser(function(user) {
user.studentData = response.data.studentData;
})
cb(response.status);
}, function errorCallback(response) {
cb(response.status);
});
}
this.getName = function(cb) {
getUser(function(user) {
cb(user === null ? 'Guest' : user.name);
})
}
this.getSkills = function(cb) {
getUser(function(user) {
console.log('skills');
console.log(user);
cb(user === null ? [] : user.studentData.skills);
})
}
this.addOrUpdateSkill = function(skillId, status, cb) {
this.addPointsForSkill(skillId, function() {
getUser(function(user) {
if (!user) return;
Skills.getSkill(skillId, function(skill) {
console.log('found skill');
for (var i = 0; i < user.studentData.skills.length; i++) {
if (user.studentData.skills[i].skill._id === skillId) {
console.log('has skill');
user.studentData.skills[i].status = status;
return save(cb);
}
}
console.log('pushing skill');
user.studentData.skills.push({
skill: skill,
status: status
});
save(cb);
})
})
})
}
this.getSkillRoot = function(cb) {
getUser(function(user) {
//what to do here
console.log('getting skill root');
console.log(user.studentData.skillRoot);
cb(user.studentData.skillRoot);
})
}
this.awardBadges = function(cb) {
getUser(function(user) {
if (!user) return cb([]);
Badges.awardBadges(user.studentData, function(newBadges) {
[].push.apply(user.studentData.badges, newBadges);
save();
if (cb) cb(newBadges);
})
})
}
this.hasBadge = function(badgeId, cb) {
getUser(function(user) {
if (!user) return cb(false);
for (var i = 0; i < user.studentData.badges.length; i++) {
if (user.studentData.badges[i]._id === badgeId) {
cb(true);
}
}
cb(false);
});
}
this.getPoints = function(cb) {
getUser(function(user) {
cb(user === null ? 0 : user.studentData.points);
})
}
this.addPoints = function(num) {
getUser(function(user) {
if (!user) return;
user.studentData.points += num;
save();
})
}
this.addPointsForSkill = function(skillId, cb) {
getUser(function(user) {
for (var i = 0; i < user.studentData.skills.length; i++) {
if (skillId === user.studentData.skills[i].skill._id) {
user.studentData.points += 50;
return save(cb);
}
}
user.studentData.points += 100;
save(cb);
})
}
this.getBadges = function(cb) {
getUser(function(user) {
console.log(user);
cb(user === null ? [] : user.studentData.badges);
})
}
this.getRequests = function(cb) {
getUser(function(user) {
cb(user === null ? [] : user.studentData.requests);
})
}
this.getTeacher = function(cb) {
getUser(function(user) {
cb(user === null ? {} : user.studentData.teacher);
})
}
this.getModifications = function(cb) {
getUser(function(user) {
if (user === null) return cb(defaultUser.studentData.modifications);
console.log('in getmod');
console.log(user.studentData);
var ret = {
showTimer: user.studentData.modifications.showTimer !== undefined ? user.studentData.modifications.showTimer : (user.studentData.myClass ? user.studentData.myClass.modifications.showTimer : true),
showLeaderboard: user.studentData.modifications.showLeaderboard !== undefined ? user.studentData.modifications.showLeaderboard : (user.studentData.myClass ? user.studentData.myClass.modifications.showLeaderboard : false),
showWhiteboard: user.studentData.modifications.showWhiteboard !== undefined ? user.studentData.modifications.showWhiteboard : (user.studentData.myClass ? user.studentData.myClass.modifications.showWhiteboard : true)
}
cb(ret);
});
}
this.setModification = function(mod, val) {
getUser(function(user) {
if (!user) return;
user.studentData.modifications[mod] = val;
save();
})
}
this.getLeaderboard = function(cb) {
getUser(function(user) {
if (!user) return cb(null);
console.log('getting leaderboard');
console.log(user.studentData);
$http({
method: 'GET',
url: '/api/users/leaderboard'
}).then(function(res) {
cb(res.data);
})
})
}
this.getTime = function(cb) {
getUser(function(user) {
if (!user) return cb(0);
var time = Date.now();
cb(user.studentData.times[time - time % (24 * 60 * 60 * 1000)] || 0);
})
}
this.getTimes = function(cb) {
getUser(function(user) {
if (!user) return cb([]);
cb(user.studentData.times);
})
}
this.updateTime = function(time) {
getUser(function(user) {
if (!user) return;
var now = Date.now();
user.studentData.times[now - now % (24 * 60 * 60 * 1000)] = time;
if (time % 10 === 0) save();
})
}
this.getJoined = function(cb) {
getUser(function(user) {
cb(user.joined);
})
}
this.clear = function() {
user = null;
}
});
|
JavaScript
| 0 |
@@ -6345,32 +6345,120 @@
e = Date.now();%0A
+ if (!user.studentData.times) %7B%0A user.studentData.times = %7B%7D;%0A %7D%0A
cb(user.
|
8d7da696333a5b47ddd38d02f4df3974705a9af8
|
Fix lint;
|
client/components/ui/fuzzy-or-native-select.js
|
client/components/ui/fuzzy-or-native-select.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Select, { Creatable } from 'react-select';
import { get } from '../../store';
import { maybeHas } from '../../helpers';
const FuzzyOrNativeSelect = connect(state => {
return {
useNativeSelect: get.isSmallScreen(state)
};
})(
class Export extends React.Component {
handleChange = event => {
let value;
if (event && maybeHas(event, "target") && maybeHas(event.target, "value")) {
value = event.target.value;
} else if (event && maybeHas(event, "value")) {
value = event.value;
} else {
value = event;
}
if (value !== this.props.value) {
this.props.onChange(value);
}
};
render() {
let {
useNativeSelect,
options,
creatable,
value,
className,
style,
...otherProps
} = this.props;
delete otherProps.onChange;
let FuzzySelect = creatable ? Creatable : Select;
if (useNativeSelect) {
let nativeOptions = options.map(opt => {
return (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
);
});
return (
<select
onChange={this.handleChange}
value={value}
style={style}
className={className}>
{nativeOptions}
</select>
);
}
return (
<FuzzySelect
{...otherProps}
value={value}
style={style}
onChange={this.handleChange}
options={options}
className={className}
/>
);
}
}
);
FuzzyOrNativeSelect.propTypes = {
// A boolean telling if the fuzzy-select should allow to create an option.
creatable: PropTypes.bool,
// A boolean telling whether the fuzzy-select should allow to clear the input.
clearable: PropTypes.bool,
// An array of options in the select.
options: PropTypes.arrayOf(
PropTypes.shape({ label: PropTypes.string.isRequired, value: PropTypes.string.isRequired })
),
// A callback to be called when the user selects a new value.
onChange: PropTypes.func.isRequired,
// The value to be selected.
value: PropTypes.string.isRequired
};
FuzzyOrNativeSelect.defaultProps = {
creatable: false,
clearable: false,
backspaceRemoves: false,
deleteRemoves: false
};
export default FuzzyOrNativeSelect;
|
JavaScript
| 0.000001 |
@@ -490,16 +490,16 @@
nt,
-%22
+'
target
-%22
+'
) &&
@@ -522,23 +522,23 @@
target,
-%22
+'
value
-%22
+'
)) %7B%0A
@@ -630,15 +630,15 @@
nt,
-%22
+'
value
-%22
+'
)) %7B
|
4b5da85c2214210cfadb0d8991bfe53815c7f3e9
|
Refactor featured code in /discover.
|
client/js/directives/photo-stream-directive.js
|
client/js/directives/photo-stream-directive.js
|
"use strict";
angular.module("hikeio").
directive("photoStream", ["$rootScope", "$timeout", "config", function($rootScope, $timeout, config) {
var template = "<div class='preview-list'>" +
"<a href='/hikes/{{hike.string_id}}' data-ng-repeat='hike in hikes'>" +
"<div class='preview'>" +
"<div data-ng-class='{\"featured-box\": $first}' >" +
"<img class='preview-img' data-ng-src='{{getPreviewImageSrc(hike, $first)}}' data-aspect-ratio='{{getPreviewImageAspectRatio(hike, $first)}}' alt='{{hike.photo_preview.alt}}' />" +
"<div class='preview-footer'>" +
"<div>" +
"<h4 class='preview-title'>{{hike.name}}</h4>" +
"<h4 class='preview-location'>{{hike.locality}}</h4>" +
"</div>" +
"<div>" +
"<h4 class='preview-distance'>{{hike.distance | distance:\"kilometers\":\"miles\":1}} mi.</h4>" +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</a>";
return {
replace: true,
scope: {
hikes: "="
},
template: template,
link: function (scope, element) {
var gutterWidth = 2;
var maxColumnWidth = 400;
scope.getPreviewImageSrc = function(hike, isFirst) {
var photo = hike.photo_preview || hike.photo_facts;
var rendition = "small";
if (isFirst || photo.height > photo.width) {
rendition = "medium";
} else if (photo.width > photo.height) {
rendition = "thumb";
}
return config.hikeImagesPath + "/" + photo.string_id + "-" + rendition + ".jpg";
};
scope.getPreviewImageAspectRatio = function(hike, isFirst) {
var photo = hike.photo_preview || hike.photo_facts;
var aspectRatio = photo.height / photo.width;
if (!isFirst && photo.width > photo.height) {
// Using the thumbnail version of the photo, therefore the aspect ratio will be 1:1
aspectRatio = 1;
}
return aspectRatio;
};
scope.$watch("hikes", function(newValue, oldValue) {
if (newValue.length === 0) return;
$timeout(function() {
var previews = element.find(".preview");
var previewTitles = element.find(".preview-title");
var previewDivs = previews.children("div");
var images = previewDivs.children("img");
var featuredBox = previews.children(".featured-box");
var featuredBoxImage = featuredBox.children("img");
images.load(function() {
var preview = $(this).parent().parent();
preview.css("opacity", "1");
}).each(function() {
if (this.complete) {
$(this).load();
}
$(this).attr("src", $(this).attr("src")); // Workaround for IE, otherwise the load events are not being fired for all images.
});
element.masonry({
itemSelector: ".preview",
gutterWidth: gutterWidth,
isAnimated: true,
columnWidth: function(containerWidth) {
var boxes = Math.ceil(containerWidth / maxColumnWidth);
var boxWidth = Math.floor((containerWidth - (boxes - 1) * gutterWidth) / boxes);
previewTitles.width(boxWidth - 73); // 50px for the distance on the right, and 20px for the outer padding, and 3 for the inner padding
previewDivs.width(boxWidth);
images.each(function(i, img) {
var aspectRatio = parseFloat($(img).attr("data-aspect-ratio"), 10);
$(img).height(aspectRatio * boxWidth);
});
if (boxes !== 1) {
featuredBox.width(boxWidth * 2 + gutterWidth);
var aspectRatio = parseFloat(featuredBoxImage.attr("data-aspect-ratio"), 10);
featuredBoxImage.height(aspectRatio * boxWidth * 2);
}
return boxWidth;
}
});
});
}, true);
}
};
}]);
|
JavaScript
| 0 |
@@ -336,22 +336,40 @@
-box%5C%22:
-$first
+isFeatured(hike, $index)
%7D' %3E%22 +%0A
@@ -437,29 +437,29 @@
eSrc(hike, $
-first
+index
)%7D%7D' data-as
@@ -510,13 +510,13 @@
e, $
-first
+index
)%7D%7D'
@@ -1128,16 +1128,198 @@
= 400;%0A
+%09%09%09%09scope.isFeatured = function(hike, index) %7B%0A%09%09%09%09%09if (index === 0) %7B%0A%09%09%09%09%09%09return true;%0A%09%09%09%09%09%7D%0A%09%09%09%09%09// TODO more logic here to make other photos featured%0A%09%09%09%09%09return false;%0A%09%09%09%09%7D;%0A
%09%09%09%09scop
@@ -1349,38 +1349,36 @@
function(hike, i
-sFirst
+ndex
) %7B%0A%09%09%09%09%09var pho
@@ -1461,23 +1461,45 @@
%09%09%09%09if (
-isFirst
+scope.isFeatured(hike, index)
%7C%7C phot
@@ -1781,22 +1781,20 @@
(hike, i
-sFirst
+ndex
) %7B%0A%09%09%09%09
@@ -1911,15 +1911,37 @@
f (!
-isFirst
+scope.isFeatured(hike, index)
&&
|
5e3dd22606b0fe4d518ba01f3472e81f68a4f41f
|
Change name of prefs object - Fixes #173
|
models/UserPreferences.js
|
models/UserPreferences.js
|
import MetadataItem from './MetadataItem';
import { Set } from '../shims/SetOps.js';
let girder = window.girder;
let UserPreferences = MetadataItem.extend({
/*
resetToDefaults doesn't work unless defaults
is a function. If defaults are a simple object,
changes to the model mutate the defaults object.
*/
defaults: () => {
return {
name: 'rra_preferences',
description: `
Contains your preferences for the Resonant Laboratory application. If
you move or delete this item, your preferences will be lost.`,
meta: {
showHelp: false,
seenTips: {},
achievements: {}
}
};
},
initialize: function () {
let seenTips = window.localStorage.getItem('seenTips');
if (seenTips) {
this.setMeta('seenTips', JSON.parse(seenTips));
}
let achievements = window.localStorage.getItem('achievements');
if (achievements) {
this.setMeta('achievements', JSON.parse(achievements));
}
},
save: function () {
return MetadataItem.prototype.save.apply(this, arguments)
.catch(() => {
// Fallback: store the user's preferences in localStorage
let seenTips = this.getMeta('seenTips');
if (seenTips) {
window.localStorage.setItem('seenTips', JSON.stringify(seenTips));
}
let achievements = this.getMeta('achievements');
if (achievements) {
window.localStorage.setItem('achievements', JSON.stringify(achievements));
}
});
},
addListeners: function () {
this.listenTo(window.mainPage.currentUser, 'rra:login',
this.adoptScratchProjects);
this.listenTo(window.mainPage, 'rra:createProject',
this.claimProject);
},
claimProject: function () {
if (!window.mainPage.currentUser.isLoggedIn()) {
// Because we created this project while not logged in,
// store the project's ID in window.localStorage so that we
// can claim "ownership" when we log in / visit this page again
// (of course, this is easy to hack, but that's the assumption
// with public scratch space)
let scratchProjects = window.localStorage.getItem('scratchProjects');
if (!scratchProjects) {
scratchProjects = [];
} else {
scratchProjects = JSON.parse(scratchProjects);
}
scratchProjects.push(window.mainPage.project.getId());
window.localStorage.setItem('scratchProjects',
JSON.stringify(scratchProjects));
}
},
adoptScratchProjects: function () {
if (!window.mainPage.currentUser.isLoggedIn()) {
return;
}
// Attempt to adopt any projects that this browser
// created in the public scratch space into the
// now-logged-in user's Private folder
let scratchProjects = window.localStorage.getItem('scratchProjects');
if (scratchProjects) {
new Promise((resolve, reject) => {
girder.restRequest({
path: 'item/adoptScratchItems',
data: {
'ids': scratchProjects // already JSON.stringified
},
error: reject,
type: 'PUT'
}).done(resolve).error(reject);
}).then(successfulAdoptions => {
// Now we need to adopt any datasets that these projects refer to
let datasetIds = new Set();
successfulAdoptions.forEach(adoptedProject => {
if (adoptedProject.meta && adoptedProject.meta.datasets) {
adoptedProject.meta.datasets.forEach(datasetId => {
datasetIds.add(datasetId);
});
}
});
new Promise((resolve, reject) => {
girder.restRequest({
path: 'item/adoptScratchItems',
data: {
'ids': JSON.stringify([...datasetIds])
},
error: reject,
type: 'PUT'
});
}).catch(() => {
// For now, silently ignore failures to adopt datasets
window.localStorage.clear('scratchProjects');
}).then(() => {
window.mainPage.currentUser.trigger('rra:updateLibrary');
// In addition to changing the user's library, the current
// project will (pretty much always) have just changed
// as well
if (window.mainPage.project) {
window.mainPage.project.updateStatus();
}
});
}).catch(() => {
// For now, silently ignore failures to adopt projects
window.localStorage.clear('scratchProjects');
});
}
},
hasSeenAllTips: function (tips) {
let seenTips = this.getMeta('seenTips');
for (let selector of Object.keys(tips)) {
let tipId = selector; // + tips[selector];
// Make the id a valid / nice mongo id
tipId = tipId.replace(/[^a-zA-Z\d]/g, '').toLowerCase();
if (seenTips[tipId] !== true) {
return false;
}
}
return true;
},
observeTips: function (tips) {
let seenTips = this.getMeta('seenTips');
for (let selector of Object.keys(tips)) {
let tipId = tips[selector].tipId;
// Make the id a valid / nice mongo id
tipId = tipId.replace(/[^a-zA-Z\d]/g, '').toLowerCase();
seenTips[tipId] = true;
}
this.setMeta('seenTips', seenTips);
this.trigger('rra:observeTips');
this.save();
},
resetToDefaults: function () {
// The user has logged out, or some other authentication
// problem is going on. This sets the app to the initial
// empty state as if no one is logged in
this.clear({
silent: true
});
this.set(this.defaults());
window.localStorage.removeItem('seenTips');
window.localStorage.removeItem('achievements');
window.localStorage.removeItem('scratchProjects');
},
levelUp: function (achievement) {
let achievements = this.getMeta('achievements');
if (achievements[achievement] !== true) {
achievements[achievement] = true;
this.setMeta('achievements', achievements);
this.save().catch(() => {
}); // fail silently
this.trigger('rra:levelUp');
}
}
});
export default UserPreferences;
|
JavaScript
| 0 |
@@ -362,18 +362,17 @@
name: 'r
-ra
+l
_prefere
|
f0ad9d2dc9b7a63fda08cb67f7659f7e69ce1808
|
Remove incorrectly-resolved conflict
|
UserForm.js
|
UserForm.js
|
// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { PropTypes } from 'react';
import Paneset from '@folio/stripes-components/lib/Paneset';
import Pane from '@folio/stripes-components/lib/Pane';
import PaneMenu from '@folio/stripes-components/lib/PaneMenu';
import { Row, Col } from 'react-bootstrap';
import Button from '@folio/stripes-components/lib/Button';
import TextField from '@folio/stripes-components/lib/TextField';
import Select from '@folio/stripes-components/lib/Select';
import RadioButtonGroup from '@folio/stripes-components/lib/RadioButtonGroup';
import RadioButton from '@folio/stripes-components/lib/RadioButton';
import fetch from 'isomorphic-fetch';
import { Field, reduxForm } from 'redux-form';
const sys = require('stripes-loader'); // eslint-disable-line
const okapiUrl = sys.okapi.url;
const tenant = sys.okapi.tenant;
let okapiToken = '';
function validate(values) {
const errors = {};
if (formProps.personal && !formProps.personal.last_name) {
if (values.personal && !values.personal.last_name) {
errors.personal = { last_name: 'Please fill this in to continue' };
}
if (!values.username) {
errors.username = 'Please fill this in to continue';
}
return errors;
}
function asyncValidate(values, dispatch, props) {
return new Promise((resolve, reject) => {
fetch(`${okapiUrl}/users?query=(username="${values.username}")`,
{ headers: Object.assign({}, {
'X-Okapi-Tenant': tenant,
'X-Okapi-Token': okapiToken,
'Content-Type': 'application/json' }),
},
).then((response) => {
if (response.status >= 400) {
console.log('Error fetching user');
} else {
response.json().then((json) => {
if (json.total_records > 0)
reject({ username: 'This User ID has already been taken' });
else
resolve();
});
}
});
});
}
class UserForm extends React.Component {
static contextTypes = {
store: PropTypes.object,
};
static propTypes = {
onClose: PropTypes.func, // eslint-disable-line react/no-unused-prop-types
newUser: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types
handleSubmit: PropTypes.func.isRequired,
reset: PropTypes.func,
pristine: PropTypes.bool,
submitting: PropTypes.bool,
onCancel: PropTypes.func,
initialValues: PropTypes.object,
};
constructor(props, context) {
super(props);
okapiToken = context.store.getState().okapi.token;
}
render() {
const {
handleSubmit,
reset, // eslint-disable-line no-unused-vars
pristine,
submitting,
onCancel,
initialValues,
} = this.props;
/* Menues for Add User workflow */
const addUserFirstMenu = <PaneMenu><button onClick={onCancel} title="close" aria-label="Close New User Dialog"><span style={{ fontSize: '30px', color: '#999', lineHeight: '18px' }} >×</span></button></PaneMenu>;
const addUserLastMenu = <PaneMenu><Button type="submit" title="Create New User" disabled={pristine || submitting} onClick={handleSubmit}>Create User</Button></PaneMenu>;
const editUserLastMenu = <PaneMenu><Button type="submit" title="Update User" disabled={pristine || submitting} onClick={handleSubmit}>Update User</Button></PaneMenu>;
const patronGroupOptions = initialValues.available_patron_groups ? initialValues.available_patron_groups.map((g) => { return { label: g.group, value: g._id, selected: initialValues.patron_group === g._id }; }) : [];
return (
<form>
<Paneset>
<Pane defaultWidth="100%" firstMenu={addUserFirstMenu} lastMenu={initialValues.username ? editUserLastMenu : addUserLastMenu} paneTitle={initialValues.username ? 'Edit User' : 'New User'}>
<Row>
<Col sm={5} smOffset={1}>
<h2>User Record</h2>
<Field label="UserName" name="username" id="adduser_username" component={TextField} required fullWidth />
{!initialValues.id ? <Field label="Password" name="creds.password" id="pw" component={TextField} required fullWidth /> : null}
<Field label="Status" name="active" component={RadioButtonGroup}>
<RadioButton label="Active" id="useractiveYesRB" value="true" inline />
<RadioButton label="Inactive" id="useractiveNoRB" value="false" inline />
</Field>
<fieldset>
<legend>Personal Info</legend>
<Field label="First Name" name="personal.first_name" id="adduser_firstname" component={TextField} required fullWidth />
<Field label="Last Name" name="personal.last_name" id="adduser_lastname" component={TextField} fullWidth />
<Field label="Email" name="personal.email" id="adduser_email" component={TextField} required fullWidth />
</fieldset>
{/* <Field
label="Type"
name="type"
id="adduser_type"
component={Select}
fullWidth
dataOptions={[{ label: 'Select user type', value: '' },
{ label: 'Patron', value: 'Patron', selected: 'selected' }]}
/> */}
<Field
label="Patron Group"
name="patron_group"
id="adduser_group"
component={Select}
fullWidth
dataOptions={[{ label: 'Select patron group', value: null }, ...patronGroupOptions]}
/>
</Col>
</Row>
</Pane>
</Paneset>
</form>
);
}
}
export default reduxForm({
form: 'userForm',
validate,
asyncValidate,
})(UserForm);
|
JavaScript
| 0.001303 |
@@ -1009,69 +1009,8 @@
%7D;%0A%0A
- if (formProps.personal && !formProps.personal.last_name) %7B%0A
if
|
a2b157a3ac4f27c7be5c6d707009480cb658fe48
|
remove parseInt for provisionRequirement.id
|
client/scripts/components/ProvisionActivity.js
|
client/scripts/components/ProvisionActivity.js
|
import React, {Component} from 'react';
import {Alert, Button, Modal, FormControls, Input, Label} from 'react-bootstrap';
import ManagerApi from 'utils/ManagerApi';
export default class ProvisionActivity extends Component {
constructor(props) {
super(props);
this.state = {
stationId: parseInt(this.props.params.id),
batchId: 0,
batches: [],
curBatchActivities: [],
showAlert: false,
showSuccessAlert: false,
showModal: false
};
this.handleAlertDismiss = this.handleAlertDismiss.bind(this);
this.handleSuccessAlertDismiss = this.handleSuccessAlertDismiss.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
this.handleClickBatch = this.handleClickBatch.bind(this);
this.handleUpdateCount = this.handleUpdateCount.bind(this);
this.handleUpdateSuccess = this.handleUpdateSuccess.bind(this);
this.handleUpdateFail = this.handleUpdateFail.bind(this);
}
handleAlertDismiss() {
this.setState({
showAlert: false
});
}
handleSuccessAlertDismiss() {
this.setState({
showSuccessAlert: false
});
}
handleCloseModal() {
this.setState({
showModal: false
});
}
handleClickBatch(id) {
const batch = this.props.batches[id];
if (!batch || !batch.provisionActivities) {
return;
}
this.setState({
showModal: true,
batchId: id,
curBatchActivities: batch.provisionActivities
});
}
handleUpdateCount() {
let body = [];
Object.keys(this.props.provisionRequirements).forEach( key => {
const shipped = parseInt(this.refs[`act${key}`].getValue());
const obj = {
shipped: shipped,
provisionRequirementId: parseInt(key),
batchId: this.state.batchId,
stationId: this.state.stationId
};
body.push(obj);
});
ManagerApi.updateProvisionAvtivity(body, this.handleUpdateSuccess, this.handleUpdateFail);
this.handleCloseModal();
}
handleUpdateSuccess() {
this.setState({
showSuccessAlert: true
});
}
handleUpdateFail() {
this.setState({
showAlert: true
});
}
renderBatches() {
const batches = this.props.batches;
let batchesTable = Object.keys(batches).map(key => {
const item = batches[key];
const contact = item._contact;
return (
<tr key={item.id} className="batches-item" onClick={this.handleClickBatch.bind(this, item.id)}>
<td>{item.trackingNumber}</td>
<td>{contact.name}</td>
<td>{contact.email}</td>
<td>{contact.phone}</td>
<td>{item.createdDate}</td>
</tr>
);
});
return batchesTable;
}
renderAlert() {
if (!this.state.showAlert) {
return;
}
return (
<Alert bsStyle="danger" onDismiss={this.handleAlertDismiss}>
<h4>Oh snap! You got an error!</h4>
<p>Please wait a moment, and try again!</p>
</Alert>
);
}
renderSuccessAlert() {
if (!this.state.showSuccessAlert) {
return;
}
return (
<Alert bsStyle="success" onDismiss={this.handleSuccessAlertDismiss}>
<h4>Update Success!</h4>
</Alert>
);
}
renderActivity() {
if (!this.state.showModal) {
return;
}
const labelCol = 'col-xs-4';
const inputCol = 'col-xs-8';
const curActivities = this.state.curBatchActivities;
const requirements = this.props.provisionRequirements;
let reqCount = {};
curActivities.forEach( item => {
const pId = item.provisionRequirementId;
const shipped = item.shipped || 0;
const promised = item.promised || 0;
if (reqCount[pId]) {
reqCount[pId] = {
shipped: reqCount[pId].shipped + shipped,
promised: reqCount[pId].promised + promised
};
} else {
reqCount[pId] = {shipped: shipped, promised: promised};
}
});
const activities = Object.keys(requirements).map( key => {
const requirement = requirements[key];
const promised = reqCount[key] && reqCount[key].promised || 0;
const shipped = reqCount[key] && reqCount[key].shipped || 0;
return (
<FormControls.Static
key={key}
labelClassName={labelCol}
wrapperClassName={inputCol}
label={requirement && requirement.name}
value={`${promised} / (已收到:${shipped})`} />
);
});
const comfirmForm = Object.keys(requirements).map( key => {
const requirement = requirements[key];
return (
<Input
key={key}
type="text"
ref={`act${key}`}
labelClassName={labelCol}
wrapperClassName={inputCol}
label={requirement && requirement.name} />
);
});
return (
<div>
<Modal show={this.state.showModal} onHide={this.handleCloseModal}>
<Modal.Header closeButton>
<Modal.Title>物資確認</Modal.Title>
</Modal.Header>
<Modal.Body>
<h4><Label bsStyle="info">預計收到物資數量</Label></h4>
{activities}
<hr />
<h4><Label bsStyle="success">實際收到物資數量</Label></h4>
<form className="form-horizontal">
{comfirmForm}
</form>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.handleCloseModal}>取消</Button>
<Button bsStyle="primary" onClick={this.handleUpdateCount}>確認</Button>
</Modal.Footer>
</Modal>
</div>
);
}
render() {
return (
<div className="pro-activity">
{this.renderAlert()}
{this.renderSuccessAlert()}
<table className="table">
<thead>
<tr>
<th>追蹤編號</th>
<th>聯絡人</th>
<th>信箱</th>
<th>電話</th>
<th>日期</th>
</tr>
</thead>
<tbody>
{this.renderBatches()}
</tbody>
</table>
{this.renderActivity()}
</div>
);
}
}
|
JavaScript
| 0.000004 |
@@ -1731,21 +1731,11 @@
Id:
-parseInt(
key
-)
,%0A
|
e7b8e0d9325ba78851e074e283dc7a59242fb428
|
fix infinite async chains on addon reload
|
resource/modules/FavIcons.jsm
|
resource/modules/FavIcons.jsm
|
// VERSION 1.0.1
this.FavIcons = {
get defaultFavicon() {
return this._favIconService.defaultFavicon.spec;
},
init: function() {
XPCOMUtils.defineLazyServiceGetter(this, "_favIconService", "@mozilla.org/browser/favicon-service;1", "nsIFaviconService");
},
// Gets the "favicon link URI" for the given xul:tab, or null if unavailable.
getFavIconUrlForTab: function(tab, callback) {
this._isImageDocument(tab).then((isImageDoc) => {
if(isImageDoc) {
callback(tab.pinned ? tab.image : null);
} else {
this._getFavIconForNonImageDocument(tab, callback);
}
});
},
// Retrieves the favicon for a tab containing a non-image document.
_getFavIconForNonImageDocument: function(tab, callback) {
if(tab.image) {
this._getFavIconFromTabImage(tab, callback);
} else if(this._shouldLoadFavIcon(tab)) {
this._getFavIconForHttpDocument(tab, callback);
} else {
callback(null);
}
},
// Retrieves the favicon for tab with a tab image.
_getFavIconFromTabImage: function(tab, callback) {
let tabImage = gBrowser.getIcon(tab);
// If the tab image's url starts with http(s), fetch icon from favicon service via the moz-anno protocol.
if(/^https?:/.test(tabImage)) {
let tabImageURI = gWindow.makeURI(tabImage);
tabImage = this._favIconService.getFaviconLinkForIcon(tabImageURI).spec;
}
callback(tabImage);
},
// Retrieves the favicon for tab containg a http(s) document.
_getFavIconForHttpDocument: function(tab, callback) {
let {currentURI} = tab.linkedBrowser;
this._favIconService.getFaviconURLForPage(currentURI, (uri) => {
if(uri) {
let icon = this._favIconService.getFaviconLinkForIcon(uri).spec;
callback(icon);
} else {
callback(this.defaultFavicon);
}
});
},
// Checks whether an image is loaded into the given tab.
_isImageDocument: function(tab, callback) {
return new Promise(function(resolve, reject) {
let repeat;
let receiver = function(m) {
if(repeat) {
repeat.cancel();
}
Messenger.unlistenBrowser(tab.linkedBrowser, "isImageDocument", receiver);
resolve(m.data);
};
Messenger.listenBrowser(tab.linkedBrowser, "isImageDocument", receiver);
// sometimes on first open, we don't get a response right away because the message isn't actually sent, although I have no clue why...
let ask = function() {
Messenger.messageBrowser(tab.linkedBrowser, "isImageDocument");
repeat = aSync(ask, 1000);
};
ask();
});
},
// Checks whether fav icon should be loaded for a given tab.
_shouldLoadFavIcon: function(tab) {
// No need to load a favicon if the user doesn't want site or favicons.
if(!Prefs.site_icons || !Prefs.favicons) {
return false;
}
let uri = tab.linkedBrowser.currentURI;
// Stop here if we don't have a valid nsIURI.
if(!uri || !(uri instanceof Ci.nsIURI)) {
return false;
}
// Load favicons for http(s) pages only.
return uri.schemeIs("http") || uri.schemeIs("https");
}
};
Modules.LOADMODULE = function() {
Prefs.setDefaults({
site_icons: true,
favicons: true
}, 'chrome', 'browser');
};
|
JavaScript
| 0 |
@@ -569,32 +569,70 @@
callback);%0A%09%09%09%7D%0A
+%09%09%7D).catch(() =%3E %7B%0A%09%09 callback(null)%0A
%09%09%7D);%0A%09%7D,%0A%0A%09// R
@@ -1872,34 +1872,24 @@
function(tab
-, callback
) %7B%0A%09%09return
@@ -2445,34 +2445,149 @@
%09%09%09%09
-repeat = aSync(ask, 1000);
+if(!repeat) %7B // only repeat once%0A%09%09%09%09 repeat = aSync(ask, 1000);%09%09%09%09 %0A%09%09%09%09%7D else %7B%0A%09%09%09%09 reject(%22isImageDocument response timeout%22);%0A%09%09%09%09%7D
%0A%09%09%09
|
ad7be9b6979565045addb38e2222f1cff2bb05a8
|
Update items.js
|
mods/testsubject/items.js
|
mods/testsubject/items.js
|
"gengarite": {
id: "gengarite",
name: "Gengarite",
spritenum: 588,
megaStone: "Gengar-Mega",
megaEvolves: "Gengar",
onTakeItem: function(item, source) {
if (item.megaEvolves === source.baseTemplate.baseSpecies) return false;
return true;
},
num: 656,
gen: 3,
desc: "Mega-evolves Gengar."
}
};
|
JavaScript
| 0.000001 |
@@ -1,8 +1,32 @@
+exports.BattleItems = %7B%0A
%09%22gengar
|
cc489d1f373eed5435a877b026cc4215b0ff8c1a
|
Update seo-flag.js
|
plugins/seo-flag.js
|
plugins/seo-flag.js
|
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-08-0
* @modified
*
* @description
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
*/
// const log = console.log;
// window.SEO_FALG_FINISHED = window.SEO_FALG_FINISHED || false;
window.SEO_FALG_FINISHED = false;
const SEO_FALG = () => {
const log = console.log;
// let finished = false;
let counter = 1;
function auto() {
const img = document.querySelector(`[data-flagcounter="img"]`);
const a = document.querySelector(`[data-flagcounter="a"]`);
if(a && img && !window.SEO_FALG_FINISHED) {
log(`❓flagcounter.com trying ${counter} times`);
a.href = `https://info.flagcounter.com/QIXi`;
img.src = `https://s11.flagcounter.com/count2/QIXi/bg_000000/txt_00FF00/border_FF00FF/columns_3/maxflags_12/viewers_0/labels_1/pageviews_1/flags_0/percent_1/`;
window.SEO_FALG_FINISHED = true;
} else {
log(` 🎉 flagcounter.com finished!`);
}
counter += 1;
}
let timer = setInterval(() => {
if(!window.SEO_FALG_FINISHED) {
auto();
} else {
log(` ✅ clearInterval, after ${counter} times`);
clearInterval(timer);
}
}, 1000);
}
// IIFE
// (() => SEO_FALG())();
// new version, 2021.07.13
setTimeout(() => {
(() => {
const flagBox = document.querySelector(`[data-uid="seo-flag"]`);
const domStr = `
<a href="https://s11.flagcounter.com/count2/QIXi" data-flagcounter="a">
<img data-flagcounter="img" src="https://s11.flagcounter.com/count2/QIXi/bg_000000/txt_00FF00/border_FF00FF/columns_3/maxflags_12/viewers_0/labels_1/pageviews_1/flags_0/percent_1/" alt="cnblogs" border="0" />
</a>
`;
flagBox.insertAdjacentHTML(`beforeend`, domStr);
log(` 🎉 flagcounter.com finished!`);
})();
}, 1000);
|
JavaScript
| 0 |
@@ -234,16 +234,672 @@
*%0A */%0A%0A
+%0A// new version, 2021.07.13%0AsetTimeout(() =%3E %7B%0A (() =%3E %7B%0A const flagBox = document.querySelector(%60%5Bdata-uid=%22seo-flag%22%5D%60);%0A const domStr = %60%0A %3Ca href=%22https://s11.flagcounter.com/count2/QIXi%22 data-flagcounter=%22a%22%3E%0A %3Cimg data-flagcounter=%22img%22 src=%22https://s11.flagcounter.com/count2/QIXi/bg_000000/txt_00FF00/border_FF00FF/columns_3/maxflags_12/viewers_0/labels_1/pageviews_1/flags_0/percent_1/%22 alt=%22cnblogs%22 border=%220%22 /%3E%0A %3C/a%3E%0A %60;%0A flagBox.insertAdjacentHTML(%60beforeend%60, domStr);%0A const log = console.log;%0A log(%60 %F0%9F%8E%89 flagcounter.com finished!%60);%0A %7D)();%0A%7D, 1000);%0A %0A %0A
// const
@@ -984,16 +984,19 @@
false;%0A
+/*%0A
window.S
@@ -1925,19 +1925,16 @@
// IIFE%0A
-//
(() =%3E S
@@ -1952,594 +1952,7 @@
);%0A%0A
+*
/
-/ new version, 2021.07.13%0AsetTimeout(() =%3E %7B%0A (() =%3E %7B%0A const flagBox = document.querySelector(%60%5Bdata-uid=%22seo-flag%22%5D%60);%0A const domStr = %60%0A %3Ca href=%22https://s11.flagcounter.com/count2/QIXi%22 data-flagcounter=%22a%22%3E%0A %3Cimg data-flagcounter=%22img%22 src=%22https://s11.flagcounter.com/count2/QIXi/bg_000000/txt_00FF00/border_FF00FF/columns_3/maxflags_12/viewers_0/labels_1/pageviews_1/flags_0/percent_1/%22 alt=%22cnblogs%22 border=%220%22 /%3E%0A %3C/a%3E%0A %60;%0A flagBox.insertAdjacentHTML(%60beforeend%60, domStr);%0A log(%60 %F0%9F%8E%89 flagcounter.com finished!%60);%0A %7D)();%0A%7D, 1000);%0A %0A
%0A
|
87ec774bad1ecfe4df23eb5c67627316ef84c59a
|
send current position when pausing, just set playbackStart to null
|
plugins/socketio.js
|
plugins/socketio.js
|
var _ = require('underscore');
var socketio = {};
var config, player;
// called when nodeplayer is started to initialize the plugin
// do any necessary initialization here
socketio.init = function(_player, callback, errCallback) {
player = _player;
config = _player.config;
if(!player.expressServer) {
errCallback('module must be initialized after expressjs module!');
} else {
socketio.io = require('socket.io')(player.expressServer);
socketio.io.on('connection', function(socket) {
if(player.queue[0]) {
socket.emit('playback', {
songID: player.queue[0].songID,
format: player.queue[0].format,
backendName: player.queue[0].backendName,
duration: player.queue[0].duration,
position: player.playbackPosition + (new Date() - player.playbackStart),
playbackStart: player.playbackStart
});
}
socket.emit('queue', player.queue);
});
player.socketio = socketio;
console.log('listening on port ' + (process.env.PORT || config.port));
callback();
}
};
socketio.onSongChange = function(player) {
socketio.io.emit('playback', {
songID: player.queue[0].songID,
format: player.queue[0].format,
backendName: player.queue[0].backendName,
duration: player.queue[0].duration,
position: player.playbackPosition + (new Date() - player.playbackStart),
playbackStart: player.playbackStart
});
socketio.io.emit('queue', player.queue);
};
socketio.onSongPause = function(player) {
socketio.io.emit('playback', null);
};
socketio.onQueueModify = function(player) {
socketio.io.emit('queue', player.queue);
};
socketio.onEndOfQueue = function(player) {
socketio.io.emit('playback', null);
socketio.io.emit('queue', player.queue);
};
module.exports = socketio;
|
JavaScript
| 0 |
@@ -1717,20 +1717,306 @@
yback',
-null
+%7B%0A songID: player.queue%5B0%5D.songID,%0A format: player.queue%5B0%5D.format,%0A backendName: player.queue%5B0%5D.backendName,%0A duration: player.queue%5B0%5D.duration,%0A position: player.playbackPosition + (new Date() - player.playbackStart),%0A playbackStart: null%0A %7D
);%0A%7D;%0A%0As
|
77fe1c03bad2407ad5a4772591d681cf614aad3f
|
Add owner to generic primitive command
|
Source/Scene/Primitive.js
|
Source/Scene/Primitive.js
|
/*global define*/
define([
'../Core/destroyObject',
'../Core/Matrix4',
'../Core/MeshFilters',
'../Core/PrimitiveType',
'../Renderer/BufferUsage',
'../Renderer/VertexLayout',
'../Renderer/CommandLists',
'../Renderer/DrawCommand',
'./SceneMode'
], function(
destroyObject,
Matrix4,
MeshFilters,
PrimitiveType,
BufferUsage,
VertexLayout,
CommandLists,
DrawCommand,
SceneMode) {
"use strict";
/**
* DOC_TBA
*/
var Primitive = function(mesh, appearance) {
/**
* DOC_TBA
*/
this.mesh = mesh;
/**
* DOC_TBA
*/
this.appearance = appearance;
/**
* DOC_TBA
*/
this.modelMatrix = Matrix4.IDENTITY.clone();
/**
* DOC_TBA
*/
this.show = true;
this._sp = undefined;
this._rs = undefined;
this._va = undefined;
this._commands = [];
this._commandLists = new CommandLists();
};
/**
* @private
*/
Primitive.prototype.update = function(context, frameState, commandList) {
if (!this.show || (frameState.mode !== SceneMode.SCENE3D)) {
// TODO: support Columbus view and 2D
return;
}
// TODO: throw if mesh and appearance are not defined
if (typeof this._va === 'undefined') {
var attributeIndices = MeshFilters.createAttributeIndices(this.mesh);
var appearance = this.appearance;
this._va = context.createVertexArrayFromMesh({
mesh : this.mesh,
attributeIndices : attributeIndices,
bufferUsage : BufferUsage.STATIC_DRAW,
vertexLayout : VertexLayout.INTERLEAVED
});
this._sp = context.getShaderCache().replaceShaderProgram(this._sp, appearance.vertexShaderSource, appearance.getFragmentShaderSource(), attributeIndices);
this._rs = context.createRenderState(appearance.renderState);
var command = new DrawCommand();
// TODO: this assumes indices in the mesh - and only one set
command.primitiveType = this.mesh.indexLists[0].primitiveType;
command.vertexArray = this._va;
command.renderState = this._rs;
command.shaderProgram = this._sp;
command.uniformMap = appearance.material._uniforms;
// TODO: command.boundingVolume =
this._commands.push(command);
}
if (frameState.passes.color) {
var commands = this._commands;
var len = commands.length;
for (var i = 0; i < len; ++i) {
commands[i].modelMatrix = this.modelMatrix;
this._commandLists.colorList[i] = commands[i];
}
commandList.push(this._commandLists);
}
};
/**
* DOC_TBA
*/
Primitive.prototype.isDestroyed = function() {
return false;
};
/**
* DOC_TBA
*/
Primitive.prototype.destroy = function() {
this._sp = this._sp && this._sp.release();
this._va = this._va && this._va.destroy();
return destroyObject(this);
};
return Primitive;
});
|
JavaScript
| 0 |
@@ -2150,16 +2150,86 @@
mand();%0A
+// TODO: best owner? Include mesh?%0A command.owner = this;%0A
// TODO:
|
a952aa667429bdc093dd3b8ac7eea144d7d73f41
|
remove old method
|
public/app/WizardClass.js
|
public/app/WizardClass.js
|
define(["js/core/Application", "app/model/FirewallConfiguration", "js/core/History"],
function (Application, FirewallConfiguration, History) {
return Application.inherit({
defaults: {
configuration: null,
I18n: null,
currentStep: 0,
api: null,
segmentedView: null
},
_initializationComplete: function () {
this.callBase();
var api = this.$.api;
var config = api.createEntity(FirewallConfiguration);
// var zones = api.createCollection(Collection.of(Zone));
// zones.fetch({}, function(){
//
// });
this.set('configuration', config);
// config.fetch({
// "fetchSubModels": ["zone",""]
// }, function(err, config){
// });
},
/***
* Starts the application
* @param parameter
* @param callback
*/
start: function (parameter, callback) {
// false - disables autostart
this.callBase(parameter, false);
callback();
},
hasNext: function () {
return (this.$.currentStep < (this.$.segmentedView.$children.length - 1));
}.onChange("currentStep"),
hasPrevious: function () {
return (this.$.currentStep > 0);
}.onChange("currentStep"),
stepsToValidate: function(stepNumber) {
switch (stepNumber) {
case 1:
return "wan";
case 2:
return "lan";
case 3:
return "hostname";
}
return null;
},
validateCurrentStep: function (success) {
var stepToValidate = this.stepsToValidate(this.$.currentStep);
var self = this;
if (stepToValidate) {
this.$.configuration.validate({fields: stepToValidate}, function (err) {
if (self.$.configuration.$[stepToValidate].isValid()) {
success();
}
});
} else {
success();
}
},
clearErrors: function (step) {
var fields = this.stepName(step);
if (fields) {
this.$.configuration.$[fields].clearErrors();
}
this.$.configuration.clearErrors();
},
next: function () {
var self = this;
self.validateCurrentStep(function(){
self.set('currentStep', self.$.currentStep + 1);
});
},
save: function () {
this.$.configuration.save();
},
previous: function () {
this.set('currentStep', this.$.currentStep - 1);
}
});
});
|
JavaScript
| 0.000006 |
@@ -1932,215 +1932,8 @@
%7D,
-%0A clearErrors: function (step) %7B%0A var fields = this.stepName(step);%0A%0A if (fields) %7B%0A this.$.configuration.$%5Bfields%5D.clearErrors();%0A %7D%0A this.$.configuration.clearErrors();%0A %7D,
%0A%0A
|
e99a96b84b5e3d0d0bd034181ec6ab9e025ab283
|
remove zoom.zoom100 command
|
public/app/events/zoom.js
|
public/app/events/zoom.js
|
/* Commands */
/*--
Interface Command {
public void constructor(JSXGraph board, Object Arguments)
public void remove()
public object execute()
}
--*/
var zoomIn = function(board, args) {
this.remove = function() {
board.zoomOut();
};
this.execute = function() {
board.zoomIn();
return {
'X': board.zoomX,
'Y': board.zoomY
};
}
};
var zoomOut = function(board, args) {
this.remove = function() {
board.zoomIn();
};
this.execute = function() {
board.zoomOut();
return {
'X': board.zoomX,
'Y': board.zoomY
};
};
};
var zoom100 = function(board, args) {
this.X = board.zoomX;
this.Y = board.zoomY;
this.remove = function() {
};
this.execute = function() {
board.zoom100();
return {
'X': board.zoomX,
'Y': board.zoomY
};
};
};
module.exports = {
zoomIn: zoomIn,
zoomOut: zoomOut,
zoom100: zoom100
};
|
JavaScript
| 0.000055 |
@@ -595,254 +595,8 @@
%7D;%0A%0A
-var zoom100 = function(board, args) %7B%0A this.X = board.zoomX;%0A this.Y = board.zoomY;%0A this.remove = function() %7B%0A %7D;%0A this.execute = function() %7B%0A board.zoom100();%0A return %7B%0A 'X': board.zoomX,%0A 'Y': board.zoomY%0A %7D;%0A %7D;%0A%7D;%0A
%0Amod
@@ -651,27 +651,7 @@
mOut
-,%0A zoom100: zoom100
%0A%7D;
|
9798d16e0cde4a4b888363be089f02ec9b41b50d
|
Fix for sprite cycles not triggering
|
Source/settings/events.js
|
Source/settings/events.js
|
FullScreenPokemon.FullScreenPokemon.settings.events = {
"keyOnSpriteCycleStart": "onThingAdd",
"keyDoSpriteCycleStart": "placed",
"keyCycleCheckValidity": "alive",
"timingDefault": 9
};
|
JavaScript
| 0 |
@@ -59,22 +59,21 @@
%22keyOn
-Sprite
+Class
CycleSta
@@ -105,14 +105,13 @@
eyDo
-Sprite
+Class
Cycl
|
eea57ec62c953a41557e3f5055fa40e5c641d66d
|
Clean up in dropdown.js
|
src/static/js/dropdown.js
|
src/static/js/dropdown.js
|
"use strict";
(function () {
var closeMenus = function () {
var openLaunchers = document.querySelectorAll('.fn1-dropdown-launcher[aria-expanded="true"]'),
len = openLaunchers.length,
i = 0;
for (i=0; i<len; i++) {
openLaunchers[i].setAttribute("aria-expanded", "");
openLaunchers[i].parentElement.focus();
openLaunchers[i].setAttribute("aria-expanded", "false");
(function (i) {
setTimeout(function() { openLaunchers[i].parentElement.querySelector('.fn1-dropdown-links').style.display = 'none'; }, 300);
})(i);
}
document.removeEventListener('click', closeMenus);
},
launcherClick = function(e) {
var launcher = e.target,
menu = launcher.parentElement.querySelector('.fn1-dropdown-links');
launcher.blur();
closeMenus();
menu.style.display = 'block';
setTimeout(function() {
launcher.setAttribute("aria-expanded", "true");
}, 50)
document.addEventListener('click', closeMenus);
e.stopPropagation();
e.preventDefault();
menu.focus();
},
launchers = document.querySelectorAll('.fn1-dropdown-launcher'),
len = launchers.length,
i = 0;
for (i=0; i<len; i++) {
launchers[i].addEventListener('click', launcherClick);
}
})();
|
JavaScript
| 0.000003 |
@@ -1,18 +1,4 @@
-%22use strict%22;%0A
(fun
@@ -3,24 +3,42 @@
unction () %7B
+%0A %22use strict%22;
%0A var clo
@@ -1048,16 +1048,17 @@
%7D, 50)
+;
%0A
|
09eaf5af1e9fec78aadab80bb3922031d2987795
|
fix end of string
|
mirrorgate-dashboard/src/js/core/Service.js
|
mirrorgate-dashboard/src/js/core/Service.js
|
/*
* Copyright 2017 Banco Bilbao Vizcaya Argentaria, S.A.
*
* 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.
*/
var Service = (function() {
'use strict';
function Service(serviceType, dashboardId) {
var url = serviceType.getUrl(dashboardId);
var timer = serviceType.timer;
var event = new Event(this);
var pending = false;
function callHttpService() {
if (pending) {
return;
}
pending = true;
httpGetAsync(url, function(data) {
pending = false;
event.notify(data);
});
}
function processServerEvent(serverEventType){
var serverSentEventtype=JSON.parse(serverEventType);
if(serverSentEventtype.type === serviceType.serverEventType){
callHttpService();
}
}
this.addListener = function(callback) {
event.attach(callback);
this._checkEventRegistration();
this.request();
};
this.removeListener = function(callback) {
event.detach(callback);
this._checkEventRegistration();
};
this.request = function() { callHttpService(); };
this._checkEventRegistration = function() {
if (event.getListeners().length && !this._attached) {
this._attached = true;
if(serviceType.serverEventType){
ServerSideEvent.addListener(processServerEvent);
}
timer.attach(callHttpService);
} else if (!event.getListeners().length && this._attached) {
this._attached = false;
if(serviceType.serverEventType){
ServerSideEvent.removeListener(processServerEvent);
}
timer.detach(callHttpService);
}
};
this.dispose = function() {
event.reset();
this._checkEventRegistration();
};
}
function ServiceType(timer, resource, serverEventType) {
this._instances = {};
this.timer = timer;
this.serverEventType = serverEventType;
this.getUrl = function(dashboardId) {
var url = 'dashboards/';
if (dashboardId) {
url += dashboardId + '/';
if (resource) {
url += resource;
}
}
return url;
};
}
var self = {
types: {
builds: new ServiceType(Timer.eventually, 'builds','BuildType'),
bugs: new ServiceType(Timer.eventually, 'bugs'),
stories: new ServiceType(Timer.eventually, 'stories', 'FeatureType'),
apps: new ServiceType(Timer.eventually, 'applications'),
dashboard: new ServiceType(Timer.never, 'details'),
dashboards: new ServiceType(Timer.never),
programincrement: new ServiceType(Timer.eventually, 'programincrement','FeatureType),
notifications: new ServiceType(Timer.never, 'notifications'),
userMetrics: new ServiceType(Timer.eventually, 'user-metrics'),
},
get: function(type, dashboardId) {
return (
type._instances[dashboardId] =
type._instances[dashboardId] || new Service(type, dashboardId));
},
reset: function() {
for (var type in self.types) {
var item = self.types[type];
for (var board in item._instances) {
item._instances[board].dispose();
}
item._instances = {};
}
}
};
return self;
})();
|
JavaScript
| 0.001027 |
@@ -3118,16 +3118,17 @@
rement',
+
'Feature
@@ -3131,16 +3131,17 @@
tureType
+'
),%0A
|
afc1b1c1d88a3b59e103c58f1bd49d9f348e3614
|
Fix tests
|
mobile/src/FileViewer/index.android.test.js
|
mobile/src/FileViewer/index.android.test.js
|
import React from 'react';
import { shallow } from 'enzyme';
import { Image } from 'react-native';
import Pdf from 'react-native-pdf';
import FileViewer from './index.android';
describe(__filename, () => {
it('renders correctly', () => {
const path = '/path/to/file/to/view';
const wrapper = shallow(<FileViewer path={path} />);
expect(wrapper.find(Pdf)).toHaveLength(1);
expect(wrapper.find(Pdf)).toHaveProp('source', {
uri: path,
});
});
it('renders an Image when fileType is `png`', () => {
const path = '/path/to/file/to/view';
const fileType = 'png';
const wrapper = shallow(<FileViewer path={path} fileType={fileType} />);
expect(wrapper.find(Image)).toHaveLength(1);
expect(wrapper.find(Image)).toHaveProp('source', {
uri: `file://${path}`,
});
});
it('renders an Image when fileType is `jpg`', () => {
const path = '/path/to/file/to/view';
const fileType = 'jpg';
const wrapper = shallow(<FileViewer path={path} fileType={fileType} />);
expect(wrapper.find(Image)).toHaveLength(1);
expect(wrapper.find(Image)).toHaveProp('source', {
uri: `file://${path}`,
});
});
});
|
JavaScript
| 0.000003 |
@@ -65,17 +65,11 @@
ort
-%7B Image %7D
+Pdf
fro
@@ -83,16 +83,20 @@
t-native
+-pdf
';%0Aimpor
@@ -90,34 +90,40 @@
e-pdf';%0Aimport P
-df
+hotoView
from 'react-nat
@@ -127,18 +127,25 @@
native-p
-df
+hoto-view
';%0A%0Aimpo
@@ -487,37 +487,41 @@
it('renders an
-Image
+PhotoView
when fileType i
@@ -702,37 +702,41 @@
ct(wrapper.find(
-Image
+PhotoView
)).toHaveLength(
@@ -755,37 +755,41 @@
ct(wrapper.find(
-Image
+PhotoView
)).toHaveProp('s
@@ -859,21 +859,25 @@
ders an
-Image
+PhotoView
when fi
@@ -1066,37 +1066,41 @@
ct(wrapper.find(
-Image
+PhotoView
)).toHaveLength(
@@ -1131,13 +1131,17 @@
ind(
-Image
+PhotoView
)).t
|
fca1a4e61dcf0300dcbe17f805ee0ef0b537a584
|
Update TOC_generator.js
|
TOC_generator.js
|
TOC_generator.js
|
document.addEventListener('DOMContentLoaded', function() {
TableOfContents();
}
);
function TableOfContents(container, output) {
var output = output || '#toc';
// Get all elements with class: section or subsection
idfromclass = document.querySelectorAll('.section, .subsection');
// Create the list element:
var list = document.createElement('ul');
// Iterate through all found elements
for(var i = 0; i < idfromclass.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
var id = idfromclass[i].id
// Replace - in id with whitespace
var titleText = id.replace(/-/gi, " ");
// Add text to list element
item.appendChild(document.createTextNode(titleText));
// Add subsection classes
if(idfromclass[i].className == "section") { item.className = "section"; }
if(idfromclass[i].className == "subsection") { item.className = "subsection"; }
// Add it to the list:
list.appendChild(item);
}
// Return generated HTML to toc div in slide
document.querySelector(output).innerHTML = list.innerHTML;
// Generate instruction message if no classes are defined
if (idfromclass.length == 0) { document.querySelector(output).innerHTML = "Add {.section} or {.subsection} to slide name to generate TOC"; }
};
|
JavaScript
| 0 |
@@ -874,18 +874,16 @@
on class
-es
%0A
@@ -888,175 +888,48 @@
i
-f(idfromclass%5Bi%5D.className == %22section%22) %7B item.className = %22section%22; %7D %0A if(idfromclass%5Bi%5D.className == %22subsection%22) %7B item.className = %22subsection%22; %7D
+tem.className = idfromclass%5Bi%5D.className
%0A
@@ -1313,8 +1313,9 @@
%7D %0A%0A%7D;
+%0A
|
b19976cb87983b637e4818d9156998cc08585e99
|
use unrounded level on missing product
|
src/thresholds.service.js
|
src/thresholds.service.js
|
// TODO: replace with Array#find ponyfill
const find = (list, match) => {
for (let i = 0; i < list.length; i++) {
if (match(list[i])) {
return list[i]
}
}
return undefined
}
const isVersion = (version, item) => item.version === version
const isId = (id, item) => item._id === id
// Zones config
const zonesPlan = {
min: 0,
reOrder: 3,
max: 6
}
class ThresholdsService {
constructor ($q, smartId, lgasService, statesService) {
this.$q = $q
this.smartId = smartId
this.lgasService = lgasService
this.statesService = statesService
}
// For zones the thresholds are based on the state store required allocation for
// the week, that information is passed as an optional param (`requiredStateStoresAllocation`).
// That param is only used for zones.
calculateThresholds (location, stockCount, products, requiredStateStoresAllocation = {}) {
if (!location || !location.allocations || !location.plans || !location.level) {
return
}
if (!stockCount || !stockCount.allocations || !stockCount.allocations.version ||
!stockCount.plans || !stockCount.plans.version) {
return
}
if (!products || !products.length) {
return
}
const allocation = find(location.allocations, isVersion.bind(null, stockCount.allocations.version))
if (!(allocation && allocation.weeklyLevels)) {
return
}
const weeklyLevels = allocation.weeklyLevels
let weeksOfStock = zonesPlan
if (location.level !== 'zone') {
const plan = find(location.plans, isVersion.bind(null, stockCount.plans.version))
if (!(plan && plan.weeksOfStock)) {
return
}
weeksOfStock = plan.weeksOfStock
}
let thresholds = Object.keys(weeklyLevels).reduce((index, productId) => {
index[productId] = Object.keys(weeksOfStock).reduce((productThresholds, threshold) => {
const level = weeklyLevels[productId] * weeksOfStock[threshold]
const product = find(products, isId.bind(null, productId))
if (!product || !product.presentation) {
return productThresholds
}
// TODO: product presentations should be ints, not strings
const presentation = parseInt(product.presentation, 10)
const roundedLevel = Math.ceil(level / presentation) * presentation
productThresholds[threshold] = roundedLevel
if (location.level === 'zone' && requiredStateStoresAllocation[productId]) {
productThresholds[threshold] += requiredStateStoresAllocation[productId]
}
return productThresholds
}, {})
if (location.targetPopulation) {
index[productId].targetPopulation = location.targetPopulation[productId]
}
return index
}, {})
return thresholds
}
getThresholdsFor (stockCounts, products) {
// TODO: make it work for zones too.
// For making it work with zones, we need to take into account the amount of stock
// to be allocated to the zone state stores in a particular week
const locationIdPattern = 'zone:?state:?lga'
let index = {}
let promises = {}
index = stockCounts.reduce((index, stockCount) => {
let scLocation = stockCount.location
if (!scLocation) {
return index
}
const id = this.smartId.idify(scLocation, locationIdPattern)
const allocations = stockCount.allocations || { version: 1 }
const plans = stockCount.plans || { version: 1 }
index[id] = angular.merge({}, { allocations: allocations, plans: plans })
if (scLocation.lga) {
if (!promises.lga) {
promises.lga = this.lgasService.list()
}
index[id].type = 'lga'
} else if (scLocation.state) {
if (!promises.state) {
promises.state = this.statesService.list()
}
index[id].type = 'state'
}
return index
}, {})
const addThresholds = (promisesRes) => {
Object.keys(index).forEach((key) => {
const item = index[key]
const location = find(promisesRes[item.type], isId.bind(null, key))
item.thresholds = this.calculateThresholds(location, item, products)
delete item.type
})
return index
}
return this.$q.all(promises)
.then(addThresholds)
}
}
ThresholdsService.$inject = ['$q', 'smartId', 'lgasService', 'statesService']
export default ThresholdsService
|
JavaScript
| 0.00012 |
@@ -2038,17 +2038,16 @@
if (
-!
product
%7C%7C !
@@ -2042,20 +2042,19 @@
product
-%7C%7C !
+&&
product.
@@ -2075,51 +2075,8 @@
%7B%0A
- return productThresholds%0A %7D%0A
@@ -2138,32 +2138,34 @@
strings%0A
+
const presentati
@@ -2204,25 +2204,25 @@
on, 10)%0A
-%0A
+
const ro
@@ -2209,24 +2209,25 @@
0)%0A
+
const rounde
@@ -2282,32 +2282,34 @@
ntation%0A
+
productThreshold
@@ -2335,16 +2335,90 @@
dedLevel
+%0A %7D else %7B%0A productThresholds%5Bthreshold%5D = level%0A %7D
%0A%0A
|
0b903a4a8f0f20a6d7cd6d5c09cfb127d36e4544
|
Update mentor.js
|
WebRTC/mentor.js
|
WebRTC/mentor.js
|
var opts = {localCamBox:null, remoteCamBox:null, screenBox:null};
opts.localCamBox = document.getElementById("localCamBox");
opts.remoteCamBox;
opts.screenBox = document.getElementById("screenBox");
var helpQueue = document.getElementById("helpQueue");
var nameField = document.getElementById("nameField");
var firstPhase = document.getElementById("firstPhase");
var firstPhaseText = document.getElementById("firstPhaseText");
var secondPhase = document.getElementById("secondPhase");
var fullScreenButton = document.getElementById("screenFull");
var socket = io();
var webrtc;
fullScreenButton.onclick = function() {
var myVideo = opts.screenBox.getElementsByTagName('video');
if (myVideo) {
console.log(myVideo);
var elem = myVideo[0];
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
}
}
/*
This function renders the ninja queue that this mentor is handling.
At the moment, this is a simple array of names. This should change in a future iteration to include ids for those ninjas for guaranteed unique identification
*/
function renderBody(queue) {
var div = helpQueue;
div.innerHTML = '';
if (queue) {
$(firstPhaseText).text("There are " + queue.length + " ninjas waiting for help");
queue.forEach(function(entry) {
var b = document.createElement("div");
$(b).addClass("btn btn-default btn-block input-sm");
$(b).text(entry.name);
b.onclick = function() {
socket.emit('answerRequest', {ninja: entry});
$(firstPhase).hide();
$(secondPhase).show();
}
div.appendChild(b);
});
}
}
/* Function to handle new queue data.
The argument should be an object with the entire new queue located in the data.queue field
*/
function handleQueueUpdate(data) {
console.log(data);
renderBody(data.queue);
}
/* Function to handle the changing of room.
The data should include fields defining the name of the room and the name of ninja who will be joining
*/
function handleRoomChange(data) {
console.log('Changing to room: ' + data.room);
setRoom(data.room);
$('#ninjaName').text(data.ninja);
$(opts.localCamBox).empty();
$(chatWindow).empty();
$(opts.screenBox).empty();
webrtc.startLocalVideo();
}
/*
Function to handle the receiving of ice server info.
This the data packet should be exactly what is returned by xirsys concerning ICE connection details. Hence, all the data will be in the data.d field.
*/
function handleIceServers(data) {
console.log(data);
console.log(data.d);
webrtc = webrtcInit(data.d, opts, true);
console.log(webrtc);
}
/*
This function should handle the event of the ninja disconnecting from the system during a session.
*/
function handleNinjaDisconnect(data) {
webrtc.stopLocalVideo();
alert("The ninja you were communicating with left");
$(secondPhase).hide();
$(firstPhase).show();
}
socket.on('queueUpdate', handleQueueUpdate);
socket.on('changeRoom', handleRoomChange);
socket.on('iceServers', handleIceServers);
socket.on('otherDisconnect', handleNinjaDisconnect);
$(firstPhase).show();
$(secondPhase).hide();
$(nameField).text(getParameterByName('user'));
$('#collapseTwo').collapse("hide");
socket.emit('iceRequest', {mentor : getParameterByName('user')});
|
JavaScript
| 0 |
@@ -2344,36 +2344,8 @@
();%0A
-%09$(opts.screenBox).empty();%0A
%09web
@@ -3378,9 +3378,8 @@
er')%7D);%0A
-%0A
|
516c7725ccb84b7930ebcc6fbe2c116eb912c0af
|
add documentation to textfield.js
|
src/ui/views/textfield.js
|
src/ui/views/textfield.js
|
M.TextfieldView = M.View.extend({
_type: 'M.TextfieldView',
label: null,
type: 'search',
placeholder: null,
_template: _.tmpl(M.TemplateManager.get('M.TextfieldView')),
_assignTemplateValues: function() {
M.View.prototype._assignTemplateValues.apply(this);
this._addLabelToTemplateValues();
this._addTypeToTemplateValues();
this._addPlaceholderToTemplateValues();
this._addIconToTemplateValues();
},
_addLabelToTemplateValues: function() {
this._templateValues.label = this._getInternationalizedTemplateValue(this.label);
},
_addPlaceholderToTemplateValues: function() {
this._templateValues.placeholder = this._getInternationalizedTemplateValue(this.placeholder);
},
_addTypeToTemplateValues: function() {
this._templateValues.type = this.type;
},
_addIconToTemplateValues: function() {
this._templateValues.icon = this.icon || '';
},
initialize: function() {
M.View.prototype.initialize.apply(this);
},
_attachToDom: function() {
return YES;
}
}).implements([M.IconBackground]);
|
JavaScript
| 0 |
@@ -1,132 +1,1224 @@
-M.TextfieldView = M.View.extend(%7B%0A%0A _type: 'M.TextfieldView',%0A%0A label: null,%0A%0A type: 'search',%0A%0A placeholder: null,%0A
+/**%0A *%0A * @type %7BM%7C*%7D%0A *%0A * A input field.%0A *%0A */%0AM.TextfieldView = M.View.extend(%7B%0A%0A /**%0A * The type of the input.%0A * @private%0A */%0A _type: 'M.TextfieldView',%0A%0A /**%0A * The label of the input.%0A */%0A label: null,%0A%0A /**%0A * The type of the input. Default is search to have the cancel button%0A */%0A type: 'search',%0A%0A /**%0A * HTML Placeholder%0A */%0A placeholder: null,%0A%0A /**%0A * String - The icon for a Textfieldview. Use a icon from font-awesome. Default is the icon on the left. give the parent div a class right and it will be displayed on the right%0A * @example%0A *%0A * example1: M.TextfieldView.extend(%7B%0A grid: 'col-xs-12',%0A label: 'Label',%0A value: '',%0A icon: 'fa-rocket',%0A placeholder: 'Rocket'%0A %7D),%0A%0A backgroundRightTextfieldExample: M.TextfieldView.extend(%7B%0A grid: 'col-xs-12',%0A label: 'Label',%0A value: '',%0A cssClass: 'right',%0A icon: 'fa-dot-circle-o',%0A placeholder: 'Dot'%0A %7D),%0A *%0A */%0A icon: null,%0A%0A /**%0A * the template of the input%0A */
%0A
@@ -1276,24 +1276,75 @@
ldView')),%0A%0A
+ /**%0A * Add all the template values%0A */%0A
_assignT
|
2767523c95d191ce4847d99be4df3961196979c9
|
Change color to yellow (#51)
|
stylish.js
|
stylish.js
|
import path from 'path';
import pathIsAbsolute from 'path-is-absolute';
import chalk from 'chalk';
import logSymbols from 'log-symbols';
import table from 'text-table';
import isNumber from 'lodash.isnumber';
let currFile;
let currTable = [];
let filenames = [];
let options;
let optionsRead = false;
function resetState() {
currFile = undefined;
currTable = [];
filenames = [];
options = undefined;
optionsRead = false;
}
function createSummary(errs, warns, total, maxErrors, maxWarnings) {
if (total === 0) {
return 'No violations';
}
let output = '';
if (errs > 0) {
output += ` ${logSymbols.error} ${errs} ${errs > 1 ? 'errors' : 'error'}`;
if (isNumber(maxErrors)) {
output += ` (Max Errors: ${maxErrors})`;
}
output += '\n';
}
if (warns > 0) {
output += ` ${logSymbols.warning} ${warns} ${warns > 1 ? 'warnings' : 'warning'}`;
if (isNumber(maxWarnings)) {
output += ` (Max Warnings: ${maxWarnings})`;
}
output += '\n';
}
return output;
}
function doneHandler(kill) {
const errs = this.cache.errs.length;
const warns = this.cache.warnings.length;
const total = errs + warns;
const formattedMessage = `${table(currTable)
.split('\n')
.map((msg, i) => (filenames[i] ? `\n${filenames[i]}\n${msg}` : msg))
.join('\n')}\n\n`;
this.cache.msg = `${formattedMessage}${createSummary(errs, warns, total, this.config.maxErrors, this.config.maxWarnings)}`;
if (kill === 'kill') {
this.cache.msg += '\nStylint: Over Error or Warning Limit.';
} else if (total === 0) {
this.cache.msg = '';
}
resetState();
return this.done();
}
export default function (msg, done, kill) {
if (done === 'done') {
return doneHandler.call(this, kill);
}
if (!optionsRead) {
optionsRead = true;
const { absolutePath, verbose } = (this.config.reporterOptions || {});
options = { absolutePath, verbose };
}
const isWarning = this.state.severity === 'Warning';
if (currFile !== this.cache.file) {
currFile = this.cache.file;
let filename;
if (options.absolutePath) {
filename = pathIsAbsolute(currFile) ? currFile : path.resolve(currFile);
} else {
filename = pathIsAbsolute(currFile) ? path.relative(process.cwd(), currFile) : currFile;
}
filenames[currTable.length] = chalk.underline(filename);
}
const column = isNumber(this.cache.col) ? this.cache.col : -1;
currTable.push([
'',
chalk.gray(`line ${this.cache.lineNo}`),
chalk.gray(column > 0 ? `col ${column}` : '-'),
isWarning ? chalk.blue(msg) : chalk.red(msg),
options.verbose ? chalk.gray(this.cache.origLine.trim()) : '',
]);
return '';
}
|
JavaScript
| 0.000218 |
@@ -2583,12 +2583,14 @@
alk.
-blue
+yellow
(msg
|
2ce580c4337f6c5d49f5bc754a75050d728cd959
|
reset scrollbar upon ajaxify load
|
public/scripts/ajaxify.js
|
public/scripts/ajaxify.js
|
define(['jquery', 'inheritance', 'throbber', 'bind', 'domReady!'], function($, inheritance, throbber) {
var Throb = Class.extend({
init: function (throbber, brand) {
var that = this;
this.throbber = $(throbber);
this.brand = $(brand);
this.throb = new Throbber({
color: '#B16848',
size: 28,
fade: 1500,
rotationspeed: 10,
lines: 10,
strokewidth: 2.4,
}).appendTo(this.throbber.get(0));
this.active = 0;
$('body').ajaxSend(function () {
if (that.active == 0) {
that.start();
}
that.active++;
});
$('body').ajaxComplete(function () {
that.active--;
setTimeout(function () {
if (that.active == 0) {
that.stop();
}
}, 500);
});
},
stop: function () {
this.throbber.hide();
this.brand.show();
this.throb.start();
},
start: function () {
this.throbber.show();
this.brand.hide();
this.throb.start();
}
});
var instance = null;
/**
* This one listens to click events and loads the href in the content div
* instead of reloading the full page.
*/
var Ajaxify = Class.extend({
init: function () {
if (instance !== null) {
throw Error('Only one instance of Ajaxify allowed!');
}
var that = this;
this.throb = new Throb('.throbber', '.brand');
this.contents = ['#content', '#right'];
if ($(this.contents[0]).length == 0) {
return;
}
this.selector = '#top, #queue, #right, #content, #footer';
$(window).bind('hashchange', function (event) {
var href = that.getHref();
if (href !== null) {
that.loadPage(href);
}
});
$('body').bind('loadFinish', function () {
var href = that.getHref();
if (href === null) {
that.setPage('/library');
} else {
$(window).trigger('hashchange');
}
});
},
getHref: function () {
var href = document.location.hash.substring(1);
if (typeof href == 'undefined' || href === '') {
href = null;
}
return href;
},
internalInit: function () {
this.load(this.selector);
},
load: function (element) {
var that = this;
$(element).find('a')
.unbind('click.ajaxify')
.bind('click.ajaxify', function (event) {
var href = $(this).attr('href');
if (!event.ctrlKey && that.isRelative(href)) {
that.setPage(href);
} else {
// open external links and ctrl-click in new window/tab
window.open(href, "_blank");
}
// continue propagation if the link has said attribute
return $(this).is("[data-ajaxify=continue]");
});
$(element).trigger('ajaxifyInit');
},
loadPage: function (href) {
var that = this;
that.disableElements(that.contents.join(','));
$.ajax(href, {
success: function (data, textStatus, xhr) {
that.setPageInDom(data);
},
error: function (xhr) {
$(that.contents[0]).html(xhr.responseText);
that.enableElements(that.contents.join(','));
},
});
},
setPageInDom: function (data) {
var html = $(data);
document.title = $.trim(html.find("#title").text());
for (var index in this.contents) {
var content = this.contents[index];
$(content).html(html.find(content + ' > *'));
this.enableElements(content);
}
this.internalInit();
},
disableElements: function (element) {
$(element).addClass('ajaxify-disabled');
$(element).find("input, textarea, select").attr("disabled", "disabled");
$(element).find("*").bind(
'click.ajaxify_disabled ' +
'dblclick.ajaxify_disabled ' +
'dragstart.ajaxify_disabled',
function(event) {
return false;
}
).unbind('click.ajaxify');
},
enableElements: function (element) {
$(element).removeClass('ajaxify-disabled');
$(element).find("input, textarea, select").removeAttr("disabled");
$(element).find("*").unbind(
'click.ajaxify_disabled ' +
'dblclick.ajaxify_disabled ' +
'dragstart.ajaxify_disabled'
);
},
setPage: function (href) {
if (!this.isRelative(href)) {
href = this.getPathComponent(href);
}
if (document.location.hash.substring(1) == href) {
$(window).trigger('hashchange');
} else {
document.location.hash = href;
}
},
getPathComponent: function (href) {
return href.match(/^http(s)?:\/\/[^\/]+(.*)/)[2];
},
isRelative: function (href) {
return !/^http(s)?:\/\//.test(href);
},
});
return (function() {
if (instance === null) {
instance = new Ajaxify();
}
return instance;
})();
});
|
JavaScript
| 0 |
@@ -3610,16 +3610,68 @@
= this;%0A
+ var contents = that.contents.join(',');%0A
@@ -3691,37 +3691,32 @@
bleElements(
-that.
contents
.join(','));
@@ -3699,34 +3699,24 @@
nts(contents
-.join(',')
);%0A
@@ -3830,32 +3830,83 @@
ageInDom(data);%0A
+ that.enableElements(contents);%0A
@@ -4052,29 +4052,24 @@
lements(
-that.
contents
.join(',
@@ -4060,26 +4060,16 @@
contents
-.join(',')
);%0A
@@ -4427,35 +4427,30 @@
-this.enableElements(content
+$(content).scrollTop(0
);%0A
|
9a70d425ef8e6a95e83d50d7681ae0725d265d27
|
Update http status code when creating a new message
|
src/api/message/index.js
|
src/api/message/index.js
|
import presenter from '../../presenter/message';
import messageRepository from '../../repository/message';
import * as message from '../../services/message';
export async function list (req, res) {
res.send(
200,
presenter(
await message.list(
getRepositories()
)
)
);
}
export async function create (req, res) {
res.send(
200,
presenter(
await message.create(
getRepositories(),
req.body,
)
)
);
}
export async function detail (req, res) {
res.send(
200,
presenter(
await message.detail(
getRepositories(),
req.params.id,
)
)
);
}
export async function update (req, res) {
req.body.id = req.params.id; // eslint-disable-line no-param-reassign
res.send(
200,
presenter(
await message.update(
getRepositories(),
req.body,
)
)
);
}
export async function remove (req, res) {
res.send(
200,
presenter(
await message.remove(
getRepositories(),
req.params.id,
)
)
);
}
function getRepositories () {
return {
message: messageRepository(),
};
}
|
JavaScript
| 0 |
@@ -355,33 +355,33 @@
res.send(%0A 20
-0
+1
,%0A presenter(
|
6c3958a0bf8ca71a08d07d0df4fb73c703406a4c
|
remove unused import
|
src/app/models/player.js
|
src/app/models/player.js
|
import { logger } from "./../index"
import Game from "./game"
import Revision from "./revision"
import Universe from "./universe"
export default class Player {
constructor(client) {
this.client = client
}
async play() {
const result = await Universe.match(this.client)
if (result === false) {
this.client.send({ action: "wait" })
return
}
const { game, opponent } = result
const gameData = await game.serialize()
this.startGame(gameData)
opponent.player.startGame(gameData)
}
async revision(data) {
const game = await Game.where({ uuid: this.client.gameUUID }).fetch()
await Revision.create(game, data)
game.publishPosition()
}
startGame(data) {
this.client.gameUUID = data.uuid
this.client.redis.subscribe(data.uuid)
this.client.send({ action: "start", game: data })
}
}
|
JavaScript
| 0.000001 |
@@ -1,41 +1,4 @@
-import %7B logger %7D from %22./../index%22%0A%0A
impo
|
c28e59ed8baddc16cefa1784629569eeeda68046
|
add to input-object ability for self-nesting
|
src/type/custom/to-input-object.js
|
src/type/custom/to-input-object.js
|
/**
* Detailed explanation https://github.com/graphql/graphql-js/issues/312#issuecomment-196169994
*/
import { nodeInterface } from '../../schema/schema';
import {
GraphQLScalarType,
GraphQLInputObjectType,
GraphQLEnumType,
GraphQLID,
} from 'graphql';
function createInputObject(type) {
return new GraphQLInputObjectType({
name: `${type.name}Input`,
fields: filterFields(type.getFields(), (field) => (!field.noInputObject)), // eslint-disable-line
});
}
function filterFields(obj, filter) {
const result = {};
Object.keys(obj).forEach((key) => {
if (filter(obj[key])) {
result[key] = convertInputObjectField(obj[key]); // eslint-disable-line no-use-before-define
}
});
return result;
}
function convertInputObjectField(field) {
let fieldType = field.type;
const wrappers = [];
while (fieldType.ofType) {
wrappers.unshift(fieldType.constructor);
fieldType = fieldType.ofType;
}
if (
!(fieldType instanceof GraphQLInputObjectType ||
fieldType instanceof GraphQLScalarType ||
fieldType instanceof GraphQLEnumType
)
) {
fieldType = fieldType.getInterfaces().includes(nodeInterface)
? GraphQLID
: createInputObject(fieldType);
}
fieldType = wrappers.reduce((type, Wrapper) => new Wrapper(type), fieldType);
return { type: fieldType };
}
export default createInputObject;
|
JavaScript
| 0.000005 |
@@ -237,18 +237,17 @@
raphQLID
-,
%0A
+
%7D from '
@@ -257,16 +257,41 @@
phql';%0A%0A
+const cachedTypes = %7B%7D;%0A%0A
function
@@ -319,22 +319,129 @@
pe) %7B%0A
-return
+const typeName = %60$%7Btype.name%7DInput%60;%0A%0A if (!cachedTypes.hasOwnProperty(typeName)) %7B%0A cachedTypes%5BtypeName%5D =
new Gra
@@ -470,35 +470,28 @@
+
name:
-%60$%7B
type
-.n
+N
ame
-%7DInput%60
,%0A
+
@@ -497,16 +497,86 @@
fields:
+ %7B%7D%0A %7D);%0A cachedTypes%5BtypeName%5D._typeConfig.fields =%0A () =%3E
filterF
@@ -633,17 +633,17 @@
Object))
-,
+;
// esli
@@ -661,17 +661,48 @@
line%0A %7D
-)
+%0A%0A return cachedTypes%5BtypeName%5D
;%0A%7D%0A%0Afun
|
d5e73bd553c04d5cc3e53e425dfb96e51de674da
|
clean up
|
test/cf.js
|
test/cf.js
|
var should = require('should')
, maxminded = require('../maxminded.js')
, fs = require('fs')
, geofile = '/tmp/GeoLiteCity.dat'
;
if (fs.existsSync(geofile)) {
fs.unlinkSync(geofile);
}
describe('CloudFlare', function() {
describe('successful USA lookup', function() {
maxminded.init();
it("latitude should be 38", function(){
var header = {'cf-ipcountry':'US'};
var geo = maxminded.getLocation('66.6.44.4', header);
should.exist(geo);
geo.latitude.should.equal(38);
});
});
});
|
JavaScript
| 0.000001 |
@@ -479,16 +479,17 @@
eader);%0A
+%0A
@@ -527,20 +527,63 @@
-geo.latitude
+should.exist(geo.latitude);%0A geo%5B'latitude'%5D
.sho
|
363eb46cec29cbc74b6ff7538b785316335361a9
|
Fix an issue where .focus() is scrolling the page, same as in UrlUI
|
src/views/ProviderView/AuthView.js
|
src/views/ProviderView/AuthView.js
|
const LoaderView = require('./Loader')
const { h, Component } = require('preact')
class AuthBlock extends Component {
componentDidMount () {
this.connectButton.focus()
}
render () {
return <div class="uppy-Provider-auth">
<div class="uppy-Provider-authIcon">{this.props.pluginIcon()}</div>
<h1 class="uppy-Provider-authTitle">Please authenticate with <span class="uppy-Provider-authTitleName">{this.props.pluginName}</span><br /> to select files</h1>
<button
type="button"
class="uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Provider-authBtn"
onclick={this.props.handleAuth}
ref={(el) => { this.connectButton = el }}
>
Connect to {this.props.pluginName}
</button>
{this.props.demo &&
<button class="uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Provider-authBtn" onclick={this.props.handleDemoAuth}>Proceed with Demo Account</button>
}
</div>
}
}
class AuthView extends Component {
componentDidMount () {
this.props.checkAuth()
}
render () {
return (
<div style={{ height: '100%' }}>
{this.props.checkAuthInProgress
? <LoaderView />
: <AuthBlock {...this.props} />
}
</div>
)
}
}
module.exports = AuthView
|
JavaScript
| 0.000144 |
@@ -145,33 +145,93 @@
-this.connectButton.focus(
+setTimeout(() =%3E %7B%0A this.connectButton.focus(%7B preventScroll: true %7D)%0A %7D, 150
)%0A
|
b6ee9e5bede3b96a88a86c3d4f016b57897f1d71
|
Add a View with flex around the data table header and rows, so that it fits better within the Paper component
|
src/widgets/DataTable/DataTable.js
|
src/widgets/DataTable/DataTable.js
|
/* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import PropTypes from 'prop-types';
import React, { useMemo, useRef, useCallback } from 'react';
import { StyleSheet, VirtualizedList, VirtualizedListPropTypes, Keyboard } from 'react-native';
import RefContext from './RefContext';
import { DATA_TABLE_DEFAULTS } from './constants';
import { KeyboardSpacing } from '../KeyboardSpacing';
/**
* Base DataTable component. Wrapper around VirtualizedList, providing
* a header component, scroll to top and focus features.
* All VirtualizedList props can be passed through, however renderItem
* is renamed renderRow.
*
* Managing focus and scrolling:
* Can manage focusing and auto-scrolling for editable cells through react context API.
*
* Four parameters are passed in through the refContext:
*
* - `getRefIndex` : Gets the ref index for an editable cell given the columnkey and row index.
* - `getCellRef` : Lazily creates a ref for a cell.
* - `focusNextCell` : Focus' the next editable cell. Call during onEditingSubmit.
* - `adjustToTop` : Scrolls so the focused row is at the top of the list.
*
* @param {Func} renderRow Renaming of VirtualizedList renderItem prop.
* @param {Func} renderHeader Function which should return a header component
* @param {Object} style Style Object for this component.
* @param {Object} data Array of data objects.
* @param {Object} columns Array of column objects.
*/
const DataTable = React.memo(
({ renderRow, renderHeader, style, data, columns, footerHeight, ...otherProps }) => {
// Reference to the virtualized list for scroll operations.
const virtualizedListRef = useRef();
// Array of column keys for determining ref indicies.
const editableColumnKeys = useMemo(
() =>
columns.reduce((columnKeys, column) => {
const { editable } = column;
if (editable) return [...columnKeys, column.key];
return columnKeys;
}, []),
[columns]
);
const numberOfEditableColumns = editableColumnKeys.length;
const numberOfRows = data.length;
const numberOfEditableCells = numberOfEditableColumns * numberOfRows;
// Array for each editable cell. Needs to be stable, but updates shouldn't cause re-renders.
const cellRefs = useRef(Array.from({ length: numberOfEditableCells }));
// Passes a cell it's ref index.
const getRefIndex = (rowIndex, columnKey) => {
const columnIndex = editableColumnKeys.findIndex(key => columnKey === key);
return rowIndex * numberOfEditableColumns + columnIndex;
};
// Callback for an editable cell. Lazily creating refs.
const getCellRef = refIndex => {
if (cellRefs.current[refIndex]) return cellRefs.current[refIndex];
const newRef = React.createRef();
cellRefs.current[refIndex] = newRef;
return newRef;
};
// Focuses the next editable cell in the list. On the last row, dismiss the keyboard.
const focusNextCell = refIndex => {
const lastRefIndex = numberOfEditableCells - 1;
if (refIndex === lastRefIndex) return Keyboard.dismiss();
const nextCellRef = (refIndex + 1) % numberOfEditableCells;
const cellRef = getCellRef(nextCellRef);
return cellRef.current && cellRef.current.focus();
};
// Adjusts the passed row to the top of the list.
const adjustToTop = useCallback(rowIndex => {
virtualizedListRef.current.scrollToIndex({ index: Math.max(0, rowIndex - 1) });
}, []);
// Contexts values. Functions passed to rows and editable cells to control focus/scrolling.
const contextValue = useMemo(
() => ({
getRefIndex,
getCellRef,
focusNextCell,
adjustToTop,
}),
[numberOfEditableCells]
);
const renderItem = useCallback(
rowItem => renderRow(rowItem, focusNextCell, getCellRef, adjustToTop),
[renderRow]
);
return (
<RefContext.Provider value={contextValue}>
{renderHeader && renderHeader()}
<VirtualizedList
ref={virtualizedListRef}
keyboardDismissMode="none"
data={data}
keyboardShouldPersistTaps="always"
style={style}
ListFooterComponent={<KeyboardSpacing />}
renderItem={renderItem}
{...otherProps}
/>
</RefContext.Provider>
);
}
);
const defaultStyles = StyleSheet.create({
virtualizedList: {
flex: 1,
},
});
DataTable.propTypes = {
...VirtualizedListPropTypes,
renderRow: PropTypes.func.isRequired,
renderHeader: PropTypes.func,
getItem: PropTypes.func,
getItemCount: PropTypes.func,
initialNumToRender: PropTypes.number,
removeClippedSubviews: PropTypes.bool,
windowSize: PropTypes.number,
style: PropTypes.object,
footerHeight: PropTypes.number,
columns: PropTypes.array,
};
DataTable.defaultProps = {
renderHeader: DATA_TABLE_DEFAULTS.RENDER_HEADER,
footerHeight: DATA_TABLE_DEFAULTS.FOOTER_HEIGHT,
style: defaultStyles.virtualizedList,
getItem: (items, index) => items[index],
getItemCount: items => items.length,
initialNumToRender: DATA_TABLE_DEFAULTS.INITIAL_NUM_TO_RENDER,
removeClippedSubviews: DATA_TABLE_DEFAULTS.REMOVE_CLIPPED_SUBVIEWS,
windowSize: DATA_TABLE_DEFAULTS.WINDOW_SIZE_MEDIUM,
columns: [],
};
export default DataTable;
|
JavaScript
| 0 |
@@ -210,16 +210,26 @@
import %7B
+%0A View,%0A
StyleSh
@@ -232,16 +232,18 @@
leSheet,
+%0A
Virtual
@@ -251,16 +251,18 @@
zedList,
+%0A
Virtual
@@ -279,16 +279,18 @@
opTypes,
+%0A
Keyboar
@@ -290,17 +290,18 @@
Keyboard
-
+,%0A
%7D from '
@@ -4066,16 +4066,53 @@
Value%7D%3E%0A
+ %3CView style=%7B%7B flex: 1 %7D%7D%3E%0A
@@ -4152,16 +4152,18 @@
+
%3CVirtual
@@ -4171,16 +4171,18 @@
zedList%0A
+
@@ -4210,32 +4210,34 @@
tRef%7D%0A
+
+
keyboardDismissM
@@ -4257,16 +4257,18 @@
+
data=%7Bda
@@ -4273,32 +4273,34 @@
data%7D%0A
+
+
keyboardShouldPe
@@ -4328,16 +4328,18 @@
+
style=%7Bs
@@ -4344,16 +4344,18 @@
%7Bstyle%7D%0A
+
@@ -4408,16 +4408,18 @@
+
renderIt
@@ -4434,16 +4434,18 @@
erItem%7D%0A
+
@@ -4470,17 +4470,35 @@
-/
+ /%3E%0A %3C/View
%3E%0A
|
771e1adf70fdaf85ca0323c38eb7bc0f612124a4
|
enable socket listening on townsperson view via role mixin
|
static/js/app/views/townsperson.js
|
static/js/app/views/townsperson.js
|
define([
"react",
"underscore"
],
function (
React,
_
) {
return React.createClass({
render: function() {
var tempStyle = {
width: "100px",
height: "100px"
};
return (
<div className="townsperson-container">
<img id="role-pic" style={{ width: tempStyle.width, height: tempStyle.height }} src={ this.props.currentPlayer.get('role').picture }></img>
<div id="role-name">{ this.props.currentPlayer.get('role').name }</div>
</div>
);
}
});
});
|
JavaScript
| 0 |
@@ -24,18 +24,24 @@
%22
-underscore
+views/role_mixin
%22%0A%5D,
@@ -67,17 +67,25 @@
ct,%0A
-_
+RoleMixin
%0A ) %7B
@@ -128,214 +128,106 @@
-render: function() %7B%0A var tempStyle = %7B%0A width: %22100px%22,%0A height: %22100px%22%0A %7D;%0A return (%0A %3Cdiv className=%22townsperson-container%22%3E
+mixins: %5BRoleMixin%5D,%0A%0A getInitialState: function() %7B%0A return this.DEFAULT_STATE;
%0A
@@ -231,26 +231,28 @@
-
+%7D,%0A%0A
%3Cimg i
@@ -247,277 +247,70 @@
- %3Cimg id=%22role-pic%22 style=%7B%7B width: tempStyle.width, height: tempStyle.height %7D%7D src=%7B this.props.currentPlayer.get('role').picture %7D%3E%3C/img%3E%0A %3Cdiv id=%22role-name%22%3E%7B this.props.currentPlayer.get('role').name %7D%3C/div%3E%0A %3C/div%3E%0A
+render: function() %7B%0A return this.getViewForRender(
);%0A
@@ -330,10 +330,8 @@
%7D);%0A%7D);%0A
-%0A%0A
|
b4812ff683182f1056a3c485ee53b0191a318707
|
Return the callback
|
index.android.js
|
index.android.js
|
'use strict'
var React = require('react-native');
var { NativeModules, requireNativeComponent } = React;
var MapMixins = {
setDirectionAnimated(mapRef, heading) {
NativeModules.MapboxGLManager.setDirectionAnimated(React.findNodeHandle(this.refs[mapRef]), heading);
},
setZoomLevelAnimated(mapRef, zoomLevel) {
NativeModules.MapboxGLManager.setZoomLevelAnimated(React.findNodeHandle(this.refs[mapRef]), zoomLevel);
},
setCenterCoordinateAnimated(mapRef, latitude, longitude) {
NativeModules.MapboxGLManager.setCenterCoordinateAnimated(React.findNodeHandle(this.refs[mapRef]), latitude, longitude);
},
setCenterCoordinateZoomLevelAnimated(mapRef, latitude, longitude, zoomLevel) {
NativeModules.MapboxGLManager.setCenterCoordinateZoomLevelAnimated(React.findNodeHandle(this.refs[mapRef]), latitude, longitude, zoomLevel);
},
addAnnotations(mapRef, annotations) {
NativeModules.MapboxGLManager.addAnnotations(React.findNodeHandle(this.refs[mapRef]), annotations);
},
selectAnnotationAnimated(mapRef, selectedIdentifier) {
NativeModules.MapboxGLManager.selectAnnotationAnimated(React.findNodeHandle(this.refs[mapRef]), selectedIdentifier);
},
removeAnnotation(mapRef, selectedIdentifier) {
NativeModules.MapboxGLManager.removeAnnotation(React.findNodeHandle(this.refs[mapRef]), selectedIdentifier);
},
removeAllAnnotations(mapRef) {
NativeModules.MapboxGLManager.removeAllAnnotations(React.findNodeHandle(this.refs[mapRef]));
},
setVisibleCoordinateBoundsAnimated(mapRef, latitudeSW, longitudeSW, latitudeNE, longitudeNE, paddingTop, paddingRight, paddingBottom, paddingLeft) {
NativeModules.MapboxGLManager.setVisibleCoordinateBoundsAnimated(React.findNodeHandle(this.refs[mapRef]), latitudeSW, longitudeSW, latitudeNE, longitudeNE, paddingTop, paddingRight, paddingBottom, paddingLeft);
},
setUserTrackingMode(mapRef, userTrackingMode) {
NativeModules.MapboxGLManager.setUserTrackingMode(React.findNodeHandle(this.refs[mapRef]), userTrackingMode);
},
setTilt(mapRef, tilt) {
NativeModules.MapboxGLManager.setTilt(React.findNodeHandle(this.refs[mapRef]), tilt);
},
getCenterCoordinateZoomLevel(mapRef, callback) {
NativeModules.MapboxGLManager.getCenterCoordinateZoomLevel(React.findNodeHandle(this.refs[mapRef]), callback);
},
getDirection(mapRef, callback) {;
NativeModules.MapboxGLManager.getDirection(React.findNodeHandle(this.refs[mapRef]), function(err){
console.log(err);
});
},
mapStyles: NativeModules.MapboxGLManager.mapStyles,
userTrackingMode: NativeModules.MapboxGLManager.userTrackingMode
};
var ReactMapView = requireNativeComponent('RCTMapbox', {
name: 'RCTMapbox',
propTypes: {
accessToken: React.PropTypes.string.isRequired,
attributionButtonIsHidden: React.PropTypes.bool,
logoIsHidden: React.PropTypes.bool,
annotations: React.PropTypes.arrayOf(React.PropTypes.shape({
title: React.PropTypes.string,
subtitle: React.PropTypes.string,
coordinates: React.PropTypes.array.isRequired,
alpha: React.PropTypes.number,
fillColor: React.PropTypes.string,
strokeColor: React.PropTypes.string,
strokeWidth: React.PropTypes.number
})),
centerCoordinate: React.PropTypes.shape({
latitude: React.PropTypes.number.isRequired,
longitude: React.PropTypes.number.isRequired
}),
centerCoordinateZoom: React.PropTypes.shape(),
debugActive: React.PropTypes.bool,
direction: React.PropTypes.number,
rotateEnabled: React.PropTypes.bool,
scrollEnabled: React.PropTypes.bool,
showsUserLocation: React.PropTypes.bool,
styleUrl: React.PropTypes.string,
userTrackingMode: React.PropTypes.number,
zoomEnabled: React.PropTypes.bool,
zoomLevel: React.PropTypes.number,
tilt: React.PropTypes.number,
compassIsHidden: React.PropTypes.bool,
onRegionChange: React.PropTypes.func,
onUserLocationChange: React.PropTypes.func,
// Fix for https://github.com/mapbox/react-native-mapbox-gl/issues/118
scaleY: React.PropTypes.number,
scaleX: React.PropTypes.number,
translateY: React.PropTypes.number,
translateX: React.PropTypes.number,
rotation: React.PropTypes.number,
// Fix for https://github.com/mapbox/react-native-mapbox-gl/issues/175
renderToHardwareTextureAndroid: React.PropTypes.bool,
onLayout: React.PropTypes.bool,
accessibilityLiveRegion: React.PropTypes.string,
accessibilityComponentType: React.PropTypes.string,
accessibilityLabel: React.PropTypes.string,
testID: React.PropTypes.string,
importantForAccessibility: React.PropTypes.string
},
defaultProps() {
return {
centerCoordinate: {
latitude: 0,
longitude: 0
},
debugActive: false,
direction: 0,
rotateEnabled: true,
scrollEnabled: true,
showsUserLocation: false,
styleUrl: NativeModules.MapboxGLManager.mapStyles.streets,
userTrackingMode: NativeModules.MapboxGLManager.userTrackingMode.none,
zoomEnabled: true,
zoomLevel: 0,
tilt: 0,
compassIsHidden: false
};
}
});
var ReactMapViewWrapper = React.createClass({
statics: {
Mixin: MapMixins
},
propTypes: {
onRegionChange: React.PropTypes.func,
onUserLocationChange: React.PropTypes.func
},
handleOnChange(event) {
if (this.props.onRegionChange) this.props.onRegionChange(event.nativeEvent.src);
},
handleUserLocation(event) {
if (this.props.onUserLocationChange) this.props.onUserLocationChange(event.nativeEvent.src);
},
render() {
return (
<ReactMapView
{...this.props}
onChange={this.handleOnChange}
onSelect={this.handleUserLocation} />
);
}
});
module.exports = ReactMapViewWrapper;
|
JavaScript
| 0.999999 |
@@ -2444,52 +2444,16 @@
%5D),
-function(err)%7B%0A console.log(err);%0A %7D
+callback
);%0A
|
4bf55d6fc4b79e461e63a89b4cfb3679c2e4d860
|
use $.popover() instead of $.tooltip()
|
public/javascripts/service/yobi.user.SignUp.js
|
public/javascripts/service/yobi.user.SignUp.js
|
/**
* @(#)yobi.user.SignUp.js 2013.04.02
*
* Copyright NHN Corporation.
* Released under the MIT license
*
* http://yobi.dev.naver.com/license
*/
(function(ns){
var oNS = $yobi.createNamespace(ns);
oNS.container[oNS.name] = function(){
var htVar = {};
var htElement = {};
/**
* initialize
*/
function _init(){
_initElement();
_initVar();
_initFormValidator();
_attachEvent();
}
/**
* initialize elements
*/
function _initElement(){
htElement.welInputPassword = $('#password');
htElement.welInputPassword2 = $('#retypedPassword');
htElement.welInputEmail = $('#email');
htElement.welInputLoginId = $('#loginId');
htElement.welInputLoginId.focus();
htElement.welForm = $("form[name=signup]");
}
/**
* initialize variables
*/
function _initVar(){
htVar.rxLoginId = /^[a-zA-Z0-9-]+([_.][a-zA-Z0-9-]+)*$/;
}
/**
* attach event
*/
function _attachEvent(){
htElement.welInputLoginId.focusout(_onBlurInputLoginId);
htElement.welInputEmail.focusout(_onBlurInputEmail);
htElement.welInputPassword.focusout(_onBlurInputPassword);
htElement.welInputPassword2.focusout(_onBlurInputPassword);
}
/**
* 아이디 입력란 벗어날 때 이벤트 핸들러
* 중복여부 즉시 확인
*/
function _onBlurInputLoginId(){
var welInput = $(this);
var sLoginId = $yobi.getTrim(welInput.val()).toLowerCase();
welInput.val(sLoginId);
if(_onValidateLoginId(sLoginId) === false){
showErrorMessage(welInput, Messages("validation.allowedCharsForLoginId"));
return false;
}
if(sLoginId != ""){
doesExists($(this), "/user/isExist/");
}
}
/**
* 이메일 입력란 벗어날 때 이벤트 핸들러
* 중복여부 즉시 확인
*/
function _onBlurInputEmail(){
var welInput = $(this);
if(welInput.val() !== ""){
doesExists(welInput, "/user/isEmailExist/");
}
}
/**
* 비밀번호 확인 입력란 벗어날 때 이벤트 핸들러
* 마지막 입력란이므로 전체 폼 유효성 검사
*/
function _onBlurInputPassword(){
htVar.oValidator._validateForm();
}
/**
* @param {Wrapped Element} welInput
* @param {String} sURL
*/
function doesExists(welInput, sURL){
if(sURL.substr(-1) != "/"){
sURL += "/";
}
$.ajax({
"url": sURL + welInput.val()
}).done(function(htData){
if(htData.isExist === true){
showErrorMessage(welInput, Messages("validation.duplicated"));
} else if (htData.isReserved == true) {
showErrorMessage(welInput, Messages("validation.reservedWord"));
} else {
hideErrorMessage(welInput);
}
});
}
/**
* initialize FormValidator
* @require validate.js
*/
function _initFormValidator(){
var aRules = [
{"name": 'loginId', "rules": 'required|callback_check_loginId'},
{"name": 'email', "rules": 'required|valid_email'},
{"name": 'password', "rules": 'required|min_length[4]'},
{"name": 'retypedPassword', "rules": 'required|matches[password]'}
];
htVar.oValidator = new FormValidator('signup', aRules, _onFormValidate);
htVar.oValidator.registerCallback('check_loginId', _onValidateLoginId)
// set error message
htVar.oValidator.setMessage('check_loginId', Messages("validation.allowedCharsForLoginId"));
htVar.oValidator.setMessage('required', Messages("validation.required"));
htVar.oValidator.setMessage('min_length', Messages("validation.tooShortPassword"));
htVar.oValidator.setMessage('matches', Messages("validation.passwordMismatch"));
htVar.oValidator.setMessage('valid_email', Messages("validation.invalidEmail"));
}
/**
* login id validation
* @param {String} sLoginId
* @return {Boolean}
*/
function _onValidateLoginId(sLoginId){
return htVar.rxLoginId.test(sLoginId);
}
/**
* on validate form
* @param {Array} aErrors
*/
function _onFormValidate(aErrors){
_clearTooltips();
// to avoid bootstrap bug
if (aErrors.length <= 0) {
return _clearTooltips();
}
var welTarget;
aErrors.forEach(function(htError){
welTarget = htElement.welForm.find("input[name=" + htError.name + "]");
if(welTarget){
showErrorMessage(welTarget, htError.message);
}
});
}
/**
* 폼 영역에 있는 jquery.tooltip 모두 제거하는 함수
*/
function _clearTooltips(){
try {
htElement.welForm.find("input").each(function(i, v){
$(v).tooltip("destroy");
});
} catch(e){}
}
/**
* Bootstrap toolTip function has some limitation.
* In this case, toolTip doesn't provide easy way to change title and contents.
* So, unfortunately I had to change data value in directly.
* @param {Wrapped Element} welInput
* @param {String} sMessage
*/
function showErrorMessage(welInput, sMessage){
welInput.tooltip({"trigger": "manual", "placement": "left"});
var oToolTip = welInput.data('tooltip');
oToolTip.options.placement = 'left';
oToolTip.options.trigger = 'manual';
oToolTip.options.title = sMessage;
oToolTip.options.content = sMessage;
welInput.tooltip('show');
}
function hideErrorMessage(welInput){
welInput.tooltip("hide");
try{
welInput.tooltip("destroy");
} catch(e){} // to avoid bootstrap bug
}
_init();
};
})("yobi.user.SignUp");
|
JavaScript
| 0.000002 |
@@ -5953,23 +5953,23 @@
elInput.
-tooltip
+popover
(%7B%22trigg
@@ -6049,23 +6049,23 @@
t.data('
-tooltip
+popover
');%0A
@@ -6164,59 +6164,8 @@
l';%0A
- oToolTip.options.title = sMessage;%0A
@@ -6233,23 +6233,23 @@
elInput.
-tooltip
+popover
('show')
@@ -6327,23 +6327,23 @@
elInput.
-tooltip
+popover
(%22hide%22)
@@ -6387,23 +6387,23 @@
elInput.
-tooltip
+popover
(%22destro
|
ecda9d5767fd6ca5fc6e8911c17aa5691bd1a3e9
|
rename to indicate what it is
|
tourney.js
|
tourney.js
|
var $ = require('interlude');
var Tournament = require('tournament');
function Id(t, id) {
$.extend(this, id); // Tournament style { s, r, m }
this.t = t; // add stage number - override if exists (from sub Tourney)
}
Id.prototype.toString = function () {
return "T" + this.t + " S" + this.s + " R" + this.r + " M" + this.m;
};
//------------------------------------------------------------------
// Setup and statics
//------------------------------------------------------------------
function Tourney(np, inst) {
this._inst = inst;
this.matches = inst.matches; // proxy reference
this.oldMatches = []; // stash matches from completed instances here
this._stage = 1;
this._oldRes = [];
// for determining when we can expect Tourney API
Object.defineProperty(this, 'hasStages', { value: true });
}
Tourney.inherit = function (Klass, Initial) {
Initial = Initial || Tourney;
Klass.prototype = Object.create(Initial.prototype);
var methods = {
_createNext: false,
_mustPropagate: false,
_proxyRes: false,
_updateRes: null
};
Object.keys(methods).forEach(function (fn) {
// Implement a default if not already implemented (when Initial is Tourney)
Klass.prototype[fn] = Initial.prototype[fn] || $.constant(methods[fn]);
});
Klass.configure = function (obj) {
// Preserve Tournament API for invalid and defaults
Tournament.configure(Klass, obj, Initial);
};
Klass.from = function (inst, numPlayers, opts) {
// Since Tourney instances have same interface, can reuse Tournament.from
var from = Tournament.from(Klass, inst, numPlayers, opts);
from._oldRes = inst.results();
return from;
};
// ignore inherited `sub` and `inherit` for now for sanity
};
Tourney.defaults = Tournament.defaults;
Tourney.invalid = Tournament.invalid;
Tourney.sub = function (name, init, Initial) {
// Preserve Tournament API. This ultimately calls Tourney.inherit
return Tournament.sub(name, init, Initial || Tourney);
};
//------------------------------------------------------------------
// Pure proxy methods
//------------------------------------------------------------------
Tourney.prototype.unscorable = function (id, score, allowPast) {
return this._inst.unscorable(id, score, allowPast);
};
Tourney.prototype.score = function (id, score) {
return this._inst.score(id, score);
};
Tourney.prototype.upcoming = function (playerId) {
return this._inst.upcoming(playerId);
};
Tourney.prototype.players = function (id) {
return this._inst.players(id);
};
Tourney.prototype.findMatch = function (id) {
return this._inst.findMatch(id);
};
Tourney.prototype.findMatches = function (id) {
return this._inst.findMatches(id);
};
//------------------------------------------------------------------
// Helpers for piping modules together
//------------------------------------------------------------------
Tourney.prototype.getName = function (depth) {
var names = [];
for (var inst = this._inst; inst ; inst = inst._inst) {
names.push(inst.name);
}
return names.slice(0, depth).join('::');
};
Tourney.prototype.isDone = function () {
// self-referential isDone for Tourney's (checking if subTourneys are done)
// but this eventually ends in a Tournament::isDone()
return this._inst.isDone() &&
!this._mustPropagate(this._stage, this._inst, this._opts);
};
Tourney.prototype.stageDone = function () {
return this._inst[this._inst.hasStages ? 'stageDone' : 'isDone']();
};
var formatCurrent = function (stage, ms) {
// prepare matches from a completed instance for oldMatches
// NB: if `ms` come from a Tourney, the stage `t` key will be overridden
// and will use the counter relative to this Tourney
return ms.map(function (m) {
var o = { id: new Id(stage, m.id), p: m.p.slice() };
if (m.m) {
o.m = m.m.slice();
}
return o;
});
};
Tourney.prototype.createNextStage = function () {
if (!this.stageDone()) {
throw new Error("cannot start next stage until current one is done");
}
if (this.isDone()) {
return false;
}
// extend current matches' ids with `t` = this._stage (overwriting if necessary)
var completedMatches = formatCurrent(this._stage, this.matches);
Array.prototype.push.apply(this.oldMatches, completedMatches);
// update results for players still in it
this._oldRes = this.results();
this._stage += 1;
// propagate createNext if we have a Tourney instance embedded
if (this._inst.hasStages && !this._inst.isDone()) {
this._inst.createNextStage();
this.matches = this._inst.matches; // update link
return true;
}
// and seal it down if all its stages were done
if (this._inst.hasStages) {
this._inst.complete();
}
// otherwise _createNext needs to handle progression
this._inst = this._createNext(this._stage, this._inst, this._opts);
this.matches = this._inst.matches;
return true;
};
Tourney.prototype.complete = function () {
if (!this.isDone()) {
throw new Error("cannot complete a tourney until it is done");
}
// last oldMatches extend
var completedMatches = formatCurrent(this._stage, this.matches);
Array.prototype.push.apply(this.oldMatches, completedMatches);
this.matches = [];
this.unscorable = $.constant("cannot score matches after completing a tourney");
this.score = function () {
console.error(this.unscorable());
return false;
};
};
//------------------------------------------------------------------
// Extra helpers - probably won't be included
//------------------------------------------------------------------
/*
Tourney.prototype.rounds = function (stage) {
return helper.partitionMatches(this.allMatches(), 'r', 't', stage);
};
Tourney.prototype.section = function (stage) {
return helper.partitionMatches(this.allMatches(), 's', 't', stage);
};
Tourney.prototype.stages = function (section) {
return helper.partitionMatches(this.allMatches(), 't', 's', section);
};
*/
//------------------------------------------------------------------
// Results
//
// If current instance does not report results for all players,
// we append knocked out players' results from their previous stage.
// By induction, all players always exist in `results`.
//------------------------------------------------------------------
// NB: same as Tournament.resultEntry but does not throw
var resultEntry = function (res, p) {
return $.firstBy(function (r) {
return r.seed === p;
}, res);
};
Tourney.prototype.results = function () {
var curr = this._inst.results();
if (this._proxyRes()) {
return curr;
}
var previous = this._oldRes;
var knockOut = previous.filter(function (r) {
// players not in current stage exist in previous results below
return !resultEntry(curr, r.seed);
});
var updater = this._updateRes.bind(this);
return curr.map(function (r) {
var old = resultEntry(previous, r.seed);
if (old) {
updater(r, old);
}
return r;
}).concat(knockOut);
};
//------------------------------------------------------------------
module.exports = Tourney;
|
JavaScript
| 0.000005 |
@@ -955,22 +955,23 @@
%0A%0A var
-method
+virtual
s = %7B%0A
@@ -1081,22 +1081,23 @@
ct.keys(
-method
+virtual
s).forEa
@@ -1257,22 +1257,23 @@
onstant(
-method
+virtual
s%5Bfn%5D);%0A
|
eb9f2a5858b40dfcd0b5479f19bf598aac91cd1b
|
Fix map drag will still cause map redraw
|
src/chart/map/MapView.js
|
src/chart/map/MapView.js
|
define(function (require) {
// var zrUtil = require('zrender/core/util');
var graphic = require('../../util/graphic');
var MapDraw = require('../../component/helper/MapDraw');
require('../../echarts').extendChartView({
type: 'map',
render: function (mapModel, ecModel, api, payload) {
// Not render if it is an toggleSelect action from self
if (payload && payload.type === 'mapToggleSelect'
&& payload.from === this.uid
) {
return;
}
var group = this.group;
group.removeAll();
// Not update map if it is an roam action from self
if (!(payload && payload.type === 'geoRoam'
&& payload.component === 'series'
&& payload.name === mapModel.name)) {
if (mapModel.needsDrawMap) {
var mapDraw = this._mapDraw || new MapDraw(api, true);
group.add(mapDraw.group);
mapDraw.draw(mapModel, ecModel, api, this, payload);
this._mapDraw = mapDraw;
}
else {
// Remove drawed map
this._mapDraw && this._mapDraw.remove();
this._mapDraw = null;
}
}
else {
var mapDraw = this._mapDraw;
mapDraw && group.add(mapDraw.group);
}
mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
&& this._renderSymbols(mapModel, ecModel, api);
},
remove: function () {
this._mapDraw && this._mapDraw.remove();
this._mapDraw = null;
this.group.removeAll();
},
_renderSymbols: function (mapModel, ecModel, api) {
var originalData = mapModel.originalData;
var group = this.group;
originalData.each('value', function (value, idx) {
if (isNaN(value)) {
return;
}
var layout = originalData.getItemLayout(idx);
if (!layout || !layout.point) {
// Not exists in map
return;
}
var point = layout.point;
var offset = layout.offset;
var circle = new graphic.Circle({
style: {
// Because the special of map draw.
// Which needs statistic of multiple series and draw on one map.
// And each series also need a symbol with legend color
//
// Layout and visual are put one the different data
fill: mapModel.getData().getVisual('color')
},
shape: {
cx: point[0] + offset * 9,
cy: point[1],
r: 3
},
silent: true,
z2: 10
});
// First data on the same region
if (!offset) {
var fullData = mapModel.mainSeries.getData();
var name = originalData.getName(idx);
var labelText = name;
var fullIndex = fullData.indexOfName(name);
var itemModel = originalData.getItemModel(idx);
var labelModel = itemModel.getModel('label.normal');
var hoverLabelModel = itemModel.getModel('label.emphasis');
var textStyleModel = labelModel.getModel('textStyle');
var hoverTextStyleModel = hoverLabelModel.getModel('textStyle');
var polygonGroups = fullData.getItemGraphicEl(fullIndex);
circle.setStyle({
textPosition: 'bottom'
});
var onEmphasis = function () {
circle.setStyle({
text: hoverLabelModel.get('show') ? labelText : '',
textFill: hoverTextStyleModel.getTextColor(),
textFont: hoverTextStyleModel.getFont()
});
};
var onNormal = function () {
circle.setStyle({
text: labelModel.get('show') ? labelText : '',
textFill: textStyleModel.getTextColor(),
textFont: textStyleModel.getFont()
});
};
polygonGroups.on('mouseover', onEmphasis)
.on('mouseout', onNormal)
.on('emphasis', onEmphasis)
.on('normal', onNormal);
onNormal();
}
group.add(circle);
});
}
});
});
|
JavaScript
| 0 |
@@ -768,16 +768,20 @@
omponent
+Type
=== 'se
@@ -813,20 +813,24 @@
payload.
-name
+seriesId
=== map
@@ -835,20 +835,18 @@
apModel.
-name
+id
)) %7B%0A%0A
|
7de97ef002db391d2dad4e360c6c3bcd272f907e
|
Use single-quoted strings
|
src/classes/WebSocket.js
|
src/classes/WebSocket.js
|
import logger from '../loggly/logger'
import {
APIError,
InternalServerError,
NotFoundAPIError
} from './APIError'
import ws from 'ws'
import { URL } from 'url'
import uid from 'uid-safe'
import Authentication from './Authentication'
import Permission from './Permission'
import Meta from './Meta'
const PRETTY_PRINT_SPACING = 2
const apiEvents = [
'rescueCreated',
'rescueUpdated',
'rescueDeleted',
'ratCreated',
'ratUpdated',
'ratDeleted',
'userCreated',
'userUpdated',
'userDeleted',
'shipCreated',
'shipUpdated',
'shipDeleted',
'connection'
]
const routes = {}
export default class WebSocket {
constructor (server, trafficManager) {
this.wss = new ws.Server({server})
this.traffic = trafficManager
this.wss.on('connection', async (client, req) => {
let url = new URL(`http://localhost:8082${req.url}`)
client.req = req
client.clientId = uid.sync(GLOBAL.WEBSOCKET_IDENTIFIER_ROUNDS)
client.subscriptions = []
let bearer = url.searchParams.get('bearer')
if (bearer) {
let {user, scope} = await Authentication.bearerAuthenticate(bearer)
if (user) {
client.user = user
client.scope = scope
}
}
this.onConnection(client)
client.on('message', (message) => {
try {
let request = JSON.parse(String(message))
this.onMessage(client, request)
} catch (ex) {
logger.info('Failed to parse incoming websocket message')
}
})
for (let event of apiEvents) {
process.on(event, (ctx, result, permissions) => {
this.onEvent.call(this, event, ctx, result, permissions)
})
}
process.on('apiBroadcast', (id, ctx, result) => {
this.onBroadcast.call(this, id, ctx, result)
})
})
}
async onConnection (client) {
let ctx = new Context(client, {})
let route = await WebSocket.getRoute('version', 'read')
let result = await route(ctx)
let meta = {
event: 'connection'
}
let rateLimit = this.traffic.validateRateLimit(ctx, false)
Object.assign(meta, {
'API-Version': 'v2.1',
'Rate-Limit-Limit': rateLimit.total,
'Rate-Limit-Remaining': rateLimit.remaining,
'Rate-Limit-Reset': this.traffic.nextResetDate
})
this.send(client, { result: result.data, meta: meta })
}
async onMessage (client, request) {
try {
let { result, meta } = await this.route(client, request)
if (!result.meta) {
result.meta = {}
}
Object.assign(result.meta, meta)
this.send(client, result)
} catch (ex) {
let error = ex
if ((error instanceof APIError) === false) {
error = new InternalServerError({})
}
this.send(client, Object.assign({"meta": request.meta}, error))
}
}
async route (client, request) {
let ctx = new Context(client, request)
let rateLimit = this.traffic.validateRateLimit(ctx)
let meta = Object.assign(request.meta || {}, {
'API-Version': 'v2.1',
'Rate-Limit-Limit': rateLimit.total,
'Rate-Limit-Remaining': rateLimit.remaining,
'Rate-Limit-Reset': this.traffic.nextResetDate
})
let [endpointName, methodName] = request.action || []
let route = WebSocket.getRoute(endpointName, methodName)
let result = await route(ctx)
return { result: result, meta: meta }
}
onBroadcast (id, ctx, result) {
let clients = [...this.socket.clients].filter((client) => {
return client.subscriptions.includes(id)
})
this.broadcast(clients, result)
}
onEvent (event, ctx, result, permissions = null) {
let clients = [...this.socket.clients].filter((client) => {
if (client.clientId !== ctx.client.clientId) {
return (!permissions || Permission.granted(permissions, client.user, client.scope))
}
return false
})
if (!result.meta) {
result.meta = {}
}
Object.assign(result.meta, { event })
this.broadcast(clients, result)
}
send (client, message) {
try {
if (process.env.NODE_ENV === 'production') {
client.send(JSON.stringify(message))
} else {
client.send(JSON.stringify(message, null, PRETTY_PRINT_SPACING))
}
} catch (ex) {
logger.info('Failed to send websocket message')
}
}
broadcast (clients, message) {
for (let client of clients) {
this.send(client, message)
}
}
static addRoute (endpointName, methodName, method) {
if (routes.hasOwnProperty(endpointName) === false) {
routes[endpointName] = {}
}
routes[endpointName][methodName] = method
}
static getRoute (endpointName, methodName) {
if (routes.hasOwnProperty(endpointName) === false || routes[endpointName].hasOwnProperty(methodName) === false) {
throw NotFoundAPIError({ parameter: 'action' })
}
return routes[endpointName][methodName]
}
}
export class Context {
constructor (client, request) {
this.inet = client.req.headers['X-Forwarded-for'] || client.req.connection.remoteAddress
this.client = client
this.state = {}
this.state.scope = client.scope
this.state.user = client.user
this.query = {}
Object.assign(this.query, request)
this.meta = new Meta()
Object.assign(this.meta, this.query)
this.data = request.data
delete this.query.data
delete this.query.meta
delete this.query.action
this.params = this.query
}
}
/**
* ESNext Decorator for routing this method for websocket requests
* @param endpointName The endpoint name to route websocket requests for
* @param methodName The method name to route websocket requests for
* @returns {Function} An ESNext decorator function
*/
export function websocket (endpointName, methodName) {
return function (target, name, descriptor) {
WebSocket.addRoute(endpointName, methodName, descriptor.value)
}
}
|
JavaScript
| 0.999323 |
@@ -2812,14 +2812,14 @@
gn(%7B
-%22
+'
meta
-%22
+'
: re
|
2953cc98b9c989d5e55154fd7b9fd9829cd280d2
|
Fix player move event name not updated in client
|
src/client/GameClient.js
|
src/client/GameClient.js
|
const io = require('socket.io-client')
const kbd = require('@dasilvacontin/keyboard')
const deepEqual = require('deep-equal')
const capitalize = require('capitalize')
const { PLAYER_EDGE, COIN_RADIUS } = require('../common/constants.js')
const { calculatePlayerAcceleration } = require('../common/utils.js')
const serverEventsNames = [
'connect', 'gameInit', 'serverPong',
'playerMoved', 'playerDisconnected',
'coinSpawned', 'coinCollected'
]
class GameClient {
constructor (roomId) {
this.roomId = roomId
this.socket = io()
this.myPlayerId = null
this.myInputs = {
LEFT_ARROW: false,
RIGHT_ARROW: false,
UP_ARROW: false,
DOWN_ARROW: false
}
this.players = {}
this.coins = {}
this.ping = Infinity
this.clockDiff = 0
serverEventsNames.forEach((serverEventName) => {
this.socket.on(
serverEventName,
this[`on${capitalize(serverEventName)}`].bind(this)
)
})
}
pingServer () {
this.pingMessageTimestamp = Date.now()
this.socket.emit('gamePing')
}
onConnect () {
this.socket.emit('joinGame', this.roomId)
this.pingServer()
}
onServerPong (serverNow) {
const now = Date.now()
this.ping = (now - this.pingMessageTimestamp) / 2
this.clockDiff = (serverNow + this.ping) - now
setTimeout(() => {
this.pingServer()
}, Math.max(200, this.ping))
}
onGameInit (myPlayerId, gameState) {
this.myPlayerId = myPlayerId
const { players, coins } = gameState
this.players = players
this.coins = coins
}
onPlayerMoved (player) {
this.players[player.id] = player
}
onCoinSpawned (coin) {
this.coins[coin.id] = coin
}
onCoinCollected (playerId, coinId) {
delete this.coins[coinId]
const player = this.players[playerId]
player.score++
}
onPlayerDisconnected (playerId) {
delete this.players[playerId]
}
updateInputs () {
const { myInputs } = this
const oldInputs = Object.assign({}, myInputs)
for (let key in myInputs) {
myInputs[key] = kbd.isKeyDown(kbd[key])
}
if (!deepEqual(myInputs, oldInputs)) {
this.socket.emit('move', myInputs)
// update our local player' inputs aproximately when
// the server takes them into account
const frozenInputs = Object.assign({}, myInputs)
setTimeout(() => {
const myPlayer = this.players[this.myPlayerId]
myPlayer.inputs = frozenInputs
calculatePlayerAcceleration(myPlayer)
}, this.ping)
}
}
logic () {
const now = Date.now()
this.updateInputs()
for (let playerId in this.players) {
const player = this.players[playerId]
const { x, y, vx, vy, ax, ay } = player
const delta = (now + this.clockDiff) - player.timestamp
const delta2 = Math.pow(delta, 2)
// dead reckoning
player.x = x + (vx * delta) + (ax * delta2 / 2)
player.y = y + (vy * delta) + (ay * delta2 / 2)
player.vx = vx + (ax * delta)
player.vy = vy + (ay * delta)
player.timestamp = now + this.clockDiff
}
}
render (canvas, ctx) {
ctx.fillStyle = 'white'
ctx.fillRect(0, 0, canvas.width, canvas.height)
// render coins
for (let coinId in this.coins) {
const coin = this.coins[coinId]
ctx.fillStyle = 'yellow'
ctx.beginPath()
ctx.arc(coin.x, coin.y, COIN_RADIUS, 0, 2 * Math.PI)
ctx.fill()
}
// render players
for (let playerId in this.players) {
const { color, x, y, score } = this.players[playerId]
ctx.save()
ctx.translate(x, y)
ctx.fillStyle = color
const HALF_EDGE = PLAYER_EDGE / 2
ctx.fillRect(-HALF_EDGE, -HALF_EDGE, PLAYER_EDGE, PLAYER_EDGE)
if (playerId === this.myPlayerId) {
ctx.strokeRect(-HALF_EDGE, -HALF_EDGE, PLAYER_EDGE, PLAYER_EDGE)
}
// render score inside players
ctx.fillStyle = 'white'
ctx.textAlign = 'center'
ctx.font = '20px Arial'
ctx.fillText(score, 0, 7)
ctx.restore()
}
// render `ping` and `clockDiff`
ctx.fillStyle = 'black'
ctx.textAlign = 'left'
ctx.font = '20px Arial'
ctx.fillText(`ping: ${this.ping}`, 15, 30)
ctx.fillText(`clockDiff: ${this.clockDiff}`, 15, 60)
}
}
module.exports = GameClient
|
JavaScript
| 0 |
@@ -2159,17 +2159,23 @@
t.emit('
-m
+playerM
ove', my
|
82cd2d41d1237cc412e10b8351e587aba8fb350b
|
Fix collapse animation
|
src/collapse/collapse.js
|
src/collapse/collapse.js
|
angular.module('ui.bootstrap.collapse', [])
.directive('uibCollapse', ['$animate', '$injector', function($animate, $injector) {
var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null;
return {
link: function(scope, element, attrs) {
function expand() {
element.removeClass('collapse')
.addClass('collapsing')
.attr('aria-expanded', true)
.attr('aria-hidden', false);
if ($animateCss) {
$animateCss(element, {
addClass: 'in',
easing: 'ease',
to: { height: element[0].scrollHeight + 'px' }
}).start().finally(expandDone);
} else {
$animate.addClass(element, 'in', {
to: { height: element[0].scrollHeight + 'px' }
}).then(expandDone);
}
}
function expandDone() {
element.removeClass('collapsing')
.addClass('collapse')
.css({height: 'auto'});
}
function collapse() {
if (!element.hasClass('collapse') && !element.hasClass('in')) {
return collapseDone();
}
element
// IMPORTANT: The height must be set before adding "collapsing" class.
// Otherwise, the browser attempts to animate from height 0 (in
// collapsing class) to the given height here.
.css({height: element[0].scrollHeight + 'px'})
// initially all panel collapse have the collapse class, this removal
// prevents the animation from jumping to collapsed state
.removeClass('collapse')
.addClass('collapsing')
.attr('aria-expanded', false)
.attr('aria-hidden', true);
if ($animateCss) {
$animateCss(element, {
removeClass: 'in',
to: {height: '0'}
}).start().finally(collapseDone);
} else {
$animate.removeClass(element, 'in', {
to: {height: '0'}
}).then(collapseDone);
}
}
function collapseDone() {
element.css({height: '0'}); // Required so that collapse works when animation is disabled
element.removeClass('collapsing')
.addClass('collapse');
}
scope.$watch(attrs.uibCollapse, function(shouldCollapse) {
if (shouldCollapse) {
collapse();
} else {
expand();
}
});
}
};
}]);
/* Deprecated collapse below */
angular.module('ui.bootstrap.collapse')
.value('$collapseSuppressWarning', false)
.directive('collapse', ['$animate', '$injector', '$log', '$collapseSuppressWarning', function($animate, $injector, $log, $collapseSuppressWarning) {
var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null;
return {
link: function(scope, element, attrs) {
if (!$collapseSuppressWarning) {
$log.warn('collapse is now deprecated. Use uib-collapse instead.');
}
function expand() {
element.removeClass('collapse')
.addClass('collapsing')
.attr('aria-expanded', true)
.attr('aria-hidden', false);
if ($animateCss) {
$animateCss(element, {
addClass: 'in',
easing: 'ease',
to: { height: element[0].scrollHeight + 'px' }
}).start().done(expandDone);
} else {
$animate.addClass(element, 'in', {
to: { height: element[0].scrollHeight + 'px' }
}).then(expandDone);
}
}
function expandDone() {
element.removeClass('collapsing')
.addClass('collapse')
.css({height: 'auto'});
}
function collapse() {
if (!element.hasClass('collapse') && !element.hasClass('in')) {
return collapseDone();
}
element
// IMPORTANT: The height must be set before adding "collapsing" class.
// Otherwise, the browser attempts to animate from height 0 (in
// collapsing class) to the given height here.
.css({height: element[0].scrollHeight + 'px'})
// initially all panel collapse have the collapse class, this removal
// prevents the animation from jumping to collapsed state
.removeClass('collapse')
.addClass('collapsing')
.attr('aria-expanded', false)
.attr('aria-hidden', true);
if ($animateCss) {
$animateCss(element, {
removeClass: 'in',
to: {height: '0'}
}).start().done(collapseDone);
} else {
$animate.removeClass(element, 'in', {
to: {height: '0'}
}).then(collapseDone);
}
}
function collapseDone() {
element.css({height: '0'}); // Required so that collapse works when animation is disabled
element.removeClass('collapsing')
.addClass('collapse');
}
scope.$watch(attrs.collapse, function(shouldCollapse) {
if (shouldCollapse) {
collapse();
} else {
expand();
}
});
}
};
}]);
|
JavaScript
| 0 |
@@ -3361,38 +3361,8 @@
, %7B%0A
- addClass: 'in',%0A
@@ -3379,32 +3379,32 @@
easing: 'ease',%0A
+
to
@@ -3522,39 +3522,38 @@
$animate.a
-ddClass
+nimate
(element, 'in',
@@ -3538,36 +3538,34 @@
nimate(element,
-'in'
+%7B%7D
, %7B%0A
@@ -3557,38 +3557,32 @@
%7B%0A
- to: %7B
height: element
@@ -3596,34 +3596,32 @@
ollHeight + 'px'
- %7D
%0A %7D).
@@ -3760,32 +3760,35 @@
dClass('collapse
+ in
')%0A .
@@ -4446,32 +4446,35 @@
eClass('collapse
+ in
')%0A .
@@ -4647,41 +4647,8 @@
, %7B%0A
- removeClass: 'in',%0A
@@ -4754,35 +4754,31 @@
$animate.
-removeClass
+animate
(element, 'i
@@ -4767,36 +4767,34 @@
nimate(element,
-'in'
+%7B%7D
, %7B%0A
@@ -4787,37 +4787,32 @@
%7B%0A
-to: %7B
height: '0'%7D%0A
@@ -4798,33 +4798,32 @@
height: '0'
-%7D
%0A %7D).
|
6b7080d7f3f4cb6295e02c1f501613e45de7e10e
|
Remove debugging statements
|
src/common/cjs/regexp.js
|
src/common/cjs/regexp.js
|
const { against, when, otherwise, isString } = require('match-iz')
const { pipe, flow, aside, memo } = require('./fp')
const makeRegExpFromWildcardString = memo(str => {
if (!isString(str) || !str.length) {
throw new TypeError('Please pass a non-empty string')
}
return pipe(
str
.replace(rxConsecutiveWildcards(), '*')
.split('*')
.map(x => x.trim())
.map(escapeStringForRegExp),
aside(x => console.log(`1 aside = "${x}"`)),
against(
when(hasNoWildcards)(templateMatchExact),
when(hasNoWildcardAtStart)(flow(insertWildcards, templateMatchStart)),
when(hasNoWildcardAtEnd)(flow(insertWildcards, templateMatchEnd)),
otherwise(insertWildcards)
),
aside(x => console.log(`2 aside = "${x}"`)),
$ => new RegExp($)
)
})
//
// Helpers
//
const rxEscape = () => /[.*+?^${}()|[\]\\]/g
const rxConsecutiveWildcards = () => /\*{2,}/g
const hasNoWildcards = x => x.length === 1
const hasNoWildcardAtStart = x => x.at(0) !== ''
const hasNoWildcardAtEnd = x => x.at(-1) !== ''
const insertWildcards = x => x.join('(.*)')
const templateMatchExact = ([x]) => `^${x}$`
const templateMatchStart = x => `^${x}`
const templateMatchEnd = x => `${x}$`
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
function escapeStringForRegExp(str) {
if (!isString(str)) {
throw new TypeError('Please pass a string')
}
// $& means the whole matched string
return str.replace(rxEscape(), '\\$&')
}
module.exports = {
makeRegExpFromWildcardString,
escapeStringForRegExp
}
|
JavaScript
| 0.000032 |
@@ -83,15 +83,8 @@
low,
- aside,
mem
@@ -105,16 +105,16 @@
'./fp')%0A
+
%0Aconst m
@@ -411,58 +411,8 @@
),%0A%0A
- aside(x =%3E console.log(%601 aside = %22$%7Bx%7D%22%60)),%0A%0A
@@ -655,16 +655,16 @@
ds)%0A
+
),%0A%0A
@@ -663,58 +663,8 @@
),%0A%0A
- aside(x =%3E console.log(%602 aside = %22$%7Bx%7D%22%60)),%0A%0A
|
d8e7ca4634c752bc8773027f56b484ceb28d1358
|
Fix import
|
_js/main.js
|
_js/main.js
|
import '../_sass/_main.scss';
import pace from 'pace-progress';
import 'bootstrap';
import 'bootstrap-toggle';
import AOS from 'aos';
import editor from './editor';
import favourites from './favourites.js';
import styleNavbar from './style-navbar';
import styleJumbotrons from './style-jumbotrons';
import displayScrollBtns from './display-scroll-btns';
import apiStats from './api-stats';
import imageError from './image-error';
import imageCrop from './image-crop';
import anchorScroll from './anchor-scroll';
import progress from './progress';
import s3 from './s3';
import ps from './project-shuffle';
import featuredProjects from './featured-projects';
import search from './search';
import btnScroll from './btn-scroll';
import tabControl from './tab-control';
import hamburger from './hamburger';
import sidebar from './sidebar.js';
import csrfToken from './csrf-token';
import msg from './flash-messages';
// TODO export to own repo to be bundled within projects - add bootstrap as dependency
import viewer from './ui/components/viewer/viewer';
// Init pace-progress
pace.start()
// Init Bootstrap popovers and tooltips
$('[data-toggle="popover"]').popover();
$('[data-toggle="tooltip"]').tooltip();
// Init aos
AOS.init({ once: 'true' });
|
JavaScript
| 0.000002 |
@@ -1004,22 +1004,25 @@
%0Aimport
-viewer
+Interface
from '.
@@ -1043,22 +1043,25 @@
/viewer/
-viewer
+interface
';%0A%0A// I
|
7b2733bb217f18907ebc26abeabe7bc7e48c25e1
|
Document `destroy` and `destroySync`
|
src/component-helpers.js
|
src/component-helpers.js
|
import createElement from 'virtual-dom/create-element'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import refsStack from './refs-stack'
import {getScheduler} from './scheduler-assignment'
const componentsWithPendingUpdates = new WeakSet
let syncUpdatesInProgressCounter = 0
let syncDestructionsInProgressCounter = 0
// This function associates a component object with a DOM element by calling
// the components `render` method, assigning an `.element` property on the
// object and also returning the element.
//
// It also assigns a `virtualElement` property based on the return value of the
// `render` method. This will be used later by `performElementUpdate` to diff
// the new results of `render` with the previous results when updating the
// component's element.
//
// Finally, this function also associates the component with a `refs` object,
// which is populated with references to elements based on `ref` properties on
// nodes of the `virtual-dom` tree. Before calling into `virtual-dom` to create
// the DOM tree, it pushes this `refs` object to a shared stack so it can be
// accessed by hooks during the creation of individual elements.
export function initialize(component) {
component.refs = {}
component.virtualElement = component.render()
refsStack.push(component.refs)
component.element = createElement(component.virtualElement)
refsStack.pop()
return component.element
}
// This function receives a component that has already been associated with an
// element via a previous call to `initialize` and updates this element by
// calling `render` on the component.
//
// When called in normal circumstances, it uses the scheduler to defer this
// update until the next animation frame, and will only perform one update of a
// given component in a given frame. This means you can call `update`
// repeatedly in a given tick without causing redundant updates.
//
// If this function called during another synchronous update (for example, as a
// result of a call to `update` on a child component), the update is performed
// synchronously.
//
// Returns a promise that will resolve when the requested update has been
// completed.
export function update (component) {
if (syncUpdatesInProgressCounter > 0) {
updateSync(component)
return Promise.resolve()
}
let scheduler = getScheduler()
if (!componentsWithPendingUpdates.has(component)) {
componentsWithPendingUpdates.add(component)
scheduler.updateDocument(function () {
componentsWithPendingUpdates.delete(component)
updateSync(component)
})
}
return scheduler.getNextUpdatePromise()
}
// Synchronsly updates the DOM element associated with a component object. .
// This method assumes the presence of `.element` and `.virtualElement`
// properties on the component, which are assigned in the `initialize`
// function.
//
// It calls `render` on the component to obtain the desired state of the DOM,
// then `diff`s it with the previous state and `patch`es the element based on
// the resulting diff. During the patch operation, it pushes the component's
// `refs` object to a shared stack so that references to DOM elements can be
// updated.
//
// If `update` is called during the invocation of `updateSync`,
// the requests are processed synchronously as well. We track whether this is
// the case by incrementing and decrementing `syncUpdatesInProgressCounter`
// around the call.
//
// For now, etch does not allow the root tag of the `render` method to change
// between invocations, because we want to preserve a one-to-one relationship
// between component objects and DOM elements for simplicity.
export function updateSync (component) {
syncUpdatesInProgressCounter++
let oldVirtualElement = component.virtualElement
let oldDomNode = component.element
let newVirtualElement = component.render()
refsStack.push(component.refs)
let newDomNode = patch(component.element, diff(oldVirtualElement, newVirtualElement))
refsStack.pop()
component.virtualElement = newVirtualElement
if (newDomNode !== oldDomNode) {
throw new Error("etch does not support changing the root DOM node type of a component")
}
syncUpdatesInProgressCounter--
}
export function destroy (component) {
if (syncUpdatesInProgressCounter > 0 || syncDestructionsInProgressCounter > 0) {
destroySync(component)
return Promise.resolve()
}
let scheduler = getScheduler()
scheduler.updateDocument(function () {
destroySync(component)
})
return scheduler.getNextUpdatePromise()
}
export function destroySync (component) {
syncDestructionsInProgressCounter++
destroyChildComponents(component.virtualElement)
if (syncDestructionsInProgressCounter === 1) component.element.remove()
syncDestructionsInProgressCounter--
}
function destroyChildComponents(virtualNode) {
if (virtualNode.type === 'Widget') {
if (virtualNode.component && typeof virtualNode.component.destroy === 'function') {
virtualNode.component.destroy()
}
} else if (virtualNode.children) {
virtualNode.children.forEach(destroyChildComponents)
}
}
|
JavaScript
| 0 |
@@ -4222,24 +4222,547 @@
ounter--%0A%7D%0A%0A
+// Removes the component's associated element and calls %60destroy%60 on any child%0A// components. Normally, this function is asynchronous and will perform the%0A// destruction on the next animation frame. If called as the result of another%0A// update or destruction, it calls %60destroy%60 on child components synchronously.%0A// If called as the result of destroying a component higher in the DOM, the%0A// element is not removed to avoid redundant DOM manipulation. Returns a promise%0A// that resolves when the destruction is completed.%0A
export funct
@@ -5082,16 +5082,180 @@
se()%0A%7D%0A%0A
+// A synchronous version of %60destroy%60.%0A//%0A// Note that we track whether %60destroy%60 calls are in progress and only remove%0A// the element if we are not a nested call.%0A
export f
|
4bc765098e75c772ae95a0274922639cf6edca38
|
use flex in error msg component
|
src/components/ErrMsg.js
|
src/components/ErrMsg.js
|
import React from 'react';
import Radium from 'radium';
const style = {
wrapper: {
padding: '5px',
borderRadius: '3px',
backgroundColor: '#FFF6F6',
position: 'absolute',
width: '35%',
height: '8%',
margin: 'auto',
top: '20%',
right: '35%',
textAlign: 'center',
'@media (max-width: 48em)': {
left: '0',
width: '100%'
}
},
icon: {
fontSize: '1em'
},
title: {
color: '#912D2B',
fontWeight: 'bold',
marginTop: '5px'
},
msg: {
color: 'rgb(159, 58, 56)'
}
};
const ErrMsg = () => (
<div style={style.wrapper}>
<div style={style.title}>Error!!</div>
<p style={style.msg}>We are sorry but something went wrong, please try again later.</p>
</div>
);
export default Radium(ErrMsg);
|
JavaScript
| 0 |
@@ -87,306 +87,201 @@
-padding
+minHeight
: '5
-px
+0vh
',%0A
-borderRadius: '3px',%0A backgroundColor: '#FFF6F6',%0A position: 'absolute',%0A width: '35%25',%0A height: '8%25',%0A margin: 'auto',%0A top: '20%25',%0A right: '35%25',%0A textAlign: 'center',%0A '@media (max-width: 48em)': %7B%0A left: '0',%0A width: '100%25'%0A %7D
+display: 'flex',%0A justifyContent: 'center',%0A alignItems: 'center'%0A %7D,%0A box: %7B%0A borderRadius: '3px',%0A backgroundColor: '#FFF6F6',%0A padding: '15px'
%0A %7D,%0A
icon
@@ -280,12 +280,13 @@
,%0A
-icon
+title
: %7B%0A
@@ -304,28 +304,39 @@
e: '
-1em'%0A %7D,%0A title: %7B
+20px',%0A textAlign: 'center',
%0A
@@ -380,30 +380,8 @@
old'
-,%0A marginTop: '5px'
%0A %7D
@@ -482,16 +482,46 @@
apper%7D%3E%0A
+ %3Cdiv style=%7Bstyle.box%7D%3E%0A
%3Cdiv
@@ -550,17 +550,17 @@
rror
-!!
%3C/div%3E%0A
+
@@ -647,16 +647,27 @@
er.%3C/p%3E%0A
+ %3C/div%3E%0A
%3C/div%3E
|
9123a7e95777a35e95eb7b6808fa93d458eab224
|
Revert overflow scroll
|
src/components/Layout.js
|
src/components/Layout.js
|
import React from 'react'
import { ThemeProvider } from 'emotion-theming'
import Helmet from 'react-helmet'
import '../styles/reset'
import theme, * as palette from '../styles/themeDark'
import config from '../utils/siteConfig'
import Wrapper from '../components/Wrapper'
import Menu from '../components/Menu'
import { injectGlobal } from 'emotion'
injectGlobal`
body {
background: ${palette.BASE} !important;
color: ${palette.SECONDARY} !important;
}
h1,h2,h3,h4,h5,h6,a,strong {
color: ${palette.TERTIARY};
}
p {
color: ${palette.SECONDARY};
}
a{
transition: all 0.5s;
color: ${palette.TERTIARY};
&:hover {
color: ${palette.HIGHLIGHT};
}
}
svg {
transition: all 0.5s;
fill: ${palette.TERTIARY};
&:hover {
fill: ${palette.HIGHLIGHT};
}
}
.bm-overlay, .bm-menu-wrap {
background: ${palette.BASE} !important;
}
.bm-cross {
background: ${palette.TERTIARY};
}
.bm-burger-bars {
background: ${palette.TERTIARY};
}
`
const Layout = ({ children, location }) => {
return (
<div className="siteRoot">
<Helmet>
<html lang="en" />
<title>{config.siteTitle}</title>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/logos/logo-512.png" />
<link rel="apple-touch-icon" href="/logos/logo-512.png" />
<meta name="description" content={config.siteDescription} />
<meta property="og:title" content={config.siteTitle} />
<meta property="og:url" content={config.siteUrl} />
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content={config.siteTitle} />
</Helmet>
<ThemeProvider theme={theme}>
<Wrapper>
<div id="outer-container" style={{ height: '100vh' }}>
<Menu />
<div
className="siteContent"
id="page-wrap"
style={{ height: '100%', overflow: 'scroll' }}
>
{children}
</div>
</div>
</Wrapper>
</ThemeProvider>
</div>
)
}
export default Layout
|
JavaScript
| 0.000001 |
@@ -1827,36 +1827,8 @@
ner%22
- style=%7B%7B height: '100vh' %7D%7D
%3E%0A
@@ -1862,30 +1862,16 @@
%3Cdiv
-%0A
classNa
@@ -1886,30 +1886,16 @@
Content%22
-%0A
id=%22pag
@@ -1905,82 +1905,8 @@
rap%22
-%0A style=%7B%7B height: '100%25', overflow: 'scroll' %7D%7D%0A
%3E%0A
|
d81d69c1c2a7ff6145395de78e634ca05b56aa8d
|
make deletion menu item read
|
src/components/header.js
|
src/components/header.js
|
'use strict'
import React from 'react'
import lang from 'i18n/lang'
import Exporter from 'components/file/export'
import Importer from 'components/file/import'
import FileOpener from 'components/file/open'
import FileSaveAs from 'components/file/saveAs'
import './header.less'
let Header = React.createClass({
createWidget: function (type) {
let deck = this.props.deck
let activeSlide = deck.getActiveSlide()
this.props.onNewWidget(activeSlide, null,
{
"type": type,
"x": 0,
"y": 0,
"text": "<div style=\"font-family: Hammersmith One;font-size: 100pt\">ddx</div>"
},
lang['new'] + ' ' + lang[type])
},
onImport: function () {
this.refs.importer.click()
},
onDelete: function(){
this.props.onDeleteDeck()
},
render: function () {
let undoTitle = lang.undo + ' ' + this.props.deck.undoStack.stack[this.props.deck.undoStack.current].desc
let redoTitle = lang.redo + ' ' + ((this.props.deck.undoStack.current + 1 < this.props.deck.undoStack.stack.length) ? this.props.deck.undoStack.stack[this.props.deck.undoStack.current + 1].desc : '')
return <nav className="navbar navbar-default sp-header">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"/>
<span className="icon-bar"/>
<span className="icon-bar"/>
</button>
<div className="dropdown">
<a href="#" className="navbar-brand dropdown-toggle" data-toggle="dropdown" role="button btn-default"
aria-haspopup="true"
aria-expanded="false">ShowPreper<span className="caret"/></a>
<ul className="dropdown-menu">
<li><a href="#" onClick={this.props.onUndo} title={undoTitle}>{lang.undo}<span
className="badge">Ctrl-z</span></a></li>
<li><a href="#" onClick={this.props.onRedo} title={redoTitle}>{lang.redo}<span
className="badge">Ctrl-y</span></a></li>
<li><a href="#fileOpen" title={lang.open}>{lang.open}</a>
</li>
<li><a href="#fileSaveAs" title={lang.saveAs}>{lang.saveAs}</a>
</li>
<li><a href="#openExport" title={lang.export}>{lang.export}</a>
</li>
<li><a href="#" onClick={this.onImport} title={lang.import}>{lang.import}</a>
</li>
<li><a href="#" onClick={this.onDelete} title={lang.delete}>{lang.delete}</a>
</li>
</ul>
<FileOpener onNewDeck={this.props.onNewDeck}/>
<FileSaveAs
onNewDeck={this.props.onNewDeck}
deck={this.props.deck}/>
<Exporter deck={this.props.deck}/>
<Importer onNewDeck={this.props.onNewDeck} ref="importer"/>
</div>
</div>
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<div className="nav navbar-btn btn-group navbar-left" role="group">
{[
{icon: 'glyphicon-text-width', text: lang.text, type: 'TextBox'},
{icon: 'glyphicon-picture', text: lang.image, type: 'image'},
{icon: 'glyphicon-film', text: lang.video, type: 'video'},
{icon: 'glyphicon-globe', text: lang.website, type: 'website'},
{icon: 'glyphicon-star', text: lang.shapes, type: 'shapes'},
].map(e =>
<button type="button" className="btn btn-default" key={e.type}
onClick={() => {this.createWidget(e.type)}}>
<span className={'glyphicon ' + e.icon}/>
<div className="btn-label">
{e.text}
</div>
</button>
)}
</div>
<div className="navbar-right">
<ul className="nav navbar-btn sp-view-btns">
<li style={this.props.currentView!=='slides'?{}: {display: 'none'}}>
<button type="button"
className="btn btn-default"
onClick={()=>this.props.changeView('slides')}
>
<span className={'glyphicon glyphicon-th-list'}/>
<div className="btn-label">
{lang.slides}
</div>
</button>
</li>
<li style={this.props.currentView!=='overview' ?{}: {display: 'none'}}>
<button type="button"
className="btn btn-default"
onClick={()=>this.props.changeView('overview')}
>
<span className={'glyphicon glyphicon-th'}/>
<div className="btn-label">
{lang.overview}
</div>
</button>
</li>
</ul>
<div className="nav navbar-btn btn-group">
<a type="button" className="btn btn-success" href="./presentation.html" target="_blank">
<span className={'glyphicon glyphicon-play'}/>
<div>{lang.show}</div>
</a>
<button type="button" className="btn btn-success dropdown-toggle" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<span className="caret"/>
<span className="sr-only">Toggle Dropdown</span>
</button>
<ul className="dropdown-menu">
<li><a href="./presentation.html" target="_blank">{lang.presentation}</a></li>
<li><a href="./handout.html" target="_blank">{lang.handouts}</a></li>
</ul>
</div>
</div>
</div>
{/*<!-- /.navbar-collapse -->*/}
</div>
{/*<!-- /.container-fluid -->*/}
</nav>
}
})
module.exports = Header
|
JavaScript
| 0.000002 |
@@ -2724,16 +2724,39 @@
.delete%7D
+ style=%7B%7Bcolor: 'red'%7D%7D
%3E%7Blang.d
|
9fcf2ea965b71ddc76c47f9616a2dd68a68202a1
|
update window spinner to horizon spec
|
src/components/styles.js
|
src/components/styles.js
|
export var styles = {
errorBox: {
fontFamily: "sans-serif",
border: 1,
borderColor: "#FF3131",
borderStyle: "dashed",
padding: 3,
borderRadius: 3,
background: "#FFF2F2",
position: "relative",
top: 8,
left: 6,
},
logos: {
container: {
display: "flex",
height: "inherit",
},
toolbar: {
height: "80%",
alignSelf: "center",
paddingLeft: 15,
paddingRight: 15,
},
},
spinners: {
toolbar: {
height: 30,
},
window: {
paddingTop: 110,
paddingBottom: 80,
height: 50,
width: "auto",
margin: "auto",
display: "flex",
},
},
toolbar: {
base: {
display: "flex",
justifyContent: "space-between",
backgroundColor: "#C0C0C0",
height: 40,
},
tools: {
height: "inherit",
display: "flex",
justifyContent: "flex-start",
},
controls: {
height: "inherit",
display: "flex",
justifyContent: "flex-end",
},
},
forms: {
width: 194,
},
buttons: {
base: {
display: "flex",
justifyContent: "space-around",
alignItems: "center",
width: 150,
border: "none",
fontSize:"15px",
fontFamily: "sans-serif",
color: "white",
},
toolbar: {
width: 120,
backgroundColor: "gray",
},
run: {
waiting: {
backgroundColor: "#317BCF"
},
running: {
color: "gray",
},
},
stop: {
stopping: {
backgroundColor: "#FF0000",
color: "white",
},
waiting: {
color: "gray",
},
},
more: {
moreButton:{
height: 40,
position: "absolute",
marginLeft: 3,
justifyContent: "center",
},
menuContainer: {
display: "flex",
flexDirection: "column",
position: "absolute",
marginTop: 40,
marginLeft: 3,
zIndex: 1,
},
menuItems: {
height: 40,
color: "black",
backgroundColor: "#EFEFEF",
textDecoration: "none",
},
},
googleDrive: {
float: "left",
width: 194,
backgroundColor: "gray"
},
},
linkStyle: {
textDecoration: "none",
color: "black",
},
};
|
JavaScript
| 0 |
@@ -544,35 +544,10 @@
op:
-110,%0A paddingBottom: 8
+20
0,%0A
|
84ff1ef396bc781798c90c9d070bfce53674fe53
|
Fix prettyPrintXML.
|
dom/prettyPrintXML.js
|
dom/prettyPrintXML.js
|
import DOM from './DefaultDOMElement'
import _isTextNodeEmpty from './_isTextNodeEmpty'
import isString from '../util/isString'
export default function prettyPrintXML (xml) {
let dom
if (isString(xml)) {
dom = DOM.parseXML(xml)
} else {
dom = xml
}
const result = []
// Note: the browser treats XML instructions in a surprising way:
// parsing `<?xml version="1.0" encoding="UTF-8"?><dummy/>` results in only one element
// i.e. the instruction is swallowed and stored in a way that it is created during serialization.
// Interestingly, this is not the case for the DOCTYPE declaration.
// ATTENTION: we have assimilated the MemoryDOM implementation, so that we get the same result.
const childNodes = dom.getChildNodes()
if (dom.isDocumentNode()) {
const xml = dom.empty().serialize()
if (/<\?\s*xml/.exec(xml)) {
result.push(xml)
}
}
childNodes.forEach(el => {
_prettyPrint(result, el, 0)
})
return result.join('\n')
}
function _prettyPrint (result, el, level) {
const indent = new Array(level * 2).fill(' ').join('')
if (el.isElementNode()) {
const isMixed = _isMixed(el)
const containsCDATA = _containsCDATA(el)
if (isMixed || containsCDATA) {
result.push(indent + el.outerHTML)
} else {
const children = el.children
const tagName = el.tagName
const tagStr = [`<${tagName}`]
el.getAttributes().forEach((val, name) => {
tagStr.push(`${name}="${val}"`)
})
if (children.length > 0) {
result.push(indent + tagStr.join(' ') + '>')
el.children.forEach((child) => {
_prettyPrint(result, child, level + 1)
})
result.push(indent + `</${tagName}>`)
} else {
result.push(indent + tagStr.join(' ') + ' />')
}
}
} else if (level === 0 && el.isTextNode()) {
// skip text outside of the root element
} else {
result.push(indent + el.outerHTML)
}
}
function _isMixed (el) {
const childNodes = el.childNodes
for (let i = 0; i < childNodes.length; i++) {
const child = childNodes[i]
if (child.isTextNode() && !_isTextNodeEmpty(child)) {
return true
}
}
}
function _containsCDATA (el) {
const childNodes = el.childNodes
for (let i = 0; i < childNodes.length; i++) {
const child = childNodes[i]
if (child.getNodeType() === 'cdata') {
return true
}
}
}
|
JavaScript
| 0.000001 |
@@ -705,16 +705,48 @@
result.%0A
+ if (dom.isDocumentNode()) %7B%0A
const
@@ -782,38 +782,8 @@
s()%0A
- if (dom.isDocumentNode()) %7B%0A
@@ -882,18 +882,16 @@
%7D%0A
-%7D%0A
childN
@@ -907,24 +907,26 @@
ach(el =%3E %7B%0A
+
_prettyP
@@ -947,18 +947,68 @@
l, 0)%0A
+ %7D)%0A %7D else %7B%0A _prettyPrint(result, dom, 0)%0A
%7D
-)
%0A retur
|
198101fe3278dc44c4a75408cdcae16667428ea7
|
update header of douban4xuandy.user.js
|
douban4xuandy.user.js
|
douban4xuandy.user.js
|
// ==UserScript==
// @name douban4xuandy
// @grant GM_xmlhttpRequest
// @description douban score for www.xuandy.com movie
// @include http://www.xuandy.com/movie/*
// author [email protected]
// github goorockey/douban4xuandy
// ==/UserScript==
var douban_search_url = 'https://api.douban.com/v2/movie/search?count=10&q=';
var douban_movie_url = 'http://movie.douban.com/subject/'
var insertDoubanScore = function(douban_data) {
if (douban_data === undefined) {
return;
}
var score = douban_data.rating.average;
var link = douban_movie_url + douban_data.id;
var a = document.createElement('a');
a.appendChild(document.createTextNode('豆瓣评分: ' + score));
a.href = link;
a.style.color = 'red';
document.getElementsByClassName('postmeat')[0].appendChild(a);
};
var parseDoubanData = function (movie_name, data) {
if (!data || !data.subjects) {
return ;
}
data = data.subjects;
for (var i = 0; i < data.length; i++) {
if (data[i].title === movie_name) {
return data[i];
}
}
};
var getDoubanScore = function (movie_name, callback) {
GM_xmlhttpRequest({
method: 'GET',
headers: {
'Accept': 'application/json'
},
url: douban_search_url + movie_name,
onload: function (res) {
if (res.status !== 200) {
return ;
}
try {
var data = JSON.parse(res.responseText);
return callback(parseDoubanData(movie_name, data));
} catch (e) {
console.log(e);
}
},
});
};
var getMovieName = function () {
var title = document.getElementsByClassName('post') [0].childNodes[1].innerHTML;
var re = /\u300A(.*)\u300B/; // 格式: 《电影名》
var m = re.exec(title);
if (!m) {
return ;
}
var movie_name = m[1];
return movie_name;
};
getDoubanScore(getMovieName(), insertDoubanScore);
|
JavaScript
| 0 |
@@ -27,19 +27,16 @@
-
douban4x
@@ -57,19 +57,16 @@
t
-
GM_xmlht
@@ -91,19 +91,16 @@
ription
-
douban s
@@ -145,19 +145,62 @@
ude
+http://www.xuandy.com/movie/*%0A// @include
+
http://w
@@ -209,29 +209,80 @@
.xuandy.com/
-movie
+television/*%0A// @include http://www.xuandy.com/video
/*%0A// author
@@ -288,19 +288,16 @@
r
-
kelvingu
@@ -330,33 +330,27 @@
- goorockey/douban4xuand
+github.com/goorocke
y%0A//
@@ -367,17 +367,16 @@
ript==%0A%0A
-%0A
var doub
@@ -502,16 +502,17 @@
ubject/'
+;
%0A%0Avar in
@@ -608,29 +608,25 @@
turn;%0A %7D%0A
-
%0A
+
var scor
@@ -707,21 +707,17 @@
ata.id;%0A
-
%0A
+
var
@@ -857,21 +857,17 @@
'red';%0A
-
%0A
+
docu
@@ -1039,20 +1039,16 @@
;%0A %7D%0A
-
%0A dat
|
cfda082cba7960ea2c718bc589d065fe188fb8fb
|
make sure to only show popover on ipad
|
test/apps/ui/popover/controllers/index.js
|
test/apps/ui/popover/controllers/index.js
|
function openPopover() {
var popover = Alloy.createController('popover').getView();
popover.show({view:$.button});
}
$.index.open();
|
JavaScript
| 0 |
@@ -18,16 +18,55 @@
ver() %7B%0A
+%09if (Ti.Platform.osname === 'ipad') %7B%0A%09
%09var pop
@@ -117,16 +117,17 @@
View();%0A
+%09
%09popover
@@ -151,16 +151,72 @@
ton%7D);%09%0A
+%09%7D else %7B%0A%09%09alert('Popover only supported on iPad');%0A%09%7D%0A
%7D%0A%0A$.ind
|
f36a343c32e85277e7fb886bd2f1e5aad3edd497
|
Remove uneccessary default permissions from test setup
|
test/bigtest/helpers/setup-application.js
|
test/bigtest/helpers/setup-application.js
|
import { beforeEach } from '@bigtest/mocha';
import { setupAppForTesting, visit, location } from '@bigtest/react';
import localforage from 'localforage';
import sinon from 'sinon';
// load these styles for our tests
import 'typeface-source-sans-pro';
import '@folio/stripes-components/lib/global.css';
import startMirage from '../network/start';
import App from '../../../src/App';
import * as actions from '../../../src/okapiActions';
import {
withModules,
clearModules,
withConfig,
clearConfig
} from './stripes-config';
export default function setupApplication({
disableAuth = true,
modules = [],
translations = {},
permissions = {},
stripesConfig,
mirageOptions,
scenarios
} = {}) {
beforeEach(async function () {
const initialState = {};
// when auth is disabled, add a fake user to the store
if (disableAuth) {
initialState.okapi = {
token: 'test',
currentUser: {
id: 'test',
username: 'testuser',
firstName: 'Test',
lastName: 'User',
email: '[email protected]',
addresses: [],
servicePoints: []
},
currentPerms: {
'perms.all': true,
...permissions
}
};
}
// mount the app
this.app = await setupAppForTesting(App, {
mountId: 'testing-root',
props: {
initialState
},
setup: () => {
this.server = startMirage(scenarios, mirageOptions);
this.server.logging = false;
withModules(modules);
withConfig({ logCategories: '', ...stripesConfig });
sinon.stub(actions, 'setTranslations').callsFake(incoming => {
return {
type: 'SET_TRANSLATIONS',
translations: Object.assign(incoming, translations)
};
});
},
teardown: () => {
actions.setTranslations.restore();
clearConfig();
clearModules();
localforage.clear();
this.server.shutdown();
}
});
// set the root to 100% height
document.getElementById('testing-root').style.height = '100%';
// setup react helpers
Object.defineProperties(this, {
visit: { value: visit },
location: { get: location }
});
});
}
|
JavaScript
| 0 |
@@ -1163,52 +1163,8 @@
ms:
-%7B%0A 'perms.all': true,%0A ...
perm
@@ -1175,18 +1175,8 @@
ons%0A
- %7D%0A
|
fcd833129c849fd4434bed2e4f21c1d9a6fb4c8f
|
Add focus event show close button when focus field if value length is >= 1
|
addclear.js
|
addclear.js
|
// Author: Stephen Korecky
// Website: http://stephenkorecky.com
// Plugin Website: http://github.com/skorecky/Add-Clear
(function($){
$.fn.extend({
addClear: function(options) {
var selector = this.selector;
var options = $.extend({
closeSymbol: "✖",
color: "#CCC",
top: 1,
right: 4,
returnFocus: true,
showOnLoad: false,
onClear: null
}, options);
$(this).wrap("<span style='position:relative;' class='add-clear-span'>");
$(this).after("<a href='#clear'>"+options.closeSymbol+"</a>");
$("a[href='#clear']").css({
color: options.color,
'text-decoration': 'none',
display: 'none',
'line-height': 1,
overflow: 'hidden',
position: 'absolute',
right: options.right,
top: options.top
}, this);
if($(this).val().length >= 1 && options.showOnLoad === true) {
$(this).siblings("a[href='#clear']").show();
}
$(this).keyup(function() {
if($(this).val().length >= 1) {
$(this).siblings("a[href='#clear']").show();
} else {
$(this).siblings("a[href='#clear']").hide();
}
});
$("a[href='#clear']").click(function(){
$(this).siblings(selector).val("");
$(this).hide();
if(options.returnFocus === true){
$(this).siblings(selector).focus();
}
if (options.onClear){
options.onClear($(this).siblings("input"));
}
return false;
});
return this;
}
});
})(jQuery);
|
JavaScript
| 0 |
@@ -994,16 +994,165 @@
%7D%0A%0A
+ $(this).focus(function() %7B%0A if($(this).val().length %3E= 1) %7B%0A $(this).siblings(%22a%5Bhref='#clear'%5D%22).show();%0A %7D%0A %7D);%0A%0A
$(
|
c905b9120af64682a01b672482153108eb04718a
|
refactor site kit plugin activation
|
tests/e2e/specs/plugin-activation.test.js
|
tests/e2e/specs/plugin-activation.test.js
|
/**
* WordPress dependencies
*/
import { deactivatePlugin, activatePlugin } from '@wordpress/e2e-test-utils';
describe( 'Plugin Activation Notice', () => {
beforeEach( async () => {
await deactivatePlugin( 'site-kit-by-google' );
await activatePlugin( 'e2e-tests-gcp-credentials-plugin' );
} );
afterEach( async () => {
await deactivatePlugin( 'e2e-tests-gcp-credentials-plugin' );
await activatePlugin( 'site-kit-by-google' );
} );
it( 'Should be displayed', async () => {
await activatePlugin( 'site-kit-by-google' );
await page.waitForSelector( '.googlesitekit-activation' );
await expect( page ).toMatchElement( 'h3.googlesitekit-activation__title', { text: 'Congratulations, the Site Kit plugin is now activated.' } );
await deactivatePlugin( 'site-kit-by-google' );
} );
it( 'Should lead you to the setup wizard', async () => {
await activatePlugin( 'site-kit-by-google' );
await page.waitForSelector( '.googlesitekit-activation' );
await expect( page ).toMatchElement( '.googlesitekit-activation__button', { text: 'Start Setup' } );
await page.click( '.googlesitekit-activation__button' );
await page.waitForSelector( '.googlesitekit-wizard-step__title' );
// Ensure we're on the first step.
await expect( page ).toMatchElement( '.googlesitekit-wizard-progress-step__number--inprogress', { text: '1' } );
} );
} );
|
JavaScript
| 0.000001 |
@@ -106,16 +106,872 @@
tils';%0A%0A
+/**%0A * Activation helpers are only necessary pre-1.0 release.%0A * WordPress populates the %60data-slug%60 attribute from the%0A * %60slug%60 returned by the wp.org plugin API. For plugins%0A * that are not available on the .org repo, the slug will be%0A * generated from the plugin's name.%0A *%0A * For this reason, we fallback to the title-based slug if the%0A * expected %22official%22 slug is not found.%0A *%0A * Once the plugin is publicly available, these helpers can be removed%0A * and consuming code can use %60google-site-kit%60 variations in their places.%0A */%0A%0Aconst activateSiteKit = async () =%3E %7B%0A%09try %7B%0A%09%09await activatePlugin( 'google-site-kit' );%0A%09%7D catch %7B%0A%09%09await activatePlugin( 'site-kit-by-google' );%0A%09%7D%0A%7D;%0A%0Aconst deactivateSiteKit = async () =%3E %7B%0A%09try %7B%0A%09%09await deactivatePlugin( 'google-site-kit' );%0A%09%7D catch %7B%0A%09%09await deactivatePlugin( 'site-kit-by-google' );%0A%09%7D%0A%7D;%0A%0A
describe
@@ -1057,37 +1057,16 @@
vate
-Plugin( 'site-kit-by-google'
+SiteKit(
);%0A%09
@@ -1243,37 +1243,16 @@
vate
-Plugin( 'site-kit-by-google'
+SiteKit(
);%0A%09
@@ -1319,37 +1319,16 @@
vate
-Plugin( 'site-kit-by-google'
+SiteKit(
);%0A%0A
@@ -1559,37 +1559,16 @@
vate
-Plugin( 'site-kit-by-google'
+SiteKit(
);%0A%09
@@ -1651,37 +1651,16 @@
vate
-Plugin( 'site-kit-by-google'
+SiteKit(
);%0A%0A
|
8d388e8bf1644e6567e9b9d64be48af380fea79c
|
fix issue 24
|
advanceSearch.js
|
advanceSearch.js
|
var advBatchStart = 0;
var advBatchSize = 5;
var advResult;
var advanceSearch=function(){
console.log("advanceSearch");
$('#advSearchmodal').modal({
show: 'true'
});
}
var filterDiv=function(division){
var out=[];
var sDivision=biography.divisions[division];
for (var j=0;j<sDivision.sutras.length;j+=1) {
var sutra=sDivision.sutras[j];
out.push(sutra);
}
return out;
}
var firstpass=function(field,val){
var divisions=biography.divisions;
var out=[];
for (var i=0;i<divisions.length;i+=1) {
for (var j=0;j<divisions[i].sutras.length;j+=1) {
var sutra=divisions[i].sutras[j];
if (sutra[field].indexOf(val)>-1) {
out.push(sutra);
}
}
}
return out;
}
var filterS=function(field,val,previousresult) { //field 欄位名, val 欄位值
var out=[]
if (!previousresult) {
return firstpass(field,val);
} else {
for (var i=0;i<previousresult.length;i++) { //other pass
if (previousresult[i][field].indexOf(val)>-1) {
out.push(previousresult[i]);
}
}
return out;
}
}
var filterOr=function(field,val,previousresult) { //field 欄位名, val 欄位值
var out=[]
if (!previousresult) {
return firstpass(field,val);
} else {
for (var i=0;i<previousresult.length;i++) { //other pass
for(var j=0;j<field.length;j+=1){
if (previousresult[i][field[j]].indexOf(val)>-1) {
out.push(previousresult[i]);
break;
}
}
}
return out;
}
}
var initialRes=function(){
var divisions=biography.divisions;
var out=[];
for (var i=0;i<divisions.length;i+=1) {
for (var j=0;j<divisions[i].sutras.length;j+=1) {
var sutra=divisions[i].sutras[j];
out.push(sutra);
}
}
return out;
}
var creatDivisionDDL=function(){
var options = "<option value='-1'>-- ALL --</option>";
var divisions=biography.divisions;
for (var i=0;i<divisions.length;i+=1) {
options += "<option value='"+i+"'>"+divisions[i].divisionName+"</option>";
}
$("#s_division").html(options);
}
var initialAdvSearch=function(){
console.log("initialAdvSearch");
creatDivisionDDL();
}
var showPagination=function(){
if(advResult.length==0)$("#batches").html("");
var batch=Math.floor((advResult.length-1)/advBatchSize)+1;
var html = "";
if(advBatchStart!=0){
html += "<li><a onClick='goRefPage(-1)' href='#' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>";
}
for(var i=0;i<batch;i+=1){
var active = "";
if(i==advBatchStart)active="active";
html += "<li class='"+active+"'><a onClick='goPage("+i+")' href='#'>" + (i+1) + "</a><li>";
}
if(advBatchStart+1<batch){
html += "<li><a onClick='goRefPage(1)' href='#' aria-label='Previous'><span aria-hidden='true'>»</span></a></li>";
}
$("#advPag").html(html);
}
var goRefPage=function(ref){
advBatchStart += ref;
$("#advResult").html( showPage());
showPagination();
}
var goPage=function(page){
advBatchStart = page;
$("#advResult").html( showPage());
showPagination();
}
var advGoSid=function(Sid){
gotoSid(Sid);
$('#advSearchmodal').modal('hide');
}
var showPage=function(){
var Rtn="";
var names=wylie.fromWylieWithWildcard($("#names").val());
/*var tname=$("#tname").val();
var aname=$("#aname").val();
var author=$("#author").val();*/
for(var i=advBatchStart*advBatchSize;i<advResult.length;i+=1){
if(i==advBatchStart*advBatchSize+advBatchSize)break;
Rtn+="<li>"
+ "<span>"+advResult[i].sutraid+"</span>"
+"<a onClick=\"advGoSid('"+advResult[i].sutraid+"')\" href='#'>"+advResult[i].tname.replace(names,"<span class='highlight'>"+names+"</span>")+"</a>"
+"</li>";
/*+",tname:"+advResult[i].tname.replace(names,"<span class='hl'>"+names+"</span>")
+",aname:"+advResult[i].aname.replace(names,"<span class='hl'>"+names+"</span>")
+",sname:"+advResult[i].aname.replace(names,"<span class='hl'>"+names+"</span>")
+",cname:"+advResult[i].aname.replace(names,"<span class='hl'>"+names+"</span>");*/
//+advResult[i].author.replace(author,"<span class='hl'>"+author+"</span>");
}
return Rtn;
}
var doAdvSearch=function(){
var namesC = ["tname","aname","sname","cname"];
var singleFilters = ["yana","chakra","location","translator","reviser"];
var division=$("#s_division").val();
var names=wylie.fromWylieWithWildcard($("#names").val());
var res;
if(division>=0){
res=filterDiv(division);
}else{
res=initialRes();
}
if(names){
res=filterOr(namesC,names,res);
}
for(var i=0;i<singleFilters.length;i+=1){
var column=singleFilters[i];
if(column){
res=filterS(column, wylie.fromWylieWithWildcard($("#"+column).val()),res);
}
}
advResult=res;
advBatchStart = 0;
var out=showPage();
showPagination();
$("#advResult").html( out);
}
|
JavaScript
| 0 |
@@ -3845,16 +3845,17 @@
oSid('%22+
+(
advResul
@@ -3866,16 +3866,49 @@
.sutraid
+).replace(%22(%22,%22%22).replace(%22)%22,%22%22)
+%22')%5C%22 h
|
d98cf7e3ed3744bd0c2c04d9d2a24fe188102581
|
increase width of experimental-submit
|
src/clincoded/static/components/experimental_submit.js
|
src/clincoded/static/components/experimental_submit.js
|
"use strict";
var React = require('react');
var _ = require('underscore');
var globals = require('./globals');
var curator = require('./curator');
var RestMixin = require('./rest').RestMixin;
var form = require('../libs/bootstrap/form');
var panel = require('../libs/bootstrap/panel');
var RecordHeader = curator.RecordHeader;
var PmidSummary = curator.PmidSummary;
var queryKeyValue = globals.queryKeyValue;
var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var Panel = panel.Panel;
var ExperimentalSubmit = React.createClass({
mixins: [FormMixin, RestMixin],
// Keeps track of values from the query string
queryValues: {},
getInitialState: function() {
return {
gdm: null, // GDM object given in query string
experimental: null, // Experimental object given in query string
annotation: null, // Annotation object given in query string
};
},
// Load objects from query string into the state variables. Must have already parsed the query string
// and set the queryValues property of this React class.
loadData: function() {
var gdmUuid = this.queryValues.gdmUuid;
var experimentalUuid = this.queryValues.experimentalUuid;
var annotationUuid = this.queryValues.annotationUuid;
// Make an array of URIs to query the database. Don't include any that didn't include a query string.
var uris = _.compact([
gdmUuid ? '/gdm/' + gdmUuid : '',
experimentalUuid ? '/experimental/' + experimentalUuid : '',
annotationUuid ? '/evidence/' + annotationUuid : ''
]);
// With all given query string variables, get the corresponding objects from the DB.
this.getRestDatas(
uris
).then(datas => {
// See what we got back so we can build an object to copy in this React object's state to rerender the page.
var stateObj = {};
datas.forEach(function(data) {
switch(data['@type'][0]) {
case 'gdm':
stateObj.gdm = data;
break;
case 'experimental':
stateObj.experimental = data;
break;
case 'annotation':
stateObj.annotation = data;
break;
default:
break;
}
});
// Set all the state variables we've collected
this.setState(stateObj);
// Not passing data to anyone; just resolve with an empty promise.
return Promise.resolve();
}).catch(function(e) {
console.log('OBJECT LOAD ERROR: %s — %s', e.statusText, e.url);
});
},
// After the Experimental Curation page component mounts, grab the GDM, experimental, and annotation UUIDs (as many as given)
// from the query string and retrieve the corresponding objects from the DB, if they exist. Note, we have to do this after
// the component mounts because AJAX DB queries can't be done from unmounted components.
componentDidMount: function() {
// Get the 'evidence', 'gdm', and 'experimental' UUIDs from the query string and save them locally.
this.loadData();
},
render: function() {
var gdm = this.state.gdm;
var experimental = this.state.experimental;
var annotation = this.state.annotation;
// Get the query strings. Have to do this now so we know whether to render the form or not. The form
// uses React controlled inputs, so we can only render them the first time if we already have the
// family object read in.
this.queryValues.gdmUuid = queryKeyValue('gdm', this.props.href);
this.queryValues.experimentalUuid = queryKeyValue('experimental', this.props.href);
this.queryValues.annotationUuid = queryKeyValue('evidence', this.props.href);
// Build the link to go back and edit the newly created experimental page
var editExperimentalLink = (gdm && experimental && annotation) ? '/experimental-curation/?gdm=' + gdm.uuid + '&evidence=' + annotation.uuid + '&experimental=' + experimental.uuid : '';
return (
<div>
<RecordHeader gdm={gdm} omimId={gdm && gdm.omimId} />
<div className="container">
{experimental ?
<h1>{experimental.evidenceType}<br />Experimental Data Information: {experimental.label} <a href={experimental['@id']} className="btn btn-info" target="_blank">View</a> <a href={editExperimentalLink} className="btn btn-info">Edit</a></h1>
: null}
{annotation && annotation.article ?
<div className="curation-pmid-summary">
<PmidSummary article={annotation.article} displayJournal />
</div>
: null}
<div className="row">
<div className="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1">
<Panel panelClassName="submit-results-panel" panelBodyClassName="bg-info">
<div className="submit-results-panel-info">
<em>Your Experimental Data has been added!</em>
</div>
</Panel>
{ experimental && annotation && annotation.article ?
<Panel panelClassName="submit-results-panel submit-results-response">
<div className="family-submit-results-choices">
<div className="submit-results-panel-info"></div>
<div className="submit-results-buttons">
<div className="col-md-7">
<span className="family-submit-results-btn">
<a className="btn btn-default" href={'/experimental-curation/?gdm=' + gdm.uuid + '&evidence=' + annotation.uuid}>Add another Experimental Data entry</a>
</span>
</div>
<div className="col-md-5">
<span className="family-submit-results-btn">
<a className="btn btn-default" href={'/curation-central/?gdm=' + gdm.uuid + '&pmid=' + annotation.article.pmid}>Return to Record Curation page</a>
</span>
</div>
</div>
</div>
</Panel>
: null }
</div>
</div>
</div>
</div>
);
}
});
globals.curator_page.register(ExperimentalSubmit, 'curator_page', 'experimental-submit');
|
JavaScript
| 0 |
@@ -5152,9 +5152,10 @@
-md-
-8
+10
col
@@ -5169,9 +5169,9 @@
set-
-2
+1
col
|
3218730a167e0e0cce0d9943baf1bbd65c741a4e
|
set query on change in opportunity_from value
|
erpnext/crm/doctype/opportunity/opportunity.js
|
erpnext/crm/doctype/opportunity/opportunity.js
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
{% include 'erpnext/selling/sales_common.js' %}
frappe.provide("erpnext.crm");
cur_frm.email_field = "contact_email";
frappe.ui.form.on("Opportunity", {
setup: function(frm) {
frm.custom_make_buttons = {
'Quotation': 'Quotation',
'Supplier Quotation': 'Supplier Quotation'
},
frm.set_query("opportunity_from", function() {
return{
"filters": {
"name": ["in", ["Customer", "Lead"]],
}
}
});
if (frm.doc.opportunity_from && frm.doc.party_name){
frm.trigger('set_contact_link');
}
},
onload_post_render: function(frm) {
frm.get_field("items").grid.set_multiple_add("item_code", "qty");
},
party_name: function(frm) {
frm.toggle_display("contact_info", frm.doc.party_name);
frm.trigger('set_contact_link');
if (frm.doc.opportunity_from == "Customer") {
erpnext.utils.get_party_details(frm);
} else if (frm.doc.opportunity_from == "Lead") {
erpnext.utils.map_current_doc({
method: "erpnext.crm.doctype.lead.lead.make_opportunity",
source_name: frm.doc.party_name,
frm: frm
});
}
},
onload_post_render: function(frm) {
frm.get_field("items").grid.set_multiple_add("item_code", "qty");
},
with_items: function(frm) {
frm.trigger('toggle_mandatory');
},
customer_address: function(frm, cdt, cdn) {
erpnext.utils.get_address_display(frm, 'customer_address', 'address_display', false);
},
contact_person: erpnext.utils.get_contact_details,
opportunity_from: function(frm) {
frm.toggle_reqd("party_name", frm.doc.opportunity_from);
frm.trigger("set_dynamic_field_label");
},
refresh: function(frm) {
var doc = frm.doc;
frm.events.opportunity_from(frm);
frm.trigger('toggle_mandatory');
erpnext.toggle_naming_series();
if(!doc.__islocal && doc.status!=="Lost") {
if(doc.with_items){
frm.add_custom_button(__('Supplier Quotation'),
function() {
frm.trigger("make_supplier_quotation")
}, __('Create'));
}
frm.add_custom_button(__('Quotation'),
cur_frm.cscript.create_quotation, __('Create'));
if(doc.status!=="Quotation") {
frm.add_custom_button(__('Lost'), () => {
frm.trigger('set_as_lost_dialog');
});
}
}
if(!frm.doc.__islocal && frm.perm[0].write && frm.doc.docstatus==0) {
if(frm.doc.status==="Open") {
frm.add_custom_button(__("Close"), function() {
frm.set_value("status", "Closed");
frm.save();
});
} else {
frm.add_custom_button(__("Reopen"), function() {
frm.set_value("status", "Open");
frm.save();
});
}
}
},
set_contact_link: function(frm) {
if(frm.doc.opportunity_from == "Customer" && frm.doc.party_name) {
frappe.dynamic_link = {doc: frm.doc, fieldname: 'party_name', doctype: 'Customer'}
} else if(frm.doc.opportunity_from == "Lead" && frm.doc.party_name) {
frappe.dynamic_link = {doc: frm.doc, fieldname: 'party_name', doctype: 'Lead'}
}
},
set_dynamic_field_label: function(frm){
if (frm.doc.opportunity_from) {
frm.set_df_property("party_name", "label", frm.doc.opportunity_from);
}
},
make_supplier_quotation: function(frm) {
frappe.model.open_mapped_doc({
method: "erpnext.crm.doctype.opportunity.opportunity.make_supplier_quotation",
frm: cur_frm
})
},
toggle_mandatory: function(frm) {
frm.toggle_reqd("items", frm.doc.with_items ? 1:0);
}
})
// TODO commonify this code
erpnext.crm.Opportunity = frappe.ui.form.Controller.extend({
onload: function() {
if(!this.frm.doc.status) {
frm.set_value('status', 'Open');
}
if(!this.frm.doc.company && frappe.defaults.get_user_default("Company")) {
frm.set_value('company', frappe.defaults.get_user_default("Company"));
}
if(!this.frm.doc.currency) {
frm.set_value('currency', frappe.defaults.get_user_default("Currency"));
}
this.setup_queries();
},
setup_queries: function() {
var me = this;
if(this.frm.fields_dict.contact_by.df.options.match(/^User/)) {
this.frm.set_query("contact_by", erpnext.queries.user);
}
me.frm.set_query('customer_address', erpnext.queries.address_query);
this.frm.set_query("item_code", "items", function() {
return {
query: "erpnext.controllers.queries.item_query",
filters: {'is_sales_item': 1}
};
});
me.frm.set_query('contact_person', erpnext.queries['contact_query'])
if (me.frm.doc.opportunity_from == "Lead") {
me.frm.set_query('party_name', erpnext.queries['lead']);
}
else if (me.frm.doc.opportunity_from == "Customer") {
me.frm.set_query('party_name', erpnext.queries['customer']);
}
},
create_quotation: function() {
frappe.model.open_mapped_doc({
method: "erpnext.crm.doctype.opportunity.opportunity.make_quotation",
frm: cur_frm
})
}
});
$.extend(cur_frm.cscript, new erpnext.crm.Opportunity({frm: cur_frm}));
cur_frm.cscript.item_code = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if (d.item_code) {
return frappe.call({
method: "erpnext.crm.doctype.opportunity.opportunity.get_item_details",
args: {"item_code":d.item_code},
callback: function(r, rt) {
if(r.message) {
$.each(r.message, function(k, v) {
frappe.model.set_value(cdt, cdn, k, v);
});
refresh_field('image_view', d.name, 'items');
}
}
})
}
}
|
JavaScript
| 0.000001 |
@@ -1583,32 +1583,64 @@
function(frm) %7B%0A
+%09%09frm.trigger('setup_queries');%0A
%09%09frm.toggle_req
|
99728085254b080aa071983316de81195cf29375
|
Allow aggregation names as field names (if quoted). Resolves #4049
|
frontend/src/metabase/lib/expressions/index.js
|
frontend/src/metabase/lib/expressions/index.js
|
import _ from "underscore";
import { mbqlEq } from "../query/util";
import { VALID_OPERATORS, VALID_AGGREGATIONS } from "./tokens";
export { VALID_OPERATORS, VALID_AGGREGATIONS } from "./tokens";
export function formatAggregationName(aggregationOption) {
return VALID_AGGREGATIONS.get(aggregationOption.short);
}
function formatIdentifier(name) {
return /^\w+$/.test(name) ?
name :
JSON.stringify(name);
}
export function formatMetricName(metric) {
return formatIdentifier(metric.name);
}
export function formatFieldName(field) {
return formatIdentifier(field.display_name);
}
export function formatExpressionName(name) {
return formatIdentifier(name);
}
// move to query lib
export function isExpression(expr) {
return isMath(expr) || isAggregation(expr) || isField(expr) || isMetric(expr) || isExpressionReference(expr);
}
export function isField(expr) {
return Array.isArray(expr) && expr.length === 2 && mbqlEq(expr[0], 'field-id') && typeof expr[1] === 'number';
}
export function isMetric(expr) {
// case sensitive, unlike most mbql
return Array.isArray(expr) && expr.length === 2 && expr[0] === "METRIC" && typeof expr[1] === 'number';
}
export function isMath(expr) {
return Array.isArray(expr) && VALID_OPERATORS.has(expr[0]) && _.all(expr.slice(1), isValidArg);
}
export function isAggregation(expr) {
return Array.isArray(expr) && VALID_AGGREGATIONS.has(expr[0]) && _.all(expr.slice(1), isValidArg);
}
export function isExpressionReference(expr) {
return Array.isArray(expr) && expr.length === 2 && mbqlEq(expr[0], 'expression') && typeof expr[1] === 'string';
}
export function isValidArg(arg) {
return isExpression(arg) || isField(arg) || typeof arg === 'number';
}
|
JavaScript
| 0 |
@@ -189,24 +189,86 @@
./tokens%22;%0A%0A
+const RESERVED_WORDS = new Set(VALID_AGGREGATIONS.values());%0A%0A
export funct
@@ -440,16 +440,45 @@
st(name)
+ && !RESERVED_WORDS.has(name)
?%0A
|
0a682c5e50345a93f242463f16416feb9a6950ed
|
add missing bower bump
|
build/tasks/prepare-release.js
|
build/tasks/prepare-release.js
|
var gulp = require('gulp');
var runSequence = require('run-sequence');
var paths = require('../paths');
var changelog = require('conventional-changelog');
var fs = require('fs');
var bump = require('gulp-bump');
gulp.task('bump-version', function(){
return gulp.src(['./package.json'])
.pipe(bump({type:'patch'})) //major|minor|patch|prerelease
.pipe(gulp.dest('./'));
});
gulp.task('changelog', function(callback) {
var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));
return changelog({
repository: pkg.repository.url,
version: pkg.version,
file: paths.doc + '/CHANGELOG.md'
}, function(err, log) {
fs.writeFileSync(paths.doc + '/CHANGELOG.md', log);
});
});
gulp.task('prepare-release', function(callback){
return runSequence(
'build',
'lint',
'bump-version',
'doc',
'changelog',
callback
);
});
|
JavaScript
| 0.000001 |
@@ -279,16 +279,32 @@
ge.json'
+, './bower.json'
%5D)%0A .
|
52c6c77035d6c5f37e64ab6eb94c6defd0fba110
|
Fix timeslider in case there are zero hit
|
quamerdes/static/js/views/search/timeslider.js
|
quamerdes/static/js/views/search/timeslider.js
|
define([
'jquery',
'underscore',
'backbone',
'd3',
'app',
'text!../../../templates/search/timeslider.html'
],
function($, _, Backbone, d3, app, timeSliderTemplate){
var TimeSliderView = Backbone.View.extend({
initialize: function(options){
// Control visibility on init. Element is shown on first query.
this.is_visible = true;
app.vent.once('QueryInput:input', this.toggleVisibility, this);
this.date_facet_name = options.date_facet;
this.model.on('change:dateHistogram', this.updateFacetValues, this);
this.model.on('change:interval', function() {
var date_stats = this.model.get('aggregations')[DATE_STATS_AGGREGATION];
if (this.model.get('interval')) {
this.updateSliderLabels(date_stats.min, date_stats.max);
}
}, this);
app.vent.on('model:redraw:' + this.model.get('name'), function(){
var histogram = this.model.get('dateHistogram');
if(histogram.length < 1){
return;
}
var min = histogram[0].time;
var max = histogram[histogram.length - 1].time;
this.updateSliderLabels(min, max);
}, this);
this.convertTime = {
year: {
display: d3.time.format('%Y'),
interval: d3.time.year
},
month: {
display: d3.time.format('%b. %Y'),
interval: d3.time.month
},
week: {
display: d3.time.format('%e %b. %Y'),
interval: d3.time.week
},
day: {
display: d3.time.format('%e %b. %Y'),
interval: d3.time.day
}
};
},
render: function(){
if (DEBUG) console.log('TimeSliderView:render');
var self = this;
this.$el.html(_.template(timeSliderTemplate));
this.slider_lower_label = this.$el.find('.slider-lower-label');
this.slider_upper_label = this.$el.find('.slider-upper-label');
this.timeslider = this.$el.find('.slider').slider({
range: true,
step: 1,
//animate: 'slow',
start: function(event, ui){
// set start value for logging purposes
self.startValue = ui.value;
},
slide: function(event, ui){
self.updateHandleLables(event, ui, self);
},
stop: function(event, ui){
self.updateHandleLables(event, ui, self);
self.changeFilter(event, ui, self.date_facet_name);
app.vent.trigger('Logging:clicks', {
action: 'daterange_facet',
fromDateMs: self.startValue,
toDateMs: ui.value,
modelName: self.model.get('name')
});
}
});
return this;
},
updateHandleLables: function(event, ui, self) {
var interval = self.model.get('interval');
// Get the position of the moved handle to determine the
// position of the handle's label
var handle_left_px = parseFloat($(ui.handle).css('left'));
var handle_width_px = $(ui.handle).width();
var handle_center_px = handle_left_px + (handle_width_px / 2.0);
// Determine which handle is being moved and replace the text
if (ui.value === ui.values[0]) {
self.slider_lower_label.text(self.convertTime[interval].display(new Date(ui.value)));
var label_width_px = self.slider_lower_label.width() / 2.0;
self.slider_lower_label.css('left', (handle_center_px - label_width_px) + 'px');
}
else {
self.slider_upper_label.text(self.convertTime[interval].display(new Date(ui.value)));
var label_width_px = self.slider_upper_label.width() / 2.0;
self.slider_upper_label.css('left', (handle_center_px - label_width_px) + 'px');
}
},
updateSliderLabels: function(min, max, interval){
if (DEBUG) console.log('TimeSliderView:updateSliderLabels');
if(!interval) interval = this.model.get('interval');
min = this.convertTime[interval].display(new Date(min));
max = this.convertTime[interval].display(new Date(max));
this.$el.find('.slider-lower-val').html(min);
this.$el.find('.slider-upper-val').html(max);
},
updateFacetValues: function(){
if (DEBUG) console.log('TimeSliderView:updateFacetValues');
var date_stats = this.model.get('aggregations')[DATE_STATS_AGGREGATION];
this.min = date_stats.min;
this.max = date_stats.max;
this.timeslider.slider('option', 'min', this.min);
this.timeslider.slider('option', 'max', this.max);
this.timeslider.slider('option', 'values', [this.min, this.max]);
this.updateSliderLabels(this.min, this.max);
},
changeFilter: function(event, ui, facet){
var self = this;
var min = new Date(ui.values[0]);
var max = new Date(ui.values[1]);
if (DEBUG) console.log('TimeSliderView:changeFilter', [min, max]);
var interval = this.model.get('interval');
// Round down to the nearest date for the given interval,
// for exmpale, when interval is 'year', 2000-04-05T14:13 will
// become 2000-01-01T00:00.
min = this.convertTime[interval].interval.floor(min);
// Round up to the nearest date for the given interval
max = this.convertTime[interval].interval.ceil(max);
// Perform the actual query
this.model.modifyQueryFilter(this.date_facet_name, [min, max], true);
// To prevent the date range slider from updating the min and max
// values as soon as the user moves a handle, we temporary switch
// off the facet value change listener.
this.model.off('change:dateHistogram', this.updateFacetValues, this);
// Update the facet values and set the slider to min/max positions directly after
// the user submits a new keyword query
app.vent.once('QueryInput:input:' + this.model.get('name'), function(){
console.log('!!!!!!!!!!!');
//self.updateFacetValues();
self.model.on('change:dateHistogram', self.updateFacetValues, self);
});
},
toggleVisibility: function(){
if (DEBUG) console.log('TimeSeriesView:toggleVisibility');
if(this.is_visible){
this.$el.hide();
this.is_visible = false;
}
else {
this.$el.show();
this.is_visible = true;
}
this.$el.show();
return this;
}
});
return TimeSliderView;
});
|
JavaScript
| 0.000013 |
@@ -734,32 +734,85 @@
_AGGREGATION%5D;%0A%0A
+ if (date_stats.count === 0) return;%0A%0A
@@ -5178,32 +5178,144 @@
_AGGREGATION%5D;%0A%0A
+ // Fixme: hide timeslider when there are zero hits%0A if (date_stats.count === 0) return;%0A%0A
this
@@ -7015,96 +7015,8 @@
()%7B%0A
- console.log('!!!!!!!!!!!');%0A //self.updateFacetValues();%0A
|
abd7b4163a95448c8d8c35ff17e2498ad10fbf4b
|
Add support for JS importers/generators (api)
|
api/data.js
|
api/data.js
|
const fse = require('fs-extra');
const got = require('got');
const unzipper = require('unzipper');
const chalk = require('chalk');
const debug = require('./utils/debug.js');
const db = require('./db.js');
// Download data into temporary folder.
function download() {
return new Promise(async (resolve) => {
debug.info('Starting data update');
debug.time('data-update');
debug.time('data-download', 'Downloading data');
// Download and extract GTFS data into temporary folder.
await got.stream('http://peatus.ee/gtfs/gtfs.zip').pipe(unzipper.Extract({ path: 'tmp' })).promise();
// Correct GTFS filetypes.
for (const file of await fse.readdir('tmp')) await fse.rename(`tmp/${file}`, `tmp/${file.substr(0, file.lastIndexOf('.'))}.csv`);
// Download and write Elron stop data into temporary folder.
let data = 'name,lat,lng\n';
for (const stop of JSON.parse((await got('https://elron.ee/api/v1/stops')).body).data) data += `${stop.peatus},${stop.latitude},${stop.longitude}\n`;
await fse.writeFile('tmp/elron.csv', data);
debug.timeEnd('data-download', 'Downloaded data');
resolve();
});
};
// Run all SQL files in a folder.
function prepare(path, msgIncomplete, msgComplete) {
return new Promise(async (resolve) => {
for (const file of await fse.readdir(path)) {
const name = file.slice(0, -4);
debug.time(`data-prepare-${name}`, `${msgIncomplete} ${chalk.blue(name)}`);
await db.query((await fse.readFile(`${path}/${file}`)).toString());
debug.timeEnd(`data-prepare-${name}`, `${msgComplete} ${chalk.blue(name)}`);
}
resolve();
});
}
// Start data update.
function update() {
return new Promise(async (resolve) => {
await download();
await prepare('sql/importers', 'Importing', 'Imported');
await prepare('sql/generators', 'Generating', 'Generated');
debug.timeEnd('data-update', 'Data update completed');
resolve();
});
};
module.exports = {
update
};
|
JavaScript
| 0 |
@@ -1339,19 +1339,20 @@
le.s
+p
li
-ce(0, -4)
+t('.')%5B0%5D
;%0A%09%09
@@ -1435,16 +1435,78 @@
%7D%60);%0A%09%09%09
+%0A%09%09%09switch (file.split('.')%5B1%5D) %7B%0A%09%09%09%09%0A%09%09%09%09case 'sql': %7B%0A%09%09%09%09%09
await db
@@ -1565,16 +1565,133 @@
ing());%0A
+%09%09%09%09%09break;%0A%09%09%09%09%7D%0A%09%09%09%09%0A%09%09%09%09case 'js': %7B%0A%09%09%09%09%09await (require(%60./$%7Bpath%7D/$%7Bfile%7D%60))();%0A%09%09%09%09%09break;%0A%09%09%09%09%7D%0A%09%09%09%09%0A%09%09%09%7D%0A%09%09%09%0A
%09%09%09debug
|
03da35f5a70360d93036c72c09fde19de0804b46
|
fix variable name conflict
|
src/index.js
|
src/index.js
|
// cheap way of doing AA
c.width = 32e2, c.height = 18e2, // 16:9 aspect ratio
//c.width = 192, c.height = 108; // battery saving
s = new AudioContext;
c = s.createScriptProcessor(512, t = 1, K = 1);
c.connect(s.destination);
// bass & arpeggio sequencers
// (compresses better when inlined)
// s=(notes,octave,rate,len) =>
// 31 & t * Math.pow(2, notes[(t>>rate) % len] / 12 - octave)
// music
X = c.onaudioprocess = c =>
c.outputBuffer.getChannelData(i=0).map(_ =>
c.outputBuffer.getChannelData(0)[i++] =
(
(
// kick drum
((
// envelope
K = 1e4 / (
t & 16382
// nice pattern variation if it fits
/* * (
(t>>14) % 16 - 15 ? 1 : .75
)*/
)
) & 1) * 30
// bass
+ (31 & t * Math.pow(2,
// melody
'7050'
[(t>>
// rate
17
) %
// melody length
4
] / 12 -
// octave
4
)) / K
)
// turn off above instruments after a while
* !(t>>22)
// hihat TODO improve/golf envelope
+ (t % 100 * t & 128) * Math.min(.2, (1e1 / ((t>>3) % 512)))
// enable hihat after t>>19
* !!(t>>19)
// arpeggio
+ (31 & t * Math.pow(2, (
// melody
((t>>17) % 2 ? '027' : '037')
)[(t>>(
// rate
13 - 3 * (t>>20) % 12
)) %
// melody length
4
] / 12 -
// octave
1
)) / K
// enable arpeggio after t>>20
* !!(t>>20)
) * (
// fade out
X = Math.min(1, Math.max(1e-9, 1e1-t++/5e5))
) / 200
);
// gfx
g = c.getContext`webgl`;
P = g.createProgram();
// NOTE: 2nd argument to drawArrays used to be 0, but undefined works
r = t => g.drawArrays(g.TRIANGLE_FAN,
// x-res, y-res, time (s), fade out
g.uniform4f(g.getUniformLocation(P, 'a'), c.width, c.height, t / 1e3, X),
3,
// 1, 0, kick envelope, unused
g.uniform4f(g.getUniformLocation(P, 'b'), 1, 0, .2/K, requestAnimationFrame(r))
);
// vertex shader
g.shaderSource(S=g.createShader(g.VERTEX_SHADER), require("./vertex.glsl"));
g.compileShader(S);g.attachShader(P,S);
// fragment shader
g.shaderSource(S=g.createShader(g.FRAGMENT_SHADER), require("./fragment.glsl"));
g.compileShader(S);g.attachShader(P,S);
// Log compilation errors
// if (!g.getShaderParameter(S, 35713)) { // COMPILE_STATUS = 35713
// throw g.getShaderInfoLog(S);
// }
g.bindBuffer(g.ARRAY_BUFFER, g.createBuffer(c.parentElement.style.margin = 0));
// 1st argument to enableVertexAttribArray used to be 0, but undefined works
// 1st argument to vertexAttribPointer used to be 0, but undefined works
g.vertexAttribPointer(
g.enableVertexAttribArray(
g.bufferData(g.ARRAY_BUFFER, Int8Array.of(-3, 1, 1, -3, 1, 1), g.STATIC_DRAW)
),
2, g.BYTE, r(c.style.height = '1e2vh'), g.linkProgram(P), g.useProgram(P));
|
JavaScript
| 0.002534 |
@@ -146,17 +146,17 @@
ontext;%0A
-c
+a
= s.cre
@@ -194,17 +194,17 @@
K = 1);%0A
-c
+a
.connect
@@ -398,17 +398,17 @@
sic%0AX =
-c
+a
.onaudio
@@ -421,16 +421,16 @@
s =
-c
+a
=%3E%0A
-c
+a
.out
@@ -472,17 +472,17 @@
=%3E%0A
-c
+a
.outputB
|
5975b619f07489746759030f9ec8e6c5d599e14c
|
remove debug logging
|
src/index.js
|
src/index.js
|
import ReactDOM from 'react-dom'
import React from 'react'
import { List } from 'immutable'
import App from './app.js'
// pull in and parse entries from the API here...
// using testdata for now
const testEntries = List([
{ name: 'testuser1', numBytes: 1e9, lastUpdated: new Date(), groups: ['group1']},
{ name: 'testuser2', numBytes: 1e9*5, lastUpdated: new Date(), groups: ['group2']},
{ name: 'testuser3', numBytes: 1e9*2, lastUpdated: new Date(), groups: ['group1']},
{ name: 'testuser9', numBytes: 1e9*0.5, lastUpdated: new Date(), groups: ['group1', 'group2']},
{ name: 'testuser5', numBytes: 1e9*0.2, lastUpdated: new Date(1000), groups: ['group1']},
])
let sort = 'uploaded'
let groupFilters = []
let render = () => { }
const onSortChange = (e) => {
sort = e.target.value
render()
}
const onGroupFilter = (e) => {
if (e.target.value === 'nofilter') {
groupFilters = []
} else {
groupFilters = [e.target.value]
}
render()
}
render = () => {
console.log(groupFilters)
console.log(sort)
ReactDOM.render(
<App
entries={testEntries}
groupFilters={groupFilters}
sort={sort}
onSort={onSortChange}
onGroupFilter={onGroupFilter}
/>,
document.getElementById('react-root')
)
}
render()
|
JavaScript
| 0.000002 |
@@ -967,54 +967,8 @@
%3E %7B%0A
-%09console.log(groupFilters)%0A%09console.log(sort)%0A
%09Rea
|
052da6bfd65b15005a303dd003c6bf2182a46193
|
Fix key form
|
src/index.js
|
src/index.js
|
import rp from 'request-promise';
import isFunction from 'lodash.isfunction';
import Stream from './stream';
class Instagram {
/**
* Create a new instance of instagram class
* @param {Object} options
* @param {String} options.clientId
* @param {String} options.accessToken
*/
constructor(options = {}) {
this.baseApi = 'https://api.instagram.com/v1/';
this.clientId = options.clientId;
this.accessToken = options.accessToken;
}
/**
* Send a request
* @param {String} type
* @param {String} endpoint
* @param {Object} options
* @param {Function} callback
* @return {Promise}
* @private
*/
request(type, endpoint, options = {}, callback) {
if (isFunction(options)) {
callback = options;
options = {};
}
let key = 'qs';
let accessToken = this.accessToken;
if (options.accessToken) {
accessToken = options.accessToken;
delete options.accessToken; // eslint-disable-line no-param-reassign
}
if (type === 'POST') {
key = 'body';
}
return rp({
method: type,
uri: `${this.baseApi}${endpoint}`,
[key]: Object.assign({
access_token: accessToken,
}, options),
json: true,
})
.then((data) => {
if (isFunction(callback)) {
callback(null, data);
}
return data;
})
.catch((err) => {
const error = err.error || err;
if (isFunction(callback)) {
return callback(error);
}
throw error;
});
}
/**
* Send a GET request
* @param {String} endpoint
* @param {Object} [options]
* @param {Function} [callback]
* @return {Promise}
*/
get(endpoint, options, callback) {
return this.request('GET', endpoint, options, callback);
}
/**
* Send a POST request
* @param {String} endpoint
* @param {Object} [options]
* @param {Function} [callback]
* @return {Promise}
*/
post(endpoint, options, callback) {
return this.request('POST', endpoint, options, callback);
}
/**
* Send a DELETE request
* @param {String} endpoint
* @param {Object} [options]
* @param {Function} [callback]
* @return {Promise}
*/
delete(endpoint, options, callback) {
return this.request('DELETE', endpoint, options, callback);
}
/**
* Create a new instagram stream
* @param {String} endpoint
* @param {Object} [options]
* @return {EventEmitter}
*/
stream(endpoint, options) {
return new Stream(this, endpoint, options);
}
}
export default Instagram;
|
JavaScript
| 0.00013 |
@@ -1038,12 +1038,12 @@
= '
-body
+form
';%0A
|
503e28e5c58438a6b04d66b240a09cc06afa2778
|
update core to be the main export, plugins add onto that
|
src/index.js
|
src/index.js
|
module.exports = {
core: require('./core'),
extras: require('./extras'),
filters: require('./filters'),
interaction: require('./interaction'),
loaders: require('./loaders'),
spine: require('./spine'),
text: require('./text')
};
|
JavaScript
| 0 |
@@ -1,8 +1,19 @@
+var core =
module.e
@@ -25,68 +25,59 @@
s =
-%7B%0A core: require('./core'),%0A
+require('./core');%0A%0A// plugins:%0Acore.
extras
-:
req
@@ -64,32 +64,34 @@
e.extras
+ =
require('./extr
@@ -98,29 +98,31 @@
as')
-,%0A
+;%0Acore.
filters
-:
+
+=
req
@@ -138,22 +138,23 @@
ilters')
-,%0A
+;%0Acore.
interact
@@ -156,20 +156,21 @@
eraction
-:
+
+=
require
@@ -190,29 +190,31 @@
on')
-,%0A
+;%0Acore.
loaders
-:
+
+=
req
@@ -234,20 +234,21 @@
rs')
-,%0A
+;%0Acore.
spine
-:
+
@@ -244,32 +244,33 @@
.spine
+=
require('./spin
@@ -276,19 +276,19 @@
ne')
-,%0A
+;%0Acore.
text
-:
@@ -293,16 +293,18 @@
+ =
require
@@ -317,8 +317,6 @@
xt')
-%0A%7D
;%0A
|
13c3b7718e3f89c2b0822a493070faa6cfb6cc46
|
move isInitialized to aurelia-pal (#14)
|
src/index.js
|
src/index.js
|
import {initializePAL} from 'aurelia-pal';
import {_PLATFORM} from './platform';
import {_FEATURE} from './feature';
import {_DOM} from './dom';
import {_ensureCustomEvent} from './custom-event';
import {_ensureFunctionName} from './function-name';
import {_ensureHTMLTemplateElement} from './html-template-element';
import {_ensureElementMatches} from './element-matches';
import {_ensureClassList} from './class-list';
import {_ensurePerformance} from './performance';
let isInitialized = false;
/**
* Initializes the PAL with the Browser-targeted implementation.
*/
export function initialize(): void {
if (isInitialized) {
return;
}
isInitialized = true;
_ensureCustomEvent();
_ensureFunctionName();
_ensureHTMLTemplateElement();
_ensureElementMatches();
_ensureClassList();
_ensurePerformance();
initializePAL((platform, feature, dom) => {
Object.assign(platform, _PLATFORM);
Object.assign(feature, _FEATURE);
Object.assign(dom, _DOM);
(function(global) {
global.console = global.console || {};
let con = global.console;
let prop;
let method;
let empty = {};
let dummy = function() {};
let properties = 'memory'.split(',');
let methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' +
'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' +
'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',');
while (prop = properties.pop()) if (!con[prop]) con[prop] = empty;
while (method = methods.pop()) if (!con[method]) con[method] = dummy;
})(platform.global);
if (platform.global.console && typeof console.log === 'object') {
['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function(method) {
console[method] = this.bind(console[method], console);
}, Function.prototype.call);
}
Object.defineProperty(dom, 'title', {
get: function() {
return document.title;
},
set: function(value) {
document.title = value;
}
});
Object.defineProperty(dom, 'activeElement', {
get: function() {
return document.activeElement;
}
});
Object.defineProperty(platform, 'XMLHttpRequest', {
get: function() {
return platform.global.XMLHttpRequest;
}
});
});
}
|
JavaScript
| 0 |
@@ -14,16 +14,31 @@
alizePAL
+, isInitialized
%7D from '
@@ -484,36 +484,8 @@
';%0A%0A
-let isInitialized = false;%0A%0A
/**%0A
@@ -632,33 +632,8 @@
%7D%0A%0A
- isInitialized = true;%0A%0A
_e
|
3d7d31b6e5b4f2fadd0cd271ce4651620544fe97
|
change login route to signup
|
src/index.js
|
src/index.js
|
import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App'
import CreatePost from './components/CreatePost'
import CreateUser from './components/CreateUser'
import { Router, Route, browserHistory } from 'react-router'
import ApolloClient, { createNetworkInterface } from 'apollo-client'
import { ApolloProvider } from 'react-apollo'
import 'tachyons'
const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })
// use the auth0IdToken in localStorage for authorized requests
networkInterface.use([{
applyMiddleware (req, next) {
if (!req.options.headers) {
req.options.headers = {}
}
// get the authentication token from local storage if it exists
if (localStorage.getItem('auth0IdToken')) {
req.options.headers.authorization = `Bearer ${localStorage.getItem('auth0IdToken')}`
}
next()
},
}])
const client = new ApolloClient({ networkInterface })
ReactDOM.render((
<ApolloProvider client={client}>
<Router history={browserHistory}>
<Route path='/' component={App} />
<Route path='create' component={CreatePost} />
<Route path='login' component={CreateUser} />
</Router>
</ApolloProvider>
),
document.getElementById('root')
)
|
JavaScript
| 0 |
@@ -1176,13 +1176,14 @@
th='
-login
+signup
' co
|
3cf13fd8fa5e742a87e7e37759b009932ea73369
|
add catch nextable
|
src/index.js
|
src/index.js
|
import _ from 'lodash';
const Next = async ({
for: _for,
each,
shouldNext,
next,
catch: _catch,
} = {}) => {
try {
if (_for && each) {
const results = _.castArray(await _for());
for (const [index, result] of results.entries()) {
try {
const eachNext = await each(result, index);
await Next(eachNext);
} catch (err) {
if (_catch) {
await _catch(err);
} else {
throw err;
}
}
}
}
if (shouldNext) {
const shouldNextOrNot = await shouldNext();
if (!shouldNextOrNot) {
return;
}
}
if (next) {
await Next(await next());
}
} catch (err) {
if (_catch) {
await _catch(err);
} else {
throw err;
}
}
}
export default Next;
|
JavaScript
| 0.000011 |
@@ -409,32 +409,43 @@
await
+Next(await
_catch(err);%0A
@@ -435,24 +435,25 @@
_catch(err)
+)
;%0A
@@ -752,24 +752,35 @@
await
+Next(await
_catch(err);
@@ -778,16 +778,17 @@
tch(err)
+)
;%0A %7D
|
5d0a00389fbab2ef9bee5777fbd8fbc586a65d95
|
Add table component to components index
|
src/index.js
|
src/index.js
|
'use strict';
export default {
Container : require('./container'),
Row : require('./row'),
Col : require('./col'),
IconButton : require('./icon-button'),
AppHeader : require('./layout/side-nav'),
TopNav : require('./layout/top-nav'),
SideNav : require('./layout/side-nav'),
Modal : require('./modal'),
Collapsible : require('./collapsible/collapsible'),
// Utilities
LayeredComponentMixin : require('./mixins/layered-component'),
TransitionIn : require('./transition-in'),
};
|
JavaScript
| 0.000001 |
@@ -317,16 +317,47 @@
dal'),%0A%0A
+ Table : require('./table'),%0A%0A
Collap
|
07f318a4e323755982af8207430f77a2c975e8fb
|
update surface defaults tests
|
test/jasmine/tests/surface_test.js
|
test/jasmine/tests/surface_test.js
|
var Surface = require('@src/traces/surface');
describe('Test surface', function() {
'use strict';
describe('supplyDefaults', function() {
var supplyDefaults = Surface.supplyDefaults;
var defaultColor = '#444',
layout = {};
var traceIn, traceOut;
beforeEach(function() {
traceOut = {};
});
it('should set \'visible\' to false if \'z\' isn\'t provided', function() {
traceIn = {};
supplyDefaults(traceIn, traceOut, defaultColor, layout);
expect(traceOut.visible).toBe(false);
});
it('should fill \'x\' and \'y\' if not provided', function() {
traceIn = {
z: [[1,2,3], [2,1,2]]
};
supplyDefaults(traceIn, traceOut, defaultColor, layout);
expect(traceOut.x).toEqual([0,1,2]);
expect(traceOut.y).toEqual([0,1]);
});
it('should coerce \'project\' if contours or highlight lines are enabled', function() {
traceIn = {
z: [[1,2,3], [2,1,2]],
contours: {
x: { show: true }
}
};
supplyDefaults(traceIn, traceOut, defaultColor, layout);
expect(traceOut.contours.x.project).toEqual({ x: false, y: false, z: false });
expect(traceOut.contours.y).toEqual({ show: false, highlight: false });
expect(traceOut.contours.z).toEqual({ show: false, highlight: false });
});
it('should coerce contour style attributes if contours lines are enabled', function() {
traceIn = {
z: [[1,2,3], [2,1,2]],
contours: {
x: { show: true }
}
};
supplyDefaults(traceIn, traceOut, defaultColor, layout);
expect(traceOut.contours.x.color).toEqual('#000');
expect(traceOut.contours.x.width).toEqual(2);
expect(traceOut.contours.x.usecolormap).toEqual(false);
['y', 'z'].forEach(function(ax) {
expect(traceOut.contours[ax].color).toBeUndefined();
expect(traceOut.contours[ax].width).toBeUndefined();
expect(traceOut.contours[ax].usecolormap).toBeUndefined();
});
});
it('should coerce colorscale and colorbar attributes', function() {
traceIn = {
z: [[1,2,3], [2,1,2]]
};
supplyDefaults(traceIn, traceOut, defaultColor, layout);
expect(traceOut.cauto).toBe(true);
expect(traceOut.cmin).toBeUndefined();
expect(traceOut.cmax).toBeUndefined();
expect(traceOut.colorscale).toEqual([
[0, 'rgb(5,10,172)'],
[0.35, 'rgb(106,137,247)'],
[0.5, 'rgb(190,190,190)'],
[0.6, 'rgb(220,170,132)'],
[0.7, 'rgb(230,145,90)'],
[1, 'rgb(178,10,28)']
]);
expect(traceOut.showscale).toBe(true);
expect(traceOut.colorbar).toBeDefined();
});
it('should coerce \'c\' attributes with \'z\' if \'c\' isn\'t present', function() {
traceIn = {
z: [[1,2,3], [2,1,2]],
zauto: false,
zmin: 0,
zmax: 10
};
supplyDefaults(traceIn, traceOut, defaultColor, layout);
expect(traceOut.cauto).toEqual(false);
expect(traceOut.cmin).toEqual(0);
expect(traceOut.cmax).toEqual(10);
});
it('should coerce \'c\' attributes with \'c\' values regardless of `\'z\' if \'c\' is present', function() {
traceIn = {
z: [[1,2,3], [2,1,2]],
zauto: false,
zmin: 0,
zmax: 10,
cauto: true,
cmin: -10,
cmax: 20
};
supplyDefaults(traceIn, traceOut, defaultColor, layout);
expect(traceOut.cauto).toEqual(true);
expect(traceOut.cmin).toEqual(-10);
expect(traceOut.cmax).toEqual(20);
});
it('should default \'c\' attributes with if \'surfacecolor\' is present', function() {
traceIn = {
z: [[1,2,3], [2,1,2]],
surfacecolor: [[2,1,2], [1,2,3]],
zauto: false,
zmin: 0,
zmax: 10
};
supplyDefaults(traceIn, traceOut, defaultColor, layout);
expect(traceOut.cauto).toEqual(true);
expect(traceOut.cmin).toBeUndefined();
expect(traceOut.cmax).toBeUndefined();
});
});
});
|
JavaScript
| 0 |
@@ -40,16 +40,48 @@
ace');%0A%0A
+var Lib = require('@src/lib');%0A%0A
%0Adescrib
@@ -1178,39 +1178,364 @@
x: %7B
- show: true %7D%0A %7D
+%7D,%0A y: %7B show: true %7D,%0A z: %7B show: false, highlight: false %7D%0A %7D%0A %7D;%0A%0A var fullOpts = %7B%0A show: false,%0A highlight: true,%0A project: %7B x: false, y: false, z: false %7D,%0A highlightcolor: '#444',%0A highlightwidth: 2
%0A
@@ -1658,16 +1658,8 @@
rs.x
-.project
).to
@@ -1668,40 +1668,16 @@
ual(
-%7B x: false, y: false, z: false %7D
+fullOpts
);%0A
@@ -1727,42 +1727,174 @@
ual(
-%7B show: false, highlight: false
+Lib.extendDeep(%7B%7D, fullOpts, %7B%0A show: true,%0A color: '#444',%0A width: 2,%0A usecolormap: false%0A
%7D)
+)
;%0A
@@ -2376,11 +2376,11 @@
l('#
-000
+444
');%0A
|
6052c3305a6d47b52ccf29e02fbb0e8a77c9289c
|
Fix all tests for iOS private browsing mode
|
test/tests/superstore-sync.test.js
|
test/tests/superstore-sync.test.js
|
var prefix = '';
var tests = {};
try {
localStorage.test = 'test';
localStorage.removeItem('test');
} catch (err) {
if (err.code == 22) prefix = '// ';
}
function getLocalStorage(key) {
return localStorage[key];
};
function setLocalStorage(key, val) {
return localStorage[key] = val;
};
tests["setUp"] = function() {
localStorage.clear();
};
tests["Should be able to set and get data against a key"] = function() {
superstoreSync.set('keyOne', 'value1');
var val = superstoreSync.get('keyOne');
assert.equals('value1', val);
};
tests[prefix + "Should be able to read things (twice) from local storage"] = function() {
setLocalStorage("keyTwo", 3884);
assert.equals(getLocalStorage("keyTwo"), 3884);
var val = superstoreSync.get('keyTwo');
assert.equals(3884, val);
var val2 = superstoreSync.get('keyTwo');
assert.equals(3884, val2);
};
tests[prefix + "Should be able to unset things"] = function() {
setLocalStorage("keyThree", "Hello");
var val = superstoreSync.unset('keyThree');
assert.equals(undefined, getLocalStorage("keyThree"));
};
tests["Getting an unset key should return a nully value"] = function() {
var val = superstoreSync.get("keySixth");
assert.equals(val, undefined);
};
tests[prefix + "Should json encode and decode objects"] = function() {
var obj = {
test: [1,4,6,7]
};
superstoreSync.set('keySeventh', obj);
assert.equals(JSON.stringify(obj), getLocalStorage("keySeventh"));
};
tests[prefix + "#clear(something) clears only our namespaced data"] = function() {
superstoreSync.set('other', '123');
superstoreSync.set('prefixKeyTenth', 'A');
superstoreSync.set('prefixKeyEleventh', 'B');
superstoreSync.clear('prefixKey');
assert.equals(undefined, getLocalStorage("prefixKeyTenth"));
assert.equals(undefined, superstoreSync.get("prefixKeyTenth"));
assert.equals(undefined, getLocalStorage("prefixKeyEleventh"));
assert.equals(undefined, superstoreSync.get("prefixKeyEleventh"));
assert.equals('"123"', getLocalStorage("other"));
assert.equals('123', superstoreSync.get("other"));
};
tests[prefix + "#clear() clears all data"] = function() {
superstoreSync.set('other', '123');
superstoreSync.set('prefixKeyTwelth', 'C');
superstoreSync.clear();
assert.equals(undefined, getLocalStorage("prefixKeyTwelth"));
assert.equals(undefined, getLocalStorage("other"));
};
tests["watch for changes in other processes"] = function() {
superstoreSync.set('key13', 'A');
var event = new CustomEvent("storage");
event.key = "key13";
event.newValue = "\"B\"";
window.dispatchEvent(event);
var val = superstoreSync.get('key13');
assert.equals(val, 'B');
};
buster.testCase('superstore-sync', tests);
|
JavaScript
| 0.000002 |
@@ -10,16 +10,47 @@
x = '';%0A
+var buggyLocalStorage = false;%0A
var test
@@ -183,16 +183,44 @@
'// ';%0A
+ buggyLocalStorage = true;%0A
%7D%0A%0Afunct
@@ -312,24 +312,47 @@
ey, val) %7B%0A
+ if (buggyLocalStorage)
return loca
@@ -430,24 +430,325 @@
lear();%0A%7D;%0A%0A
+tests%5B%22Removing a key before it's set should be harmless%22%5D = function() %7B%0A var exceptionThrown = false;%0A try %7B%0A superstoreSync.unset('keyUnset');%0A %7D catch (e) %7B%0A exceptionThrown = true;%0A %7D%0A assert.equals(false, exceptionThrown);%0A assert.equals(undefined, getLocalStorage('keyUnset'));%0A%7D;%0A%0A
tests%5B%22Shoul
@@ -1840,33 +1840,24 @@
;%0A%7D;%0A%0Atests%5B
-prefix +
%22#clear(some
@@ -2085,71 +2085,8 @@
);%0A%0A
- assert.equals(undefined, getLocalStorage(%22prefixKeyTenth%22));%0A
as
@@ -2151,74 +2151,8 @@
));%0A
- assert.equals(undefined, getLocalStorage(%22prefixKeyEleventh%22));%0A
as
@@ -2220,60 +2220,8 @@
));%0A
- assert.equals('%22123%22', getLocalStorage(%22other%22));%0A
as
@@ -2261,32 +2261,252 @@
.get(%22other%22));%0A
+%0A if (!buggyLocalStorage) %7B%0A assert.equals(undefined, getLocalStorage(%22prefixKeyEleventh%22));%0A assert.equals('%22123%22', getLocalStorage(%22other%22));%0A assert.equals(undefined, getLocalStorage(%22prefixKeyTenth%22));%0A %7D%0A
%7D;%0A%0Atests%5Bprefix
@@ -2499,25 +2499,16 @@
%0A%0Atests%5B
-prefix +
%22#clear(
@@ -2649,24 +2649,179 @@
c.clear();%0A%0A
+ assert.equals(undefined, superstoreSync.get(%22prefixKeyTwelth%22));%0A assert.equals(undefined, superstoreSync.get(%22other%22));%0A%0A if (!buggyLocalStorage) %7B%0A
assert.equ
@@ -2864,32 +2864,34 @@
ixKeyTwelth%22));%0A
+
assert.equals(
@@ -2924,24 +2924,28 @@
(%22other%22));%0A
+ %7D%0A
%7D;%0A%0Atests%5B%22w
|
7d0e70947ecc322024000e0b48e2a061115cf438
|
Use fixed method names
|
test/unit/js/translations-tests.js
|
test/unit/js/translations-tests.js
|
const { expect } = require('chai')
const translations = require('../../../app/js/translations')
describe('translations', function() {
beforeEach(function() {
this.translations = translations.setup({
subdomainLang: {
www: { lngCode: 'en', url: 'www.sharelatex.com' },
fr: { lngCode: 'fr', url: 'fr.sharelatex.com' },
da: { lngCode: 'da', url: 'da.sharelatex.com' }
}
})
this.req = {
originalUrl: "doesn'tmatter.sharelatex.com/login",
headers: {
'accept-language': ''
}
}
this.res = {}
})
describe('setLangBasedOnDomainMiddlewear', function() {
it('should set the lang to french if the domain is fr', function(done) {
this.req.url = 'fr.sharelatex.com/login'
this.req.headers.host = 'fr.sharelatex.com'
this.translations.expressMiddlewear(this.req, this.req, () => {
this.translations.setLangBasedOnDomainMiddlewear(
this.req,
this.res,
() => {
expect(this.req.lng).to.equal('fr')
done()
}
)
})
})
it('ignores domain if setLng query param is set', function(done) {
this.req.originalUrl = 'fr.sharelatex.com/login?setLng=en'
this.req.url = 'fr.sharelatex.com/login'
this.req.headers.host = 'fr.sharelatex.com'
this.translations.expressMiddlewear(this.req, this.req, () => {
this.translations.setLangBasedOnDomainMiddlewear(
this.req,
this.res,
() => {
expect(this.req.lng).to.equal('en')
done()
}
)
})
})
describe('showUserOtherLng', function() {
it('should set it to true if the language based on headers is different to lng', function(done) {
this.req.headers['accept-language'] = 'da, en-gb;q=0.8, en;q=0.7'
this.req.url = 'fr.sharelatex.com/login'
this.req.headers.host = 'fr.sharelatex.com'
this.translations.expressMiddlewear(this.req, this.req, () => {
this.translations.setLangBasedOnDomainMiddlewear(
this.req,
this.res,
() => {
expect(this.req.showUserOtherLng).to.equal('da')
done()
}
)
})
})
it('should not set prop', function(done) {
this.req.headers['accept-language'] = 'da, en-gb;q=0.8, en;q=0.7'
this.req.url = 'da.sharelatex.com/login'
this.req.headers.host = 'da.sharelatex.com'
this.translations.expressMiddlewear(this.req, this.req, () => {
this.translations.setLangBasedOnDomainMiddlewear(
this.req,
this.res,
() => {
expect(this.req.showUserOtherLng).to.not.exist
done()
}
)
})
})
})
})
})
|
JavaScript
| 0.000005 |
@@ -609,19 +609,19 @@
nMiddlew
-e
ar
+e
', funct
@@ -832,35 +832,35 @@
s.expressMiddlew
-e
ar
+e
(this.req, this.
@@ -917,35 +917,35 @@
dOnDomainMiddlew
-e
ar
+e
(%0A this
@@ -1357,35 +1357,35 @@
s.expressMiddlew
-e
ar
+e
(this.req, this.
@@ -1442,35 +1442,35 @@
dOnDomainMiddlew
-e
ar
+e
(%0A this
@@ -1976,35 +1976,35 @@
s.expressMiddlew
-e
ar
+e
(this.req, this.
@@ -2063,35 +2063,35 @@
dOnDomainMiddlew
-e
ar
+e
(%0A th
@@ -2535,19 +2535,19 @@
sMiddlew
-e
ar
+e
(this.re
@@ -2626,11 +2626,11 @@
dlew
-e
ar
+e
(%0A
|
bce8491c781aab450ed46833c7e05d58c62cf5d6
|
fix undefined description
|
src/writer_extensions/archivist/select_entity_mixin.js
|
src/writer_extensions/archivist/select_entity_mixin.js
|
var $$ = React.createElement;
var TYPE_LABELS = {
"prison": "Prison",
"toponym": "Toponym",
"person": "Person",
"definition": "Definition"
};
// Example of a sub view
// ----------------
var EntityView = React.createClass({
displayName: "Entity",
handleClick: function(e) {
e.preventDefault();
this.props.handleSelection(this.props.id);
},
render: function() {
var className = ["entity", this.props.type];
if (this.props.active) className.push("active");
var props = [
$$("div", {className: "type"}, TYPE_LABELS[this.props.type]),
$$("div", {className: "name"}, this.props.name || this.props.title)
];
if (this.props.synonyms) {
props.push($$("div", {className: "synonyms"}, "Also known as: "+this.props.synonyms));
}
if (this.props.country) {
props.push($$("div", {className: "country"}, "Country: "+this.props.country));
}
if (this.props.type == 'person') {
var description = this.props.description;
// Trim person description if it's too long
if (description.length > 100) description = description.substring(0, 100) + '...';
props.push($$("div", {className: "description"}, description));
}
return $$("div", {
className: className.join(" "),
onClick: this.handleClick
}, props);
}
});
// Entities Panel extension
// ----------------
var SelectEntityMixin = {
contextTypes: {
app: React.PropTypes.object.isRequired,
backend: React.PropTypes.object.isRequired
},
handleCancel: function(e) {
var app = this.context.app;
e.preventDefault();
console.log('props', this.props);
if (this.props.entityReferenceId) {
// Go back to show entities panel
app.replaceState({
contextId: "showEntityReference",
entityReferenceId: this.props.entityReferenceId
});
} else {
// Go to regular entities panel
app.replaceState({
contextId: "entities"
});
}
},
// Data loading methods
// ------------
loadEntities: function(searchString, type) {
var self = this;
var type = type || false;
var backend = this.context.backend;
backend.searchEntities(searchString, type, function(err, entities) {
self.setState({
state: entities.state,
entities: entities.results
});
});
},
// State relevant things
// ------------
getInitialState: function() {
return {
searchString: this.props.searchString,
entities: []
};
},
// Events
// ------------
componentDidMount: function() {
this.loadEntities(this.state.searchString);
},
handleSearchStringChange: function(e) {
var searchString = e.target.value;
var searchType = this.state.type || false;
this.setState({searchString: searchString});
this.loadEntities(searchString, searchType);
},
handleEntityFilterChange: function(e) {
var searchType = e.currentTarget.value;
this.setState({type: searchType});
this.loadEntities(this.state.searchString, searchType);
},
handleRefreshClick: function() {
var type = this.state.type || false;
var searchString = this.state.searchString || '';
this.loadEntities(searchString, type);
},
// Rendering
// -------------------
render: function() {
var self = this;
var entities = this.state.entities;
var entityNodes;
var stateMessage = this.state.state;
if (entities.length > 0) {
entityNodes = entities.map(function(entity) {
entity.handleSelection = self.handleSelection;
return $$(EntityView, entity);
});
} else {
entityNodes = [$$('div', {className: "no-results", text: "Loading suggestions"})];
}
return $$("div", {className: "panel dialog tag-entity-panel-component"},
$$('div', {className: "dialog-header"},
$$('a', {
href: "#",
className: 'back',
onClick: this.handleCancel,
dangerouslySetInnerHTML: {__html: '<i class="fa fa-chevron-left"></i>'}
}),
$$('div', {className: 'label'}, "Select entity")
),
$$('div', {className: "panel-content"},
$$('div', {className: "search", html: ""},
$$('input', {
className: "search-str",
type: "text",
placeholder: "Type to search for entities",//,
value: this.state.searchString,
onChange: this.handleSearchStringChange
}),
$$('select', {
className: "entity-type",
onChange: this.handleEntityFilterChange
},
$$('option', {value: ""}, "All"),
//$$('option', {value: "prison"}, "Prison"),
//$$('option', {value: "toponym"}, "Toponym"),
$$('option', {value: "location"}, "Location"),
$$('option', {value: "person"}, "Person"),
$$('option', {value: "definition"}, "Definition")
),
$$('span', {
className: "refresh",
onClick: this.handleRefreshClick
},
$$('i', { className: "fa fa-refresh" }, "")
)
),
$$('div', {className: "search-result-state"},
$$('span', { className: "state" }, stateMessage),
$$('span', { className: "add-entity" },
$$('span', { className: "label" }, "Add new: "),
$$('a', { href: "/prisons/add", target: "_blank" },
$$('i', { className: "fa fa-th" }, "")
),
$$('a', { href: "/toponyms/add", target: "_blank" },
$$('i', { className: "fa fa-globe" }, "")
),
$$('a', { href: "/definitions/add", target: "_blank" },
$$('i', { className: "fa fa-bookmark" }, "")
),
$$('a', { href: "/persons/add", target: "_blank" },
$$('i', { className: "fa fa-users" }, "")
)
)
),
$$('div', {className: "entities"},
entityNodes
)
)
);
}
};
module.exports = SelectEntityMixin;
|
JavaScript
| 0.999999 |
@@ -988,24 +988,30 @@
.description
+ %7C%7C ''
;%0A // T
|
546e8d70a45fe1eb43c9f726a3725fff9fea2aa5
|
Make linter happy
|
src/manet.js
|
src/manet.js
|
"use strict";
const _ = require('lodash'),
express = require('express'),
bodyParser = require('body-parser'),
logger = require('winston'),
fs = require('fs-extra'),
nocache = require('nocache'),
passport = require('passport'),
config = require('./config'),
routes = require('./routes'),
filters = require('./filters'),
utils = require('./utils'),
DEF_LOGGER_LEVEL = 'info',
DEF_LOGGER_SILENT = false;
/* Logging system */
function initLogging(conf) {
logger.setLevels({
error: 0,
warn: 1,
info: 2,
verbose: 3,
debug: 4,
silly: 5
});
logger.addColors({
debug: 'green',
info: 'cyan',
silly: 'magenta',
warn: 'yellow',
error: 'red'
});
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, {
level: conf.level || DEF_LOGGER_LEVEL,
silent: conf.silent || DEF_LOGGER_SILENT,
colorize: true,
timestamp: true
});
}
/* Termination & Errors handling */
function initExitHandling(server) {
const onExit = () => {
server.close(() => {
logger.info('Manet server stopped');
process.exit(0);
});
}
process.on('SIGTERM', onExit);
process.on('SIGINT', onExit);
}
/* Init FS services */
function cleanupFsStorage(conf) {
if (conf.cleanupStartup) {
const storagePath = conf.storage,
files = fs.readdirSync(storagePath);
files.forEach((file) => {
try {
const filePath = utils.filePath(file, storagePath);
fs.removeSync(filePath, {force: true});
} catch (err) {}
});
}
}
function initFsWatchdog(conf) {
const timeout = conf.cache * 1000,
dir = conf.storage;
utils.runFsWatchdog(dir, timeout, (file) => {
fs.unlink(file, (err) => {
if (err) {
logger.debug('Can not delete file "%s": %s', file, err);
} else {
logger.info('Deleted file "%s"', file);
}
});
});
}
function initFsStorage(conf) {
cleanupFsStorage(conf);
initFsWatchdog(conf);
}
/* Web application */
function createWebApplication(conf) {
const app = express(),
index = routes.index(conf),
urlencoded = bodyParser.urlencoded({ extended: false }),
json = bodyParser.json(),
noCache = nocache(),
basic = filters.basic(conf),
usage = filters.usage(conf),
merge = filters.merge,
notNull = (f) => _.without(f, null);
filters.configureWebSecurity(conf);
app.use(express.static(utils.filePath('../public')));
app.use(passport.initialize());
app.get('/', notNull([noCache, basic, merge, usage]), index);
app.post('/', notNull([noCache, basic, urlencoded, json, merge, usage]), index);
return app;
}
function runWebServer(conf, onStart) {
const app = createWebApplication(conf),
host = conf.host,
port = conf.port,
server = app.listen(port, host, () => {
if (onStart) {
onStart(server);
}
});
logger.info('Manet server started on %s:%d', host, port);
initExitHandling(server);
}
/* Initialize and run server */
function main(onStart) {
const conf = config.read();
initLogging(conf);
initFsStorage(conf);
logger.debug('Default configuration file: %s', conf.path);
logger.debug('Configuration parameters: %s', JSON.stringify(conf));
runWebServer(conf, onStart);
}
/* Exported functions */
module.exports = {
main: main
};
|
JavaScript
| 0.000005 |
@@ -1275,24 +1275,26 @@
%7D);%0A %7D
+;%0A
%0A process
|
8592852a27986c6886999940e3f92f3ca762b5f1
|
Consolidate logic.
|
src/queue.js
|
src/queue.js
|
import {slice} from "./array";
var noabort = {};
function Queue(size) {
if (!((size = +size) >= 1)) throw new Error("invalid size");
this._size = size;
this._call =
this._error = null;
this._tasks = [];
this._data = [];
this._waiting =
this._active =
this._ended =
this._start = 0; // inside a synchronous task callback?
}
Queue.prototype = queue.prototype = {
constructor: Queue,
defer: function(callback) {
if (typeof callback !== "function") throw new Error("invalid callback");
if (this._call) throw new Error("defer after await");
if (this._error != null) return this;
var t = slice.call(arguments, 1);
t.push(callback);
++this._waiting, this._tasks.push(t);
poke(this);
return this;
},
abort: function() {
if (this._error == null) abort(this, new Error("abort"));
return this;
},
await: function(callback) {
if (typeof callback !== "function") throw new Error("invalid callback");
if (this._call) throw new Error("multiple await");
this._call = function(error, results) { callback.apply(null, [error].concat(results)); };
maybeNotify(this);
return this;
},
awaitAll: function(callback) {
if (typeof callback !== "function") throw new Error("invalid callback");
if (this._call) throw new Error("multiple await");
this._call = callback;
maybeNotify(this);
return this;
}
};
function poke(q) {
if (!q._start) {
try { start(q); } // let the current task complete
catch (e) {
if (q._tasks[q._ended + q._active - 1]) abort(q, e); // task errored synchronously
else if (!q._data) throw e; // await callback errored synchronously
}
}
}
function start(q) {
while (q._start = q._waiting && q._active < q._size) {
var i = q._ended + q._active,
t = q._tasks[i],
j = t.length - 1,
c = t[j];
t[j] = end(q, i);
--q._waiting, ++q._active;
t = c.apply(null, t);
if (!q._tasks[i]) continue; // task finished synchronously
q._tasks[i] = t || noabort;
}
}
function end(q, i) {
return function(e, r) {
if (!q._tasks[i]) return; // ignore multiple callbacks
--q._active, ++q._ended;
q._tasks[i] = null;
if (q._error != null) return; // ignore secondary errors
if (e != null) {
abort(q, e);
} else {
q._data[i] = r;
if (q._waiting) poke(q);
else maybeNotify(q);
}
};
}
function abort(q, e) {
var i = q._tasks.length, t;
q._error = e; // ignore active callbacks
q._data = undefined; // allow gc
q._waiting = NaN; // prevent starting
while (--i >= 0) {
if (t = q._tasks[i]) {
q._tasks[i] = null;
if (t.abort) {
try { t.abort(); }
catch (e) { /* ignore */ }
}
}
}
q._active = NaN; // allow notification
maybeNotify(q);
}
function maybeNotify(q) {
if (!q._active && q._call) {
var d = q._data;
q._data = undefined; // allow gc
q._call(q._error, d);
}
}
export default function queue(concurrency) {
return new Queue(arguments.length ? +concurrency : Infinity);
}
|
JavaScript
| 0.000005 |
@@ -71,71 +71,8 @@
) %7B%0A
- if (!((size = +size) %3E= 1)) throw new Error(%22invalid size%22);%0A
th
@@ -2952,66 +2952,175 @@
%7B%0A
-return new Queue(arguments.length ? +concurrency : Infinit
+if (concurrency == null) concurrency = Infinity;%0A else if (!((concurrency = +concurrency) %3E= 1)) throw new Error(%22invalid concurrency%22);%0A return new Queue(concurrenc
y);%0A
|
71d0560133c3bf3eccc8350e8761860c12be147e
|
Remove text field from payload
|
src/slack.js
|
src/slack.js
|
'use strict';
// load .env variables if set
require('dotenv').config();
const config = require('config');
const rp = require('request-promise-native');
module.exports.notify = function(restaurants) {
let content = createContentFrom(restaurants),
completeWebhook = process.env.SLACK.concat(process.env.WEBHOOK),
options = {
method: 'POST',
uri: completeWebhook,
form: {
payload: JSON.stringify(content)
}
};
return rp(options)
.then(function(body) {
return { message: 'Slack message sent' };
})
.catch(function(error) {
console.log(error.message);
throw error;
});
};
function createContentFrom(restaurants) {
return {
'text' : { toString: () => '' }, // only way to have no text without attachment fallback
'channel' : config.has('slack.channel') ? config.get('slack.channel') : undefined,
'username' : config.get('slack.username'),
'icon_emoji' : config.get('slack.icon_emoji'),
'attachments': restaurants.map(restaurant => (
{
'title' : restaurant.name,
'title_link': restaurant.url,
'fallback' : config.get('slack.fallback'),
'color' : restaurant.color,
'mrkdwn_in' : ['text', 'pretext', 'fields'],
'fields' : restaurant.offers.map(offer => (
{
'title' : offer.title,
'value' : offer.description,
'short' : true,
}
)),
'footer': restaurant.parser.name,
'ts': Math.round((new Date).getTime() / 1000)
}
))
};
}
|
JavaScript
| 0 |
@@ -722,107 +722,8 @@
n %7B%0A
- 'text' : %7B toString: () =%3E '' %7D, // only way to have no text without attachment fallback%0A
|
4016d059759680b0539c4c531b2f559722051ac3
|
fix #361
|
src/utils.js
|
src/utils.js
|
/**
* Gets the data attribute. the name must be kebab-case.
*/
export const getDataAttribute = (el, name) => el.getAttribute(`data-vv-${name}`);
/**
* Determines the input field scope.
*/
export const getScope = (el) => {
let scope = getDataAttribute(el, 'scope');
if (! scope && el.form) {
scope = getDataAttribute(el.form, 'scope');
}
return scope;
};
/**
* Debounces a function.
*/
export const debounce = (callback, wait = 0, immediate) => {
let timeout;
if (wait == 0) {
return callback;
}
return (...args) => {
const later = () => {
timeout = null;
if (!immediate) callback(...args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) callback(args);
};
};
/**
* Emits a warning to the console.
*/
export const warn = (message) => {
if (! console) {
return;
}
console.warn(`[vee-validate]: ${message}`); // eslint-disable-line
};
/**
* Checks if the value is an object.
*/
export const isObject = (object) => {
return object !== null && object && typeof object === 'object' && ! Array.isArray(object);
};
/**
* Checks if a function is callable.
*/
export const isCallable = (func) => typeof func === 'function';
/**
* Check if element has the css class on it.
*/
export const hasClass = (el, className) => {
if (el.classList) {
return el.classList.contains(className);
}
return !!el.className.match(new RegExp(`(\\s|^)${className}(\\s|$)`));
};
/**
* Adds the provided css className to the element.
*/
export const addClass = (el, className) => {
if (el.classList) {
el.classList.add(className);
return;
}
if (!hasClass(el, className)) {
el.className += ` ${className}`;
}
};
/**
* Remove the provided css className from the element.
*/
export const removeClass = (el, className) => {
if (el.classList) {
el.classList.remove(className);
return;
}
if (hasClass(el, className)) {
const reg = new RegExp(`(\\s|^)${className}(\\s|$)`);
el.className = el.className.replace(reg, ' ');
}
};
/**
* Converts an array-like object to array.
* Simple polyfill for Array.from
*/
export const toArray = (arrayLike) => {
if (Array.from) {
return Array.from(arrayLike);
}
const array = [];
const length = arrayLike.length;
for (let i = 0; i < length; i++) {
array.push(arrayLike[i]);
}
return array;
};
/**
* Assign polyfill from the mdn.
*/
export const assign = (target, ...others) => {
if (Object.assign) {
return Object.assign(target, ...others);
}
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
const to = Object(target);
others.forEach(arg => {
// Skip over if undefined or null
if (arg != null) {
Object.keys(arg).forEach(key => {
to[key] = arg[key];
});
}
});
return to;
};
/**
* polyfills array.find
* @param {Array} array
* @param {Function} predicate
*/
export const find = (array, predicate) => {
if (array.find) {
return array.find(predicate);
}
let result;
array.some(item => {
if (predicate(item)) {
result = item;
return true;
}
return false;
});
return result;
};
/**
* Gets the rules from a binding value or the element dataset.
*
* @param {String} expression The binding expression.
* @param {Object|String} value The binding value.
* @param {element} el The element.
* @returns {String|Object}
*/
export const getRules = (expression, value, el) => {
if (! expression) {
return getDataAttribute(el, 'rules');
}
if (typeof value === 'string') {
return value;
}
if (~['string', 'object'].indexOf(typeof value.rules)) {
return value.rules
}
return value;
};
|
JavaScript
| 0 |
@@ -479,52 +479,9 @@
ut;%0A
- if (wait == 0) %7B%0A return callback;%0A %7D
%0A
+
re
@@ -1020,19 +1020,10 @@
) =%3E
+%0A
-%7B%0A return
obj
@@ -1102,19 +1102,16 @@
object);
-%0A%7D;
%0A%0A/**%0A *
@@ -1635,20 +1635,17 @@
urn;%0A %7D
- %0A
+%0A
%0A if (!
@@ -3284,17 +3284,16 @@
aset.%0A *
-
%0A * @par
@@ -3693,24 +3693,24 @@
e.rules)) %7B%0A
-
return v
@@ -3719,16 +3719,17 @@
ue.rules
+;
%0A %7D%0A%0A
|
aa12080c5a1d97a8521377c212276bf0f5c0e815
|
Remove console.log
|
src/utils.js
|
src/utils.js
|
import fs from 'fs';
import path from 'path';
import https from 'https';
import child_process from 'child_process';
import { rimrafSync, copydirSync } from 'sander';
const tmpDirName = 'tmp';
const degitConfigName = 'degit.json';
export {degitConfigName};
export class DegitError extends Error {
constructor(message, opts) {
super(message);
Object.assign(this, opts);
}
}
export function tryRequire(file, opts) {
try {
if (opts && opts.clearCache === true) {
delete require.cache[require.resolve(file)];
}
return require(file);
} catch (err) {
return null;
}
}
export function exec(command) {
return new Promise((fulfil, reject) => {
child_process.exec(command, (err, stdout, stderr) => {
if (err) {
reject(err);
return;
}
fulfil({ stdout, stderr });
});
});
}
export function mkdirp(dir) {
const parent = path.dirname(dir);
if (parent === dir) return;
mkdirp(parent);
try {
fs.mkdirSync(dir);
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
}
export function fetch(url, dest) {
return new Promise((fulfil, reject) => {
https.get(url, response => {
const code = response.statusCode;
if (code >= 400) {
reject({ code, message: response.statusMessage });
} else if (code >= 300) {
fetch(response.headers.location, dest).then(fulfil, reject);
} else {
response.pipe(fs.createWriteStream(dest))
.on('finish', () => fulfil())
.on('error', reject);
}
}).on('error', reject);
});
}
export function stashFiles(dir, dest) {
const tmpDir = path.join(dir, tmpDirName);
console.log('tmpDir', tmpDir)
rimrafSync(tmpDir);
mkdirp(tmpDir);
fs.readdirSync(dest).forEach(file => {
const filePath = path.join(dest, file);
const targetPath = path.join(tmpDir, file);
const isDir = fs.lstatSync(filePath).isDirectory();
if (isDir) {
copydirSync(filePath).to(targetPath);
rimrafSync(filePath);
} else {
fs.copyFileSync(filePath, targetPath);
fs.unlinkSync(filePath);
}
});
}
export function unstashFiles(dir, dest) {
const tmpDir = path.join(dir, tmpDirName);
fs.readdirSync(tmpDir).forEach(filename => {
const tmpFile = path.join(tmpDir, filename);
const targetPath = path.join(dest, filename);
const isDir = fs.lstatSync(tmpFile).isDirectory();
if (isDir) {
copydirSync(tmpFile).to(targetPath);
rimrafSync(tmpFile);
} else {
if (filename !== 'degit.json') {
fs.copyFileSync(tmpFile, targetPath);
}
fs.unlinkSync(tmpFile);
}
});
rimrafSync(tmpDir);
}
|
JavaScript
| 0.000004 |
@@ -1571,39 +1571,8 @@
e);%0A
-%09console.log('tmpDir', tmpDir)%0A
%09rim
|
1d8373148413b63181ad7d98e64aac1d451292e9
|
Use AxiosError constructor to create axios errors if available
|
src/utils.js
|
src/utils.js
|
"use strict";
var isEqual = require("fast-deep-equal");
var isBuffer = require("is-buffer");
var isBlob = require("./is_blob");
var toString = Object.prototype.toString;
function find(array, predicate) {
var length = array.length;
for (var i = 0; i < length; i++) {
var value = array[i];
if (predicate(value)) return value;
}
}
function isFunction(val) {
return toString.call(val) === "[object Function]";
}
function isObjectOrArray(val) {
return val !== null && typeof val === "object";
}
function isStream(val) {
return isObjectOrArray(val) && isFunction(val.pipe);
}
function isArrayBuffer(val) {
return toString.call(val) === "[object ArrayBuffer]";
}
function combineUrls(baseURL, url) {
if (baseURL) {
return baseURL.replace(/\/+$/, "") + "/" + url.replace(/^\/+/, "");
}
return url;
}
function findHandler(
handlers,
method,
url,
body,
parameters,
headers,
baseURL
) {
return find(handlers[method.toLowerCase()], function (handler) {
if (typeof handler[0] === "string") {
return (
(isUrlMatching(url, handler[0]) ||
isUrlMatching(combineUrls(baseURL, url), handler[0])) &&
isBodyOrParametersMatching(method, body, parameters, handler[1]) &&
isObjectMatching(headers, handler[2])
);
} else if (handler[0] instanceof RegExp) {
return (
(handler[0].test(url) || handler[0].test(combineUrls(baseURL, url))) &&
isBodyOrParametersMatching(method, body, parameters, handler[1]) &&
isObjectMatching(headers, handler[2])
);
}
});
}
function isUrlMatching(url, required) {
var noSlashUrl = url[0] === "/" ? url.substr(1) : url;
var noSlashRequired = required[0] === "/" ? required.substr(1) : required;
return noSlashUrl === noSlashRequired;
}
function isBodyOrParametersMatching(method, body, parameters, required) {
var allowedParamsMethods = ["delete", "get", "head", "options"];
if (allowedParamsMethods.indexOf(method.toLowerCase()) >= 0) {
var data = required ? required.data : undefined;
var params = required ? required.params : undefined;
return isObjectMatching(parameters, params) && isBodyMatching(body, data);
} else {
return isBodyMatching(body, required);
}
}
function isObjectMatching(actual, expected) {
if (expected === undefined) return true;
if (typeof expected.asymmetricMatch === "function") {
return expected.asymmetricMatch(actual);
}
return isEqual(actual, expected);
}
function isBodyMatching(body, requiredBody) {
if (requiredBody === undefined) {
return true;
}
var parsedBody;
try {
parsedBody = JSON.parse(body);
} catch (e) {}
return isObjectMatching(parsedBody ? parsedBody : body, requiredBody);
}
function purgeIfReplyOnce(mock, handler) {
Object.keys(mock.handlers).forEach(function (key) {
var index = mock.handlers[key].indexOf(handler);
if (index > -1) {
mock.handlers[key].splice(index, 1);
}
});
}
function settle(resolve, reject, response, delay) {
if (delay > 0) {
setTimeout(settle, delay, resolve, reject, response);
return;
}
if (
!response.config.validateStatus ||
response.config.validateStatus(response.status)
) {
resolve(response);
} else {
reject(
createAxiosError(
"Request failed with status code " + response.status,
response.config,
response
)
);
}
}
function createAxiosError(message, config, response, code) {
var error = new Error(message);
error.isAxiosError = true;
error.config = config;
if (response !== undefined) {
error.response = response;
}
if (code !== undefined) {
error.code = code;
}
error.toJSON = function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code,
};
};
return error;
}
function createCouldNotFindMockError(config) {
var message =
"Could not find mock for: \n" +
JSON.stringify(config, ["method", "url"], 2);
var error = new Error(message);
error.isCouldNotFindMockError = true;
error.url = config.url;
error.method = config.method;
return error;
}
module.exports = {
find: find,
findHandler: findHandler,
purgeIfReplyOnce: purgeIfReplyOnce,
settle: settle,
isStream: isStream,
isArrayBuffer: isArrayBuffer,
isFunction: isFunction,
isObjectOrArray: isObjectOrArray,
isBuffer: isBuffer,
isBlob: isBlob,
isBodyOrParametersMatching: isBodyOrParametersMatching,
isEqual: isEqual,
createAxiosError: createAxiosError,
createCouldNotFindMockError: createCouldNotFindMockError,
};
|
JavaScript
| 0 |
@@ -8,16 +8,46 @@
rict%22;%0A%0A
+var axios = require(%22axios%22);%0A
var isEq
@@ -3505,24 +3505,245 @@
se, code) %7B%0A
+ // axios v0.27.0+ defines AxiosError as constructor%0A if (typeof axios.AxiosError === 'function') %7B%0A return new axios.AxiosError(message, code, config, null, response);%0A %7D%0A%0A // handling for axios v0.26.1 and below%0A
var error
|
c86fe8f3f822ffc2f47bef491ac7f25006bbbb51
|
call iterator on values
|
src/vnode.js
|
src/vnode.js
|
import { VNodeIterator } from './access';
export function VNode(cx,inode,type,name,value,parent,depth,indexInParent,cache){
this.cx = cx;
this.inode = inode;
this.type = type;
this.name = name;
this.value = value;
this.parent = parent;
this.depth = depth | 0;
this.indexInParent = indexInParent;
this.cache = cache;
}
VNode.prototype.__is_VNode = true;
VNode.prototype.toString = function(){
return this.cx.stringify(this.inode);
};
VNode.prototype.count = function(){
if(typeof this.inode == "function") return 0;
return this.cx.count(this.inode);
};
VNode.prototype.keys = function(){
var cache = this.cache || this.cx.cached(this.inode, this.type);
if(cache) return cache.keys();
return this.cx.keys(this.inode,this.type);
};
VNode.prototype.values = function(){
return this.cx.values(this.inode,this.type);
};
VNode.prototype.first = function(){
return this.cx.first(this.inode,this.type);
};
VNode.prototype.last = function(){
return this.cx.last(this.inode,this.type);
};
VNode.prototype.next = function(node){
return this.cx.next(this.inode,node,this.type);
};
VNode.prototype.push = function(child){
this.inode = this.cx.push(this.inode,[child.name,child.inode],this.type);
return this;
};
VNode.prototype.set = function(key,val){
this.inode = this.cx.set(this.inode,key,val,this.type);
return this;
};
VNode.prototype.removeChild = function(child){
this.inode = this.cx.removeChild(this.inode,child,this.type);
return this;
};
VNode.prototype.finalize = function(){
this.inode = this.cx.finalize(this.inode);
return this;
};
VNode.prototype.attrEntries = function(){
return this.cx.attrEntries(this.inode);
};
VNode.prototype.attr = function(k,v){
if(arguments.length == 1) return this.cx.getAttribute(this.inode, k);
if(arguments.length === 0) {
this.inode = this.cx.clearAttributes(this.inode);
} else {
this.inode = this.cx.setAttribute(this.inode, k, v);
}
return this;
};
VNode.prototype.modify = function(node,ref) {
this.inode = this.cx.modify(this.inode,node,ref,this.type);
return this;
};
// hitch this on VNode for reuse
VNode.prototype.vnode = function(inode, parent, depth, indexInParent){
return this.cx.vnode(inode, parent, depth, indexInParent);
};
VNode.prototype.ivalue = function(type, name, value) {
return this.cx.ivalue(type, name, value);
};
VNode.prototype.emptyINode = function(type, name, attrs, ns){
return this.cx.emptyINode(type, name, attrs, ns);
};
VNode.prototype.emptyAttrMap = function(init) {
return this.cx.emptyAttrMap(init);
};
// TODO create iterator that yields a node seq
// position() should overwrite get(), but the check should be name or indexInParent
VNode.prototype[Symbol.iterator] = function(){
return new VNodeIterator(this.values(),this, this.cx.vnode);
};
VNode.prototype.get = function(idx){
var val = this.cx.get(this.inode,idx,this.type,this.cache);
if(!val) return [];
val = val.constructor == Array ? val : [val];
return new VNodeIterator(val[Symbol.iterator](), this, this.cx.vnode);
};
|
JavaScript
| 0.000001 |
@@ -2750,16 +2750,35 @@
values()
+%5BSymbol.iterator%5D()
,this, t
|
914fe7ccc3a257df4a1626e2434e6abad25f02c3
|
Correct version in comment
|
migration/fixtures/v10.js
|
migration/fixtures/v10.js
|
/* eslint-disable no-magic-numbers */
// NOTE This file is an important documentation of the data structure of v9.
var c = require('./common');
var db = require('tresdb-db');
module.exports = {
collections: {
config: [{
key: 'schemaVersion',
value: 10, // NOTE
}],
entries: [{
_id: db.id('581f166110a1482dd0b7ea01'),
data: {
isVisit: false,
markdown: 'A ghost town',
filepath: null,
mimetype: null,
thumbfilepath: null,
thumbmimetype: null,
},
deleted: false,
locationId: c.irbeneId,
time: '2009-09-04T23:44:21.000Z',
type: 'location_entry',
user: 'admin',
}, {
_id: db.id('581f166110a1482dd0b7ea02'),
comments: [
{
time: '2009-10-04T19:55:01.000Z',
user: 'admin',
message: 'Hello world',
},
],
data: {
isVisit: false,
markdown: null,
filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
mimetype: 'image/jpeg',
thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
thumbmimetype: 'image/jpeg',
},
deleted: false,
locationId: c.irbeneId,
time: '2009-10-02T11:11:01.000Z',
type: 'location_entry',
user: 'admin',
}],
events: [{
data: {
lng: 21.857705,
lat: 57.55341,
},
locationId: c.irbeneId,
locationName: 'Irbene',
time: '2009-07-30T10:44:57.000Z',
type: 'location_created',
user: 'admin',
}, {
data: {
entryId: db.id('581f166110a1482dd0b7ea01'),
isVisit: false,
markdown: 'A ghost town',
filepath: null,
mimetype: null,
thumbfilepath: null,
thumbmimetype: null,
},
locationId: c.irbeneId,
locationName: 'Irbene',
time: '2009-09-04T23:44:21.000Z',
type: 'location_entry_created',
user: 'admin',
}, {
data: {
newTags: ['abandoned'],
oldTags: [],
},
locationId: c.irbeneId,
locationName: 'Irbene',
time: '2009-09-04T23:45:20.000Z',
type: 'location_tags_changed', // legacy event type
user: 'admin',
}, {
data: {
entryId: db.id('581f166110a1482dd0b7ea02'),
isVisit: false,
markdown: null,
filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
mimetype: 'image/jpeg',
thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
thumbmimetype: 'image/jpeg',
},
locationId: c.irbeneId,
locationName: 'Irbene',
time: '2009-10-02T11:11:01.000Z',
type: 'location_entry_created',
user: 'admin',
}, {
data: {
entryId: db.id('581f166110a1482dd0b7ea02'),
message: 'Dang radar, dude',
},
locationId: c.irbeneId,
locationName: 'Irbene',
time: '2009-10-04T19:55:01.000Z',
type: 'location_entry_comment_created',
user: 'admin',
}],
users: [{
admin: true,
email: '[email protected]',
hash: c.PASSWORD,
name: 'admin',
points: 0,
// points7days: created by worker
// points30days: created by worker
status: 'active',
}],
locations: [{
_id: c.irbeneId,
creator: 'admin',
deleted: false,
geom: {
type: 'Point',
coordinates: [21.857705, 57.55341],
},
layer: 12,
childLayer: 0, // NOTE
isLayered: true,
name: 'Irbene',
points: 0,
places: [],
status: 'abandoned',
type: 'default',
visits: [], // NOTE
text1: '',
text2: '',
}],
},
};
|
JavaScript
| 0.000001 |
@@ -105,13 +105,14 @@
ure
-of v9
+at v10
.%0A%0Av
|
7c411abc574f1a925aa0890166d4bd4294c969b4
|
simplify save extension lookups
|
app/atom.js
|
app/atom.js
|
// Stopgap atom.js file for handling normal browser things that atom
// does not yet have stable from the browser-side API.
// - Opening external links in default web browser
// - Saving files/downloads to disk
$(document).ready(function() {
if (typeof process === 'undefined') return;
if (typeof process.versions['atom-shell'] === undefined) return;
var remote = require('remote');
var shell = require('shell');
var http = require('http');
var url = require('url');
var fs = require('fs');
$('body').on('click', 'a', function(ev) {
var uri = url.parse(ev.currentTarget.href);
// Opening external URLs.
if (uri.hostname && uri.hostname !== 'localhost') {
shell.openExternal(ev.currentTarget.href);
return false;
}
// File saving.
var fileTypes = {
'Package': [
'tm2z'
],
'Tiles': [
'mbtiles'
],
'Image': [
'png',
'jpg',
'jpeg'
]
}
var typeLabel = '';
var typeExtension = '';
for (var label in fileTypes) {
for (var i in fileTypes[label]) {
if (uri.pathname.split('.').pop().toLowerCase() == fileTypes[label][i]) {
typeLabel = label;
typeExtension = fileTypes[label][i];
break;
}
}
}
if (typeExtension) {
var filePath = remote.require('dialog').showSaveDialog({
title: 'Save ' + typeLabel,
defaultPath: '~/Untitled ' + typeLabel + '.' + typeExtension
});
if (filePath) {
uri.method = 'GET';
var writeStream = fs.createWriteStream(filePath);
var req = http.request(uri, function(res) {
if (res.statusCode !== 200) return;
res.pipe(writeStream);
});
req.end();
}
return false;
}
// Passthrough everything else.
});
});
|
JavaScript
| 0.000001 |
@@ -860,16 +860,22 @@
+ tm2z:
'Packag
@@ -872,27 +872,25 @@
z: 'Package'
-: %5B
+,
%0A
@@ -894,82 +894,25 @@
- 'tm2z'%0A %5D,%0A 'T
+mbt
iles
-'
:
-%5B%0A 'mbt
+'T
iles'
+,
%0A
@@ -924,30 +924,20 @@
-%5D,%0A
+png:
'Image'
: %5B%0A
@@ -936,11 +936,9 @@
age'
-: %5B
+,
%0A
@@ -950,16 +950,19 @@
- 'png
+jpg: 'Image
',%0A
@@ -976,491 +976,176 @@
- 'jpg',%0A 'jpeg'%0A %5D%0A %7D%0A var typeLabel = '';%0A var typeExtension = '';%0A for (var label in fileTypes) %7B%0A for (var i in fileTypes%5Blabel%5D) %7B%0A if (uri.pathname.split('.').pop().toLowerCase() == fileTypes%5Blabel%5D%5Bi%5D) %7B%0A typeLabel = label;%0A typeExtension = fileTypes%5Blabel%5D%5Bi%5D;%0A break;%0A %7D%0A %7D%0A %7D%0A if (typeExtension
+jpeg: 'Image'%0A %7D%0A var typeExtension = uri.pathname.split('.').pop().toLowerCase();%0A var typeLabel = fileTypes%5BtypeExtension%5D;%0A if (typeLabel
) %7B%0A
|
e7a63b8e12ea2af68f9b8cb64cdd74d87ab894a8
|
add import firebase
|
app/auth.js
|
app/auth.js
|
import angular from 'angular';
import {appName, firebaseUrl} from './constants';
const authFactory = ($firebaseAuth) => {
const ref = new Firebase(firebaseUrl);
return $firebaseAuth(ref);
};
authFactory.$inject = ['$firebaseAuth'];
angular.module(appName).factory('Auth', authFactory);
|
JavaScript
| 0.000002 |
@@ -24,16 +24,49 @@
gular';%0A
+import Firebase from 'firebase';%0A
import %7B
|
a83c3a6180265312dbedd10eb6a3db6c4f234902
|
Fix typo
|
app/main.js
|
app/main.js
|
var counter;
var header = 160;
var effectiveWindowWidth, effectiveWindowHeight;
var objectSize = 80;
function setup() {
effectiveWindowWidth = windowWidth - 16;
effectiveWindowHeight = windowHeight - header;
var canvas = createCanvas(effectiveWindowWidth, effectiveWindowHeight);
if (displayWidth < 700)
objectSize = 30;
canvas.parent('play');
counter = new Counter();
counter.new();
var buttons = selectAll('.value-button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].mouseClicked(function () {
if (counter.loosing)
counter.new();
else
counter.guess(this.elt.innerHTML);
});
}
var enterButton = select('.enter-button');
enterButton.mouseClicked(function () {
if (counter.loosing)
counter.new();
else
counter.submitGuess();
});
}
function draw() {
background(255, 255, 255);
counter.draw();
}
function windowResized() {
effectiveWindowWidth = windowWidth - 16;
effectiveWindowHeight = windowHeight - header;
resizeCanvas(effectiveWindowWidth, effectiveWindowHeight);
}
function keyTyped() {
if (key === ' ' || counter.loosing) {
counter.new();
return;
}
if (keyCode == ENTER) {
counter.submitGuess();
return;
}
var numbers = ["1","2","3","4","5","6","7","8","9","0"];
if (numbers.indexOf(key) > - 1) {
counter.guess(key);
}
}
function touchStarted() {
if (touches.length > 0) {
var touch = touches[0];
if (
touch.x >= 0 && touch.x < effectiveWindowWidth &&
touch.y >= 0 && touch.y < effectiveWindowHeight
)
{
if (counter.loosing)
counter.new();
}
}
}
function Counter () {
this.objects = [];
this.score = 0;
this.number = 0;
var gap = objectSize + 5;
this.new = function () {
this.lastGuess = null;
this.loosing = false;
this.objects = [];
this.number = floor(random(1, 10));
var newPosition;
while(this.objects.length < this.number) {
newPosition = this.findNewPosition();
if (!newPosition)
{
this.number--;
continue;
}
this.objects.push({
position: newPosition,
color: color('red'),
type: 'ellipse'
});
}
var level2 = floor(random(1, 5));
if (this.score > 5) {
for(var i = 0; i < level2; i++) {
newPosition = this.findNewPosition();
if (!newPosition)
{
level2--;
continue;
}
this.objects.push({
position: newPosition,
color: color('blue'),
type: 'ellipse'
});
}
}
var level3 = floor(random(1, 5));
if (this.score > 10) {
for(var i = 0; i < level3; i++) {
newPosition = this.findNewPosition();
if (!newPosition)
{
level3--;
continue;
}
this.objects.push({
position: newPosition,
color: color('red'),
type: 'rect'
});
}
}
var div = select('#solution');
div.html("Count the RED circles and press ENTER!");
}
this.findNewPosition = function() {
var counter = 0;
while(true)
{
var newPosition = createVector(random(gap, effectiveWindowWidth - gap), random(gap, effectiveWindowHeight - gap));
if (this.objects.every(function(item){
return p5.Vector.sub(item.position, newPosition).mag() > objectSize * 2 + 5;
}))
{
return newPosition;
}
counter++;
if (counter > 200)
break;
}
}
this.draw = function() {
for(var i = 0; i < this.objects.length; i++) {
var object = this.objects[i];
fill(object.color);
switch (object.type)
{
case 'ellipse':
ellipse(object.position.x, object.position.y, objectSize * 2);
break;
case 'rect':
rect(object.position.x - objectSize, object.position.y - objectSize, objectSize * 2, objectSize * 2, 20);
break;
}
}
fill(0,0,0);
textSize(30);
text(this.score, 10, 35);
}
this.guess = function(guess) {
this.lastGuess = guess;
var div = select('#solution');
div.html("Your guess is: " + this.lastGuess);
}
this.submitGuess = function(guess) {
if (!this.lastGuess)
return;
if (this.isValid()) {
var div = select('#solution');
div.html("Right");
this.win();
this.new();
}
else{
var div = select('#solution');
div.html("Wrong. Press any key/touch to restart.");
this.loose();
}
}
this.isValid = function() {
return this.lastGuess == this.number;
}
this.win = function() {
this.score += 1;
}
this.loose = function() {
this.score = 0;
this.objects = [];
this.loosing = true;
}
}
|
JavaScript
| 0.999999 |
@@ -575,33 +575,32 @@
if (counter.lo
-o
sing)%0A
@@ -811,33 +811,32 @@
if (counter.lo
-o
sing)%0A
@@ -5373,17 +5373,16 @@
this.lo
-o
se();%0A
@@ -5552,17 +5552,16 @@
this.lo
-o
se = fun
@@ -5632,25 +5632,24 @@
this.lo
-o
sing = true;
|
d0e6a07669536dab73bde02a5f6e356bc675bef6
|
Remove placeholder from initial state
|
app/javascript/app/components/my-climate-watch/viz-creator/viz-creator-initial-state.js
|
app/javascript/app/components/my-climate-watch/viz-creator/viz-creator-initial-state.js
|
export default {
creatorIsOpen: false,
title: '',
description: '',
placeholder: '',
creationStatus: {
failed: false,
fields: []
},
datasets: {
name: 'datasets',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'visualisations',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'locations',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'models',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'scenarios',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'categories',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'subcategories',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'indicators',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'years',
selected: null,
data: [],
loading: false,
loaded: false,
child: {
name: 'timeseries',
selected: null,
data: [],
loading: false,
loaded: false
}
}
}
}
}
}
}
}
}
}
};
|
JavaScript
| 0.000001 |
@@ -70,27 +70,8 @@
'',%0A
- placeholder: '',%0A
cr
|
3233aa6012331a07dce88af3d10242d1ec07d56e
|
Fix creation alarmdef fails when threshold equals 0
|
monitoring/static/monitoring/js/services.js
|
monitoring/static/monitoring/js/services.js
|
/*
* Copyright 2016 FUJITSU LIMITED
*
* 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';
angular
.module('monitoring.services', [])
.factory('monExpressionBuilder', expressionBuilder);
function expressionBuilder() {
return {
asString: subExpressionToString
};
function subExpressionToString(subExpressions, withOp) {
var tmp = [],
exprAsStr;
angular.forEach(subExpressions, function(expr) {
exprAsStr = [
withOp ? renderOp(expr) : '',
expr.fun || '',
expr.fun && '(',
expr.metric ? expr.metric.name : '', renderDimensions(expr),
(expr.deterministic ? ',deterministic': ''),
expr.fun && ')',
expr.cmp || '',
expr.threshold || ''
].join('');
tmp.push(exprAsStr);
});
return tmp.join('');
}
function renderDimensions(expr) {
var tmp = [];
if (angular.isUndefined(expr.dimensions) || !expr.dimensions.length){
return tmp.join('');
}
tmp.push('{');
tmp.push(expr.dimensions.join(','));
tmp.push('}');
return tmp.join('');
}
function renderOp(expr) {
var tmp = [];
if ('op' in expr) {
tmp.push(' ');
tmp.push(expr['op']);
tmp.push(' ');
}
return tmp.join('');
}
}
|
JavaScript
| 0.00002 |
@@ -1312,24 +1312,51 @@
+ expr.threshold === 0 ? 0 :
expr.thresh
|
a03c7964c5737b3315646aee52342a8dca18ad3c
|
Add missing semicolon
|
ie9-console-workaround.js
|
ie9-console-workaround.js
|
/*
* IE9 console workaround
* The console object is only exposed on Internet Explorer 9
* after opening the developer tools (F12)
*/
if (!window.console) {
var console = {
log: function() {},
warn: function() {},
error: function() {},
time: function() {},
timeEnd: function() {}
}
}
|
JavaScript
| 0.999999 |
@@ -302,11 +302,12 @@
) %7B%7D%0A %7D
+;
%0A%7D%0A
|
e22389fdeb0ddab70c4b4e7e36e08b5a720b6bfc
|
add text saying whether description is truncated (turned off for now)
|
meetup-better-export.user.js
|
meetup-better-export.user.js
|
// ==UserScript==
// @name Meetup Better Event Exporter
// @namespace http://boris.joff3.com
// @version 1.0
// @description Export full Meetup event description to Google Calendar
// @author Boris Joffe
// @match http://*.meetup.com/*
// @match https://*.meetup.com/*
// @grant none
// ==/UserScript==
/* jshint -W097 */
/* eslint-disable no-console, no-unused-vars */
'use strict';
/*
The MIT License (MIT)
Copyright (c) 2015 Boris Joffe
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.
*/
// Util
var DEBUG = false;
function dbg() {
if (DEBUG)
console.log.apply(console, arguments);
return arguments[0];
}
var
qs = document.querySelector.bind(document),
err = console.error.bind(console),
log = console.log.bind(console),
euc = encodeURIComponent;
function qsv(elmStr, parent) {
var elm = parent ? parent.querySelector(elmStr) : qs(elmStr);
if (!elm) err('(qs) Could not get element -', elmStr);
return elm;
}
function updateExportLink() {
log('Event Exporter running');
var
calLink = qsv('a[href*="google.com/calendar"]'),
descElm = qsv('#event-description-wrap'),
desc;
if (descElm.innerText) {
desc = descElm.innerText;
} else {
// fallback, HTML encoded entities will appear broken
desc = descElm.innerHTML
.replace(/<br>\s*/g, '\n') // fix newlines
.replace(/<a href="([^"]*)"[^>]*>/g, '[$1] ') // show link urls
.replace(/<[^>]*>/g, ''); // strip html tags
}
var meetupGroupName = qsv('meta[property="og:title"]').getAttribute('content');
// Google? doesn't allow calendar links over a certain length
var leadingText = euc(meetupGroupName + '\n' + location.href + '\n\n');
var leadingTextTruncated = euc('[Details cut off]\n' + location.href + '\n');
var linkWithoutDetails = calLink.href.replace(/details=([^&]*)/, 'details=');
// limit seems to be around 2000-3000 chars but may not be a full url limit and seems to vary depending on the Meetup content
var FULL_LINK_MAX_CHARS = 2300; //2543;
var FULL_DETAILS_MAX_CHARS = FULL_LINK_MAX_CHARS - linkWithoutDetails.length;
var DETAILS_MAX_CHARS = FULL_DETAILS_MAX_CHARS - leadingText.length;
var ELLIPSIS = '...';
var isTruncated = false;
dbg('original desc length =', euc(desc).length);
if (euc(desc).length > DETAILS_MAX_CHARS) {
dbg('truncating');
desc = desc.replace(/(\s)\s*/g, '$1'); // condense whitespace
desc = leadingTextTruncated + euc(desc); // inform user about truncation
desc = desc.slice(0, FULL_DETAILS_MAX_CHARS - ELLIPSIS.length) + ELLIPSIS;
isTruncated = true;
} else {
dbg('not truncating');
desc = leadingText + euc(desc);
}
calLink.href = linkWithoutDetails.replace(/details=/, 'details=' + desc);
dbg('desc text len =', desc.length);
dbg('full link length =', calLink.href.length);
calLink.target = '_blank';
// show color change to notify user that link changed
var lightGreen = 'rgba(0, 255, 0, 0.1)';
var lightYellow = 'rgba(255, 255, 0, 0.1)';
var linkColor = isTruncated ? lightYellow : lightGreen;
calLink.parentNode.style.backgroundColor = linkColor;
qsv('#addToCalAction').style.backgroundColor = linkColor;
}
window.addEventListener('load', updateExportLink, true);
|
JavaScript
| 0.000038 |
@@ -3720,16 +3720,82 @@
desc);%0A
+%09//calLink.innerHTML += isTruncated ? ' (truncated)' : ' (full)';%0A
%09dbg('de
|
f2bc749082e8f00cda465e8d1a09579534f6080b
|
Use new init mechanism for transactions
|
caspy/static/js/transaction.js
|
caspy/static/js/transaction.js
|
(function(){
var mod = angular.module('caspy.transaction', ['caspy.api', 'caspy.ui', 'generic']);
mod.factory('TransactionService', ['ResourceWrapper', 'caspyAPI',
function(ResourceWrapper, caspyAPI) {
function splitcmp(a, b) {
if (0 < a.amount && 0 < b.amount)
return 1/a.amount - 1/b.amount;
return a.amount - b.amount;
}
function mapTransactions(transactions) {
return transactions.map(function(xdata) {
var xact = {
'date': xdata.date,
'description': xdata.description,
'splits': xdata.splits.sort(splitcmp)
};
return xact;
});
}
return function(book_id) {
var res = caspyAPI.get_resource('transaction', {'book_id': book_id});
var rw = new ResourceWrapper(res, 'transaction_id');
rw.orig_all = rw.all;
rw.all = function() {
return this.orig_all().then(mapTransactions);
}
return rw;
};
}]
);
mod.controller('TransactionController'
,['$injector'
, '$routeParams'
, 'ListControllerMixin'
, 'TransactionService'
, function($injector
, $routeParams
, ListControllerMixin
, TransactionService
) {
$injector.invoke(ListControllerMixin, this);
var ref = this;
this.book_id = $routeParams['book_id'];
this.dataservice = TransactionService(this.book_id);
this.assign('transactions', this.dataservice.all());
this.pk = 'transaction_id';
}]
);
mod.controller('TransactionEditController'
,['$scope', 'focus',
function($scope, focus) {
var ctrl = this;
this.splits = function(splits) {
if (arguments.length)
$scope.transaction.splits = splits;
return $scope.transaction.splits;
};
this.addSplit = function addSplit(amount) {
var splitObj = {
'amount': amount
,'status': 'n'
,'number': ''
,'description': ''
};
splitObj.auto = true;
this.splits().push(splitObj);
if (arguments.length)
focus('split.auto');
};
function nonzero(split) {
return split.amount || split.auto;
}
this.onSplitChange = function(split) {
split.auto = false;
var total = 0;
var auto;
var splits = this.splits(this.splits().filter(nonzero));
splits.forEach(function(s, i) {
if (s.auto)
auto = i;
else
total += +s.amount;
});
if (Math.abs(total) >= 0.1) {
if (typeof auto !== 'undefined')
splits[auto].amount = -total;
else
this.addSplit(-total);
} else {
splits.splice(auto, 1);
}
};
this.onTransactionChange = function() {
if (typeof this.splits() === 'undefined')
this.splits([]);
if (0 == this.splits().length)
this.addSplit();
focus("cspFocus == 'date'");
}
$scope.$watch('transaction', function() {
if ($scope.transaction)
ctrl.onTransactionChange();
});
}]
);
mod.directive('cspTransactionEdit', function() {
return {
scope: {
transaction: '='
}
, controller: 'TransactionEditController'
, templateUrl: 'partials/transaction/transaction-edit.html'
};
});
})();
|
JavaScript
| 0 |
@@ -1659,16 +1659,76 @@
on_id';%0A
+ this.newitem = function() %7B return %7Bsplits: %5B%5D%7D; %7D;%0A
%7D%5D%0A)
@@ -3253,95 +3253,8 @@
) %7B%0A
- if (typeof this.splits() === 'undefined')%0A this.splits(%5B%5D);%0A
|
54e9789196ae23d47d2c585cca0d203b3bad24a5
|
Use `hostname` when nuking cookies
|
lib/assets/javascripts/unobtrusive_flash.js
|
lib/assets/javascripts/unobtrusive_flash.js
|
$(function() {
// Delete the cookie regardless of the domain it was set from
// Partial credit to http://stackoverflow.com/a/2959110/6678
function nukeCookie(cookieName) {
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
var hostParts = window.location.host.split('.').reverse();
var expireHost = hostParts.shift();
expireHost = expireHost.replace(/^([a-z]{1,})\:[0-9]{1,5}/, '$1');
$.each(hostParts, function(i,part) {
expireHost = part + '.' + expireHost;
document.cookie = cookieName+'=; path=/;expires='+yesterday+'; domain='+expireHost;
});
document.cookie = cookieName+'=; path=/';expires=+yesterday+'; domain=';
}
// Extracts flash array stored in cookie and clears the cookie
function extractFlashFromCookies() {
var data = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
var name = 'flash';
var cookieValue = null;
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
// replace fixes problems with Rails escaping. Duh.
cookieValue = decodeURIComponent(cookie.substring(name.length + 1).replace(/\+/g,'%20'));
if (cookieValue.length > 0) break; // there might be empty "flash=" cookies
}
}
try {
data = $.parseJSON(cookieValue);
} catch(e) {
}
nukeCookie('flash');
}
return data;
}
// Reads flash messages from cookies and fires corresponding events
function showFlashFromCookies() {
var flashMessages = extractFlashFromCookies();
if (flashMessages !== null) {
$.each(flashMessages, function(_, flashMessage) {
$(window).trigger('rails:flash', {type: flashMessage[0], message: flashMessage[1]});
});
}
}
$(function() {
showFlashFromCookies();
});
$(document).on('page:change page:load', showFlashFromCookies);
$(document).ajaxSuccess(function(event,request,options) {
showFlashFromCookies();
});
});
|
JavaScript
| 0.000001 |
@@ -297,16 +297,20 @@
ion.host
+name
.split('
|
706a776187cdad8e1b396f774f3ad7f405c19a8f
|
should be uppercase F
|
src/events/setHandler.js
|
src/events/setHandler.js
|
import eventHooks from './shared/eventHooks';
/**
* Creates a wrapped handler that hooks into the Inferno
* eventHooks system based on the type of event being
* attached.
*
* @param {string} type
* @param {function} handler
* @return {function} wrapped handler
*/
export default function setHandler(type, handler) {
let wrapper = eventHooks[type];
if (wrapper) {
return wrapper(handler);
}
return { handler };
}
|
JavaScript
| 1 |
@@ -206,17 +206,17 @@
@param %7B
-f
+F
unction%7D
@@ -236,17 +236,17 @@
return %7B
-f
+F
unction%7D
|
f7c74c35ee5829a491930f85505f50400d9611ba
|
Fix code style
|
src/foam/u2/FloatView.js
|
src/foam/u2/FloatView.js
|
/**
* @license
* Copyright 2015 Google Inc. 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.
*/
foam.CLASS({
package: 'foam.u2',
name: 'FloatView',
extends: 'foam.u2.TextField',
documentation: 'View for editing Float Properties.',
css: `
^:read-only {
border: none;
background: rgba(0,0,0,0);
}
`,
properties: [
['type', 'number'],
{ class: 'Float', name: 'data' },
'precision',
'min',
'max',
{
class: 'Float',
name: 'step',
documentation: `The amount that the value should increment or decrement by
when the arrow buttons in the input are clicked.`,
value: 0.01
}
],
methods: [
function initE() {
this.SUPER();
this.addClass(this.myClass());
if ( this.min != undefined ) this.setAttribute('min', this.min);
if ( this.max != undefined ) this.setAttribute('max', this.max);
if ( this.step != undefined ) this.setAttribute('step', this.step);
},
function link() {
this.attrSlot(null, this.onKey ? 'input' : null).relateFrom(
this.data$,
this.textToData.bind(this),
this.dataToText.bind(this));
},
function fromProperty(p) {
this.SUPER(p);
this.precision = p.precision;
this.min = p.min;
this.max = p.max;
},
function formatNumber(val) {
if ( ! val ) return '0';
val = val.toFixed(this.precision);
var i = val.length - 1;
for ( ; i > 0 && val.charAt(i) === '0'; i -- ) {}
return val.substring(0, val.charAt(i) === '.' ? i : i + 1);
},
function dataToText(val) {
return this.precision !== undefined ?
this.formatNumber(val) :
'' + val;
},
function textToData(text) {
return parseFloat(text) || 0;
}
]
});
|
JavaScript
| 0.000169 |
@@ -2034,20 +2034,20 @@
=== '0'
+
; i
-
-- ) %7B%7D%0A
|
638bb3cf7fb54e7bed3a78a79f896fd4348438fc
|
Fix with @pablo's comment
|
src/geo/ui/fullscreen.js
|
src/geo/ui/fullscreen.js
|
/**
* FullScreen widget:
*
* var widget = new cdb.ui.common.FullScreen({
* doc: ".container", // optional; if not specified, we do the fullscreen of the whole window
* template: this.getTemplate("table/views/fullscreen")
* });
*
*/
cdb.ui.common.FullScreen = cdb.core.View.extend({
tagName: 'div',
className: 'cartodb-fullscreen',
events: {
"click a": "_toggleFullScreen"
},
initialize: function() {
_.bindAll(this, 'render');
_.defaults(this.options, this.default_options);
//this.model = new cdb.core.Model({
//allowWheelOnFullscreen: false
//});
this._addWheelEvent();
},
_addWheelEvent: function() {
var self = this;
var mapView = this.options.mapView;
$(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange', function() {
if ( !document.fullscreenElement && !document.webkitFullscreenElement && !document.mozFullScreenElement && !document.msFullscreenElement) {
if (self.model.get("allowWheelOnFullscreen")) {
mapView.options.map.set("scrollwheel", false);
}
}
mapView.invalidateSize();
});
},
_toggleFullScreen: function(ev) {
ev.stopPropagation();
ev.preventDefault();
var doc = window.document;
var docEl = doc.documentElement;
if (this.options.doc) { // we use a custom element
docEl = $(this.options.doc)[0];
}
var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
var mapView = this.options.mapView;
if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
if (docEl.webkitRequestFullScreen) {
// Cartodb.js #361 :: Full screen button not working on Safari 8.0.3 #361
// Safari has a bug that fullScreen doestn't work with Element.ALLOW_KEYBOARD_INPUT);
// Reference: Ehttp://stackoverflow.com/questions/8427413/webkitrequestfullscreen-fails-when-passing-element-allow-keyboard-input-in-safar
requestFullScreen.call(docEl, undefined);
} else {
// CartoDB.js #412 :: Fullscreen button is throwing errors
// Nowadays (2015/03/25), fullscreen is not supported in iOS Safari. Reference: http://caniuse.com/#feat=fullscreen
if (requestFullScreen !== undefined) {
requestFullScreen.call(docEl);
}
}
if (mapView) {
if (this.model.get("allowWheelOnFullscreen")) {
mapView.options.map.set("scrollwheel", true);
}
}
} else {
cancelFullScreen.call(doc);
}
},
render: function() {
var $el = this.$el;
var options = _.extend(this.options);
$el.html(this.options.template(options));
return this;
}
});
|
JavaScript
| 0 |
@@ -2529,22 +2529,8 @@
reen
- !== undefined
) %7B%0A
|
8e59a7f7dcbf1e9e11e10f6e3da033103a900bab
|
make loadArea return a promise from either exit point
|
src/helpers/load-area.js
|
src/helpers/load-area.js
|
import db from './db'
import {enhance as enhanceHanson} from '../area-tools'
import some from 'lodash/some'
import maxBy from 'lodash/maxBy'
import isArray from 'lodash/isArray'
import yaml from 'js-yaml'
function resolveArea(areas, query) {
if (!('revision' in query)) {
return maxBy(areas, 'revision')
}
else if (some(areas, possibility => 'dateAdded' in possibility)) {
return maxBy(areas, 'dateAdded')
}
else {
return maxBy(areas, possibility => possibility.sourcePath.length)
}
}
function loadArea(areaQuery) {
const {name, type, revision, source, isCustom} = areaQuery
let area = {...areaQuery}
if (isCustom && source) {
return {...areaQuery, _area: enhanceHanson(yaml.safeLoad(source))}
}
let dbQuery = {name: [name], type: [type]}
if (revision && revision !== 'latest') {
dbQuery.revision = [revision]
}
return db.store('areas').query(dbQuery)
.then(result => {
if (result === undefined) {
return {...areaQuery, _error: `the area "${name}" (${type}) could not be found with the query ${JSON.stringify(dbQuery)}`}
}
if (result.length === 1) {
result = result[0]
}
else if (result.length >= 2) {
result = resolveArea(result, dbQuery)
}
else {
result = {name, type, revision, _error: `the area "${name}" (${type}) could not be found with the query ${JSON.stringify(dbQuery)}`}
}
return {...areaQuery, _area: enhanceHanson(result)}
})
.catch(err => {
console.error(err) // we can probably remove this in the future
area._error = `Could not find area ${JSON.stringify(dbQuery)} (error: ${err.message})`
return area
})
}
const promiseCache = new Map()
export default async function getArea({name, type, revision, source, isCustom}, {cache=[]}) {
let cachedArea = find(cache, a => (a.name === name) && (a.type === type) && (revision === 'latest' ? true : a.revision === revision))
if (cachedArea) {
console.log('loadArea used cached area')
return cachedArea
}
let id = `{${name}, ${type}, ${revision}}`
if (promiseCache.has(id)) {
return promiseCache.get(id)
}
let promise = loadArea({name, type, revision, source, isCustom})
promiseCache.set(id, promise)
let area = await promiseCache.get(id)
promiseCache.delete(id)
return area
}
|
JavaScript
| 0.000001 |
@@ -639,32 +639,48 @@
rce) %7B%0A%09%09return
+Promise.resolve(
%7B...areaQuery, _
@@ -722,16 +722,17 @@
ource))%7D
+)
%0A%09%7D%0A%0A%09le
|
2eac86163be2bd5627dab3e33e8b4e0926895442
|
fix spelling in error message (#1427)
|
src/hooks/useSelector.js
|
src/hooks/useSelector.js
|
import {
useReducer,
useRef,
useEffect,
useMemo,
useLayoutEffect,
useContext
} from 'react'
import invariant from 'invariant'
import { useReduxContext as useDefaultReduxContext } from './useReduxContext'
import Subscription from '../utils/Subscription'
import { ReactReduxContext } from '../components/Context'
// React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser. We need useLayoutEffect to ensure the store
// subscription callback always has the selector from the latest render commit
// available, otherwise a store update may happen between render and the effect,
// which may cause missed updates; we also must ensure the store subscription
// is created synchronously, otherwise a store update may occur before the
// subscription is created and an inconsistent state may be observed
const useIsomorphicLayoutEffect =
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
typeof window.document.createElement !== 'undefined'
? useLayoutEffect
: useEffect
const refEquality = (a, b) => a === b
function useSelectorWithStoreAndSubscription(
selector,
equalityFn,
store,
contextSub
) {
const [, forceRender] = useReducer(s => s + 1, 0)
const subscription = useMemo(() => new Subscription(store, contextSub), [
store,
contextSub
])
const latestSubscriptionCallbackError = useRef()
const latestSelector = useRef()
const latestSelectedState = useRef()
let selectedState
try {
if (
selector !== latestSelector.current ||
latestSubscriptionCallbackError.current
) {
selectedState = selector(store.getState())
} else {
selectedState = latestSelectedState.current
}
} catch (err) {
let errorMessage = `An error occured while selecting the store state: ${err.message}.`
if (latestSubscriptionCallbackError.current) {
errorMessage += `\nThe error may be correlated with this previous error:\n${latestSubscriptionCallbackError.current.stack}\n\nOriginal stack trace:`
}
throw new Error(errorMessage)
}
useIsomorphicLayoutEffect(() => {
latestSelector.current = selector
latestSelectedState.current = selectedState
latestSubscriptionCallbackError.current = undefined
})
useIsomorphicLayoutEffect(() => {
function checkForUpdates() {
try {
const newSelectedState = latestSelector.current(store.getState())
if (equalityFn(newSelectedState, latestSelectedState.current)) {
return
}
latestSelectedState.current = newSelectedState
} catch (err) {
// we ignore all errors here, since when the component
// is re-rendered, the selectors are called again, and
// will throw again, if neither props nor store state
// changed
latestSubscriptionCallbackError.current = err
}
forceRender({})
}
subscription.onStateChange = checkForUpdates
subscription.trySubscribe()
checkForUpdates()
return () => subscription.tryUnsubscribe()
}, [store, subscription])
return selectedState
}
/**
* Hook factory, which creates a `useSelector` hook bound to a given context.
*
* @param {Function} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useSelector` hook bound to the specified context.
*/
export function createSelectorHook(context = ReactReduxContext) {
const useReduxContext =
context === ReactReduxContext
? useDefaultReduxContext
: () => useContext(context)
return function useSelector(selector, equalityFn = refEquality) {
invariant(selector, `You must pass a selector to useSelectors`)
const { store, subscription: contextSub } = useReduxContext()
return useSelectorWithStoreAndSubscription(
selector,
equalityFn,
store,
contextSub
)
}
}
/**
* A hook to access the redux store's state. This hook takes a selector function
* as an argument. The selector is called with the store state.
*
* This hook takes an optional equality comparison function as the second parameter
* that allows you to customize the way the selected state is compared to determine
* whether the component needs to be re-rendered.
*
* @param {Function} selector the selector function
* @param {Function=} equalityFn the function that will be used to determine equality
*
* @returns {any} the selected state
*
* @example
*
* import React from 'react'
* import { useSelector } from 'react-redux'
*
* export const CounterComponent = () => {
* const counter = useSelector(state => state.counter)
* return <div>{counter}</div>
* }
*/
export const useSelector = createSelectorHook()
|
JavaScript
| 0.000017 |
@@ -1875,16 +1875,17 @@
or occur
+r
ed while
|
2d7c845cd36daaec7c42f8965b9347df335acafe
|
Update TreeAPI.js
|
TreeAPI.js
|
TreeAPI.js
|
/*
* TreeAPI.js
*
* Provide a "Person" object where data is gathered from the WikiTree API.
* We use the WikiTree API action "getPerson" to retrieve the profile data and then store it in object fields.
*
*/
// Put our functions into a "WikiTreeAPI" namespace.
window.WikiTreeAPI = window.WikiTreeAPI || {};
// Our basic constructor for a Person. We expect the "person" data from the API returned result
// (see getPerson below). The basic fields are just stored in the internal _data array.
// We pull out the Parent and Child elements as their own Person objects.
WikiTreeAPI.Person = class Person {
constructor(data) {
this._data = data;
if(data.Parents){
for(var p in data.Parents){
this._data.Parents[p] = new WikiTreeAPI.Person(data.Parents[p]);
}
}
if(data.Children){
for(var c in data.Children){
this._data.Children[c] = new WikiTreeAPI.Person(data.Children[c]);
}
}
}
// Basic "getters" for the data elements.
getId() { return this._data.Id; }
getName() { return this._data.Name; }
getGender() { return this._data.Gender; }
getBirthDate() { return this._data.BirthDate; }
getBirthLocation() { return this._data.BirthLocation; }
getDeathDate() { return this._data.DeathDate; }
getDeathLocation() { return this._data.DeathLocation; }
getChildren() { return this._data.Children; }
getFatherId() { return this._data.Father; }
getMotherId() { return this._data.Mother; }
getDisplayName() { return this._data.BirthName ? this._data.BirthName : this._data.BirthNamePrivate; }
getPhotoUrl() {
if (this._data.PhotoData && this._data.PhotoData['url']) {
return this._data.PhotoData['url'];
}
}
// Getters for Mother and Father return the Person objects, if there is one.
// The getMotherId and getFatherId functions above return the actual .Mother and .Father data elements (ids).
getMother() {
if (this._data.Mother && this._data.Parents) {
return this._data.Parents[this._data.Mother];
}
}
getFather() {
if (this._data.Father && this._data.Parents) {
return this._data.Parents[this._data.Father];
}
}
// We use a few "setters". For the parents, we want to update the Parents Person objects as well as the ids themselves.
// For TreeViewer we only set the parents and children, so we don't need setters for all the _data elements.
setMother(person) {
var id = person.getId();
var oldId = this._data.Mother;
this._data.Mother = id;
if (!this._data.Parents) { this._data.Parents = {}; }
else if (oldId) { delete this._data.Parents[oldId]; }
this._data.Parents[id] = person;
}
setFather(person) {
var id = person.getId();
var oldId = this._data.Father;
this._data.Father = id;
if (!this._data.Parents) { this._data.Parents = {}; }
else if (oldId) { delete this._data.Parents[oldId]; }
this._data.Parents[id] = person;
}
setChildren(children) { this._data.Children = children; }
} // End Person class definition
// To get a Person for a given id, we POST to the APIs getPerson action. When we get a result back,
// we convert the returned JSON data into a Person object.
// Note that postToAPI returns the Promise from jquerys .ajax() call.
// That feeds our .then() here, which also returns a Promise, which gets resolved by the return inside the "then" function.
// So we can use this through our asynchronous actions with something like:
// WikiTree.getPerson.then(function(result) {
// // the "result" here is that from our API call. The profile data is in result[0].person.
// });
//
WikiTreeAPI.getPerson = function(id,fields) {
return WikiTreeAPI.postToAPI( { 'action': 'getPerson', 'key': id, 'fields': fields.join(','), 'resolveRedirect': 1 } )
.then(function(result) {
return new WikiTreeAPI.Person(result[0].person);
});
}
// This is just a wrapper for the Ajax call, sending along necessary options for the WikiTree API.
WikiTreeAPI.postToAPI = function (postData) {
var API_URL = 'https://api.wikitree.com/api.php';
var ajax = $.ajax({
// The WikiTree API endpoint
'url': API_URL,
// We tell the browser to send any cookie credentials we might have (in case we authenticated).
'xhrFields': { withCredentials: true },
// We're POSTing the data, so we don't worry about URL size limits and want JSON back.
type: 'POST',
dataType: 'json',
data: postData
});
return ajax;
}
// Utility function to get/set cookie data.
// Adapted from https://github.com/carhartl/jquery-cookie which is obsolete and has been
// superseded by https://github.com/js-cookie/js-cookie. The latter is a much more complete cookie utility.
// Here we just want to get and set some simple values in limited circumstances to track an API login.
// So we'll use a stripped-down function here and eliminate a prerequisite. This function should not be used
// in complex circumstances.
//
// key = The name of the cookie to set/read. If reading and no key, then array of all key/value pairs is returned.
// value = The value to set the cookie to. If undefined, the value is instead returned. If null, cookie is deleted.
// options = Used when setting the cookie,
// options.expires = Date or number of days in the future (converted to Date for cookie)
// options.path, e.g. "/"
// options.domain, e.g. "apps.wikitree.com"
// options.secure, if true then cookie created with ";secure"
WikiTreeAPI.cookie = function(key, value, options) {
if (options === undefined) { options = {}; }
// If we have a value, we're writing/setting the cookie.
if (value !== undefined) {
if (value === null) { options.expires = -1; }
if (typeof options.expires === 'number') {
var days = options.expires;
options.expires = new Date();
options.expires.setDate(options.expires.getDate() + days);
}
value = String(value);
return (document.cookie = [
encodeURIComponent(key), '=', value,
options.expires ? '; expires=' + options.expires.toUTCString() : '',
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// We're not writing/setting the cookie, we're reading a value from it.
var cookies = document.cookie.split('; ');
var result = key ? null : {};
for (var i=0,l=cookies.length; i<l; i++) {
var parts = cookies[i].split('=');
var name = parts.shift();
name = decodeURIComponent(name.replace(/\+/g, ' '));
var value = parts.join('=');
value = decodeURIComponent(value.replace(/\+/g, ' '));
if (key && key === name) {
result = value;
break;
}
if (!key) {
result[name] = value;
}
}
return result;
}
|
JavaScript
| 0 |
@@ -2975,16 +2975,17 @@
the API
+'
s getPer
|
35398b4671e29be63635256f08c9be8634f8852e
|
remove unnecessary line
|
adapter.js
|
adapter.js
|
'use strict';
// Dependencies
// ---
var _ = require('lodash');
var Bluebird = require('bluebird');
var Backbone = require('backbone');
var request = require('request');
var debug = require('./debug');
var BootieError = require('./error');
module.exports = Backbone.Model.extend({
urlRoot: '',
/**
* If there's an error, try your damndest to find it.
* APIs hide errors in all sorts of places these days
*
* @param {String|Object} body
* @return {String}
*/
_extractError: function(body) {
if (_.isString(body)) {
return body;
} else if (_.isObject(body) && _.isString(body.error)) {
return body.error;
} else if (_.isObject(body) && _.isString(body.msg)) {
return body.msg;
} else if (_.isObject(body) && _.isObject(body.error)) {
return this._extractError(body.error);
} else if (_.isObject(body) && _.isString(body.message)) {
return body.message;
} else if (_.isObject(body) &&
body.meta &&
_.isString(body.meta.error_message)) {
return body.meta.error_message;
} else {
return 'Unknown Request Error';
}
},
/**
* Build and configure the request options
*
* @param {Object} options
* @param {String} options.url
* @param {String} [options.path=]
* @param {String} [options.method=GET]
* @param {String} [options.qs={}]
* @param {String} [options.headers={}]
* @param {String} options.json
* @param {String} options.form
* @param {String} options.body
* @param {String} options.access_token
* @param {String} options.oauth_token
* @param {String} options.authorization_token
* @param {String} options.auth
* @return {Object}
*/
_buildRequestOptions: function(options) {
options = options || {};
// Set default path
if (!options.url && !options.path) {
options.path = '';
}
// Prepare the request
var requestOptions = {
method: options.method || 'GET',
url: options.url || this.urlRoot + options.path,
qs: options.qs || {},
headers: options.headers || {},
};
// Add `form`, `body`, or `json` as Request Payload (only one per request)
//
// If `json` is a Boolean,
// Request will set` Content-Type`
// and call `JSON.stringify()` on `body`
if (options.body) {
requestOptions.body = options.body;
requestOptions.json = _.isBoolean(options.json) ? options.json : true;
} else if (options.form) {
requestOptions.form = options.form;
requestOptions.headers['Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
} else if (_.isBoolean(options.json) || _.isObject(options.json)) {
requestOptions.json = options.json;
}
// Basic HTTP Auth
if (options.auth) {
requestOptions.auth = options.auth;
}
// Access Token
var accessToken = options.access_token || this.get('access_token');
if (accessToken) {
_.defaults(requestOptions.headers, {
Authorization: ['Bearer', accessToken].join(' ')
});
}
// OAuth Token
var oauthToken = options.oauth_token || this.get('oauth_token');
if (oauthToken) {
_.defaults(requestOptions.headers, {
Authorization: ['OAuth', oauthToken].join(' ')
});
}
// Authorization Token (No Scheme)
var authorizationToken = options.authorization_token || this.get('authorization_token');
if (authorizationToken) {
_.defaults(requestOptions.headers, {
Authorization: authorizationToken
});
}
return requestOptions;
},
/**
* Send an HTTP Request with provided request options
*
* @param {Object} options
* @param {Function} callback
* @return {Promise}
*/
sendRequest: function(options, callback) {
// Create a promise to defer to later
var deferred = Bluebird.defer();
var requestOptions = this._buildRequestOptions(options);
// Fire the request
request(this._buildRequestOptions(options), function(err, response, body) {
// Handle Errors
if (err) {
// Usually a connection error (server unresponsive)
err = new BootieError(err.message || 'Internal Server Error', err.code || 500);
} else if (response.statusCode >= 400) {
// Usually an intentional error from the server
err = new BootieError(this._extractError(body), response.statusCode);
}
if (err) {
debug.error(
'Adapter Request Error with Code: %d and Message: %s',
err.code,
err.message
);
callback && callback(err);
return deferred.reject(err);
}
// Handle Success
debug.log(
'Adapter Request Sent with code: %d and body: %s',
response.statusCode,
body
);
callback && callback(null, body);
return deferred.resolve(body);
}.bind(this));
return deferred.promise;
}
});
|
JavaScript
| 0.669882 |
@@ -3869,69 +3869,8 @@
r();
-%0A var requestOptions = this._buildRequestOptions(options);
%0A%0A
|
dae269d0aa25d0174a48d2cc3e9b170a7d50bc43
|
add missing prop types
|
renderer/components/Autopay/AutopayCardView.js
|
renderer/components/Autopay/AutopayCardView.js
|
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { themeGet } from 'styled-system'
import { Box, Flex } from 'rebass'
import { Card, Heading } from 'components/UI'
import AutopayAddButton from './AutopayAddButton'
import AutopayLimitBadge from './AutopayLimitBadge'
const CardWithBg = styled(Card)`
position: relative;
background-image: url(${props => props.src});
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
height: 300px;
width: 195px;
border-radius: 40px;
padding: 0;
cursor: pointer;
`
const Overlay = styled(Flex)`
position: absolute;
height: 100%;
width: 100%;
pointer-events: none;
`
const GradientOverlay = styled(Card)`
position: absolute;
background-image: linear-gradient(
146deg,
${themeGet('colors.tertiaryColor')},
${themeGet('colors.primaryColor')}
);
opacity: 0.5;
width: 100%;
height: 100%;
border-radius: 40px;
transition: all 0.25s;
&:hover {
opacity: 0;
}
`
const TextOverlay = styled(Overlay)`
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
`
const AutopayCardView = ({
merchant: { image, nickname, pubkey, isActive, limit, limitCurrency },
onClick,
...rest
}) => (
<Box {...rest} onClick={() => onClick(`${pubkey}`)}>
<CardWithBg mb="12px" src={image}>
<GradientOverlay />
<TextOverlay alignItems="center" flexDirection="column" justifyContent="center" p={3}>
<Heading.h1 fontWeight="normal" textAlign="center">
{nickname}
</Heading.h1>
</TextOverlay>
<Overlay alignItems="flex-end" justifyContent="center" mt={isActive ? -15 : 12}>
{isActive ? (
<AutopayLimitBadge limit={limit} limitCurrency={limitCurrency} />
) : (
<AutopayAddButton />
)}
</Overlay>
</CardWithBg>
</Box>
)
AutopayCardView.propTypes = {
merchant: PropTypes.shape({
description: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
nickname: PropTypes.string.isRequired,
pubkey: PropTypes.string.isRequired,
}),
onClick: PropTypes.func.isRequired,
}
export default React.memo(AutopayCardView)
|
JavaScript
| 0.00048 |
@@ -2026,24 +2026,142 @@
isRequired,%0A
+ isActive: PropTypes.bool,%0A limit: PropTypes.string.isRequired,%0A limitCurrency: PropTypes.string.isRequired,%0A
nickname
|
fe6ab2bdaa247c4b1a7bb5e22aca3a2c1eaa3b79
|
Use mouse wheel to zoom by default
|
client-data/tools/zoom/zoom.js
|
client-data/tools/zoom/zoom.js
|
/**
* WHITEBOPHIR
*********************************************************
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2013 Ophir LOJKINE
*
*
* The JavaScript code in this page is free software: you can
* redistribute it and/or modify it under the terms of the GNU
* General Public License (GNU GPL) as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. The code is distributed WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
*
* As additional permission under GNU GPL version 3 section 7, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 4, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
* @licend
*/
(function () { //Code isolation
var ZOOM_FACTOR = .5;
var origin = {
scrollX: document.documentElement.scrollLeft,
scrollY: document.documentElement.scrollTop,
x: 0.0,
y: 0.0,
clientY: 0,
scale: 1.0
};
var moved = false, pressed = false;
function zoom(origin, scale) {
var oldScale = origin.scale;
var newScale = Tools.setScale(scale);
window.scrollTo(
origin.scrollX + origin.x * (newScale - oldScale),
origin.scrollY + origin.y * (newScale - oldScale)
);
}
var animation = null;
function animate(scale) {
cancelAnimationFrame(animation);
animation = requestAnimationFrame(function () {
zoom(origin, scale);
});
}
function setOrigin(x, y, evt, isTouchEvent) {
origin.scrollX = document.documentElement.scrollLeft;
origin.scrollY = document.documentElement.scrollTop;
origin.x = x;
origin.y = y;
origin.clientY = getClientY(evt, isTouchEvent);
origin.scale = Tools.getScale();
}
function press(x, y, evt, isTouchEvent) {
evt.preventDefault();
setOrigin(x, y, evt, isTouchEvent);
moved = false;
pressed = true;
}
function move(x, y, evt, isTouchEvent) {
if (pressed) {
evt.preventDefault();
var delta = getClientY(evt, isTouchEvent) - origin.clientY;
var scale = origin.scale * (1 + delta * ZOOM_FACTOR / 100);
if (Math.abs(delta) > 1) moved = true;
animation = animate(scale);
}
}
function onwheel(evt) {
evt.preventDefault();
if (evt.ctrlKey || Tools.curTool === zoomTool) {
// zoom
var scale = Tools.getScale();
var x = evt.pageX / scale;
var y = evt.pageY / scale;
setOrigin(x, y, evt, false);
animate((1 - ((evt.deltaY > 0) - (evt.deltaY < 0)) * 0.25) * Tools.getScale());
} else if (evt.altKey) {
// make finer changes if shift is being held
var change = evt.shiftKey ? 1 : 5;
// change tool size
Tools.setSize(Tools.getSize() - ((evt.deltaY > 0) - (evt.deltaY < 0)) * change);
} else if (evt.shiftKey) {
// scroll horizontally
window.scrollTo(document.documentElement.scrollLeft + evt.deltaY, document.documentElement.scrollTop + evt.deltaX);
} else {
// regular scrolling
window.scrollTo(document.documentElement.scrollLeft + evt.deltaX, document.documentElement.scrollTop + evt.deltaY);
}
}
Tools.board.addEventListener("wheel", onwheel, { passive: false });
Tools.board.addEventListener("touchmove", function ontouchmove(evt) {
// 2-finger pan to zoom
var touches = evt.touches;
if (touches.length === 2) {
var x0 = touches[0].clientX, x1 = touches[1].clientX,
y0 = touches[0].clientY, y1 = touches[1].clientY,
dx = x0 - x1,
dy = y0 - y1;
var x = (touches[0].pageX + touches[1].pageX) / 2 / Tools.getScale(),
y = (touches[0].pageY + touches[1].pageY) / 2 / Tools.getScale();
var distance = Math.sqrt(dx * dx + dy * dy);
if (!pressed) {
pressed = true;
setOrigin(x, y, evt, true);
origin.distance = distance;
} else {
var delta = distance - origin.distance;
var scale = origin.scale * (1 + delta * ZOOM_FACTOR / 100);
animate(scale);
}
}
}, { passive: true });
function touchend() {
pressed = false;
}
Tools.board.addEventListener("touchend", touchend);
Tools.board.addEventListener("touchcancel", touchend);
function release(x, y, evt, isTouchEvent) {
if (pressed && !moved) {
var delta = (evt.shiftKey === true) ? -1 : 1;
var scale = Tools.getScale() * (1 + delta * ZOOM_FACTOR);
zoom(origin, scale);
}
pressed = false;
}
function key(down) {
return function (evt) {
if (evt.key === "Shift") {
Tools.svg.style.cursor = "zoom-" + (down ? "out" : "in");
}
}
}
function getClientY(evt, isTouchEvent) {
return isTouchEvent ? evt.changedTouches[0].clientY : evt.clientY;
}
var keydown = key(true);
var keyup = key(false);
function onstart() {
window.addEventListener("keydown", keydown);
window.addEventListener("keyup", keyup);
}
function onquit() {
window.removeEventListener("keydown", keydown);
window.removeEventListener("keyup", keyup);
}
var zoomTool = {
"name": "Zoom",
"shortcut": "z",
"listeners": {
"press": press,
"move": move,
"release": release,
},
"onstart": onstart,
"onquit": onquit,
"mouseCursor": "zoom-in",
"icon": "tools/zoom/icon.svg",
"helpText": "click_to_zoom",
"showMarker": true,
};
Tools.add(zoomTool);
})(); //End of code isolation
|
JavaScript
| 0.000315 |
@@ -2766,24 +2766,25 @@
if (
+!
evt.ctrlKey
@@ -2786,38 +2786,8 @@
lKey
- %7C%7C Tools.curTool === zoomTool
) %7B%0A
|
53bad06f03993d27d4c686c8768c8f1d5890bcba
|
fix log => console.log
|
verbose.js
|
verbose.js
|
/**
*
*/
function logAutoconnectProxy(acp){
console.log('adding logger');
acp.on('source.connect',function(source){
source.on('open',function(){
console.log('autoconnect created proxy: there are '+acp.connectionPoolCount()+' ready sockets');
}).on('message', function message(data, flags) {
console.log('autoconnect proxy source sends: '+(typeof data));
}).on('close',function(code, message){
console.log('autoconnect proxy source close: '+code+' '+message);
}).on('error',function(error){
console.log('autoconnect proxy source error: '+error);
});
}).on('destination.connect',function(destination){
destination.on('message', function message(data, flags) {
console.log('autoconnect proxy destination sends: '+(typeof data));
}).on('error',function(error){
console.error('autoconnect proxy destination error: '+error+' | '+(typeof error));
}).on('close',function(code, message){
console.log('autoconnect proxy destination close: '+code+' '+message);
});
});
}
function logBridgeProxy(brdg){
brdg.server.on('close',function(code, mesage){
console.log('bridge closed: '+code+' - '+message);
});
brdg.on('server.connect',function(server){
console.log('bridge recieved server socket');
server.on('message', function message(data, flags) {
console.log('bridge server sends: '+(typeof data));
}).on('close',function(code, message){
console.log('bridge server close: '+code+' '+message);
}).on('error',function(error){
console.log('bridge server error: '+error)
})
}).on('client.connect',function(client){
console.log('bridge recieved client socket');
client.on('message', function message(data, flags) {
log('bridge client sends: '+(typeof data));
}).on('close',function(code, message){
console.log('bridge client close: '+code+' '+message);
}).on('error',function(error){
console.log('bridge client error: '+error)
});
}).on('pair',function(server, client){
console.log('bridge paired server client sockets');
});
}
module.exports={
logAutoconnectProxy:logAutoconnectProxy,
logBridgeProxy:logBridgeProxy
}
|
JavaScript
| 0.000003 |
@@ -1698,17 +1698,24 @@
gs) %7B%0A%09%09
-%09
+console.
log('bri
|
a6163b8d8f8397a29b5e80b47b5ec96e1a68d789
|
add this to get/set attribute function
|
client/muon/m_41_modelviews.js
|
client/muon/m_41_modelviews.js
|
function __setGetElementValue__(view,getter){
function set(val){
if (!this.dataset["attrType"]){
if (this.tagName == "INPUT" || this.tagName == "SELECT" || this.tagName == "TEXTAREA") $(this).val(val);
else this.innerText = val;
}
else if (this.dataset["attrType"] == "text") this.innerText = val;
else if (this.dataset["attrType"] == "html") this.innerHTML = val;
else $(this).attr(this.dataset["attrType"],val);
}
if (typeof view["get_"+getter] == "function"){
var val = view["get_"+getter]();
if (typeof val == "object" && "then" in val) val.then(set.bind(this));
else set.call(this,val);
}
else set.call(this,view.model.get(getter));
}
function __updateModelView__(attrs){
var _this = this;
if (this.$el.find("[data-model-attr]").length != 0){
for(var i in attrs){
var $subElement = this.$el.find("[data-model-attr^='"+i+"']");
if (!$subElement.length) continue;
$subElement.each(function(){
var attrsList = this.dataset["modelAttr"].split(".");
var attrValue = attrs[attrsList.shift()];
try {
while(attrsList.length != 0){
attrValue = attrValue[attrsList.shift()];
}
}
catch(e){
attrValue = attrValue.toString();
}
if (!this.dataset["attrType"]) this.innerText = attrValue;
else if (this.dataset["attrType"] == "text") this.innerText = attrValue;
else if (this.dataset["attrType"] == "html") this.innerHTML = attrValue;
else $(this).attr(this.dataset["attrType"],attrValue);
});
}
}
this.$el.find("[data-model-get],[data-model-set]").each(function(){
__setGetElementValue__.call(this,_this,this.dataset.modelGet || this.dataset.modelSet);
});
__renderDataRoutes__.call(this);
}
m.ModelView = m.View.extend({
viewType: "model",
initialize: function(model){
var _this = this;
this.model = model;
this.listenTo(model,"change",this.__update__);
this.listenTo(model,"destroy",_this.remove);
m.View.prototype.initialize.apply(this,arguments);
},
__set__: function(){
__updateModelView__.call(this,this.model.attributes);
var view = this;
this.$el.find("[data-model-set]").each(function(){
var setter = this.dataset.modelSet;
var _this = this;
var interval = null;
view.listenTo(view.model,"sync",function(){
__setGetElementValue__.call(_this,view,setter);
});
if (!(this.dataset.silent || view.silent)){
$(this).keyup(function(){
clearTimeout(interval);
interval = setTimeout(function(){$(_this).trigger("change");},150);
});
$(this).change(function(){
if (typeof view["set_"+setter] == "function") view["set_"+setter]($(this).val(),this);
else view.model.set(setter,$(this).val());
});
}
});
this.$el.attr("id",this.model.id);
},
__update__:function(a,b,c){
__updateModelView__.call(this,this.model.changedAttributes());
},
remove: function(){
if (!this.model.collection){
delete __syncNames__[this.__syncName__];
}
m.View.prototype.remove.call(this);
},
destroy: function(){
return this.model.destroy();
},
save: function(){
var view = this;
this.$el.find("[data-model-set]").each(function(){
var setter = this.dataset.modelSet;
if (typeof view["set_"+setter] == "function") view["set_"+setter]($(this).val(),this);
else view.model.set(setter,$(this).val(),{silent: true});
});
return view.model.save();
},
fetch: function(){
return this.model.fetch();
}
});
|
JavaScript
| 0.000001 |
@@ -570,18 +570,53 @@
getter%5D(
-);
+this);%0A // %D0%94%D0%BB%D1%8F %D0%B4%D0%B5%D1%84%D0%B5%D1%80%D0%B5%D0%B4 %D0%BE%D1%82%D0%B2%D0%B5%D1%82%D0%BE%D0%B2
%0A
|
0409a44f651085db0ba913eb516a184b3729a1e9
|
Update companies filter test
|
test/functional/cypress/specs/companies/filter-spec.js
|
test/functional/cypress/specs/companies/filter-spec.js
|
const selectors = require('../../../../selectors')
describe('Company Collections Filter', () => {
before(() => {
cy.visit('/companies?sortby=collectionTest')
cy.get(selectors.entityCollection.entities)
.children()
.should('have.length', 9)
cy.get(selectors.entityCollection.collection).should(
'contain',
'100,172 companies'
)
})
beforeEach(() => {
cy.server()
cy.route('/companies?*').as('filterResults')
})
it('should filter by name', () => {
cy.get(selectors.filter.name).type('FilterByCompany').type('{enter}')
cy.get(selectors.entityCollection.entities)
.children()
.should('have.length', 1)
cy.get(selectors.entityCollection.collection).should(
'contain',
'1 company matching FilterByCompany'
)
cy.get(selectors.entityCollection.collectionRowMessage).should(
'contain',
'You can now download this company'
)
cy.get(selectors.entityCollection.collectionRowButton).should('be.visible')
})
it('should filter by active status', () => {
cy.get(selectors.filter.statusActive).click()
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain(
'?sortby=collectionTest&custom=true&name=FilterByCompany&archived=false'
)
})
cy.get(selectors.entityCollection.entities)
.children()
.should('have.length', 1)
})
it('should filter by inactive status', () => {
cy.get(selectors.filter.statusInactive).click()
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain(
'?sortby=collectionTest&custom=true&name=FilterByCompany&archived=false&archived=true'
)
})
cy.get(selectors.entityCollection.entities)
.children()
.should('have.length', 1)
})
it('should filter by last interaction date', () => {
cy.get(selectors.filter.firstInteractionDate).click()
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain('interaction_between=0')
})
cy.get(selectors.entityCollection.entities)
.children()
.should('have.length', 1)
})
it('should remove all filters', () => {
cy.get(selectors.entityCollection.collectionRemoveAllFilter).click()
cy.get(selectors.entityCollection.collection).should(
'contain',
'100,172 companies'
)
})
it('should filter by sector', () => {
const sector = selectors.filter.sector
const { typeahead } = selectors.filter
cy.get(typeahead(sector).selectedOption)
.click()
.get(typeahead(sector).textInput)
.type('Advanced Engineering')
.get(typeahead(sector).options)
.should('have.length', 1)
.get(typeahead(sector).textInput)
.type('{enter}')
.type('{esc}')
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain(
'sector_descends=af959812-6095-e211-a939-e4115bead28a'
)
})
})
it('should filter by country', () => {
const country = selectors.filter.country
const { typeahead } = selectors.filter
cy.get(typeahead(country).selectedOption)
.click()
.get(typeahead(country).textInput)
.type('United Kingdom')
.get(typeahead(country).options)
.should('have.length', 1)
.get(typeahead(country).textInput)
.type('{enter}')
.type('{esc}')
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain('country=80756b9a-5d95-e211-a939-e4115bead28a')
})
})
it('should filter by currently exporting to', () => {
const exportingTo = selectors.filter.exportingTo
const { typeahead } = selectors.filter
cy.get(typeahead(exportingTo).selectedOption)
.click()
.get(typeahead(exportingTo).textInput)
.type('Australia')
.get(typeahead(exportingTo).options)
.should('have.length', 1)
.get(typeahead(exportingTo).textInput)
.type('{enter}')
.type('{esc}')
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain(
'export_to_countries=9f5f66a0-5d95-e211-a939-e4115bead28a'
)
})
})
it('should filter by future countries of interest', () => {
const interestedIn = selectors.filter.interestedIn
const { typeahead } = selectors.filter
cy.get(typeahead(interestedIn).selectedOption)
.click()
.get(typeahead(interestedIn).textInput)
.type('Bahamas')
.get(typeahead(interestedIn).options)
.should('have.length', 1)
.get(typeahead(interestedIn).textInput)
.type('{enter}')
.type('{esc}')
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain(
'future_interest_countries=a25f66a0-5d95-e211-a939-e4115bead28a'
)
})
})
it('should filter by UK postcode', () => {
const POSTCODE = 'GL11'
cy.reload(true)
cy.get(selectors.filter.ukPostcode).should('be.visible')
cy.get(selectors.filter.ukPostcode).clear().type(POSTCODE).type('{enter}')
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain(`uk_postcode=${POSTCODE}`)
})
cy.get(selectors.entityCollection.entities)
.children()
.should('have.length', 24)
})
it('should filter by Lead ITA and Global Account Manager', () => {
const leadIta = selectors.filter.leadIta
const { typeahead } = selectors.filter
cy.get(typeahead(leadIta).selectedOption)
.click()
.get(typeahead(leadIta).textInput)
.type('Shawn Cohen')
.get(typeahead(leadIta).options)
.should('have.length', 63)
cy.get(typeahead(leadIta).selectedOption).type('{enter}').type('{esc}')
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain(
'one_list_group_global_account_manager=2c42c516-9898-e211-a939-e4115bead28a'
)
})
})
it('should filter by uk region', () => {
const { ukRegion, typeahead } = selectors.filter
cy.get(typeahead(ukRegion).selectedOption)
.click()
.get(typeahead(ukRegion).textInput)
.type('North West')
.get(typeahead(ukRegion).options)
.should('have.length', 1)
.get(typeahead(ukRegion).textInput)
.type('{enter}')
.type('{esc}')
cy.wait('@filterResults').then((xhr) => {
expect(xhr.url).to.contain(
'uk_region=824cd12a-6095-e211-a939-e4115bead28a'
)
})
})
})
|
JavaScript
| 0 |
@@ -5556,17 +5556,17 @@
ngth', 6
-3
+4
)%0A%0A c
|
f844f1093d1c4398e3db5b718de0221a809c110c
|
Update version string to 2.5.2
|
version.js
|
version.js
|
if (enyo && enyo.version) {
enyo.version["enyo-ilib"] = "2.5.2-rc.1";
}
|
JavaScript
| 0.000004 |
@@ -60,13 +60,8 @@
.5.2
--rc.1
%22;%0A%7D
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.