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
|
---|---|---|---|---|---|---|---|
4de5e59b82f22af29cd61de627d00584e18f4e97 | fix bugs | static/js/room.js | static/js/room.js | 'use strict';
var socket;
var room = "";
// var i = 0;
// var Fake = [
// 'Hi there, I\'m Trump and you?',
// 'Nice to meet you',
// 'How are you?',
// 'Not too bad, thanks',
// 'What do you do?',
// 'That\'s awesome',
// 'Codepen is a nice place to stay',
// 'I think you\'re a nice person',
// 'Why do you think that?',
// 'Can you explain?',
// 'Anyway I\'ve gotta go now',
// 'It was a pleasure chat with you',
// 'Time to make a new codepen',
// 'Bye',
// ':)'
// ];
$(document).ready(function() {
initializePage();
$(window).unload(function(){
socket.disconnect();
})
})
function initializePage() {
room = $('#roomName').text();
socket = io.connect('http://localhost:3000', {'sync disconnect on unload':true});
socket.emit("login", {programName: room});
socket.on("receiveMsg", renderReceivedMessage);
socket.on("userJoined", renderUserJoined);
$('.message-submit').click(sendMessage);
$('input[type="text"].message-input').keydown(function(e){
if (e.keyCode == 13){
sendMessage(e);
}
});
}
function sendMessage(e) {
e.preventDefault();
var content = $('.message-input').val();
$('.message-input').val("");
if(content.length == 0){
console.log("empty input received");
}
else{
var message = {
"content":content,
"program":room
};
renderMessage(message);
socket.emit("sendMsg", message);
}
}
function fakeMessage(){
console.log("faked");
var content = Fake[i];
i ++;
var date = new Date();
var time = date.getHours() + ":" + date.getMinutes();
var addHTML = '<div class="message-inverse">\
<div class="msg-content">' + content +
'</div>\
<img id="" class="" src="/img/trump.jpeg" alt="">\
<div class="timestamp" id="">' + time + '\
</div>\
</div>';
$('.messages').append(addHTML);
updateScrollBar();
}
function renderMessage(data){
var content = data.content;
var date = new Date();
var time = date.getHours() + ":" + date.getMinutes();
var addHTML = '<div class="message-block">\
<div class="msg-content">' + content +
'</div>\
<img id="" class="" src="/img/profile-max.jpg" alt="">\
<div class="timestamp" id="">' + time + '\
</div>\
</div>';
$('.messages').append(addHTML);
updateScrollBar();
setTimeout(function() {
// fakeMessage();
}, 1000 + (Math.random() * 20) * 100);
}
function renderReceivedMessage(data){
console.log("received");
var content = data.content;
var date = new Date();
var time = date.getHours() + ":" + date.getMinutes();
var addHTML = '<div class="message-inverse">\
<div class="msg-content">' + content +
'</div>\
<img id="" class="" src="/img/trump.jpeg" alt="">\
<div class="timestamp" id="">' + time + '\
</div>\
</div>';
$('.messages').append(addHTML);
updateScrollBar();
}
function renderUserJoined(data){
console.log("current number of connected users:" + data);
}
function updateScrollBar() {
$('html, body').scrollTop( $(document).height() - $(window).height() );
}
| JavaScript | 0.000001 | @@ -703,67 +703,8 @@
ect(
-'http://localhost:3000', %7B'sync disconnect on unload':true%7D
);%0A
@@ -2870,18 +2870,16 @@
%22 + data
-);
%0A%7D%0A%0A%0A%0Afu
|
9f5698aba278345de56576e262493d5e98a35db1 | return model after setting from it | client/hippo/components/form/api.js | client/hippo/components/form/api.js | /* eslint no-param-reassign: ["error", {
"props": true, "ignorePropertyModificationsFor": ["field", "model"]
}] */
import { observable, computed, when, action } from 'mobx';
import {
pick, isFunction, mapValues, every, get, set, filter, isNil, each, extend,
} from 'lodash';
export class FormField {
name: '';
@observable isTouched = false
@observable isChanged = false;
@observable value = '';
@observable message = '';
@observable help;
@observable validate;
@observable default;
constructor(name, attrs) {
this.name = name;
this.update(attrs);
if (this.default) {
this.value = this.default;
}
}
update(attrs) {
each(pick(attrs, [
'name', 'default', 'help', 'validate', 'value',
]), (v, k) => {
this[k] = isFunction(v) ? v.call(this) : v;
});
}
@action.bound
onChange({ target: { value: updatedValue } }) {
this.isChanged = (this.value !== updatedValue);
this.value = updatedValue;
}
@action.bound
exposeError() {
if (!this.isValid) {
this.isTouched = true;
}
}
@action.bound
onBlur() {
this.isTouched = true;
}
@computed get isValid() {
if (!this.validate) { return true; }
return !!this.validate.test(this.value);
}
@computed get invalidMessage() {
return (!this.isValid && this.isTouched) ? this.validate.message : null;
}
get events() {
return {
onBlur: this.onBlur,
onChange: this.onChange,
};
}
reset() {
this.value = '';
this.isTouched = false;
this.isChanged = false;
}
}
export class FormState {
fields = observable.map();
@action
setFields(fields) {
this.fields.replace(
mapValues(fields, (field, name) => new FormField(name, field)),
);
}
@action
setField(name, attrs) {
let field = this.fields.get(name);
if (field) {
field.update(attrs);
} else {
field = new FormField(name, extend({}, attrs, { value: get(this.values, name) }));
this.fields.set(name, field);
}
return field;
}
@computed get invalidFields() {
return filter(this.fields.values(), { isValid: false });
}
@computed get isValid() {
return 0 === this.invalidFields.length;
}
@computed get isTouched() {
return !every(this.fields.values(), { isTouched: false });
}
@action
exposeErrors() {
this.fields.forEach(field => field.exposeError());
}
@action
reset() {
this.fields.forEach(field => field.reset());
}
get(path, defaultValue) {
const [name, ...rest] = path.split('.');
const field = this.fields.get(name);
if (!field) { return defaultValue; }
if (rest.length) {
return get(field, rest.join('.'), defaultValue);
}
return field;
}
@action
set(values) {
this.values = values;
this.fields.forEach((field, name) => {
const value = get(values, name);
field.value = isNil(value) ? '' : value;
});
}
@action
update(values) {
each(values, (v, k) => {
const field = this.fields.get(k);
if (field) { field.value = v; }
});
}
@action
setFromModel(model) {
if (get(model, 'syncInProgress.isFetch')) {
when(
() => !get(model, 'syncInProgress.isFetch'),
() => this.set(model),
);
} else {
this.set(model);
}
}
persistTo(model) {
this.fields.forEach((field, name) => (set(model, name, field.value)));
return Promise.resolve(model);
}
}
| JavaScript | 0.000001 | @@ -3741,32 +3741,54 @@
del);%0A %7D%0A
+ return model;%0A
%7D%0A%0A persi
|
20cecd96a2365ec96689ab10b80d485ab93fb4ca | Fix create grant request | client/javascript/overviewGrants.js | client/javascript/overviewGrants.js | var template;
var user;
var grantid;
var loadDepartmentNavigation = function(overview) {
if(overview.user.permissions.level == 1) {
var stages = ["Research", "Internal", "ASU", "Complete"];
overview.departmentNames = stages;
overview.currentDepartment = overview.user.permissions.stage;
}
};
var loadDepartment = function(grantID, stageIndex) {
var query = '/setAdminStage?stage=' + stageIndex;
$.ajax({
url: query,
type: 'POST',
contentType: 'application/json',
success: function() {
window.location = '/detail/' + grantID;
}
});
};
var editGrant = function (grantid) {
jsonObj = {
title: $('#grantNameEdit').val(),
description: $('#grantDescriptionEdit').summernote('code'),
url: $('#grantUrlEdit').val()
};
$.ajax({
url: '/grants/' + grantid,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
$set: jsonObj
}),
}).done(function() {
window.location.reload(true);
});
}
$(function() {
$.ajax({
url: 'getOverview',
type: 'GET',
dataType: 'json',
success: function(overview) {
user = overview.user;
loadNavbar(user);
loadDepartmentNavigation(overview);
$.ajax({
url : 'templates/overviewPanel.html',
dataType: 'html',
method: 'GET',
success: function(data) {
template = Handlebars.compile(data);
$("#overviewContent").append(template(overview));
$('[data-toggle="tooltip"]').tooltip({container:'body'});
}
});
}
});
$('#grantGen * [data-toggle="popover"]').popover({
container:'body',
html : true
});
$('#grantEdit').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
grantid = button.data('grantid'); // Extract info from data-* attributes
var modal = $(this);
$.ajax({
url: '/grants/' + grantid,
type: 'GET',
dataType: 'json'
}).done(function(data) {
$('#grantNameEdit').val(data.title);
$('#grantUrlEdit').val(data.url);
$('#grantDescriptionEdit').summernote('code', data.description);
$('#grantEditSubmit').click(function () {
editGrant(grantid);
});
// $('#grantEditDismiss').click(function () {
// $('#grantEditSubmit').unbind();
// })
});
});
$("#cardGenCreate").click(function () {
var grantDescription = $("#grantDescription").summernote('code');
var grantName = $("#grantName").val();
var grantUrl = $("#grantUrl").val();
var myGrant = {
title : grantName,
description : grantDescription,
url : grantUrl,
users : [],
cardCount : 0,
stages: [
{
progress: 0.0,
toDo: [],
inProgress: [],
complete: []
},
{
progress: 0.0,
toDo: [],
inProgress: [],
complete: []
},
{
progress: 0.0,
toDo: [],
inProgress: [],
complete: []
},
{
progress: 0.0,
cards: []
}
]
};
$.ajax({
url: 'http://localhost:8080/grants',
type: 'PUT',
data: JSON.stringify(myGrant),
contentType: 'application/json',
success: function(result) {
var updateObj = {$addToSet: {grantIds: result._id}};
$.ajax({
url: '/users/' + user._id,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(updateObj),
success: function() {
window.location.reload(true);
}
});
}
});
})
$('#modalDelete').on('hidden.bs.modal', function() {
$('#grantEdit').modal('hide');
});
$('#confirmDeleteButton').click(function() {
$.ajax({
url: '/grants/' + grantid,
type: 'DELETE',
contentType: 'application/json',
success: function() {
window.location.reload(true);
}
});
});
});
| JavaScript | 0.000001 | @@ -3186,29 +3186,8 @@
l: '
-http://localhost:8080
/gra
|
9863ac3ed573024cd9f9984ecfed2f2a09e35de5 | Add POST request to the SET_CHANNEL action | src/actions/index.js | src/actions/index.js | import axios from 'axios';
// get top twitch channels
export const GET_CHANNELS = 'GET_CHANNELS';
export function getChannels() {
const request = axios.get('https://api.twitch.tv/kraken/streams?api_version=3&limit=10');
return {
type: GET_CHANNELS,
payload: request,
};
}
// set the currently active channel
export const SET_CHANNEL = 'SET_CHANNEL';
export function setChannel(channel) {
return {
type: SET_CHANNEL,
payload: channel,
};
}
export const GET_MESSAGE = 'GET_MESSAGE';
export function getMessage(data) {
return {
type: GET_MESSAGE,
payload: data,
};
}
| JavaScript | 0 | @@ -21,16 +21,63 @@
xios';%0A%0A
+const ROOT_URL = 'http://localhost:3000/api';%0A%0A
// get t
@@ -440,24 +440,97 @@
(channel) %7B%0A
+ const request = axios.post(%60$%7BROOT_URL%7D/channels/subscribe%60, channel);%0A
return %7B%0A
@@ -564,23 +564,23 @@
ayload:
-channel
+request
,%0A %7D;%0A%7D
|
6c4b2c81f53d81fc1d067470b7813e391b71e6e8 | Optimize collection helper event forwarding | src/helpers/collection.js | src/helpers/collection.js | /* global
$serverSide,
collectionElementAttributeName, createErrorMessage, getParent,
helperViewPrototype, normalizeHTMLAttributeOptions,
viewRestoreAttribute
*/
Thorax.CollectionHelperView = Thorax.CollectionView.extend({
// Forward render events to the parent
events: {
'rendered:collection': forwardRenderEvent('rendered:collection'),
'rendered:item': forwardRenderEvent('rendered:item'),
'rendered:empty': forwardRenderEvent('rendered:empty'),
'restore:collection': forwardRenderEvent('restore:collection'),
'restore:item': forwardRenderEvent('restore:item'),
'restore:empty': forwardRenderEvent('restore:empty')
},
// Thorax.CollectionView allows a collectionSelector
// to be specified, disallow in a collection helper
// as it will cause problems when neseted
getCollectionElement: function() {
return this.$el;
},
constructor: function(options) {
var restorable = true;
// need to fetch templates if template name was passed
if (options.options['item-template']) {
options.itemTemplate = Thorax.Util.getTemplate(options.options['item-template']);
}
if (options.options['empty-template']) {
options.emptyTemplate = Thorax.Util.getTemplate(options.options['empty-template']);
}
// Handlebars.VM.noop is passed in the handlebars options object as
// a default for fn and inverse, if a block was present. Need to
// check to ensure we don't pick the empty / null block up.
if (!options.itemTemplate && options.template && options.template !== Handlebars.VM.noop) {
options.itemTemplate = options.template;
options.template = Handlebars.VM.noop;
// We can not restore if the item has a depthed reference, ../foo, so we need to
// force a rerender on the client-side
if (options.itemTemplate.depth) {
restorable = false;
}
}
if (!options.emptyTemplate && options.inverse && options.inverse !== Handlebars.VM.noop) {
options.emptyTemplate = options.inverse;
options.inverse = Handlebars.VM.noop;
if (options.emptyTemplate.depth) {
restorable = false;
}
}
var shouldBindItemContext = _.isFunction(options.itemContext),
shouldBindItemFilter = _.isFunction(options.itemFilter);
var response = Thorax.HelperView.call(this, options);
if (shouldBindItemContext) {
this.itemContext = _.bind(this.itemContext, this.parent);
} else if (_.isString(this.itemContext)) {
this.itemContext = _.bind(this.parent[this.itemContext], this.parent);
}
if (shouldBindItemFilter) {
this.itemFilter = _.bind(this.itemFilter, this.parent);
} else if (_.isString(this.itemFilter)) {
this.itemFilter = _.bind(this.parent[this.itemFilter], this.parent);
}
if (this.parent.name) {
if (!this.emptyView && !this.parent.renderEmpty) {
this.emptyView = Thorax.Util.getViewClass(this.parent.name + '-empty', true);
}
if (!this.emptyTemplate && !this.parent.renderEmpty) {
this.emptyTemplate = Thorax.Util.getTemplate(this.parent.name + '-empty', true);
}
if (!this.itemView && !this.parent.renderItem) {
this.itemView = Thorax.Util.getViewClass(this.parent.name + '-item', true);
}
if (!this.itemTemplate && !this.parent.renderItem) {
// item template must be present if an itemView is not
this.itemTemplate = Thorax.Util.getTemplate(this.parent.name + '-item', !!this.itemView);
}
}
if ($serverSide && !restorable) {
this.$el.attr(viewRestoreAttribute, 'false');
this.trigger('restore:fail', {
type: 'serialize',
view: this,
err: 'collection-depthed-query'
});
}
return response;
},
setAsPrimaryCollectionHelper: function() {
var self = this,
parent = self.parent;
_.each(forwardableProperties, function(propertyName) {
forwardMissingProperty(self, propertyName);
});
_.each(['itemFilter', 'itemContext', 'renderItem', 'renderEmpty'], function(propertyName) {
if (parent[propertyName]) {
self[propertyName] = function(thing1, thing2) {
return parent[propertyName](thing1, thing2);
};
}
});
}
});
_.extend(Thorax.CollectionHelperView.prototype, helperViewPrototype);
Thorax.CollectionHelperView.attributeWhiteList = {
'item-context': 'itemContext',
'item-filter': 'itemFilter',
'item-template': 'itemTemplate',
'empty-template': 'emptyTemplate',
'item-view': 'itemView',
'empty-view': 'emptyView',
'empty-class': 'emptyClass'
};
function forwardRenderEvent(eventName) {
return function() {
var args = _.toArray(arguments);
args.unshift(eventName);
this.parent.trigger.apply(this.parent, args);
};
}
var forwardableProperties = [
'itemTemplate',
'itemView',
'emptyTemplate',
'emptyView'
];
function forwardMissingProperty(view, propertyName) {
var parent = getParent(view);
if (!view[propertyName]) {
var prop = parent[propertyName];
if (prop){
view[propertyName] = prop;
}
}
}
Handlebars.registerViewHelper('collection', Thorax.CollectionHelperView, function(collection, view) {
if (arguments.length === 1) {
view = collection;
collection = view.parent.collection;
if (collection) {
view.setAsPrimaryCollectionHelper();
}
view.$el.attr(collectionElementAttributeName, 'true');
// propagate future changes to the parent's collection object
// to the helper view
view.listenTo(view.parent, 'change:data-object', function(type, dataObject) {
if (type === 'collection') {
view.setAsPrimaryCollectionHelper();
view.setCollection(dataObject);
}
});
}
if (collection) {
view.setCollection(collection);
}
});
Handlebars.registerHelper('collection-element', function(options) {
if (!options.data.view.renderCollection) {
throw new Error(createErrorMessage('collection-element-helper'));
}
var hash = options.hash;
normalizeHTMLAttributeOptions(hash);
hash.tagName = hash.tagName || 'div';
hash[collectionElementAttributeName] = true;
return new Handlebars.SafeString(Thorax.Util.tag.call(this, hash, '', this));
});
| JavaScript | 0 | @@ -382,42 +382,147 @@
': f
-orwardRenderEvent('rendered:item')
+unction(view, collection, model, itemEl, index) %7B%0A this.parent.trigger('rendered:item', view, collection, model, itemEl, index);%0A %7D
,%0A
@@ -4790,125 +4790,75 @@
ion(
-) %7B%0A var args = _.toArray(arguments);%0A args.unshift(eventName);%0A this.parent.trigger.apply(this.parent, args
+thing1, thing2) %7B%0A this.parent.trigger(eventName, thing1, thing2
);%0A
|
f6a61c65bb5621c1a285a77e5d0195a79e788864 | fix enable contidion for analytics | src/anm/analytics.js | src/anm/analytics.js | var engine = require('engine'),
utils = require('./utils.js');
var Analytics = function () {
var self = this,
supportSendBeacon = !!navigator.sendBeacon,
timeout = supportSendBeacon ? 2000 : 1000,
beacon = null,
animatronUrl = utils.makeApiUrl('/analytics/player');
self.enabled = animatronUrl != null || animatronUrl.indexOf('animatron-test') >= 0;
self.queue = [];
var event = function () {
if (self.queue.length > 0) {
var data = JSON.stringify(self.queue);
self.queue = [];
if (supportSendBeacon) {
navigator.sendBeacon(animatronUrl, data);
setTimeout(event, timeout);
} else {
var trackUrl = animatronUrl + '?data=' + encodeURIComponent(data);
sendViaGif(trackUrl);
}
} else {
setTimeout(event, timeout);
}
};
var sendViaGif = function (trackUrl) {
if (!beacon) {
beacon = engine.createStatImg();
}
beacon.src = trackUrl;
beacon.onerror = beacon.onload = function () {
beacon.onerror = beacon.onload = null;
setTimeout(event, timeout);
}
};
if (self.enabled) {
event();
window.addEventListener('unload', event, false);
}
this.trackPlayingStart = this.trackPlayer('playing_start');
this.trackPlayingPause = this.trackPlayer('playing_pause');
this.trackPlayingComplete = this.trackPlayer('playing_complete');
};
Analytics.prototype.track = function track(name, opts) {
opts = opts || {};
opts.name = name;
opts.referer = document.referrer;
opts.lang = navigator.language || navigator.userLanguage;
opts.url = location.href;
opts.screenHeight = screen.height;
opts.screenWidth = screen.width;
opts.windowHeight = window.innerHeight;
opts.windowWidth = window.innerWidth;
opts.timestamp = new Date().getTime();
if (this.enabled) {
this.queue.push(opts);
}
};
Analytics.prototype.trackPlayer = function trackPlayer(name) {
return function (player) {
var opts = {viewId: player.viewId, projectId: player.anim.meta._anm_id, time: player.state.time};
this.track(name, opts);
}.bind(this);
};
Analytics.prototype.getObjectId = function () {
var timestamp = (new Date().getTime() / 1000 | 0).toString(16);
return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function () {
return (Math.random() * 16 | 0).toString(16);
}).toLowerCase();
};
module.exports = new Analytics();
| JavaScript | 0 | @@ -341,18 +341,18 @@
!= null
-%7C%7C
+&&
animatr
|
0450ae32e385126e8169db9d125416c97716d339 | remove unused vars | src/helpers/dimensions.js | src/helpers/dimensions.js | 'use strict';
angular.module('mgcrea.ngStrap.helpers.dimensions', [])
.factory('dimensions', function($document, $window) {
var jqLite = angular.element;
var fn = {};
/**
* Test the element nodeName
* @param element
* @param name
*/
var nodeName = fn.nodeName = function(element, name) {
return element.nodeName && element.nodeName.toLowerCase() === name.toLowerCase();
};
/**
* Returns the element computed style
* @param element
* @param prop
* @param extra
*/
fn.css = function(element, prop, extra) {
var value;
if (element.currentStyle) { //IE
value = element.currentStyle[prop];
} else if (window.getComputedStyle) {
value = window.getComputedStyle(element)[prop];
} else {
value = element.style[prop];
}
return extra === true ? parseFloat(value) || 0 : value;
};
/**
* Provides read-only equivalent of jQuery's offset function:
* @required-by bootstrap-tooltip, bootstrap-affix
* @url http://api.jquery.com/offset/
* @param element
*/
fn.offset = function(element) {
var boxRect = element.getBoundingClientRect();
var docElement = element.ownerDocument;
return {
width: boxRect.width || element.offsetWidth,
height: boxRect.height || element.offsetHeight,
top: boxRect.top + (window.pageYOffset || docElement.documentElement.scrollTop) - (docElement.documentElement.clientTop || 0),
left: boxRect.left + (window.pageXOffset || docElement.documentElement.scrollLeft) - (docElement.documentElement.clientLeft || 0)
};
};
/**
* Provides set equivalent of jQuery's offset function:
* @required-by bootstrap-tooltip
* @url http://api.jquery.com/offset/
* @param element
* @param options
* @param i
*/
fn.setOffset = function (element, options, i) {
var curPosition,
curLeft,
curCSSTop,
curTop,
curOffset,
curCSSLeft,
calculatePosition,
position = fn.css(element, 'position'),
curElem = angular.element(element),
props = {};
// Set position first, in-case top/left are set even on static elem
if (position === 'static') {
element.style.position = 'relative';
}
curOffset = fn.offset(element);
curCSSTop = fn.css(element, 'top');
curCSSLeft = fn.css(element, 'left');
calculatePosition = (position === 'absolute' || position === 'fixed') &&
(curCSSTop + curCSSLeft).indexOf('auto') > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if (calculatePosition) {
curPosition = fn.position(element);
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat(curCSSTop) || 0;
curLeft = parseFloat(curCSSLeft) || 0;
}
if (angular.isFunction(options)) {
options = options.call(element, i, curOffset);
}
if (options.top !== null ) {
props.top = (options.top - curOffset.top) + curTop;
}
if ( options.left !== null ) {
props.left = (options.left - curOffset.left) + curLeft;
}
if ('using' in options) {
options.using.call(curElem, props);
} else {
curElem.css({
top: props.top + 'px',
left: props.left + 'px'
});
}
};
/**
* Provides read-only equivalent of jQuery's position function
* @required-by bootstrap-tooltip, bootstrap-affix
* @url http://api.jquery.com/offset/
* @param element
*/
fn.position = function(element) {
var offsetParentRect = {top: 0, left: 0},
offsetParentElement,
offset;
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if (fn.css(element, 'position') === 'fixed') {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = element.getBoundingClientRect();
} else {
// Get *real* offsetParentElement
offsetParentElement = offsetParent(element);
// Get correct offsets
offset = fn.offset(element);
if (!nodeName(offsetParentElement, 'html')) {
offsetParentRect = fn.offset(offsetParentElement);
}
// Add offsetParent borders
offsetParentRect.top += fn.css(offsetParentElement, 'borderTopWidth', true);
offsetParentRect.left += fn.css(offsetParentElement, 'borderLeftWidth', true);
}
// Subtract parent offsets and element margins
return {
width: element.offsetWidth,
height: element.offsetHeight,
top: offset.top - offsetParentRect.top - fn.css(element, 'marginTop', true),
left: offset.left - offsetParentRect.left - fn.css(element, 'marginLeft', true)
};
};
/**
* Returns the closest, non-statically positioned offsetParent of a given element
* @required-by fn.position
* @param element
*/
var offsetParent = function offsetParentElement(element) {
var docElement = element.ownerDocument;
var offsetParent = element.offsetParent || docElement;
if(nodeName(offsetParent, '#document')) return docElement.documentElement;
while(offsetParent && !nodeName(offsetParent, 'html') && fn.css(offsetParent, 'position') === 'static') {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElement.documentElement;
};
/**
* Provides equivalent of jQuery's height function
* @required-by bootstrap-affix
* @url http://api.jquery.com/height/
* @param element
* @param outer
*/
fn.height = function(element, outer) {
var value = element.offsetHeight;
if(outer) {
value += fn.css(element, 'marginTop', true) + fn.css(element, 'marginBottom', true);
} else {
value -= fn.css(element, 'paddingTop', true) + fn.css(element, 'paddingBottom', true) + fn.css(element, 'borderTopWidth', true) + fn.css(element, 'borderBottomWidth', true);
}
return value;
};
/**
* Provides equivalent of jQuery's width function
* @required-by bootstrap-affix
* @url http://api.jquery.com/width/
* @param element
* @param outer
*/
fn.width = function(element, outer) {
var value = element.offsetWidth;
if(outer) {
value += fn.css(element, 'marginLeft', true) + fn.css(element, 'marginRight', true);
} else {
value -= fn.css(element, 'paddingLeft', true) + fn.css(element, 'paddingRight', true) + fn.css(element, 'borderLeftWidth', true) + fn.css(element, 'borderRightWidth', true);
}
return value;
};
return fn;
});
| JavaScript | 0.000007 | @@ -103,64 +103,12 @@
ion(
-$document, $window) %7B%0A%0A var jqLite = angular.element;
+) %7B%0A
%0A
|
43f0356e30caf348e758e2f57a58f183bc629f0c | Repair from PIECE_NUM to PIECE_NUM_X; | tutorial/002/public/js/main.js | tutorial/002/public/js/main.js | var SCREEN_WIDTH = 680
, SCREEN_HEIGHT = 960
, SCREEN_CENTER_X = SCREEN_WIDTH / 2
, SCREEN_CENTER_Y = SCREEN_HEIGHT / 2;
var PIECE_NUM_X = 5
, PIECE_NUM_Y = 5
, PIECE_NUM = PIECE_NUM * PIECE_NUM_Y
, PIECE_OFFSET_X = 90
, PIECE_OFFSET_Y = 240
, PIECE_WIDTH = 120
, PIECE_HEIGHT = 120;
var FONT_FAMILY_FLAT = "'Helvetica-Light' 'Meiryo' sans-serif";
tm.main(function() {
var app = tm.app.CanvasApp("#world");
app.resize(SCREEN_WIDTH, SCREEN_HEIGHT);
app.fitWindow();
app.background = "rgba(250, 250, 250, 1.0)";
app.replaceScene( GameScene() );
app.run();
});
tm.define("GameScene", {
superClass: "tm.app.Scene",
init: function() {
this.superInit();
this.pieceGroup = tm.app.CanvasElement();
this.addChild(this.pieceGroup);
var nums = [].range(1, PIECE_NUM + 1);
nums.shuffle();
for (var i = 0; i < PIECE_NUM_Y; ++i) {
for (var j = 0; j < PIECE_NUM_X; ++j) {
var number = nums[i * PIECE_NUM_X + j];
var piece = Piece(number).addChildTo(this.pieceGroup);
piece.x = j * 125 + PIECE_OFFSET_X;
piece.y = i * 125 + PIECE_OFFSET_Y;
}
}
}
});
tm.define("Piece", {
superClass: "tm.app.Shape",
init: function(number) {
this.superInit(PIECE_WIDTH, PIECE_HEIGHT);
this.number = number;
this.setInteractive(true);
this.setBoundingType("rect");
var angle = tm.util.Random.randint(0, 360);
this.canvas.clearColor("hsl({0}, 80%, 70%)".format(angle));
this.label = tm.app.Label(number).addChildTo(this);
this.label
.setFontSize(70)
.setFontFamily(FONT_FAMILY_FLAT)
.setAlign("center")
.setBaseline("middle");
}
});
| JavaScript | 0 | @@ -197,16 +197,18 @@
IECE_NUM
+_X
* PIECE
|
2e6a7bdc1b3695bc0f89eac6e77f4e0823a67553 | Update copy | src/app/Hit/index.js | src/app/Hit/index.js | import IconTime from 'react-icons/lib/md/access-time'
import {Highlight} from 'react-instantsearch/dom'
import React from 'react'
import Badge from '../Badge'
import './style.scss'
const getTimestamp = item => item.updatedAt || item.createdAt
const renderTimeIcon = time => (
<Badge
iconComponent={<IconTime size={20} />}
className='ml1'>{time}</Badge>
)
const isRecently = (timestamp, hours) => {
const lastHours = 1000 * 60 * 60 * hours
return Date.now() - timestamp < lastHours
}
const getTimeIcon = timestamp => {
if (isRecently(timestamp, 24)) return renderTimeIcon('24 Hours')
if (isRecently(timestamp, 48)) return renderTimeIcon('48 Hours')
if (isRecently(timestamp, 72)) return renderTimeIcon('3 Days')
if (isRecently(timestamp, 120)) return renderTimeIcon('1 Week')
return renderTimeIcon('1 Month')
}
const renderPopularIcon = rarity => {
return (
<Badge
iconComponent={
<img
alt={rarity}
className='v-mid'
src={`/assets/img/popular/${rarity}.svg`}
/>
}
className='mr1'>{rarity}</Badge>
)
}
function getPopularIcon (item) {
const {priceScore} = item
if (priceScore < 0.5) return
if (priceScore > 0.95) return renderPopularIcon('legendary')
if (priceScore > 0.80) return renderPopularIcon('epic')
if (priceScore > 0.70) return renderPopularIcon('rare')
return renderPopularIcon('uncommon')
}
function getImageUrl (item) {
const {image, provider} = item
if (!image) return `/assets/img/provider/${provider}.jpg`
const el = document.createElement('a')
el.href = image
return `https://images.weserv.nl/?url=${el.hostname}${el.pathname}&w=96&t=fit`
}
export default props => {
const {item} = props
const {price, title} = item
const imageURL = getImageUrl(item)
const priceText = price ? `${price}€` : 'N/A'
const timestamp = getTimestamp(item)
return (
<article
data-app='hit'
role='article'
className='hit fade-in bg-white mv2 br2 pa3 h6'>
<a
className='hit__link flex link w-100 h-100 black'
href={item.link}
target='_blank'
rel='nofollow noopener'>
<div className='pv2 w-100 lh-copy f4 flex flex-column justify-around'>
<p className='link lh-title mv0 blue-grey-900 fw5 w-95'>
<Highlight attributeName='title' hit={item} />
</p>
<div className='ma0'>
<span className='blue-500 pr1'>{priceText}</span>
{' '}
<p className='tracked blue-grey-300 f6 di'>
by <Highlight attributeName='provider' hit={item} />
</p>
</div>
<p className='ma0'>
{getPopularIcon(item)}
{getTimeIcon(timestamp)}
</p>
</div>
<img alt={title} src={imageURL} className='hit__image db br2 pt3' />
</a>
</article>
)
}
| JavaScript | 0 | @@ -590,17 +590,17 @@
con('24
-H
+h
ours')%0A
@@ -657,17 +657,17 @@
con('48
-H
+h
ours')%0A
@@ -723,17 +723,17 @@
Icon('3
-D
+d
ays')%0A
@@ -793,9 +793,9 @@
('1
-W
+w
eek'
@@ -826,14 +826,17 @@
n('1
- M
+-3 m
onth
+s
')%0A%7D
|
4719be5e738d762ae78fa6ab4d04a6ff92f2ad5e | Update dmmOriginalSizeImage.user.js | H/dmmOriginalSizeImage.user.js | H/dmmOriginalSizeImage.user.js | // ==UserScript==
// @name dmmOriginalSizeImage
// @name:zh-CN 【DMM】原始图片大小
// @namespace https://github.com/dodying/Dodying-UserJs
// @include http://www.dmm.co.jp/*
// @include http://www.javlibrary.com/*
// @version 1
// @grant none
// ==/UserScript==
var img = document.querySelectorAll('img');
for (var i = 0; i < img.length; i++) {
img[i].src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==';
}
if (location.href.indexOf('detail/=/cid=') >= 0 && location.href.indexOf('dmm.co.jp') >= 0) {
var code = location.href.split(/\/|=/) [10];
var date = document.querySelector('table.mg-b20').innerHTML.replace(/[\r\n]/g, '').replace(/ /g, '').replace(/.*日:<\/td>.*?>/, '').replace(/<.*/, '');
var time = parseInt(document.querySelector('table.mg-b20').innerHTML.replace(/[\r\n]/g, '').replace(/ /g, '').replace(/.*時間:<\/td>.*?>/, '').replace(/<.*/, '')) / 60;
document.querySelector('title').innerHTML = '[' + date + ']' + '[' + time.toPrecision(2) + 'H]' + code;
//document.querySelector('meta[name="description"]').setAttribute('content', date);//更改描述
};
var img = document.querySelectorAll('#sample-image-block>a>img,.previewthumbs>img');
console.log(img);
for (var i = 0; i < img.length; i++) {
img[i].src = preview_src(img[i].src);
img[i].style.width = img[i].naturalWidth + 'px';
img[i].style.height = img[i].naturalHeight + 'px';
img[i].parentNode.style.width = img[i].naturalWidth + 'px';
img[i].parentNode.style.height = img[i].naturalHeight + 'px';
img[i].parentNode.onclick = function () {
return false;
};
}
function preview_src(src) {
if (src.match(/(p[a-z]\.)jpg/)) {
return src.replace(RegExp.$1, 'pl.');
} else if (src.match(/consumer_game/)) {
return src.replace('js-', '-');
} else if (src.match(/js\-([0-9]+)\.jpg$/)) {
return src.replace('js-', 'jp-');
} else if (src.match(/ts\-([0-9]+)\.jpg$/)) {
return src.replace('ts-', 'tl-');
} else if (src.match(/(\-[0-9]+\.)jpg$/)) {
return src.replace(RegExp.$1, 'jp' + RegExp.$1);
} else {
return src.replace('-', 'jp-');
}
}
| JavaScript | 0 | @@ -279,230 +279,8 @@
t==%0A
-var img = document.querySelectorAll('img');%0Afor (var i = 0; i %3C img.length; i++) %7B%0A img%5Bi%5D.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==';%0A%7D%0A
if (
|
c53ad5e5af0b8d493e139e3fd331739b9a9490d8 | Add id selector to jQuery | teknologr/registration/static/js/registration.js | teknologr/registration/static/js/registration.js | /* Some browsers (e.g. desktop Safari) does not have built-in datepickers (e.g. Firefox).
* Thus we check first if the browser supports this, in case not we inject jQuery UI into the DOM.
* This enables a jQuery datepicker.
*/
const datefield = document.createElement('input');
datefield.setAttribute('type', 'date');
if (datefield.type != 'date') {
const jQueryUIurl = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1';
document.write(`<link href="${jQueryUIurl}/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n`)
document.write(`<script src="${jQueryUIurl}/jquery-ui.min.js"><\/script>\n`)
}
$(document).ready(function() {
// There is no default option for setting readonly a field with django-bootstrap4
$('#id_mother_tongue').prop('readonly', true);
// Set tooltips
$('[data-toggle="tooltip"]').tooltip();
// Set the datepicker on birth date, in case input type of date is not supported
if (datefield.type != 'date') {
const currentYear = new Date().getFullYear();
$('id_birth_date').datepicker({
changeMonth: true,
changeYear: true,
yearRange: `1930:${currentYear}`,
});
}
});
$('#id_degree_programme_options').change(function() {
if (this.value === 'extra') {
$('#unknown_degree').show();
$('#unknown_degree input').val('');
} else {
$('#unknown_degree').hide();
$('#unknown_degree input').val(this.value);
}
});
$('input:radio[name="language"]').change(function() {
if ($(this).is(':checked')) {
if ($(this).val() == 'extra') {
$('#id_mother_tongue').prop('readonly', false);
$('#id_mother_tongue').val('');
} else {
$('#id_mother_tongue').prop('readonly', true);
$('#id_mother_tongue').val(this.value);
}
}
});
| JavaScript | 0.000001 | @@ -224,21 +224,19 @@
r.%0A */%0A%0A
-const
+var
datefie
@@ -1045,16 +1045,17 @@
$('
+#
id_birth
|
003e93241085de0c267baaf2e63fe66b72ace135 | handle missing plugins propery in config | customize.js | customize.js | /*!
* thought <https://github.com/nknapp/thought>
*
* Copyright (c) 2015 Nils Knappmeier.
* Released under the MIT license.
*/
'use strict'
const path = require('path')
const fs = require('fs')
const debug = require('debug')
const pify = require('pify')
const readFile = pify(fs.readFile)
/**
* Default configuration for .thought. Override this configuration by creating a file `.thought/config.js`
* @api public
*/
const defaultConfig = {
plugins: [],
badges: {
/**
* Should there be a greenkeeper badge?
* `undefined` means autodetect (by parsing the badge for the repo-url)
* @property
*/
greenkeeper: undefined
}
}
/**
*
* Create a spec that can be loaded with `customize` using the `load()` function.
*
* @param {String} workingDir the working directory of thought
* @returns {Function} the Customize-Spec
*/
module.exports = function createSpec (workingDir) {
return function thoughtSpec (customize) {
debug('creating customize config')
const configFile = path.resolve('.thought', 'config.js')
const config = fs.existsSync(configFile) ? require(configFile) : defaultConfig
debug('config loaded', config)
return customize
.registerEngine('handlebars', require('customize-engine-handlebars'))
.merge({
handlebars: {
partials: path.join(__dirname, 'handlebars', 'partials'),
templates: path.join(__dirname, 'handlebars', 'templates'),
helpers: require.resolve('./handlebars/helpers/index.js'),
data: {
'package': readFile(path.resolve(workingDir, 'package.json'), 'utf-8').then(JSON.parse),
config: config,
workingDir: workingDir
},
preprocessor: require('./handlebars/preprocessor.js'),
hbsOptions: {
noEscape: true
}
}
})
// Apply any customization from the config-files (such as loading modules)
.load(function (customize) {
debug('Loading modules', config)
return config.plugins.reduce((prev, plugin) => {
return prev.load(plugin)
}, customize)
})
.merge({
handlebars: {
partials: path.join(workingDir, '.thought', 'partials'),
templates: path.join(workingDir, '.thought', 'templates'),
helpers: path.resolve(workingDir, '.thought', 'helpers.js'),
preprocessor: path.resolve(workingDir, '.thought', 'preprocessor.js')
}
})
}
}
| JavaScript | 0.000001 | @@ -526,84 +526,23 @@
dge?
-%0A * %60undefined%60 means autodetect (by parsing the badge for the repo-url)
+ Default: false
%0A
@@ -584,17 +584,13 @@
er:
-undefined
+false
%0A %7D
@@ -1205,16 +1205,82 @@
bars'))%0A
+ .merge(%7B handlebars: %7B data: %7B config: defaultConfig %7D %7D %7D)%0A
.m
@@ -2010,24 +2010,66 @@
s', config)%0A
+ if (config && config.plugins) %7B%0A
retu
@@ -2119,24 +2119,26 @@
%7B%0A
+
return prev.
@@ -2158,16 +2158,18 @@
+
%7D, custo
@@ -2174,16 +2174,70 @@
tomize)%0A
+ %7D else %7B%0A return customize%0A %7D%0A
%7D)
|
b95fba1caebef848a4cd3a69a9ff30f151603d8b | Update repl.js improve readability & performance. | packages/core/lib/repl.js | packages/core/lib/repl.js | var repl = require("repl");
var expect = require("@truffle/expect");
var async = require("async");
var EventEmitter = require("events");
var inherits = require("util").inherits;
inherits(ReplManager, EventEmitter);
function ReplManager(options) {
EventEmitter.call(this);
expect.options(options, [
"working_directory",
"contracts_directory",
"contracts_build_directory",
"migrations_directory",
"network",
"network_id",
"provider",
"resolver",
"build_directory"
]);
this.options = options;
this.repl = options.repl;
this.contexts = [];
}
ReplManager.prototype.start = function(options) {
var self = this;
this.contexts.push({
prompt: options.prompt,
interpreter: options.interpreter,
ignoreUndefined: options.ignoreUndefined || false,
done: options.done
});
var currentContext = this.contexts[this.contexts.length - 1];
if (!this.repl) {
this.repl = repl.start({
prompt: currentContext.prompt,
eval: this.interpret.bind(this)
});
this.repl.on("exit", function() {
// If we exit for some reason, call done functions for good measure
// then ensure the process is completely killed. Once the repl exits,
// the process is in a bad state and can't be recovered (e.g., stdin is closed).
var doneFunctions = self.contexts.map(function(context) {
return context.done
? function() {
context.done();
}
: function() {};
});
async.series(doneFunctions, function() {
process.exit();
});
});
}
// Bubble the internal repl's exit event
this.repl.on("exit", function() {
self.emit("exit");
});
// Bubble the internal repl's reset event
this.repl.on("reset", function() {
process.stdout.write("\u001B[2J\u001B[0;0f");
self.emit("reset");
});
this.repl.setPrompt(options.prompt);
this.setContextVars(options.context || {});
this.activate(options);
};
ReplManager.prototype.setContextVars = function(obj) {
var self = this;
if (this.repl) {
Object.keys(obj || {}).forEach(function(key) {
self.repl.context[key] = obj[key];
});
}
};
ReplManager.prototype.activate = function(session) {
const { prompt, context, ignoreUndefined } = session;
this.repl.setPrompt(prompt);
this.repl.ignoreUndefined = ignoreUndefined;
this.setContextVars(context);
};
ReplManager.prototype.stop = function(callback) {
var oldContext = this.contexts.pop();
if (oldContext.done) {
oldContext.done();
}
var currentContext = this.contexts[this.contexts.length - 1];
if (currentContext) {
this.activate(currentContext);
} else {
// If there's no new context, stop the process altogether.
// Though this might seem like an out of place process.exit(),
// once the Node repl closes, the state of the process is not
// recoverable; e.g., stdin is closed and can't be reopened.
// Since we can't recover to a state before the repl was opened,
// we should just exit. He're, we'll exit after we've popped
// off the stack of all repl contexts.
process.exit();
}
if (callback) {
callback();
}
};
ReplManager.prototype.interpret = function(
replInput,
context,
filename,
callback
) {
const currentContext = this.contexts[this.contexts.length - 1];
currentContext.interpreter(replInput, context, filename, callback);
};
module.exports = ReplManager;
| JavaScript | 0 | @@ -1308,19 +1308,21 @@
.%0A
-var
+const
doneFun
@@ -1348,112 +1348,70 @@
xts.
-map(function(context) %7B%0A return context.done%0A ? function() %7B%0A context
+reduce((fns, ctx) =%3E %7B%0A if (ctx.done) fns.push(ctx
.done
-(
);%0A
@@ -1421,39 +1421,18 @@
- %7D%0A : function() %7B%7D
+return fns
;%0A
@@ -1432,24 +1432,28 @@
fns;%0A %7D
+, %5B%5D
);%0A asy
|
665e5a4f216330983015cae3f1135e212bc10523 | Update background.js | chrome/js/background.js | chrome/js/background.js | chrome.webRequest.onBeforeRequest.addListener(
function(details) {
if( details.url == "http://210.77.16.21:8081/eportal/interface/index_files/pc/login_bch.js" )
return {redirectUrl: "chrome-extension://" + chrome.runtime.id + "/js/login_bch.js" };
},
{urls:["<all_urls>"]},
["blocking"]); | JavaScript | 0.000001 | @@ -115,17 +115,17 @@
6.21:808
-1
+0
/eportal
@@ -317,8 +317,9 @@
king%22%5D);
+%0A
|
f9952f9fa7cd0d90add221793aea07f45ba05cc8 | Fix 500 error when account token does not resolve to account | packages/nylas-api/app.js | packages/nylas-api/app.js | const Hapi = require('hapi');
const HapiSwagger = require('hapi-swagger');
const HapiBoom = require('hapi-boom-decorators')
const HapiBasicAuth = require('hapi-auth-basic');
const Inert = require('inert');
const Vision = require('vision');
const Package = require('./package');
const fs = require('fs');
const path = require('path');
global.Promise = require('bluebird');
global.NylasError = require('nylas-core').NylasError;
const server = new Hapi.Server({
connections: {
router: {
stripTrailingSlash: true,
},
},
});
server.connection({ port: process.env.PORT || 5100 });
const plugins = [Inert, Vision, HapiBasicAuth, HapiBoom, {
register: HapiSwagger,
options: {
info: {
title: 'Nylas API Documentation',
version: Package.version,
},
},
}];
let sharedDb = null;
const {DatabaseConnector, SchedulerUtils} = require(`nylas-core`)
DatabaseConnector.forShared().then((db) => {
sharedDb = db;
});
const validate = (request, username, password, callback) => {
const {AccountToken} = sharedDb;
AccountToken.find({
where: {
value: username,
},
}).then((token) => {
if (!token) {
callback(null, false, {});
return
}
token.getAccount().then((account) => {
if (!account) {
callback(new Error("Could not find Account referenced by AccountToken"), false, {});
return;
}
SchedulerUtils.notifyAccountIsActive(account.id)
callback(null, true, account);
});
});
};
const attach = (directory) => {
const routesDir = path.join(__dirname, directory)
fs.readdirSync(routesDir).forEach((filename) => {
if (filename.endsWith('.js')) {
const routeFactory = require(path.join(routesDir, filename));
routeFactory(server);
}
});
}
server.register(plugins, (err) => {
if (err) { throw err; }
attach('./routes/')
attach('./decorators/')
server.auth.strategy('api-consumer', 'basic', { validateFunc: validate });
server.auth.default('api-consumer');
server.start((startErr) => {
if (startErr) { throw startErr; }
console.log('API running at:', server.info.uri);
});
});
| JavaScript | 0.000001 | @@ -1285,69 +1285,11 @@
ck(n
-ew Error(%22Could not find Account referenced by AccountToken%22)
+ull
, fa
|
55117f1a3cbcfb1fc06083809ac142be8c925e23 | Return Response instances for fakeFetch | src/interceptors/fetch.js | src/interceptors/fetch.js | import queryString from 'query-string';
import pathMatch from 'path-match';
import parseUrl from 'parse-url';
const nativeFetch = window.fetch;
export const fakeFetch = (serverRoutes) => {
return (url, options = {}) => {
const body = options.body || '';
const method = options.method || 'GET';
const handlers = serverRoutes[method];
const pathname = parseUrl(url).pathname;
const matchesPathname = path => pathMatch()(path)(pathname);
const route = Object.keys(handlers).find(matchesPathname);
if (!route) {
return nativeFetch(url, options);
}
const handler = handlers[route];
const query = queryString.parse(parseUrl(url).search);
const params = matchesPathname(route);
// @TODO: Wrap 'resolve' result into a Response instance,
// check https://github.com/devlucky/Kakapo.js/issues/16
return Promise.resolve(handler({params, query, body}));
};
};
export const reset = () => {
window.fetch = nativeFetch;
};
| JavaScript | 0.000001 | @@ -139,16 +139,182 @@
fetch;%0A%0A
+//TODO: Handle response headers%0Alet fakeResponse = function(response = %7B%7D) %7B%0A const responseStr = JSON.stringify(response);%0A%0A return new Response(responseStr);%0A%7D;%0A%0A
export c
@@ -892,131 +892,8 @@
);%0A%0A
- // @TODO: Wrap 'resolve' result into a Response instance,%0A // check https://github.com/devlucky/Kakapo.js/issues/16%0A
@@ -915,16 +915,29 @@
resolve(
+fakeResponse(
handler(
@@ -959,16 +959,17 @@
body%7D))
+)
;%0A %7D;%0A%7D
|
8e24aede6d68d6b314bf9032c9ae9f1022f2eed0 | fix status-bar theme for dark mode | chrome/status-bar.uc.js | chrome/status-bar.uc.js | // ==UserScript==
// @name Status Bar
// @author xiaoxiaoflood
// @include main
// @startup UC.statusBar.exec(win);
// @shutdown UC.statusBar.destroy();
// @onlyonce
// ==/UserScript==
UC.statusBar = {
PREF_ENABLED: 'userChromeJS.statusbar.enabled',
PREF_STATUSTEXT: 'userChromeJS.statusbar.appendStatusText',
get enabled() {
return xPref.get(this.PREF_ENABLED);
},
get textInBar() {
return this.enabled && xPref.get(this.PREF_STATUSTEXT);
},
init: function () {
xPref.set(this.PREF_ENABLED, true, true);
xPref.set(this.PREF_STATUSTEXT, true, true);
this.enabledListener = xPref.addListener(this.PREF_ENABLED, (isEnabled) => {
CustomizableUI.getWidget('status-dummybar').instances.forEach(dummyBar => {
dummyBar.node.setAttribute('collapsed', !isEnabled);
});
});
this.textListener = xPref.addListener(this.PREF_STATUSTEXT, (isEnabled) => {
if (!UC.statusBar.enabled)
return;
_uc.windows((doc, win) => {
let StatusPanel = win.StatusPanel;
if (isEnabled)
win.statusbar.textNode.appendChild(StatusPanel._labelElement);
else
StatusPanel.panel.firstChild.appendChild(StatusPanel._labelElement);
});
});
this.setStyle();
_uc.sss.loadAndRegisterSheet(this.STYLE.url, this.STYLE.type);
CustomizableUI.registerArea('status-bar', {});
},
exec: function (win) {
let document = win.document;
let StatusPanel = win.StatusPanel;
let dummystatusbar = _uc.createElement(document, 'toolbar', {
id: 'status-dummybar',
toolbarname: 'Status Bar',
hidden: 'true'
});
dummystatusbar.collapsed = !this.enabled;
dummystatusbar.setAttribute = function (att, value) {
let result = Element.prototype.setAttribute.apply(this, arguments);
if (att == 'collapsed') {
let StatusPanel = win.StatusPanel;
if (value === true) {
xPref.set(UC.statusBar.PREF_ENABLED, false);
win.statusbar.node.setAttribute('collapsed', true);
StatusPanel.panel.firstChild.appendChild(StatusPanel._labelElement);
win.statusbar.node.parentNode.collapsed = true;;
} else {
xPref.set(UC.statusBar.PREF_ENABLED, true);
win.statusbar.node.setAttribute('collapsed', false);
if (UC.statusBar.textInBar)
win.statusbar.textNode.appendChild(StatusPanel._labelElement);
win.statusbar.node.parentNode.collapsed = false;
}
}
return result;
};
win.gNavToolbox.appendChild(dummystatusbar);
win.statusbar.node = _uc.createElement(document, 'toolbar', {
id: 'status-bar',
customizable: 'true',
context: 'toolbar-context-menu',
mode: 'icons'
});
win.statusbar.textNode = _uc.createElement(document, 'toolbaritem', {
id: 'status-text',
flex: '1',
width: '100'
});
if (this.textInBar)
win.statusbar.textNode.appendChild(StatusPanel._labelElement);
win.statusbar.node.appendChild(win.statusbar.textNode);
let resizerContainer = _uc.createElement(document, 'toolbaritem', {id: 'resizer-container'});
let resizer = _uc.createElement(document, 'resizer');
resizerContainer.appendChild(resizer);
win.statusbar.node.appendChild(resizerContainer);
win.eval('Object.defineProperty(StatusPanel, "_label", {' + Object.getOwnPropertyDescriptor(StatusPanel, '_label').set.toString().replace(/^set _label/, 'set').replace(/((\s+)this\.panel\.setAttribute\("inactive", "true"\);)/, '$2this._labelElement.value = val;$1') + ', enumerable: true, configurable: true});');
let bottomBox = document.getElementById('browser-bottombox');
if (!this.enabled)
bottomBox.collapsed = true;
CustomizableUI.registerToolbarNode(win.statusbar.node);
bottomBox.appendChild(win.statusbar.node);
win.statusbar.node.parentNode = bottomBox;
},
orig: Object.getOwnPropertyDescriptor(StatusPanel, '_label').set.toString(),
setStyle: function () {
this.STYLE = {
url: Services.io.newURI('data:text/css;charset=UTF-8,' + encodeURIComponent(`
@-moz-document url('${_uc.BROWSERCHROME}') {
#status-bar {
color: initial !important;
background-color: var(--toolbar-non-lwt-bgcolor) !important;
}
#status-text > #statuspanel-label {
border-top: 0 !important;
background-color: unset !important;
color: #444 !important;
}
#browser-bottombox:not([collapsed]) {
border-top: 1px solid var(--chrome-content-separator-color) !important;
}
#wrapper-status-text label::after {
content: "Status text" !important;
color: red !important;
border: 1px #aaa solid !important;
border-radius: 3px !important;
font-weight: bold !important;
}
#status-bar > #status-text {
display: flex !important;
justify-content: center !important;
align-content: center !important;
flex-direction: column !important;
}
}
`)),
type: _uc.sss.USER_SHEET
}
},
destroy: function () {
xPref.removeListener(this.enabledListener);
xPref.removeListener(this.textListener);
CustomizableUI.unregisterArea('status-bar');
_uc.sss.unregisterSheet(this.STYLE.url, this.STYLE.type);
_uc.windows((doc, win) => {
win.eval('Object.defineProperty(StatusPanel, "_label", {' + this.orig.replace(/^set _label/, 'set') + ', enumerable: true, configurable: true});');
let StatusPanel = win.StatusPanel;
StatusPanel.panel.firstChild.appendChild(StatusPanel._labelElement);
doc.getElementById('status-dummybar').remove();
win.statusbar.node.remove();
});
delete UC.statusBar;
}
}
UC.statusBar.init(); | JavaScript | 0 | @@ -4341,37 +4341,26 @@
lwt-bgcolor)
- !important
;%0A
+
%7D%0A
@@ -4518,163 +4518,8 @@
#444
- !important;%0A %7D%0A #browser-bottombox:not(%5Bcollapsed%5D) %7B%0A border-top: 1px solid var(--chrome-content-separator-color) !important
;%0A
@@ -4963,32 +4963,32 @@
ter !important;%0A
-
flex
@@ -5022,32 +5022,533 @@
nt;%0A %7D%0A
+ @media (-moz-toolbar-prefers-color-scheme: light) %7B%0A #browser-bottombox:not(%5Bcollapsed%5D) %7B%0A border-top: 1px solid var(--panel-separator-color) !important;%0A %7D%0A %7D%0A @media (-moz-toolbar-prefers-color-scheme: dark) %7B%0A #status-bar %7B%0A background-color: var(--toolbar-bgcolor);%0A %7D%0A #status-text %3E #statuspanel-label %7B%0A color: var(--lwt-text-color) !important;%0A %7D%0A %7D%0A
%7D%0A
|
12a43f0b3d0fe581c7621fb1b50019e424c2768d | Update crooz.js | public/js/crooz.js | public/js/crooz.js | "use strict";
var socket;
var mapper;
function main() {
socket = io();
mapper = Mapper.init(document.getElementById('mapCard'));
socket.on('connected', function (users) {
socket.emit('subscribe', users.sort(function(a,b) {
- return ((new Date(a.lastActive)).getTime() > (new Date(b.lastActive)).getTime()) ? 1: -1
- }[0]));
console.log(users);
});
socket.on('newPacket', function (packet) {
console.log(packet);
mapper.addPackets([packet]);
console.log(mapper._packets);
mapper.render();
var car = mapper.car;
document.getElementById('songCard').innerText = car.song;
document.getElementById('moodCard').innerText = Object.keys(car.mood).reduce(
function(a, b) {
return car.mood[a] > car.mood[b] ? a : b
}
);
});
socket.on('newPackets', function (packets) {
console.log(packets);
mapper.addPackets(packets);
console.log(mapper._packets);
mapper.render();
var car = mapper.car;
document.getElementById('songCard').innerText = car.song;
document.getElementById('moodCard').innerText = Object.keys(car.mood).reduce(
function(a, b) {
return car.mood[a] > car.mood[b] ? a : b
}
);
});
}
| JavaScript | 0 | @@ -224,44 +224,15 @@
ort(
-function(a,b) %7B %0A - return
+compare
((ne
@@ -262,18 +262,17 @@
etTime()
- %3E
+,
(new Da
@@ -303,35 +303,8 @@
e())
- ? 1: -1 %0A - %7D%5B0%5D));
%0A
@@ -1299,8 +1299,153 @@
%7D);%0A%7D%0A
+%0Afunction compare(a,b) %7B%0A if (a %3E b) %7B%0A return 1;%0A %7D else if (a %3C b) %7B%0A return -1;%0A %7D else %7B%0A return 0; %0A %7D%0A%7D%0A
|
9240736a5464c8c09254d140be82b6eabc07dd97 | fix spelling in comment | example/react/src/App.js | example/react/src/App.js | import React, { Component, Suspense } from 'react';
import { useTranslation, withTranslation, Trans } from 'react-i18next';
import logo from './logo.svg';
import './App.css';
// use hoc for class based components
class LegacyWelcomeClass extends Component {
render() {
const { t, i18n } = this.props;
return <h2>{t('title')}</h2>;
}
}
const Welcome = withTranslation()(LegacyWelcomeClass);
// Component using the Trans component
function MyComponent() {
return (
<Trans i18nKey="description.part1">
To get started, edit <code>src/App.js</code> and save to reload.
</Trans>
);
}
// page uses the hook
function Page() {
const { t, i18n } = useTranslation();
const changeLanguage = lng => {
i18n.changeLanguage(lng);
};
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<Welcome />
<button onClick={() => changeLanguage('de')}>de</button>
<button onClick={() => changeLanguage('en')}>en</button>
</div>
<div className="App-intro">
<MyComponent />
</div>
<div>{t('description.part2')}</div>
</div>
);
}
// loading component for suspence fallback
const Loader = () => (
<div className="App">
<img src={logo} className="App-logo" alt="logo" />
<div>loading...</div>
</div>
);
// here app catches the suspense from page in case translations are not yet loaded
export default function App() {
return (
<Suspense fallback={<Loader />}>
<Page />
</Suspense>
);
}
| JavaScript | 0.001874 | @@ -1212,17 +1212,17 @@
r suspen
-c
+s
e fallba
|
6e2c81dda879b946c6353299703afa1f9a59e52d | Edit variable name to be more precise | packages/core/lib/testing/testrunner.js | packages/core/lib/testing/testrunner.js | const { createInterfaceAdapter } = require("@truffle/interface-adapter");
const web3Utils = require("web3-utils");
const Config = require("@truffle/config");
const Migrate = require("@truffle/migrate");
const TestResolver = require("./testresolver");
const TestSource = require("./testsource");
const expect = require("@truffle/expect");
const contract = require("@truffle/contract");
const path = require("path");
const fs = require("fs-extra");
const util = require("util");
const debug = require("debug")("lib:testing:testrunner");
const Decoder = require("@truffle/decoder");
const Codec = require("@truffle/codec");
function TestRunner(options = {}) {
expect.options(options, [
"resolver",
"provider",
"contracts_build_directory"
]);
this.config = Config.default().merge(options);
this.logger = options.logger || console;
this.initial_resolver = options.resolver;
this.provider = options.provider;
this.can_snapshot = false;
this.first_snapshot = true;
this.initial_snapshot = null;
this.interfaceAdapter = createInterfaceAdapter({
provider: options.provider,
networkType: options.networks[options.network].type
});
this.decoder = null;
// For each test
this.currentTestStartBlock = null;
this.BEFORE_TIMEOUT =
(options.mocha && options.mocha.before_timeout) || 120000;
this.TEST_TIMEOUT = (options.mocha && options.mocha.timeout) || 300000;
}
TestRunner.prototype.initialize = async function() {
debug("initializing");
let test_source = new TestSource(this.config);
this.config.resolver = new TestResolver(
this.initial_resolver,
test_source,
this.config.contracts_build_directory
);
if (this.first_snapshot) {
debug("taking first snapshot");
try {
let initial_snapshot = await this.snapshot();
this.can_snapshot = true;
this.initial_snapshot = initial_snapshot;
} catch (error) {
debug("first snapshot failed");
debug("Error: %O", error);
}
this.first_snapshot = false;
} else {
await this.resetState();
}
let files = fs
.readdirSync(this.config.contracts_build_directory)
.filter(file => path.extname(file) === ".json");
let data = files.map(file =>
fs.readFileSync(
path.join(this.config.contracts_build_directory, file),
"utf8"
)
);
let contracts = data.map(JSON.parse).map(json => contract(json));
//NOTE: in future should get rid of contracts argument
this.decoder = await Decoder.forProject(this.provider, contracts);
};
TestRunner.prototype.deploy = async function() {
await Migrate.run(
this.config.with({
reset: true,
quiet: true
})
);
};
TestRunner.prototype.resetState = async function() {
if (this.can_snapshot) {
debug("reverting...");
await this.revert(this.initial_snapshot);
this.initial_snapshot = await this.snapshot();
} else {
debug("redeploying...");
await this.deploy();
}
};
TestRunner.prototype.startTest = async function() {
let blockNumber = await this.interfaceAdapter.getBlockNumber();
let one = web3Utils.toBN(1);
blockNumber = web3Utils.toBN(blockNumber);
// Add one in base 10
this.currentTestStartBlock = blockNumber.add(one);
};
TestRunner.prototype.endTest = async function(mocha) {
// Skip logging if test passes and `show-events` option is not true
if (mocha.currentTest.state !== "failed" && !this.config["show-events"]) {
return;
}
function indent(unindented, indentation, initialPrefix = "") {
return unindented
.split("\n")
.map(
(line, index) =>
index === 0
? initialPrefix + " ".repeat(indentation - initialPrefix) + line
: " ".repeat(indentation) + line
)
.join("\n");
}
function printEvent(decoding, indentation = 0, initialPrefix = "") {
const anonymousPrefix = decoding.kind === "anonymous" ? "<anonymous> " : "";
const className = decoding.definedIn
? decoding.definedIn.typeName
: decoding.class.typeName;
const eventName = decoding.abi.name;
const fullEventName = anonymousPrefix + `${className}.${eventName}`;
const eventArgs = decoding.arguments
.map(({ name, indexed, value }) => {
let namePrefix = name ? `${name}: ` : "";
let indexedPrefix = indexed ? "<indexed> " : "";
let displayValue = util.inspect(
new Codec.Format.Utils.Inspect.ResultInspector(value),
{
depth: null,
colors: true,
maxArrayLength: null,
breakLength: 80 - indentation //should this include prefix lengths as well?
}
);
let typeString = ` (type: ${Codec.Format.Types.typeStringWithoutLocation(
value.type
)})`;
return namePrefix + indexedPrefix + displayValue + typeString;
})
.join(",\n");
if (decoding.arguments.length > 0) {
return indent(
`${fullEventName}(\n${indent(eventArgs, 2)}\n)`,
indentation,
initialPrefix
);
} else {
return indent(`${fullEventName}()`, indentation, initialPrefix);
}
}
const logs = await this.decoder.events({
//NOTE: block numbers shouldn't be over 2^53 so this
//should be fine, but should change this once decoder
//accepts more general types for blocks
fromBlock: this.currentTestStartBlock.toNumber()
});
const filteredLogs = logs.filter(log => {
return !log.decodings.length || log.decodings[0].abi.name !== "TestEvent";
});
if (filteredLogs.length === 0) {
this.logger.log(" > No events were emitted");
return;
}
this.logger.log("\n Events emitted during test:");
this.logger.log(" ---------------------------");
this.logger.log("");
for (const log of filteredLogs) {
switch (log.decodings.length) {
case 0:
this.logger.log(` Warning: Could not decode event!`);
this.logger.log("");
break;
case 1:
this.logger.log(printEvent(log.decodings[0], 4));
this.logger.log("");
break;
default:
this.logger.log(` Ambiguous event, possible interpretations:`);
for (const decoding of log.decodings) {
this.logger.log(printEvent(decoding, 6, " * "));
}
this.logger.log("");
break;
}
}
this.logger.log("\n ---------------------------");
};
TestRunner.prototype.snapshot = async function() {
return (await this.rpc("evm_snapshot")).result;
};
TestRunner.prototype.revert = async function(snapshot_id) {
await this.rpc("evm_revert", [snapshot_id]);
};
TestRunner.prototype.rpc = async function(method, arg) {
let request = {
jsonrpc: "2.0",
method: method,
id: Date.now(),
params: arg
};
let result = await util.promisify(this.provider.send)(request);
if (result.error != null) {
throw new Error("RPC Error: " + (result.error.message || result.error));
}
return result;
};
module.exports = TestRunner;
| JavaScript | 0.000001 | @@ -5387,24 +5387,32 @@
const
-filtered
+userDefinedEvent
Logs = l
@@ -5523,24 +5523,32 @@
%0A%0A if (
-filtered
+userDefinedEvent
Logs.len
@@ -5788,16 +5788,24 @@
of
-filtered
+userDefinedEvent
Logs
|
bdbe9d190276955cf6191a215bd90cdb19499322 | Add an ONA_ORG env var | config/Config.js | config/Config.js | const env = process.env;
module.exports = {
// core
environment: env.NODE_ENV || 'development', // dev, prod, test
PORT: env.PORT || env.APP_PORT || 3000, // env to run karma on
defaultLanguage: env.DEFAULT_LANGUAGE || 'en',
conversationTimeout: env.CONVERSATION_TIMEOUT || 120000,
// facebook
facebookPageAccessToken: env.FACEBOOK_PAGE_ACCESS_TOKEN,
facebookAppSecret: env.FACEBOOK_APP_SECRET,
facebookApiVersion: env.FACEBOOK_API_VERSION || 'v2.10',
facebookVerifyToken: env.FACEBOOK_VERIFY_TOKEN || 'karma',
// external data stores
onadataApiToken: env.ONADATA_API_TOKEN,
rapidproApiToken: env.RAPIDPRO_API_TOKEN,
rapidproGroups: env.RAPIDPRO_GROUPS ? JSON.parse(env.RAPIDPRO_GROUPS) : [],
// logging and error reporting
sentryDSN: env.SENTRY_DSN,
karmaAccessLogFile: env.KARMA_ACCESS_LOG_FILE || 'bot.access.log',
debugTranslations: env.DEBUG_TRANSLATIONS === 'true' || false,
};
| JavaScript | 0 | @@ -553,16 +553,39 @@
stores%0A
+ onaOrg: env.ONA_ORG,%0A
onadat
|
a3fa123e9b290cf0861d9a1b57113c95e3abf6a7 | Test post | public/js/index.js | public/js/index.js | 'use strict';
// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
initializePage();
})
/*
* Function that is called when the document is ready.
*/
function initializePage() {
$(".header__hamburger-menu").on('click', function(){
$(".menu-container").removeClass('close', 1000);
});
$('.drawer-menu__close-btn').on('click', function(){
$(".menu-container").addClass('close', 1000);
});
$(".toggle__calendar").on('click', function(){
$(".toggle__events").removeClass('active');
$(this).addClass('active');
$('.calendar-container .calendar').show();
$('.calendar-container .events').hide();
});
$(".toggle__events").on('click', function(){
$(".toggle__calendar").removeClass('active');
$(this).addClass('active');
$('.calendar-container .events').show();
$('.calendar-container .calendar').hide();
});
$("#testBTN").on('click', function(){
console.log("hi");
$.ajax(
{
type: "POST",
url: "http://styloappstag.herokuapp.com/test",
crossDomain:true,
dataType: "json",
data:JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}})
}
);
});
}
| JavaScript | 0 | @@ -984,16 +984,17 @@
l: %22http
+s
://stylo
|
e342356d74411219df48f5739fe203ef859665fe | Use permission service in model. | api/models/User.js | api/models/User.js | var User = {
// Enforce model schema in the case of schemaless databases
schema: true,
attributes: {
username: { type: 'string', unique: true },
email: { type: 'email', unique: true },
passports: { collection: 'Passport', via: 'user' },
permissions: { type: 'array', defaultsTo: [] },
permission_groups: { collection: 'PermissionGroup', via: 'users_in_group', defaultsTo: [] },
hasPermission: function (inPermission) {
return _.contains(this.permissions, inPermission) || _.some(this.permission_groups, function (permissionGroup) {
_.contains(permissionGroup.permissions, inPermission);
});
},
addPermission: function(permission) {
this.permissions.push(permission);
},
removePermission: function(permission) {
this.permissions = _.without(this.permissions, permission);
},
addToPermissionGroup: function(group) {
},
removeFromPermissionGroup: function(group) {
}
}
};
module.exports = User;
| JavaScript | 0 | @@ -490,26 +490,44 @@
return
-_.contains
+PermissionService.isIncluded
(this.pe
@@ -597,28 +597,112 @@
tion
- (permissionGroup) %7B
+(group) %7B%0A PermissionService.isIncluded(group.permissions, inPermission);%0A %7D);
%0A
@@ -706,24 +706,27 @@
+%7D,%0A
_.contai
@@ -721,63 +721,326 @@
-_.contains(permissionGroup.permissions, inPermission);%0A
+allPermissions: function() %7B%0A var all = %5B%5D;%0A this.permissions.forEach(function(perm) %7B%0A all.push(perm);%0A %7D);%0A%0A this.permission_groups.forEach(function(group) %7B%0A group.permissions.forEach(function(perm) %7B%0A all.push(perm);%0A
@@ -1051,34 +1051,75 @@
%7D);%0A
+
-%7D,
+ %7D);%0A%0A return all;%0A %7D%0A
%0A addPerm
@@ -1379,32 +1379,81 @@
nction(group) %7B%0A
+ this.permission_groups.add(group.id);
%0A %7D,%0A
@@ -1501,16 +1501,68 @@
roup) %7B%0A
+ this.permission_groups.remove(group.id);
%0A
|
43a7230b5d88688df6d7d79e2fcb6419ad8246e9 | Fix arrows keys in slug input field in FireFox | public/js/augmenters/slug-validation.js | public/js/augmenters/slug-validation.js | // ------------------------
// Slug Validation
// ------------------------
require( [ 'jquery', 'utils/slugify' ],
function( $, slugify ) {
var check_allowed_letter = function(ltr){
if (
(ltr >= 97 && ltr <= 122) // a-z
|| (ltr >= 65 && ltr <= 90) // A-Z
|| (ltr >= 48 && ltr <= 57) // 0-9
|| (ltr === 45) // -
|| (ltr === 32) // space - let it through and then let thu slugify code convert them into dashes
|| ($.inArray(ltr, [13, 37, 39, 9, 20, 46, 8]) >= 0) // Special keys, http://mikemurko.com/general/jquery-keycode-cheatsheet/
) {
return true;
} else {
return false;
}
}
$(document).on(
{
keypress: function(e) {
// Return True/False to prevent or allow the key being pressed or add an
// error class to display the hint when a disallowed key is pressed
return check_allowed_letter(e.which);
},
change: function(e) {
// Check pasted text
var changedText = $(this).val();
var cleanedText = slugify( changedText );
$(this).val(cleanedText);
}
},
'input[name=slug]'
);
});
| JavaScript | 0.000002 | @@ -718,16 +718,222 @@
ion(e) %7B
+%0A%0A // .which seems to return 0 for some keys in firefox - like the arrow keys. If%0A // we don't get a response from which fall back to .keyCode%0A var key = e.which %7C%7C e.keyCode;%0A
%0A%09
@@ -1116,23 +1116,21 @@
_letter(
-e.which
+ key
);%0A%09
|
3a435eded8a99c559d6f559db93a5e9a08f0b484 | Add future tests | packages/docpack-jsdoc-extractor/test/extractor.test.js | packages/docpack-jsdoc-extractor/test/extractor.test.js | var chai = require('chai');
chai.use(require('chai-as-promised'));
chai.should();
var extract = require('../lib/extractor');
var Source = require('docpack/lib/data/Source');
var Example = require('docpack/lib/data/Example');
describe('Extractor', () => {
var source;
beforeEach(() => {
source = new Source({
path: 'source.js',
absolutePath: '/source.js',
content: ''
});
});
it('should return null if source content is empty', () => {
source.content = '';
return extract(source).should.become(null);
});
it('should reject when invalid jsdoc', () => {
source.content = `/** @type {{{ */ var a = 123;`;
return extract(source).should.be.rejected;
});
it('should save tags from first comment in source attributes', (done) => {
source.content = `
/** @module tralala */
var a = 1
/** @name qwe */
var b = 2
`;
extract(source)
.then(source => {
source.attrs.module.should.eql('tralala');
source.blocks.should.have.lengthOf(2);
source.blocks[0].attrs.module.should.eql('tralala');
source.blocks[1].attrs.name.should.eql('qwe');
done();
})
.catch(done);
});
it('should process markdown in comment text', (done) => {
source.content = '/** qwe *qwe* qwe */';
extract(source)
.then(source => {
source.blocks[0].description.should.contain(' <em>qwe</em> ');
done();
})
.catch(done);
});
it('should save every tag in block.attrs and support custom tags', (done) => {
source.content = `
/**
* @type {Object} foo
* @qwe1 qwe1
* @qwe2 qwe2
*/`;
extract(source)
.then(source => {
var attrs = source.blocks[0].attrs;
attrs.should.have.property('type').and.eql('{Object} foo');
attrs.should.have.property('qwe1').and.eql('qwe1');
attrs.should.have.property('qwe2').and.eql('qwe2');
done();
})
.catch(done);
});
describe('Tags special processing', () => {
describe('@description', () => {
it('should process markdown', (done) => {
source.content = `
/**
* @description qwe *qwe* ***
*/
`;
extract(source)
.then(source => {
source.blocks[0].attrs.description.should.contain(' <em>qwe</em> ');
done();
})
.catch(done);
});
});
describe('@example', () => {
it('should create example from simple example', (done) => {
source.content = `
/**
* @example
* func(123);
* // => 456;
*/
`;
extract(source)
.then(source => {
var example = source.blocks[0].examples[0];
example.should.exist.and.be.instanceOf(Example);
example.files.should.be.empty;
done();
})
.catch(done);
});
it('should process xml examples', (done) => {
source.content = `
/**
* @example
* <example><file></file></example>
*/
`;
extract(source)
.then(source => {
var example = source.blocks[0].examples[0];
example.should.exist.and.be.instanceOf(Example);
example.files.should.be.lengthOf(1);
done();
})
.catch(done);
});
});
});
}); | JavaScript | 0.000001 | @@ -3447,18 +3447,311 @@
%7D);%0A
+%0A describe('@example-file', () =%3E %7B%0A it('should properly resolve the file', () =%3E %7B%7D);%0A it('should parse file properly', () =%3E %7B%7D);%0A it('should assign examples in right order', () =%3E %7B%7D);%0A it('should cause recompilation when example file was changed', () =%3E %7B%7D);%0A
%7D);%0A
+ %7D);
%0A%7D);
|
f590ab151e3ca2a8c88da1eba8e26608f9f186fc | Update config.js | config/config.js | config/config.js | var config = {
port: 8080,
ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"],
language: 'en',
untis: 'imperial',
modules: [
{
module: "updatenotification",
position: "top_bar"
},
{
module: 'clock',
position: 'top_left'
},
{
module: 'currentweather',
position: 'top_right',
header: "New York City",
config: {
location: "NYC, NY",
latitude: "40.73",
longitude: "-73.94",
apiBaseURL: "twcservice.mybluemix.net/api/weather/v1/geocode/",
username: "5a6159b6-edb8-4741-9584-140d1f1506f2",
password: "rnag46J0ue",
endpoint: "observations"
}
},
{
module: 'news',
position: 'bottom_right',
header: "News"
},
{
module: 'maps',
position: 'middle_center',
config: {
apikey: 'AIzaSyA60mxJ7eqA6zxthZ7JE44uomf5TTcnOKA',
origin: '',
destination: '',
width: "100%",
height: "500px"
}
},
{
module: 'youtube',
position: 'bottom_left'
},
{
module: 'fb',
position: 'right',
config: {
style: 'border:none;overflow:hidden',
width: "540",
height: "1700"
}
},
{
module: 'trafficincidents',
position: 'middle_center',
header: 'Traffic'
},
{
module: 'jokes',
position: 'middle_center',
header: 'Jokes By Ron Swanson'
},
{
module: 'conversation'
},
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== 'undefined') {module.exports = config;}
| JavaScript | 0.000002 | @@ -321,20 +321,19 @@
n: 'top_
-righ
+lef
t',%0A
@@ -373,321 +373,8 @@
-config: %7B%0A location: %22NYC, NY%22,%0A latitude: %2240.73%22,%0A longitude: %22-73.94%22,%0A apiBaseURL: %22twcservice.mybluemix.net/api/weather/v1/geocode/%22,%0A username: %225a6159b6-edb8-4741-9584-140d1f1506f2%22,%0A password: %22rnag46J0ue%22,%0A endpoint: %22observations%22%0A %7D
%0A
|
fc13658c7a122e4e46e4f0893d989b09652d53c5 | Use `vivify` in `t/merge/race.t.js`. | t/merge/race.t.js | t/merge/race.t.js | #!/usr/bin/env node
require('./proof')(2, function (step, tmp, Strata, load, serialize, objectify, assert) {
var cadence = require('cadence'), strata, insert
function tracer (type, object, callback) {
switch (type) {
case 'plan':
cadence(function (step) {
step(function () {
strata.mutator(insert, step())
}, function (cursor) {
step(function () {
cursor.insert(insert, insert, ~cursor.index, step())
}, function () {
cursor.unlock()
})
})
})(callback)
break
default:
callback()
}
}
step(function () {
serialize(__dirname + '/fixtures/race.before.json', tmp, step())
}, function () {
strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3, tracer: tracer })
strata.open(step())
}, function () {
strata.mutator('b', step())
}, function (cursor) {
step(function () {
cursor.remove(cursor.index, step())
}, function () {
cursor.unlock()
})
}, function () {
insert = 'b'
strata.balance(step())
}, function () {
objectify(tmp, step())
load(__dirname + '/fixtures/race-left.after.json', step())
}, function(actual, expected) {
assert(actual, expected, 'race left')
strata.close(step())
}, function () {
serialize(__dirname + '/fixtures/race.before.json', tmp, step())
}, function () {
strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3, tracer: tracer })
strata.open(step())
}, function () {
strata.mutator('d', step())
}, function (cursor) {
step(function () {
cursor.remove(cursor.index, step())
}, function () {
cursor.unlock()
})
}, function () {
insert = 'd'
strata.balance(step())
}, function () {
objectify(tmp, step())
load(__dirname + '/fixtures/race-right.after.json', step())
}, function(actual, expected) {
assert(actual, expected, 'race right')
strata.close(step())
})
})
| JavaScript | 0 | @@ -82,22 +82,19 @@
ialize,
-object
+viv
ify, ass
@@ -1298,38 +1298,35 @@
on () %7B%0A
-object
+viv
ify(tmp, step())
@@ -2064,22 +2064,19 @@
-object
+viv
ify(tmp,
|
37057a82b298e400d808150eaa291bfc351a8080 | Fix "sparkly" and "json" formatters | penkki.js | penkki.js | #!/usr/bin/env node
/*globals require, console*/
'use strict'
const chalk = require('chalk'),
process = require('process'),
args = require('command-line-args'),
cp = require('child_process'),
R = require('ramda')
const error = chalk.bold.red
const header = `${chalk.blue('Penkki')}. Run a command ${chalk.italic('n')} times and measure how long it takes.`
const cli = args([
{ name: 'command',
type: String,
multiple: true,
defaultOption: true,
description: 'The command to run.'
},
{ name: 'formatter',
alias: 'f',
type: String,
defaultValue: 'json',
description: 'The formatter to use. Either "json", "sparkly", "chart", or "html". Default: "json".'
},
{ name: 'times',
alias: 't',
type: Number,
description: 'The number of times to run the command.'
},
{ name: 'help',
alias: 'h',
type: Boolean,
description: 'Show this help.'
}
])
const options = cli.parse()
// Every method is a function that returns the options for the given formatter.
const formatterOptions = {
chart: () => { return { width: 80, height: 25 } },
html: R.identity
}
if (!options.command || options.help) {
console.log(header)
console.log(cli.getUsage())
process.exit(1)
}
function time(command) {
let before = Date.now()
cp.execSync(command)
let after = Date.now()
return after - before
}
// Get the output formatter.
//
// Try to load the given formatter in the "formatters" directory. If not found,
// try the dependencies. If still not found, throw an error.
function loadFormatter(name) {
try {
return require('./formatters/' + name)
} catch (_) {
try {
return require(name)
} catch (e) {
console.error(`${error('ERROR:')} Couldn't load formatter "${name}":`)
console.error(e)
process.exit(1)
}
}
}
function main() {
const command = options.command.join(' ')
const data = R.times(R.partial(time, [command]), options.times)
let formatter = loadFormatter(options.formatter)
return formatter(data, formatterOptions[formatter.name](command))
}
console.log(main())
| JavaScript | 0.100372 | @@ -1191,16 +1191,18 @@
chart:
+
() =%3E %7B
@@ -1240,29 +1240,8 @@
%7D %7D
-,%0A html: R.identity
%0A%7D%0A%0A
@@ -1937,24 +1937,141 @@
%7D%0A %7D%0A%7D%0A%0A
+function getFormatterOptions(name) %7B%0A return R.has(name, formatterOptions) ? formatterOptions%5Bname%5D : R.identity%0A%7D%0A%0A
function mai
@@ -2262,17 +2262,20 @@
r(data,
-f
+getF
ormatter
@@ -2281,17 +2281,17 @@
rOptions
-%5B
+(
formatte
@@ -2296,17 +2296,17 @@
ter.name
-%5D
+)
(command
|
62cef5062006dcdd24d8ba05fce3f48e694e51f7 | Update after merge? | js/sky/src/phonefield/phonefield.directive.js | js/sky/src/phonefield/phonefield.directive.js | /* global angular, intlTelInputUtils*/
(function () {
'use strict';
/**
* bbPhoneField directive controller for bb-phone-field
*/
function bbPhoneField() {
function link($scope, el, attrs, ngModel) {
// ** variables **
var input = el;
/**
* getFormattedNumber returns the national or internationally formatted phone number in the input
* based on the currently selected country and the default country
*/
function getFormattedNumber() {
var formattedNumber = '',
selectedCountryData = input.intlTelInput('getSelectedCountryData');
// Grab the plugin's version of the formatted phone number
if (input.val()) {
formattedNumber = input.intlTelInput('getNumber', intlTelInputUtils.numberFormat.NATIONAL);
// If the currently selected country is also the directive's default country, it is already formatted
if ($scope.bbPhoneFieldConfig.props && $scope.bbPhoneFieldConfig.props.countryIso2 === selectedCountryData.iso2) {
return formattedNumber;
} else if (selectedCountryData && formattedNumber.indexOf('+') < 0) {
return '+' + selectedCountryData.dialCode + ' ' + formattedNumber;
}
}
return formattedNumber;
}
// ** intl-tel-input initilization **
// initialize the intl-tel-input plugin.
// nationalMode is true by default, which we want for easy formatting purposes.
input.intlTelInput();
// when the country changes, update the scope's bbPhoneFieldConfig property
input.on('countrychange', function (e, countryData) {
ngModel.$setViewValue(getFormattedNumber());
$scope.$apply(function () {
if ($scope.bbPhoneFieldConfig.props) {
$scope.bbPhoneFieldConfig.props.selectedCountry = countryData;
}
});
});
// ** ng-model settings **
// anytime ng-model is updated, its final value should be the formatted phone number
$scope.$watch(attrs.ngModel, function () {
ngModel.$setViewValue(getFormattedNumber());
});
// tie ng-model's format validation to the plugin's validator
ngModel.$validators.bbPhoneFormat = function (modelValue) {
return modelValue && input.intlTelInput('isValidNumber');
};
// ** bbPhoneFieldConfig properties **
if ($scope.bbPhoneFieldConfig.props) {
// if a default country is provided, we set that as the initial country
if ($scope.bbPhoneFieldConfig.props.countryIso2) {
input.intlTelInput('setCountry', $scope.bbPhoneFieldConfig.props.countryIso2);
}
$scope.bbPhoneFieldConfig.props.selectedCountry = input.intlTelInput('getSelectedCountryData');
}
// ** ARIA (Accessibility Rich Internet Applications) **
// We hide the country dropdown from a screen reader because the "dropdown"
// is actually an unordered list which is not easily accessed without clicking or arrowing accordingly
angular.element('.selected-flag').attr('aria-hidden', true);
// If the screen-reader user does manage to get the dropdown going, we apply the ARIA tags so that they can header the countries
angular.element('.country-list').attr('role', 'listbox');
angular.element('.country').attr('role', 'option');
}
return {
bindToController: {
props: '=bbPhoneField'
},
controller: bbPhoneField,
controllerAs: "bbPhoneFieldConfig",
link: link,
restrict: 'A',
require: 'ngModel'
};
}
angular.module('sky.phonefield.directive', [])
.directive('bbPhoneField', bbPhoneField);
}());
| JavaScript | 0 | @@ -1943,99 +1943,99 @@
+if (
$scope.
-$apply(function () %7B%0A if ($scope.bbPhoneFieldConfig.props) %7B%0A
+bbPhoneFieldConfig.props) %7B%0A $scope.$apply(function () %7B%0A
@@ -2137,33 +2137,39 @@
-%7D
+ %7D);
%0A
@@ -2161,39 +2161,33 @@
- %7D);
+%7D
%0A %7D);
|
a8fbb8c695499252820f4ad93ea450986d74a017 | Fix error | v1/OnlineFriendCount.plugin.js | v1/OnlineFriendCount.plugin.js | //META {"name": "OnlineFriendCount", "source": "https://github.com/Zerthox/BetterDiscord-Plugins/blob/master/v1/OnlineFriendCount.plugin.js"} *//
/**
* @author Zerthox
* @version 1.0.2
* @return {class} OnlineFriendCount plugin class
*/
const OnlineFriendCount = (() => {
// Api constants
const {React} = BdApi;
/**
* module storage
*/
const Module = {
status: BdApi.findModuleByProps("getStatus", "getOnlineFriendCount"),
guilds: BDV2.WebpackModules.findByDisplayName("Guilds")
};
/**
* selector storage
*/
const Selector = {
guildsWrapper: BdApi.findModuleByProps("wrapper", "unreadMentionsBar"),
guilds: BdApi.findModuleByProps("listItem", "friendsOnline")
};
/**
* storage for patches
*/
const Patches = {};
// return plugin class
return class OnlineFriendCount {
/**
* @return {string} plugin name
*/
getName() {
return "OnlineFriendCount";
}
/**
* @return {*} plugin description
*/
getDescription() {
return React.createElement("span", {"white-space": "pre-line"},
"Add the old online friend count back to guild list. Because nostalgia."
);
}
/**
* @return {string} plugin version
*/
getVersion() {
return "1.0.2";
}
/**
* @return {*} plugin author
*/
getAuthor() {
return React.createElement("a", {href: "https://github.com/Zerthox", target: "_blank"}, "Zerthox");
}
/**
* plugin start function
*/
start() {
// patch guilds render function
Patches.guilds = BdApi.monkeyPatch(Module.guilds.prototype, "render", {after: (d) => {
// get return value
const r = d.returnValue;
// find guild list
const l = r.props.children[1].props.children;
// check if online friends count is not inserted yet
if (!l.find((e) => e.props.className === Selector.guilds.friendsOnline)) {
// insert online friends count before separator
l.splice(l.indexOf(l.find((e) => e.type.name === "N")), 0, React.createElement("div", {className: Selector.guilds.friendsOnline, style: {"margin-left": 0}}, `${Module.status.getOnlineFriendCount()} Online`));
}
// return modified return value
return r;
}});
// force update
this.forceUpdateAll();
// console output
console.log(`%c[${this.getName()}]%c v${this.getVersion()} enabled`, "color: #3a71c1; font-weight: 700;", "");
}
/**
* plugin stop function
*/
stop() {
// revert all patches
for (const f of Object.values(Patches)) {
f();
}
// force update
this.forceUpdateAll();
// console output
console.log(`%c[${this.getName()}]%c v${this.getVersion()} disabled`, "color: #3a71c1; font-weight: 700;", "");
}
/**
* force update guild list
*/
forceUpdateAll() {
// force update guilds wrapper
for (const e of document.getElementsByClassName(Selector.guildsWrapper.wrapper)) {
const i = BdApi.getInternalInstance(e);
i && i.return.stateNode.forceUpdate();
}
}
}
})();
| JavaScript | 0.000004 | @@ -179,17 +179,17 @@
ion 1.0.
-2
+3
%0A * @ret
@@ -1431,17 +1431,17 @@
rn %221.0.
-2
+3
%22;%0A
@@ -2179,16 +2179,27 @@
d((e) =%3E
+ e.props &&
e.props
|
bc7439174c9d024937585596b11de04a78546777 | Update with-destructuring.js | katas/es6/language/rest/with-destructuring.js | katas/es6/language/rest/with-destructuring.js | // 19: rest - with-destructuring
// To do: make all tests pass, leave the assert lines unchanged!
describe('rest with destrcturing', () => {
it('rest parameter must be last', () => {
const [...all, last] = [1, 2, 3, 4];
assert.deepEqual(all, [1, 2, 3, 4]);
});
it('assign rest of an array to a variable', () => {
const [...all] = [1, 2, 3, 4];
assert.deepEqual(all, [2, 3, 4]);
});
// the following are actually using `spread` ... oops, to be fixed
it('concat differently', () => {
const theEnd = [3, 4];
const allInOne = [1, 2, ...[theEnd]];
assert.deepEqual(allInOne, [1, 2, 3, 4]);
});
it('`apply` made simple, even for constructors', () => {
const theDate = [2015, 1, 1];
const date = new Date(theDate);
assert.deepEqual(new Date(2015, 1, 1), date);
});
});
| JavaScript | 0 | @@ -117,16 +117,17 @@
th destr
+u
cturing'
|
4dbc3d48acffd68dbe9014179e589e5890de9c76 | add js defn of that = this | usage/jsgui/src/main/webapp/assets/js/view/entity-policies.js | usage/jsgui/src/main/webapp/assets/js/view/entity-policies.js | /**
* Render the policies tab.You must supply the model and optionally the element
* on which the view binds itself.
*
* @type {*}
*/
define([
"underscore", "jquery", "backbone",
"model/policy-summary", "model/policy-config-summary", "view/viewutils", "view/policy-config-invoke", "text!tpl/apps/policy.html", "text!tpl/apps/policy-row.html", "text!tpl/apps/policy-config-row.html",
"jquery-datatables", "datatables-extensions"
], function (_, $, Backbone, PolicySummary, PolicyConfigSummary, ViewUtils, PolicyConfigInvokeView, PolicyHtml, PolicyRowHtml, PolicyConfigRowHtml) {
var EntityPoliciesView = Backbone.View.extend({
template:_.template(PolicyHtml),
policyRow:_.template(PolicyRowHtml),
events:{
'click .refresh':'refreshPolicyConfigNow',
'click .filterEmpty':'toggleFilterEmpty',
"click #policies-table tr":"rowClick",
"click .policy-start":"callStart",
"click .policy-stop":"callStop",
"click .policy-destroy":"callDestroy",
"click .show-policy-config-modal":"showPolicyConfigModal"
},
initialize:function () {
_.bindAll(this)
this.$el.html(this.template({ }));
var that = this;
// fetch the list of policies and create a row for each one
that._policies = new PolicySummary.Collection();
that._policies.url = that.model.getLinkByName("policies");
this.loadedData = false;
ViewUtils.fadeToIndicateInitialLoad(this.$('#policies-table'));
that.render();
this._policies.on("all", this.render, this)
ViewUtils.fetchRepeatedlyWithDelay(this, this._policies,
{ doitnow: true, success: function() {
that.loadedData = true;
ViewUtils.cancelFadeOnceLoaded(that.$('#policies-table'));
}})
},
render:function () {
if (this.viewIsClosed)
return;
var that = this,
$tbody = this.$('#policies-table tbody').empty();
if (that._policies.length==0) {
if (this.loadedData)
this.$(".has-no-policies").show();
this.$("#policy-config").hide();
this.$("#policy-config-none-selected").hide();
} else {
this.$(".has-no-policies").hide();
that._policies.each(function (policy) {
// TODO better to use datatables, and a json array, as we do elsewhere
$tbody.append(that.policyRow({
cid:policy.get("id"),
name:policy.get("name"),
state:policy.get("state"),
summary:policy
}));
if (that.activePolicy) {
that.$("#policies-table tr[id='"+that.activePolicy+"']").addClass("selected");
that.showPolicyConfig(that.activePolicy);
that.refreshPolicyConfig();
} else {
that.$("#policy-config").hide();
that.$("#policy-config-none-selected").show();
}
});
}
return that;
},
toggleFilterEmpty:function() {
ViewUtils.toggleFilterEmpty($('#policy-config-table'), 2);
},
refreshPolicyConfigNow:function () {
this.refreshPolicyConfig();
},
rowClick:function(evt) {
evt.stopPropagation();
var row = $(evt.currentTarget).closest("tr"),
id = row.attr("id"),
policy = this._policies.get(id);
$("#policies-table tr").removeClass("selected");
if (this.activePolicy == id) {
// deselected
this.activePolicy = null;
this._config = null;
$("#policy-config-table").dataTable().fnDestroy();
$("#policy-config").slideUp(100);
$("#policy-config-none-selected").slideDown(100);
} else {
row.addClass("selected");
var that = this;
// fetch the list of policy config entries
that._config = new PolicyConfigSummary.Collection();
that._config.url = policy.getLinkByName("config");
ViewUtils.fadeToIndicateInitialLoad($('#policy-config-table'))
that.showPolicyConfig(id);
that._config.fetch({ success:function () {
that.showPolicyConfig(id);
ViewUtils.cancelFadeOnceLoaded($('#policy-config-table'))
}});
}
},
showPolicyConfig:function (activePolicyId) {
var that = this;
if (activePolicyId != null && that.activePolicy != activePolicyId) {
// TODO better to use a json array, as we do elsewhere
var $table = $('#policy-config-table'),
$tbody = $('#policy-config-table tbody').empty();
$("#policy-config-none-selected").slideUp(100);
if (that._config.length==0) {
$(".has-no-policy-config").show();
} else {
$(".has-no-policy-config").hide();
that.activePolicy = activePolicyId;
var policyConfigRow = _.template(PolicyConfigRowHtml);
that._config.each(function (config) {
$tbody.append(policyConfigRow({
cid:config.cid,
name:config.get("name"),
description:config.get("description"),
type:config.get("type"),
reconfigurable:config.get("reconfigurable"),
link:config.getLinkByName('self'),
value:'' // will be set later
}));
$tbody.find('*[rel="tooltip"]').tooltip();
});
that.currentStateUrl = that._policies.get(that.activePolicy).getLinkByName("config") + "/current-state";
$("#policy-config").slideDown(100);
$table.slideDown(100);
ViewUtils.myDataTable($table, {
"bAutoWidth": false,
"aoColumns" : [
{ sWidth: '220px' },
{ sWidth: '240px' },
{ sWidth: '25px' }
]
});
$table.dataTable().fnAdjustColumnSizing();
}
}
that.refreshPolicyConfig();
},
refreshPolicyConfig:function() {
if (that.viewIsClosed) return;
var $table = that.$('#policy-config-table').dataTable(),
$rows = that.$("tr.policy-config-row");
$.get(that.currentStateUrl, function (data) {
if (that.viewIsClosed) return;
// iterate over the sensors table and update each sensor
$rows.each(function (index, row) {
var key = $(this).find(".policy-config-name").text();
var v = data[key];
if (v === undefined) v = "";
$table.fnUpdate(_.escape(v), row, 1, false);
});
});
$table.dataTable().fnStandingRedraw();
},
showPolicyConfigModal:function (evt) {
evt.stopPropagation();
// get the model that we need to show, create its view and show it
var cid = $(evt.currentTarget).attr("id");
this._modal = new PolicyConfigInvokeView({
el:"#policy-config-modal",
model:this._config.get(cid),
policy:this.model
});
this._modal.render().$el.modal('show');
},
callStart:function(event) { this.doPost(event, "start"); },
callStop:function(event) { this.doPost(event, "stop"); },
callDestroy:function(event) { this.doPost(event, "destroy"); },
doPost:function(event, linkname) {
event.stopPropagation();
var that = this,
url = $(event.currentTarget).attr("link");
$.ajax({
type:"POST",
url:url,
success:function() {
that._policies.fetch();
}
});
}
});
return EntityPoliciesView;
});
| JavaScript | 0.998363 | @@ -6987,32 +6987,61 @@
ig:function() %7B%0A
+ var that = this;%0A
if (
|
e035612592ed476710837ebbb9b76e676791ea58 | Fix the variable name | config/engine.js | config/engine.js | export default {
apiKey: process.env.ENGINE_API_KEY, // Set your Apollo Engine API key
logging: {
level: 'DEBUG' // Engine Proxy logging level. DEBUG, INFO, WARN or ERROR
}
};
| JavaScript | 0.999999 | @@ -32,16 +32,23 @@
ess.env.
+APOLLO_
ENGINE_A
|
d723cedfe880aaf4361ecd89be25d3b49ed2717c | Add support for literal entries in the manifest. | tasks/appcache.js | tasks/appcache.js | /*
* grunt-appcache
* http://canvace.com/
*
* Copyright (c) 2013 Canvace Srl
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
var path = require('path');
var appcache = require('./lib/appcache').init(grunt);
function array(input) {
return Array.isArray(input) ? input : [input];
}
function isUrl(path) {
return (/^(?:https?:)?\/\//i).test(path);
}
function relative(basePath, filePath) {
return path.relative(
path.normalize(basePath),
path.normalize(filePath));
}
function expand(pattern, basePath) {
var matches = grunt.file.expand({
filter: function (src) {
return grunt.file.isFile(src) || isUrl(src);
}
}, pattern);
if (typeof basePath === 'string') {
matches = matches.map(function (filePath) {
return relative(basePath, filePath);
});
}
return matches;
}
grunt.registerMultiTask('appcache', 'Automatically generates an HTML5 AppCache manifest from a list of files.', function () {
var output = path.normalize(this.data.dest);
var options = this.options({
basePath: process.cwd(),
ignoreManifest: true,
preferOnline: false
});
var ignored = [];
if (this.data.ignored) {
ignored = expand(this.data.ignored, options.basePath);
}
if (options.ignoreManifest) {
ignored.push(relative(options.basePath, output));
}
var cache = expand(this.data.cache, options.basePath).filter(function (path) {
return ignored.indexOf(path) === -1;
});
var manifest = {
version: {
revision: 1,
date: new Date()
},
cache: cache,
network: array(this.data.network || []),
fallback: array(this.data.fallback || [])
};
if (grunt.file.exists(output)) {
var original = appcache.readManifest(output);
manifest.version.revision = (1 + original.version.revision);
}
if (!appcache.writeManifest(output, manifest)) {
grunt.log.error('AppCache manifest creation failed.');
return false;
}
grunt.log.writeln('AppCache manifest "' +
path.basename(output) +
'" created.');
});
};
| JavaScript | 0 | @@ -1627,138 +1627,578 @@
ache
- = expand(this.data.cache, options.basePath).filter(function (path) %7B%0A return ignored.indexOf(path) === -1;%0A %7D);
+Patterns = array(this.data.cache %7C%7C %5B%5D);%0A if (typeof this.data.cache === 'object') %7B%0A this.data.cache.patterns = array(this.data.cache.patterns %7C%7C %5B%5D);%0A this.data.cache.literals = array(this.data.cache.literals %7C%7C %5B%5D);%0A cachePatterns = this.data.cache.patterns;%0A %7D%0A var cache = expand(cachePatterns, options.basePath).filter(function (path) %7B%0A return ignored.indexOf(path) === -1;%0A %7D);%0A if (typeof this.data.cache === 'object') %7B%0A cache.concat(this.data.cache.literals);%0A %7D
%0A%0A
|
f2fa37a5c19107fb6647b3a83e7668ea276c63d8 | use clean vs custom function to cleanup tar tempdir. | tasks/compress.js | tasks/compress.js | /**
* Task: compress
* Description: Compress files
* Dependencies: zipstream / tar / fstream
* Contributor(s): @ctalkington / @tkellen
* Inspired by: @jzaefferer (jquery-validation)
*/
module.exports = function(grunt) {
var _ = grunt.utils._,
async = grunt.utils.async;
grunt.registerMultiTask("compress", "Compress files.", function() {
var files = this.data.files,
options = grunt.helper("options", this, {type: 'zip', gzip: false, level: 1}),
supported = ['zip', 'tar'],
done = this.async();
async.forEachSeries(_.keys(files),function(dest, next) {
var src = files[dest],
srcFiles = grunt.file.expandFiles(src),
dest = grunt.template.process(dest);
if(!_.include(supported, options.type)) {
grunt.log.error('Compression type ' + options.type + ' not supported.');
done();
return;
}
// these are suffixed with helper because grunt has a conflicting, built-in "gzip" helper
grunt.helper(options.type + "Helper", srcFiles, dest, options, function(error, written) {
if (error === null) {
grunt.log.writeln('File "' + dest + '" created (' + written + ' bytes written).');
} else {
grunt.log.error(error);
grunt.fail.warn(options.type + " compressor failed.");
}
next();
});
}, function() {
done();
});
});
grunt.registerHelper("zipHelper", function(files, dest, options, callback) {
var fs = require("fs"),
zip = require("zipstream").createZip(options),
destdir = _(dest).strLeftBack("/");
if (require("path").existsSync(destdir) === false) {
grunt.file.mkdir(destdir);
}
zip.pipe(fs.createWriteStream(dest));
function addFile(){
if (!files.length) {
zip.finalize(function(written) {
callback(null, written);
});
return;
}
var current = files.shift();
grunt.verbose.writeln('Adding "' + current + '" to zip.');
zip.addFile(fs.createReadStream(current), {name: current}, addFile);
}
addFile();
});
grunt.registerHelper("tarHelper", function(files, dest, options, callback) {
var fs = require("fs"),
path = require("path"),
fstream = require("fstream"),
tar = require("tar"),
zlib = require("zlib");
function rmdir(dir) {
var list = fs.readdirSync(dir);
for(var i = 0; i < list.length; i++) {
var filename = path.join(dir, list[i]);
var stat = fs.statSync(filename);
if(filename == "." || filename == "..") {
// pass these files
} else if(stat.isDirectory()) {
// rmdir recursively
rmdir(filename);
} else {
// rm fiilename
fs.unlinkSync(filename);
}
}
fs.rmdirSync(dir);
}
var destdir = _(dest).strLeftBack("/"),
tempdir = destdir + "/tar" + new Date().getTime() + "/";
if (require("path").existsSync(destdir) === false) {
grunt.file.mkdir(destdir);
}
_.each(files, function(filepath) {
var filename = _(filepath).strRightBack("/");
grunt.file.copy(filepath, tempdir + "/" + filename)
})
var reader = fstream.Reader({path: tempdir, type: "Directory"}),
packer = tar.Pack(),
gzipper = zlib.createGzip(),
writer = fstream.Writer(dest);
reader.pipe(packer);
if (options.gzip) {
packer.pipe(gzipper);
gzipper.pipe(writer);
} else {
packer.pipe(writer);
}
reader.on("error", function(e) {
callback(e, null);
});
packer.on("error", function(e) {
callback(e, null);
});
gzipper.on("error", function(e) {
callback(e, null);
});
writer.on("error", function(e) {
callback(e, null);
});
writer.on("close", function() {
rmdir(tempdir);
callback(null, "unknown");
});
});
}; | JavaScript | 0 | @@ -2365,514 +2365,8 @@
);%0A%0A
- function rmdir(dir) %7B%0A var list = fs.readdirSync(dir);%0A for(var i = 0; i %3C list.length; i++) %7B%0A var filename = path.join(dir, list%5Bi%5D);%0A var stat = fs.statSync(filename);%0A%0A if(filename == %22.%22 %7C%7C filename == %22..%22) %7B%0A // pass these files%0A %7D else if(stat.isDirectory()) %7B%0A // rmdir recursively%0A rmdir(filename);%0A %7D else %7B%0A // rm fiilename%0A fs.unlinkSync(filename);%0A %7D%0A %7D%0A fs.rmdirSync(dir);%0A %7D%0A%0A
@@ -3385,14 +3385,30 @@
-rmdir(
+grunt.helper(%22clean%22,
temp
@@ -3438,17 +3438,30 @@
ll,
-%22unknown%22
+fs.statSync(dest).size
);%0A
|
2b766a2eb70990ebefae632e940b254dddc321e6 | remove callback override | src/js/connector/jsonp.js | src/js/connector/jsonp.js | /**
* @fileoverview This Connector make connection between FileManager and file server api at old browser.<br>
* This Connector use hidden iframe.
* @dependency ne-code-snippet 1.0.3, jquery1.8.3
* @author NHN entertainment FE dev team Jein Yi <jein.yi@nhnent.com>
*/
ne.util.defineNamespace('ne.component.Uploader.Jsonp');
/**
* The modules will be mixed in connector by type.
*/
ne.component.Uploader.Jsonp = {/** @lends ne.component.Uploader.Jsonp */
/**
* Request by form submit.
* @param {object} config Configuration for submit form.
* @param {function} config.success Callback when post submit complate.
*/
addRequest: function(config) {
var callbackName = this._uploader.callbackName,
callback = config.success;
ne.util.defineNamespace(callbackName, ne.util.bind(this.successPadding, this, callback));
this._uploader.inputView.$el.submit();
},
/**
* Preprocessing response before callback run.
* @param {function} callback Request Callback function
* @param {object} response Response from server
*/
successPadding: function(callback, response) {
var result = {};
if (this._uploader.isCrossDomain()) {
result.items = this._getSplitItems(response);
} else {
result.items = response.filelist;
}
callback(result);
},
/**
* Make query data to array
* @param {object} data The Data extracted from querystring separated by '&'
* @private
*/
_getSplitItems: function(data) {
var sep = this._uploader.separator,
status = data.status.split(sep),
names = data.names.split(sep),
sizes = data.sizes.split(sep),
items = [];
ne.util.forEach(status, function(item, index) {
if (item === 'success') {
var nItem = {
name: names[index],
status: status[index],
size: sizes[index]
};
items.push(nItem);
}
});
return items;
},
/**
* Request ajax by config to remove file.
* @param {object} config
*/
removeRequest: function(config) {
var callbackName = this._uploader.callbackName + 'Remove',
data = {
callback: callbackName
},
callback = config.success;
ne.util.defineNamespace(callbackName, ne.util.bind(this.removePadding, this, callback));
$.ajax({
url: this._uploader.url.remove,
dataType: 'jsonp',
jsonp: callbackName,
data: ne.util.extend(data, config.data)
});
},
/**
* Preprocessing response before callback run.
* @param {function} callback Request Callback function
* @param {object} response Response from server
*/
removePadding: function(callback, response) {
var result = {};
result.action = 'remove';
result.name = decodeURIComponent(response.name);
callback(result);
}
};
| JavaScript | 0.000001 | @@ -2322,19 +2322,8 @@
Name
- + 'Remove'
,%0A
@@ -2521,32 +2521,38 @@
this, callback)
+, true
);%0A%0A $.aj
|
fb2335a9066a27a5bc178ed7a3e2dab6ec38a7d6 | fix filepath in debug comment | tasks/includes.js | tasks/includes.js | /*
* grunt-includes
* https://github.com/vanetix/grunt-includes
*
* Copyright (c) 2013 Matt McFarland
* Licensed under the MIT license.
*/
module.exports = function(grunt) {
/**
* Dependencies
*/
var path = require('path');
/**
* Regex for parsing includes
*/
var regex = /^(\s*)include\s+"(\S+)"\s*$/;
/**
* Format of comments for debug
*/
var html_comment = '<!-- %s -->', cstyle_comment = '/* --- %s --- */';
/**
* Core `grunt-includes` task
* Iterates over all source files and calls `recurse(path)` on each
*/
grunt.registerMultiTask('includes', 'Your task description goes here.', function() {
var opts = this.options({
regex: regex,
pos: 2, // the regex match group pos
nodup: false, // no duplicate files, that means already included files will not be imported again
comment: null, // default comment based on filename
debug: process.env.DEBUG
});
var use_default_comment = !opts.comment;
this.files.forEach(function(f) {
var cwd = f.cwd;
var src = f.src.filter(function(p) {
p = cwd ? path.join(cwd, p) : p;
if(grunt.file.exists(p)) {
return true;
} else {
grunt.log.warn('Source file "' + p + '" not found.');
return false;
}
});
var isfile = grunt.file.isFile(f.dest);
if (src.length > 1 && isfile) {
grunt.log.warn('Source file cannot be more than one when dest is a file.');
}
var flatten = f.flatten;
src.forEach(function(p) {
var save_name = flatten ? path.basename(p) : p;
var dest_file = isfile ? f.dest : path.join(f.dest, save_name);
p = cwd ? path.join(cwd, p) : p;
if (use_default_comment) {
opts.comment = isHtml(dest_file) ? html_comment : cstyle_comment;
}
grunt.file.write(dest_file, recurse(p, opts));
grunt.log.oklns('Saved ' + dest_file);
});
});
});
/**
* Helper to define whether it is a html file
*
* @param {String} p
* @return {Boolean}
*/
function isHtml(p) {
return ['html', 'htm'].indexOf(p.split('.').pop()) !== -1;
}
/**
* Helper for `includes` builds all includes for `p`
*
* @param {String} p
* @return {String}
*/
function recurse(p, opts, included) {
if(!grunt.file.isFile(p)) {
grunt.log.warn('Included file "' + p + '" not found.');
return 'Error including "' + p + '".';
}
included = included || {};
var comment = opts.comment;
if (opts.nodup && (p in included)) {
var msg = 'File ' + p + ' included before, skip';
grunt.log.debug(msg);
return opts.debug && comment.replace('%s', msg) || '';
}
included[p] = 1;
var src = grunt.file.read(p).split(grunt.util.linefeed);
var compiled = src.map(function(line) {
var match = line.match(opts.regex);
if(match) {
line = recurse(path.join(path.dirname(p), match[opts.pos]), opts, included);
if (opts.debug) {
var msg_begin = 'File: ' + p;
var msg_end = 'EOF: ' + p;
line = comment.replace('%s', msg_begin) + '\n' + line + '\n';
line = line + comment.replace('%s', msg_end);
}
}
return line;
});
return compiled.join(grunt.util.linefeed);
}
};
| JavaScript | 0 | @@ -2953,23 +2953,16 @@
-line = recurse(
+var f =
path
@@ -3000,16 +3000,42 @@
ts.pos%5D)
+;%0A line = recurse(f
, opts,
@@ -3104,25 +3104,25 @@
'File: ' +
-p
+f
;%0A
@@ -3145,17 +3145,17 @@
OF: ' +
-p
+f
;%0A
|
a3f7bf4ef60fd4efac83f20d2da1af4ce6eba859 | Set max bounds on map | source/javascripts/_choropleth.js | source/javascripts/_choropleth.js | //= require "_core"
ratgraph.choropleth = function (id, dimension, group, colorScale, geoJson) {
var _id = id;
var _chart = dc.leafletChoroplethChart(id);
var _dimension = dimension;
var _group = group;
var _colorScale = colorScale;
var _geoJson = geoJson;
_chart._init = function() {
var mapSize = ratgraph.calculateSvgSize(_id, margin, 1);
d3.select(_id).style('height',mapSize.height+'px');
_chart.width(mapSize.width)
.height(mapSize.height)
.dimension(_dimension)
.group(_group)
.tiles(function (map) {
var Stamen_TonerLite = L.tileLayer('http://{s}.tile.stamen.com/toner-lite/{z}/{x}/{y}.png', {
attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
subdomains: 'abcd',
minZoom: 0,
maxZoom: 20
});
Stamen_TonerLite.addTo(map);
})
.center([40.739039, -73.920887])
.zoom(11)
.colors(_colorScale)
.colorDomain(function() {
return [dc.utils.groupMin(this.group(), this.valueAccessor()),
dc.utils.groupMax(this.group(), this.valueAccessor())];
})
.colorAccessor(function (d) {
return d.value;
})
.featureKeyAccessor(function(feature) {
return feature.properties.ZIP;
})
.geojson(_geoJson);
_chart.calculateColorDomain();
// Create a legend for the choropleth
// Thanks to http://eyeseast.github.io/visible-data/2013/08/27/responsive-legends-with-d3/
var legend = d3.select('#legend')
.append('ul')
.attr('class', 'list-inline');
var keys = legend.selectAll('li.key')
.data(_colorScale.range());
keys.enter().append('li')
.attr('class', 'key')
.style('border-top-color', String)
.text(function (d) {
var r = _colorScale.invertExtent(d);
return formatCount(r[0]);
});
_chart.renderlet(function (chart) {
d3.select('#legend').selectAll('li.key')
.data(_chart.colors().range())
.text(function (d) {
var r = _chart.colors().invertExtent(d);
return formatCount(r[0]);
});
});
return _chart;
};
return _chart._init();
};
| JavaScript | 0 | @@ -288,16 +288,167 @@
on() %7B%0A%0A
+%09%09var southWest = L.latLng(40.4856, -74.27238),%0A%09%09 northEast = L.latLng(40.92026, -73.69011),%0A%09%09 bounds = L.latLngBounds(southWest, northEast);%0A%0A
%09%09var ma
@@ -498,16 +498,16 @@
in, 1);%0A
-
%0A%09%09d3.se
@@ -676,16 +676,79 @@
_group)%0A
+%09 .mapOptions(%7B%0A%09 %09maxBounds: bounds%0A%09 %7D)%0A
%09
@@ -1224,16 +1224,17 @@
inZoom:
+1
0,%0A%09%09%09%09%09
@@ -1318,25 +1318,23 @@
40.7
-39039
+4023
, -73.9
+6
20
-887
+2
%5D)%0A%09
@@ -2613,25 +2613,24 @@
%7D);%0A
-%0A
%09 %7D);%0A%0A%09
|
8898830b90740bfcf107ae78a7d4418d9743d5ff | remove indentation of filename in printout | replace.js | replace.js | var fs = require("fs"),
path = require("path"),
colors = require("colors"),
minimatch = require("minimatch");
module.exports = function(options) {
var lineCount = 0,
limit = 400; // chars per line
if (!options.color) {
options.color = "cyan";
}
var flags = "g"; // global multiline
if (options.ignoreCase) {
flags += "i";
}
if (options.multiline) {
flags += "m";
}
var regex;
if (options.regex instanceof RegExp) {
regex = options.regex;
}
else {
regex = new RegExp(options.regex, flags);
}
var canReplace = !options.preview && options.replacement !== undefined;
var includes;
if (options.include) {
includes = options.include.split(",");
}
var excludes = [];
if (options.exclude) {
excludes = options.exclude.split(",");
}
var ignoreFile = options.excludeList || path.join(__dirname, '/defaultignore');
var ignores = fs.readFileSync(ignoreFile, "utf-8").split("\n");
excludes = excludes.concat(ignores);
var replaceFunc;
if (options.funcFile) {
eval('replaceFunc = ' + fs.readFileSync(options.funcFile, "utf-8"));
}
for (var i = 0; i < options.paths.length; i++) {
if (options.async) {
replacizeFile(options.paths[i]);
}
else {
replacizeFileSync(options.paths[i]);
}
}
function canSearch(file, isFile) {
var inIncludes = includes && includes.some(function(include) {
return minimatch(file, include, { matchBase: true });
})
var inExcludes = excludes.some(function(exclude) {
return minimatch(file, exclude, { matchBase: true });
})
return ((!includes || !isFile || inIncludes) && (!excludes || !inExcludes));
}
function replacizeFile(file) {
fs.lstat(file, function(err, stats) {
if (err) throw err;
if (stats.isSymbolicLink()) {
// don't follow symbolic links for now
return;
}
var isFile = stats.isFile();
if (!canSearch(file, isFile)) {
return;
}
if (isFile) {
fs.readFile(file, "utf-8", function(err, text) {
if (err) {
if (err.code == 'EMFILE') {
console.log('Too many files, try running `replace` without --async');
process.exit(1);
}
throw err;
}
text = replacizeText(text, file);
if (canReplace && text !== null) {
fs.writeFile(file, text, function(err) {
if (err) throw err;
});
}
});
}
else if (stats.isDirectory() && options.recursive) {
fs.readdir(file, function(err, files) {
if (err) throw err;
for (var i = 0; i < files.length; i++) {
replacizeFile(path.join(file, files[i]));
}
});
}
});
}
function replacizeFileSync(file) {
var stats = fs.lstatSync(file);
if (stats.isSymbolicLink()) {
// don't follow symbolic links for now
return;
}
var isFile = stats.isFile();
if (!canSearch(file, isFile)) {
return;
}
if (isFile) {
var text = fs.readFileSync(file, "utf-8");
text = replacizeText(text, file);
if (canReplace && text !== null) {
fs.writeFileSync(file, text);
}
}
else if (stats.isDirectory() && options.recursive) {
var files = fs.readdirSync(file);
for (var i = 0; i < files.length; i++) {
replacizeFileSync(path.join(file, files[i]));
}
}
}
function replacizeText(text, file) {
var match = text.match(regex);
if (!match) {
return null;
}
if (!options.silent) {
var printout = " " + file[options.fileColor];
if (options.count) {
printout += (" (" + match.length + ")").grey;
}
console.log(printout);
}
if (!options.silent && !options.quiet
&& !(lineCount > options.maxLines)
&& options.multiline) {
var lines = text.split("\n");
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.match(regex)) {
if (++lineCount > options.maxLines) {
break;
}
var replacement = options.replacement || "$&";
line = line.replace(regex, replaceFunc || replacement[options.color]);
console.log(" " + (i + 1) + ": " + line.slice(0, limit));
}
}
}
if (canReplace) {
return text.replace(regex, replaceFunc || options.replacement);
}
}
}
| JavaScript | 0.000015 | @@ -4150,15 +4150,8 @@
ut =
- %22 %22 +
fil
@@ -4928,20 +4928,16 @@
le.log(%22
-
%22 + (i
|
0f39d34b18ae339bafc062335afedfee079fd270 | Add test for duplicateProperty & local variables | test/specs/linters/duplicate_property.js | test/specs/linters/duplicate_property.js | 'use strict';
var path = require('path');
var expect = require('chai').expect;
var linter = require('../../../lib/linters/' + path.basename(__filename));
var parseAST = require('../../../lib/linter').parseAST;
describe('lesshint', function () {
describe('#duplicateProperty()', function () {
it('should allow single instances of each property', function () {
var source = '.foo { color: red; }';
var result;
var ast;
var options = {
exclude: []
};
ast = parseAST(source);
ast = ast.first().first('block');
result = linter.lint(options, ast);
expect(result).to.be.undefined;
});
it('should not allow duplicate properties', function () {
var source = '.foo { color: red; color: blue; }';
var result;
var ast;
var expected = [{
column: 20,
line: 1,
message: 'Duplicate property: "color".'
}];
var options = {
exclude: []
};
ast = parseAST(source);
ast = ast.first().first('block');
result = linter.lint(options, ast);
expect(result).to.deep.equal(expected);
});
it('should allow excluded properties', function () {
var source = '.foo { color: red; color: green; }';
var result;
var ast;
var options = {
exclude: ['color']
};
ast = parseAST(source);
ast = ast.first().first('block');
result = linter.lint(options, ast);
expect(result).to.be.undefined;
});
it('should not allow duplicates of properties that are not excluded', function () {
var source = '.foo { color: red; color: green; }';
var result;
var ast;
var expected = [{
column: 20,
line: 1,
message: 'Duplicate property: "color".'
}];
var options = {
exclude: ['background']
};
ast = parseAST(source);
ast = ast.first().first('block');
result = linter.lint(options, ast);
expect(result).to.deep.equal(expected);
});
});
});
| JavaScript | 0 | @@ -2395,16 +2395,436 @@
%7D);
+%0A%0A it('should ignore local variables', function () %7B%0A var source = '.foo %7B @a: red; @b: 3px; %7D';%0A var result;%0A var ast;%0A%0A var options = %7B%0A exclude: %5B%5D%0A %7D;%0A%0A ast = parseAST(source);%0A ast = ast.first().first('block');%0A%0A result = linter.lint(options, ast);%0A%0A expect(result).to.be.undefined;%0A %7D);
%0A %7D);
|
a2d1a10f7c5ffa29944885ef6794700a5b8ca6ec | make sure tweetable | data/data.js | data/data.js | var request = require('request');
var forismatic = require('forismatic-node')();
var fs = require('fs');
var hexu = require('hexu');
var quotes = JSON.parse(fs.readFileSync(__dirname + "/data.json")) || [];
module.exports.quotes = quotes;
// console.log(hexu.blue("*** Ice is mining data ***"));
function pushData(cb) {
quotes = quotes.filter(function(item, pos) {
return quotes.indexOf(item) == pos;
});
fs.writeFile(__dirname + '/data.json', JSON.stringify(quotes), function (err) {
cb();
});
}
module.exports.addData = function(data) {
quotes.push(data);
fs.writeFile(__dirname + '/data.json', JSON.stringify(quotes), function (err) {});
}
function mineData() {
request('http://quote.machinu.net/api', function (error, response, body) {
if (!error && response.statusCode == 200) {
var obj = JSON.parse(body);
console.log(hexu.green("\t Success \u2713 => ") + "Mined Data: " + obj.text);
quotes.push(obj.text);
}
});
forismatic.getQuote(function (err, quote) {
if(err) throw err;
console.log(hexu.green("\t Success \u2713 => ") + "Mined Data: " + quote.quoteText);
quotes.push(quote.quoteText);
});
}
setInterval(mineData, 2000);
process.on('SIGINT', function() {
pushData(function() {
process.exit();
});
});
| JavaScript | 0.000036 | @@ -1036,16 +1036,24 @@
if(err)
+ %7B%0A
throw e
@@ -1056,16 +1056,62 @@
ow err;%0A
+ %7D%0A if(quote.quoteText.length %3C= 140) %7B%0A
co
@@ -1229,16 +1229,22 @@
eText);%0A
+ %7D%0A
%7D);%0A%7D%0A
|
f82d3ae716a30283a98310838c24d85f320e6212 | add steps | Algorithms/JS/integers/staircase.js | Algorithms/JS/integers/staircase.js | // Your teacher has given you the task of drawing a staircase structure. Being an expert programmer, you decided to make a program to draw it for you instead. Given the required height, can you print a staircase as shown in the example?
// Input
// You are given an integer depicting the height of the staircase.
// Output
// Print a staircase of height that consists of # symbols and spaces. For example for , here's a staircase of that height:
// #
// ##
// ###
// ####
// #####
// ######
// Note: The last line has 0 spaces before it.
function staircase(n) {
for(var i = 1; i <= n; i++){
var diff = n - i;
ht = " ".repeat(diff) + '#'.repeat(i);
console.log(ht);
}
}
| JavaScript | 0.000566 | @@ -553,16 +553,361 @@
e it.%0A%0A%0A
+%0A// create a loop that runs as many times as n starting from 1. (starting from zero ads an extra empty space)%0A // create a variable that gets the difference of n minus the current level we're on%0A // create a variable that stores as many spaces as the difference and as many hashtags as on the level the loop is on%0A // print out the variable%0A%0A
function
@@ -989,16 +989,20 @@
+var
ht = %22 %22
|
06e668c3c21001e96e8eaf92679b7fd81a80409d | Put years in an inverse order | packages/ember-forms/lib/fields/date.js | packages/ember-forms/lib/fields/date.js | require("ember-forms/fields/base");
var e = Ember.empty;
EF.DateComponent = Ember.ContainerView.extend({
childViews: ['dayView', 'monthView', 'yearView'],
value: Ember.computed(function(key, value){
var day, month, year;
if (arguments.length === 1){
day = this.getPath('dayView.value');
month = this.getPath('monthView.value');
year = this.getPath('yearView.value');
if(!e(day) && !e(month) && !e(year)){
return new Date(year, month, day);
}
}else if(value){
day = value.getDay() + '';
month = value.getMonth() + '';
year = value.getFullYear() + '';
this.setPath('dayView.value', day);
this.setPath('monthView.value', month);
this.setPath('yearView.value', year);
}
return value;
}).volatile(),
dayView: Ember.Select.extend({
attributeBindings: ['name'],
name: Ember.computed(function(){
return this.getPath('parentView').get('name') + '_day';
}),
prompt: "- Day -",
content: Ember.computed(function(){
var days = [];
for(var i=1; i<=31; i++){
days.push(i + '');
}
return Ember.A(days);
}).cacheable()
}),
monthView: Ember.Select.extend({
optionLabelPath: 'content.name',
optionValuePath: 'content.id',
prompt: "- Month -",
attributeBindings: ['name'],
name: Ember.computed(function(){
return this.getPath('parentView').get('name') + '_month';
}),
content: Ember.computed(function(){
var months = Ember.A(["January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December"]);
return Ember.A(months.map(function(month, index){
return {id: (index + ''), name: month};
}));
}).cacheable()
}),
yearView: Ember.Select.extend({
prompt: "- Year -",
attributeBindings: ['name'],
name: Ember.computed(function(){
return this.getPath('parentView').get('name') + '_year';
}),
content: Ember.computed(function(){
var years = [],
currentDate = new Date(),
currentYear = currentDate.getFullYear();
for(var i=1920; i<=currentYear; i++){
years.push(i + "");
}
return Ember.A(years);
}).cacheable()
})
});
EF.DateField = EF.BaseField.extend({
InputView: EF.DateComponent.extend({}),
value: Ember.computed(function(key, value){
if(arguments.length === 1){
return this.getPath('inputView.value');
}else{
this.setPath('inputView.value', value);
return value;
}
})
});
| JavaScript | 0.999315 | @@ -2164,17 +2164,8 @@
r i=
-1920; i%3C=
curr
@@ -2174,18 +2174,27 @@
tYear; i
-++
+%3E=1920; i--
)%7B%0A
|
137bc5d46f3bec6597c382d14f0a0729e3323122 | Use a class name for date fields | packages/ember-forms/lib/fields/date.js | packages/ember-forms/lib/fields/date.js | require("ember-forms/fields/base");
require("ember-forms/controls/unbound_select");
var e = Ember.empty;
EF.DateComponent = Ember.ContainerView.extend({
childViews: ['dayView', 'monthView', 'yearView'],
tagName: 'span',
value: Ember.computed(function(key, value){
var day, month, year;
if (arguments.length === 1){
day = this.getPath('dayView.value');
month = this.getPath('monthView.value');
year = this.getPath('yearView.value');
if(!e(day) && !e(month) && !e(year)){
return new Date(year, month, day, 12, 0, 0);
}
}else if(value){
day = value.getUTCDate() + '';
month = value.getUTCMonth() + '';
year = value.getUTCFullYear() + '';
this.setPath('dayView.value', day);
this.setPath('monthView.value', month);
this.setPath('yearView.value', year);
}
return value;
}).volatile(),
dayView: EF.UnboundSelect.extend({
attributeBindings: ['name'],
name: Ember.computed(function(){
return this.getPath('parentView').get('name') + '_day';
}),
prompt: "- Day -",
content: Ember.computed(function(){
var days = [];
for(var i=1; i<=31; i++){
days.push(i + '');
}
return Ember.A(days);
}).cacheable()
}),
monthView: EF.UnboundSelect.extend({
prompt: "- Month -",
attributeBindings: ['name'],
name: Ember.computed(function(){
return this.getPath('parentView').get('name') + '_month';
}),
content: Ember.computed(function(){
var months = Ember.A(["January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December"]);
return months.map(function(month, index){
return {value: (index + ''), label: month};
});
}).cacheable()
}),
yearView: EF.UnboundSelect.extend({
prompt: "- Year -",
attributeBindings: ['name'],
name: Ember.computed(function(){
return this.getPath('parentView').get('name') + '_year';
}),
content: Ember.computed(function(){
var years = [],
currentDate = new Date(),
currentYear = currentDate.getFullYear();
for(var i=currentYear; i>=1920; i--){
years.push(i + "");
}
return Ember.A(years);
}).cacheable()
})
});
EF.DateField = EF.BaseField.extend({
InputView: EF.DateComponent.extend({}),
value: Ember.computed(function(key, value){
if(arguments.length === 1){
return this.getPath('inputView.value');
}else{
this.setPath('inputView.value', value);
return value;
}
})
});
| JavaScript | 0.000007 | @@ -218,16 +218,40 @@
'span',
+%0A classNames: %5B'date'%5D,
%0A%0A valu
|
261e3a887db6f62d178d52d51e8ae7b9db062353 | Move shuttle paths to qa | app/AppSettings.js | app/AppSettings.js | module.exports = {
/* APP CONFIG */
APP_NAME: 'Campus Mobile',
GOOGLE_ANALYTICS_ID: 'GOOGLE_ANALYTICS_ID_PH',
/* ENDPOINTS */
/* QA */
AUTH_SERVICE_API_URL: 'https://3hepzvdimd.execute-api.us-west-2.amazonaws.com/dev/v1/access-profile',
ACADEMIC_TERM_API_URL: 'https://m9zc9vs4f1.execute-api.us-west-2.amazonaws.com/dev/v1/term/current',
ACADEMIC_TERM_FINALS_API_URL: 'https://m9zc9vs4f1.execute-api.us-west-2.amazonaws.com/dev/v1/term/current/finals',
ACADEMIC_HISTORY_API_URL: 'https://api-qa.ucsd.edu:8243/student/my/academic_history/v1/class_list',
TOPICS_API_URL: 'https://bvgjvzaakl.execute-api.us-west-2.amazonaws.com/dev/topics',
MYMESSAGES_API_URL: 'https://api-qa.ucsd.edu:8243/mp-mymessages/1.0.0',
MP_REGISTRATION_API_URL: 'https://api-qa.ucsd.edu:8243/mp-registration/1.0.0',
MESSAGES_TOPICS_URL: 'https://s3-us-west-1.amazonaws.com/ucsd-mobile-dev/mock-apis/messaging/topics.json',
/* PROD */
// SHUTTLE
SHUTTLE_STOPS_API_URL: 'https://ies4wyrlx9.execute-api.us-west-2.amazonaws.com/prod/v2/stops/',
/* DEV ROUTE, REMOVE BEFORE DEPLOYING! */
SHUTTLE_PATHS_URL: 'https://11wl1gc3v9.execute-api.us-west-2.amazonaws.com/dev/polylines/',
SHUTTLE_VEHICLES_API_URL: 'https://hjr84cay81.execute-api.us-west-2.amazonaws.com/prod?route=',
SHUTTLE_ROUTES_MASTER: 'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/shuttle_routes_master_map.json',
SHUTTLE_STOPS_MASTER: 'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/shuttle_stops_master_map.json',
SHUTTLE_STOPS_MASTER_NO_ROUTES: 'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/shuttle_stops_master_map_no_routes.json',
// GENERAL
NEWS_API_URL: 'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/allstories.json',
EVENTS_API_URL: 'https://2jjml3hf27.execute-api.us-west-2.amazonaws.com/prod/events/student',
SPECIAL_EVENT_API_URL: 'https://2jjml3hf27.execute-api.us-west-2.amazonaws.com/prod/events/special',
WEATHER_API_URL: 'https://w3wyps9yje.execute-api.us-west-2.amazonaws.com/prod/forecast?',
SURF_API_URL: 'https://kusyfng6mg.execute-api.us-west-2.amazonaws.com/prod/v1/surf',
DINING_API_URL: 'https://pg83tslbyi.execute-api.us-west-2.amazonaws.com/prod/v3/dining',
MAP_SEARCH_API_URL: 'https://xgu9qa7gx4.execute-api.us-west-2.amazonaws.com/prod/v2/map/search?region=0&query=',
FEEDBACK_URL: 'https://eforms.ucsd.edu/view.php?id=175631',
QUICKLINKS_API_URL: 'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/quick_links/ucsd-quicklinks-v3.json',
PARKING_API_URL: 'https://b2waxbcovi.execute-api.us-west-2.amazonaws.com/prod/parking/v1.0/status',
/* RESOURCES */
WEATHER_ICON_BASE_URL: 'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/images/v1/weather-icons/',
/* LINKS */
SHUTTLE_SCHEDULE_URL: 'https://transportation.ucsd.edu/shuttles/',
PRIVACY_POLICY_URL: 'https://mobile.ucsd.edu/privacy-policy.html',
ACCOUNT_HELP_URL: 'https://acms.ucsd.edu/students/accounts-and-passwords/index.html',
/* TTLs */
LOCATION_TTL: 5000, // 5 seconds
SHUTTLE_API_TTL: 15000, // 15 seconds
DATA_SAGA_TTL: 60000, // 1 minute
SCHEDULE_TTL: 300000, // 5 minutes
PARKING_API_TTL: 300000, // 5 minutes
WEATHER_API_TTL: 1800000, // 30 minutes
SURF_API_TTL: 1800000, // 30 minutes
SPECIAL_EVENTS_TTL: 1800000, // 30 minutes
EVENTS_API_TTL: 3600000, // 1 hour
NEWS_API_TTL: 3600000, // 1 hour
DINING_API_TTL: 3600000, // 1 hour
DINING_MENU_API_TTL: 3600000, // 1 hour
SHUTTLE_MASTER_TTL: 3600000, // 1 hour
USER_PROFILE_SYNC_TTL: 3600000, // 1 hour
QUICKLINKS_API_TTL: 86400000, // 1 day
/* TIMEOUTS */
HTTP_REQUEST_TTL: 15000, // 15 seconds
SSO_TTL: 15000, // 15 seconds
MESSAGING_TTL: 15000, // 15 seconds
/* RETRIES */
SSO_IDP_ERROR_RETRY_INCREMENT: 10000, // 10 seconds
SSO_REFRESH_MAX_RETRIES: 3,
SSO_REFRESH_RETRY_INCREMENT: 5000, // 5 seconds
SSO_REFRESH_RETRY_MULTIPLIER: 3, // Multiplies increment by this amount for next try
}
| JavaScript | 0.000008 | @@ -904,16 +904,110 @@
.json',%0A
+%09SHUTTLE_PATHS_URL: 'https://11wl1gc3v9.execute-api.us-west-2.amazonaws.com/dev/polylines/',%0A%0A
%09/* PROD
@@ -1123,146 +1123,8 @@
/',%0A
-%0A%09/* DEV ROUTE, REMOVE BEFORE DEPLOYING! */%0A%09SHUTTLE_PATHS_URL: 'https://11wl1gc3v9.execute-api.us-west-2.amazonaws.com/dev/polylines/',%0A%0A
%09SHU
|
718565ac4dbdf4b8187ee17f9dd12ff4e047fc0a | Remove waypoint library from AppbaseList | app/AppbaseList.js | app/AppbaseList.js | import { default as React, Component } from 'react';
import { render } from 'react-dom';
var Appbase = require('appbase-js');
var helper = require('./helper.js');
import {List} from './component/List.js';
var Waypoint = require('react-waypoint');
var {EventEmitter} = require('fbemitter');
var emitter = new EventEmitter();
export class AppbaseList extends Component {
constructor(props) {
super(props);
this.state = {
items: {},
selectedItems: {},
streamingStatus: 'Intializing..',
query: {}
};
this.appbaseRef = helper.getAppbaseRef(this.props.config);
this.streamingInstance;
this.pageNumber = 0;
emitter.addListener('change', function(query) {
this.setState({
query: query
});
});
this.handleSelect = this.handleSelect.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
subscribeToUpdates() {
var requestObject = helper.getMatchAllQuery(this.props.config, this.props.fieldName, 1, this.props.size, true);
var self = this;
self.setState({
streamingStatus: 'Listening...'
});
if (this.streamingInstance) {
this.streamingInstance.stop();
}
this.streamingInstance = this.appbaseRef.searchStream(requestObject).on('data', function (stream) {
var updated = self.state.items;
updated[stream._id] = eval(`stream._source.${self.props.fieldName}`);
self.setState({
items: updated
});
}).on('error', function (error) {
console.log(error);
});
}
getItems(pageNumber) {
var requestObject = helper.getMatchAllQuery(this.props.config, this.props.fieldName, pageNumber, this.props.size, false);
var self = this;
this.appbaseRef.search(requestObject).on('data', function (data) {
self.addItemsToList(data.hits.hits);
self.subscribeToUpdates();
}).on('error', function (error) {
console.log(error)
});
}
addItemsToList(newItems) {
var updated = this.state.items;
var self = this;
newItems.map(function (item) {
updated[item._id] = eval(`item._source.${self.props.fieldName}`);
});
this.setState({ items: updated });
}
handleWaypointEnter() {
this.getItems(this.pageNumber);
this.pageNumber++;
}
handleSelect(_id, value){
value = value.toString()
console.log(value)
console.log(queryObject.addShouldClause(this.props.fieldName, value));
}
handleRemove(_id, value){
queryObject.removeShouldClause(this.props.fieldName, value);
}
render() {
return (
<div>
<List items={this.state.items} onSelect={this.handleSelect} onRemove={this.handleRemove} onPageEnd={this.handleWaypointEnter.bind(this)} />
</div>
);
}
}
AppbaseList.defaultProps = {
size: 60,
}; | JavaScript | 0.000001 | @@ -202,51 +202,8 @@
s';%0A
-var Waypoint = require('react-waypoint');%0A%0A
var
|
3d6b42503fef082bf4532cdd7f5c7b0bc7a6f1ad | Add support for custom deserialization | src/lib/buslib/lib/bus.js | src/lib/buslib/lib/bus.js | "use strict";
const amqp = require("amqplib");
const { AsyncEventEmitter } = require("emitter");
const { synchronize } = require("misc");
class Bus extends AsyncEventEmitter {
constructor(synchronized = false) {
super();
this.config = {};
this.connection = null;
this.channel = null;
if (synchronized) {
synchronize(this, "_handleMessage");
}
}
async start(config) {
this.config = config;
if (!this.config.testMode) {
this.connection = await amqp.connect(this.config.uri);
this.channel = await this.connection.createChannel();
this.channel.on("close", () => {
this.emit("close", `Channel closed: ${this.config.uri}`);
});
this.channel.on("error", (error) => {
this.emit("error", error);
});
}
await this.emit("connect", this.config.uri);
return this.config.uri;
}
async assertExchange(name, durable = true) {
if (!this.config.testMode) {
if (!this.channel) {
throw new Error("Bus must be connected before assertExchange");
}
await this.channel.assertExchange(name, "topic", { durable });
}
await this.emit("exchange", name);
return name;
}
async assertQueue(exchange, name, durable = true, exclusive = true, routingKey = "") {
if (!this.config.testMode) {
if (!this.channel) {
throw new Error("Bus must be connected before assertExchange");
}
const queueRef = await this.channel.assertQueue(name, { exclusive, durable, autoDelete: !durable });
const queue = await this.channel.bindQueue(queueRef.queue, exchange, routingKey);
this.channel.consume(queue.queue, (msg) => {
this._handleMessage(name, msg)
.catch((error) => {
this.emit("error", error);
});
});
}
await this.emit("queue", name);
return name;
}
async deleteQueue(name) {
if (!this.config.testMode) {
if (!this.channel) {
throw new Error("Bus must be connected before assertExchange");
}
await this.channel.deleteQueue(name);
}
}
async _handleMessage(queue, msg) {
let content = msg.content;
if (msg.properties.contentType === "application/json") {
content = JSON.parse(content.toString());
}
await this.emit("data", content);
await this.emit(`data.${queue}`, content);
if (!this.config.testMode) {
this.channel.ack(msg);
}
}
async publish(exchange, data, routingKey = "", timeout = 0) {
if (!this.config.testMode) {
if (!this.channel) {
throw new Error("Bus must be connected before assertExchange");
}
const opts = {
contentType: "application/json"
};
if (timeout) {
opts.expiration = timeout.toString();
}
const content = new Buffer(JSON.stringify(data));
if (!this.channel.publish(exchange, routingKey, content, opts)) {
throw new Error("Channel publish failed, the channel's write buffer is full!");
}
}
await this.emit("publish", data);
}
async dispose() {
if (this.channel) {
await this.channel.close();
this.channel = null;
}
if (this.connection) {
await this.connection.close();
this.connection = null;
}
await this.emit("disconnect");
this.removeAllListeners();
}
}
module.exports = Bus;
| JavaScript | 0 | @@ -1033,16 +1033,32 @@
e = true
+, type = %22topic%22
) %7B%0A
@@ -1270,23 +1270,20 @@
e(name,
-%22topic%22
+type
, %7B dura
@@ -1594,39 +1594,36 @@
ed before assert
-Exchang
+Queu
e%22);%0A
@@ -2407,36 +2407,31 @@
-async _handleMessage(queue,
+_deserializeMsgContent(
msg)
@@ -2468,24 +2468,163 @@
ontent;%0A
-%0A
+ if (typeof this.config.deserializeMsgContent === %22function%22) %7B%0A content = this.config.deserializeMsgContent(msg);%0A %7D else
if (msg
@@ -2706,16 +2706,20 @@
N.parse(
+msg.
content.
@@ -2734,32 +2734,161 @@
());%0A %7D%0A%0A
+ return content;%0A %7D%0A%0A async _handleMessage(queue, msg) %7B%0A const content = this._deserializeMsgContent(msg);%0A%0A
await th
|
b2447b126aa111c3214b216d470cbf9cc0cf1eef | test fixes (#2532) | test/server/cards/05-UotE/PeasantsAdvice.spec.js | test/server/cards/05-UotE/PeasantsAdvice.spec.js | fdescribe('Peasant\'s Advice', function() {
integration(function() {
describe('Peasant\'s Advice\'s ability', function() {
beforeEach(function() {
this.setupTest({
phase: 'conflict',
player1: {
inPlay: ['seppun-guardsman'],
hand: ['peasant-s-advice']
},
player2: {
dynastyDiscard: ['shiba-tsukune']
}
});
this.shamefulDisplay = this.player2.findCardByName('shameful-display', 'province 1');
this.shibaTsukune = this.player2.placeCardInProvince('shiba-tsukune', 'province 1');
});
it('should dishonor the character chosen as a cost', function() {
this.player1.clickCard('peasant-s-advice');
this.player1.clickPrompt('Pay Costs First');
this.seppunGuardsman = this.player1.clickCard('seppun-guardsman');
expect(this.seppunGuardsman.isDishonored).toBe(true);
});
it('should display a text message about a provice with a facedown card in it', function() {
this.shibaTsukune.facedown = true;
this.player1.clickCard('peasant-s-advice');
this.player1.clickCard(this.shamefulDisplay);
this.seppunGuardsman = this.player1.clickCard('seppun-guardsman');
expect(this.player2).toHavePrompt('Action Window');
expect(this.getChatLogs(5)).toContain('Peasant\'s Advice sees Shameful Display');
});
it('should offer the option to shuffle a faceup card in a faceup province', function() {
this.shamefulDisplay.facedown = false;
this.player1.clickCard('peasant-s-advice');
this.player1.clickCard(this.shamefulDisplay);
this.seppunGuardsman = this.player1.clickCard('seppun-guardsman');
expect(this.player1).toHavePrompt('Choose a card to return to owner\'s deck');
expect(this.player1).toHavePromptButton('Shiba Tsukune');
expect(this.player1).toHavePromptButton('Done');
this.player1.clickPrompt('Done');
expect(this.player2).toHavePrompt('Action Window');
expect(this.getChatLogs(5)).not.toContain('Peasant\'s Advice sees Shameful Display');
expect(this.shibaTsukune.location).toBe('province 1');
});
it('should both display a text message and offer the option to shuffle a faceup card in a facedown province', function() {
this.player1.clickCard('peasant-s-advice');
this.player1.clickCard(this.shamefulDisplay);
this.seppunGuardsman = this.player1.clickCard('seppun-guardsman');
expect(this.getChatLogs(5)).toContain('Peasant\'s Advice sees Shameful Display');
expect(this.player1).toHavePrompt('Choose a card to return to owner\'s deck');
expect(this.player1).toHavePromptButton('Shiba Tsukune');
expect(this.player1).toHavePromptButton('Done');
this.player1.clickPrompt('Shiba Tsukune');
expect(this.player2).toHavePrompt('Action Window');
expect(this.getChatLogs(5)).toContain('Peasant\'s Advice sees Shameful Display');
expect(this.shibaTsukune.location).toBe('dynasty deck');
expect(this.player2.player.getDynastyCardInProvince('province 1')).not.toBeUndefined();
});
it('should not allow shuffling a stronghold', function() {
this.strongholdProvince = this.player2.findCardByName('shameful-display', 'stronghold province');
this.player1.clickCard('peasant-s-advice');
this.player1.clickCard(this.strongholdProvince);
this.seppunGuardsman = this.player1.clickCard('seppun-guardsman');
expect(this.player2).toHavePrompt('Action Window');
expect(this.getChatLogs(5)).toContain('Peasant\'s Advice sees Shameful Display');
});
it('should not be allowed to target a faceup province with a facedown card in it', function() {
this.shamefulDisplay.facedown = false;
this.shibaTsukune.facedown = true;
this.player1.clickCard('peasant-s-advice');
expect(this.player1).toHavePrompt('Peasant\'s Advice');
expect(this.player1).not.toBeAbleToSelect(this.shamefulDisplay);
});
});
});
});
| JavaScript | 0 | @@ -2811,32 +2811,117 @@
amefulDisplay);%0A
+ this.spy = spyOn(this.player2.player, 'moveCard').and.callThrough();%0A
@@ -3577,49 +3577,85 @@
is.s
-hibaTsukune.location).toBe('dynasty deck'
+py).toHaveBeenCalledWith(this.shibaTsukune, 'dynasty deck', %7B bottom: false %7D
);%0A
|
2ef5a2ba6f7bb9b897f109986f7c1868d0d39bc4 | Add bounding volume to Advanced example in the Sandbox. | Examples/Sandbox/CodeSnippets/Advanced.js | Examples/Sandbox/CodeSnippets/Advanced.js | (function() {
"use strict";
/*global Cesium,Sandbox*/
Sandbox.CustomRendering = function (scene, ellipsoid, primitives) {
this.code = function () {
Sandbox.ExamplePrimitive = function(position) {
var ellipsoid = Cesium.Ellipsoid.WGS84;
this._ellipsoid = ellipsoid;
this._va = undefined;
this._sp = undefined;
this._rs = undefined;
this._pickId = undefined;
this.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
var that = this;
this._drawUniforms = {
u_model : function() { return that.modelMatrix; },
u_color : function() { return { red : 0.0, green : 1.0, blue : 0.0, alpha : 1.0 }; }
};
this._pickUniforms = {
u_model : function() { return that.modelMatrix; },
u_color : function() { return that._pickId.normalizedRgba; }
};
};
Sandbox.ExamplePrimitive.prototype.update = function(context, sceneState) {
var vs = '';
vs += 'attribute vec4 position;';
vs += 'void main()';
vs += '{';
vs += ' gl_Position = agi_modelViewProjection * position;';
vs += '}';
var fs = '';
fs += 'uniform vec4 u_color;';
fs += 'void main()';
fs += '{';
fs += ' gl_FragColor = u_color;';
fs += '}';
var zLength = this._ellipsoid.getRadii().getMaximumComponent() * 0.1;
var mesh = Cesium.MeshFilters.toWireframeInPlace(
Cesium.BoxTessellator.compute({
dimensions : new Cesium.Cartesian3(zLength * 0.1, zLength * 0.5, zLength)
}));
var attributeIndices = Cesium.MeshFilters.createAttributeIndices(mesh);
this._va = context.createVertexArrayFromMesh({
mesh : mesh,
attributeIndices : attributeIndices,
bufferUsage : Cesium.BufferUsage.STATIC_DRAW
});
this._sp = context.getShaderCache().getShaderProgram(vs, fs, attributeIndices);
this._rs = context.createRenderState({
depthTest : {
enabled : true
}
});
this.update = function() {};
};
Sandbox.ExamplePrimitive.prototype.render = function(context) {
context.draw({
primitiveType : Cesium.PrimitiveType.LINES,
shaderProgram : this._sp,
uniformMap : this._drawUniforms,
vertexArray : this._va,
renderState : this._rs
});
};
Sandbox.ExamplePrimitive.prototype.updateForPick = function(context) {
this._pickId = this._pickId || context.createPickId(this);
this.updateForPick = function() {};
};
Sandbox.ExamplePrimitive.prototype.renderForPick = function(context, framebuffer) {
context.draw({
primitiveType : Cesium.PrimitiveType.LINES,
shaderProgram : this._sp,
uniformMap : this._pickUniforms,
vertexArray : this._va,
renderState : this._rs,
framebuffer : framebuffer
});
};
Sandbox.ExamplePrimitive.prototype.isDestroyed = function() {
return false;
};
Sandbox.ExamplePrimitive.prototype.destroy = function () {
this._va = this._va && this._va.destroy();
this._sp = this._sp && this._sp.release();
this._pickId = this._pickId && this._pickId.destroy();
return Cesium.destroyObject(this);
};
primitives.add(new Sandbox.ExamplePrimitive(ellipsoid.cartographicToCartesian(Cesium.Cartographic.fromDegrees(-75.59777, 40.03883))));
};
this.clear = function () {
delete Sandbox.ExamplePrimitive;
};
};
}());
| JavaScript | 0 | @@ -481,16 +481,67 @@
fined;%0A%0A
+ this._boundingVolume = undefined;%0A%0A
@@ -620,16 +620,16 @@
ition);%0A
-
%0A
@@ -1758,16 +1758,390 @@
* 0.1;%0A
+ var x = zLength * 0.1;%0A var y = zLength * 0.5;%0A var z = zLength;%0A%0A this._boundingVolume = Cesium.BoundingSphere.fromPoints(%5B%0A new Cesium.Cartesian3(x, 0.0, 0.0),%0A new Cesium.Cartesian3(0.0, y, 0.0),%0A new Cesium.Cartesian3(0.0, 0.0, z)%0A %5D);%0A%0A
@@ -2334,45 +2334,15 @@
an3(
-zLength * 0.1, zLength * 0.5, zLength
+x, y, z
)%0A
@@ -3019,28 +3019,345 @@
pdate =
-function() %7B
+this._update;%0A return this._update(context, sceneState);%0A %7D;%0A%0A Sandbox.ExamplePrimitive.prototype._update = function(context, sceneState) %7B%0A return %7B%0A boundingVolume : this._boundingVolume,%0A modelMatrix : this._modelMatrix%0A
%7D;%0A
|
2606e26cfb5c9e6e1ec24432c19188f9e07da5d5 | Use the new rouotes in the app | config/routes.js | config/routes.js | 'use strict'
module.exports.mount = app => {
const routes = require('../routes')
const authRoutes = require('../routes/auth')
app.use('/', routes)
app.use('/auth', authRoutes)
}
| JavaScript | 0 | @@ -87,92 +87,200 @@
nst
-authRoutes = require('../routes/auth')%0A%0A%09app.use('/', routes)%0A%09app.use('/auth', auth
+%7B%0A%09%09loginRoutes,%0A%09%09registerRoutes,%0A%09%09secretRoutes%0A%09%7D = require('../api/indexRoutes')%0A%0A%09app.use('/secret', secretRoutes)%0A%09app.use('/auth/login', loginRoutes)%0A%09app.use('/auth/register', register
Rout
|
985734eeb5f7af593f97baa5820409379e5a48e1 | add the bet routes | config/routes.js | config/routes.js | /**
* Route Mappings
* (sails.config.routes)
*
* Your routes map URLs to views and controllers.
*
* If Sails receives a URL that doesn't match any of the routes below,
* it will check for matching files (images, scripts, stylesheets, etc.)
* in your assets directory. e.g. `http://localhost:1337/images/foo.jpg`
* might match an image file: `/assets/images/foo.jpg`
*
* Finally, if those don't match either, the default 404 handler is triggered.
* See `api/responses/notFound.js` to adjust your app's 404 logic.
*
* Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
* flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or
* CoffeeScript for the front-end.
*
* For more information on configuring custom routes, check out:
* http://sailsjs.org/#/documentation/concepts/Routes/RouteTargetSyntax.html
*/
module.exports.routes = {
/***************************************************************************
* *
* Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, *
* etc. depending on your default view engine) your home page. *
* *
* (Alternatively, remove this and add an `index.html` file in your *
* `assets` directory) *
* *
***************************************************************************/
'GET /': {
view: 'homepage'
},
'GET /teams': 'TeamController.boFind',
'GET /teams/new': 'TeamController.boNew',
'GET /teams/:id': 'TeamController.boFindOne',
'GET /matches': 'MatchController.boFind',
'GET /matches/new': 'MatchController.boNew',
'GET /matches/:id': 'MatchController.boFindOne',
'GET /users': 'UserController.boFind',
'GET /users/new': 'UserController.boNew',
'GET /users/:id': 'UserController.boFindOne'
/***************************************************************************
* *
* Custom routes here... *
* *
* If a request to a URL doesn't match any of the custom routes above, it *
* is matched against Sails route blueprints. See `config/blueprints.js` *
* for configuration options and examples. *
* *
***************************************************************************/
};
| JavaScript | 0.000001 | @@ -2088,16 +2088,144 @@
FindOne'
+,%0A%0A 'GET /bets': 'BetController.boFind',%0A 'GET /bets/new': 'BetController.boNew',%0A 'GET /bets/:id': 'BetController.boFindOne'
%0A%0A /***
|
6a211ca900973bf3d96f3ad8f9bc4da25eaf3a06 | Update android.js | app/app/android.js | app/app/android.js | if (window.innerWidth && window.innerWidth <= 600) {
$(document).ready(function(){
$('#header ul').addClass('hide');
$('#header').append('<div class="leftButton" onclick="toggleMenu()">Menu</div>');
});
function toggleMenu() {
$('#header ul').toggleClass('hide');
$('#header .leftButton').toggleClass('pressed');
}
}
| JavaScript | 0.000002 | @@ -186,27 +186,26 @@
nclick=%22
-toggleMenu(
+about.html
)%22%3EMenu%3C
|
29c2bb8364da29389120c1f93db847a2baa52721 | fix border radius | libs/views/tabs.js | libs/views/tabs.js | module.exports=require('base/view').extend({
name:'Tabs',
overflow:'none',
props:{
isTop:true
},
onIsTop:function(){
if(this.isTop){
this.padding = [26,0,0,0]
}
else{
this.padding = [0,0,26,0]
}
},
isTop:true,
tools:{
Tab:require('tools/tab').extend({
onTabSelected:function(e){
this.view._tabSelected(this.index, e)
},
onTabSlide:function(e){
this.view._tabSlide(this, e)
},
onTabReleased:function(e){
this.view._tabReleased()
}
}),
Background:require('tools/bg').extend({
color:'#2',
wrap:false,
}),
CloseButton:require('tools/button').extend({
x:'@1',
icon:'close',
Bg:{
margin:[2,0,0,0],
color:'#3',
padding:[4,0,0,8]
},
w:26,
h:23,
onClick:function(e){
this.view.closeTab(this.view.selectedIndex)
}
}),
FlipButton:require('tools/button').extend({
x:'@1',
Bg:{
margin:[2,0,0,0],
color:'#9',
padding:[4,0,0,7]
},
w:26,
h:23,
onClick:function(e){
this.view.isTop = !this.view.isTop
}
})
},
fontSize:11,
_tabSelected:function(index, e){
// deselect the other tab
this.selectTab(index)
this.slidePos = undefined
this.defSliding = false
this.selSliding = false
this.slideDelta = e.x
this.slideStartY = e.yAbs
},
_tabSlide:function(tabStamp, e){
if(this.children[tabStamp.index].noDragTab || this.slideStartY === undefined) return
var ts = tabStamp.stampGeom()
var xWant = e.xView - this.slideDelta
this.slidePos = clamp(xWant,0,this.$w-ts.w)
this.defSliding = true
// lets check if the y position is too far from the tab
var dy = abs(this.slideStartY - e.yAbs)
var dx = abs(this.slidePos - xWant)
if((dx > 30 || dy > 30) && this.onTabRip){
this.slideStartY = undefined
this.slidePos = NaN
this.defSliding = true
this.selSliding = true
this.slidePos
var index = tabStamp.index
var child = this.children.splice(index, 1)[0]
if(this.selectedIndex === index){
var next = clamp(index, 0, this.children.length -1)
this.selectedIndex = -1
this.selectTab(next)
}
child.oldTabs = this
this.onTabRip(child, e)
return
}
// lets see where we belong
var set = this.children
// remove old one
item = set.splice(tabStamp.index, 1)[0]
// find insertion point
//console.log(ts.x)
//var x = tabStamp.x
var ins = tabStamp.index
for(var i = 0; i < set.length; i++){
var stamp = set[i].tabStamp
var geom = stamp.stampGeom()
if(ts.x > geom.x) ins = i + 1 // insertion point
}
// insert it again, switching our stampId
if(ins > tabStamp.index){
this.view.transferFingerMove(e.digit,set[ins-1].tabStamp.$stampId)
}
else if(ins < tabStamp.index){
this.view.transferFingerMove(e.digit,set[ins].tabStamp.$stampId)
}
set.splice(ins, 0, item)
this.selectedIndex = ins
this.redraw()
},
_tabReleased:function(){
this.slidePos = NaN
this.defSliding = false
this.selSliding = true
},
closeTab:function(index){
if(this.onCloseTab(index)){
return
}
this.removeChild(index)
if(this.selectedIndex === index){
var next = clamp(index, 0, this.children.length -1)
this.selectedIndex = -1
this.selectTab(next)
}
},
selectTab:function(index){
if(this.selectedIndex !== index){
this.selectedIndex = index
for(var i = 0; i < this.children.length; i++){
var child = this.children[i]
if(child) child.visible = i === index?true:false
}
this.onSelectTab(index)
this.redraw()
}
},
onSelectTab:function(index){
},
onCloseTab:function(index){
},
toggleTabSettings:function(show){
this.showTabSettings = show
this.redraw()
},
onDraw:function(){
if(this.isTop){
this.beginBackground({
align:[0.,0.],
padding:[0,0,0,0],
w:this.$w,
y:0,
h:26,
})
}
else{
this.beginBackground({
align:[0.,1.],
padding:[0,0,0,0],
w:this.$w,
y:this.$h-26,
h:26,
})
}
// make sure our normale tab happens first
this.orderTab({})
for(var i = 0, len = this.children.length; i < len; i++){
var child = this.children[i]
if(!child.tabText && !child.tabIcon) continue
var isSel = i === this.selectedIndex
child.tabStamp = this.drawTab({
$layer:isSel?1:undefined,
x:isSel?this.slidePos:NaN,
Bg:{
borderRadius:this.isTop?[6,6,1,1]:[1,1,6,6]
},
index:i,
state:isSel?
(this.selSliding?'selected_slide':'selected_over'):
(this.defSliding?'slide':'default'),
icon:child.tabIcon,
canClose:false,//child.tabCanClose,
text:child.tabText
})
}
// lets draw the close button for the current tab
var clen = this.children.length
if(!this.children[this.selectedIndex].noCloseTab){
this.drawCloseButton({
})
}
if(this.showTabSettings){
this.drawFlipButton({
icon:this.isTop?'arrow-down':'arrow-up'
})
}
this.endBackground()
this.defSliding = false
this.selSliding = false
}
}) | JavaScript | 0.000002 | @@ -4317,17 +4317,17 @@
6,6,
-1,1%5D:%5B1,1
+2,2%5D:%5B2,2
,6,6
|
89fdbddb50a3fc0233afbef5db6b5c2534b4f96e | Update feedvalue_render.js | Views/js/widgets/feedvalue/feedvalue_render.js | Views/js/widgets/feedvalue/feedvalue_render.js | /*
All emon_widgets code is released under the GNU General Public License v3.
See COPYRIGHT.txt and LICENSE.txt.
---------------------------------------------------------------------
Part of the OpenEnergyMonitor project:
http://openenergymonitor.org
Author: Trystan Lea: trystan.lea@googlemail.com
If you have any questions please get in touch, try the forums here:
http://openenergymonitor.org/emon/forum
*/
function feedvalue_widgetlist()
{
var widgets = {
"feedvalue":
{
"offsetx":-40,"offsety":-30,"width":80,"height":60,
"menu":"Widgets",
"options":["feedname","units","decimals"],
"optionstype":["feed","value","decimals"],
"optionsname":[_Tr("Feed"),_Tr("Units"),_Tr("Decimals")],
"optionshint":[_Tr("Feed value"),_Tr("Units to show"),_Tr("Decimals to show (-1 for automatic)")]
}
}
return widgets;
}
function feedvalue_init()
{
feedvalue_draw();
}
function feedvalue_draw()
{
$('.feedvalue').each(function(index)
{
var feed = $(this).attr("feedname");
if (feed==undefined) feed = $(this).attr("feed");
var units = $(this).attr("units");
var val = assoc[feed];
var decimals = $(this).attr("decimals");
if (feed==undefined) val = 0;
if (units==undefined) units = '';
if (val==undefined) val = 0;
if (decimals==undefined) decimals = -1;
if (isNaN(val)) val = 0;
if (decimals==<0)
{
if (val>=100)
val = (val*1).toFixed(0);
else if (val>=10)
val = (val*1).toFixed(1);
else if (val<=-100)
val = (val*1).toFixed(0);
else if (val<=-10)
val = (val*1).toFixed(1);
else
val = (val*1).toFixed(2);
}
else
{
val = val.toFixed(decimals);
}
$(this).html(val+units);
});
}
function feedvalue_slowupdate()
{
feedvalue_draw();
}
function feedvalue_fastupdate()
{
}
| JavaScript | 0.000001 | @@ -1426,18 +1426,16 @@
decimals
-==
%3C0)%0A
|
d7da1088064119838aeef1caa54295d97d08f8f8 | add more pseudo examples | src/pseudos.js | src/pseudos.js | !function () {
function children(node) {
var i, nodes = node.childNodes, r = [], l;
for (i = 0, l = nodes.length; i < l; i++) {
var item = nodes[i];
nodes[i].nodeType == 1 && r.push(nodes[i]);
}
return r;
}
qwery.pseudos['last-child'] = function (el, p, childs) {
return el.parentNode && (p = el.parentNode) && (childs = children(p)) && childs[childs.length - 1] == el;
};
qwery.pseudos['first-child'] = function (el, p) {
return el.parentNode && (p = el.parentNode) && (childs = children(p)) && childs[0] == el;
};
qwery.pseudos['nth-child'] = function (el, val, p) {
if (!val || !(p = el.parentNode)) return false;
var childs = children(p), i, l;
if (isFinite(val)) {
return childs[val - 1] == el;
} else if (val == 'odd') {
for (i = 0, l = childs.length;i < l; i = i + 2) {
if (el == childs[i]) return true;
}
} else if (val == 'even') {
for (i = 1, l = childs.length;i < l; i = i + 2) {
if (el == childs[i]) return true;
}
}
return false;
};
}();
| JavaScript | 0 | @@ -1067,13 +1067,311 @@
e;%0A %7D;%0A
+%0A qwery.pseudos.checked = function (el) %7B%0A return el.checked;%0A %7D;%0A%0A qwery.pseudos.enabled = function (el) %7B%0A return !el.disabled;%0A %7D;%0A%0A qwery.pseudos.disabled = function (el) %7B%0A return el.disabled;%0A %7D;%0A%0A qwery.pseudos.empty = function (el) %7B%0A return !el.childNodes.length;%0A %7D;%0A%0A
%7D();%0A
|
4352ffe54bdf46f45a03d9676bbfe4eca1bcf1ca | Fix bad regex | src/publish.js | src/publish.js | const chalk = require('chalk');
const inquirer = require('inquirer');
const child = require('child_process');
const path = require('path');
const checkMissingFiles = require('./checkMissingFiles');
const fileExists = require('./fileExists');
/**
* Publishes a new gist via gistup. First verifies that all
* expected files exist. If the current directory is already a
* git repo, it informs the user to use git to update the block.
* If it is not a git repo, the user can enter a title for the block
* then gistup is used to publish it.
*/
module.exports = function publish() {
Promise.resolve()
.then(() => new Promise(interactiveCheckMissingFiles))
.then(() => new Promise(checkForGitRepo))
.then(() => new Promise(promptForBlockTitle))
.then(title => new Promise((resolve, reject) => gistup(title, resolve, reject)))
.catch((err) => {
if (err) {
console.log();
console.log(chalk.red(err));
}
console.log(chalk.dim('\nPublish was aborted.\n'));
});
}
/**
* Checks for missing files and gives user the option to abort if
* files are missing.
*/
function interactiveCheckMissingFiles(resolve, reject) {
const isMissingFiles = checkMissingFiles();
console.log();
if (isMissingFiles) {
const questions = [{
type: 'confirm',
name: 'publish',
message: 'Some expected files are missing. Proceed with publishing?',
default: false
}];
inquirer.prompt(questions).then(function (answers) {
if (answers.publish) {
console.log();
resolve();
} else {
reject();
}
});
} else {
resolve();
}
}
/**
* Check if the current directory is a git repo already and abort if so
*/
function checkForGitRepo(resolve, reject) {
// check if we are in a git repo
if (fileExists('.git')) {
console.log(chalk.yellow('This is already a git repo. Update your block with standard git commands.'));
reject();
} else {
resolve();
}
}
/**
* Ask the user to enter a title for the block
*/
function promptForBlockTitle(resolve, reject) {
const questions = [{
type: 'input',
name: 'title',
message: 'Block Title:',
}];
inquirer.prompt(questions).then(function (answers) {
const title = answers.title.trim();
resolve(title.length ? title : undefined);
});
}
/**
* Use gistup to publish the block with the specified title. If no title is provided,
* gistup does not set the `description` flag.
*/
function gistup(title, resolve, reject) {
const gistupPath = path.join(__dirname, '../node_modules/gistup/bin/gistup');
const gistupArgs = title ? `--description "${title}"` : '';
if (!title) {
console.log(chalk.dim('\nPublishing block with no title...\n'));
} else {
console.log(chalk.dim(`\nPublishing block "${title}"...\n`));
}
// run gistup with description arg if title is provided
child.exec(`${gistupPath} ${gistupArgs}`, function(error, stdout, stderr) {
if (error) {
reject(error);
}
if (stderr) {
process.stderr.write(stderr);
}
if (stdout) {
process.stdout.write(stdout);
}
// extract the hash from the standard error message and use it to create the blocks URL
const gistHash = stderr.match(/To git@gist.github.com:([a-z0-9]+).git/)[1]
if (gistHash) {
const blockUrl = `https://bl.ocks.org/${gistHash}`;
console.log(chalk.bold('\nBlock published! You can view it at', chalk.bold.blue(blockUrl)));
} else {
console.log(chalk.bold('\nBlock published!'));
}
console.log(chalk.dim('\nThis directory is now a git repository. To update your block, ' +
'use standard git commands.\n'));
resolve();
});
}
| JavaScript | 0.004475 | @@ -3125,23 +3125,21 @@
/To
-git@
gist
+%5C
.github
+%5C
.com
@@ -3150,16 +3150,17 @@
-z0-9%5D+)
+%5C
.git/)%5B1
|
30b0f454ca2df854e5a3a39ae13293649f2a9268 | Rename state files | src/defaults.js | src/defaults.js | 'use babel'
/* @flow */
import {Template} from 'string-templates'
export const CONFIG_FILE_NAME: string = '.ucompilerrc'
export const DEFAULT_IGNORED: Array<string> = [
'node_modules',
'bower_components',
'coverage',
't{e,}mp',
'*.min.js',
'*.log',
'bundle.js',
'fixture{-*,}.{js,jsx}',
'spec',
'test{s, }',
'fixture{s, }',
'vendor',
'dist',
'*___jb_old___',
'*___jb_bak___',
'*.dist.*'
]
export const template = Template.create()
| JavaScript | 0 | @@ -117,10 +117,66 @@
iler
-rc
+'%0Aexport const STATE_FILE_NAME: string = '.ucompiler.state
'%0A%0Ae
|
ddeda5d4d6ab7bf50e2d92892de8647cf5f9e63f | Rename variable | src/devTools.js | src/devTools.js | const ActionTypes = {
PERFORM_ACTION: 'PERFORM_ACTION',
RESET: 'RESET',
ROLLBACK: 'ROLLBACK',
COMMIT: 'COMMIT',
SWEEP: 'SWEEP',
TOGGLE_ACTION: 'TOGGLE_ACTION',
JUMP_TO_STATE: 'JUMP_TO_STATE',
RECOMPUTE_STATES: 'RECOMPUTE_STATES'
};
const INIT_ACTION = {
type: '@@INIT'
};
function toggle(obj, key) {
const clone = { ...obj };
if (clone[key]) {
delete clone[key];
} else {
clone[key] = true;
}
return clone;
}
/**
* Computes the next entry in the log by applying an action.
*/
function computeNextEntry(reducer, action, state, error) {
if (error) {
return {
state,
error: 'Interrupted by an error up the chain'
};
}
let nextState = state;
let nextError;
try {
nextState = reducer(state, action);
} catch (err) {
nextError = err.toString();
console.error(err.stack || err);
}
return {
state: nextState,
error: nextError
};
}
/**
* Runs the reducer on all actions to get a fresh computation log.
* It's probably a good idea to do this only if the code has changed,
* but until we have some tests we'll just do it every time an action fires.
*/
function recomputeStates(reducer, committedState, stagedActions, skippedActions) {
const computedStates = [];
for (let i = 0; i < stagedActions.length; i++) {
const action = stagedActions[i];
const previousEntry = computedStates[i - 1];
const previousState = previousEntry ? previousEntry.state : committedState;
const previousError = previousEntry ? previousEntry.error : undefined;
const shouldSkip = Boolean(skippedActions[i]);
const entry = shouldSkip ?
previousEntry :
computeNextEntry(reducer, action, previousState, previousError);
computedStates.push(entry);
}
return computedStates;
}
/**
* Lifts the app state reducer into a DevTools state reducer.
*/
function liftReducer(reducer, monitorStateReducer, initialState) {
const initialLiftedState = {
committedState: initialState,
stagedActions: [INIT_ACTION],
skippedActions: {},
currentStateIndex: 0,
monitorState: monitorStateReducer(undefined, INIT_ACTION),
timestamps: [Date.now()]
};
/**
* Manages how the DevTools actions modify the DevTools state.
*/
return function liftedReducer(liftedState = initialLiftedState, liftedAction) {
let {
committedState,
stagedActions,
skippedActions,
computedStates,
currentStateIndex,
monitorState,
timestamps
} = liftedState;
switch (liftedAction.type) {
case ActionTypes.RESET:
committedState = initialState;
stagedActions = [INIT_ACTION];
skippedActions = {};
currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break;
case ActionTypes.COMMIT:
committedState = computedStates[currentStateIndex].state;
stagedActions = [INIT_ACTION];
skippedActions = {};
currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break;
case ActionTypes.ROLLBACK:
stagedActions = [INIT_ACTION];
skippedActions = {};
currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break;
case ActionTypes.TOGGLE_ACTION:
skippedActions = toggle(skippedActions, liftedAction.index);
break;
case ActionTypes.JUMP_TO_STATE:
currentStateIndex = liftedAction.index;
break;
case ActionTypes.SWEEP:
stagedActions = stagedActions.filter((_, i) => !skippedActions[i]);
timestamps = timestamps.filter((_, i) => !skippedActions[i]);
skippedActions = {};
currentStateIndex = Math.min(currentStateIndex, stagedActions.length - 1);
break;
case ActionTypes.PERFORM_ACTION:
if (currentStateIndex === stagedActions.length - 1) {
currentStateIndex++;
}
stagedActions = [...stagedActions, liftedAction.action];
timestamps = [...timestamps, liftedAction.timestamp];
break;
case ActionTypes.RECOMPUTE_STATES:
stagedActions = liftedAction.stagedActions;
timestamps = liftedAction.timestamps;
committedState = liftedAction.committedState;
currentStateIndex = stagedActions.length - 1;
skippedActions = {};
break;
default:
break;
}
computedStates = recomputeStates(
reducer,
committedState,
stagedActions,
skippedActions
);
monitorState = monitorStateReducer(monitorState, liftedAction);
return {
committedState,
stagedActions,
skippedActions,
computedStates,
currentStateIndex,
monitorState,
timestamps
};
};
}
/**
* Lifts an app action to a DevTools action.
*/
function liftAction(action) {
const liftedAction = {
type: ActionTypes.PERFORM_ACTION,
action,
timestamp: Date.now()
};
return liftedAction;
}
/**
* Unlifts the DevTools state to the app state.
*/
function unliftState(liftedState) {
const { computedStates, currentStateIndex } = liftedState;
const { state } = computedStates[currentStateIndex];
return state;
}
/**
* Unlifts the DevTools store to act like the app's store.
*/
function unliftStore(liftedStore, monitorStateReducer) {
let lastDefinedState;
return {
...liftedStore,
devToolsStore: liftedStore,
dispatch(action) {
liftedStore.dispatch(liftAction(action));
return action;
},
getState() {
const state = unliftState(liftedStore.getState());
if (state !== undefined) {
lastDefinedState = state;
}
return lastDefinedState;
},
replaceReducer(nextReducer) {
liftedStore.replaceReducer(liftReducer(nextReducer, monitorStateReducer));
}
};
}
/**
* Action creators to change the DevTools state.
*/
export const ActionCreators = {
reset() {
return { type: ActionTypes.RESET, timestamp: Date.now() };
},
rollback() {
return { type: ActionTypes.ROLLBACK, timestamp: Date.now() };
},
commit() {
return { type: ActionTypes.COMMIT, timestamp: Date.now() };
},
sweep() {
return { type: ActionTypes.SWEEP };
},
toggleAction(index) {
return { type: ActionTypes.TOGGLE_ACTION, index };
},
jumpToState(index) {
return { type: ActionTypes.JUMP_TO_STATE, index };
},
recomputeStates(committedState, stagedActions) {
return {
type: ActionTypes.RECOMPUTE_STATES,
committedState,
stagedActions
};
}
};
/**
* Redux DevTools middleware.
*/
export default function devTools(monitorStateReducer = () => undefined) {
return next => (reducer, initialState) => {
const liftedReducer = liftReducer(reducer, monitorStateReducer, initialState);
const liftedStore = next(liftedReducer);
const store = unliftStore(liftedStore, monitorStateReducer);
return store;
};
}
| JavaScript | 0.000003 | @@ -1887,37 +1887,32 @@
reducer, monitor
-State
Reducer, initial
@@ -2086,37 +2086,32 @@
orState: monitor
-State
Reducer(undefine
@@ -4406,29 +4406,24 @@
te = monitor
-State
Reducer(moni
@@ -5167,37 +5167,32 @@
edStore, monitor
-State
Reducer) %7B%0A let
@@ -5650,37 +5650,32 @@
Reducer, monitor
-State
Reducer));%0A %7D
@@ -6433,18 +6433,22 @@
ols
-middleware
+store enhancer
.%0A *
@@ -6485,29 +6485,24 @@
ools(monitor
-State
Reducer = ()
@@ -6614,29 +6614,24 @@
cer, monitor
-State
Reducer, ini
@@ -6737,21 +6737,16 @@
monitor
-State
Reducer)
|
da2ee5a4c46a362bd8a51aaedbf19488a2e7b2e1 | Fix clean function | src/commands/eval.js | src/commands/eval.js | const Discord = require("discord.js");
const Command = require("../command.js");
const moment = require("moment");
const {inspect} = require("util");
const {post} = require("snekfetch");
class Eval extends Command {
constructor(client) {
super(client, {
name: "eval",
type: "utility",
description: "Evaluates code from a provided string.",
use: [
["code", true]
],
aliases: [
"run"
],
ownerOnly: true
});
this.endings = ["ns", "\u03bcs", "ms", "s"];
this.default = true;
}
clean(str) {
const reg = new RegExp(`${this.client.token}|${this.client.token.split("").reverse().join("")}${this.client.user.bot ? "" : `|${this.client.user.email}`}`, "g");
return typeof str === "string" ? str.replace(/[`@]/g, "$&\u200b").replace(reg, "[SECRET]").replace(new RegExp(process.cwd().replace(/[.\\]/g, "\\$&"), "g"), ".") : str;
}
async run(message, args) {
const client = this.client, embed = new Discord.RichEmbed();
const code = args.join(" ");
client.utils.log(code);
let evaled, suffix;
const start = process.hrtime();
try {
evaled = await eval(code);
embed.setColor(24120);
suffix = "**OUTPUT**: ";
} catch (err) {
evaled = err;
embed.setColor(13379110);
suffix = "**ERROR**: ";
}
const hrDiff = process.hrtime(start);
let end = (hrDiff[0] * 1000000000) + hrDiff[1];
let ending = this.endings[0], i = 0;
while (this.endings[++i] && end > 1000) {
end /= 1000;
ending = this.endings[i];
}
client.utils[~suffix.indexOf("ERROR") ? "error" : "log"](evaled);
if (typeof evaled !== "string") evaled = evaled instanceof Error ? evaled : inspect(evaled);
if (evaled.length > 1800) {
message = await (!client.user.bot ? message.edit.bind(message) : message.channel.send.bind(message.channel))("Uploading to gist, this may take a moment...");
let id;
try {
({id} = await post("https://api.github.com/gists").send({
public: false,
description: ``,
files: {
[`output_${message.author.id}_${moment().format("YYYY_MM_DD")}.md`]: {
content: `Evaled in ${message.guild ? `Guild **${message.guild.name}**,` : "DM with"} ${message.channel.type === "dm" ? `**${message.channel.recipient.tag}**` : `channel **#${message.channel.name}**`} at **${moment.utc().format("h:mm A")} UTC**
## Input
\`\`\`js
${code}
\`\`\`
## Output
\`\`\`js
${evaled}
\`\`\``
}
}
}).then(res => JSON.parse(res.text)));
} catch (err) {
client.utils.error(err);
}
suffix += id ? `[Gist created](https://gist.github.com/${id})` : "Failed to generate gist.";
} else {
suffix += `\`\`\`${~suffix.indexOf("ERROR") ? "xl" : "js"}\n${this.clean(evaled)}\n\`\`\``;
}
embed.setDescription(`**INPUT:** \`\`\`js\n${code}\n\`\`\`\n${suffix}`)
.setFooter(`Runtime: ${end.toFixed(3)}${ending}`, "https://cdn.discordapp.com/attachments/286943000159059968/298622278097305600/233782775726080012.png");
return (!client.user.bot ? message.edit.bind(message) : message.channel.send.bind(message.channel))({embed});
}
}
module.exports = Eval;
| JavaScript | 0.000082 | @@ -882,51 +882,51 @@
ace(
-/%5B%60@%5D/g, %22$&%5Cu200b%22).replace(reg, %22%5BSECRET%5D
+reg, %22%5BSECRET%5D%22).replace(/%5B%60@%5D/g, %22$&%5Cu200b
%22).r
|
1d8fa1132d2be6ec64a2126cfb5ab787d401edb7 | Fix small output formatting error | src/commands/eval.js | src/commands/eval.js | const Discord = require("discord.js");
const Command = require("../command.js");
const moment = require("moment");
const {inspect} = require("util");
const {post} = require("snekfetch");
class Eval extends Command {
constructor(client) {
super(client, {
name: "eval",
type: "utility",
description: "Evaluates code from a provided string.",
use: [
["code", true]
],
aliases: [
"run"
],
ownerOnly: true
});
this.endings = ["ns", "\u03bcs", "ms", "s"];
this.default = true;
}
clean(str) {
const reg = new RegExp(`${this.client.token}|${this.client.token.split("").reverse().join("")}`, "g");
return typeof str === "string" ? str.replace(/[`@]/g, "$&\u200b").replace(reg, "[SECRET]").replace(new RegExp(process.cwd(), "g"), ".") : str;
}
async run(message, args) {
const client = this.client, embed = new Discord.RichEmbed();
const code = args.join(" ");
client.utils.log(code);
let evaled, suffix;
const start = process.hrtime();
try {
evaled = await eval(code);
client.utils.log(evaled);
embed.setColor(24120);
suffix = `**OUTPUT**: \`\`\`js\n`;
} catch (err) {
evaled = err;
client.utils.error(err);
embed.setColor(13379110);
suffix = `**ERROR**: \`\`\`xl\n`;
}
const hrDiff = process.hrtime(start);
let end = (hrDiff[0] > 0 ? (hrDiff[0] * 1000000000) : 0) + hrDiff[1];
let ending = this.endings[0], i = 0;
while (this.endings[++i] && end > 1000) {
end /= 1000;
ending = this.endings[i];
}
if (typeof evaled !== "string") evaled = inspect(evaled);
if (evaled.length > 1800) {
message = await (client._selfbot ? message.edit.bind(message) : message.channel.send.bind(message.channel))("Uploading to gist, this may take a moment...");
let id;
try {
({id} = await post("https://api.github.com/gists").send({
public: true,
files: {
[`output_${message.author.id}_${moment().format("YYYY_MM_DD")}.js`]: {content:evaled}
}
}).then(res => JSON.parse(res.text)));
} catch (err) {
client.utils.error(err);
}
suffix += id ? `[Gist created](https://gist.github.com/${id})` : "Failed to generate gist.";
} else {
suffix += `${this.clean(evaled)}\n\`\`\``;
}
embed.setDescription(`**INPUT:** \`\`\`js\n${code}\n\`\`\`\n${suffix}`)
.setFooter(`Runtime: ${end.toFixed(3)}${ending}`, "https://cdn.discordapp.com/attachments/286943000159059968/298622278097305600/233782775726080012.png");
return (client._selfbot ? message.edit.bind(message) : message.channel.send.bind(message.channel))({embed});
}
}
module.exports = Eval;
| JavaScript | 0.000088 | @@ -1311,17 +1311,17 @@
uffix =
-%60
+%22
**OUTPUT
@@ -1328,19 +1328,9 @@
**:
-%5C%60%5C%60%5C%60js%5Cn%60
+%22
;%0A
@@ -1473,17 +1473,17 @@
uffix =
-%60
+%22
**ERROR*
@@ -1489,19 +1489,9 @@
**:
-%5C%60%5C%60%5C%60xl%5Cn%60
+%22
;%0A
@@ -2676,16 +2676,66 @@
fix += %60
+%5C%60%5C%60%5C%60$%7Bsuffix === %22**OUTPUT**: %22 ? %22js%22 : %22xl%22%7D%5Cn
$%7Bthis.c
|
48625db47fd0dd4b4ced29d8409ed2e708f190ff | fix (init): fix typo in init error msg | src/commands/init.js | src/commands/init.js | var fs = require('fs');
var ff = require('ff');
var path = require('path');
var color = require('cli-color');
var commands = require('./index');
var apps = require('../apps');
var BaseCommand = require('../util/BaseCommand').BaseCommand;
var UsageError = require('../util/BaseCommand').UsageError;
var DestinationExistsError = apps.DestinationExistsError;
var InitCommand = Class(BaseCommand, function (supr) {
this.name = 'init';
this.description = 'creates a new devkit app';
this.init = function () {
supr(this, 'init', arguments);
this.opts
.boolean('no-template')
.describe('no-template', 'copy no files other than manifest.json')
.describe('local-template', 'path to local application template')
.describe('git-template', 'path to git repository');
};
this.exec = function (command, args, cb) {
return Promise.bind(this).then(function () {
// check the app name
var appPath = args.shift();
var errorMessage;
if (typeof(appPath) === 'undefined') {
// TODO: print usage
errorMessage = 'No app name provided';
this.logger.error(errorMessage);
return Promise.reject(new UsageError(errorMessage));
}
var appName = path.basename(appPath);
if (!appName) {
// TODO: refactor and print usage
errorMessage = 'No app name provided';
this.logger.error(errorMessage);
return Promise.reject(new UsageError(errorMessage));
}
this.appName = appName;
if (!/^[a-z][a-z0-9]*$/i.test(appName)) {
errorMessage = 'App name must start with a letter and consist only of' +
'letters and numbers';
this.logger.error(errorMessage);
return Promise.reject(new UsageError(errorMessage));
}
this.appPath = appPath = path.resolve(process.cwd(), appPath);
var template = {type: void 0};
if (this.opts.argv.template !== void 0) {
template.type = 'none';
template.path = '';
} else if (this.opts.argv['local-template']) {
template.type = 'local';
template.path = this.opts.argv['local-template'];
} else if (this.opts.argv['git-template']) {
template.type = 'git';
template.path = this.opts.argv['git-template'];
}
// create the app
return apps.create(appPath, template);
}).then(function (app) {
// change to app root and run install command
process.chdir(app.paths.root);
return commands.get('install').exec('install', []);
}).then(function () {
// Success message
this.logger.log(
color.cyanBright('created new app'), color.yellowBright(this.appName)
);
return new Promise(function (resolve) {
commands
.get('instructions')
.exec('instructions', ['new_application'], resolve);
});
}).catch(DestinationExistsError, function (err) {
this.logger.error(
'The path you specified (' + err.message + ') already exists.',
'Aborting.'
);
}).catch(function (err) {
console.error(err);
}).nodeify(cb);
};
});
module.exports = InitCommand;
| JavaScript | 0.000006 | @@ -1634,16 +1634,17 @@
only of
+
' +%0A
|
1bf793b32fb7a69a8f10324afbe8b2dc40b9cbfc | Fix fadeouts sometimes being cut short. | src/dynamics.js | src/dynamics.js |
// Functions embedded in Gadfly plots to add interactivity.
// Clicking an entry in a color key toggles visibility of the data within that
// group.
function toggle_color_group(name)
{
geoms = document.getElementsByClassName('color_group_' + name);
entry = document.getElementById('color_key_' + name);
state = geoms[0].getAttribute('visibility');
if (!state || state == 'visible') {
for (i = 0; i < geoms.length; ++i) {
geoms[i].setAttribute('visibility', 'hidden');
}
entry.setAttribute('opacity', 0.5);
} else {
for (i = 0; i < geoms.length; ++i) {
geoms[i].setAttribute('visibility', 'visible');
}
entry.setAttribute('opacity', 1.0);
}
}
// Turn on a possibily hidden annotation.
function show_annotation(id)
{
annot = document.getElementById(id)
annot.setAttribute('visibility', 'visible')
}
// Turn off a possibly hidden annotation.
function hide_annotation(id)
{
annot = document.getElementById(id)
annot.setAttribute('visibility', 'hidden')
}
// Dim all geometry objects with some exceptions.
function present_geometry(ids)
{
on_anim_dur = 0.1;
off_anim = document.getElementById('panel-focus-filter-off-anim');
off_anim.endElement();
t0 = Number(off_anim.getStartTime());
if (t0 < Infinity) {
t = Number(off_anim.getCurrentTime());
d = Number(off_anim.getSimpleDuration());
from = Number(off_anim.getAttribute('from'));
to = Number(off_anim.getAttribute('to'));
p = Math.max(0.0, Math.min(1.0, ((t - t0) / d)));
v = from + p * (to - from);
}
else {
p=1.0;
v=0.0;
}
geoms = document.getElementsByClassName('geometry');
for (i = 0; i < geoms.length; ++i) {
geoms[i].setAttribute('filter', 'url(#panel-focus-filter)');
}
for (i = 0; i < ids.length; ++i) {
geom = document.getElementById(ids[i]);
geom.setAttribute('filter', 'inherit');
}
on_anim = document.getElementById('panel-focus-filter-on-anim');
on_anim.setAttribute('from', v);
on_anim.setAttribute('dur', p * on_anim_dur + 's');
on_anim.beginElement();
}
// Set all geometries to full opacity.
function unpresent_geometry()
{
off_anim_dur = 0.3;
on_anim = document.getElementById('panel-focus-filter-on-anim');
on_anim.endElement();
t0 = Number(on_anim.getStartTime());
t = Number(on_anim.getCurrentTime());
d = Number(on_anim.getSimpleDuration());
from = Number(on_anim.getAttribute('from'));
to = Number(on_anim.getAttribute('to'));
p = Math.max(0.0, Math.min(1.0, ((t - t0) / d)));
v = from + p * (to - from);
off_anim = document.getElementById('panel-focus-filter-off-anim');
off_anim.setAttribute('from', v);
dur = p * off_anim_dur
off_anim.setAttribute('dur', dur + 's');
off_anim.addEventListener('endEvent', unpresent_geometry_end);
off_anim.beginElement();
// Webkit doesn't support the "onend" attribute, so we work arround.
setTimeout("unpresent_geometry_end()", 1000 * dur);
}
// Called when the animation in unpresent_geometry finishes.
// Enabling a filter, even if it has no effect, adds an extra layer of
// rasterization, which tends to make things look like shit, so we clear all the
// filters when the animation ends.
function unpresent_geometry_end()
{
// skip this function in the on_animation has been triggered since the last
// off_animation.
on_anim = document.getElementById('panel-focus-filter-on-anim');
off_anim = document.getElementById('panel-focus-filter-off-anim');
if (on_anim.getStartTime() > off_anim.getStartTime()) {
return;
}
geoms = document.getElementsByClassName('geometry');
for (i = 0; i < geoms.length; ++i) {
geoms[i].setAttribute('filter', 'inherit');
}
}
| JavaScript | 0 | @@ -3714,32 +3714,235 @@
return;%0A %7D%0A%0A
+ // Skip this if the off animation isn't actually finished.%0A elapsed = off_anim.getCurrentTime() - off_anim.getStartTime();%0A if (elapsed %3C off_anim.getSimpleDuration()) %7B%0A return;%0A %7D%0A%0A
geoms = docu
|
75efe138b9ff22c4fe2a616a4161edaf87ac265e | add fancy human readable output | request.js | request.js | // --------------------------------------------------------------------------------------
var exp = {}
const request = require('request');
const url_base = 'https://etlog.cesnet.cz:8443/api';
// --------------------------------------------------------------------------------------
// get invalid records
// --------------------------------------------------------------------------------------
exp.get_invalid_records_monthly = function(callback)
{
var ret = [];
var url = "/invalid_records/filtered/";
var date = new Date(); // current date
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0); // set to 00:00:00:000
date.setDate(date.getDate() -1); // decrease by 1 day - data for current date are not available yet
var interval = 30;
var cnt = 0; // number of processed items
for(var i = 0; i < interval; i++) {
request.get({ // get data
url: url_base + url + date.toISOString(),
}, function (error, response, body) {
if(error || (response.status != undefined && response.status != 200)) {
if(error) { // handle error
console.log(error);
return;
}
else { // handle status code
console.log(JSON.parse(body).error);
return;
}
}
else {
if(JSON.parse(body).length != 0) { // no not add empty response
ret.push(JSON.parse(body)); // add data
}
}
cnt++; // increase processed count
if(cnt == interval) {
//callback("měsíční report - invalidní záznamy", filter_data(ret).toString()); // return data when all requests are done
// TODO - mail content is too big
// debug
return;
}
});
date.setDate(date.getDate() -1); // decrease by 1 day
}
}
// --------------------------------------------------------------------------------------
// filter invalid records data to gen only one entry per pair [ pn, csi ]
// --------------------------------------------------------------------------------------
function filter_data(data)
{
var filter = []; // filtering "rules"
var ret = [];
for(var arr in data) { // create filtering rules
for(var item in data[arr]) {
var fields = data[arr][item].split("#");
var csi = fields[4];
var pn = fields[5];
var id = csi + "#" + pn;
// item already in array, do not add it again
if(filter.includes(id))
continue;
filter.push(id); // combined id from csi and pn
}
}
// --------------------------------------------------------------------------------------
// filter by pair [ pn, csi ]
// both pn and csi may be empty at the same time - in that case, we want all the records including this pair
// => filtering is exclusion based
for(var item in filter) {
var cnt = 0;
for(var arr in data) {
for(var line in data[arr]) {
if(data[arr][line].indexOf(filter[item]) != -1) { // pair present in line
if(cnt == 0) // first occurence
ret.push(data[arr][line].replace(/[^ -~]+/g, "")); // add to result, remove non printable characters
cnt++;
}
}
}
}
return ret;
}
// --------------------------------------------------------------------------------------
// get failed logins
// parameter limit number of results
// --------------------------------------------------------------------------------------
exp.get_failed_logins_monthly = function(limit, callback)
{
var test = [];
var url = "/failed_logins/";
var max = new Date(); // current date
max.setHours(0);
max.setMinutes(0);
max.setSeconds(0);
max.setMilliseconds(0); // set to 00:00:00:000
var min = new Date(max);
min.setDate(max.getDate() - 30); // 30 days before
var query = '?timestamp>=' + min.toISOString() + "×tamp<" + max.toISOString(); // use ISO-8601 format
query += "&limit=" + limit; // limit number of records
query += "&sort=-fail_count"; // sort by fail_count
request.get({
url: url_base + url + query // use query string here for simple usage
}, function (error, response, body) {
if(error)
console.log(error);
else
callback("měsíční report - neúspěšná přihlášení", failed_to_human_readable(JSON.parse(body))); // return response to caller
});
}
// --------------------------------------------------------------------------------------
// convert failed logins structure to human readable text
// --------------------------------------------------------------------------------------
function failed_to_human_readable(data)
{
var ret = "";
for(var item in data)
ret += data[item].username + "| fail_count: " + data[item].fail_count + ", ok_count: " + data[item].ok_count + ", ratio : " + data[item].ratio + "\n";
return ret;
}
// --------------------------------------------------------------------------------------
module.exports = exp;
| JavaScript | 0.999686 | @@ -4677,20 +4677,41 @@
et = %22%22;
+%0A var longest = 0;
%0A%0A
+//
for(var
@@ -4726,16 +4726,18 @@
data)%0A
+//
ret +=
@@ -4882,16 +4882,489 @@
%22%5Cn%22;%0A%0A
+ // fancy version%0A // =======================%0A%0A for(var item in data) %7B%0A if(data%5Bitem%5D.username.length %3E longest)%0A longest = data%5Bitem%5D.username.length;%0A %7D%0A%0A for(var item in data) %7B%0A ret += data%5Bitem%5D.username;%0A for(var i = data%5Bitem%5D.username.length; i %3C longest; i++) // insert space padding%0A ret+= %22 %22;%0A%0A ret += %22 %7C fail_count: %22 + data%5Bitem%5D.fail_count + %22, ok_count: %22 + data%5Bitem%5D.ok_count + %22, ratio : %22 + data%5Bitem%5D.ratio + %22%5Cn%22;%0A %7D%0A%0A%0A
return
|
2c343f896e7734e8fbc493a8072786d0414f9b28 | Fix timing issue in firefox where cycle wouldn't start before replay | src/restart.js | src/restart.js | import {run} from '@cycle/core';
import Rx from 'rx';
import restartable from './restartable';
function restart (main, drivers, {sources, sinks}, isolate = {}, timeToTravelTo = null) {
sources.dispose();
sinks && sinks.dispose();
if (typeof isolate === 'function' && 'reset' in isolate) {
isolate.reset();
}
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.onPreReplay) {
driver.onPreReplay();
}
}
const newSourcesAndSinks = run(main, drivers);
setTimeout(() => {
const scheduler = new Rx.HistoricalScheduler();
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.replayLog) {
const log$ = sources[driverName].log$;
driver.replayLog(scheduler, log$, timeToTravelTo);
}
}
scheduler.scheduleAbsolute({}, new Date(), () => {
// TODO - remove this setTimeout, figure out how to tell when an async app is booted
setTimeout(() => {
for (let driverName in drivers) {
const driver = drivers[driverName];
if (driver.onPostReplay) {
driver.onPostReplay();
}
}
}, 500);
});
scheduler.start();
});
return newSourcesAndSinks;
}
module.exports = {
restart,
restartable
}
| JavaScript | 0.000001 | @@ -1223,16 +1223,19 @@
t();%0A %7D
+, 1
);%0A%0A re
|
e33887ef4ced9e7980b088598661e44318d63d41 | fix script error | clean-scripts.config.js | clean-scripts.config.js | const childProcess = require('child_process')
const util = require('util')
const execAsync = util.promisify(childProcess.exec)
module.exports = {
build: [
{
js: [
`file2variable-cli app.template.html -o variables.ts --html-minify`,
`tsc`,
`webpack --display-modules`
],
css: {
vendor: `cleancss ./node_modules/bootstrap/dist/css/bootstrap.min.css ./node_modules/github-fork-ribbon-css/gh-fork-ribbon.css -o vendor.bundle.css`,
index: [
`postcss index.css -o index.postss.css`,
`cleancss index.postss.css -o index.bundle.css`
]
},
clean: `rimraf vendor.bundle-*.js vendor.bundle-*.css index.bundle-*.js index.bundle-*.css`
},
`rev-static`,
[
`sw-precache --config sw-precache.config.js`,
`uglifyjs service-worker.js -o service-worker.bundle.js`
],
async () => {
const { createServer } = require('http-server')
const puppeteer = require('puppeteer')
const fs = require('fs')
const beautify = require('js-beautify').html
const server = createServer()
server.listen(8000)
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.emulate({ viewport: { width: 1440, height: 900 }, userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36' })
await page.goto(`http://localhost:8000`)
await page.screenshot({ path: `screenshot.png`, fullPage: true })
const content = await page.content()
fs.writeFileSync(`screenshot-src.html`, beautify(content))
server.close()
browser.close()
}
],
lint: {
ts: `tslint "*.ts" "tests/*.ts"`,
js: `standard "**/*.config.js"`,
export: `no-unused-export "*.ts" "tests/*.ts"`
},
test: [
'tsc -p spec',
'karma start spec/karma.config.js',
'git checkout screenshot.png',
async () => {
const { stdout } = await execAsync('git status -s')
if (stdout) {
console.log(stdout)
throw new Error(`generated files doesn't match.`)
}
}
],
fix: {
ts: `tslint --fix "*.ts" "tests/*.ts"`,
js: `standard --fix "**/*.config.js"`
},
release: `clean-release`,
watch: {
template: `file2variable-cli app.template.html -o variables.ts --html-minify --watch`,
src: `tsc --watch`,
webpack: `webpack --watch`,
css: `watch-then-execute "index.css" --script "clean-scripts build[0].css.index"`,
rev: `rev-static --watch`,
sw: `watch-then-execute "vendor.bundle-*.js" "index.html" "worker.bundle.js" --script "clean-scripts build[2]"`
},
prerender: [
async () => {
const { createServer } = require('http-server')
const puppeteer = require('puppeteer')
const fs = require('fs')
const server = createServer()
server.listen(8000)
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.emulate({ viewport: { width: 1440, height: 900 }, userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36' })
await page.waitFor(1000)
await page.goto('http://localhost:8000')
await page.waitFor(1000)
const content = await page.evaluate(() => {
const element = document.querySelector('#prerender-container')
return element ? element.innerHTML : ''
})
fs.writeFileSync('prerender.html', content)
server.close()
browser.close()
},
`clean-scripts build[1]`,
`clean-scripts build[2]`
]
}
| JavaScript | 0.000001 | @@ -533,24 +533,25 @@
o index.post
+c
ss.css%60,%0A
@@ -577,16 +577,17 @@
dex.post
+c
ss.css -
|
0d1f3b20f36f5f7000c0fa4aacbe334a548cef57 | Call callback even if same as last error | src/rollbar.js | src/rollbar.js | var RateLimiter = require('./rateLimiter');
var Queue = require('./queue');
var Notifier = require('./notifier');
var Telemeter = require('./telemetry');
var _ = require('./utility');
/*
* Rollbar - the interface to Rollbar
*
* @param options
* @param api
* @param logger
*/
function Rollbar(options, api, logger, platform) {
this.options = _.extend(true, {}, options);
this.logger = logger;
Rollbar.rateLimiter.configureGlobal(this.options);
Rollbar.rateLimiter.setPlatformOptions(platform, this.options);
this.queue = new Queue(Rollbar.rateLimiter, api, logger, this.options);
this.notifier = new Notifier(this.queue, this.options);
this.telemeter = new Telemeter(this.options);
this.lastError = null;
}
var defaultOptions = {
maxItems: 0,
itemsPerMinute: 60
};
Rollbar.rateLimiter = new RateLimiter(defaultOptions);
Rollbar.prototype.global = function(options) {
Rollbar.rateLimiter.configureGlobal(options);
return this;
};
Rollbar.prototype.configure = function(options, payloadData) {
this.notifier && this.notifier.configure(options);
this.telemeter && this.telemeter.configure(options);
var oldOptions = this.options;
var payload = {};
if (payloadData) {
payload = {payload: payloadData};
}
this.options = _.extend(true, {}, oldOptions, options, payload);
this.global(this.options);
return this;
};
Rollbar.prototype.log = function(item) {
var level = this._defaultLogLevel();
return this._log(level, item);
};
Rollbar.prototype.debug = function(item) {
this._log('debug', item);
};
Rollbar.prototype.info = function(item) {
this._log('info', item);
};
Rollbar.prototype.warn = function(item) {
this._log('warning', item);
};
Rollbar.prototype.warning = function(item) {
this._log('warning', item);
};
Rollbar.prototype.error = function(item) {
this._log('error', item);
};
Rollbar.prototype.critical = function(item) {
this._log('critical', item);
};
Rollbar.prototype.wait = function(callback) {
this.queue.wait(callback);
};
Rollbar.prototype.captureEvent = function(metadata, level) {
return this.telemeter.captureEvent(metadata, level);
};
Rollbar.prototype.captureDomContentLoaded = function(ts) {
return this.telemeter.captureDomContentLoaded(ts);
};
Rollbar.prototype.captureLoad = function(ts) {
return this.telemeter.captureLoad(ts);
};
/* Internal */
Rollbar.prototype._log = function(defaultLevel, item) {
if (this._sameAsLastError(item)) {
return;
}
try {
var callback = null;
if (item.callback) {
callback = item.callback;
delete item.callback;
}
item.level = item.level || defaultLevel;
item.telemetryEvents = this.telemeter.copyEvents();
this.telemeter._captureRollbarItem(item);
this.notifier.log(item, callback);
} catch (e) {
this.logger.error(e)
}
};
Rollbar.prototype._defaultLogLevel = function() {
return this.options.logLevel || 'debug';
};
Rollbar.prototype._sameAsLastError = function(item) {
if (this.lastError && this.lastError === item.err) {
return true;
}
this.lastError = item.err;
return false;
};
module.exports = Rollbar;
| JavaScript | 0.000001 | @@ -2446,24 +2446,64 @@
or(item)) %7B%0A
+ if (item.callback) item.callback();%0A
return;%0A
|
0602f4f36d181448167840ee4e4ae77afe8041a1 | replace timeout default value 30s to 120s | src/config/config.js | src/config/config.js | 'use strict';
/**
* default config
* @type {Object}
*/
let config = {
port: 8360,
host: '',
encoding: 'utf-8',
pathname_prefix: '',
pathname_suffix: '.html',
proxy_on: false,
hook_on: true,
cluster_on: false,
service_on: true, //Service available
timeout: 30, //30 seconds
auto_reload: false, //file auto reload
resource_on: true,
resource_reg: /^(static\/|[^\/]+\.(?!js|html)\w+$)/,
route_on: true,
log_pid: false,
log_request: false,
create_server: undefined,
output_content: undefined,
deny_module_list: [],
default_module: 'home',
default_controller: 'index',
default_action: 'index',
callback_name: 'callback',
json_content_type: 'application/json',
subdomain: {} //subdomain deploy
};
/**
* extra config on cli mode
* @type {Object}
*/
let cliConfig = {
auto_close_socket: true
}
if(think.cli){
config = think.extend(config, cliConfig);
}
export default config; | JavaScript | 0.005151 | @@ -281,15 +281,17 @@
ut:
-3
+12
0, //
-3
+12
0 se
|
16c11e33df29501c8341804e4dd0a0ad97b34d2a | Update squidroot to the new devstep init path | plugin.js | plugin.js | squidRoot = _currentPluginPath;
squidShared = squidRoot + "/shared";
devstep.on('configLoaded', function(config) {
config
.addLink('squid3:squid3.dev')
.setEnv('http_proxy', 'http://squid3.dev:3128')
.setEnv('https_proxy', 'http://squid3.dev:3128')
.setEnv('HTTPS_PROXY_CERT', 'squid3.dev.crt')
.addVolume(squidShared + '/certs/squid3.dev.crt:/usr/share/ca-certificates/squid3.dev.crt')
.addVolume(squidRoot + '/proxy.sh:/etc/my_init.d/proxy.sh');
});
| JavaScript | 0 | @@ -452,11 +452,16 @@
etc/
-my_
+devstep/
init
|
6e049f9bbc20107c496af54663253bc1f554412b | make use of new location field color map feature | lib/components/form/connect-location-field.js | lib/components/form/connect-location-field.js | import { connect } from 'react-redux'
import * as apiActions from '../../actions/api'
import * as locationActions from '../../actions/location'
import { getActiveSearch, getShowUserSettings } from '../../util/state'
/**
* This higher-order component connects the target (styled) LocationField to the
* redux store.
* @param StyledLocationField The input LocationField component to connect.
* @param options Optional object with the following optional props:
* - actions: a list of actions to include in mapDispatchToProps
* - includeLocation: whether to derive the location prop from
* the active query
* @returns The connected component.
*/
export default function connectLocationField (StyledLocationField, options = {}) {
// By default, set actions to empty list and do not include location.
const {actions = [], includeLocation = false} = options
const mapStateToProps = (state, ownProps) => {
const { config, currentQuery, location, transitIndex, user } = state.otp
const { currentPosition, nearbyStops, sessionSearches } = location
const activeSearch = getActiveSearch(state)
const query = activeSearch ? activeSearch.query : currentQuery
const stateToProps = {
currentPosition,
geocoderConfig: config.geocoder,
nearbyStops,
sessionSearches,
showUserSettings: getShowUserSettings(state),
stopsIndex: transitIndex.stops,
userLocationsAndRecentPlaces: [...user.locations, ...user.recentPlaces]
}
// Set the location prop only if includeLocation is specified, else leave unset.
// Otherwise, the StyledLocationField component will use the fixed undefined/null value as location
// and will not respond to user input.
if (includeLocation) {
stateToProps.location = query[ownProps.locationType]
}
return stateToProps
}
const mapDispatchToProps = {
addLocationSearch: locationActions.addLocationSearch,
findNearbyStops: apiActions.findNearbyStops,
getCurrentPosition: locationActions.getCurrentPosition,
...actions
}
return connect(mapStateToProps, mapDispatchToProps)(StyledLocationField)
}
| JavaScript | 0.000001 | @@ -1308,16 +1308,68 @@
ocoder,%0A
+ layerColorMap: config.geocoder.resultsColors,%0A
ne
|
100c1d62160bc53210f50732875aa911ec4ed982 | Fix leg focus, address some PR comments. | lib/components/mobile/batch-results-screen.js | lib/components/mobile/batch-results-screen.js | import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { Button } from 'react-bootstrap'
import { connect } from 'react-redux'
import styled from 'styled-components'
import Map from '../map/map'
import Icon from '../narrative/icon'
import NarrativeItineraries from '../narrative/narrative-itineraries'
import { getActiveError } from '../../util/state'
import MobileContainer from './container'
import ResultsHeaderAndError from './results-header-and-error'
const StyledMobileContainer = styled(MobileContainer)`
.options > .header {
margin: 10px;
}
&.otp.mobile .mobile-narrative-container {
bottom: 0;
left: 0;
overflow-y: auto;
padding: 0;
position: fixed;
right: 0;
}
`
const ExpandMapButton = styled(Button)`
bottom: 25px;
position: absolute;
right: 10px;
z-index: 999999;
`
class BatchMobileResultsScreen extends Component {
static propTypes = {
error: PropTypes.object
}
constructor () {
super()
this.state = {
itineraryExpanded: false,
mapExpanded: false
}
}
componentDidUpdate (prevProps) {
// Check if the active leg changed
if (this.props.activeLeg !== prevProps.activeLeg) {
this._setItineraryExpanded(false)
}
}
_setItineraryExpanded = itineraryExpanded => {
this.setState({ itineraryExpanded })
}
_toggleMapExpanded = () => {
this.setState({ mapExpanded: !this.state.mapExpanded })
}
renderMap () {
const { mapExpanded } = this.state
return (
<div className='results-map' style={{bottom: mapExpanded ? 0 : '60%'}}>
<Map />
<ExpandMapButton
bsSize='small'
onClick={this._toggleMapExpanded}
>
<Icon name={mapExpanded ? 'list-ul' : 'arrows-alt'} />
{mapExpanded ? 'Show results' : 'Expand map'}
</ExpandMapButton>
</div>
)
}
render () {
const { error } = this.props
const { itineraryExpanded, mapExpanded } = this.state
return (
<StyledMobileContainer>
<ResultsHeaderAndError />
{!error && (mapExpanded
// Set up two separate renderings of the map according to mapExpanded,
// so that the map is properly sized and itineraries fit under either conditions.
// (Otherwise, if just the narrative is added/removed, the map doesn't resize properly.)
? this.renderMap()
: (
<>
{!itineraryExpanded && this.renderMap()}
<div className='mobile-narrative-container' style={{top: itineraryExpanded ? '100px' : '40%'}}>
<NarrativeItineraries
containerStyle={{
display: 'flex',
flexDirection: 'column',
height: '100%',
width: '100%'
}}
onToggleDetailedItinerary={this._setItineraryExpanded}
/>
</div>
</>
))
}
</StyledMobileContainer>
)
}
}
// connect to the redux store
const mapStateToProps = (state, ownProps) => {
return {
error: getActiveError(state.otp)
}
}
export default connect(mapStateToProps)(BatchMobileResultsScreen)
| JavaScript | 0 | @@ -347,16 +347,33 @@
iveError
+, getActiveSearch
%7D from
@@ -391,16 +391,16 @@
/state'%0A
-
%0Aimport
@@ -806,10 +806,24 @@
om:
-25
+10px;%0A left: 10
px;%0A
@@ -848,23 +848,8 @@
te;%0A
- right: 10px;%0A
z-
@@ -866,16 +866,107 @@
999;%0A%60%0A%0A
+/**%0A * This component renders the mobile view of itinerary results from batch routing.%0A */%0A
class Ba
@@ -1221,47 +1221,8 @@
) %7B%0A
- // Check if the active leg changed%0A
@@ -1269,24 +1269,231 @@
ctiveLeg) %7B%0A
+ // Check if the active leg has changed. If a different leg is selected,%0A // unexpand the itinerary to show the map focused on the selected leg%0A // (similar to the behavior of LineItinerary).%0A
this._
@@ -2053,16 +2053,21 @@
alt'%7D /%3E
+%7B' '%7D
%0A
@@ -3403,16 +3403,127 @@
%7B%0A
-return %7B
+const activeSearch = getActiveSearch(state.otp)%0A return %7B%0A activeLeg: activeSearch ? activeSearch.activeLeg : null,
%0A
|
4fc1ed003d8d74c10f67bc079fde2bba688d1ee3 | Check before recreating Listeners. | src/core/Listener.js | src/core/Listener.js | /*
* @license
* Copyright 2016 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.
*/
/**
Listeners are high-level pre-bound event call-backs.
<pre>
Ex.
foam.CLASS({
name: 'Sprinkler',
listeners: [
// short-form
function onAlarm() { ... },
// long-form
{
name: 'onClear',
isFramed: true,
code: function() { ... }
}
]
});
</pre>
You might use the above onAlarm listener like this:
alarm.ring.sub(sprinker.onAlarm);
<p>
Notice, that normally JS methods forget which object they belong
to so you would need to do something like:
<pre>alarm.ring.sub(sprinker.onAlarm.bind(sprinkler));</pre>
But listeners are pre-bound.
*/
foam.CLASS({
package: 'foam.core',
name: 'Listener',
properties: [
// TODO: doc
'name',
'code',
{ class: 'Boolean', name: 'isFramed', value: false },
{ class: 'Boolean', name: 'isMerged', value: false },
{ class: 'Int', name: 'mergeDelay', value: 16, units: 'ms' }
],
methods: [
function validate() {
this.assert( ! this.isMerged || ! this.isFramed, "Listener can't be both isMerged and isFramed: ", this.name);
},
function installInProto(proto) {
var name = this.name;
var code = this.code;
var isMerged = this.isMerged;
var isFramed = this.isFramed;
var mergeDelay = this.mergeDelay;
Object.defineProperty(proto, name, {
get: function topicGetter() {
if ( ! this.hasOwnPrivate_(name) ) {
var self = this;
var l = function(sub) {
if ( self.isDestroyed() ) {
if ( sub ) {
console.warn('Destroying stale subscription for', self.cls_.id);
sub.destroy();
}
} else {
code.apply(self, arguments);
}
};
foam.Function.setName(l, name);
if ( isMerged ) {
l = this.X.merged(l, mergeDelay);
} else if ( isFramed ) {
l = this.X.framed(l);
}
// TODO: warn if both merged and framed.
this.setPrivate_(name, l);
}
return this.getPrivate_(name);
},
configurable: true,
enumerable: false
});
}
]
});
foam.CLASS({
refines: 'foam.core.Model',
properties: [
{
class: 'AxiomArray',
of: 'Listener',
name: 'listeners',
adaptArrayElement: function(o) {
if ( typeof o === 'function' ) {
console.assert(o.name, 'Listener must be named');
return foam.core.Listener.create({name: o.name, code: o});
}
// TODO: check that not already a Listener
return foam.core.Listener.create(o);
}
}
]
});
| JavaScript | 0 | @@ -3255,65 +3255,77 @@
-// TODO: check that not already a Listener%0A return
+return foam.core.Listener.isInstance(o) ?%0A o :%0A
foa
@@ -3349,16 +3349,17 @@
reate(o)
+
;%0A
|
7b0163641ab1d5079ef69420c312e250e178358f | Version error finally fixed. Hallelujah jesusfish amen. | app/js/services.js | app/js/services.js | 'use strict';
/* Services */
// Demonstrate how to register services
// In this case it is a simple value service.
var animalsServices = angular.module('animalsServices', ['ngResource']);
animalsServices.factory('Animal', ['$resource', function($resource){
return $resource('animals/:animalId.json', {}, {
query: {method:'GET', params:{animalId:'animals'}, isArray:true}
});
}]);
| JavaScript | 0 | @@ -185,16 +185,58 @@
ce'%5D);%0A%0A
+animalsServices.value('version', '0.1');%0A%0A
animalsS
|
937348ea4cd0eed5565e856653e9b92e74b3d385 | update app/lib/scripts -- globby moved to toolz | app/lib/scripts.js | app/lib/scripts.js | //
// █████╗ ██╗ ██╗██╗██╗ ███████╗███████╗███████╗
// ██╔══██╗██║ ██╔╝██║██║ ██╔════╝██╔════╝╚══███╔╝
// ███████║█████╔╝ ██║██║ █████╗ █████╗ ███╔╝
// ██╔══██║██╔═██╗ ██║██║ ██╔══╝ ██╔══╝ ███╔╝
// ██║ ██║██║ ██╗██║███████╗███████╗███████╗███████╗
// ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚══════╝╚══════╝
// Rendr JS Requirements
// ///////////////////////////////////////////////////////////////////////////////
var writeFile = require('toolz/src/file/writeFile')
var concat = require('toolz/src/file/concat')
var assert = require('assert')
var isEmpty = require('toolz/src/lang/isEmpty')
var isBoolean = require('toolz/src/lang/isBoolean')
var iterate = require('toolz/src/async/iterate')
var values = require('toolz/src/object/values')
var pick = require('toolz/src/object/pick')
var union = require('toolz/src/array/union')
var logger = require('../util/logger')
var getBaseDir = require('../util/getBaseDir')
var globby = require('../src/globby')
var rsync = require('./support').sync
// var modernizr = require('../nodes/customizr');
// JS settings and env variables
// ///////////////////////////////////////////////////////////////////////////////
function scriptz (fp, globals, defaults, cb) {
var env = globals.BUILD_ENV
var stage = globals.BUILD_STAGE
var flag
var src
var dest
var ext
if (env === 'development') {
if (stage === 'dev') flag = 'none'
else flag = false
if (fp) {
var keys = [getBaseDir(fp)]
if (keys == 'views') return cb(null, 'views')
var globFilez = values(pick(defaults.SCRPTfilez, keys))
if (keys == 'framework') src = globFilez
else src = globby.sync(globFilez)
dest = [defaults.paths.js, '/', keys, '.js'].join('')
concatenate(src, dest, flag, function () {
rsync('static', 'js', defaults, function () {
cb(null, 'scriptz')
})
})
} else {
var series = defaults.SCRPTfilez
iterate.each(series, function (val, key, done) {
if (key === 'framework') src = val
else src = globby.sync(val)
dest = [defaults.paths.js, '/', key, '.js'].join('')
concatenate(src, dest, flag, function () {
done(null, key)
})
}, function (err, res) {
assert.ifError(err)
rsync('static', 'js', defaults, function () {
cb(null, 'scriptz')
})
})
}
} else {
if (stage === 'test') {
flag = false
ext = '.js'
} else {
flag = true
ext = '-min.js'
}
src = union(
defaults.SCRPTfilez.framework,
globby.sync(defaults.SCRPTfilez.plugins),
globby.sync(defaults.SCRPTfilez.libs),
globby.sync(defaults.SCRPTfilez.theme)
)
dest = [defaults.paths.js, '/scripts', ext].join('')
concatenate(src, dest, flag, function () {
rsync('static', 'js', defaults, function () {
cb(null, 'scriptz')
})
})
}
}
function concatenate (src, dest, flag, cb) {
if (isEmpty(src)) return cb()
if (isBoolean(flag) && flag === true) {
var resolve = require('resolve')
var ugly = require(resolve.sync('uglify-js', {basedir: '/usr/local/lib/node_modules'}))
return writeFile(dest, ugly.minify(concat.sync(src), {
fromString: true,
output: {
comments: false
}
}).code, function (err) {
assert.ifError(err)
logger.msg(dest, 'generated')
cb()
})
} else {
return concat.async(src, dest, function (err) {
assert.ifError(err)
logger.msg(dest, 'generated')
cb()
})
}
}
module.exports = scriptz
// // Modernizr process
// // ///////////////////////////////////////////////////////////////////////////////
// function modernizr () {
// modernizr({
// "cache" : true,
// "devFile" : 'scripts/views/configs/modernizr-dev.js',
// "dest" : 'assets/js/modernizr.js',
// "options" : [
// "setClasses",
// "addTest",
// "html5printshiv",
// "testProp",
// "fnBind"
// ],
// "uglify" : false,
// "tests" : [],
// "excludeTests": [],
// "crawl" : true,
// "useBuffers": false,
// "files" : {
// "src": [
// "assets/{js,css}/*.{js,css}",
// "!assets/js/modernizr.js"
// ]
// },
// "customTests" : []
// }, function () {
// // all done!
// })
// }
| JavaScript | 0 | @@ -1011,14 +1011,22 @@
re('
-../src
+toolz/src/glob
/glo
|
4818c46256de26e3357f3e05c4d0986113a7efa8 | debug data amigo cloud | client/geocode/index.js | client/geocode/index.js | var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;
var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];
/**********tismart **********************/
var dev_amigo_token = "A:m8SOB7KwYWuuWAeYEHHjBf7U9VIZFrMuH2LLjS";
/**
* Geocode
*/
module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;
module.exports.suggestAmigo = suggestAmigo;
/**
* Geocode
*/
function geocode(address, callback) {
log('--> geocoding %s', address);
get('/geocode/' + address, function(err, res) {
if (err) {
log('<-- geocoding error %s', err);
callback(err, res);
} else {
log('<-- geocoding complete %j', res.body);
callback(null, res.body);
}
});
}
/**
* Reverse geocode
*/
function reverse(ll, callback) {
console.log("reserve ll", ll);
console.log("reserve callback", callback);
log('--> reverse geocoding %s', ll);
get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
if (err) {
log('<-- geocoding error %e', err);
callback(err, res);
} else {
log('<-- geocoding complete %j', res.body);
callback(null, res.body);
}
});
}
/**
* Suggestions!
*/
function suggestAmigo(text, callback) {
var lista_direcciones;
//get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token,
get('https://www.amigocloud.com/api/v1/me/geocoder/search?token=R:DNiePlGOMsw93cEgde88woWAQxm1xzWt7lvVXe&boundary.rect.min_lat=36.155617833819&boundary.rect.min_lon=-123.607177734375&boundary.rect.max_lat=38.826870521381&boundary.rect.max_lon=-120.701293945312&sources=osm,oa&text=' + text,
function(err, res) {
if(err) {
console.log("Error amigo cloud");
log("Amigo Cloud Response Error ->", err);
}else{
if(res.body.features) {
var lista_direcciones = res.body.features;
if (lista_direcciones.length > 0) {
callback(
null,
lista_direcciones
);
}else {
callback(true, res);
}
}
}
});
}
function suggest(text, callback) {
var bingSuggestions, nominatimSuggestions, totalSuggestions;
log('--> getting suggestion for %s', text);
get('/geocode/suggest/'+ text, function(err, res){
if (err) {
log('<-- suggestion error %s', err);
callback(err, res);
} else {
log('<-- got %s suggestions', res.body.length);
bingSuggestions = res.body;
console.log("------------API GEOCODE---------------");
console.log("res ->", res.body);
console.log("res.body ->", res);
// callback(null, res.body);
get('http://nominatim.openstreetmap.org/search' +
'?format=json&addressdetails=1&' +
'viewbox=' + southWest[0] + ',' +
northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
'&bounded=1' +
'countrycodes=us&q=' + text, function (err, nRes) {
var inside = false;
nominatimSuggestions = [];
for (var i = 0; i < nRes.body.length; i++) {
// inside = inside && (nRes.body[i].lng > southWest[0]);
// inside = inside && (nRes.body[i].lng < northEast[0]);
// inside = inside && (nRes.body[i].lat > southWest[1]);
// inside = inside && (nRes.body[i].lat < northEast[1]);
// if (inside) {
nominatimSuggestions.push(nRes.body[i]);
// }
}
console.log('======data enviada===============');
console.log(nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3)));
callback(
null,
nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3))
);
});
}
});
} | JavaScript | 0.000001 | @@ -333,16 +333,304 @@
2LLjS%22;%0A
+var url_search_amigo = %22https://www.amigocloud.com/api/v1/me/geocoder/search%22;%0Avar data_boundary = %7B%0A %22min_lat%22 : 36.155617833819,%0A %22min_lon%22 : -123.607177734375,%0A %22max_lat%22 : 38.826870521381,%0A %22max_lon%22 : -120.701293945312%0A%7D;%0A%0A%0Aconsole.log(%22data_boundary -%3E%22, data_boundary);
%0A/**%0A *
|
0568cbb652a4f6ab3d6b5a4193d24ab817655f79 | fix buildAggregatePipeline | lib/query/hypernova/buildAggregatePipeline.js | lib/query/hypernova/buildAggregatePipeline.js | import { _ } from 'meteor/underscore';
import {SAFE_DOTTED_FIELD_REPLACEMENT} from './constants';
export default function (childCollectionNode, filters, options, userId) {
let containsDottedFields = false;
const linker = childCollectionNode.linker;
const linkStorageField = linker.linkStorageField;
const collection = childCollectionNode.collection;
let pipeline = [];
if (collection.firewall) {
collection.firewall(filters, options, userId);
}
filters = cleanUndefinedLeafs(filters);
pipeline.push({$match: filters});
if (options.sort && _.keys(options.sort).length > 0) {
pipeline.push({$sort: options.sort})
}
let _id = linkStorageField;
if (linker.isMeta()) {
_id += '._id';
}
let dataPush = {
_id: '$_id'
};
_.each(options.fields, (value, field) => {
if (field.indexOf('.') >= 0) {
containsDottedFields = true;
}
const safeField = field.replace(/\./g, SAFE_DOTTED_FIELD_REPLACEMENT);
dataPush[safeField] = '$' + field
});
if (linker.isMeta()) {
dataPush[linkStorageField] = '$' + linkStorageField;
}
pipeline.push({
$group: {
_id: "$" + _id,
data: {
$push: dataPush
}
}
});
if (options.limit || options.skip) {
let $slice = ["$data"];
if (options.skip) $slice.push(options.skip);
if (options.limit) $slice.push(options.limit);
pipeline.push({
$project: {
_id: 1,
data: {$slice}
}
})
}
function cleanUndefinedLeafs(tree) {
const a = Object.assign({}, tree);
_.each(a, (value, key) => {
if (value === undefined) {
delete a[key];
}
if (!_.isArray(value) && _.isObject(value)) {
a[key] = cleanUndefinedLeafs(value);
}
})
return a;
}
return {pipeline, containsDottedFields};
} | JavaScript | 0 | @@ -1900,16 +1900,44 @@
t(value)
+ && !(value instanceof Date)
) %7B%0A
|
217d384ee10d52cdc81629e1d6346236e16fe3fa | change test | WebRTC/test/FeedbackTest.js | WebRTC/test/FeedbackTest.js |
var io = require('socket.io-client');
var ninjaSocket;
var WebdriverIO = require('webdriverio'),
browserB = WebdriverIO.remote({
host: 'ondemand.saucelabs.com',
logLevel: 'silent',
port:80,
user: 'CoderDojoDev',
key: 'd079bf09-33be-4565-aea4-f07ffd191a7d',
desiredCapabilities: {
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
browserName: 'chrome',
name: process.env.TRAVIS_JOB_NUMBER,
'public': true
}
});
var should = require('should');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
assert = require('assert');
chai.use(chaiAsPromised);
expect = chai.expect;
chai.Should();
// chaiAsPromised.transferPromiseness = browserB.transferPromiseness;
describe('test mentor feedback', function() {
this.timeout(99999999);
before(function(done) {
mentorSocket = io('https://127.0.0.1:8000',{forceNew: true});
ninjaSocket = io('https://127.0.0.1:8000',{forceNew: true});
browserB
.init(done)
.windowHandleSize({width: 1300, height: 1000})
.url('https://127.0.0.1:8000/sign_in?url=%2FMentor')
.then(function(){
ninjaSocket.emit('iceRequest', {mentor:'Test Ninja'});
}).call(done);
});
after(function() {
mentorSocket.disconnect();
ninjaSocket.disconnect();
});
describe('static', function() {
it('should fill email and password and login as mentor', function(done) {
browserB .setValue('input[name="email"]', 'jj')
.setValue('input[name="password"]', '123')
.pause(1000)
.click('.btn').pause(1000)
.getTitle().then(function(title){
title.should.equal('Mentor Toolbar');
})
.call(done);
});
it('ninja should request', function(done) {
browserB.getTitle().then(function(){
ninjaSocket.emit('requestHelp');
}).pause(1000)
.getHTML('#helpQueue .btn',false).then(function(ele){
ele.should.exist;
})
.call(done);
});
it('mentor should answer', function(done) {
browserB.click('#helpQueue .btn').pause(1000)
.getHTML('#headingThree h4 a',false).then(function(ele){
ele.should.equal('Chats');
})
.call(done);
});
it('should add video', function(done) {
ninjaSocket.emit('test_addVideo');
browserB.pause(1000)
.getHTML('#ninjaScreen',false).then(function(ele){
ele.should.exist;
})
.call(done);
});
it('should take screenshot', function(done) {
browserB.click('#takescreenShot')
.isVisible('#myCanvas').then(function(isVisible) {
isVisible.should.equal(true);
})
.call(done);
});
it('should cancel current screenshot and take a new one', function(done) {
browserB.click('#closeCanvas').pause(1000)
.isVisible('#myCanvas').then(function(isVisible) {
isVisible.should.equal(false);
})
.click('#takescreenShot').pause(1000)
.isVisible('#myCanvas').then(function(isVisible) {
isVisible.should.equal(true);
})
.call(done);
});
it('should highlight screenshot', function(done) {
ninjaSocket.emit('test_highlight');
browserB.pause(2000).getAttribute('#myCanvas', 'textContent').then(function(txtContent) {
txtContent.should.not.equal(' ');
})
.pause(1000)
.call(done);
});
it('should send out image', function(done) {
function test(data){
data.should.have.property('image');
data.should.have.property('name');
//console.log(data);
}
browserB.click('#sendscreenShot').pause(2000)
.isExisting('img.fancybox').then(function(isExisting) {
isExisting.should.equal(true);
});
//.pause(2000);
ninjaSocket.once('screenshot',test);
browserB.call(done);
});
});
describe('test mentor handler', function() {
it('should enable pointing handler', function(done) {
ninjaSocket.emit('test_addVideo');
browserB.pause(1000)
.click('#handler-option1').pause(300)
.getCssProperty('#handler-bright','display').then(function(display){
display.value.should.equal('block');
})
.call(done);
});
it('should move handler to trigger socket', function(done) {
function test(data) {
should.exist(data);
data.should.have.property('MX');
data.MX.should.not.equal(0);
data.should.have.property('MY');
data.MY.should.not.equal(0);
};
browserB.moveToObject('#handler-bright')
.buttonDown().then(function(){
ninjaSocket.once('RTPointing', test);
})
.moveToObject('#screenBox',80,60)
.buttonUp()
.call(done);
});
it('should sign out', function(done) {
browserB.click('#signOut')
.call(done);
});
it('should end the session', function(done) {
browserB.end()
.call(done);
});
});
});
| JavaScript | 0.000003 | @@ -5292,22 +5292,20 @@
handler-
-bright
+dark
','displ
@@ -5866,14 +5866,12 @@
ler-
-bright
+dark
')%0A
|
d085223a152d43369d8dc48f290bba392cfaa506 | Update rss | rss/rss.js | rss/rss.js | var request = require('request'),
FeedParser = require('feedparser'),
config = require('../server/config/config'),
Iconv = require('iconv').Iconv,
zlib = require('zlib'),
async = require('async'),
moment = require('moment'),
log4js = require('log4js');
log4js.configure(config.log4js);
log4js.setGlobalLogLevel(config.logLevel);
var db = null;
var logger = log4js.getLogger("rss");
function getUsers(criteria, resultCallback) {
db.user.find(criteria, resultCallback);
}
function getFeedDataFromUsers(users, resultCallback) {
async.eachSeries(users, function iterator(user, callback) {
if (!user || !user.keywords) return callback();
if (user.keywords.length === 0) return callback();
var updatedLastFeedDate = new Date();
updateUserLastFeedDate(user._id, updatedLastFeedDate);
fetchUserFeed(user._id, user.feeds, user.keywords, user.lastFeedDate, callback);
}, function done() {
if (resultCallback) resultCallback();
});
}
function fetchUserFeed(userId, feedArray, keywordArray, lastFeedDate, resultCallback) {
async.eachSeries(feedArray, function iterator(feed, callback) {
fetch(userId, feed, keywordArray, lastFeedDate);
callback();
}, function done() {
if (resultCallback) resultCallback();
});
}
function maybeDecompress (res, encoding) {
var decompress;
if (encoding.match(/\bdeflate\b/)) {
decompress = zlib.createInflate();
} else if (encoding.match(/\bgzip\b/)) {
decompress = zlib.createGunzip();
}
return decompress ? res.pipe(decompress) : res;
}
function maybeTranslate (res, charset) {
var iconv;
// Use iconv if its not utf8 already.
if (!iconv && charset && !/utf-*8/i.test(charset)) {
try {
iconv = new Iconv(charset, 'utf-8');
logger.info('Converting from charset %s to utf-8', charset);
iconv.on('error', done);
// If we're using iconv, stream will be the output of iconv
// otherwise it will remain the output of request
res = res.pipe(iconv);
} catch(err) {
logger.error('error: ',err);
}
}
return res;
}
function getParams(str) {
var params = str.split(';').reduce(function (params, param) {
var parts = param.split('=').map(function (part) { return part.trim(); });
if (parts.length === 2) {
params[parts[0]] = parts[1];
}
return params;
}, {});
return params;
}
function done(err) {
if (err) {
logger.error(err, err.stack);
return;
}
logger.info("rss end!");
//process.exit(); // 프로세스 죽이지 않고 계속 배치로 작업 진행
}
function makeFeedData(userId, keywordArray, post, feed, pubDate) {
var postKeywordArray = [];
var keywordPattern, feedData;
// 매칭되는 키워드 있는지 검사해서 매칭되는 키워드 postKeywordArray에 넣음
// TODO: 향후 이 부분 수정해야함!
keywordArray.forEach(function(keyword) {
keywordPattern = new RegExp(keyword, "g");
if (keywordPattern.test(post.description)) {
postKeywordArray.push(keyword);
}
});
feedData = {
user: userId.valueOf().toString(), // UserId to String
title: post.title,
description: post.description,
link: post.link,
source: feed,
categories: post.categories,
keywords: postKeywordArray,
hasKeyword: (postKeywordArray.length > 0) ? true : false,
pubDate: pubDate
};
return feedData;
}
function saveFeedData(postArray, callback) {
if (!postArray || postArray.length === 0) return callback();
db.feed.insert(postArray, function(err) {
callback(err);
});
}
function updateUserLastFeedDate(userId, lastFeedDate, callback) {
logger.info("Update user lastFeedDate: ", lastFeedDate);
db.user.update({_id:userId}, {$set:{lastFeedDate: lastFeedDate}}, function(err) {
if (callback) callback(err);
});
}
function setDB(inDB) {
db = inDB;
}
exports.setDB = setDB;
function getNeedCollections() {
return ["user", "feed"];
}
exports.getNeedCollections = getNeedCollections;
function fetch(userId, feed, keywordArray, lastFeedDate) {
// Define our streams
var req = request(feed, {timeout: 10000, pool: false});
req.setMaxListeners(50);
// Some feeds do not respond without user-agent and accept headers.
req.setHeader('user-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')
req.setHeader('accept', 'text/html,application/xhtml+xml');
var feedparser = new FeedParser();
// Define our handlers
req.on('error', done);
req.on('response', function(res) {
if (res.statusCode != 200) return logger.error("res.statusCode: ", res.statusCode);
var encoding = res.headers['content-encoding'] || 'identity'
, charset = getParams(res.headers['content-type'] || '').charset;
res = maybeDecompress(res, encoding);
res = maybeTranslate(res, charset);
res.pipe(feedparser);
});
feedparser.on('error', done);
feedparser.on('end', done);
feedparser.on('readable', function() {
var postArray = [];
var post;
while (post = this.read()) {
var lastDate = moment(lastFeedDate);
var pubDate = moment(post.pubDate);
if (lastDate.isBefore(pubDate)) {
logger.debug(post);
postArray.push(makeFeedData(userId, keywordArray, post, feed, pubDate.toDate()));
}
}
logger.info('post.length:',post.length);
saveFeedData(postArray, function(err) {
if (err) logger.error("saveFeedData err: ",err);
});
});
}
exports.fetch = fetch;
function run(resultCallback) {
async.waterfall([
function(callback){
var criteria = {};
getUsers(criteria, function(err, users) {
callback(err, users);
});
},
function(users, callback) {
logger.info("users: ", users);
getFeedDataFromUsers(users, function(err) {
callback(users, err);
});
}
], function(err){
if(err) logger.error(err);
if(resultCallback) resultCallback(err);
});
}
exports.run = run;
| JavaScript | 0 | @@ -5649,29 +5649,15 @@
post
-.length:',post.length
+:',post
);%0A
|
db7ce8e657444530d0b230527eb8dcc1f11da15b | Use new ol.style in dynamic-data example | examples/dynamic-data.js | examples/dynamic-data.js | goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.geom.MultiPoint');
goog.require('ol.layer.Tile');
goog.require('ol.shape');
goog.require('ol.source.MapQuestOpenAerial');
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuestOpenAerial()
})
],
renderer: ol.RendererHint.CANVAS,
target: 'map',
view: new ol.View2D({
center: [0, 0],
zoom: 2
})
});
map.beforeRender(function(map, frameState) {
frameState.animate = true;
return true;
});
var imageStyle = ol.shape.renderCircle(5, {
color: 'yellow'
}, {
color: 'red',
width: 1
});
var n = 200;
var omegaTheta = 30000; // Rotation period in ms
var R = 7e6;
var r = 2e6;
var p = 2e6;
map.on('postcompose', function(event) {
var render = event.getRender();
var frameState = event.getFrameState();
var theta = 2 * Math.PI * frameState.time / omegaTheta;
var coordinates = [];
var i;
for (i = 0; i < n; ++i) {
var t = theta + 2 * Math.PI * i / n;
var x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r);
var y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r);
coordinates.push([x, y]);
}
render.setImageStyle(imageStyle);
render.drawMultiPointGeometry(new ol.geom.MultiPoint(coordinates));
});
map.requestRenderFrame();
| JavaScript | 0 | @@ -216,16 +216,80 @@
rial');%0A
+goog.require('ol.style.Fill');%0Agoog.require('ol.style.Stroke');%0A
%0A%0Avar ma
@@ -658,36 +658,76 @@
e(5,
- %7B
%0A
-color: 'yellow'%0A%7D, %7B%0A
+ new ol.style.Fill(%7Bcolor: 'yellow'%7D),%0A new ol.style.Stroke(%7B
colo
@@ -735,18 +735,16 @@
: 'red',
-%0A
width:
@@ -744,18 +744,18 @@
width: 1
-%0A
%7D
+)
);%0Avar n
|
8f9fefa9f419c9817676df61f3e4535bd6d5b8a4 | Fix linter issues (#183) | res/dom.js | res/dom.js | gpf.require.define({}, function () {
"use strict";
return {
addEventsListener: function (events) {
Object.keys(events).forEach(function (eventKey) {
var eventParts = eventKey.split("@"),
eventSelector = eventParts[0],
eventName = eventParts[1],
eventHandler = events[eventKey];
if (eventSelector) {
[].slice.call(document.querySelectorAll(eventSelector)).forEach(function (oElement) {
oElement.addEventListener(eventName, eventHandler);
});
} else {
document.addEventListener(eventName, eventHandler);
}
});
}
};
});
| JavaScript | 0 | @@ -49,16 +49,248 @@
rict%22;%0A%0A
+ function _addEventsListener (selector, eventName, handler) %7B%0A %5B%5D.slice.call(document.querySelectorAll(selector)).forEach(function (oElement) %7B%0A oElement.addEventListener(eventName, handler);%0A %7D);%0A %7D%0A%0A
retu
@@ -478,22 +478,17 @@
-eventS
+s
elector
@@ -571,22 +571,17 @@
-eventH
+h
andler =
@@ -623,127 +623,16 @@
if (
-eventSelector) %7B%0A %5B%5D.slice.call(document.querySelectorAll(eventSelector)).forEach(function (oElement
+selector
) %7B%0A
@@ -651,37 +651,25 @@
- oElement.
+_
addEvent
Listener
@@ -652,32 +652,33 @@
_addEvent
+s
Listener(eventNa
@@ -662,32 +662,42 @@
dEventsListener(
+selector,
eventName, event
@@ -695,44 +695,15 @@
me,
-eventHandler);%0A %7D
+handler
);%0A
@@ -787,14 +787,9 @@
me,
-eventH
+h
andl
|
bfaca3367f4ff32acd8ff53bea6e051dcbc0805c | Change denunciation fields. | server/api/denunciation/denunciation.model.js | server/api/denunciation/denunciation.model.js | 'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var DenunciationSchema = new Schema({
name: String,
info: String,
active: Boolean
});
module.exports = mongoose.model('Denunciation', DenunciationSchema); | JavaScript | 0 | @@ -139,41 +139,82 @@
-info: String,%0A active: Boolean
+address: String,%0A date: Date,%0A hour: String,%0A description: String
%0A%7D);
@@ -283,8 +283,9 @@
Schema);
+%0A
|
4563aae50a3f4bf28dfdfc4a3e1d1be412e0305e | Change locale error to locale warning | packages/strapi-admin/admin/src/i18n.js | packages/strapi-admin/admin/src/i18n.js | /**
* i18n.js
*
* This will setup the i18n language files and locale data for your plugin.
*
*/
import { addLocaleData } from 'react-intl';
import { reduce } from 'lodash';
// Import config
import { languages } from './config/languages.json';
/**
* Try to require translation file.
*
* @param language {String}
*/
const requireTranslations = language => {
try {
return require(`./translations/${language}.json`); // eslint-disable-line global-require
} catch (error) {
console.error(`Unable to load "${language}" translation. Please make sure "${language}.json" file exists in "admin/public/app/translations" folder.`); // eslint-disable-line no-console
return false;
}
};
/**
* Try to require the language in `react-intl` locale data
* and add locale data if it has been found.
*
* @param language {String}
*/
const addLanguageLocaleData = language => {
try {
const localeData = require(`react-intl/locale-data/${language}`); // eslint-disable-line global-require
addLocaleData(localeData);
return true;
} catch (error) {
console.error(`It looks like the language "${language}" is not supported by "react-intl" module.`); // eslint-disable-line no-console
return false;
}
};
/**
* Dynamically generate `translationsMessages object`.
*/
const translationMessages = reduce(languages, (result, language) => {
const obj = result;
obj[language] = requireTranslations(language);
addLanguageLocaleData(language);
return obj;
}, {});
export {
languages,
translationMessages,
};
| JavaScript | 0.00003 | @@ -1080,23 +1080,25 @@
console.
-error(%60
+warn(%60%E2%9A%A0%EF%B8%8F
It looks
|
81f93e47e861979554c2bfb05a1700b9aff6a1c7 | Disable default error behavior on girder.login request | clients/web/src/init.js | clients/web/src/init.js | /*global girder:true*/
/*global console:true*/
'use strict';
/*
* Initialize global girder object
*/
var girder = girder || {};
/*
* Some cross-browser globals
*/
if (!window.console) {
var console = {
log: $.noop,
error: $.noop
};
}
_.extend(girder, {
models: {},
collections: {},
views: {},
apiRoot: $('#g-global-info-apiroot').text().replace(
'%HOST%', window.location.origin),
staticRoot: $('#g-global-info-staticroot').text().replace(
'%HOST%', window.location.origin),
currentUser: null,
currentToken: null,
events: _.clone(Backbone.Events),
uploadHandlers: {},
corsAuth: girder.corsAuth || false,
/**
* Constants and enums:
*/
UPLOAD_CHUNK_SIZE: 1024 * 1024 * 64, // 64MB
SORT_ASC: 1,
SORT_DESC: -1,
MONTHS: [
'January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
],
AccessType: {
NONE: -1,
READ: 0,
WRITE: 1,
ADMIN: 2
},
AssetstoreType: {
FILESYSTEM: 0,
GRIDFS: 1,
S3: 2
},
Layout: {
DEFAULT: 'default',
EMPTY: 'empty'
},
layout: 'default',
/**
* Make a request to the REST API. Bind a "done" handler to the return
* value that will be called when the response is successful. To bind a
* custom error handler, bind an "error" handler to the return promise,
* which will be executed in addition to the normal behavior of logging
* the error to the console. To override the default error handling
* behavior, pass an "error" key in your opts object; this should be done
* any time the server might throw an exception from validating user input,
* e.g. logging in, registering, or generally filling out forms.
*
* @param path The resource path, e.g. "user/login"
* @param data The form parameter object.
* @param [type='GET'] The HTTP method to invoke.
* @param [girderToken] An alternative auth token to use for this request.
*/
restRequest: function (opts) {
opts = opts || {};
var defaults = {
dataType: 'json',
type: 'GET',
error: function (error, status) {
var info;
if (error.status === 401) {
girder.events.trigger('g:loginUi');
info = {
text: 'You must log in to view this resource',
type: 'warning',
timeout: 4000,
icon: 'info'
};
} else if (error.status === 403) {
info = {
text: 'Access denied. See the console for more details.',
type: 'danger',
timeout: 5000,
icon: 'attention'
};
} else if (error.status === 0 && error.statusText === 'abort') {
/* We expected this abort, so do nothing. */
return;
} else if (error.status === 500 && error.responseJSON &&
error.responseJSON.type === 'girder') {
info = {
text: error.responseJSON.message,
type: 'warning',
timeout: 5000,
icon: 'info'
};
} else if (status === 'parsererror') {
info = {
text: 'A parser error occurred while communicating with the ' +
'server (did you use the correct value for `dataType`?). ' +
'Details have been logged in the console.',
type: 'danger',
timeout: 5000,
icon: 'attention'
};
} else {
info = {
text: 'An error occurred while communicating with the ' +
'server. Details have been logged in the console.',
type: 'danger',
timeout: 5000,
icon: 'attention'
};
}
girder.events.trigger('g:alert', info);
console.error(error.status + ' ' + error.statusText, error.responseText);
girder.lastError = error;
}
};
if (opts.path.substring(0, 1) !== '/') {
opts.path = '/' + opts.path;
}
opts.url = girder.apiRoot + opts.path;
opts = _.extend(defaults, opts);
var token = opts.girderToken ||
girder.currentToken ||
girder.cookie.find('girderToken');
if (token) {
opts.headers = opts.headers || {};
opts.headers['Girder-Token'] = token;
}
return Backbone.ajax(opts);
},
/**
* Log in to the server. If successful, sets the value of girder.currentUser
* and girder.currentToken and triggers the "g:login" and "g:login.success".
* On failure, triggers the "g:login.error" event.
*
* @param username The username or email to login as.
* @param password The password to use.
* @param cors If the girder server is on a different origin, set this
* to "true" to save the auth cookie on the current domain. Alternatively,
* you may set the global option "girder.corsAuth = true".
*/
login: function (username, password, cors) {
var auth = 'Basic ' + window.btoa(username + ':' + password);
if (cors === undefined) {
cors = girder.corsAuth;
}
return girder.restRequest({
method: 'GET',
path: '/user/authentication',
headers: {
'Girder-Authorization': auth
}
}).then(function (response) {
response.user.token = response.authToken;
girder.currentUser = new girder.models.UserModel(response.user);
girder.currentToken = response.user.token.token;
if (cors && !girder.cookie.find('girderToken')) {
// For cross-origin requests, we should write the token into
// this document's cookie also.
document.cookie = 'girderToken=' + girder.currentToken;
}
girder.events.trigger('g:login.success', response.user);
girder.events.trigger('g:login', response);
return response.user;
}, function (jqxhr) {
girder.events.trigger('g:login.error', jqxhr.status, jqxhr);
return jqxhr;
});
},
logout: function () {
return girder.restRequest({
method: 'DELETE',
path: '/user/authentication'
}).then(function () {
girder.currentUser = null;
girder.currentToken = null;
girder.events.trigger('g:login', null);
girder.events.trigger('g:logout.success');
}, function (jqxhr) {
girder.events.trigger('g:logout.error', jqxhr.status, jqxhr);
});
},
fetchCurrentUser: function () {
return girder.restRequest({
method: 'GET',
path: '/user/me'
});
}
});
/**
* The old "jade.templates" namespace is deprecated as of version 1.1, but is
* retained here for backward compatibility. It will be removed in version 2.0.
*/
/* jshint -W079 */
var jade = jade || {};
jade.templates = girder.templates;
| JavaScript | 0 | @@ -6037,32 +6037,57 @@
th%0A %7D
+,%0A error: null
%0A %7D).then
|
de84b123a87ac6aa54e4ffbd148bbafc9d389269 | update years in meta.js, use data.json temporarily | src/data/phl/meta.js | src/data/phl/meta.js | window.OpenBudget = {"data":{"meta":{
"hierarchy": ["Funding Source", "Department", "Expense Type", "Expense Subtype"],
"page_title": "City of Philadelphia Budget",
"description": "",
"h1": "City of Philadelphia",
"h2": "Operating Budget",
"data_link": "https://github.com/CityOfPhiladelphia/open-budget-data-transformer/blob/master/data/FY2014-actual.csv",
"data_title": "Download Data",
"uservoice": "",
"base_headline": "Funding Sources",
"gross_cost_label": "Expenses",
"revenue_label": "Revenues",
"currency_prefix": "$",
"overview_label": "Overview",
"deficit_label": "Deficit",
"surplus_label": "Surplus",
"data_url": "data/phl/data.json",
"cache_url": "data/phl/cache.json",
"value": {
"label": "FY 2016",
"type": "accounts",
"year": "2016"
},
"value2": {
"label": "FY 2015",
"type": "accounts",
"year": "2015"
}
}}};
| JavaScript | 0 | @@ -707,16 +707,19 @@
on%22,%0A
+ //
%22cache_
@@ -786,17 +786,17 @@
%22FY 201
-6
+7
%22,%0A
@@ -842,9 +842,9 @@
%22201
-6
+7
%22%0A
@@ -888,17 +888,17 @@
%22FY 201
-5
+6
%22,%0A
@@ -944,9 +944,9 @@
%22201
-5
+6
%22%0A
|
92d1430d5985cd866464015e0874a0e59401c573 | Fix getElementsByTagName | src/main/webapp/js/cas.js | src/main/webapp/js/cas.js | /**
* Shim for String.prototype.startsWith
* https://github.com/mathiasbynens/String.prototype.startsWith
*/
if (!String.prototype.startsWith) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch(error) {}
return result;
}());
var toString = {}.toString;
var startsWith = function(search) {
if (this == null) {
throw TypeError();
}
var string = String(this);
if (search && toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
// `ToInteger`
var pos = position ? Number(position) : 0;
if (pos != pos) { // better `isNaN`
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
// Avoid the `indexOf` call if no match is possible
if (searchLength + start > stringLength) {
return false;
}
var index = -1;
while (++index < searchLength) {
if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
return false;
}
}
return true;
};
if (defineProperty) {
defineProperty(String.prototype, 'startsWith', {
'value': startsWith,
'configurable': true,
'writable': true
});
} else {
String.prototype.startsWith = startsWith;
}
}());
}
(function() {
/**
* Utility for Cookies
* @namespace cookies
* @author Nisarg Jhaveri <nisarg.jhaveri@students.iiit.ac.in>
*
* Originally written for Felicity '15 website
*/
var cookies = {
/**
* Add or update cookie
*
* @memberof cookies
*
* @param {string} name - Name of the cookie
* @param {string} value - Value to be set
* @param {number} expiry - Expiry of cookie in hours (i.e expire after this many hours)
* @param {string} [path] - Path for the cookie
*/
set: function( name, value, expiry, path ) {
var ex = new Date();
ex.setTime( ex.getTime() + ( expiry * 60 * 60 * 1000 ) );
var expires = "expires=" + ex.toUTCString();
document.cookie = name + "=" + value + "; " + expires + ( path ? '; path=' + path : '' );
},
/**
* Get required cookie value
*
* @memberof cookies
*
* @param {string} name - Name of the cookie
*
* @returns {string} Value of the cookie
*/
get: function( name ) {
name = name + '=';
var cookieList = document.cookie.split( ';' );
var cookie;
for ( cookie in cookieList ) {
cookie = cookieList[cookie].trim();
if ( cookie.substr( 0, name.length ) == name ) {
return cookie.substr( name.length );
}
}
},
/**
* Remove a cookie
*
* @memberof cookies
*
* @param {string} name - Name of the cookie
*/
remove: function ( name ) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
};
var areCookiesDisabled = function () {
cookies.set('testCookie', 'true', 1);
var value = cookies.get('testCookie');
if (value !== undefined) {
cookies.remove('testCookie');
return false;
}
return true;
};
var setupEmailAutocomplete = function () {
var element = document.getElementsByTagName('username')[0];
var emailDomains = [
'iiit.ac.in',
'students.iiit.ac.in',
'research.iiit.ac.in',
];
var oldValue = '';
var autoCompleteDomainName = function(e) {
var parts = element.value.split('@');
var username = parts[0] || '';
var newValue = parts[1] || '';
if (newValue && newValue.length > oldValue.length) {
var allowed = emailDomains.filter(function(domain) {
return domain.startsWith(newValue);
});
if (allowed.length == 1) {
var domain = allowed[0];
var partToAdd = domain.replace(newValue, '');
element.value = username + '@' + domain;
element.focus();
setTimeout(function() {
element.setSelectionRange(
element.value.length - partToAdd.length,
element.value.length
);
}, 0);
}
}
oldValue = newValue;
};
var setOldValue = function () {
oldValue = element.value.split('@')[1] || '';
};
element.addEventListener('input', autoCompleteDomainName);
element.addEventListener('change', setOldValue);
element.addEventListener('focus', setOldValue);
element.addEventListener('click', setOldValue);
element.focus();
};
var setupCheckForCapslock = function () {
var capslockOnMessage = document.getElementById('capslock-on');
document
.getElementById('password')
.addEventListener('keypress', function(e) {
var s = String.fromCharCode( e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
capslockOnMessage.style.display = 'inline';
} else {
capslockOnMessage.style.display = 'none';
}
});
};
var onLoad = function() {
if (areCookiesDisabled()) {
document.getElementById('cookiesDisabled').style.display = 'block';
}
setupEmailAutocomplete();
setupCheckForCapslock();
};
window.addEventListener('load', onLoad);
})();
| JavaScript | 0.997049 | @@ -3882,18 +3882,12 @@
ment
-s
By
-TagName
+Id
('us
@@ -3894,19 +3894,16 @@
ername')
-%5B0%5D
;%0A
|
00618e7609de0840ad25a3d692e97bff82fed776 | Deploy fix. | app/models/User.js | app/models/User.js | 'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
},
fullName: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
unique: false,
},
updatedAt: {
type: Date,
required: true,
},
createdAt: {
type: Date,
required: true,
},
stats: {
type: Schema.Types.ObjectId,
ref: 'UserStats',
},
gameIds: [{
type: Schema.Types.ObjectId,
ref: 'Game',
}],
friendIds: [{
type: Schema.Types.ObjectId,
ref: 'Friend',
}],
comments: [{
type: Schema.Types.ObjectId,
ref: 'Comment',
}],
},
{
collection: 'users',
});
UserSchema.createIndex({ email: 1 }, { sparse: true });
module.exports = mongoose.model('User', UserSchema);
| JavaScript | 0 | @@ -858,15 +858,9 @@
ema.
-createI
+i
ndex
|
cb59f4e41f8b8104d4b3ab0c9e627e76de9554a4 | Update cmdline.js | examples/node/cmdline.js | examples/node/cmdline.js | // Copyright 2011 Splunk, Inc.
//
// 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.
(function() {
var path = require('path');
var fs = require('fs');
var commander = require('../../contrib/commander');
var utils = require('../../lib/utils');
var DEFAULTS_PATHS = [
process.env.HOME || process.env.HOMEPATH,
path.resolve(__dirname, "..")
];
var readDefaultsFile = function(path, defaults) {
var contents = fs.readFileSync(path, "utf8") || "";
var lines = contents.split("\n") || [];
for(var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (line !== "" && !utils.startsWith(line, "#")) {
var parts = line.split("=");
var key = parts[0].trim();
var value = parts[1].trim();
defaults[key] = value;
console.log(key, value);
}
}
};
var getDefaults = function() {
var defaults = {};
for(var i = 0; i < DEFAULTS_PATHS.length; i++) {
var defaultsPath = path.join(DEFAULTS_PATHS[i], ".splunkrc");
if (fs.existsSync(defaultsPath)) {
readDefaultsFile(defaultsPath, defaults);
}
}
return defaults;
};
module.exports.create = function() {
var parser = new commander.Command();
var parse = parser.parse;
parser.password = undefined;
parser
.option('-u, --username <username>', "Username to login with", undefined, true)
.option('--password <password>', "Username to login with", undefined, false)
.option('--scheme <scheme>', "Scheme to use", "https", false)
.option('--host <host>', "Hostname to use", "localhost", false)
.option('--port <port>', "Port to use", 8089, false)
.option('--version <version>', "Which version to use", "4", false);
parser.parse = function(argv) {
argv = (argv || []).slice(2);
var defaults = getDefaults();
for(var key in defaults) {
if (defaults.hasOwnProperty(key) && argv.indexOf("--" + key) < 0) {
var value = defaults[key];
argv.unshift(value);
argv.unshift("--" + key.trim());
}
}
argv.unshift("");
argv.unshift("");
var cmdline = parse.call(parser, argv);
return cmdline;
};
parser.add = function(commandName, description, args, flags, required_flags, onAction) {
var opts = {};
flags = flags || [];
var command = parser.command(commandName + (args ? " " + args : "")).description(description || "");
// For each of the flags, add an option to the parser
for(var i = 0; i < flags.length; i++) {
var required = required_flags.indexOf(flags[i]) >= 0;
var option = "<" + flags[i] + ">";
command.option("--" + flags[i] + " " + option, "", undefined, required);
}
command.action(function() {
var args = utils.toArray(arguments);
args.unshift(commandName);
onAction.apply(null, args);
});
};
return parser;
};
})(); | JavaScript | 0.000001 | @@ -1415,49 +1415,8 @@
ue;%0A
- console.log(key, value);%0A
|
91d8a884e1f630648596af7ac83e8c95b75edff3 | update examples | src/docs/examples.js | src/docs/examples.js | export default {
SimpleLineChart: '//jsfiddle.net/x1yoboc7/612/embedded/result,js,css,html,resources/',
TinyLineChart: '//jsfiddle.net/bc5kbskj/embedded/result,js,css,html,resources/',
VerticalLineChart: '//jsfiddle.net/j1Le1dLe/embedded/result,js,css,html,resources/',
BiaxialLineChart: '//jsfiddle.net/j1Le1dLe/embedded/result,js,css,html,resources/',
CustomizedDotLineChart: '//jsfiddle.net/h475hoe0/embedded/result,js,css,html,resources/',
CustomizedLabelLineChart: '//jsfiddle.net/x7dvL69z/embedded/result,js,css,html,resources/',
LineChartWithReferenceLines: '//jsfiddle.net/ymq96sty/embedded/result,js,css,html,resources/',
DashedLineChart: '//jsfiddle.net/349rr8ap/embedded/result,js,css,html,resources/',
LineChartWithXAxisPading: '//jsfiddle.net/3gttvdLw/embedded/result,js,css,html,resources/',
VerticalLineChartWithSpecifiedDomain: '//jsfiddle.net/4kcjsajd/embedded/result,js,css,html,resources/',
LineChartConnectNulls: '//jsfiddle.net/zs8g2Led/embedded/result,js,css,html,resources/',
SynchronizedLineChart: '//jsfiddle.net/4vjan28o/embedded/result,js,css,html,resources/',
SimpleAreaChart: '//jsfiddle.net/ktwfp03m/embedded/result,js,css,html,resources/',
StackedAreaChart: '//jsfiddle.net/t41dctho/embedded/result,js,css,html,resources/',
TinyAreaChart: '//jsfiddle.net/2zy0c1y0/embedded/result,js,css,html,resources/',
PercentAreaChart: '//jsfiddle.net/q1u0p6m6/embedded/result,js,css,html,resources/',
CardinalAreaChart: '//jsfiddle.net/pz3167kg/embedded/result,js,css,html,resources/',
AreaChartConnectNulls: '//jsfiddle.net/5dL4vd6u/embedded/result,js,css,html,resources/',
SynchronizedAreaChart: '//jsfiddle.net/am4yrshm/embedded/result,js,css,html,resources/',
TinyBarChart: '//jsfiddle.net/aougnz8t/embedded/result,js,css,html,resources/',
SimpleBarChart: '//jsfiddle.net/qbmg1567/embedded/result,js,css,html,resources/',
StackedBarChart: '//jsfiddle.net/4mr2mx7c/embedded/result,js,css,html,resources/',
MixBarChart: '//jsfiddle.net/fy5uotpt/embedded/result,js,css,html,resources/',
CustomShapeBarChart: '//jsfiddle.net/m65amscw/embedded/result,js,css,html,resources/',
PositiveAndNegativeBarChart: '//jsfiddle.net/er4bds08/embedded/result,js,css,html,resources/',
BrushBarChart: '//jsfiddle.net/wn4jhdu5/embedded/result,js,css,html,resources/',
BarChartWithCustomizedEvent: '//jsfiddle.net/prwg1hLs/embedded/result,js,css,html,resources/',
BarChartWithMinHeight: '//jsfiddle.net/d1kw32qd/embedded/result,js,css,html,resources/',
BarChartStackedBySign: '//jsfiddle.net/965a4kz2/embedded/result,js,css,html,resources/',
BiaxialBarChart: '//jsfiddle.net/hdks6k6x/embedded/result,js,css,html,resources/',
LineBarAreaComposedChart: '//jsfiddle.net/huLyxqLq/embedded/result,js,css,html,resources/',
VerticalComposedChart: '//jsfiddle.net/629nzexh/embedded/result,js,css,html,resources/',
SameDataComposedChart: '//jsfiddle.net/xedrcqeL/embedded/result,js,css,html,resources/',
ComposedChartWithAxisLabels: '//jsfiddle.net/6sp2ejx6/embedded/result,js,css,html,resources/',
SimpleScatterChart: '//jsfiddle.net/zdhvvt2e/embedded/result,js,css,html,resources/',
ThreeDimScatterChart: '//jsfiddle.net/tbgdjnqp/embedded/result,js,css,html,resources/',
JointLineScatterChart: '//jsfiddle.net/7ek2qdy4/embedded/result,js,css,html,resources/',
TwoLevelPieChart: '//jsfiddle.net/44huhska/embedded/result,js,css,html,resources/',
StraightAnglePieChart: '//jsfiddle.net/k158nL5c/embedded/result,js,css,html,resources/',
TwoSimplePieChart: '//jsfiddle.net/sj0cfqc8/embedded/result,js,css,html,resources/',
CustomActiveShapePieChart: '//jsfiddle.net/pwpLb0e7/embedded/result,js,css,html,resources/',
PieChartWithCustomizedLabel: '//jsfiddle.net/2rt6rj2h/embedded/result,js,css,html,resources/',
PieChartWithPaddingAngle: '//jsfiddle.net/g8oyg8rL/embedded/result,js,css,html,resources/',
SimpleRadarChart: '//jsfiddle.net/5jkcLqv4/embedded/result,js,css,html,resources/',
SpecifiedDomainRadarChart: '//jsfiddle.net/fv3Leepv/embedded/result,js,css,html,resources/',
SimpleTreemap: '//jsfiddle.net/f07jao0m/embedded/result,js,css,html,resources/',
CustomContentTreemap: '//jsfiddle.net/q9wtzvod/embedded/result,js,css,html,resources/',
SimpleRadialBarChart: '//jsfiddle.net/c3wah6je/embedded/result,js,css,html,resources/',
CustomContentOfTooltip: '//jsfiddle.net/eewg0dea/embedded/result,js,css,html,resources/',
AreaResponsiveContainer: '//jsfiddle.net/4zja5eo0/embedded/result,js,css,html,resources/',
ComposedResponsiveContainer: '//jsfiddle.net/gzh5krkv/embedded/result,js,css,html,resources/',
PieResponsiveContainer: '//jsfiddle.net/svrquh32/embedded/result,js,css,html,resources/',
LegendEffectOpacity: '//jsfiddle.net/z9orjuww/embedded/result,js,css,html,resources/',
};
| JavaScript | 0.000001 | @@ -3644,16 +3644,19 @@
wpLb0e7/
+49/
embedded
|
f4dcc08de3f6551960cc05e5204cd32ecb2f76e5 | make hid_generic_inout tester have reportLength-sized buffer, since some OSes need that | examples/device/hid_generic_inout/hid_test.js | examples/device/hid_generic_inout/hid_test.js | var HID = require('node-hid');
var devices = HID.devices();
var deviceInfo = devices.find( function(d) {
var isNRF = d.vendorId===0Xcafe && d.productId===0X4004;
return isNRF;
});
if( deviceInfo ) {
console.log(deviceInfo)
var device = new HID.HID( deviceInfo.path );
device.on("data", function(data) {console.log(data)});
device.on("error", function(err) {console.log(err)});
setInterval(function () {
device.write([0x00, 0x01, 0x01, 0x05, 0xff, 0xff]);
},500)
}
| JavaScript | 0 | @@ -181,16 +181,36 @@
RF;%0A%7D);%0A
+var reportLen = 64;%0A
if( devi
@@ -326,16 +326,17 @@
(data) %7B
+
console.
@@ -343,17 +343,35 @@
log(data
-)
+.toString('hex'));
%7D);%0A%0A%09de
@@ -456,57 +456,131 @@
%7B%0A%09%09
-device.write(%5B0x00, 0x01, 0x01, 0x05, 0xff, 0xff%5D
+var buf = Array(reportLen);%0A%09%09for( var i=0; i%3Cbuf.length; i++) %7B%0A%09%09%09buf%5Bi%5D = 0x30 + i; // 0x30 = '0'%0A%09%09%7D%0A%09%09device.write(buf
);%0A%09
|
cf93d0eb073a184ee06c2aa56d16386e2e074947 | Clean up config, only build once | src/configPassthrough.js | src/configPassthrough.js | import fs from 'fs'
import * as babel from 'babel-core'
import _eval from 'eval'
import babelConfig from './babelConfig'
import log from './log'
const configFile = 'bastion.conf.js'
export default function configPassthrough (name, config) {
if (fileExists(configFile)) {
log.verbose('found config file')
const source = babel.transformFileSync(configFile, babelConfig(true)).code
const fns = _eval(source, configFile, {}, true)
if (typeof fns[name] === 'function') {
log.verbose('found config function for %s', name)
return fns[name](config)
} else {
log.verbose('no config function four %s', name)
}
} else {
log.verbose('no config file found')
}
return config
}
function fileExists (path) {
try {
fs.accessSync(path, fs.F_OK)
return true
} catch (e) {
return false
}
}
| JavaScript | 0 | @@ -156,14 +156,27 @@
figF
-ile =
+ns = readConfigFns(
'bas
@@ -188,16 +188,17 @@
conf.js'
+)
%0A%0Aexport
@@ -260,249 +260,149 @@
if (
-fileExists(configFile)) %7B%0A log.verbose('found config file')%0A%0A const source = babel.transformFileSync(configFile, babelConfig(true)).code%0A const fns = _eval(source, configFile, %7B%7D, true)%0A%0A if (typeof fns%5Bname%5D === 'function')
+typeof configFns%5Bname%5D === 'function') %7B%0A log.verbose('found config function for %25s', name)%0A return configFns%5Bname%5D(config)%0A %7D else
%7B%0A
-
@@ -406,37 +406,34 @@
log.verbose('
-found
+no
config function
@@ -427,32 +427,33 @@
nfig function fo
+u
r %25s', name)%0A%0A
@@ -449,21 +449,21 @@
, name)%0A
-%0A
+ %7D%0A%0A
return
@@ -467,41 +467,88 @@
urn
-fns%5Bname%5D(config)%0A %7D else
+config%0A%7D%0A%0Afunction readConfigFns (configFile) %7B%0A if (fileExists(configFile))
%7B%0A
-
@@ -552,34 +552,37 @@
log.verbose('
-no
+found
config function
@@ -578,37 +578,154 @@
ig f
-unction four %25s', name)%0A %7D
+ile %25s', configFile)%0A const source = babel.transformFileSync(configFile, babelConfig(true)).code%0A return _eval(source, configFile, %7B%7D, true)
%0A %7D
@@ -773,16 +773,32 @@
ound
-')%0A %7D%0A%0A
+ at %25s', configFile)%0A%0A
re
@@ -794,38 +794,38 @@
le)%0A%0A return
-config
+%7B%7D%0A %7D
%0A%7D%0A%0Afunction fil
|
178ed3e5f9c6b39f55c79b39c2f2f24c09578489 | add description for #1245 | examples/js/cell-edit/cell-edit-hook-table.js | examples/js/cell-edit/cell-edit-hook-table.js | /* eslint max-len: 0 */
/* eslint no-alert: 0 */
/* eslint guard-for-in: 0 */
/* eslint no-unused-vars: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
function onAfterSaveCell(row, cellName, cellValue) {
alert(`Save cell ${cellName} with value ${cellValue}`);
let rowStr = '';
for (const prop in row) {
rowStr += prop + ': ' + row[prop] + '\n';
}
alert('Thw whole row :\n' + rowStr);
}
function onBeforeSaveCell(row, cellName, cellValue) {
// You can do any validation on here for editing value,
// return false for reject the editing
return true;
}
const cellEditProp = {
mode: 'click',
blurToSave: true,
beforeSaveCell: onBeforeSaveCell, // a hook for before saving cell
afterSaveCell: onAfterSaveCell // a hook for after saving cell
};
export default class BlurToSaveTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } cellEdit={ cellEditProp }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
| JavaScript | 0 | @@ -905,16 +905,672 @@
rue;%0A%7D%0A%0A
+function onBeforeSaveCellAsync(row, cellName, cellValue, done) %7B%0A // if your validation is async, for example: you want to pop a confirm dialog for user to confim%0A // in this case, react-bootstrap-table pass a callback function to you%0A // you are supposed to call this callback function with a bool value to perfom if it is valid or not%0A // in addition, you should return 1 to tell react-bootstrap-table this is a async operation.%0A%0A // I use setTimeout to perform an async operation.%0A // setTimeout(() =%3E %7B%0A // done(true); // it's ok to save :)%0A // done(false); // it's not ok to save :(%0A // %7D, 3000);%0A // return 1; // please return 1%0A%7D%0A%0A
const ce
|
09620220d89d5ee702e2d7a5f724cb1b09bb6b71 | include user validations | app/models/user.js | app/models/user.js | import Ember from 'ember';
import DS from 'ember-data';
import ENV from 'bracco/config/environment';
import { validator, buildValidations } from 'ember-cp-validations';
const Validations = buildValidations({
// provider: [
// validator('presence', {
// presence: true,
// ignoreBlank: true,
// disabled: Ember.computed('model', function() {
// console.log(['staff_admin', 'staff_user', 'user'].includes(this.get('model').get('role_id')))
// return ['staff_admin', 'staff_user', 'user'].includes(this.get('model').get('role_id'));
// })
// })
// ],
// client: [
// validator('presence', {
// presence: true,
// ignoreBlank: true,
// disabled: Ember.computed('model', function() {
// return ['client_admin', 'client_user'].includes(this.get('model').get('role_id'));
// })
// })
// ]
});
export default DS.Model.extend(Validations, {
provider: DS.belongsTo('provider', {
async: false
}),
client: DS.belongsTo('client', {
async: false
}),
role: DS.belongsTo('role', {
async: false
}),
sandbox: DS.belongsTo('sandbox', {
async: true
}),
givenNames: DS.attr('string'),
familyName: DS.attr('string'),
name: DS.attr('string'),
uid: DS.attr('string'),
orcid: DS.attr('string'),
github: DS.attr('string'),
email: DS.attr('string'),
isActive: DS.attr('boolean'),
created: DS.attr('date'),
updated: DS.attr('date'),
identifier: Ember.computed('id', function() {
return ENV.ORCID_URL + '/' + this.get('id');
})
});
| JavaScript | 0.000001 | @@ -203,19 +203,16 @@
ions(%7B%0A
- //
provide
@@ -213,27 +213,24 @@
rovider: %5B%0A
- //
validator
@@ -237,35 +237,32 @@
('presence', %7B%0A
- //
presence: t
@@ -260,39 +260,36 @@
esence: true,%0A
-//
-
ignoreBlank: tru
@@ -284,35 +284,32 @@
reBlank: true,%0A
- //
disabled: E
@@ -349,122 +349,38 @@
%7B%0A
- //
-console.log(%5B'staff_admin', 'staff_user', 'user'%5D.includes(this.get('model').get('role_id')))%0A //
+return true;%0A
+ //
ret
@@ -458,35 +458,32 @@
t('role_id'));%0A
- //
%7D)%0A // %7D
@@ -479,29 +479,20 @@
%7D)%0A
- //
%7D)%0A
- //
%5D,%0A
- //
cli
@@ -499,19 +499,16 @@
ent: %5B%0A
- //
valid
@@ -523,27 +523,24 @@
esence', %7B%0A
- //
presenc
@@ -545,27 +545,24 @@
nce: true,%0A
- //
ignoreB
@@ -574,19 +574,16 @@
true,%0A
- //
dis
@@ -632,16 +632,37 @@
%7B%0A
-//
+return true;%0A //
ret
@@ -742,19 +742,16 @@
id'));%0A
- //
%7D)%0A
@@ -756,20 +756,14 @@
)%0A
-//
-
%7D)%0A
- //
%5D%0A%7D
|
82c0a955983dd02d1d5fbb886dadda83ec9cc83c | make isAdmin attribute of user modifiable by admin (#2678) | app/models/user.js | app/models/user.js | import { or } from '@ember/object/computed';
import { computed } from '@ember/object';
import { on } from '@ember/object/evented';
import { inject as service } from '@ember/service';
import attr from 'ember-data/attr';
import ModelBase from 'open-event-frontend/models/base';
import { hasMany } from 'ember-data/relationships';
import { toString } from 'lodash';
export default ModelBase.extend({
authManager: service(),
email : attr('string'),
password : attr('string'),
isVerified : attr('boolean', { readOnly: true }),
isSuperAdmin : attr('boolean', { readOnly: true }),
isAdmin : attr('boolean', { readOnly: true }),
isUserOrganizer : attr('boolean'),
isUserCoorganizer : attr('boolean'),
isUserTrackOrganizer : attr('boolean'),
isUserModerator : attr('boolean'),
isUserRegistrar : attr('boolean'),
isSalesAdmin : attr('boolean'),
isMarketer : attr('boolean'),
wasRegisteredWithOrder : attr('boolean'),
firstName : attr('string'),
lastName : attr('string'),
details : attr('string'),
contact : attr('string'),
avatarUrl : attr('string'),
iconImageUrl : attr('string'),
smallImageUrl : attr('string'),
thumbnailImageUrl : attr('string'),
originalImageUrl : attr('string'),
facebookUrl : attr('string'),
instagramUrl : attr('string'),
twitterUrl : attr('string'),
googlePlusUrl : attr('string'),
facebookId: attr('string', { readOnly: true }),
createdAt : attr('moment', { readOnly: true }),
deletedAt : attr('moment'),
lastAccessedAt : attr('moment', { readOnly: true }),
status: computed('lastAccessedAt', 'deletedAt', function() {
if (this.get('deletedAt') == null) {
if (this.get('lastAccessedAt') == null) {
return 'inactive';
}
return ((new Date().getMonth() - new Date(this.get('lastAccessedAt')).getMonth() <= 12) ? 'active' : 'inactive');
} else {
return 'deleted';
}
}),
isAnAdmin: or('isSuperAdmin', 'isAdmin'),
/**
* Relationships
*/
emailNotifications : hasMany('email-notification'),
notifications : hasMany('notification'),
orders : hasMany('order'),
events : hasMany('event', { inverse: 'user' }),
sessions : hasMany('session'),
invoice : hasMany('event-invoice'),
attendees : hasMany('attendee'),
speakers : hasMany('speaker'),
discountCodes : hasMany('discount-code'),
accessCodes : hasMany('access-code'),
organizerEvents : hasMany('event'),
coorganizerEvents : hasMany('event'),
trackOrganizerEvents : hasMany('event'),
registrarEvents : hasMany('event'),
moderatorEvents : hasMany('event'),
marketerEvents : hasMany('event'),
salesAdminEvents : hasMany('event'),
_didUpdate: on('didUpdate', function(user) {
if (toString(user.id) === toString(this.get('authManager.currentUser.id'))) {
user = this.get('store').peekRecord('user', user.id);
this.get('authManager').persistCurrentUser(user);
}
})
});
| JavaScript | 0 | @@ -674,36 +674,16 @@
boolean'
-, %7B readOnly: true %7D
),%0A isU
|
e2a8899cd0f8a25aa7a2bddfe9f564fac51320b5 | Fix whitespaces | src/constants/actions.js | src/constants/actions.js | 'use strict';
const ACTIONS = [
{
name: 'findOne',
type: 'find',
multiple: false,
},
{
name: 'findMany',
type: 'find',
multiple: true,
},
{
name: 'createOne',
type: 'create',
multiple: false,
},
{
name: 'createMany',
type: 'create',
multiple: true,
},
{
name: 'replaceOne',
type: 'replace',
multiple: false,
},
{
name: 'replaceMany',
type: 'replace',
multiple: true,
},
{
name: 'updateOne',
type: 'update',
multiple: false,
},
{
name: 'updateMany',
type: 'update',
multiple: true,
},
{
name: 'upsertOne',
type: 'upsert',
multiple: false,
},
{
name: 'upsertMany',
type: 'upsert',
multiple: true,
},
{
name: 'deleteOne',
type: 'delete',
multiple: false,
},
{
name: 'deleteMany',
type: 'delete',
multiple: true,
},
];
module.exports = {
ACTIONS,
};
| JavaScript | 0.999999 | @@ -25,28 +25,24 @@
IONS = %5B%0A %7B
-%0A
name: 'find
@@ -42,28 +42,24 @@
: 'findOne',
-%0A
type: 'find
@@ -52,36 +52,32 @@
', type: 'find',
-%0A
multiple: false
@@ -72,38 +72,31 @@
tiple: false
-,%0A
%7D,%0A %7B
-%0A
name: 'find
@@ -97,28 +97,24 @@
'findMany',
-%0A
type: 'find
@@ -115,20 +115,16 @@
'find',
-%0A
multipl
@@ -126,38 +126,31 @@
ltiple: true
-,%0A
%7D,%0A %7B
-%0A
name: 'crea
@@ -148,36 +148,32 @@
me: 'createOne',
-%0A
type: 'create',
@@ -164,36 +164,32 @@
type: 'create',
-%0A
multiple: false
@@ -184,38 +184,31 @@
tiple: false
-,%0A
%7D,%0A %7B
-%0A
name: 'crea
@@ -207,36 +207,32 @@
e: 'createMany',
-%0A
type: 'create',
@@ -227,28 +227,24 @@
e: 'create',
-%0A
multiple: t
@@ -242,38 +242,31 @@
ltiple: true
-,%0A
%7D,%0A %7B
-%0A
name: 'repl
@@ -269,28 +269,24 @@
replaceOne',
-%0A
type: 'repl
@@ -282,36 +282,32 @@
type: 'replace',
-%0A
multiple: false
@@ -302,38 +302,31 @@
tiple: false
-,%0A
%7D,%0A %7B
-%0A
name: 'repl
@@ -330,28 +330,24 @@
eplaceMany',
-%0A
type: 'repl
@@ -351,20 +351,16 @@
eplace',
-%0A
multipl
@@ -362,38 +362,31 @@
ltiple: true
-,%0A
%7D,%0A %7B
-%0A
name: 'upda
@@ -388,28 +388,24 @@
'updateOne',
-%0A
type: 'upda
@@ -400,36 +400,32 @@
type: 'update',
-%0A
multiple: false
@@ -420,38 +420,31 @@
tiple: false
-,%0A
%7D,%0A %7B
-%0A
name: 'upda
@@ -443,36 +443,32 @@
e: 'updateMany',
-%0A
type: 'update',
@@ -463,28 +463,24 @@
e: 'update',
-%0A
multiple: t
@@ -478,38 +478,31 @@
ltiple: true
-,%0A
%7D,%0A %7B
-%0A
name: 'upse
@@ -504,28 +504,24 @@
'upsertOne',
-%0A
type: 'upse
@@ -516,36 +516,32 @@
type: 'upsert',
-%0A
multiple: false
@@ -536,38 +536,31 @@
tiple: false
-,%0A
%7D,%0A %7B
-%0A
name: 'upse
@@ -563,28 +563,24 @@
upsertMany',
-%0A
type: 'upse
@@ -583,20 +583,16 @@
upsert',
-%0A
multipl
@@ -598,30 +598,23 @@
le: true
-,%0A
%7D,%0A %7B
-%0A
name: '
@@ -624,20 +624,16 @@
eteOne',
-%0A
type: '
@@ -632,36 +632,32 @@
type: 'delete',
-%0A
multiple: false
@@ -660,22 +660,15 @@
alse
-,%0A
%7D,%0A %7B
-%0A
nam
@@ -683,20 +683,16 @@
teMany',
-%0A
type: '
@@ -703,12 +703,8 @@
te',
-%0A
mul
@@ -714,19 +714,16 @@
le: true
-,%0A
%7D,%0A%5D;%0A%0A
|
cc134a297821555c5e1a4c5e797ed605e4a38c24 | add default email for author | src/containers/Author.js | src/containers/Author.js | import { connect } from 'react-redux'
import { denormalizeArticles } from '../utils/denormalize-articles'
import AuthorCollection from '../components/author-page/author-collection'
import AuthorData from '../components/author-page/author-data'
import Helmet from 'react-helmet'
import loggerFactory from '../logger'
import PropTypes from 'prop-types'
import React from 'react'
import Sponsor from '../components/Sponsor'
import siteMeta from '../constants/site-meta'
// @twreporter
import { replaceGCSUrlOrigin } from '@twreporter/core/lib/utils/storage-url-processor'
import twreporterRedux from '@twreporter/redux'
// lodash
import get from 'lodash/get'
const {
fetchAuthorCollectionIfNeeded,
fetchAuthorDetails,
} = twreporterRedux.actions
const _ = {
get,
}
const authorDefaultImg = {
url: '/asset/author-default-img.svg',
width: 500,
height: 500,
}
const logger = loggerFactory.getLogger()
class Author extends React.Component {
static propTypes = {
author: PropTypes.object,
collections: PropTypes.arrayOf(PropTypes.object),
collectionMeta: PropTypes.shape({
hasMore: PropTypes.bool.isRequired,
isFetching: PropTypes.bool.isRequired,
currentPage: PropTypes.number.isRequired,
totalResults: PropTypes.number,
}),
authorIsFull: PropTypes.bool,
fetchAuthorCollectionIfNeeded: PropTypes.func,
fetchAuthorDetails: PropTypes.func,
}
static defaultProps = {
totalResults: 0,
author: {},
collections: [],
}
componentDidMount() {
const authorId = _.get(this.props, 'match.params.authorId')
if (authorId) {
this.fetchAuthorCollectionIfNeededWithCatch(authorId)
const { authorIsFull } = this.props
if (!authorIsFull) {
return this.fetchAuthorDetailsWithCatch(authorId)
}
}
}
fetchAuthorCollectionIfNeededWithCatch = authorId => {
return (
this.props
.fetchAuthorCollectionIfNeeded(authorId)
// TODO render alter message
.catch(failAction => {
logger.errorReport({
report: _.get(failAction, 'payload.error'),
message: `Error to fetch the posts of the author (id: '${authorId}').`,
})
})
)
}
fetchAuthorDetailsWithCatch = authorId => {
return (
this.props
.fetchAuthorDetails(authorId)
// TODO render alter message
.catch(failAction => {
logger.errorReport({
report: _.get(failAction, 'payload.error'),
message: `Error to fetch description of the author (id: '${authorId}').`,
})
})
)
}
handleLoadmore = () => {
const authorId = _.get(this.props, 'author.id')
return this.fetchAuthorCollectionIfNeededWithCatch(authorId)
}
render() {
const { author, collections, collectionMeta } = this.props
const fullTitle = author.name + siteMeta.name.separator + siteMeta.name.full
const canonical = `${siteMeta.urlOrigin}/authors/${author.id}`
const pureTextBio = author.bio ? author.bio.replace(/<[^>]*>?/gm, '') : '' // pure text only
return (
<React.Fragment>
<Helmet
title={fullTitle}
link={[{ rel: 'canonical', href: canonical }]}
meta={[
{ name: 'description', content: pureTextBio },
{ name: 'twitter:title', content: fullTitle },
{ name: 'twitter:description', content: pureTextBio },
{ name: 'twitter:image', content: siteMeta.ogImage.url },
{ name: 'twitter:card', content: 'summary' },
{ property: 'og:title', content: fullTitle },
{ property: 'og:description', content: pureTextBio },
{ property: 'og:image', content: siteMeta.ogImage.url },
{ property: 'og:image:width', content: siteMeta.ogImage.width },
{ property: 'og:image:height', content: siteMeta.ogImage.height },
{ property: 'og:type', content: 'profile' },
{ property: 'og:url', content: canonical },
{ property: 'og:rich_attachment', content: 'true' },
]}
/>
<AuthorData authorData={author} />
<AuthorCollection
collections={collections}
currentId={author.id}
hasMore={collectionMeta.hasMore}
isFetching={collectionMeta.isFetching}
currentPage={collectionMeta.currentPage}
handleLoadmore={this.handleLoadmore}
totalResults={collectionMeta.totalResults}
/>
<Sponsor />
</React.Fragment>
)
}
}
function mapStateToProps(state, ownProps) {
const authorId = _.get(ownProps, 'match.params.authorId')
const articlesByAuthor = _.get(state, 'articlesByAuthor', {})
const entities = _.get(state, 'entitiesForAuthors', {})
const authorIsFull = _.get(entities, [authorId, 'full'], false)
const {
hasMore,
isFetching,
currentPage,
collectIndexList,
totalResults,
} = _.get(articlesByAuthor, authorId, {})
const collections = denormalizeArticles(collectIndexList, entities)
const authorEntity = _.get(entities, ['authors', authorId], {})
const authorImageSouce = _.get(
authorEntity,
'thumbnail.resizedTargets.mobile'
)
const authorImage = authorImageSouce
? { ...authorImageSouce, url: replaceGCSUrlOrigin(authorImageSouce.url) }
: authorDefaultImg
const author = {
id: authorId,
name: _.get(authorEntity, 'name') || '',
title: _.get(authorEntity, 'jobTitle') || '',
image: authorImage,
mail: _.get(authorEntity, 'email') || '',
bio: _.get(authorEntity, 'bio' || ''),
}
return {
author,
authorIsFull,
collections,
collectionMeta: {
hasMore,
isFetching,
currentPage,
totalResults,
},
}
}
export default connect(
mapStateToProps,
{ fetchAuthorCollectionIfNeeded, fetchAuthorDetails }
)(Author)
| JavaScript | 0.000056 | @@ -859,24 +859,71 @@
ht: 500,%0A%7D%0A%0A
+const defaultEmail = 'contact@twreporter.org'%0A%0A
const logger
@@ -5583,26 +5583,36 @@
'email') %7C%7C
-''
+defaultEmail
,%0A bio: _
|
ad264eb6371f248956d49265876b5d3154911617 | Remove isXManager cruft | app/models/user.js | app/models/user.js | import { not } from '@ember/object/computed';
import DS from 'ember-data';
export default DS.Model.extend({
status: DS.attr('user-status'),
username: DS.attr('string'),
isActive: DS.attr('boolean'),
isStaff: DS.attr('boolean'),
person: DS.belongsTo('person', {async: true}),
permissions: DS.attr(),
isDisabled: not(
'permissions.write'
),
isConventionManager: DS.attr('boolean'),
isSessionManager: DS.attr('boolean'),
isRoundManager: DS.attr('boolean'),
isScoringManager: DS.attr('boolean'),
isGroupManager: DS.attr('boolean'),
isPersonManager: DS.attr('boolean'),
isAwardManager: DS.attr('boolean'),
isOfficerManager: DS.attr('boolean'),
isChartManager: DS.attr('boolean'),
isAssignmentManager: DS.attr('boolean'),
});
| JavaScript | 0.999851 | @@ -357,405 +357,8 @@
),%0A
- isConventionManager: DS.attr('boolean'),%0A isSessionManager: DS.attr('boolean'),%0A isRoundManager: DS.attr('boolean'),%0A isScoringManager: DS.attr('boolean'),%0A isGroupManager: DS.attr('boolean'),%0A isPersonManager: DS.attr('boolean'),%0A isAwardManager: DS.attr('boolean'),%0A isOfficerManager: DS.attr('boolean'),%0A isChartManager: DS.attr('boolean'),%0A isAssignmentManager: DS.attr('boolean'),%0A
%7D);%0A
|
531277b7cb8a1af18f3ff30f6c2f7fb1c0437b00 | Remove comments | app/models/user.js | app/models/user.js | import Ember from 'ember';
const {
inject,
computed,
RSVP
} = Ember;
export default Ember.Object.extend({
auth: inject.service(),
ajax: inject.service(),
skype: inject.service(),
id: null,
person: null,
init() {
this._super(...arguments);
const person = this.get('person');
let deferred = RSVP.defer();
this.set('loaded', deferred.promise);
if (typeof person.id.get === "function") {
person.id.get()
.then(() => {
this.set('id', person.id());
this.set('displayName', person.displayName());
return person.status.get()
})
.then(() => {
this.set('rawPresence', person.status());
return person.email ?
person.email.get() :
person.emails.get();
})
.then(([email]) => {
if (email && email.emailAddress) {
this.set('email', email.emailAddress());
} else {
this.set('email', person.email());
}
this.setupPhoto();
deferred.resolve(this);
});
} else {
this.set('displayName', person.displayName);
if (person.emails) {
this.set('email', person.emails[0]);
} else {
this.set('email', person.email);
}
this.set('rawPresence', person.status);
this.set('avatarUrl', person.avatarUrl);
deferred.resolve(this);
}
this.subscribeToProperties();
},
rawPresence: computed(function () {
return 'Offline';
}),
presence: computed('rawPresence', function () {
const status = this.get('person').status();
const map = {
Online: 'Available',
Busy: 'Busy',
DoNotDisturb: 'Do Not Disturb',
Away: 'Away'
};
if (map[status]) {
return map[status];
}
return status;
}),
presenceClass: computed('presence', function () {
let presence = this.get('presence');
if (presence) {
return presence.toLowerCase();
}
else {
return 'Offline';
}
}),
photoUrl: computed('email', function () {
const email = this.get('email');
return this.get('ajax').request(`https://outlook.office.com/api/v2.0/Users/${email}/photo`)
.then(photoDescriptor => {
const avatarUrl = photoDescriptor['@odata.id'];
const requestUrl = `${avatarUrl}/$value`;
return fetch(requestUrl, {
method: 'GET',
headers: {
Authorization: `bearer ${this.get('auth.msftAccessToken')}`
}
}).then(response => {
return response.blob();
}).then(blob => {
return (window.URL || window.webkitURL).createObjectURL(blob);
});
// return new RSVP.Promise(resolve => {
// // const xhr = new XMLHttpRequest();
// // xhr.responseType = 'text';
// // xhr.setRequestHeader('Authorization', `bearer ${this.get('auth.msftAccessToken')}`);
// // xhr.onload = function() {
// // const blb = new Blob([xhr.response], {type: 'image/png'});
// // const url = (window.URL || window.webkitURL).createObjectURL(blb);
// // resolve(url);
// // }
// // xhr.open('GET', `${avatarUrl}/$value`);
// // xhr.send();
// // this.get('ajax').request(requestUrl, {
// // dataType: 'text',
// // contentType: 'text'
// // }).then(data => {
// // window.imageData = data;
// // resolve('');
// // });
// })
});
}),
subscribeToProperties() {
let person = this.get('person');
if (person.status) {
person.status.changed(() => this.notifyPropertyChange('presence'));
}
}
});
| JavaScript | 0 | @@ -3229,1063 +3229,8 @@
%7D);%0A
- // return new RSVP.Promise(resolve =%3E %7B%0A // // const xhr = new XMLHttpRequest();%0A // // xhr.responseType = 'text';%0A // // xhr.setRequestHeader('Authorization', %60bearer $%7Bthis.get('auth.msftAccessToken')%7D%60);%0A // // xhr.onload = function() %7B%0A // // const blb = new Blob(%5Bxhr.response%5D, %7Btype: 'image/png'%7D);%0A // // const url = (window.URL %7C%7C window.webkitURL).createObjectURL(blb);%0A // // resolve(url);%0A // // %7D%0A%0A // // xhr.open('GET', %60$%7BavatarUrl%7D/$value%60);%0A // // xhr.send();%0A%0A // // this.get('ajax').request(requestUrl, %7B%0A // // dataType: 'text',%0A // // contentType: 'text'%0A // // %7D).then(data =%3E %7B%0A // // window.imageData = data;%0A // // resolve('');%0A // // %7D);%0A%0A%0A // %7D)%0A
|
288ec27a7dcc461405b7c1e497688ade42657eae | Fix demo | demo/demo.js | demo/demo.js | /* globals document, FileReader */
import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom'; // eslint-disable-line
import ReactCrop, { makeAspectCrop } from '../lib/ReactCrop';
/**
* Load the image in the crop editor.
*/
const cropEditor = document.querySelector('#crop-editor');
function loadEditView(dataUrl) {
class Parent extends PureComponent {
state = {
crop: {
x: 20,
y: 10,
width: 40,
aspect: 16 / 9,
},
maxHeight: 80,
}
onButtonClick = () => {
const { image } = this.state;
this.setState({
crop: makeAspectCrop({
x: 20,
y: 5,
aspect: 1,
height: 50,
}, image.naturalWidth / image.naturalHeight),
disabled: true,
});
}
onButtonClick2 = () => {
this.setState({
crop: {
x: 20,
y: 5,
height: 20,
width: 30,
},
disabled: false,
});
}
onImageLoaded = (image, pixelCrop) => {
console.log('onImageLoaded', { image, pixelCrop });
// this.setState({
// crop: makeAspectCrop({
// x: 0,
// y: 0,
// aspect: 10 / 4,
// width: 50,
// }, image.naturalWidth / image.naturalHeight),
// image,
// });
}
onCropComplete = (crop, pixelCrop) => {
console.log('onCropComplete', { crop, pixelCrop });
}
onCropChange = (crop, pixelCrop) => {
// console.log('onCropChange', { crop, pixelCrop });
this.setState({ crop });
}
render() {
return (
<div>
<ReactCrop
{...this.state}
className="ACustomClassA ACustomClassB"
src={dataUrl}
onImageLoaded={this.onImageLoaded}
onComplete={this.onCropComplete}
onChange={this.onCropChange}
/>
<button type="button" onClick={this.onButtonClick}>Programatically set crop</button>
<button type="button" onClick={this.onButtonClick2}>Programatically set crop 2</button>
</div>
);
}
}
ReactDOM.render(<Parent />, cropEditor);
}
/**
* Select an image file.
*/
const imageType = /^image\//;
const fileInput = document.querySelector('#file-picker');
fileInput.addEventListener('change', (e) => {
const file = e.target.files.item(0);
if (!file || !imageType.test(file.type)) {
return;
}
const reader = new FileReader();
reader.onload = (e2) => {
loadEditView(e2.target.result);
};
reader.readAsDataURL(file);
});
| JavaScript | 0.000001 | @@ -542,44 +542,8 @@
%3E %7B%0A
- const %7B image %7D = this.state;%0A
@@ -570,39 +570,24 @@
crop:
-makeAspectCrop(
%7B%0A
@@ -648,24 +648,24 @@
height: 50,%0A
+
%7D, i
@@ -666,51 +666,8 @@
%7D,
- image.naturalWidth / image.naturalHeight),
%0A
|
48da7675764392864c53c8b3d56f775555547943 | Use object.assign to extend none class map to avoid undefined template vars | generators/css-framework/modules/class-maps.js | generators/css-framework/modules/class-maps.js | /**
* No CSS Framework
*/
export const noneClassMap = {
defaultButton: 'button default'
};
/**
* Bootstrap
*/
export const bootstrapClassMap = {
// Grid
row: 'row',
col4: 'col-sm-4',
fluidContainer: 'container-fluid',
// Buttons
defaultButton: 'button default',
// Components
panel: 'panel',
panelBody: 'panel-body'
};
/**
* Foundation
*/
export const foundationClassMap = {
// Grid
// row: 'row',
// col4: 'col-sm-4',
//
// // Buttons
// defaultButton: 'button default',
//
// // Components
// panel: 'panel',
// panelBody: 'panel-body'
};
/**
* Bourbon Neat
*/
export const bourbonNeatClassMap = {};
| JavaScript | 0 | @@ -1,15 +1,17 @@
/
-**%0A *
+/ Base (
No CSS F
@@ -18,20 +18,17 @@
ramework
-%0A */
+)
%0Aexport
@@ -56,38 +56,84 @@
%7B%0A
-defaultButton: 'b
+// Grid%0A row: '',%0A col4: '',%0A fluidContainer: '',%0A%0A // B
utton
+s%0A
default
'%0A%7D;
@@ -128,28 +128,80 @@
default
+Button: '',%0A%0A // Components%0A panel: '',%0A panelBody: '
'%0A%7D;%0A%0A/
-**%0A *
+/
Bootstr
@@ -203,20 +203,16 @@
otstrap%0A
- */%0A
export c
@@ -227,32 +227,64 @@
tstrapClassMap =
+ Object.assign(%7B%7D, noneClassMap,
%7B%0A // Grid%0A r
@@ -462,25 +462,22 @@
-body'%0A%7D
+)
;%0A%0A/
-**%0A *
+/
Foundat
@@ -480,20 +480,16 @@
ndation%0A
- */%0A
export c
@@ -518,203 +518,50 @@
p =
-%7B%0A // Grid%0A // row: 'row',%0A // col4: 'col-sm-4',%0A //%0A // // Buttons%0A // defaultButton: 'button default',%0A //%0A // // Components%0A // panel: 'panel',%0A // panelBody: 'panel-body'
+Object.assign(%7B%7D, noneClassMap, %7B%0A
%0A%7D
+)
;%0A%0A/
-**%0A *
+/
Bou
@@ -574,12 +574,8 @@
eat%0A
- */%0A
expo
@@ -605,12 +605,47 @@
ssMap =
-%7B%7D
+Object.assign(%7B%7D, noneClassMap, %7B%0A%0A%7D)
;%0A
|
b840bd3ce8ba96f89ce5749ee6c9832033d09ec3 | Use title as document.title as well | Titlebar.js | Titlebar.js | "use strict";
class Titlebar {
constructor(title) {
this.element = document.createElement("div");
this.element.classList.add("titlebar");
this.setTitle(title);
}
getElement() {
return this.element;
}
setTitle(value) {
this.getElement().textContent = value;
return this;
}
}
module.exports = Titlebar;
| JavaScript | 0.000001 | @@ -267,16 +267,42 @@
value;%0A
+%09%09document.title = value;%0A
%09%09return
|
35a1f82e94f744b33fb3d0ec5907371d70bd63f9 | update request field present checks to use 'in' operator | receive/request.js | receive/request.js | 'use strict'
const validation = require('../lib/validation')
const response = require('./response')
module.exports.validate = function (data, callback) {
checkHoneyPot(data, callback)
checkToParam(data, callback)
}
function checkHoneyPot (data, callback) {
if ('_honeypot' in data) {
response.render('honeypot', data, callback)
}
}
function checkToParam (data, callback) {
if (!('_to' in data)) {
response.render('no-admin-email', data, callback)
}
if ('_to' in data && !validation.isEmail(data['_to'])) {
response.render('bad-admin-email', data, callback)
}
}
module.exports.hasRedirect = function (data) {
if (data['_redirect-to'] !== undefined && validation.isURL(data['_redirect-to'])) {
return true
}
return false
}
module.exports.isJsonResponse = function (data) {
if (data['_format'] !== undefined && data['_format'].toLowerCase() === 'json') {
return true
}
return false
}
| JavaScript | 0 | @@ -640,21 +640,16 @@
%7B%0A if (
-data%5B
'_redire
@@ -654,31 +654,24 @@
rect-to'
-%5D !== undefined
+ in data
&& vali
@@ -802,21 +802,16 @@
%7B%0A if (
-data%5B
'_format
@@ -815,23 +815,16 @@
mat'
-%5D !== undefined
+ in data
&&
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.