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
|
---|---|---|---|---|---|---|---|
a0ed1236b1373c9e809cb88bc5173c7a9e4a56f5
|
fix rotation issue in export
|
js/export.js
|
js/export.js
|
// Test rotation state stuff
function exportOTF(matrix) {
var glyphs = [];
var notdefPath = new opentype.Path();
notdefPath.moveTo(100, 0);
notdefPath.lineTo(100, 700);
notdefPath.lineTo(0,700);
notdefPath.close();
var notdefGlyph = new opentype.Glyph({
name: '.notdef',
unicode: 0,
advanceWidth: 650,
path: notdefPath
});
glyphs.push(notdefGlyph);
var stringCache = ntype.string;
for (var key in window.TYPE) {
ntype.clear();
ntype.reset();
ntype.addLetter(key);
ntype.rotate(matrix);
ntype.updateTrails();
ntype.updateLines();
var projectedLines = ntype.shapes[0].get2DProjection(ntype.camera),
glyph = new opentype.Glyph({
name : key,
unicode : key.charCodeAt(0),
advanceWidth : 300
});
glyph.path = projectedLines.reduce(function(path, line) {
var point1 = line[0],
point2 = line[1],
matrix = new THREE.Matrix4().makeRotationZ(Math.PI/2);
lineOffset = new THREE.Vector3().copy(point2).sub(point1).applyMatrix4(matrix).normalize();
path.moveTo(point1.x - lineOffset.x, point1.y - lineOffset.y);
path.lineTo(point1.x + lineOffset.x, point1.y + lineOffset.y);
path.lineTo(point2.x + lineOffset.x, point2.y + lineOffset.y);
path.lineTo(point2.x - lineOffset.x, point2.y - lineOffset.y);
path.close();
return path;
}, new opentype.Path());
glyphs.push(glyph);
}
ntype.clear();
ntype.addString(stringCache);
ntype.rotate(matrix);
ntype.trailsNeedReset = true;
ntype.updateTrails();
ntype.updateLines();
var Font = new opentype.Font({familyName : 'NType', styleName : 'Rotation-' + matrix.determinant(), 'unitsPerEm' : 200, glyphs : glyphs});
Font.download();
}
document.querySelector('#download').addEventListener('click', function(e) {
e.preventDefault();
exportOTF(new THREE.Matrix4().copy(ntype.accumulationMatrix));
});
|
JavaScript
| 0 |
@@ -1388,24 +1388,40 @@
pe.clear();%0A
+%09ntype.reset();%0A
%09ntype.addSt
|
5384524f53ce1490f210499ed8186fd1247ae8b8
|
Delete route update
|
routes.js
|
routes.js
|
var passport = require('passport');
var Account = require('./models/account');
var Pet = require('./models/pet');
module.exports = function (app) {
app.get('/', function (req, res) {
if (req.user) {
res.redirect('/pets');
} else {
res.render('index', { user : req.user });
}
});
app.get('/register', function(req, res) {
res.render('register', { });
});
app.post('/register', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { info: "Sorry. That username already exists." });
}
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
app.get('/login', function(req, res) {
res.render('login', { user : req.user });
});
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/pets');
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.get('/pets', function(req, res) {
if (req.user) {
Pet.find({ owner: req.user.username }, function (err, pets) {
if (err) return console.error(err);
if (!pets) {
res.render('add-pet', { user : req.user });
} else {
res.render('pets', { user : req.user, pets : pets });
}
});
} else {
res.redirect('/login');
}
});
app.post('/add-pet', function(req, res) {
var url_name = req.body.name.toLowerCase();
var pet = new Pet({
name : req.body.name,
owner : req.body.owner,
url_name : url_name,
birthday : Date.now(),
fed_at : Date.now(),
slept_at : Date.now(),
played_at : Date.now()
});
pet.save(function(err, pet) {
if (err) return console.error(err);
});
res.redirect('/pets');
});
app.get('/add-pet', function(req, res) {
if (req.user) {
res.render('add-pet', { user : req.user });
} else {
res.redirect('/login');
}
});
app.get('/pet/*', function(req, res) {
if (req.user) {
var action = req.body.action;
Pet.findOne({
owner: req.user.username,
url_name: req.params[0]
}, function(err, pet) {
if (err) return console.error(err);
if (req.param('json')) {
res.json({pet : pet});
} else {
res.render('pet', { user : req.user, pet : pet });
}
});
}
});
app.post('/pet/*', function(req, res) {
if (req.user) {
if ( req.body.action ) {
var key;
switch(req.body.action) {
case 'feed':
key = 'fed_at';
break;
case 'sleep':
key = 'slept_at';
break;
case 'play':
key = 'played_at';
break;
}
var conditions = {
owner : req.user.username,
url_name : req.params[0]
},
update = {
[key] : Date.now()
}
Pet.update(conditions, update, function(){
Pet.findOne({
owner: req.user.username,
url_name: req.params[0]
}, function(err, pet) {
if (err) return console.error(err);
res.json({pet : pet});
/*if (req.param('json')) {
} else {
res.render('pet', { user : req.user, pet : pet });
}*/
});
});
}
}
});
app.get('/pet/:url_name(*)/play', function(req, res) {
if (req.user) {
Pet.findOne({
owner: req.user.username,
url_name: req.params.url_name
}, function(err, pet) {
if (err) return console.error(err);
res.render('play', { user : req.user, pet : pet, url_name : url_name });
});
}
});
app.post('/remove/*', function(req, res) {
if (req.user) {
Pet.findOne({
owner: req.user.username,
url_name: req.params[0]
}, function(err, pet) {
if (err) return console.error(err);
if ( req.body.delete === 'delete') {
if ( req.body.confirm !== 'true' ) {
res.render('pet', { user : req.user, pet : pet, msg : 'You must check the confirmation box to delete this pet' });
}
res.render('pet', { user : req.user, pet : pet });
}
});
} else {
res.redirect('/login');
}
});
};
|
JavaScript
| 0.000001 |
@@ -4334,34 +4334,44 @@
%7D);%0A %7D
-%0A%0A
+ else %7B%0A
res.rend
@@ -4408,21 +4408,141 @@
et : pet
+, msg : 'Pet will be deleted' %7D);%0A%0A %7D%0A%0A %7D else %7B%0A res.render('pet', %7B user : req.user, pet : pet
%7D);
-%0A
%0A
|
a4d39aa57d3477527050d74a2dfe7c5fec9eabc8
|
adding undefined
|
back-end/services/socket.js
|
back-end/services/socket.js
|
(function() {
'use strict';
var elasticsearch = require('elasticsearch'),
clients = {},
client = new elasticsearch.Client({
host: 'localhost:9200',
});
module.exports = function(socket) {
clients[socket.id] = socket;
console.log('client connected');
socket.on('disconnect', disconnect);
socket.on('close', function() {
disconnect();
});
/*chat*/
socket.on('send_message', function(data) {
socket.broadcast.to(data.room).emit('receive_message', data.message);
});
socket.on('videoRemoved', function(room) {
socket.broadcast.to(room).emit('videoRemoved');
});
socket.on('stop', function(data) {
socket.broadcast.to(data.room).emit('stop');
});
socket.on('find', function(data) {
/* search for common interest */
if (data.lat !== undefined && data.lon !== undefined && data.range !== undefined) {
if (data.interest !== undefined) {
/* location = true*/
/* interest(tags) = true */
console.log('location with interest');
io.elastic_search_location_with_interest(client, clients, socket, data);
} else {
/* location = true*/
/* interest(tags) = false */
io.elastic_search_location(client, clients, socket, data);
}
} else {
if (data.interest !== undefined) {
io.elastic_search_interest(client, clients, socket, data);
} else {
/* make a random choice */
io.elastic_search_random(client, clients, socket, data);
}
}
});
function disconnect() {
/*search if we have this document*/
client.search({
index: 'webrtc',
type: 'data',
body: {
query: {
filtered: {
/* first step we must know if the socket id is present*/
filter: { term: { _id: socket.id }}
}
}
}
}).then(function (body) {
var hits = body.hits.hits;
if (hits.length !== 0) {
var otherRoom = hits[0]._source.room;
/* if we have document delete it*/
client.delete({
index: 'webrtc',
type: 'data',
id: socket.id
}).then(function(body) {
socket.broadcast.to(otherRoom).emit('stop');
if (hits[0]._source.match_id !== 'null') {
client.delete({
index: 'webrtc',
type: 'data',
id : hits[0]._source.match_id.toString()
});
}
}, function(err) {
return;
});
}
}, function(error) {
return;
});
console.log('client disconnected');
}
};
}());
|
JavaScript
| 0.998965 |
@@ -986,32 +986,56 @@
st !== undefined
+ %7C%7C data.interest === ''
) %7B%0A
@@ -1457,32 +1457,56 @@
st !== undefined
+ %7C%7C data.interest === ''
) %7B%0A
|
0052b0a40297fe0313ea8d6271fa4e120305f975
|
remove deleted track in playlist (#8)
|
e2e/tests/playlist-page.js
|
e2e/tests/playlist-page.js
|
const path = require('path');
const zcBtnSelector = '.listenEngagement .sc-button-share + button.zc-button-download';
const trackItemSelector = '.listenDetails .trackList__item:last-of-type';
module.exports = {
'@tags': ['playlist-page'],
before(browser) {
browser
.url('https://soundcloud.com/xtangle/sets/test-playlist')
.dismissCookiePolicyNotification();
},
after(browser) {
browser.end();
},
'Adds a Download button to a SoundCloud playlist page': function (browser) {
browser
.waitForElementVisible(zcBtnSelector)
.assert.containsText(zcBtnSelector, 'Download');
},
'Downloads all tracks in the playlist when clicked': function (browser) {
const playlistDir = path.join(browser.globals.downloadDir, 'xtangle - test playlist');
// track 1: uses the download_url method, does not have a .mp3 file extension
// (but should download in mp3 format anyways because of 'always download mp3' option enabled by default),
// has cover art, and original track title has '__FREE DOWNLOAD__' as a suffix which should be removed
const track1Path = path.join(playlistDir, 'Rather Be (Marimba Remix).mp3');
// track 2: uses the stream_url method, does not have cover art
const track2Path = path.join(playlistDir, '23. M2U - Blythe.mp3');
// track 3: uses the a1_api method
const track3Path = path.join(playlistDir, 'Ryuusei.mp3');
// track 4: uses the stream_url method, has a long track title with weird characters
// with some that are unsuitable for filenames, has cover art
const track4Path = path.join(playlistDir,
'مهرجان _ رب الكون ميزنا بميزه _ حمو بيكا - علي قدوره - نور التوت - توزيع فيجو الدخلاوي 2019.mp3');
browser
.click(zcBtnSelector)
.assert.fileDownloaded(track1Path)
.verify.fileHasSize(track1Path, 523662)
.assert.fileDownloaded(track2Path)
.verify.fileHasSize(track2Path, 2189492)
.assert.fileDownloaded(track3Path)
.verify.fileHasSize(track3Path, 5099728)
.assert.fileDownloaded(track4Path)
.verify.fileHasSize(track4Path, 5551831);
},
'Adds a Download button for every item in the track list': function (browser) {
browser
.elements('css selector', '.listenDetails .trackList__item'
+ ' .sc-button-share + button.zc-button-download', (result) => {
browser.assert.strictEqual(result.value.length, 4,
'Should add a download button for every track item');
})
.assert.hidden(`${trackItemSelector} button.zc-button-download`, 'Download button is hidden on a track item')
.moveToElement(trackItemSelector, 100, 20)
.assert.visible(`${trackItemSelector} button.zc-button-download`,
'Download button is visible when hovering over a track item');
},
'Downloads the track when a Download button in the track list is clicked': function (browser) {
const trackPath = path.join(browser.globals.downloadDir,
'مهرجان _ رب الكون ميزنا بميزه _ حمو بيكا - علي قدوره - نور التوت - توزيع فيجو الدخلاوي 2019.mp3');
browser
.click(`${trackItemSelector} button.zc-button-download`)
.assert.fileDownloaded(trackPath)
.verify.fileHasSize(trackPath, 5551832); // not sure where the extra byte comes from
},
};
|
JavaScript
| 0.000001 |
@@ -1411,315 +1411,8 @@
3');
-%0A // track 4: uses the stream_url method, has a long track title with weird characters%0A // with some that are unsuitable for filenames, has cover art%0A const track4Path = path.join(playlistDir,%0A '%D9%85%D9%87%D8%B1%D8%AC%D8%A7%D9%86 _ %D8%B1%D8%A8 %D8%A7%D9%84%D9%83%D9%88%D9%86 %D9%85%D9%8A%D8%B2%D9%86%D8%A7 %D8%A8%D9%85%D9%8A%D8%B2%D9%87 _ %D8%AD%D9%85%D9%88 %D8%A8%D9%8A%D9%83%D8%A7 - %D8%B9%D9%84%D9%8A %D9%82%D8%AF%D9%88%D8%B1%D9%87 - %D9%86%D9%88%D8%B1 %D8%A7%D9%84%D8%AA%D9%88%D8%AA - %D8%AA%D9%88%D8%B2%D9%8A%D8%B9 %D9%81%D9%8A%D8%AC%D9%88 %D8%A7%D9%84%D8%AF%D8%AE%D9%84%D8%A7%D9%88%D9%8A 2019.mp3');
%0A%0A
@@ -1715,96 +1715,8 @@
728)
-%0A .assert.fileDownloaded(track4Path)%0A .verify.fileHasSize(track4Path, 5551831)
;%0A
@@ -2008,17 +2008,17 @@
length,
-4
+3
,%0A
@@ -2560,107 +2560,17 @@
Dir,
-%0A '%D9%85%D9%87%D8%B1%D8%AC%D8%A7%D9%86 _ %D8%B1%D8%A8 %D8%A7%D9%84%D9%83%D9%88%D9%86 %D9%85%D9%8A%D8%B2%D9%86%D8%A7 %D8%A8%D9%85%D9%8A%D8%B2%D9%87 _ %D8%AD%D9%85%D9%88 %D8%A8%D9%8A%D9%83%D8%A7 - %D8%B9%D9%84%D9%8A %D9%82%D8%AF%D9%88%D8%B1%D9%87 - %D9%86%D9%88%D8%B1 %D8%A7%D9%84%D8%AA%D9%88%D8%AA - %D8%AA%D9%88%D8%B2%D9%8A%D8%B9 %D9%81%D9%8A%D8%AC%D9%88 %D8%A7%D9%84%D8%AF%D8%AE%D9%84%D8%A7%D9%88%D9%8A 2019
+ 'Ryuusei
.mp3
@@ -2730,14 +2730,14 @@
h, 5
-551832
+099729
); /
|
ecf7a27a775cea086492586c2fd59064ca8fe947
|
Update details-spec.js
|
test/functional/cypress/specs/events/details-spec.js
|
test/functional/cypress/specs/events/details-spec.js
|
import urls from '../../../../../src/lib/urls'
const {
assertKeyValueTable,
assertBreadcrumbs,
} = require('../../support/assertions')
const fixtures = require('../../fixtures')
const selectors = require('../../../../selectors')
describe('Event Details', () => {
it('should display event details with link to documents', () => {
cy.visit(urls.events.details(fixtures.event.oneDayExhibition.id))
cy.get(selectors.entityCollection.editEvent).should('be.visible')
assertBreadcrumbs({
Home: urls.dashboard.route,
Events: '/events',
'One-day exhibition': null,
})
assertKeyValueTable('eventDetails', {
'Type of event': 'Exhibition',
'Event date': '1 January 2021',
'Event location type': 'HQ',
Address:
'Day Court Exhibition Centre, Day Court Lane, China, SW9 9AB, China',
Region: '',
Notes: 'This is a dummy event for testing.',
'Lead team': 'CBBC Hangzhou',
Organiser: 'John Rogers',
'Other teams': 'CBBC HangzhouCBBC North West',
'Related programmes': 'Grown in Britain',
'Related Trade Agreements': 'UK - Japan',
Service: 'Events : UK Based',
Documents: 'View files and documents (opens in a new window or tab)',
})
cy.contains('a', 'View files and documents').should((el) => {
expect(el).to.have.attr('href', '/documents/123')
expect(el).to.have.attr('target', '_blank')
})
})
describe('Disabled event with no document', () => {
before(() => {
cy.visit(urls.events.details(fixtures.event.teddyBearExpo.id))
})
it('should display no document link details', () => {
assertBreadcrumbs({
Home: urls.dashboard.route,
Events: '/events',
'Teddy bear expo': null,
})
assertKeyValueTable('eventDetails', {
'Type of event': 'Exhibition',
'Event date': '1 January 2021',
'Event location type': 'HQ',
Address:
'Day Court Exhibition Centre, Day Court Lane, China, SW9 9AB, China',
Region: '',
Notes: 'This is a dummy event for testing.',
'Lead team': 'CBBC Hangzhou',
Organiser: 'John Rogers',
'Other teams': 'CBBC HangzhouCBBC North West',
'Related programmes': 'Grown in Britain',
'Related Trade Agreements': '',
Service: 'Events : UK Based',
})
})
it('should hide edit event button for disabled events', () => {
cy.get(selectors.entityCollection.editEvent).should('not.exist')
})
})
})
|
JavaScript
| 0.000001 |
@@ -284,16 +284,24 @@
display
+one day
event de
|
1b1130639b3c773b6c8bcf6ec2619943844f0e5b
|
add meteor day redirect
|
routes.js
|
routes.js
|
Router.map(function() {
this.route('home', {
path: '/',
waitOn: function() {
return this.subscribe("meetups");
},
data: {
upcomingMeetup: Meetups.find({dateTime : {$gt : new Date()} }, {sort: {dateTime: 1}, limit: 1}),
groupName : Meteor.settings.public.meetup.group_name,
groupInfo : Meteor.settings.public.meetup.group_info
}
});
this.route('meetups', {
path: '/meetups',
waitOn: function() {
return this.subscribe("meetups");
},
data: {
upcomingMeetup: Meetups.find({dateTime : {$gt : new Date()} }, {sort: {dateTime: 1}, limit: 1}),
previousMeetups: Meetups.find({dateTime : {$lt : new Date()} }, {sort: {dateTime: -1}})
},
onAfterAction: function() {
SEO.set({
title: 'Meetups | ' + SEO.settings.title
});
}
});
this.route('meetupDetail', {
path: '/meetups/:_id',
waitOn: function() {
return [
this.subscribe("meetup", this.params._id),
this.subscribe("suggestedTopics"),
this.subscribe("members")
];
},
data: function() {
return {
meetup: Meetups.findOne({_id: this.params._id}),
suggestedTopics: Topics.find({presented: {$ne: true}}, {sort: {points: -1}}),
members: Meteor.users.find({}, {sort: {'profile.points': -1}})
};
},
onAfterAction: function() {
if(this.ready()) {
SEO.set({
title: this.data().meetup.title + ' | Meetups | ' + SEO.settings.title
});
}
}
});
this.route('topics', {
path: '/topics',
waitOn: function() {
return [
this.subscribe("suggestedTopics"),
this.subscribe("presentedTopics")
];
},
data: {
suggestedTopics: Topics.find({presented: {$ne: true}}, {sort: {points: -1}}),
presentedTopics: Topics.find({presented: true}, {sort: {points: -1}})
},
onBeforeAction: function() {
if (!this.params.tab) {
this.params.tab = 'suggested';
}
},
onAfterAction: function() {
SEO.set({
title: 'Topics | ' + SEO.settings.title
});
}
});
this.route('topicDetail', {
path: '/topics/:_id',
waitOn: function() {
return this.subscribe("topic", this.params._id);
},
data: function() {
return {
topic: Topics.findOne({_id: this.params._id}),
comments: Comments.find({parentType: 'topic', parentId: this.params._id}, {sort: { createdAt: -1 }})
};
},
onAfterAction: function() {
if(this.ready()) {
SEO.set({
title: this.data().topic.title + ' | Topics | ' + SEO.settings.title
});
}
}
});
this.route('presentations', {
path: '/presentations',
waitOn: function() {
return [this.subscribe("presentations"), this.subscribe("members")];
},
data: {
topics: Presentations.find({})
}
});
this.route('presentationDetail', {
path: '/presentations/:_id',
waitOn: function() {
return this.subscribe("presentation", this.params._id);
},
data: function() {
return {
presentation: Presentations.findOne({_id: this.params._id}),
comments: Comments.find({parentType: 'presentation', parentId: this.params._id}, {sort: { createdAt: -1 }})
};
}
});
this.route('members', {
path: '/members',
waitOn: function() {
return this.subscribe("members");
},
data: {
members: Meteor.users.find({}, {sort: {'profile.points': -1}})
},
onAfterAction: function() {
SEO.set({
title: 'Members | ' + SEO.settings.title
});
}
});
this.route('memberDetail', {
path: '/members/:_id',
waitOn: function() {
return this.subscribe("member", this.params._id);
},
data: function() {
return {
member: Meteor.users.findOne({_id: this.params._id})
};
},
onAfterAction: function() {
if(this.ready()) {
SEO.set({
title: this.data().member.profile.name + ' | Members | ' + SEO.settings.title
});
}
}
});
this.route('notFound', {
path: '*',
where: 'server',
action: function() {
this.response.statusCode = 404;
this.response.end(Handlebars.templates['404']());
}
});
});
|
JavaScript
| 0.000001 |
@@ -4091,32 +4091,273 @@
%7D%0A %7D%0A %7D);%0A%0A
+ this.route('meteorday', %7B%0A path: '/cpanel',%0A where: 'server',%0A action: function() %7B%0A this.response.writeHead(301, Location: 'http://www.meetup.com/Meteor-Las-Vegas/events/212820662/');%0A this.response.end();%0A %7D%0A %7D);%0A%0A
this.route('no
|
d53559ac9a5ad78272d22df2154c8b639c6f3ca5
|
Work around weird inferred name in Chrome
|
packages/react-error-overlay/src/components/frame.js
|
packages/react-error-overlay/src/components/frame.js
|
/* @flow */
import { enableTabClick } from '../utils/dom/enableTabClick';
import { createCode } from './code';
import { isInternalFile } from '../utils/isInternalFile';
import type { StackFrame } from '../utils/stack-frame';
import type { FrameSetting, OmitsObject } from './frames';
import { applyStyles } from '../utils/dom/css';
import {
omittedFramesStyle,
functionNameStyle,
depStyle,
linkStyle,
anchorStyle,
hiddenStyle,
} from '../styles';
function getGroupToggle(
document: Document,
omitsCount: number,
omitBundle: number
) {
const omittedFrames = document.createElement('div');
enableTabClick(omittedFrames);
const text1 = document.createTextNode(
'\u25B6 ' + omitsCount + ' stack frames were collapsed.'
);
omittedFrames.appendChild(text1);
omittedFrames.addEventListener('click', function() {
const hide = text1.textContent.match(/▲/);
const list = document.getElementsByName('bundle-' + omitBundle);
for (let index = 0; index < list.length; ++index) {
const n = list[index];
if (hide) {
n.style.display = 'none';
} else {
n.style.display = '';
}
}
if (hide) {
text1.textContent = text1.textContent.replace(/▲/, '▶');
text1.textContent = text1.textContent.replace(/expanded/, 'collapsed');
} else {
text1.textContent = text1.textContent.replace(/▶/, '▲');
text1.textContent = text1.textContent.replace(/collapsed/, 'expanded');
}
});
applyStyles(omittedFrames, omittedFramesStyle);
return omittedFrames;
}
function insertBeforeBundle(
document: Document,
parent: Node,
omitsCount: number,
omitBundle: number,
actionElement
) {
const children = document.getElementsByName('bundle-' + omitBundle);
if (children.length < 1) {
return;
}
let first: ?Node = children[0];
while (first != null && first.parentNode !== parent) {
first = first.parentNode;
}
const div = document.createElement('div');
enableTabClick(div);
div.setAttribute('name', 'bundle-' + omitBundle);
const text = document.createTextNode(
'\u25BC ' + omitsCount + ' stack frames were expanded.'
);
div.appendChild(text);
div.addEventListener('click', function() {
return actionElement.click();
});
applyStyles(div, omittedFramesStyle);
div.style.display = 'none';
parent.insertBefore(div, first);
}
function frameDiv(document: Document, functionName, url, internalUrl) {
const frame = document.createElement('div');
const frameFunctionName = document.createElement('div');
let cleanedFunctionName;
if (!functionName || functionName === 'Object.<anonymous>') {
cleanedFunctionName = '(anonymous function)';
} else {
cleanedFunctionName = functionName;
}
const cleanedUrl = url.replace('webpack://', '.');
if (internalUrl) {
applyStyles(
frameFunctionName,
Object.assign({}, functionNameStyle, depStyle)
);
} else {
applyStyles(frameFunctionName, functionNameStyle);
}
frameFunctionName.appendChild(document.createTextNode(cleanedFunctionName));
frame.appendChild(frameFunctionName);
const frameLink = document.createElement('div');
applyStyles(frameLink, linkStyle);
const frameAnchor = document.createElement('a');
applyStyles(frameAnchor, anchorStyle);
frameAnchor.appendChild(document.createTextNode(cleanedUrl));
frameLink.appendChild(frameAnchor);
frame.appendChild(frameLink);
return frame;
}
function createFrame(
document: Document,
frameSetting: FrameSetting,
frame: StackFrame,
contextSize: number,
critical: boolean,
omits: OmitsObject,
omitBundle: number,
parentContainer: HTMLDivElement,
lastElement: boolean
) {
const { compiled } = frameSetting;
let { functionName, _originalFileName: sourceFileName } = frame;
const {
fileName,
lineNumber,
columnNumber,
_scriptCode: scriptLines,
_originalLineNumber: sourceLineNumber,
_originalColumnNumber: sourceColumnNumber,
_originalScriptCode: sourceLines,
} = frame;
// TODO: find a better place for this.
// Chrome has a bug with inferring function.name:
// https://github.com/facebookincubator/create-react-app/issues/2097
// Let's ignore a meaningless name we get for top-level modules.
if (functionName === 'Object.friendlySyntaxErrorLabel') {
functionName = '(anonymous function)';
}
let url;
if (!compiled && sourceFileName && sourceLineNumber) {
// Remove everything up to the first /src/
const trimMatch = /^[/|\\].*?[/|\\](src[/|\\].*)/.exec(sourceFileName);
if (trimMatch && trimMatch[1]) {
sourceFileName = trimMatch[1];
}
url = sourceFileName + ':' + sourceLineNumber;
if (sourceColumnNumber) {
url += ':' + sourceColumnNumber;
}
} else if (fileName && lineNumber) {
url = fileName + ':' + lineNumber;
if (columnNumber) {
url += ':' + columnNumber;
}
} else {
url = 'unknown';
}
let needsHidden = false;
const internalUrl = isInternalFile(url, sourceFileName);
if (internalUrl) {
++omits.value;
needsHidden = true;
}
let collapseElement = null;
if (!internalUrl || lastElement) {
if (omits.value > 0) {
const capV = omits.value;
const omittedFrames = getGroupToggle(document, capV, omitBundle);
window.requestAnimationFrame(() => {
insertBeforeBundle(
document,
parentContainer,
capV,
omitBundle,
omittedFrames
);
});
if (lastElement && internalUrl) {
collapseElement = omittedFrames;
} else {
parentContainer.appendChild(omittedFrames);
}
++omits.bundle;
}
omits.value = 0;
}
const elem = frameDiv(document, functionName, url, internalUrl);
if (needsHidden) {
applyStyles(elem, hiddenStyle);
elem.setAttribute('name', 'bundle-' + omitBundle);
}
let hasSource = false;
if (!internalUrl) {
if (
compiled && scriptLines && scriptLines.length !== 0 && lineNumber != null
) {
elem.appendChild(
createCode(
document,
scriptLines,
lineNumber,
columnNumber,
contextSize,
critical,
frame._originalFileName,
frame._originalLineNumber
)
);
hasSource = true;
} else if (
!compiled &&
sourceLines &&
sourceLines.length !== 0 &&
sourceLineNumber != null
) {
elem.appendChild(
createCode(
document,
sourceLines,
sourceLineNumber,
sourceColumnNumber,
contextSize,
critical,
frame._originalFileName,
frame._originalLineNumber
)
);
hasSource = true;
}
}
return { elem: elem, hasSource: hasSource, collapseElement: collapseElement };
}
export { createFrame };
|
JavaScript
| 0.000026 |
@@ -4255,16 +4255,21 @@
.%0A if (
+%0A
function
@@ -4310,16 +4310,71 @@
orLabel'
+ %7C%7C%0A functionName === 'Object.exports.__esModule'%0A
) %7B%0A
|
b749d8312b0dd88c134d52dd78a30caa53f215ae
|
Remove loadable import of wys
|
packages/strapi-helper-plugin/lib/src/components/InputsIndex/index.js
|
packages/strapi-helper-plugin/lib/src/components/InputsIndex/index.js
|
/**
*
* InputsIndex references all the input with errors available
*/
/* eslint-disable react/require-default-props */
import React from 'react';
import PropTypes from 'prop-types';
import { isEmpty, merge } from 'lodash';
// Design
import InputAddonWithErrors from 'components/InputAddonWithErrors';
import InputCheckboxWithErrors from 'components/InputCheckboxWithErrors';
import InputDateWithErrors from 'components/InputDateWithErrors';
import InputEmailWithErrors from 'components/InputEmailWithErrors';
import InputFileWithErrors from 'components/InputFileWithErrors';
import InputNumberWithErrors from 'components/InputNumberWithErrors';
import InputSearchWithErrors from 'components/InputSearchWithErrors';
import InputSelectWithErrors from 'components/InputSelectWithErrors';
import InputPasswordWithErrors from 'components/InputPasswordWithErrors';
import InputTextAreaWithErrors from 'components/InputTextAreaWithErrors';
import InputTextWithErrors from 'components/InputTextWithErrors';
import InputToggleWithErrors from 'components/InputToggleWithErrors';
import WysiwygWithErrors from 'components/WysiwygWithErrors/Loadable';
const DefaultInputError = ({ type }) => <div>Your input type: <b>{type}</b> does not exist</div>;
const inputs = {
addon: InputAddonWithErrors,
checkbox: InputCheckboxWithErrors,
date: InputDateWithErrors,
email: InputEmailWithErrors,
file: InputFileWithErrors,
number: InputNumberWithErrors,
password: InputPasswordWithErrors,
search: InputSearchWithErrors,
select: InputSelectWithErrors,
string: InputTextWithErrors,
text: InputTextWithErrors,
textarea: InputTextAreaWithErrors,
toggle: InputToggleWithErrors,
wysiwyg: WysiwygWithErrors,
};
function InputsIndex(props) {
const type = props.type && !isEmpty(props.addon) ? 'addon' : props.type;
let inputValue;
switch (props.type) {
case 'checkbox':
case 'toggle':
inputValue = props.value || false;
break;
case 'number':
inputValue = props.value === 0 ? props.value : props.value || '';
break;
case 'file':
inputValue = props.value || [];
break;
default:
inputValue = props.value || '';
}
merge(inputs, props.customInputs);
const Input = inputs[type] ? inputs[type] : DefaultInputError;
return <Input {...props} value={inputValue} />;
}
DefaultInputError.propTypes = {
type: PropTypes.string.isRequired,
};
InputsIndex.defaultProps = {
addon: false,
customInputs: {},
};
InputsIndex.propTypes = {
addon: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string,
]),
customInputs: PropTypes.object,
type: PropTypes.string.isRequired,
value: PropTypes.any,
};
export default InputsIndex;
|
JavaScript
| 0 |
@@ -1129,17 +1129,8 @@
rors
-/Loadable
';%0A%0A
|
f396dbbd6102ead6bd5782996199967ff9c3bc04
|
change function fire to 150px from botton of document
|
ReleaseDisplay/js/app.js
|
ReleaseDisplay/js/app.js
|
function moreHeadlines(strAPI) {
"use strict";
//Call StellBioTech NewsRelease
$.getJSON(strAPI, function (pressReleases) {
pressReleases.news.forEach(function (headline) {
var $panel = $('<div class="panel panel-default">'),
$h2 = $("<h2>"),
$p = $("<p>");
$panel.hide();
$h2.text(headline.title);
$p.text(headline.published);
$panel.append($h2);
$panel.append($p);
$(".releases").append($panel);
$panel.fadeIn();
});
});
}
var main = function () {
"use strict";
//control api output with limit & offset
var limit = 10,
offset = 0,
win = $(window),
status = false,
url = "http://www.stellarbiotechnologies.com/media/press-releases/json?limit=" + limit.toString() + "&offset=" + offset.toString();
moreHeadlines(url);
//on end of document, load more headlines
win.scroll(function () {
console.log($(document).height() - win.height() - win.scrollTop());
if ($(document).height() - win.height() === win.scrollTop()) {
offset += 5;
limit = 5;
url = "http://www.stellarbiotechnologies.com/media/press-releases/json?limit=" + limit.toString() + "&offset=" + offset.toString();
//request more headlines at new offset
moreHeadlines(url);
}
});
};
$(document).ready(main);
|
JavaScript
| 0 |
@@ -1116,61 +1116,77 @@
($(
-document).height() - win.height() === win.scrollTop()
+window).scrollTop() + $(window).height() %3E $(document).height() - 150
) %7B%0A
|
cdfb6c1f7826a623a4ebad2b0a156d593ad2b1de
|
Add conditional render based on overflowAmount
|
src/components/avatar/AvatarStack.js
|
src/components/avatar/AvatarStack.js
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
import uiUtilities from '@teamleader/ui-utilities';
class AvatarStack extends PureComponent {
render() {
const { children, className, direction, displayMax, inverse, onOverflowClick, size, ...others } = this.props;
const classNames = cx(
theme['stack'],
theme[direction],
theme[`is-${size}`],
inverse ? [theme['light']] : [theme['dark']],
className,
);
const childrenToDisplay = displayMax > 0 ? children.slice(0, displayMax) : children;
const overflowAmount = children.length - displayMax;
return (
<Box data-teamleader-ui="avatar-stack" className={classNames} {...others}>
{overflowAmount !== children.length && (
<div
className={cx(uiUtilities['reset-font-smoothing'], theme['overflow'])}
onClick={onOverflowClick}
>{`+${overflowAmount}`}</div>
)}
{childrenToDisplay}
</Box>
);
}
}
AvatarStack.propTypes = {
/** The avatars to display in a stack. */
children: PropTypes.node,
/** A class name for the wrapper to give custom styles. */
className: PropTypes.string,
/** The direction in which the avatars will be rendered. */
direction: PropTypes.oneOf(['horizontal', 'vertical']),
/** The maximum amount of avatars to render. */
displayMax: PropTypes.number,
/** If true, component will be rendered in inverse mode. */
inverse: PropTypes.bool,
/** Callback function that is fired when the overflow circle is clicked. */
onOverflowClick: PropTypes.func,
/** The size of the avatar stack. */
size: PropTypes.oneOf(['tiny', 'small', 'medium']),
};
AvatarStack.defaultProps = {
direction: 'horizontal',
displayMax: 0,
inverse: false,
size: 'medium',
};
export default AvatarStack;
|
JavaScript
| 0 |
@@ -709,17 +709,16 @@
layMax;%0A
-%0A
retu
@@ -831,27 +831,11 @@
unt
-!== children.length
+%3E 0
&&
|
780532ba0960f0fffc9ad8a324aca80229f0736f
|
Return if imageUpload was already created.g
|
src/jQuery-image-upload.js
|
src/jQuery-image-upload.js
|
/*
* jQuery prioritize events
*
* A jQuery plugin that adds controls to the selected jQuery
* elements with a simple call.
*
* Example:
*
* $("img").imageUpload();
*
* Copyright (c) jillix GmbH
* License: MIT License
*
* */
(function ($) {
// defaults
var defaults = {
wrapContent: "<div class='jQuery-imageUpload'>",
inputFileName: "inputFile",
inputFileClass: "inputFile",
uploadButtonValue: "Upload",
uploadButtonClass: "uploadButton",
browseButtonClass: "browseButton",
browseButtonValue: "Browse",
formClass: "controlForm",
hideFileInput: true,
uploadIframe: ".uploadIframe",
hover: true,
addClass: "jQuery-image-upload"
};
/*
* $("[jQuery selector]").imageUpload({...});
* */
$.fn.imageUpload = function(options) {
// defaults
var settings = $.extend(defaults, options);
// selected jQuery objects
var $self = this;
// return if no elements
if (!$self.length) { return $self; }
// call image upload for each element
if ($self.length > 1) {
$self.each(function () {
$(this).imageUpload(settings);
});
return $self;
}
// add class
$self.addClass(settings.addClass);
// set imageUpload data
$self.data("imageUpload", options);
// form action not provided
if (!settings.formAction) {
throw new Error ("Form action was not provided. Please provide it: $(...).imageUpload({formAction: '...'})");
}
// wrap
if (!settings.hover) {
$self.wrap(settings.wrapContent)
}
// create the controls div
var $controls = $("<div>").addClass("controls")
, $fileInput = $("<input>")
.attr("type", "file")
.addClass(settings.inputFileClass)
.attr("name", settings.inputFileName)
, $uploadButton = $("<button>")
.attr("type", "submit")
.addClass(settings.uploadButtonClass)
.html(settings.uploadButtonValue)
, $browseButton = $("<button>")
.addClass(settings.browseButtonClass)
.html(settings.browseButtonValue)
.on("click", function () {
$fileInput.click();
return false;
})
, $uploadIframe = $("<iframe>")
.attr("id", "uploadIframe-" + Math.random().toString(36).substring(5, 20).toUpperCase())
.hide()
, $uploadForm = $("<form>")
.addClass(settings.formClass)
.attr("target", $uploadIframe.attr("id"))
.attr("enctype", "multipart/form-data")
.attr("method", "post")
.attr("action", settings.formAction);
// append controls to form
$uploadForm.append([$browseButton, $fileInput, $uploadButton, $uploadIframe]);
// hide file input
if (settings.hideFileInput) {
$fileInput.hide();
} else {
// hide browse button
$browseButton.hide();
}
// append $form to $controls
$controls.append($uploadForm);
// form on submit
$uploadForm.on("submit", function () {
// get submiited form
var $form = $(this);
// unset the load handler
$uploadIframe.off("load");
// set it again
$uploadIframe.on("load", function () {
// get text from the page
var result = $(this.contentWindow.document).text();
// if no result, return
if (!result) { return; }
// reload the image upload controls only if the file input is hidden
if (settings.hideFileInput) {
$self.trigger("imageUpload.reload");
}
// verify file input value
if (!$fileInput.val()) {
return;
}
// try to parse result
try {
result = JSON.parse(result);
} catch (e) {
// nothing to do
}
// set src of iframe
$uploadIframe.attr("src", "");
// upadte the image source
$self.attr("src", result);
// trigger image changed event
$self.trigger("imageChanged");
// replace the file input
$fileInput.replaceWith($fileInput.clone(true));
});
});
// no hover
if (!settings.hover) {
// append controls to image wrapper
$self.parent().append($controls);
} else {
// set absolute position to controls and set the offset
$controls.css({ position: "absolute" });
// add class to controls
$controls.addClass("jQuery-image-upload-controls");
// append controls to body
$("body").append($controls.hide());
// self on mouse enter
$self.on("mouseenter", function () {
// get the self offset
var offset = $self.offset();
// set control possition
$controls.css({
top: offset.top,
left: offset.left
});
// show controls
$controls.show();
});
// on mouse leave
$("body").on("mouseleave", "." + settings.addClass, function (e) {
// get position
var o = $self.offset()
// width
, w = $self.width()
// and the hegiht
, h = $self.height();
// hide controls
if ((e.pageX < o.left || e.pageX > o.left + w) ||
(e.pageY < o.top || e.pageY > o.top + h)) {
$controls.hide();
}
});
}
// destroy
$self.on("imageUpload.destroy", function () {
// remove controls
$controls.remove();
// remove events
$self.off("imageUpload.destroy");
$self.off("imageUpload.reload");
// remove data
$self.data("imageUpload", null);
});
// reload
$self.on("imageUpload.reload", function () {
$self.trigger("imageUpload.destroy");
$self.imageUpload(options);
});
// return selected element
return $self;
};
// defaults
$.imageUpload = $.fn.imageUpload;
$.imageUpload.defaults = defaults;
})($);
|
JavaScript
| 0.00016 |
@@ -1341,32 +1341,185 @@
elf;%0A %7D%0A%0A
+ // don't create the image upload if it was already created%0A // for this element%0A if ($self.data(%22imageUpload%22)) %7B return $self; %7D%0A%0A
// add c
|
488f05792b1eed4a8c47fce4038b3ff7db4ef0df
|
Simplify log messages
|
src/logging/request_message.js
|
src/logging/request_message.js
|
'use strict';
const getRequestMessage = function ({
protocolFullName,
protocolMethod,
path,
protocolStatus,
error,
actions = {},
fullAction,
}) {
const action = error ? fullAction : Object.keys(actions).join(' ');
const message = [
protocolStatus,
error,
'-',
protocolFullName,
protocolMethod,
path,
action,
].filter(val => val)
.join(' ');
return message;
};
module.exports = {
getRequestMessage,
};
|
JavaScript
| 0.999249 |
@@ -53,32 +53,24 @@
%7B%0A protocol
-FullName
,%0A protocol
@@ -293,16 +293,8 @@
ocol
-FullName
,%0A
|
2f46d5280f9b0b8dc3d130b8fe5dd91d249b1979
|
make the wait after slave start before configuring repl to be 40 sec
|
src/test/ed/db/repl/_repl.js
|
src/test/ed/db/repl/_repl.js
|
// _repl.js
/*
framework for replication testing
takes 1 paramter, the function to test.
that function takes 2 paramters, first is master db, second is slave db
*/
dbDir = "../p/db/";
masterPort = 5001;
slavePort = 5002;
try {
// start master
sysexec( "rm -rf /tmp/db-master" );
sysexec( "mkdir /tmp/db-master/" );
sysexec( "touch /tmp/db-master/a" );
master = fork(
function(){
print( "MASTER starting" );
sysexec( dbDir + "db --master --port " + masterPort + " --dbpath /tmp/db-master/" , null , null , null ,
{ out : function( s ){ print( "MASTER out: " + s ) } ,
err : function( s ){ print( "MASTER err: " + s ) }
}
);
}
);
master.start();
// start slave
sysexec( "rm -rf /tmp/db-slave" );
sysexec( "mkdir /tmp/db-slave/" );
sysexec( "touch /tmp/db-slave/a" );
slave = fork(
function(){
print( "SLAVE starting" );
sysexec( dbDir + "db --slave --port " + slavePort + " --dbpath /tmp/db-slave/" , null , null , null ,
{ out : function( s ){ print( "SLAVE out: " + s ) } ,
err : function( s ){ print( "SLAVE err: " + s ) }
}
);
}
);
slave.start();
sleep( 20000 );
print( "ADDING source" );
connect( "127.0.0.1:" + slavePort + "/local" ).sources.save( { host : "127.0.0.1:" + masterPort , source:"main"} );
sleep( 2000 );
// --------
// START REAL TEST
print(" ##### SETUP COMPLETE : STARTING TEST #####");
arguments[0](
connect( "127.0.0.1:" + masterPort + "/test" ) ,
connect( "127.0.0.1:" + slavePort + "/test" ),
{ masterPort : masterPort,
slavePort : slavePort,
replTimeMS : 40000
}
);
print(" ##### TEST COMPLETE : STARTING TEARDOWN #####");
}
finally {
// SHUTDOWN
print( "SHUTTING DOWN" );
sysexec( dbDir + "db msg end " + slavePort );
slave.join();
sysexec( dbDir + "db msg end " + masterPort );
master.join();
}
|
JavaScript
| 0.000003 |
@@ -1215,17 +1215,17 @@
sleep(
-2
+4
0000 );
|
c829f2572a45c721735e77fe92b40f93e357589a
|
Add css-only watch
|
gulpfile.js
|
gulpfile.js
|
/*
* gulpfile.js
*
* All automated tasks should find a home in here.
*/
var gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer'),
babelify = require('babelify'),
browserify = require('browserify'),
buffer = require('vinyl-buffer'),
concat = require('gulp-concat'),
gettextParser = require('gettext-parser'),
gutil = require('gulp-util'),
less = require('gulp-less'),
rename = require('gulp-rename'),
source = require('vinyl-source-stream'),
through = require('through2'),
uglify = require('gulp-uglify'),
webpack = require('webpack');
var paths = {
js: './themes/janeswalk/js',
js_lib: [
'./themes/janeswalk/js/app.js',
'./themes/janeswalk/js/extend.js',
'./themes/janeswalk/js/shims.js',
'./themes/janeswalk/js/tiny-pubsub.js'
],
jsx_app: './themes/janeswalk/js/router.jsx',
jsx_views: ['./themes/janeswalk/js/router.jsx'],
jsx: ['./themes/janeswalk/js/components/**/*.jsx'],
languages: './languages',
mos: ['./languages/*/*.mo'],
less: ['./themes/janeswalk/css/main.less'],
css: './themes/janeswalk/css/',
react_views: './themes/janeswalk/js/components/'
};
gulp.task('css', function() {
return gulp.src(paths.less)
.pipe(less({compress: false}))
.on('error', console.error.bind(console))
.pipe(autoprefixer('last 3 versions'))
.pipe(gulp.dest(paths.css));
});
gulp.task('js', function() {
gulp.run('js.theme', 'js.blocks', 'js.global');
});
gulp.task('js.theme', function() {
// TODO: transform: [babelify.configure({optional: ['optimisation.react.inlineElements']})],
webpack({
entry: [paths.jsx_app],
output: {
path: paths.js,
filename: 'janeswalk.js'
},
module: {
loaders: [{
test: /\.less$/,
loader: 'style!css!less'
}, {
test: /\.jsx?$/,
exclude: /(bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
},
}],
},
watch: true
}, function(err, stats) {
if(err) throw new gutil.PluginError("webpack:build", err);
gutil.log("[webpack:build]", stats.toString({
colors: true
}));
});
});
gulp.task('js.blocks', function() {
/*
// Run for each block view in array
return [
'./blocks/search/templates/header/',
'./blocks/page_list/templates/typeahead/',
'./blocks/page_list/templates/walk_filters/'
].map(function(template) {
return browserify({
entries: template + 'view.jsx',
transform: [babelify.configure({optional: ['optimisation.react.inlineElements']})],
extensions: ['.jsx', '.es6']
})
.bundle()
.pipe(source('view.js'))
.pipe(gulp.dest(template))
});
*/
[
'./blocks/search/templates/header/',
'./blocks/page_list/templates/typeahead/',
'./blocks/page_list/templates/walk_filters/'
].map(function(entry) {
webpack({
entry: [entry + 'view.jsx'],
output: {
path: entry,
filename: 'view.js'
},
module: {
loaders: [{
test: /\.less$/,
loader: 'style!css!less'
}, {
test: /\.jsx?$/,
exclude: /(bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
},
}],
},
}, function(err, stats) {
if(err) throw new gutil.PluginError("webpack:build", err);
gutil.log("[webpack:build]", stats.toString({
colors: true
}));
});
});
});
gulp.task('js.global', function() {
return browserify({
entries: './js/jwobject.jsx',
transform: [babelify.configure({optional: ['optimisation.react.inlineElements']})],
extensions: ['.jsx', '.es6']
})
.bundle()
.pipe(source('jwglobal.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./js/'));
});
// Build JSON from the mo files
gulp.task('i18n.json', function() {
gulp.src(paths.mos)
.pipe(
(function() {
var stream = through.obj(function(file, enc, cb) {
var locale = file.history[0].substring(file.base.length)
.split('/')[0];
var trans = gettextParser.mo.parse(file.contents);
// Remove redundant ID, as that's the key already
for (var i in trans.translations) {
for (var j in trans.translations[i]) {
var plural = trans.translations[i][j]['msgid_plural'];
if (plural) {
// Build the key for plurals as singular_plural
trans.translations[i][j + '_' + plural] =
trans.translations[i][j]['msgstr'];
delete trans.translations[i][j];
} else {
trans.translations[i][j] = trans.translations[i][j]['msgstr'];
}
}
}
file.contents = new Buffer(JSON.stringify(trans));
file.path = gutil.replaceExtension(file.path, '.json');
cb(null, file);
});
return stream;
})())
.pipe(gulp.dest(paths.languages));
});
// Placeholder for 'download po and build mos' task
gulp.task('i18n.mo', function() {
var options = {
username: 'janeswalk_anon',
password: 'anonemouse'
}
});
gulp.task('watch', function() {
gulp.watch(paths.css + '**/*.less', ['css']);
gulp.watch(paths.jsx, ['js.theme']);
gulp.watch(paths.jsx_views, ['js.theme']);
gulp.watch('./blocks/**/*.jsx', ['js.blocks']);
});
gulp.task('default', function() {
// place code for your default task here
});
|
JavaScript
| 0 |
@@ -1354,32 +1354,121 @@
ths.css));%0A%7D);%0A%0A
+gulp.task('watch.css', function() %7B%0A gulp.watch(paths.css + '**/*.less', %5B'css'%5D);%0A%7D);%0A%0A
gulp.task('js',
|
002431c3b352544acc86240e2b42fb7c85e20781
|
Check for undefined var in clearEvents
|
src/basic/BasicEventRenderer.js
|
src/basic/BasicEventRenderer.js
|
function BasicEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.clearEvents = clearEvents;
// imports
DayEventRenderer.call(t);
function renderEvents(events, modifiedEventId) {
t.renderDayEvents(events, modifiedEventId);
}
function clearEvents() {
t.getDaySegmentContainer().empty();
}
// TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div
}
|
JavaScript
| 0 |
@@ -293,18 +293,84 @@
nts() %7B%0A
-%09%09
+ if (t.getDaySegmentContainer() !== undefined) %7B%0A
t.getDay
@@ -397,16 +397,26 @@
mpty();%0A
+ %7D%0A
%09%7D%0A%0A%0A%09//
|
7aade0df50e5f6d6d306282014bf45d0e7ef1505
|
Fix button unit test
|
src/components/button/Button.spec.js
|
src/components/button/Button.spec.js
|
import { shallowMount, mount } from '@vue/test-utils'
import BButton from '@components/button/Button'
import config, {setOptions} from '@utils/config'
let wrapper
describe('BButton', () => {
beforeEach(() => {
wrapper = shallowMount(BButton)
})
it('is called', () => {
expect(wrapper.name()).toBe('BButton')
expect(wrapper.isVueInstance()).toBeTruthy()
})
it('render correctly', () => {
expect(wrapper.html()).toMatchSnapshot()
})
it('emit a click event', () => {
const click = jest.fn()
wrapper.vm.$on('click', click)
wrapper.find('.button').trigger('click')
expect(click).toHaveBeenCalledTimes(1)
})
it('should show icon', () => {
wrapper = mount(BButton, {
propsData: {
iconLeft: 'plus'
}
})
expect(wrapper.contains('.icon')).toBe(true)
})
it('should be medium', () => {
wrapper = shallowMount(BButton, {
propsData: {
size: 'is-medium'
}
})
expect(wrapper.classes()).toContain('is-medium')
})
it('should be small + icon', () => {
wrapper = mount(BButton, {
propsData: {
size: 'is-small',
iconLeft: 'plus'
}
})
expect(wrapper.classes()).toContain('is-small')
expect(wrapper.contains('.icon')).toBe(true)
})
it('should be large + icon', () => {
wrapper = mount(BButton, {
propsData: {
size: 'is-large',
iconLeft: 'plus'
}
})
expect(wrapper.classes()).toContain('is-large')
expect(wrapper.contains('.icon')).toBe(true)
})
it('should be rounded when default config set to true', () => {
setOptions(Object.assign(config, {
defaultButtonRounded: true
}))
wrapper = mount(BButton, {
propsData: {
rounded: config.defaultButtonRounded
}
})
expect(wrapper.classes()).toContain('is-rounded')
})
})
|
JavaScript
| 0 |
@@ -573,30 +573,114 @@
pper
-.vm.$on(
+ = shallowMount(BButton, %7B%0A listeners: %7B%0A
'click'
-,
+:
click
+%0A %7D%0A %7D
)%0A
|
7277426185aa014badd8404b5a37431be19042ca
|
Update inject.js
|
js/inject.js
|
js/inject.js
|
var s = document.createElement('script');
s.src = "https://rawgit.com/joshisa/huemix-blopscotch/master/js/hopscotch.highlight.js";
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head || document.documentElement).appendChild(s);
chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
var prefix = "[Huemix Blopscotch]] ";
console.log(prefix + "current page URL is: " + location.href);
// https://api.github.com/repos/joshisa/huemix-blopscotch/git/trees/master?recursive=1
// Array of registered hoplets
whitelist = ["hoplet/demo.js",
"hoplet/jstart.js",
"hoplet/jupyter2.js",
"hoplet/spark.js"];
console.log(prefix + "Number of Hoplets defined : " + whitelist.length);
var i = 0;
while (whitelist[i]) {
// https://rawgit.com/joshisa/huemix-blopscotch/master/ + whitelist[i]
console.log(prefix + "Loading " + whitelist[i]);
proxyXHR.get('https://rawgit.com/joshisa/huemix-blopscotch/master/' + whitelist[i]).onSuccess(function (data) {
eval(data);
});
i++;
}
console.log(prefix + "Hopscotch Dependencies successfully injected");
}
}, 10);
});
|
JavaScript
| 0.000002 |
@@ -1,55 +1,18 @@
-var s = document.createElement('script');%0As.src = %22
+proxyXHR.get('
http
@@ -88,30 +88,29 @@
t.js
-%22;%0As.onload =
+').onSuccess(
function
() %7B
@@ -105,25 +105,30 @@
function
-(
+ (data
) %7B%0A
this.par
@@ -123,45 +123,99 @@
-this.parentNode.removeChild(this);%0A%7D;
+eval(data);%0A console.log(%22%5BHuemix Blopscotch%5D%5D Hopscotch lib loaded!%22);%0A%7D);%0A
%0A(do
|
2173b34505eceebd34c4d1cc07a17036f6d326db
|
edit for new button style
|
1019.js
|
1019.js
|
// 35-001 #1019 display WRLC Digital Object on bib even if flagged as Finding Aid
//
//
casper.test.begin('m35_001 #1019 WRLC Digital Object along with Finding Aid', 5, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/2495607';
var ENTITY=SERVER+USECASE;
casper.start(ENTITY, function() {
test.assertTextExists('Timothy Vedder' , 'matched title');
test.assertTextExists('Special Collections Vault' , 'matched holding spec vault');
test.assertTextExists('WRLC Libraries Digital' , 'matched holding WRLC digital collection');
test.assertTextExists('Finding Aid' , 'matched finding aid link');
test.assertTextExists('Online' , 'found online link');
}).run(function() {
test.done();
});
});
|
JavaScript
| 0 |
@@ -161,17 +161,17 @@
g Aid',
-5
+4
, functi
@@ -429,13 +429,8 @@
ons
-Vault
' ,
@@ -455,107 +455,8 @@
pec
-vault');%0A%09test.assertTextExists('WRLC Libraries Digital' , 'matched holding WRLC digital collection
');%0A
|
502d47822cb9a7700e34e6a8fdcd2324d68b6c07
|
fix tasks for styles
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp'),
changed = require('gulp-changed'),
csso = require('gulp-csso'),
autoprefixer = require('gulp-autoprefixer'),
browserify = require('browserify'),
watchify = require('watchify'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
reactify = require('reactify'),
del = require('del'),
notify = require('gulp-notify'),
browserSync = require('browser-sync'),
reload = browserSync.reload,
p = {
jsx: ['./lib/scripts/app.jsx'],
css: ['lib/styles/main.css', 'lib/styles/bootstrap.min.css'],
bundle: 'app.js',
distJs: 'dist/js',
distCss: 'dist/css'
};
gulp.task('clean', function(cb) {
del(['dist'], cb);
});
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: './'
}
})
});
gulp.task('watchify', function() {
var bundler = watchify(browserify(p.jsx, watchify.args));
function rebundle() {
return bundler
.bundle()
.on('error', notify.onError())
.pipe(source(p.bundle))
.pipe(gulp.dest(p.distJs))
.pipe(reload({stream: true}));
}
bundler.transform(reactify)
.on('update', rebundle);
return rebundle();
});
gulp.task('browserify', function() {
browserify(p.jsx)
.transform(reactify)
.bundle()
.pipe(source(p.bundle))
.pipe(buffer())
.pipe(gulp.dest(p.distJs));
});
gulp.task('styles', function() {
gulp.watch('lib/styles/**/*.css', function () {
return gulp.src(p.css)
.pipe(changed(p.distCss))
.pipe(autoprefixer('last 1 version'))
.pipe(csso())
.pipe(gulp.dest(p.distCss))
.pipe(reload({stream: true}));
});
});
gulp.task('watchTask', function() {
gulp.watch(p.scss, ['styles']);
});
gulp.task('watch', ['clean'], function() {
gulp.start(['browserSync', 'watchify']);
});
gulp.task('build', ['clean'], function() {
process.env.NODE_ENV = 'production';
gulp.start(['browserify', 'styles']);
});
gulp.task('default', ['build', 'watch']);
|
JavaScript
| 0.000112 |
@@ -1452,60 +1452,8 @@
) %7B%0A
- gulp.watch('lib/styles/**/*.css', function () %7B%0A
re
@@ -1473,26 +1473,24 @@
(p.css)%0A
-
-
.pipe(change
@@ -1495,34 +1495,32 @@
ged(p.distCss))%0A
-
.pipe(autopr
@@ -1545,18 +1545,16 @@
sion'))%0A
-
.pip
@@ -1563,26 +1563,24 @@
csso())%0A
-
.pipe(gulp.d
@@ -1591,26 +1591,24 @@
p.distCss))%0A
-
.pipe(re
@@ -1634,16 +1634,8 @@
));%0A
- %7D);%0A
%7D);%0A
@@ -1686,17 +1686,16 @@
watch(p.
-s
css, %5B's
@@ -1787,19 +1787,42 @@
, 'watch
-ify
+Task', 'watchify', 'styles
'%5D);%0A%7D);
|
3bc4f35030c98bcc49638825d50521dd0b523a91
|
add flow to helpers.js
|
src/core/helpers.js
|
src/core/helpers.js
|
const normalize = (fields) => {
if (Array.isArray(fields)) {
return fields.reduce((prev, curr) => {
if (~curr.indexOf('.')) {
prev[curr.split('.')[1]] = curr;
} else {
prev[curr] = curr;
}
return prev;
}, {});
}
return fields;
};
/**
* Maps fields to computed functions.
*
* @param {Array|Object} fields
*/
const mapFields = (fields) => {
const normalized = normalize(fields);
return Object.keys(normalized).reduce((prev, curr) => {
const field = normalized[curr];
prev[curr] = function mappedField () {
// if field exists
if (this.$validator.flags[field]) {
return this.$validator.flags[field];
}
// if it has a scope defined
const index = field.indexOf('.');
if (index <= 0) {
return {};
}
let [scope, ...name] = field.split('.');
scope = this.$validator.flags[`$${scope}`];
name = name.join('.');
if (scope && scope[name]) {
return scope[name];
}
return {};
};
return prev;
}, {});
};
export default mapFields;
|
JavaScript
| 0.000001 |
@@ -1,20 +1,30 @@
+// @flow%0A%0A
const normalize = (f
@@ -20,33 +20,62 @@
malize = (fields
-)
+: Array%3Cany%3E %7C Object): Object
=%3E %7B%0A if (Arra
@@ -367,71 +367,65 @@
.%0A *
-%0A * @param %7BArray%7CObject%7D fields%0A */%0Aconst mapFields = (fields)
+/%0Aconst mapFields = (fields: Array%3Cany%3E %7C Object): Object
=%3E
|
8976350702d8ebe73636cc51b98072c4f52f1687
|
Fix missing semicolon
|
lib/Layer.js
|
lib/Layer.js
|
var Model = require('./Model');
var triggerParams = require('./mixins/triggerParams');
var volumeParams = require('./mixins/volumeParams');
var connectable = require('./mixins/connectable');
var bypassable = require('./mixins/bypassable');
var Params = require('./Params');
var context = null;
function createPool (factoryName) {
var nodes = [];
return function pool(node) {
if (node) {
nodes.push(node);
}
else if (nodes.length) {
return nodes.shift();
}
else {
return context[factoryName]();
}
};
}
var gainPool = createPool('createGain');
var pannerPool = createPool('createPanner');
var destination = null;
var Layer = Model.extend(triggerParams, volumeParams, {
type: 'layer',
props: {
sources: ['object', true, function () { return {}; }]
},
start: function (time, note, channel, pattern, kit, slot) {
if (this.mute) { return; }
if (typeof time !== 'number') {
pattern = channel;
channel = note;
note = time;
time = this.context.currentTime;
}
note = note || {};
context = context || this.context;
var params = this._params(note, channel, pattern, kit, slot);
var source = this._source(params);
if (source) {
var connections = this._getConnections(note, channel, pattern);
var destination = this._connectDestination(connections, params);
var gain = source._gain = gainPool();
this._configureAttack(time, params, gain, destination);
var panner = this._configurePan(params, gain);
source.connect(panner || gain);
this._startSource(time, params, source);
this._triggerPlaybackStateEvent('started', time, params, note, channel, pattern, kit, slot);
var cid = note.cid || 'null';
this.sources[cid] = this.sources[cid] || [];
this.sources[cid].push(source);
if (params.length) {
var stopTime = this._getStopTime(time, params, source);
this.stop(stopTime, note, channel, pattern);
}
source.onended = function () {
var index = this.sources[cid].indexOf(source);
this.sources[cid].splice(index, 1);
gain.disconnect();
source.disconnect();
if (panner) {
panner.disconnect();
pannerPool(panner);
}
gainPool(gain);
this._triggerPlaybackStateEvent('stopped', this.context.currentTime, params, note, channel, pattern, kit, slot);
source = source.onended = source._gain = gain = panner = null;
if (typeof note.after === 'function') note.after();
}.bind(this);
}
},
_getStopTime: function (time, params, source) {
return time + params.length;
},
_triggerPlaybackStateEvent: function(event, time, params, note, channel, pattern, kit, slot) {
var lookahead = Math.floor((time - context.currentTime) * 1000) - 1;
if (lookahead < 0) lookahead = 0;
setTimeout(function () {
[note, channel, pattern, kit, slot, this].forEach(function (target) {
target.trigger(event, note, params)
});
}, lookahead);
},
stop: function (time, note, channel, pattern, kit, slot) {
if (typeof time !== 'number') {
pattern = channel;
channel = note;
note = time;
time = this.context.currentTime;
}
note = note || {};
var params = this._params(note, channel, pattern, kit, slot);
var cid = note.cid || 'null';
var sources = this.sources[cid] || [];
if (cid === 'null') {
sources = [];
Object.keys(this.sources).forEach(function (cid) {
sources = sources.concat(this.sources[cid]);
}.bind(this));
}
sources.forEach(function (source) {
if (source._gain) {
this._configureRelease(time, params, source._gain);
}
this._stopSource(time, params, source);
}.bind(this));
},
_paramsSources: function (note, channel, pattern, kit, slot) {
slot = slot || this.collection && this.collection.parent || {};
kit = kit || slot && slot.kit || {};
var patternParams = {
volume: pattern && pattern.volume,
pitch: pattern && pattern.pitch,
pan: pattern && pattern.pan
};
return [note, channel, patternParams, this, slot, kit];
},
_params: function (note, channel, pattern, kit, slot) {
var sources = this._paramsSources(note, channel, pattern, kit, slot);
return Params.fromSources(sources);
},
_getConnections: function (note, channel, pattern) {
var sources = this._paramsSources(note, channel, pattern);
var connections = [];
sources.forEach(function (source) {
if (source && source.connections) {
connections = connections.concat(source.connections);
}
});
return connections;
},
_createGain: function (params, source) {
return this.context.createGain();
},
_startSource: function (time, params, source) {
source.start(time);
},
_stopSource: function (time, params, source) {
source.stop(time);
},
_source: function (params) {
throw new Error('Required method "_source" is not implemented for ' + this.cid);
},
_getLocalDestination: function () {
if (!destination) {
destination = gainPool();
destination.connect(this.context.destination);
}
destination.gain.value = (this.vent.bap.volume / 100) * 0.8;
return destination;
},
_connectDestination: function (connections, params) {
var localDestination = this._getLocalDestination();
if (params.bypass === true) return localDestination;
var cid = this.cid;
connections.filter(function (connection) {
if (params.bypass === connection.type || Array.isArray(params.bypass) && ~params.bypass.indexOf(connection.type)) return false;
return !connection.bypass;
}).reverse().forEach(function (connection, index, list) {
var next = list[index - 1];
var node = connection.getNode(next && next.cid || 'destination');
if (node.__connectedTo && node.__connectedTo !== localDestination) {
console.error('Attempted to reconnect already connected effect (' + connection.cid + ') for target ' + cid);
}
else if (!node._connectedTo) {
node.connect(localDestination);
node._connectedTo = localDestination;
}
localDestination = node;
});
return localDestination;
},
_configurePan: function (params, out) {
if (params.pan !== 0) {
var panner = pannerPool();
var x = params.pan / 100;
var z = 1 - Math.abs(x);
panner.setPosition(x, 0, z);
panner.connect(out);
return panner;
}
},
_configureAttack: function (time, params, gain, destination) {
var volume = (params.volume !== null && params.volume !== undefined ? params.volume : 100) / 100;
gain.connect(destination);
gain.gain.value = 0;
gain.gain.setValueAtTime(0, time);
gain.gain.linearRampToValueAtTime(volume, time + params.attack);
},
_configureRelease: function (time, params, gain) {
var volume = (params.volume !== null && params.volume !== undefined ? params.volume : 100) / 100;
if (params.release) {
gain.gain.cancelScheduledValues(time - 0.001);
gain.gain.linearRampToValueAtTime(volume, time - params.release);
gain.gain.linearRampToValueAtTime(0, time);
}
}
}, connectable);
module.exports = Layer;
|
JavaScript
| 0.999999 |
@@ -3044,16 +3044,17 @@
params)
+;
%0A %7D
|
6abbde3f43d2488d46d99da9e84a3cc49bca56bc
|
fix "use http" link
|
js/events.js
|
js/events.js
|
var helpers = require('./helpers')
var events = function(){
body = $('body')
stage = $('#stage')
back = $('a.back')
var file = null
var url = ''
var url = location.href
if ( ! SSL && url.split('://')[0] === 'https') {
$('footer').css('opacity', '1')
$('footer').html("You need to use HTTP. This is just as secure since we use end-to-end encryption. <a href='' id=reloadUsingHTTP>Use HTTP</a>")
$('#reloadUsingHTTP').prop('href',
'http://' + url.split(':///')[1]
)
}
$('#step1 .button').css('cursor', 'default')
$('#step1').on('change', '#send-input', function(e){
helpers.sendOnIncoming(conn, e.target.files[0], password)
body.attr('class', 'send')
helpers.step(2)
})
back.click(function() { // The back button
stopTransfer = function () { return true }
helpers.connectToBroker('reconnect')
$('#send-input').replaceWith(function() {
return $(this).clone() // Reinitialize the hidden file input
})
if (anchor) {
window.location.hash = ''
helpers.visualReadyStatus()
}
helpers.step(1)
})
}
module.exports = events
|
JavaScript
| 0.00051 |
@@ -483,17 +483,16 @@
lit('://
-/
')%5B1%5D%0A
|
70d43eceb200bd15848af3ed37fbeaef93b0e610
|
jshint task
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var bowerFiles = require('main-bower-files');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var livereload = require('gulp-livereload');
var jshint = require('gulp-jshint');
// jshint
gulp.task('jshint', function() {
return gulp.src('src/js/**/*.js')
.pipe(jshint())
});
// concat js into one min file javascript.min.js
gulp.task('js-min', function() {
return gulp.src(['src/js/app.js', 'src/js/**/*.js'])
.pipe(concat('javascript.js'))
.pipe(gulp.dest('js'))
.pipe(uglify())
.pipe(rename('javascript.min.js'))
.pipe(gulp.dest('js'));
});
// All bower dependecies become vendor.min.js
gulp.task('vendor-min', function() {
return gulp.src(bowerFiles())
.pipe(concat('vendor.js'))
.pipe(gulp.dest('js'))
.pipe(uglify())
.pipe(rename('vendor.min.js'))
.pipe(gulp.dest('js'));
});
// the default task
// checks all files and reloads index
gulp.task('default', function() {
livereload.listen();
gulp.watch(['src/**/*', 'index.html'],
[
'js-min',
function() { livereload.reload('index.html'); }
]
);
});
|
JavaScript
| 0.999956 |
@@ -360,16 +360,54 @@
hint())%0A
+ .pipe(jshint.reporter('default'))%0A
%7D);%0A%0A//
@@ -1118,16 +1118,17 @@
%0A %5B
+
%0A '
|
cca081c1cd9403f3c85619c0b70ee08527681f31
|
Clean up code
|
webapp/app/scripts/controllers/header-controller.js
|
webapp/app/scripts/controllers/header-controller.js
|
'use strict';
angular.module('gpConnect')
.controller('headerController', function ($scope, $rootScope, $state, usSpinnerService, $stateParams, UserService, $modal) {
// Get current user
UserService.setCurrentUserFromQueryString();
$scope.currentUser = UserService.getCurrentUser();
// Direct different roles to different pages at login
switch ($scope.currentUser.role) {
case 'gpconnect':
$state.go('main-search');
break;
case 'phr':
$state.go('patients-summary', {
patientId: 9999999000
}); // id is hard coded
break;
default:
$state.go('patients-summary', {
patientId: 9999999000
}); // id is hard coded
}
$rootScope.$on('$stateChangeSuccess', function (event, to, toParams, from, toState) {
$scope.backState = from.name;
var previousState = '';
var pageHeader = '';
var previousPage = '';
var mainWidth = 0;
var detailWidth = 0;
switch (toState.name) {
case 'main-search':
previousState = '';
pageHeader = 'Welcome';
previousPage = '';
mainWidth = 12;
detailWidth = 0;
break;
case 'patients-list':
previousState = 'main-search';
pageHeader = 'Patient Lists';
previousPage = 'Patient Dashboard';
mainWidth = 12;
detailWidth = 0;
break;
case 'patients-summary':
previousState = 'patients-list';
pageHeader = 'Patient Summary';
previousPage = 'Patient Lists';
mainWidth = 11;
detailWidth = 0;
break;
case 'patients-lookup':
previousState = '';
pageHeader = 'Patients lookup';
previousPage = '';
mainWidth = 6;
detailWidth = 6;
break;
default:
previousState = 'patients-list';
pageHeader = 'Patients Details';
previousPage = 'Patient Lists';
mainWidth = 11;
detailWidth = 0;
break;
}
$scope.pageHeader = pageHeader;
$scope.previousState = previousState;
$scope.previousPage = previousPage;
$scope.mainWidth = mainWidth;
$scope.detailWidth = detailWidth;
$scope.goBack = function (patient) {
var requestHeader = {
patientId: $stateParams.patientId
};
$state.go($scope.backState, requestHeader);
};
$scope.userContextViewExists = ('user-context' in $state.current.views);
$scope.actionsExists = ('actions' in $state.current.views);
$scope.go = function (patient) {
$state.go('patients-summary', {
patientId: patient.id
});
};
if ($scope.currentUser.role === 'gpconnect') {
$scope.title = UserService.getContent('gpconnect_title');
$scope.privacy = UserService.getContent('gpconnect_privacy');
}
if ($scope.currentUser.role === 'phr') {
$scope.title = UserService.getContent('phr_title');
}
$scope.footer = UserService.getContent('gpconnect_footer');
$scope.goHome = function () {
if ($scope.currentUser.role === 'gpconnect') {
$state.go('main-search');
}
if ($scope.currentUser.role === 'phr') {
$state.go('patients-summary', {
patientId: 9999999000
}); // Id is hardcoded
}
};
$scope.gpConnectInfo = function () {
$modal.open({
templateUrl: 'views/application/information-modal.html',
size: 'lg',
controller: 'InformationModalCtrl'
});
};
});
});
|
JavaScript
| 0.000004 |
@@ -2243,31 +2243,24 @@
= function (
-patient
) %7B%0A%09%09var re
|
722b881cfe1b9e014fb66b6fe3dfd02e632fe89d
|
make links in friend hovercard work
|
server/static/js/friend.js
|
server/static/js/friend.js
|
define(
['rmc_backbone', 'ext/jquery', 'ext/underscore', 'ext/underscore.string',
'ext/bootstrap', 'ext/slimScroll', 'course'],
function(RmcBackbone, $, _, _s, bootstrap, __, _course) {
var FriendView = RmcBackbone.View.extend({
className: 'friend',
initialize: function(attributes) {
this.friendModel = attributes.friendModel;
this.mutualCourses = this.friendModel.get('mutual_courses');
},
render: function() {
this.$el.html(
_.template($('#friend-tpl').html(), {
friend: this.friendModel,
mutual_courses: this.mutualCourses
}));
this.$('.friend-name')
.popover({
html: true,
title: this.friendModel.get('last_term_name'),
content: _.bind(this.getFriendPopoverContent, this),
trigger: 'hover',
placement: 'in right'
})
.on('click', '.popover', function(evt) {
// Prevent clicking in the hovercard from going to triggering the
// link the hovercard is attached to
return false;
});
this.$('.mutual-courses')
.popover({
html: true,
title: 'Mutual Courses',
content: _.bind(this.getMutualCoursesPopoverContent, this),
trigger: 'hover',
placement: 'in right'
})
.click(function(evt) {
// Prevent clicking in the hovercard from going to triggering the
// link the hovercard is attached to
return false;
});
return this;
},
getFriendPopoverContent: function() {
if (!this.friendPopoverView) {
this.friendHovercardView = new FriendHovercardView({
friendModel: this.friendModel
});
}
return this.friendHovercardView.render().$el;
},
getMutualCoursesPopoverContent: function() {
if (!this.mutualCoursesPopoverView) {
this.mutualCoursesHovercardView = new MutualCoursesHovercardView({
friendModel: this.friendModel,
mutualCourses: this.mutualCourses
});
}
var $el = this.mutualCoursesHovercardView.render().$el;
window.setTimeout(function() {
var maxHeight = 250;
if ($el.find('.mini-courses').outerHeight() > maxHeight) {
$el.slimScroll({
height: maxHeight,
width: $el.outerWidth(),
alwaysVisible: true
});
}
});
return $el;
}
});
var FriendHovercardView = RmcBackbone.View.extend({
className: 'friend-hovercard',
initialize: function(attributes) {
this.friendModel = attributes.friendModel;
this.lastTermCourses = this.friendModel.get('last_term_courses');
},
render: function() {
this.$el.html(
_.template($('#friend-hovercard-tpl').html(), {
friend: this.friendModel,
last_term_courses: this.lastTermCourses
}
));
return this;
}
});
var MutualCoursesHovercardView = RmcBackbone.View.extend({
className: 'mutual-courses-hovercard',
initialize: function(options) {
this.friendModel = options.friendModel;
this.mutualCourses = options.mutualCourses;
},
render: function() {
this.$el.html(
_.template($('#mutual-courses-hovercard-tpl').html(), {
friend: this.friendModel,
mutual_courses: this.mutualCourses
}));
return this;
}
});
var FriendCollectionView = RmcBackbone.CollectionView.extend({
tagName: 'ol',
className: 'friend-collection',
createItemView: function(model) {
return new FriendView({ friendModel: model });
}
});
FriendSidebarView = RmcBackbone.View.extend({
className: 'friend-sidebar',
initialize: function(attributes) {
this.friendCollection = attributes.friendCollection;
this.profileUser = attributes.profileUser;
},
render: function() {
this.$el.html(_.template($('#friend-sidebar-tpl').html(), {
num_friends: this.friendCollection.length,
own_profile: this.profileUser.get('own_profile')
}));
var collectionView = new FriendCollectionView({
collection: this.friendCollection
});
this.$('.friend-collection-placeholder').replaceWith(
collectionView.render().$el);
return this;
}
});
return {
FriendView: FriendView,
FriendHovercardView: FriendHovercardView,
FriendCollectionView: FriendCollectionView,
FriendSidebarView: FriendSidebarView
};
});
|
JavaScript
| 0 |
@@ -1026,32 +1026,74 @@
is attached to%0A
+ if (!$(evt.target).is('a')) %7B%0A
return
@@ -1092,32 +1092,44 @@
return false;%0A
+ %7D%0A
%7D);%0A%0A
@@ -1520,32 +1520,74 @@
is attached to%0A
+ if (!$(evt.target).is('a')) %7B%0A
return
@@ -1586,32 +1586,44 @@
return false;%0A
+ %7D%0A
%7D);%0A%0A
|
8042b1d96e527776b2ee3fcd8926bb2d109dfa65
|
Include rules and long_description from API
|
app/models/project.js
|
app/models/project.js
|
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr("string"),
description: DS.attr("string"),
startAt: DS.attr("date"),
percentageComplete: DS.attr("number"),
totalTargetsCount: DS.attr("number"),
fixedTargetsCount: DS.attr("number"),
pendingTargetsCount: DS.attr("number"),
percentageThrough: function() {
var perc = this.get("percentageComplete");
return "width: " + perc + "%;";
}.property("percentageComplete"),
});
|
JavaScript
| 0 |
@@ -117,16 +117,82 @@
ring%22),%0A
+ longDescription: DS.attr(%22string%22),%0A rules: DS.attr(%22string%22),%0A
startA
|
7ac0db337aa4564c679b46586fc2cd46330211d9
|
improve room buttons
|
src/components/chat/RoomSelection.js
|
src/components/chat/RoomSelection.js
|
import React, { Component, PropTypes } from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as firebase from 'firebase/firebase-browser';
import {getChatRoomsSuccess, accessRoom} from '../../actions/chatActions';
class RoomSelection extends Component {
componentWillMount() {
const chatRoomsRef = firebase.database().ref('chatRooms');
chatRoomsRef.on('child_added', data => {
this.props.getChatRoomsSuccess(data.key, data.val());
});
}
accessRoom(roomKey) {
this.props.accessRoom(roomKey);
}
render() {
return (
<div className="flex-column align-center">
<h4>Select a chat room</h4>
{
Object.keys(this.props.chatRooms).length > 0
&& (
<div className="selector">
{
Object.keys(this.props.chatRooms).map((roomKey) => (
<div
key={roomKey}
className="selector-button"
onClick={() => this.accessRoom(roomKey)}
>
<p>{this.props.chatRooms[roomKey].name}</p>
</div>
))
}
</div>
)
}
</div>
);
}
}
RoomSelection.propTypes = {
chatRooms: PropTypes.object,
currentUser: PropTypes.string,
accessRoom: PropTypes.func,
getChatRoomsSuccess: PropTypes.func
};
function mapStateToProps(state, ownProps) {
return {
currentUser: state.user.uid,
chatRooms: state.chat.rooms
};
}
function mapDispatchToProps(dispatch) {
return {
accessRoom: bindActionCreators(accessRoom, dispatch),
getChatRoomsSuccess: bindActionCreators(getChatRoomsSuccess, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(RoomSelection);
|
JavaScript
| 0.000002 |
@@ -739,72 +739,71 @@
ms).
-length %3E 0%0A && (%0A %3Cdiv className=%22selector%22%3E
+map((roomKey) =%3E (%0A %3Cdiv%0A key=%7BroomKey%7D
%0A
@@ -805,32 +805,39 @@
%7D%0A
+style=%7B
%7B%0A
@@ -842,172 +842,458 @@
-Object.keys(this.props.chatRooms).map((roomKey) =%3E (%0A %3Cdiv%0A key=%7BroomKey%7D%0A className=%22selector-button%22%0A
+borderColor: 'rgb(200, 200, 200)',%0A margin: '8px 0',%0A borderWidth: '1px',%0A borderStyle: 'solid',%0A borderRadius: '45px',%0A height: '30px',%0A padding: '5px 15px',%0A cursor: 'pointer',%0A marginRight: '20px',%0A display: 'flex',%0A justifyContent: 'center',%0A alignItems: 'center'%0A %7D%7D%0A
@@ -1359,19 +1359,10 @@
- %3E%0A
+%3E%0A
@@ -1375,14 +1375,14 @@
-
%3Cp%3E
+%7B%60$
%7Bthi
@@ -1417,73 +1417,17 @@
ame%7D
+ %3E%60%7D
%3C/p%3E%0A
- %3C/div%3E%0A ))%0A %7D%0A
@@ -1437,24 +1437,24 @@
%3C/div%3E%0A
-
)%0A
@@ -1452,16 +1452,17 @@
)
+)
%0A
|
6604cc02269a0d99ed77eb6077ee1f19d7c89231
|
Add comment about from var setting after success
|
client/client.js
|
client/client.js
|
var map = null;
var legend = document.getElementById('legend');
var mapStyle = require('./map-style.json');
var pointsStyle = require('./points-style.json');
function initMap() {
// Create a map object and specify the DOM element for display.
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 38.922239,
lng: -95.794675
},
disableDefaultUI: true,
styles: mapStyle,
zoom: 5
});
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);
}
var pageviews = 0;
var commitments = 0;
var from = null;
var to = null;
var lastEvaluatedKey;
// Displays the points data provided.
function displayPoints(data) {
return new Promise(function(resolve) {
if (data.hasOwnProperty('LastEvaluatedKey')) lastEvaluatedKey = data.LastEvaluatedKey.Id;
else lastEvaluatedKey = 'finished';
for (var i = 0; i < data.Items.length; i++) {
var LatLng = new google.maps.LatLng({
lat: data.Items[i].Coordinates[0],
lng: data.Items[i].Coordinates[1]
});
var circle = new google.maps.Circle({
fillColor: pointsStyle[data.Items[i].Action].fillColor,
fillOpacity: pointsStyle[data.Items[i].Action].fillOpacity,
map: map,
center: LatLng,
radius: pointsStyle[data.Items[i].Action].radius,
strokeWeight: 0
});
if (data.Items[i].Action === 'view') pageviews++;
if (data.Items[i].Action === 'commitment') commitments++;
}
document.getElementById('pageviews').innerText = pageviews;
document.getElementById('commitments').innerText = commitments;
resolve('All points processed');
});
}
function get(url) {
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.setRequestHeader('Content-Type', 'application/json');
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
} else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
statusBad('Disconnected, server error');
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
statusBad('Disconnected, network error');
reject(Error('Network Error'));
};
// Make the request
req.send();
});
}
// Delay for a number of milliseconds
function delay(t) {
return new Promise(function(resolve) {
setTimeout(resolve, t);
});
}
// https://medium.com/adobe-io/how-to-combine-rest-api-calls-with-javascript-promises-in-node-js-or-openwhisk-d96cbc10f299
// https://gist.github.com/trieloff/168312d4dd4d149afdd55cde3d3724cabea
var promiseChain = {
runChain: function() {
var timeString = '';
if (from === null) { // If from time is not specified, default to the beginning of today.
var d = new Date();
d.setHours(0, 0, 0, 0);
from = d.getTime() / 1000;
}
if (to === null) { // If to time is not specified, default to now
to = new Date() / 1000;
}
timeString = 'from=' + from + '&to=' + to + '&';
var exclusiveStartKeyString = '';
if (lastEvaluatedKey != undefined && lastEvaluatedKey != 'finished') {
exclusiveStartKeyString = 'exclusivestartkey=' + lastEvaluatedKey;
}
get('/rest/live/read?' + timeString + exclusiveStartKeyString).then(JSON.parse).then(displayPoints).then(function() {
if (lastEvaluatedKey !== 'finished') promiseChain.runChain();
else {
// Done paginating through data
from = to + 0.001;
to = null;
statusGood('Map connected live');
return delay(3000).then(function() {
promiseChain.runChain();
});
}
}).catch(function() {
return delay(3000).then(function() {
promiseChain.runChain();
});
});
}
};
var midnight = new Date();
midnight.setDate(new Date().getDate()+1);
midnight.setHours(0,0,0,0);
midnight = midnight / 1000;
var now = new Date() / 1000;
midnight = midnight - now;
midnight = midnight + 5; // Add 5 seconds as a cushion
setTimeout(
midnightTask,
midnight * 1000
);
function midnightTask() {
window.location.reload(true);
}
promiseChain.runChain(); // execute function
|
JavaScript
| 0 |
@@ -3530,16 +3530,90 @@
+ 0.001;
+ // Next time, get data starting one millisecond after the last time range
%0A%09%09%09%09to
|
e27303a4c01f28ef4791fbe34cde9adbba77b888
|
Update fmfwio.js
|
js/fmfwio.js
|
js/fmfwio.js
|
'use strict';
// ---------------------------------------------------------------------------
const hitbtc = require ('./hitbtc.js');
// ---------------------------------------------------------------------------
module.exports = class fmfwio extends hitbtc {
describe () {
return this.deepExtend (super.describe (), {
'id': 'fmfwio',
'alias': true,
'name': 'FMFW.io',
'countries': [ 'KN' ],
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/159177712-b685b40c-5269-4cea-ac83-f7894c49525d.jpg',
'api': {
'public': 'https://api.fmfw.io',
'private': 'https://api.fmfw.io',
},
'www': 'https://fmfw.io',
'doc': 'https://api.fmfw.io/api/2/explore/',
'fees': 'https://fmfw.io/fees-and-limits',
'referral': 'https://fmfw.io/referral/da948b21d6c92d69',
},
'fees': {
'trading': {
'maker': this.parseNumber ('0.005'),
'taker': this.parseNumber ('0.005'),
},
},
});
}
};
|
JavaScript
| 0 |
@@ -361,35 +361,8 @@
o',%0A
- 'alias': true,%0A
|
d034f2b64600d8fd06f47e14ca92d30e17a89c3d
|
debug. params.perspective = 0
|
src/core/transit.js
|
src/core/transit.js
|
function whichTransitionEvent() {
var e = $('<div>')[0];
var transitions = {
'transition': 'transitionEnd',
'OTransition': 'oTransitionEnd',
'MSTransition': 'msTransitionEnd',
'MozTransition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd'
}
for (var t in transitions) {
if(e.style[t] !== undefined) {
return transitions[t];
}
}
};
$.fn.transit = function(params, duration, delay, easing, callback) {
var origin = undefined;
var style = undefined;
if (typeof duration === 'function') {
callback = duration;
duration = undefined;
}
if (typeof delay === 'function') {
callback = delay;
delay = undefined;
}
if (typeof easing === 'function') {
callback = easing;
easing = undefined;
}
if (params.duration) {
duration = params.duration;
delete params.duration;
}
if (params.delay) {
delay = params.delay;
delete params.delay;
}
if (params.easing) {
easing = params.easing;
delete params.easing;
}
if (params.origin) {
origin = params.origin;
delete params.origin;
}
if (params.style) {
origin = params.style;
delete params.style;
}
if (params.perspective) {
this.parent().css('-webkit-perspective', params.perspective);
delete params.perspective;
} else {
this.parent().css('-webkit-perspective', 'none');
}
var css = new Style(params, duration, delay, easing, origin, style);
var onTransitionEvent = whichTransitionEvent();
var end = function(e) {
this.unbind(onTransitionEvent);
this.trigger('onTransitionEnd');
if (typeof callback === 'function') {
($.proxy(callback, this))(e);
}
};
this.bind(event, $.proxy(onTransitionEvent, this))
.css(css.build())
return this;
};
|
JavaScript
| 0.999997 |
@@ -1400,16 +1400,29 @@
spective
+ != undefined
) %7B%0A
|
623aee4db252587fd61eee0007fd39ce987f4be3
|
fix issue where user seems to be logged in if html is returned.
|
src/token-auth-provider.js
|
src/token-auth-provider.js
|
/**
* @module myModule
* @summary: This module's purpose is to:
*
* @description:
*
* Author: Justin Mooser
* Created On: 2015-05-15.
* @license Apache-2.0
*/
"use strict";
module.exports = function construct(config, $http) {
var m = {};
config = config ? config : {};
config = _.defaults(config, {});
m.login = function(params) {
return $http.post('/token', params)
.success(function(res) {
var user = JSON.parse(res.body);
return p.resolve(user);
})
.error(function(err) {
return p.reject(err);
});
};
m.logout = function() {
return p.resolve();
};
m.reauthenticate = function(params) {
return m.login(params);
};
return m;
};
|
JavaScript
| 0 |
@@ -411,24 +411,40 @@
tion(res) %7B%0A
+ try %7B%0A
var
@@ -472,32 +472,34 @@
.body);%0A
+
+
return p.resolve
@@ -502,24 +502,139 @@
olve(user);%0A
+ %7D%0A catch (ex) %7B%0A return p.reject(%7Bmessage: 'Failed to login.', html: res.body%7D);%0A %7D%0A
%7D)%0A
|
d3e361a81ff9f0fafcd701c2d3fb1db66e9996a3
|
Fix regex
|
saveto.js
|
saveto.js
|
javascript:
(function() {
var page = prompt("page");
if (page == "" || page == null) return;
page = page.replace(/_/g, " ");
var pages = page.split("|");
wpTextbox1.value = wpTextbox1.value.replace(/(==.+==)\n\n?/, "$1\n{{saveto|" + page + "}}\n");
wpSummary.value = wpSummary.value + " saveto [[" + pages.join("]]、[[") + "]]";
wpMinoredit.click();
if (confirm("Save?")) wpSave.click();
})();
|
JavaScript
| 0.999981 |
@@ -221,16 +221,18 @@
(==.+==)
+ *
%5Cn%5Cn?/,
|
85e4908606e523d1835f579ce5d23e61ce835cb0
|
fix undefined project, closes rnpm/rnpm-plugin-link#76 (#77)
|
src/link.js
|
src/link.js
|
const log = require('npmlog');
const path = require('path');
const uniq = require('lodash').uniq;
const flatten = require('lodash').flatten;
const pkg = require('../package.json');
const isEmpty = require('lodash').isEmpty;
const promiseWaterfall = require('./promiseWaterfall');
const registerDependencyAndroid = require('./android/registerNativeModule');
const registerDependencyIOS = require('./ios/registerNativeModule');
const isInstalledAndroid = require('./android/isInstalled');
const isInstalledIOS = require('./ios/isInstalled');
const copyAssetsAndroid = require('./android/copyAssets');
const copyAssetsIOS = require('./ios/copyAssets');
const getProjectDependencies = require('./getProjectDependencies');
const getDependencyConfig = require('./getDependencyConfig');
const pollParams = require('./pollParams');
log.heading = 'rnpm-link';
const commandStub = (cb) => cb();
const dedupeAssets = (assets) => uniq(assets, asset => path.basename(asset));
const promisify = (func) => new Promise((resolve, reject) =>
func((err, res) => err ? reject(err) : resolve(res))
);
const linkDependencyAndroid = (androidProject, dependency) => {
if (!androidProject || !dependency.config.android) {
return null;
}
const isInstalled = isInstalledAndroid(androidProject, dependency.name);
if (isInstalled) {
log.info(`Android module ${dependency.name} is already linked`);
return null;
}
return pollParams(dependency.config.params).then(params => {
log.info(`Linking ${dependency.name} android dependency`);
registerDependencyAndroid(
dependency.name,
dependency.config.android,
params,
androidProject
);
log.info(`Android module ${dependency.name} has been successfully linked`);
});
};
const linkDependencyIOS = (iOSProject, dependency) => {
if (!iOSProject || !dependency.config.ios) {
return;
}
const isInstalled = isInstalledIOS(iOSProject, dependency.config.ios);
if (isInstalled) {
log.info(`iOS module ${dependency.name} is already linked`);
return;
}
log.info(`Linking ${dependency.name} ios dependency`);
registerDependencyIOS(dependency.config.ios, iOSProject);
log.info(`iOS module ${dependency.name} has been successfully linked`);
};
const linkAssets = (project, assets) => {
if (isEmpty(assets)) {
return;
}
if (project.ios) {
log.info('Linking assets to ios project');
copyAssetsIOS(assets, project.ios);
}
if (project.android) {
log.info('Linking assets to android project');
copyAssetsAndroid(assets, project.android.assetsPath);
}
log.info(`Assets has been successfully linked to your project`);
};
/**
* Updates project and linkes all dependencies to it
*
* If optional argument [packageName] is provided, it's the only one that's checked
*/
module.exports = function link(config, args) {
try {
const project = config.getProjectConfig();
} catch (err) {
log.error('ERRPACKAGEJSON', `No package found. Are you sure it's a React Native project?`);
return Promise.reject(err);
}
const packageName = args[0];
const dependencies = getDependencyConfig(
config,
packageName ? [packageName] : getProjectDependencies()
);
const assets = dedupeAssets(dependencies.reduce(
(assets, dependency) => assets.concat(dependency.config.assets),
project.assets
));
const tasks = flatten(dependencies.map(dependency => [
() => promisify(dependency.config.commands.prelink || commandStub),
() => linkDependencyAndroid(project.android, dependency),
() => linkDependencyIOS(project.ios, dependency),
() => promisify(dependency.config.commands.postlink || commandStub),
]));
tasks.push(() => linkAssets(project, assets));
return promiseWaterfall(tasks).catch(err => {
log.error(
`It seems something went wrong while linking. Error: ${err.message} \n`
+ `Please file an issue here: ${pkg.bugs.url}`
);
throw err;
});
};
|
JavaScript
| 0 |
@@ -2853,16 +2853,31 @@
args) %7B%0A
+ var project;%0A
try %7B%0A
@@ -2880,22 +2880,16 @@
y %7B%0A
-const
project
|
867d6e09f2508d66dbf4a843b11170b2ab574ee9
|
Fix search View dependency issue.
|
js/app/views/search.js
|
js/app/views/search.js
|
define(['jquery', 'underscore', 'backbone',
'text!./app/views/templates/search-empty.html',
'text!./app/views/templates/search-listing.html',
'text!./app/views/templates/search-listings.html',
'text!./app/views/templates/add-listing.html',
'models', 'utils'], function($, _, Backbone, emptySearchTemplate, searchListingTemplate, searchContainerTemplate, addListingTemplate, Models, Utils) {
var Views = {};
Views.AddItemModal = Backbone.View.extend({
template: _.template(addListingTemplate),
initialize: function() {
this.render();
},
render: function() {
this.$el.html(this.template(this.model.attributes));
},
events: {
"click button.btn-success": "submitRequest",
"click button.btn-danger": "closeModal"
},
submitRequest: function() {
var country = $('select.form-control').val();
var city = $('#inputPickupCity').val();
var locationCombined = city + ", " + country;
// JS uses milliseconds, we need seconds.
var dateStart = Math.floor(Date.now() / 1000);
var inputDate = $('#inputExpiryDate').val();
var dateEnd = (new Date(inputDate)).getTime() / 1000;
var that = this;
$.ajax({
url: '/service/listings/create',
dataType: 'json',
type: 'POST',
data: {
product_id: this.model.attributes.id,
date_start: dateStart,
date_expire: dateEnd,
location: locationCombined
},
success: function() {
$('#add-listing-modal').modal('hide');
that.trigger("viewClosed");
},
error: function() {
alert("Oops, something went wrong. Try sending your request again!");
}
});
},
closeModal: function() {
this.trigger("viewClosed");
}
});
Views.SearchResult = Backbone.View.extend({
template: _.template(searchListingTemplate),
events: {
"click a.search-result": "clickResult"
},
clickResult: function() {
if (this.modal) {
this.disposeModal();
}
this.modal = new Views.AddItemModal({
model: this.model,
el: '#modal-container'
});
this.listenTo(this.modal, 'viewClosed', this.disposeModal);
$('#add-listing-modal').modal('show');
},
initialize: function() {
this.listenTo(this.model, "change", this.render);
this.id = "search-" + this.model.attributes.id;
},
render: function() {
this.$el.html(this.template(this.model.attributes));
return this;
},
disposeModal: function() {
this.modal.undelegateEvents();
}
});
Views.SearchResultListing = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'add', this.collectionAdded);
this.listenTo(this.collection, 'change', this.collectionChanged);
this.listenTo(this.collection, 'remove', this.collectionRemoved);
this.childViews = [];
this._addAllModels();
},
render: function() {
var fragment = document.createDocumentFragment();
if (this.childViews.length > 0) {
_(this.childViews).each(function(currentView) {
fragment.appendChild(currentView.render().el);
});
} else {
$(emptySearchTemplate).appendTo(fragment);
}
this.$el.html(fragment);
return this;
},
collectionAdded: function(item) {
this._addViewForModel(item);
this.render();
},
collectionRemoved: function(item) {
this.childViews = this.childViews.filter(function(view) {
return view.model.id !== item.id;
});
this.render();
},
collectionChanged: function() {
this.childViews = [];
this._addAllModels();
},
_addViewForModel: function(item) {
this.childViews.push(new Views.SearchResult({
model: item
}));
},
_addAllModels: function() {
var that = this;
this.collection.each(function(item) {
that._addViewForModel(item);
});
this.render();
}
});
Views.SearchSession = Backbone.View.extend({
events: {
"click button.close": "clickClose"
},
initialize: function() {
var escapedSearchTerm = Utils.urlencode(Utils.urlencode(this.options.searchTerm));
var productSearchUrl = '/service/products/search/' + escapedSearchTerm;
var productResultCollection = new Models.ProductSearchResults([], {
url: productSearchUrl
});
this.productSearchResultView = new Views.SearchResultListing({
collection: productResultCollection
});
var listingSearchUrl = '/service/listings/search/' + escapedSearchTerm;
var listingResultCollection = new Models.Wants([], {
url: listingSearchUrl
});
this.listingSearchResultView = new Views.ListingView({
collection: listingResultCollection
});
this.render();
},
render: function() {
this.$el.html(_.template(searchContainerTemplate, {
searchTerm: this.options.searchTerm
}));
this.productSearchResultView.setElement('#product-listing');
this.productSearchResultView.render();
this.listingSearchResultView.setElement('#request-listing');
this.listingSearchResultView.render();
$('#search-section').fadeIn();
},
clickClose: function() {
this.trigger("goHome");
}
});
Views.SearchForm = Backbone.View.extend({
events: {
"click a#btn-search": "searchClick",
"keypress input[type=text]": "keypress"
},
keypress: function(e) {
switch (e.keyCode) {
case 13:
this.searchClick();
}
},
searchClick: function() {
var searchListingView = new Views.SearchSession({
searchTerm: $('#txt-search').val()
});
this.trigger('changeView', searchListingView);
},
initialize: function() {}
});
return Views;
});
|
JavaScript
| 0 |
@@ -393,26 +393,8 @@
) %7B%0A
-%09var Views = %7B%7D;%0A%0A
%09Vie
|
c297e6ebc826f606a0b525013a37ab02eef2e463
|
Add callback *onSetUserStatus* to watch status changes
|
client/client.js
|
client/client.js
|
var timer, status;
UserPresence = {
awayTime: 60000, //1 minute
awayOnWindowBlur: false,
startTimer: function() {
UserPresence.stopTimer();
timer = setTimeout(UserPresence.setAway, UserPresence.awayTime);
},
stopTimer: function() {
clearTimeout(timer);
},
restartTimer: function() {
UserPresence.startTimer();
},
setAway: function() {
if (status !== 'away') {
status = 'away';
Meteor.call('UserPresence:away');
}
UserPresence.stopTimer();
},
setOnline: function() {
if (status !== 'online') {
status = 'online';
Meteor.call('UserPresence:online');
}
UserPresence.startTimer();
},
start: function() {
Deps.autorun(function() {
var user = Meteor.user();
status = user && user.statusConnection;
UserPresence.startTimer();
});
Meteor.methods({
'UserPresence:setDefaultStatus': function(status) {
Meteor.users.update({_id: Meteor.userId()}, {$set: {status: status, statusDefault: status}});
},
'UserPresence:online': function() {
var user = Meteor.user();
if (user && user.statusDefault === 'online') {
Meteor.users.update({_id: Meteor.userId()}, {$set: {status: 'online'}});
}
}
});
document.addEventListener('mousemove', UserPresence.setOnline);
document.addEventListener('mousedown', UserPresence.setOnline);
document.addEventListener('keydown', UserPresence.setOnline);
window.addEventListener('focus', UserPresence.setOnline);
if (UserPresence.awayOnWindowBlur === true) {
window.addEventListener('blur', UserPresence.setAway);
}
}
}
|
JavaScript
| 0 |
@@ -84,16 +84,49 @@
: false,
+%0A%09onSetUserStatus: function() %7B%7D,
%0A%0A%09start
@@ -1192,16 +1192,187 @@
;%0A%09%09%09%09%7D%0A
+%09%09%09%09UserPresence.onSetUserStatus(user, 'online');%0A%09%09%09%7D,%0A%09%09%09'UserPresence:away': function() %7B%0A%09%09%09%09var user = Meteor.user();%0A%09%09%09%09UserPresence.onSetUserStatus(user, 'away');%0A
%09%09%09%7D%0A%09%09%7D
|
7c41165e2c5a38e8f6b326baf8d1dd0beda3a78a
|
remove merge_stream from plugins
|
gulpfile.js
|
gulpfile.js
|
/*
webgame - three.js project gulp boilerplate
MrPaws 2014
TODO: 1) image processing boilerplate 2) always use minified bower deps (link)
*/
var gulp = require('gulp');
var del = require('del');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var merge = require('merge-stream');
var connect = require('gulp-connect');
var bower = require('main-bower-files');
var htmlSrc = '*.html';
var jsSrc = 'js/**/*.js';
var cssSrc = 'css/**/*.css';
var assetsSrc = 'assets/**';
var buildDir = 'dist';
gulp.task('clean', function(cb) {
return del([buildDir], cb);
});
gulp.task('html',function () {
return gulp.src(htmlSrc)
.pipe(gulp.dest(buildDir))
.pipe(connect.reload());
});
gulp.task('js', function () {
return gulp.src(jsSrc)
.pipe(concat('project.js'))
.pipe(uglify())
.pipe(rename('project.min.js'))
.pipe(gulp.dest(buildDir + '/js'));
});
gulp.task('link', ['js'], function () {
var jsFiles = bower();
jsFiles.push(buildDir + '/js/project.min.js');
return gulp.src(jsFiles)
.pipe(concat('all.js'))
.pipe(rename('all.min.js'))
.pipe(gulp.dest(buildDir + '/js'))
.pipe(connect.reload());
})
gulp.task('css', function () {
return gulp.src(cssSrc)
.pipe(gulp.dest(buildDir + '/css'))
.pipe(connect.reload());
});
gulp.task('assets', function () {
return gulp.src(assetsSrc)
.pipe(gulp.dest(buildDir + '/assets'))
.pipe(connect.reload());
});
gulp.task('connect', function() {
connect.server({
root: buildDir,
livereload: true
});
});
gulp.task('watch', function () {
gulp.watch([htmlSrc], ['html']);
gulp.watch([jsSrc], ['js','link']);
gulp.watch([cssSrc], ['css']);
gulp.watch([assetsSrc], ['assets']);
gulp.watch(['bower.json'], ['link']);
});
gulp.task('default', ['clean','html','js','link','css','assets','connect','watch']);
|
JavaScript
| 0.000002 |
@@ -351,45 +351,8 @@
');%0A
-var merge = require('merge-stream');%0A
var
|
e00cde4cbbb548cc50e243e299ab2b1252f4d6ce
|
handle transparent colors in violin
|
src/traces/violin/hover.js
|
src/traces/violin/hover.js
|
'use strict';
var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');
var boxHoverPoints = require('../box/hover');
var helpers = require('./helpers');
module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
if(!opts) opts = {};
var hoverLayer = opts.hoverLayer;
var cd = pointData.cd;
var trace = cd[0].trace;
var hoveron = trace.hoveron;
var hasHoveronViolins = hoveron.indexOf('violins') !== -1;
var hasHoveronKDE = hoveron.indexOf('kde') !== -1;
var closeData = [];
var closePtData;
var violinLineAttrs;
if(hasHoveronViolins || hasHoveronKDE) {
var closeBoxData = boxHoverPoints.hoverOnBoxes(pointData, xval, yval, hovermode);
if(hasHoveronKDE && closeBoxData.length > 0) {
var xa = pointData.xa;
var ya = pointData.ya;
var pLetter, vLetter, pAxis, vAxis, vVal;
if(trace.orientation === 'h') {
vVal = xval;
pLetter = 'y';
pAxis = ya;
vLetter = 'x';
vAxis = xa;
} else {
vVal = yval;
pLetter = 'x';
pAxis = xa;
vLetter = 'y';
vAxis = ya;
}
var di = cd[pointData.index];
if(vVal >= di.span[0] && vVal <= di.span[1]) {
var kdePointData = Lib.extendFlat({}, pointData);
var vValPx = vAxis.c2p(vVal, true);
var kdeVal = helpers.getKdeValue(di, trace, vVal);
var pOnPath = helpers.getPositionOnKdePath(di, trace, vValPx);
var paOffset = pAxis._offset;
var paLength = pAxis._length;
kdePointData[pLetter + '0'] = pOnPath[0];
kdePointData[pLetter + '1'] = pOnPath[1];
kdePointData[vLetter + '0'] = kdePointData[vLetter + '1'] = vValPx;
kdePointData[vLetter + 'Label'] = vLetter + ': ' + Axes.hoverLabelText(vAxis, vVal, trace[vLetter + 'hoverformat']) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3);
// move the spike to the KDE point
var medId = 0;
for(var k = 0; k < closeBoxData.length; k++) {
if(closeBoxData[k].attr === 'med') {
medId = k;
break;
}
}
kdePointData.spikeDistance = closeBoxData[medId].spikeDistance;
var spikePosAttr = pLetter + 'Spike';
kdePointData[spikePosAttr] = closeBoxData[medId][spikePosAttr];
closeBoxData[medId].spikeDistance = undefined;
closeBoxData[medId][spikePosAttr] = undefined;
// no hovertemplate support yet
kdePointData.hovertemplate = false;
closeData.push(kdePointData);
violinLineAttrs = {stroke: pointData.color};
violinLineAttrs[pLetter + '1'] = Lib.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength);
violinLineAttrs[pLetter + '2'] = Lib.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength);
violinLineAttrs[vLetter + '1'] = violinLineAttrs[vLetter + '2'] = vAxis._offset + vValPx;
}
}
if(hasHoveronViolins) {
closeData = closeData.concat(closeBoxData);
}
}
if(hoveron.indexOf('points') !== -1) {
closePtData = boxHoverPoints.hoverOnPoints(pointData, xval, yval);
}
// update violin line (if any)
var violinLine = hoverLayer.selectAll('.violinline-' + trace.uid)
.data(violinLineAttrs ? [0] : []);
violinLine.enter().append('line')
.classed('violinline-' + trace.uid, true)
.attr('stroke-width', 1.5);
violinLine.exit().remove();
violinLine.attr(violinLineAttrs);
// same combine logic as box hoverPoints
if(hovermode === 'closest') {
if(closePtData) return [closePtData];
return closeData;
}
if(closePtData) {
closeData.push(closePtData);
return closeData;
}
return closeData;
};
|
JavaScript
| 0 |
@@ -8,16 +8,103 @@
rict';%0A%0A
+var tinycolor = require('tinycolor2');%0A%0Avar Color = require('../../components/color');%0A
var Lib
@@ -3038,49 +3038,352 @@
v
-iolinLineAttrs = %7Bstroke: pointData.color
+ar strokeC = pointData.color;%0A var strokeColor = tinycolor(strokeC);%0A var strokeAlpha = strokeColor.getAlpha();%0A var strokeRGB = Color.tinyRGB(strokeColor);%0A%0A violinLineAttrs = %7B%0A stroke: strokeRGB,%0A 'stroke-opacity': strokeAlpha%0A
%7D;%0A
|
99c5dea28a5ea8ab4419c87858c4397d062694c6
|
fix issue
|
client/js/app.js
|
client/js/app.js
|
'use strict';
// Declare app level module
var howtc = angular.module('howtc', ['ngRoute', 'ngAutocomplete', 'uiGmapgoogle-maps', 'datePicker']);
var options = {
apiBaseUrl: 'https://localhost:3000/api'
};
howtc.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $location) {
$routeProvider.when('/', {
templateUrl: 'partials/landing.html',
controller: 'LandingCtrl'
});
$routeProvider.when('/search/:searchText', {
templateUrl: 'partials/search.html',
controller: 'SearchCtrl'
});
$routeProvider.when('/new', {
templateUrl: 'partials/new_company.html',
controller: 'NewCompanyCtrl'
});
$routeProvider.when('/company/:companyId', {
templateUrl: 'partials/company_details.html',
controller: 'CompanyDetailsCtrl'
});
$routeProvider.when('/new-survey/:companyId', {
templateUrl: 'partials/new_survey.html',
controller: 'NewSurveyCtrl'
});
$routeProvider.when('/404', {
templateUrl: 'partials/404.html',
controller: '404Ctrl'
});
$routeProvider.otherwise({
redirectTo: '/404'
});
}]);
|
JavaScript
| 0.000002 |
@@ -185,22 +185,33 @@
s://
-localhost:3000
+howtheycode.herokuapp.com
/api
|
0ff394424ef70f69aaed0acc7032c189e78ba222
|
add loading style and fonts from CDN
|
src/main.js
|
src/main.js
|
"use strict";
import React from 'react'
import ReactDOM from 'react-dom'
import './styles/main.scss'
import CalculatorSmall from './components/calculatorSmall/CalculatorSmall'
import CalculatorLarge from './components/calculatorLarge/CalculatorLarge'
import TablePrices from './components/tablePrices/TablePrices'
import createStore from './store/createStore'
import initialState from './store/initState';
import {Provider} from 'react-redux';
import {fetchInitTree, fetchStatistic, fetchCoupon, fetchUser} from './store/actions';
// Store Initialization
// ------------------------------------
const store = createStore(initialState);
store.dispatch(fetchUser());
store.dispatch(fetchInitTree());
// Render Setup
// ------------------------------------
const MOUNT_NODE_TP = document.getElementById('tp');
const MOUNT_NODE_CL_1 = document.getElementById('cl-1');
// const MOUNT_NODE_CL_2 = document.getElementById('cl-2');
const MOUNT_NODE_1 = document.getElementById('cs-1');
const MOUNT_NODE_2 = document.getElementById('cs-2');
// const MOUNT_NODE_3 = document.getElementById('cs-3');
const MOUNT_NODES = [MOUNT_NODE_TP, MOUNT_NODE_CL_1, MOUNT_NODE_1, MOUNT_NODE_2];
const MOUNT_CLASSES = ['tp','calc-lg', 'calc-sm', 'calc-sm'];
let render = () => {
MOUNT_NODES.forEach((MOUNT_NODE, i) => {
if (MOUNT_CLASSES[i].indexOf('calc-lg') !== -1) {
ReactDOM.render(
<Provider store={store}>
<div>
<CalculatorLarge calcId={i}
calcTitle={MOUNT_NODE.dataset.title}
calcTitleDiscount={MOUNT_NODE.dataset.titleDiscount}
containerClass={MOUNT_CLASSES[i]}/>
</div>
</Provider>,
MOUNT_NODE
);
} else if (MOUNT_CLASSES[i] === 'tp') {
ReactDOM.render(
<Provider store={store}>
<div>
<TablePrices calcId={i} containerClass={MOUNT_CLASSES[i]}/>
</div>
</Provider>,
MOUNT_NODE
);
}
else {
ReactDOM.render(
<Provider store={store}>
<div>
<CalculatorSmall calcId={i}
calcTitle={MOUNT_NODE.dataset.title}
calcTitleDiscount={MOUNT_NODE.dataset.titleDiscount}
calcType={MOUNT_NODE.dataset.type}
containerClass={MOUNT_CLASSES[i]}/>
</div>
</Provider>,
MOUNT_NODE
);
}
});
};
// Development Tools
// ------------------------------------
if (__DEV__) {
if (module.hot) {
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error}/>, MOUNT_NODE_1)
}
render = () => {
try {
renderApp()
} catch (e) {
console.error(e)
renderError(e)
}
}
// Setup hot module replacement
module.hot.accept([
'./main',
], () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE_1)
render()
})
)
}
}
// Let's Go!
// ------------------------------------
if (!__TEST__) render()
|
JavaScript
| 0 |
@@ -526,16 +526,702 @@
ions';%0A%0A
+const css = 'https://s3.amazonaws.com/genericapps/resources/calculators/main.259b2e5f8db7f0ca0ae3a05093744601.css';%0Aconst font = 'https://fonts.googleapis.com/css?family=Open+Sans%22 rel=%22stylesheet';%0Afunction loadCSS(filename) %7B%0A%0A const file = document.createElement(%22link%22);%0A file.setAttribute(%22rel%22, %22stylesheet%22);%0A file.setAttribute(%22type%22, %22text/css%22);%0A file.setAttribute(%22href%22, filename);%0A document.head.appendChild(file);%0A%0A%7D%0Afunction loadFont(filename) %7B%0A const file = document.createElement(%22link%22);%0A file.setAttribute(%22rel%22, %22stylesheet%22);%0A file.setAttribute(%22href%22, filename);%0A document.head.appendChild(file);%0A%7D%0A%0A// loadCSS(css);%0A// loadFont(font);%0A
%0A// Stor
@@ -1882,16 +1882,17 @@
= %5B'tp',
+
'calc-lg
|
9fd9a26675c69fc87250c024eb02d3205dd37079
|
Refactor helpers
|
react-github-battle/app/utils/githubHelpers.js
|
react-github-battle/app/utils/githubHelpers.js
|
var axios = require('axios');
var id = "YOUR_CLIENT_ID";
var sec = "YOUR_SECRET_ID";
var param = "?client_id" + id + "&client_secret=" + sec;
function getUserInfo (username) {
return axios.get('https://api.github.com/users/' + username + param);
}
function getRepos (username) {
// fetch username repos
return axios.get('https://api.github.com/users/' + username + '/repos' + param + '&per_page=100');
}
function getTotalStars (repos) {
// calculate all the stars that the user has
return repos.data.reduce(function(prev, current){
return prev + current.stargazers_count
}, 0)
}
function getPlayersData (player) {
// get repos
// getTotalStars
// return object with that data
return getRepos(player.login)
.then(getTotalStars)
.then(function (totalStars) {
return {
followers: player.followers,
totalStars: totalStars
}
})
}
function calculateScores (players) {
// return an array, after doing some fancy algorithm to determine a winner
return [
players[0].followers * 3 + players[0].totalStars,
players[1].followers * 3 + players[1].totalStars
]
}
var helpers = {
getPlayersInfo: function(players) {
return axios.all(players.map(function (username) {
return getUserInfo(username)
})).then(function (info) {
return info.map(function (user) {
return user.data;
})
}).catch(function (err) {
console.warn('Error in getPlayersInfo', err)
})
},
battle: function (players) {
var playerOneData = getPlayersData(players[0]);
var playerTwoData = getPlayersData(players[1]);
return axios.all([playerOneData, playerTwoData])
.then(calculateScores)
.catch(function(err) {console.warn("Error in getPlayersInfo: ", err)})
}
};
module.exports = helpers;
|
JavaScript
| 0.000001 |
@@ -1,38 +1,36 @@
-var
+import
axios
-= require('axios');%0A%0Avar
+from 'axios'%0A%0Aconst
id
@@ -49,19 +49,21 @@
NT_ID%22;%0A
-var
+const
sec = %22
@@ -79,19 +79,21 @@
ET_ID%22;%0A
-var
+const
param =
@@ -1135,25 +1135,23 @@
%0A%7D%0A%0A
-var helpers = %7B%0A
+export function
get
@@ -1161,26 +1161,17 @@
yersInfo
-: function
+
(players
@@ -1172,26 +1172,24 @@
layers) %7B%0A
-
-
return axios
@@ -1227,26 +1227,24 @@
name) %7B%0A
-
return getUs
@@ -1260,18 +1260,16 @@
ername)%0A
-
%7D)).th
@@ -1289,26 +1289,24 @@
info) %7B%0A
-
return info.
@@ -1323,26 +1323,24 @@
on (user) %7B%0A
-
return
@@ -1355,23 +1355,19 @@
ta;%0A
-
%7D)%0A
-
%7D).cat
@@ -1382,26 +1382,24 @@
ion (err) %7B%0A
-
console.
@@ -1439,29 +1439,22 @@
rr)%0A
-
%7D)%0A
- %7D,%0A battle:
+%7D%0A%0Aexport
fun
@@ -1459,16 +1459,23 @@
unction
+battle
(players
@@ -1480,21 +1480,21 @@
rs) %7B%0A
- var
+const
playerO
@@ -1536,13 +1536,13 @@
;%0A
- var
+const
pla
@@ -1584,18 +1584,16 @@
%5B1%5D);%0A
-
-
return a
@@ -1637,18 +1637,16 @@
a%5D)%0A
-
.then(ca
@@ -1664,18 +1664,16 @@
es)%0A
-
-
.catch(f
@@ -1739,38 +1739,6 @@
)%7D)%0A
- %7D%0A%7D;%0A%0Amodule.exports = helpers;
+%7D
%0A
|
593417fd0b29bccbe585cb2f2108bd356333ae97
|
Update konami.js
|
js/konami.js
|
js/konami.js
|
// a key map of allowed keys
var allowedKeys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down',
65: 'a',
66: 'b'
};
// the 'official' Konami Code sequence
var konamiCode = ['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a'];
// a variable to remember the 'position' the user has reached so far.
var konamiCodePosition = 0;
// add keydown event listener
document.addEventListener('keydown', function(e) {
// get the value of the key code from the key map
var key = allowedKeys[e.keyCode];
// get the value of the required key from the konami code
var requiredKey = konamiCode[konamiCodePosition];
// compare the key with the required key
if (key == requiredKey) {
// move to the next key in the konami code sequence
konamiCodePosition++;
// if the last key is reached, activate cheats
if (konamiCodePosition == konamiCode.length)
activateCheats();
} else
konamiCodePosition = 0;
});
function activateCheats() {
chili.electricBugaloo {
top: 100%;
left: 100%;
-webkit-transform: rotate(2000deg);
transform: rotate(2000deg);
chili {
position: fixed;
width: 32px;
height: 32px;
background: url('http://i.imgur.com/SyCqOhA.png');
top: -5%;
left: -5%;
z-index: 11200000;
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transition: all 2s linear;
transition: all 2s linear;
var audio = new Audio('audio/pling.mp3');
audio.play();
alert("cheats activated");
}
|
JavaScript
| 0.000001 |
@@ -1108,24 +1108,29 @@
e(2000deg);%0A
+ %7D;%0A
%0A chili
@@ -1430,17 +1430,21 @@
linear;
-
+%0A %7D;
%0A %0A va
|
30e4aaafb7eb41e4f09d0f5bbde66ea1629420e0
|
Fix pilas-blockly-test
|
tests/integration/components/pilas-blockly-test.js
|
tests/integration/components/pilas-blockly-test.js
|
import { moduleForComponent, skip } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('pilas-blockly', 'Integration | Component | pilas blockly', {
integration: true
});
skip('it renders', function(assert) {
this.set('pilas', {
on: function() {
}
});
this.set('bloques', ['controls_if']);
/* Cuando el componente está listo para ser usado. */
this.render(hbs`{{pilas-blockly cargando=false pilas=pilas bloques=bloques}}`);
assert.ok(this.$().text().indexOf("Ejecutar") > -1, "Tiene el botón ejecutar visible");
assert.ok(this.$().text().indexOf("Compartir") === -1, 'Ya no existe un botón para compartir por twitter por omisión');
assert.ok(this.$().text().indexOf("Abrir") > -1, 'Existe un botón para cargar una solución');
assert.ok(this.$().text().indexOf("Guardar") > -1, 'Existe un botón para guardar una solución');
/* Cuando el componente está cargando */
this.render(hbs`{{pilas-blockly cargando=true pilas=pilas bloques=bloques}}`);
assert.equal(this.$().text().indexOf("Ejecutar") > -1, true, 'Cuando carga, solamente está el botón Ejecutar (deshabilitado)');
});
|
JavaScript
| 0.002575 |
@@ -21,16 +21,22 @@
mponent,
+ test,
skip %7D
@@ -212,24 +212,48 @@
);%0A%0A
-skip('it renders
+test('Cuando el componente est%C3%A1 cargando
', f
@@ -274,111 +274,246 @@
) %7B%0A
-%0A
this.
-set('pilas', %7B%0A on: function() %7B%0A %7D%0A %7D
+render(hbs%60%7B%7Bpilas-blockly cargando=true pilas=pilas bloques=bloques%7D%7D%60);%0A%0A assert.equal(this.$(%22button%22).length, 0, 'No muestra ning%C3%BAn bot%C3%B3n'
);%0A
-%0A
-this.set('bloques', %5B'controls_if'%5D);%0A%0A /*
+assert.ok(existeTexto(%22cargando%22), %22Solo muestra el texto 'cargando'%22);%0A%7D);%0A%0Atest('
Cuan
@@ -558,12 +558,29 @@
sado
-. */
+', function(assert) %7B
%0A t
@@ -650,32 +650,35 @@
es=bloques%7D%7D%60);%0A
+ %0A
assert.ok(this
@@ -673,39 +673,27 @@
sert.ok(
-this.$().text().indexOf
+existeBoton
(%22Ejecut
@@ -696,21 +696,16 @@
ecutar%22)
- %3E -1
, %22Tiene
@@ -747,34 +747,25 @@
ert.
-ok(this.$().text().indexOf
+notOk(existeBoton
(%22Co
@@ -777,15 +777,8 @@
ir%22)
- === -1
, 'Y
@@ -853,39 +853,27 @@
sert.ok(
-this.$().text().indexOf
+existeBoton
(%22Abrir%22
@@ -873,21 +873,16 @@
%22Abrir%22)
- %3E -1
, 'Exist
@@ -932,39 +932,27 @@
sert.ok(
-this.$().text().indexOf
+existeBoton
(%22Guarda
@@ -954,21 +954,16 @@
uardar%22)
- %3E -1
, 'Exist
@@ -1006,51 +1006,67 @@
');%0A
-%0A /* Cuando el componente est%C3%A1 cargando */
+%7D);%0A%0Askip('Cuando ejecuta un ejercicio', function(assert) %7B
%0A t
@@ -1097,35 +1097,36 @@
lockly cargando=
-tru
+fals
e pilas=pilas bl
@@ -1150,136 +1150,373 @@
;%0A
-assert.equal(this.$().text().indexOf(%22Ejecutar%22) %3E -1, true, 'Cuando carga, solamente est%C3%A1 el bot%C3%B3n Ejecutar (deshabilitado)'
+this.send(%22ejecutar%22);%0A%0A assert.ok(existeBoton(%22Reiniciar%22), %22Tiene el bot%C3%B3n reiniciar visible%22);%0A%7D);%0A%0Afunction existeElementoConTexto(elemento, texto) %7B%0A return this.$(elemento).text().includes(texto);%0A%7D%0A%0Afunction existeBoton(texto) %7B%0A return existeElementoConTexto(%22button%22, texto);%0A%7D%0A%0Afunction existeTexto(texto) %7B%0A return existeElementoConTexto(%22p%22, texto
);%0A%7D
-);
+%0A
%0A
|
72b81358aae0584796790e2a7fa29a3714461518
|
Add a warning to prevent a memory leak (#10953)
|
src/styles/MuiThemeProvider.js
|
src/styles/MuiThemeProvider.js
|
import React from 'react';
import PropTypes from 'prop-types';
import warning from 'warning';
import createBroadcast from 'brcast';
import themeListener, { CHANNEL } from './themeListener';
import exactProp from '../utils/exactProp';
/**
* This component takes a `theme` property.
* It makes the `theme` available down the React tree thanks to React context.
* This component should preferably be used at **the root of your component tree**.
*/
class MuiThemeProvider extends React.Component {
constructor(props, context) {
super(props, context);
// Get the outer theme from the context, can be null
this.outerTheme = themeListener.initial(context);
// Propagate the theme so it can be accessed by the children
this.broadcast.setState(this.mergeOuterLocalTheme(this.props.theme));
}
getChildContext() {
const { sheetsManager, disableStylesGeneration } = this.props;
const muiThemeProviderOptions = this.context.muiThemeProviderOptions || {};
if (sheetsManager !== undefined) {
muiThemeProviderOptions.sheetsManager = sheetsManager;
}
if (disableStylesGeneration !== undefined) {
muiThemeProviderOptions.disableStylesGeneration = disableStylesGeneration;
}
return {
[CHANNEL]: this.broadcast,
muiThemeProviderOptions,
};
}
componentDidMount() {
// Subscribe on the outer theme, if present
this.unsubscribeId = themeListener.subscribe(this.context, outerTheme => {
this.outerTheme = outerTheme;
// Forward the parent theme update to the children
this.broadcast.setState(this.mergeOuterLocalTheme(this.props.theme));
});
}
componentDidUpdate(prevProps) {
// Propagate a local theme update
if (this.props.theme !== prevProps.theme) {
this.broadcast.setState(this.mergeOuterLocalTheme(this.props.theme));
}
}
componentWillUnmount() {
if (this.unsubscribeId !== null) {
themeListener.unsubscribe(this.context, this.unsubscribeId);
}
}
broadcast = createBroadcast();
unsubscribeId = null;
// We are not using the React state in order to avoid unnecessary rerender.
outerTheme = null;
// Simple merge between the outer theme and the local theme
mergeOuterLocalTheme(localTheme) {
// To support composition of theme.
if (typeof localTheme === 'function') {
warning(
this.outerTheme,
[
'Material-UI: you are providing a theme function property ' +
'to the MuiThemeProvider component:',
'<MuiThemeProvider theme={outerTheme => outerTheme} />',
'',
'However, no outer theme is present.',
'Make sure a theme is already injected higher in the React tree ' +
'or provide a theme object.',
].join('\n'),
);
return localTheme(this.outerTheme);
}
if (!this.outerTheme) {
return localTheme;
}
return { ...this.outerTheme, ...localTheme };
}
render() {
return this.props.children;
}
}
MuiThemeProvider.propTypes = {
/**
* You can only provide a single element with react@15, a node with react@16.
*/
children: PropTypes.node.isRequired,
/**
* You can disable the generation of the styles with this option.
* It can be useful when traversing the React tree outside of the HTML
* rendering step on the server.
* Let's say you are using react-apollo to extract all
* the queries made by the interface server side.
* You can significantly speed up the traversal with this property.
*/
disableStylesGeneration: PropTypes.bool,
/**
* The sheetsManager is used to deduplicate style sheet injection in the page.
* It's deduplicating using the (theme, styles) couple.
* On the server, you should provide a new instance for each request.
*/
sheetsManager: PropTypes.object,
/**
* A theme object.
*/
theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired,
};
MuiThemeProvider.propTypes = exactProp(MuiThemeProvider.propTypes, 'MuiThemeProvider');
MuiThemeProvider.childContextTypes = {
...themeListener.contextTypes,
muiThemeProviderOptions: PropTypes.object,
};
MuiThemeProvider.contextTypes = {
...themeListener.contextTypes,
muiThemeProviderOptions: PropTypes.object,
};
export default MuiThemeProvider;
|
JavaScript
| 0 |
@@ -2960,24 +2960,328 @@
render() %7B%0A
+ warning(%0A typeof window !== 'undefined' %7C%7C this.props.sheetsManager,%0A %5B%0A 'Material-UI: you need to provide a sheetsManager to the MuiThemeProvider ' +%0A 'when rendering on the server.',%0A 'If you do not, you might experience a memory leak',%0A %5D.join('%5Cn'),%0A );%0A%0A
return t
|
e17ef45476866c725133b1013832e7fd0f87b1a8
|
Fix missing first run wizard
|
src/js/Init/Application.js
|
src/js/Init/Application.js
|
import Vue from 'vue';
import App from '@vue/App';
import API from '@js/Helper/api';
import router from '@js/Helper/router';
import EventEmitter from 'eventemitter3';
import SectionAll from '@vue/Section/All';
import Utility from '@js/Classes/Utility';
import Messages from '@js/Classes/Messages';
import EventManager from '@js/Manager/EventManager';
import AlertManager from '@js/Manager/AlertManager';
import SearchManager from '@js/Manager/SearchManager';
import SettingsService from '@js/Services/SettingsService';
import KeepAliveManager from '@js/Manager/KeepAliveManager';
class Application {
/**
* @return {Vue}
*/
get app() {
return this._app;
}
/**
* @return {EventEmitter}
*/
get events() {
return this._events;
}
/**
* @return {Boolean}
*/
get loginRequired() {
return this._loginRequired;
}
/**
*
* @param {Boolean} value
*/
set loginRequired(value) {
this._loginRequired = value;
}
constructor() {
this._loaded = false;
this._timer = null;
this._app = null;
this._loginRequired = true;
this._events = new EventEmitter();
}
/**
*
*/
init() {
window.addEventListener('DOMContentLoaded', () => { this._initApp(); }, {once: true, passive: true});
this._timer = setInterval(() => { this._initApp(); }, 10);
}
/**
*
* @returns {Promise<void>}
* @private
*/
_initApp() {
if(this._loaded || !document.querySelector('meta[name=pw-api-user]')) return;
clearInterval(this._timer);
this._loaded = true;
this._initSettings();
if(this._initApi()) {
this._checkLoginRequirement();
this._initVue();
SearchManager.init();
EventManager.init();
KeepAliveManager.init();
AlertManager.init();
}
}
// noinspection JSMethodCanBeStatic
/**
*
* @private
*/
_initSettings() {
SettingsService.init();
document.body.setAttribute('data-server-version', SettingsService.get('server.version'));
let customBackground = SettingsService.get('server.theme.background').indexOf('/core/') === -1 ? 'true':'false';
document.body.setAttribute('data-custom-background', customBackground);
let customColor = SettingsService.get('server.theme.color.primary') === '#0082c9' ? 'false':'true';
document.body.setAttribute('data-custom-color', customColor);
document.body.style.setProperty('--pw-image-login-background', `url(${SettingsService.get('server.theme.background')})`);
document.body.style.setProperty('--pw-image-logo-themed', `url(${SettingsService.get('server.theme.app.icon')})`);
let appIcon = SettingsService.get('server.theme.color.text') === '#ffffff' ? 'app':'app-dark';
document.body.style.setProperty('--pw-image-logo', `url(${OC.appswebroots.passwords}/img/${appIcon}.svg)`);
}
/**
*
* @returns {boolean}
* @private
*/
_initApi() {
let baseUrl = Utility.generateUrl(),
userEl = document.querySelector('meta[name=pw-api-user]'),
tokenEl = document.querySelector('meta[name=pw-api-token]'),
user = userEl ? userEl.getAttribute('content'):null,
token = tokenEl ? tokenEl.getAttribute('content'):null,
cseMode = SettingsService.get('user.encryption.cse') === 1 ? 'CSEv1r1':'none',
folderIcon = SettingsService.get('server.theme.folder.icon');
if(!user || !token) {
Messages.alert('The app was unable to obtain the api access credentials.', 'Initialisation Error')
.then(() => { location.reload(); });
return false;
}
if(baseUrl.indexOf('index.php') !== -1) baseUrl = baseUrl.substr(0, baseUrl.indexOf('index.php'));
API.initialize({baseUrl, user, password: token, folderIcon, cseMode, events: this._events});
return true;
}
/**
* Check if the user needs to authenticate
*
* @private
*/
_checkLoginRequirement() {
let impersonateEl = document.querySelector('meta[name=pw-impersonate]'),
authenticateEl = document.querySelector('meta[name=pw-authenticate]');
if(authenticateEl && impersonateEl) {
this._loginRequired = authenticateEl.getAttribute('content') === 'true' || impersonateEl.getAttribute('content') === 'true';
}
if(!this._loginRequired) {
document.body.classList.remove('pw-auth-visible');
document.body.classList.add('pw-auth-skipped');
API.openSession({});
}
}
/**
*
* @private
*/
_initVue() {
let section = SettingsService.get('client.ui.section.default');
router.addRoutes(
[
{name: 'All', path: section === 'all' ? '/':'/all', param: [], components: {main: SectionAll}},
{path: '*', redirect: {name: section.capitalize()}}
]
);
router.beforeEach((to, from, next) => {
if(!API.isAuthorized && this._loginRequired && to.name !== 'Authorize') {
let target = {name: to.name, path: to.path, hash: to.hash, params: to.params};
target = btoa(JSON.stringify(target));
next({name: 'Authorize', params: {target}});
}
next();
if(to.name !== from.name && window.innerWidth < 768) {
let app = document.getElementById('app');
if(app) app.classList.remove('mobile-open');
}
});
this._app = new Vue(App);
}
}
export default new Application();
|
JavaScript
| 0.006851 |
@@ -573,16 +573,69 @@
nager';%0A
+import SetupManager from %22@js/Manager/SetupManager%22;%0A
%0A%0Aclass
@@ -4828,24 +4828,69 @@
ession(%7B%7D);%0A
+ SetupManager.runAutomatically();%0A
%7D%0A
|
fb60e3f0767678c66cebebfdc570e2219fff9f22
|
load plugins in akyuu
|
lib/akyuu.js
|
lib/akyuu.js
|
/**
* XadillaX created at 2016-03-23 14:52:05 With ♥
*
* Copyright (c) 2016 akyuu.moe, all rights
* reserved.
*/
"use strict";
var path = require("path");
var util = require("util");
require("sugar");
var Model = require("./loader/model.js");
var Connection = require("./loader/connection");
var Controller = require("./loader/controller");
var Express = require("./_express/application");
var Logger = require("./logger");
var Service = require("./loader/service");
var logRequest = require("./middware/request_logger");
/**
* Akyuu
* @constructor
* @param {String} [projectRoot] the project root path
*/
var Akyuu = function(projectRoot) {
Express.call(this);
this.projectRoot = projectRoot || path.resolve(__dirname, "../../../src");
this.requirePaths = require("./require");
this.requirePaths.addRequirePath(this.projectRoot);
this.config = require("./config");
this.logger = new Logger(this);
this.Errors = require("./error/predefinition");
this.connection = new Connection(this);
this.model = new Model(this);
this.controller = new Controller(this);
this.service = new Service(this);
};
util.inherits(Akyuu, Express);
/**
* init
* @param {Function} callback the callback function
*/
Akyuu.prototype.init = function(callback) {
Express.prototype.init.call(this);
// load controllers...
this.logger.load();
this.use(logRequest);
this.service.load("");
this.connection.load();
this.model.load("");
this.controller.load("");
process.nextTick(callback);
};
module.exports = Akyuu;
|
JavaScript
| 0 |
@@ -421,24 +421,65 @@
./logger%22);%0A
+var Plugin = require(%22./loader/plugin%22);%0A
var Service
@@ -1022,24 +1022,95 @@
inition%22);%0A%0A
+ this.PLUGIN_POS = Plugin.POS;%0A%0A this.plugin = new Plugin(this);%0A
this.con
@@ -1449,35 +1449,8 @@
);%0A%0A
- // load controllers...%0A
@@ -1509,106 +1509,570 @@
his.
-service.load(%22%22);%0A this.connection.load();%0A this.model.load(%22%22);%0A this.controller.load(%22%22
+plugin.load();%0A%0A this.plugin.plug(this.PLUGIN_POS.BEFORE_SERVICE);%0A this.service.load(%22%22);%0A this.plugin.plug(this.PLUGIN_POS.AFTER_SERVICE);%0A%0A this.plugin.plug(this.PLUGIN_POS.BEFORE_CONNECTION);%0A this.connection.load();%0A this.plugin.plug(this.PLUGIN_POS.AFTER_CONNECTION);%0A%0A this.plugin.plug(this.PLUGIN_POS.BEFORE_MODEL);%0A this.model.load(%22%22);%0A this.plugin.plug(this.PLUGIN_POS.AFTER_MODEL);%0A%0A this.plugin.plug(this.PLUGIN_POS.BEFORE_CONTROLLER);%0A this.controller.load(%22%22);%0A this.plugin.plug(this.PLUGIN_POS.AFTER_CONTROLLER
);%0A%0A
|
8dd2d13070a7f03c2a169a794f3603997d7ace5d
|
use plain getters in Svelte useStore
|
src/svelte/shared/use-store.js
|
src/svelte/shared/use-store.js
|
// eslint-disable-next-line
import { onDestroy } from 'svelte';
import { f7 } from './f7';
export const useStore = (...args) => {
// (store, getter, callback)
let store = args[0];
let getter = args[1];
let callback = args[2];
if (args.length === 1) {
// (getter)
store = f7.store;
getter = args[0];
} else if (args.length === 2 && typeof args[0] === 'string') {
// (getter, callback)
store = f7.store;
getter = args[0];
callback = args[1];
}
const obj = store.getters[getter];
const value = obj.value;
if (callback) {
obj.onUpdated(callback);
}
onDestroy(() => {
if (callback) {
// eslint-disable-next-line
store.__removeCallback(callback);
}
// eslint-disable-next-line
store.__removeCallback(obj.__callback);
});
return value;
};
|
JavaScript
| 0 |
@@ -478,16 +478,46 @@
1%5D;%0A %7D%0A
+ // eslint-disable-next-line%0A
const
@@ -532,15 +532,21 @@
ore.
+_
getters
+Plain
%5Bget
@@ -754,84 +754,8 @@
%7D%0A
- // eslint-disable-next-line%0A store.__removeCallback(obj.__callback);%0A
%7D)
|
f0df4b9d5a903221d514874a5f52ea6e47c8bd27
|
Update index.js
|
js/index.js
|
js/index.js
|
var dns = {}
dns.google = new Array("8.8.8.8", "8.8.4.4", "Google Public DNS Server");
dns.opendns = new Array("208.67.222.222", "208.67.220.220", "OpenDNS");
dns.nortondns = new Array("198.153.192.50", "198.153.194.50", "Norton DNS Server");
dns.advantage = new Array("156.154.70.1", "156.154.71.1", "DNS Advantage");
dns.comodo = new Array("8.26.56.26", "8.20.247.20", "Comodo Secure DNS Server");
var main_dns = "google";
$(document).ready(function(){
if($("dns")){
for(var key in dns){
if(key != main_dns){
$("dns").append("<p><b>" + dns[key][0] + "</b>, <b>" + dns[key][1] + "</b> - " + dns[key][2] + "</p>");
}
}
$("#mdns").html("<b>" + dns[main_dns][0] + "</b>, <b>" + dns[main_dns][1] + "</b>");
$("#name").html("<b>" + dns[main_dns][2]);
}
});
|
JavaScript
| 0.000002 |
@@ -1,431 +1,4 @@
-var dns = %7B%7D%0Adns.google = new Array(%228.8.8.8%22, %228.8.4.4%22, %22Google Public DNS Server%22);%0Adns.opendns = new Array(%22208.67.222.222%22, %22208.67.220.220%22, %22OpenDNS%22);%0Adns.nortondns = new Array(%22198.153.192.50%22, %22198.153.194.50%22, %22Norton DNS Server%22);%0Adns.advantage = new Array(%22156.154.70.1%22, %22156.154.71.1%22, %22DNS Advantage%22);%0Adns.comodo = new Array(%228.26.56.26%22, %228.20.247.20%22, %22Comodo Secure DNS Server%22);%0A%0Avar main_dns = %22google%22;%0A%0A
$(do
|
2779fa4e614b23f69c522385bd52b26597de6ad1
|
add unselectable class on init editor
|
src/main.js
|
src/main.js
|
'use strict'
/**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 2016 SIRAP Group All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* plugin.js Tinymce plugin headersfooters
* @file plugin.js
* @module
* @name tinycmce-plugin-headersfooters
* @description
* A plugin for tinymce WYSIWYG HTML editor that allow to insert headers and footers
* It will may be used with requires tinymce-plugin-paginate the a near future, but not for now.
* @link https://github.com/sirap-group/tinymce-plugin-headersfooters
* @author Rémi Becheras
* @author Groupe SIRAP
* @license GNU GPL-v2 http://www.tinymce.com/license
* @version 1.0.0
*/
/**
* Tinymce library - injected by the plugin loader.
* @external tinymce
* @see {@link https://www.tinymce.com/docs/api/class/tinymce/|Tinymce API Reference}
*/
var tinymce = window.tinymce
/**
* The jQuery plugin namespace - plugin dependency.
* @external "jQuery.fn"
* @see {@link http://learn.jquery.com/plugins/|jQuery Plugins}
*/
var $ = window.jQuery
var ui = require('./utils/ui')
var HeaderFooterFactory = require('./classes/HeaderFooterFactory')
// Add the plugin to the tinymce PluginManager
tinymce.PluginManager.add('headersfooters', tinymcePluginHeadersFooters)
/**
* Tinymce plugin headers/footers
* @function
* @global
* @param {tinymce.Editor} editor - The injected tinymce editor.
* @returns void
*/
function tinymcePluginHeadersFooters (editor, url) {
var headerFooterFactory
var menuItems = {
insertHeader: ui.createInsertHeaderMenuItem(),
insertFooter: ui.createInsertFooterMenuItem(),
removeHeader: ui.createRemoveHeaderMenuItem(),
removeFooter: ui.createRemoveFooterMenuItem()
}
// add menu items
editor.addMenuItem('insertHeader', menuItems.insertHeader)
editor.addMenuItem('removeHeader', menuItems.removeHeader)
editor.addMenuItem('insertFooter', menuItems.insertFooter)
editor.addMenuItem('removeFooter', menuItems.removeFooter)
editor.on('init', onInitHandler)
editor.on('SetContent', onSetContent)
editor.on('NodeChange', onNodeChange)
editor.on('NodeChange', function (evt) {
// if (!editor.selection.isCollapsed()) {
// if (editor.selection.getNode() === editor.getBody()) {
// console.info('Select ALL')
// editor.selection.select(headerFooterFactory.getActiveSection())
// }
// }
})
/**
* On init event handler. Instanciate the factory and initialize menu items states
* @function
* @inner
* @returns void
*/
function onInitHandler () {
headerFooterFactory = new HeaderFooterFactory(editor)
initMenuItems(headerFooterFactory, menuItems)
}
/**
* On SetContent event handler. Load or reload headers and footers from existing elements if it should do.
* @function
* @inner
* @returns void
*/
function onSetContent (evt) {
// var $bodyElmt = $('body', editor.getDoc())
var content = $(editor.getBody()).html()
var emptyContent = '<p><br data-mce-bogus="1"></p>'
if (content && content !== emptyContent) {
if (headerFooterFactory) {
reloadHeadFoots(menuItems)
} else {
setTimeout(reloadHeadFoots.bind(null, menuItems), 100)
}
} else {
// evt.content = '<section data-headfoot="true" data-headfoot-body="true">' + evt.content + '</section>'
}
}
function onNodeChange (evt) {
headerFooterFactory.forceCursorToAllowedLocation(evt.element)
}
/**
* Helper function. Do the reload of headers and footers
* @function
* @inner
* @returns void
*/
function reloadHeadFoots (menuItems) {
var $headFootElmts = $('*[data-headfoot]', editor.getDoc())
var $bodyElmt = $('*[data-headfoot-body]', editor.getDoc())
var hasBody = !!$bodyElmt.length
var $allElmts = null
// init starting states
menuItems.insertHeader.show()
menuItems.insertFooter.show()
menuItems.removeHeader.hide()
menuItems.removeFooter.hide()
// set another state and load elements if a header or a footer exists
$headFootElmts.each(function (i, el) {
var $el = $(el)
if ($el.attr('data-headfoot-header')) {
menuItems.insertHeader.hide()
menuItems.removeHeader.show()
} else if ($el.attr('data-headfoot-body')) {
// @TODO something ?
} else if ($el.attr('data-headfoot-footer')) {
menuItems.insertFooter.hide()
menuItems.removeFooter.show()
}
headerFooterFactory.loadElement(el)
})
if (!hasBody) {
$allElmts = $(editor.getBody()).children()
headerFooterFactory.insertBody()
var $body = $(headerFooterFactory.body.node)
$body.empty()
$allElmts.each(function (i, el) {
var $el = $(el)
if (!$el.attr('data-headfoot')) {
$body.append($el)
}
})
}
}
}
/**
* Initialize menu items states (show, hide, ...) and implements onclick handlers
* @function
* @inner
* @param {HeaderFooterFactory} factory The header and footer factory
* @param {object} menuItems The set of plugin's menu items
* @returns undefined
*/
function initMenuItems (factory, menuItems) {
// on startup, hide remove buttons
menuItems.removeHeader.hide()
menuItems.removeFooter.hide()
// override insertHeader, insertFooter, removeHeader and removeFooter onclick handlers
menuItems.insertHeader.onclick = function () {
factory.insertHeader()
menuItems.insertHeader.hide()
menuItems.removeHeader.show()
}
menuItems.insertFooter.onclick = function () {
factory.insertFooter()
menuItems.insertFooter.hide()
menuItems.removeFooter.show()
}
menuItems.removeHeader.onclick = function () {
factory.removeHeader()
menuItems.insertHeader.show()
menuItems.removeHeader.hide()
}
menuItems.removeFooter.onclick = function () {
factory.removeFooter()
menuItems.insertFooter.show()
menuItems.removeFooter.hide()
}
}
|
JavaScript
| 0.000001 |
@@ -2726,16 +2726,55 @@
uItems)%0A
+ ui.addUnselectableCSSClass(editor)%0A
%7D%0A%0A /
|
67ad7dda23fb95584f83df3c5fc5690a58185b60
|
Fix Prototype Pollution
|
lib/apply.js
|
lib/apply.js
|
'use strict';
var serialize = require('./utils').serialize;
module.exports = function apply(target, patch) {
patch = serialize(patch);
if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) {
return patch;
}
target = serialize(target);
if (target === null || typeof target !== 'object' || Array.isArray(target)) {
target = {};
}
var keys = Object.keys(patch);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (patch[key] === null) {
if (target.hasOwnProperty(key)) {
delete target[key];
}
} else {
target[key] = apply(target[key], patch[key]);
}
}
return target;
};
|
JavaScript
| 0.000001 |
@@ -461,16 +461,122 @@
eys%5Bi%5D;%0A
+ if (key === '__proto__' %7C%7C key === 'constructor' %7C%7C key === 'prototype') %7B%0A return target;%0A %7D%0A
if (
|
c76cad413a33a88455f9c9e42492dc46d734cf98
|
Remove spurious semicolon
|
js/energy-systems/view/EnergySystemsScreenView.js
|
js/energy-systems/view/EnergySystemsScreenView.js
|
// Copyright 2014-2015, University of Colorado Boulder
/**
* View for the 'Energy Systems' screen of the Energy Forms And Changes simulation.
*
* @author John Blanco
* @author Martin Veillette (Berea College)
* @author Jesse Greenberg
* @author Andrew Adare
*/
define( function( require ) {
'use strict';
// Modules
var Bounds2 = require( 'DOT/Bounds2' );
var CheckBox = require( 'SUN/CheckBox' );
var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
var EnergyChunkLegend = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/EnergyChunkLegend' );
var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
var EnergySystemElementSelector = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/EnergySystemElementSelector' );
var EnergyChunkNode = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkNode' );
var EnergyType = require( 'ENERGY_FORMS_AND_CHANGES/common/model/EnergyType' );
var HSlider = require( 'SUN/HSlider' );
var Image = require( 'SCENERY/nodes/Image' );
var inherit = require( 'PHET_CORE/inherit' );
var LayoutBox = require( 'SCENERY/nodes/LayoutBox' );
var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
var Node = require( 'SCENERY/nodes/Node' );
var Panel = require( 'SUN/Panel' );
var PhetFont = require( 'SCENERY_PHET/PhetFont' );
var Property = require( 'AXON/Property' );
var Rectangle = require( 'SCENERY/nodes/Rectangle' );
var ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
var ScreenView = require( 'JOIST/ScreenView' );
var SunNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/SunNode' );
var Text = require( 'SCENERY/nodes/Text' );
var Vector2 = require( 'DOT/Vector2' );
// Images
var mockupImage = require( 'image!ENERGY_FORMS_AND_CHANGES/mockup_energy_systems.png' );
// Strings
var energySymbolsString = require( 'string!ENERGY_FORMS_AND_CHANGES/energySymbols' );
// Constants
var EDGE_INSET = 10;
/**
* @param {EnergySystemsModel} model
* @constructor
*/
function EnergySystemsScreenView( model ) {
ScreenView.call( this, {
layoutBounds: new Bounds2( 0, 0, 1008, 679 )
} );
// Bounds2 object for use as primary geometric reference
var stage = this.layoutBounds;
// Node for back-most layer
var backLayer = new Node();
this.addChild( backLayer );
// ScreenView handle for use inside functions
var thisScreenView = this;
// Create the model-view transform. The primary units used in the model are
// meters, so significant zoom is used. The multipliers for the 2nd parameter
// can be used to adjust where the point (0, 0) in the model, which is on the
// middle of the screen above the counter as located in the view.
// Final arg is zoom factor - smaller zooms out, larger zooms in.
var mvtOriginX = Math.round( stage.width * 0.5 );
var mvtOriginY = Math.round( stage.height * 0.475 );
var modelViewTransform = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
Vector2.ZERO, new Vector2( mvtOriginX, mvtOriginY ), 2200 );
// Add beige background rectangle
function addBackground() {
backLayer.addChild( new Rectangle( stage, {
fill: EFACConstants.SECOND_TAB_BACKGROUND_COLOR
} ) );
}
// Create a background rectangle for the play/pause controls.
function addPlayControls() {
var bottomPanel = new Rectangle( 0, stage.maxY - 114, stage.width, stage.height, 0, 0, {
fill: EFACConstants.CLOCK_CONTROL_BACKGROUND_COLOR,
stroke: 'black'
} );
backLayer.addChild( bottomPanel );
}
//Show the mock-up and a slider to change its transparency
function addMockupImage() {
var opacity = new Property( 0.8 );
var image = new Image( mockupImage, {
pickable: false
} );
image.scale( stage.width / image.width );
opacity.linkAttribute( image, 'opacity' );
thisScreenView.addChild( image );
thisScreenView.addChild( new HSlider( opacity, {
min: 0,
max: 1
}, {
top: 10,
left: 10
} ) );
}
// Create the legend for energy chunk types
function addEnergyChunkLegend() {
var legend = new EnergyChunkLegend();
legend.center = new Vector2( 0.9 * stage.width;, 0.5 * stage.height );
thisScreenView.addChild( legend );
}
// Check box panel to display energy chunks
function addCheckBoxPanel() {
var label = new Text( energySymbolsString, {
font: new PhetFont( 20 )
} );
var energyChunkNode = EnergyChunkNode.createEnergyChunkNode( EnergyType.THERMAL );
energyChunkNode.scale( 1.0 );
energyChunkNode.pickable = false;
var checkBox = new CheckBox( new LayoutBox( {
children: [ label, energyChunkNode ],
orientation: 'horizontal',
spacing: 5
} ), model.energyChunksVisibleProperty );
var panel = new Panel( checkBox, {
fill: EFACConstants.CONTROL_PANEL_BACKGROUND_COLOR,
stroke: EFACConstants.CONTROL_PANEL_OUTLINE_STROKE,
lineWidth: EFACConstants.CONTROL_PANEL_OUTLINE_LINE_WIDTH
} );
panel.rightTop = new Vector2( stage.width - EDGE_INSET, EDGE_INSET );
thisScreenView.addChild( panel );
}
// Create and add the Reset All Button in the bottom right, which resets the model
function addResetButton() {
var resetAllButton = new ResetAllButton( {
listener: function() {
model.reset();
},
right: stage.maxX - 10,
bottom: stage.maxY - 10
} );
thisScreenView.addChild( resetAllButton );
}
function addSun() {
var sun = new SunNode( model.sun, model.energyChunksVisibleProperty, modelViewTransform );
thisScreenView.addChild( sun );
}
// Create the carousel control nodes.
function addCarousels() {
var sourcesCarousel = new EnergySystemElementSelector( model.energySourcesCarousel );
// var convertersCarousel = new EnergySystemElementSelector( model.energyConvertersCarousel );
// var usersCarousel = new EnergySystemElementSelector( model.energyUsersCarousel );
thisScreenView.addChild( sourcesCarousel );
// thisScreenView.addChild( convertersCarousel );
// thisScreenView.addChild( usersCarousel );
}
addBackground();
addPlayControls();
addMockupImage();
addEnergyChunkLegend();
addCheckBoxPanel();
addResetButton();
addSun();
addCarousels();
}
energyFormsAndChanges.register( 'EnergySystemsScreenView', EnergySystemsScreenView );
return inherit( ScreenView, EnergySystemsScreenView );
} );
|
JavaScript
| 0.999365 |
@@ -4386,17 +4386,16 @@
ge.width
-;
, 0.5 *
|
b9939d5fb24604dde2a75ba305d794e1ddb69b79
|
fix svg optimization, add clear cache task
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var prefix = require('gulp-autoprefixer');
var minify = require('gulp-minify-css');
var sequence = require('run-sequence');
var uglify = require('gulp-uglifyjs');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var rsync = require('rsyncwrapper').rsync;
var gutil = require('gulp-util');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var args = require('yargs').argv;
var gulpif = require('gulp-if');
var config = require('./config.json');
var src = 'app/';
var dest = 'build/';
var bower = 'components/';
var deployTarget = ( typeof args.target !== 'undefined' ? args.target : 'staging' );
gulp.task('styles', function () {
return gulp.src([
src + 'scss/main.scss',
src + 'scss/editor.scss'
])
.pipe(sass({
precision: 10,
loadPath: [
process.cwd() + '/app/scss',
process.cwd() + '/components'
]
}))
.pipe(prefix('last 1 version', 'ie 9'))
.pipe(minify({ keepSpecialComments: 1 }))
.pipe(gulp.dest(dest + 'css'));
});
gulp.task('scripts', function() {
return gulp.src([
bower + 'bootstrap-sass-official/assets/javascripts/bootstrap.js',
bower + 'fitvids/jquery.fitvids.js',
src + 'js/plugins/*.js',
src + 'js/main.js'
])
.pipe(uglify('main.js', {
outSourceMap: true,
basePath: 'build/js'
}))
.pipe(gulp.dest(dest + 'js'));
});
gulp.task('admin-scripts', function() {
return gulp.src([
src + 'js/admin.js'
])
.pipe(uglify('admin.js', {
outSourceMap: true,
basePath: 'build/js'
}))
.pipe(gulp.dest(dest + 'js'));
});
gulp.task('lint', function() {
return gulp.src(src + 'js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'));
});
gulp.task('images', function() {
return gulp.src(src + 'img/**/*')
.pipe(cache(imagemin({
optimizationLevel: 5,
progressive: true,
interlaced: true
})))
.pipe(gulp.dest(dest + 'img'));
});
gulp.task('fonts', function() {
return gulp.src(src + 'font/*')
.pipe(gulp.dest(dest + 'font'));
});
gulp.task('watch', function () {
gulp.watch(src + 'scss/**/*.scss', ['styles']);
gulp.watch(src + 'js/**/*.js', ['scripts']);
gulp.watch(src + 'img/**/*', ['images']);
});
gulp.task('rsync', function() {
if ( config.servers[deployTarget].user === '' ||
config.servers[deployTarget].host === '' ) {
return gutil.log(gutil.colors.red('ERROR:'), 'User, host and path not configured for ' + deployTarget + ' target in config.json');
}
rsync({
ssh: true,
src: './',
dest: config.servers[deployTarget].user + '@' + config.servers[deployTarget].host + ':' + config.servers[deployTarget].path,
recursive: true,
syncDest: true,
exclude: ['node_modules', '.sass-cache'],
args: ['--verbose']
}, function(error, stdout, stderr, cmd) {
gutil.log(stdout);
});
});
gulp.task('deploy', function(cb) {
sequence('default', 'rsync', cb);
});
gulp.task('default', ['styles', 'scripts', 'admin-scripts', 'images', 'fonts']);
|
JavaScript
| 0 |
@@ -2086,16 +2086,92 @@
ed: true
+,%0A svgoPlugins: %5B%0A %7B removeUselessStrokeAndFill: false %7D%0A %5D
%0A %7D))
@@ -3131,32 +3131,94 @@
t);%0A %7D);%0A%0A%7D);%0A%0A
+gulp.task('clearCache', function() %7B%0A cache.clearAll();%0A%7D);%0A%0A
gulp.task('deplo
@@ -3236,17 +3236,16 @@
n(cb) %7B%0A
-%0A
sequen
@@ -3272,17 +3272,16 @@
', cb);%0A
-%0A
%7D);%0A%0Agul
|
a6088945a6a25dbd35c4a45f5e51f7fc125fc25a
|
fix > in reply
|
src/js/controller/write.js
|
src/js/controller/write.js
|
define(function(require) {
'use strict';
var angular = require('angular'),
appController = require('js/app-controller'),
aes = require('cryptoLib/aes-cbc'),
util = require('cryptoLib/util'),
str = require('js/app-config').string,
emailDao;
//
// Controller
//
var WriteCtrl = function($scope, $routeParams) {
$scope.signature = str.signature;
//
// Init
//
// start the main app controller
appController.start(function(err) {
if (err) {
console.error(err);
return;
}
if (window.chrome && chrome.identity) {
init('passphrase', function() {
emailDao = appController._emailDao;
getReplyTo($routeParams.folder, $routeParams.id, function() {
$scope.$apply();
});
});
return;
}
});
function init(passphrase, callback) {
appController.fetchOAuthToken(passphrase, function(err) {
if (err) {
console.error(err);
return;
}
callback();
});
}
function getReplyTo(folder, id, callback) {
if (!folder || !id) {
callback();
}
emailDao.listMessages({
folder: folder + '_' + id
}, function(err, list) {
if (err) {
console.error(err);
return;
}
if (list.length > 0) {
fillFields(list[0]);
}
callback();
});
}
function fillFields(re) {
if (!re) {
return;
}
// fille title
$scope.title = 'Reply';
// fill recipient field
$scope.to = re.from[0].address;
// fill subject
$scope.subject = 'Re: ' + ((re.subject) ? re.subject.replace('Re: ', '') : '');
// fill text body
var body = '<br><br>' + re.sentDate + ' ' + re.from[0].name + ' <' + re.from[0].address + '>';
var bodyRows = re.body.split('\n');
bodyRows.forEach(function(row) {
body += (!re.html) ? '<br> > ' + row : '';
});
$scope.body = body;
}
//
// Editing
//
// generate key,iv for encryption preview
var key = util.random(128),
iv = util.random(128);
$scope.updatePreview = function() {
var body = $scope.body;
// remove generated html from body
body = parseBody(body);
// Although this does encrypt live using AES, this is just for show. The plaintext is encrypted seperately before sending the email.
var plaintext = ($scope.subject) ? $scope.subject + body : body;
$scope.ciphertextPreview = (plaintext) ? aes.encrypt(plaintext, key, iv) : '';
};
$scope.sendEmail = function() {
var to, body, email;
// validate recipients
to = $scope.to.replace(/\s/g, '').split(/[,;]/);
if (!to || to.length < 1) {
console.log('Seperate recipients with a comma!');
return;
}
body = $scope.body;
// remove generated html from body
body = parseBody(body);
email = {
to: [], // list of receivers
subject: $scope.subject, // Subject line
body: body // plaintext body
};
email.from = [{
name: '',
address: emailDao._account.emailAddress
}];
to.forEach(function(address) {
email.to.push({
name: '',
address: address
});
});
emailDao.smtpSend(email, function(err) {
if (err) {
console.log(err);
return;
}
if (window.chrome && chrome.app.window) {
// close the chrome window
chrome.app.window.current().close();
return;
}
});
};
};
function parseBody(body) {
function has(substr) {
return (body.indexOf(substr) !== -1);
}
while (has('<div>')) {
body = body.replace('<div>', '\n');
}
while (has('<br>')) {
body = body.replace('<br>', '\n');
}
while (has('</div>')) {
body = body.replace('</div>', '');
}
return body;
}
//
// Directives
//
var ngModule = angular.module('write', []);
ngModule.directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
// view -> model
elm.on('keyup keydown focus', function() {
scope.$apply(function() {
ctrl.$setViewValue(elm.html());
});
});
// model -> view
ctrl.$render = function() {
elm.html(ctrl.$viewValue);
};
// load init value from DOM
ctrl.$setViewValue(elm.html());
}
};
});
ngModule.directive('focusMe', function($timeout) {
return {
link: function(scope, element) {
$timeout(function() {
element[0].focus();
});
}
};
});
return WriteCtrl;
});
|
JavaScript
| 0 |
@@ -365,16 +365,25 @@
teParams
+, $filter
) %7B%0A
@@ -1843,24 +1843,63 @@
ields(re) %7B%0A
+ var from, body, bodyRows;%0A%0A
@@ -2258,100 +2258,166 @@
-var body = '%3Cbr%3E%3Cbr%3E' + re.sentDate + ' ' + re.from%5B0%5D.name
+from = re.from%5B0%5D.name %7C%7C re.from%5B0%5D.address;%0A body = '%3Cbr%3E%3Cbr%3E' + $filter('date')(re.sentDate, 'EEEE, MMM d, yyyy h:mm a')
+ '
-%3C
' +
-re.
from
-%5B0%5D.address + '%3E
+ + ' wrote:
';%0A
@@ -2423,28 +2423,24 @@
-var
bodyRows = r
@@ -2546,19 +2546,16 @@
? '%3Cbr%3E
- %3E
' + row
@@ -5329,14 +5329,8 @@
down
- focus
', f
|
020cb953b21bf2e0e7fa0feed85fcbbe655516fa
|
Remove TODO comment
|
src/main.js
|
src/main.js
|
;(function() {
"use strict"
var $ = document.querySelectorAll.bind(document)
// --- DOM elements ---------------------------------------
var $diskSlot = $('#slot')[0]
var $powerSwitch = $('#power-switch')[0]
var $filesScript = $('#files')[0]
var $groveWorkerScript = $('#grove-worker')[0]
var $modalOverlay = $('#overlay')[0]
var $hideDataEditorButton = $('#file-modal .close-button button')[0]
var $showDataEditorButton = $('#data-editor-button')[0]
var $entryNameInput = $('#file-modal .file-selector input')[0]
var $entryContentInput = $('#file-modal textarea')[0]
var $dataEditorSaveButton = $('#file-modal .save')[0]
var $title = $('head title')[0]
// --- Initial state --------------------------------------
var dataRecords = FILES
var lastSaveTimestamp = +(new Date())
var groveWorker = GroveWorker(
dataRecords,
handleMessageFromWorker)
setTitleTo(getComputerName(dataRecords))
// --- Event handler setup --------------------------------
click($diskSlot, function() {
$filesScript.innerText
= 'var FILES = ' + JSON.stringify(dataRecords)
var pageData = document.documentElement.outerHTML
var blob = new Blob([pageData], {type: 'text/html'})
saveAs(blob, createFilename(getComputerName(dataRecords)))
lastSaveTimestamp = +(new Date())
})
click($showDataEditorButton, function() {
$modalOverlay.style.display = 'block';
$entryNameInput.focus()
})
click($hideDataEditorButton, function() {
$modalOverlay.style.display = 'none';
})
click($dataEditorSaveButton, function() {
var name = $entryNameInput.value
var content = $entryContentInput.value
if (!name) return
dataRecords[name] = content
groveWorker.postMessage({
type: 'updateDataRecord',
name: name,
content: content
})
})
click($powerSwitch, function() {
if (groveWorker) {
// turn off
groveWorker.terminate()
groveWorker = null
redraw([])
} else {
// turn on
groveWorker = GroveWorker(dataRecords, handleMessageFromWorker)
}
})
window.addEventListener('beforeunload', function(e) {
if (shouldWarnAboutUnsavedChanges()) {
// This message isn't shown in Chrome but it might be in other browsers.
return e.returnValue = "You have unsaved changes. Are you sure you want to leave?"
}
})
window.addEventListener('keydown', function(e) {
if (groveWorker) { // TODO refactor to null object pattern
groveWorker.postMessage({type: 'keyDown', event: {keyCode: e.keyCode}})
}
})
window.addEventListener('keyup', function(e) {
if (groveWorker) {
groveWorker.postMessage({type: 'keyUp', event: {keyCode: e.keyCode}})
}
})
// --- Function definitions -------------------------------
function handleMessageFromWorker(msg) {
switch (msg.data.type) {
case 'redraw':
redraw(msg.data.value)
break
case 'dataRecordChange':
dataRecords[msg.data.name] = msg.data.content
setTitleTo(getComputerName(dataRecords))
break
}
}
function GroveWorker(dataRecords, messageCallback) {
var scriptBlob = new Blob([
'var FILES = ',
JSON.stringify(dataRecords),
';',
$groveWorkerScript.innerText
])
var worker = new Worker(URL.createObjectURL(scriptBlob))
worker.addEventListener('message', messageCallback)
return worker
}
function click(elem, callback) {
elem.addEventListener('click', callback)
}
function setTitleTo(title) {
$title.innerText = title
}
function redraw(text) {
var lines = $('#terminal p')
for (var i = 0; i < lines.length; i++) {
lines[i].innerHTML = text[i] || ''
}
}
function createFilename(computerName) {
var date = new Date()
return computerName + '-' + formatDateForFilename(date)
}
function shouldWarnAboutUnsavedChanges() {
return +(new Date()) - lastSaveTimestamp > 30 * 1000
}
})();
|
JavaScript
| 0 |
@@ -2321,48 +2321,8 @@
r) %7B
- // TODO refactor to null object pattern
%0A
|
7510d6591fbdedc80c02e06e249124a7ef6134d8
|
add onerror for test, failing tests would not move to rebuild when watching.
|
gulpfile.js
|
gulpfile.js
|
(function () {
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var opn = require('opn');
var del = require('del');
var lintSrc = ['./gulpfile.js', './index.js', 'test/**/*.js', 'bin/*.js'];
var testSrc = ['test/*helper.js', 'test/*spec.js'];
function runCoverage (opts) {
return gulp.src(testSrc, { read: false })
.pipe($.coverage.instrument({
pattern: ['./index.js'],
debugDirectory: 'debug'}))
.pipe($.plumber())
.pipe($.mocha({reporter: 'dot'})
.on('error', function () { this.emit('end'); })) // test errors dropped
.pipe($.plumber.stop())
.pipe($.coverage.gather())
.pipe($.coverage.format(opts));
}
gulp.task("clean", function (done) {
del(["coverage.html", "debug/**/*", "debug"], done);
});
gulp.task("lint", function () {
return gulp.src(lintSrc)
.pipe($.jshint())
.pipe($.jshint.reporter(require('jshint-table-reporter')));
});
gulp.task('coveralls', ['clean'], function () {
return runCoverage({reporter: 'lcov'})
.pipe($.coveralls());
});
gulp.task('coverage', ['clean'], function () {
return runCoverage({outFile: './coverage.html'})
.pipe(gulp.dest('./'))
.on('end', function () {
opn('./coverage.html');
});
});
gulp.task("test", ['clean', 'lint'], function () {
return gulp.src(testSrc, { read: false })
.pipe($.plumber())
.pipe($.mocha({reporter: 'spec', globals: ['expect', 'should']}))
.pipe($.plumber.stop());
});
gulp.task("watch", function () {
gulp.watch(lintSrc, ['test']);
});
gulp.task("default", ["test"]);
})();
|
JavaScript
| 0 |
@@ -1517,16 +1517,75 @@
ould'%5D%7D)
+%0A .on('error', function () %7B this.emit('end'); %7D)
)%0A
|
8ff313fe956d5f5d9f471db6cc227bd4afac520b
|
Add mouse click for firing
|
src/js/game/states/game.js
|
src/js/game/states/game.js
|
var _ = require('lodash'),
zombieLogic = require('./zombie')(),
playerLogic = require('./player')(),
buildingLogic = require('./building')(),
weapon = require('./weapon')();
module.exports = function(game) {
var gameState = {},
staticObjects,
player,
zombies,
cursors,
bullets,
buildings,
playerCollisionGroup,
zombiesCollisionGroup,
staticObjectsCollisionGroup;
function resetEntity(entity) {
entity.body.velocity.x = 0;
entity.body.velocity.y = 0;
};
function killZombie(bullet, zombie) {
bullet.kill();
zombie.kill();
}
gameState.create = function () {
game.physics.startSystem(Phaser.Physics.P2JS);
staticObjects = game.add.group();
buildings = game.add.group();
zombies = game.add.group();
playerCollisionGroup = game.physics.p2.createCollisionGroup();
zombiesCollisionGroup = game.physics.p2.createCollisionGroup();
staticObjectsCollisionGroup = game.physics.p2.createCollisionGroup();
//Create an array of coordinates that make a 3000px x 3000 grid
var placementMatrix = [];
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
placementMatrix.push([i*500, j*500]);
};
};
//Iterate through array to randomly drop cars or trees
//Once a placement is determined in a grid box, it is randomly placed
_.each(placementMatrix, function (coordinates) {
rand = _.random(0, 100);
randX = _.random(0, 500);
randY = _.random(0, 500);
if (rand < 50) {
if (rand%2 == 0) {
var car = staticObjects.create(coordinates[0]-randX, coordinates[1]-randY, 'car');
game.physics.p2.enable(car);
car.body.setCollisionGroup(staticObjectsCollisionGroup);
} else {
var tree = staticObjects.create(coordinates[0]-randX, coordinates[1]-randY, 'tree');
game.physics.p2.enable(tree);
tree.body.setCollisionGroup(staticObjectsCollisionGroup);
}
} else if (rand > 90) {
var building = buildings.create(coordinates[0], coordinates[1], 'building');
building.hasSpawned = false;
game.physics.p2.enable(building);
building.body.setCollisionGroup(staticObjectsCollisionGroup);
}
});
//Create player in center area
player = game.add.sprite(game.world.centerX, game.world.centerY, 'hero');
player.pivot.setTo(0,0);
game.physics.p2.enable(player);
player.body.collideWorldBounds = true;
player.body.setCollisionGroup(playerCollisionGroup);
//Create bullets
bullets = game.add.group();
game.physics.enable(bullets, Phaser.Physics.ARCADE);
};
gameState.update = function() {
// Reset the players velocity (movement)
resetEntity(player);
game.camera.follow(player);
// game.physics.arcade.collide(player, staticObjects);
// game.physics.arcade.collide(player, zombies);
// game.physics.arcade.collide(zombies, staticObjects);
// game.physics.arcade.collide(zombies, zombies);
game.physics.arcade.overlap(bullets, zombies, killZombie, null, this);
playerLogic.movePlayer(game, player);
playerLogic.rotatePlayer(game, player);
if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
weapon.shoot(game, player, bullets);
}
_.each(zombies.children, function(zombie){
zombieLogic.moveZombie(player, zombie);
});
_.each(buildings.children, function(building) {
buildingLogic.spawnZombiesFromBuilding(game, zombies, player, building, zombiesCollisionGroup);
});
}
return gameState;
};
|
JavaScript
| 0.000001 |
@@ -3278,16 +3278,57 @@
PACEBAR)
+ %7C%7C game.input.mousePointer.justPressed()
) %7B%0A
|
ee58f9ab02b62612ef978c1f12da10fcf9319c2f
|
Revert "Removed code that is implemented yet (conflict wasn't resolved properly)"
|
src/dataviews/dataview-model-base.js
|
src/dataviews/dataview-model-base.js
|
var _ = require('underscore');
var Model = require('../core/model');
var WindshaftFiltersBoundingBoxFilter = require('../windshaft/filters/bounding-box');
/**
* Default dataview model
*/
module.exports = Model.extend({
defaults: {
url: '',
data: [],
columns: [],
syncData: true,
syncBoundingBox: true,
enabled: true
},
url: function () {
var params = [];
if (this.get('boundingBox')) {
params.push('bbox=' + this.get('boundingBox'));
}
return this.get('url') + '?' + params.join('&');
},
initialize: function (attrs, opts) {
attrs = attrs || {};
opts = opts || {};
if (!opts.map) {
throw new Error('map is required');
}
if (!opts.windshaftMap) {
throw new Error('windshaftMap is required');
}
if (!attrs.id) {
this.set('id', attrs.type + '-' + this.cid);
}
this.layer = opts.layer;
this._map = opts.map;
this._windshaftMap = opts.windshaftMap;
// filter is optional, so have to guard before using it
this.filter = opts.filter;
if (this.filter) {
this.filter.set('dataviewId', this.id);
}
this._initBinds();
},
_initBinds: function () {
this.listenTo(this._windshaftMap, 'instanceCreated', this._onNewWindshaftMapInstance);
this.listenToOnce(this, 'change:url', function () {
this._fetch(this._onChangeBinds.bind(this));
});
if (this.filter) {
this.listenTo(this.filter, 'change', this._onFilterChanged);
}
},
_onFilterChanged: function (filter) {
this._map.reload({
sourceLayerId: this.layer.get('id')
});
},
_onNewWindshaftMapInstance: function (windshaftMapInstance, sourceLayerId) {
var url = windshaftMapInstance.getDataviewURL({
dataviewId: this.get('id'),
protocol: 'http'
});
if (url) {
var silent = (sourceLayerId && sourceLayerId !== this.layer.get('id'));
// TODO: Instead of setting the url here, we could invoke fetch directly
this.set('url', url, { silent: silent });
}
},
_onChangeBinds: function () {
var BOUNDING_BOX_FILTER_WAIT = 500;
this.listenTo(this._map, 'change:center change:zoom', _.debounce(this._onMapBoundsChanged.bind(this), BOUNDING_BOX_FILTER_WAIT));
this.listenTo(this, 'change:url', function () {
if (this._shouldFetchOnURLChange()) {
this._fetch();
}
});
this.listenTo(this, 'change:boundingBox', function () {
if (this._shouldFetchOnBoundingBoxChange()) {
this._fetch();
}
});
this.listenTo(this, 'change:enabled', function (mdl, isEnabled) {
if (isEnabled) {
if (mdl.changedAttributes(this._previousAttrs)) {
this._fetch();
}
} else {
this._previousAttrs = {
url: this.get('url'),
boundingBox: this.get('boundingBox')
};
}
});
},
_onMapBoundsChanged: function () {
this._updateBoundingBox();
},
_updateBoundingBox: function () {
var boundingBoxFilter = new WindshaftFiltersBoundingBoxFilter(this._map.getViewBounds());
this.set('boundingBox', boundingBoxFilter.toString());
},
_shouldFetchOnURLChange: function () {
return this.get('syncData') && this.get('enabled');
},
_shouldFetchOnBoundingBoxChange: function () {
return this.get('enabled') && this.get('syncBoundingBox');
},
_fetch: function (callback) {
var self = this;
this.fetch({
success: callback,
error: function () {
self.trigger('error');
}
});
},
fetch: function (opts) {
this.trigger('loading', this);
if (this.layer.getDataProvider()) {
this._fetchFromDataProvider(opts);
} else {
return Model.prototype.fetch.call(this, opts);
}
},
_fetchFromDataProvider: function (opts) {
var dataProvider = this.layer.getDataProvider();
// TODO: At the beginning, the dataProvider will not have any features
// loaded so we will have to listen to the `featuresChanged` event, but
// once the dataProvider has been initialized, we should implement and use
// dataProvider.getFeatures() instead of adding yet another binding.
dataProvider.bind('featuresChanged', function (features) {
try {
var data = dataProvider.generateDataForDataview(this, features);
// TODO: this.parse() is doing some magic (like resetting this._data)
// in some cases (category and histogram) and that's why we use it here.
// If that wasn't the case, data could be generated by the dataProvider in
// the format that the dataview expects.
this.set(this.parse(data));
this.trigger('sync');
opts && opts.success && opts.success(this);
} catch (error) {
// TODO: fallback to Model.prototype.fetch.call(this, opts);?
}
}.bind(this));
},
refresh: function () {
this._fetch();
},
getData: function () {
return this.get('data');
},
getPreviousData: function () {
return this.previous('data');
},
toJSON: function () {
throw new Error('toJSON should be defined for each dataview');
},
remove: function () {
if (this.filter) {
this.filter.remove();
}
this.trigger('destroy', this);
this.stopListening();
}
});
|
JavaScript
| 0 |
@@ -1534,24 +1534,176 @@
(filter) %7B%0A
+ var dataProvider = this.layer.getDataProvider();%0A if (dataProvider) %7B%0A dataProvider.applyFilter(this.get('column'), filter);%0A %7D else %7B%0A
this._ma
@@ -1713,16 +1713,18 @@
eload(%7B%0A
+
so
@@ -1757,28 +1757,36 @@
t('id')%0A
+
%7D);%0A
+ %7D%0A
%7D,%0A%0A _onN
|
811f4039d81a3526714604ee9d1fc28a89d836dc
|
version bump
|
src/js/lib/Bootstrapper.js
|
src/js/lib/Bootstrapper.js
|
/* eslint-disable no-console */
export default class {
/**
* Primer constructor.
*/
constructor() {
this.debug = false;
// Stash console for later use.
this.console = global.console;
}
/**
* Get the Primer version.
*
* @returns {string}
*/
get version() {
return '0.1.4';
}
/**
* Boot Primer.
*
* @param {bool} debug
*
* @returns {object}
*/
boot(debug = false) {
this.debug = debug;
// Suppress console loging when debugging is disabled.
if (! debug) {
this.disableConsole();
} else {
this.enableConsole();
}
return this;
}
/**
* Disable console logging.
*/
disableConsole() {
global.console = {};
console.log
= console.info
= console.warm
= console.error = () => {};
}
/**
* Enable/Restore console logging.
*/
enableConsole() {
global.console = this.console;
global.console.warn(`Centagon Primer ${this.version} debug mode enabled!
Please disable logging on production by calling (new Primer).boot(false);`);
}
}
|
JavaScript
| 0.000001 |
@@ -351,9 +351,9 @@
0.1.
-4
+8
';%0A
|
85ebe79da8be9b51c3452bf28f641a9f87e9159d
|
Remove console output for facebook
|
facebook.js
|
facebook.js
|
filterKeyWords = [
["like page"],
["sponsored"],
["happy birthday"]];
Set.prototype.intersection = function(setB) {
var intersection = new Set();
for (var elem of setB) {
if (this.has(elem)) {
intersection.add(elem);
}
}
return intersection;
}
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
}
function getRawString(str){
return str.replaceAll("<[^>]*>", " ").toLowerCase().replaceAll("\\s+", " ").trim();
}
function toBeFiltered(element) {
if (!element) {return true;}
article = getRawString(element.html());
console.log(article);
for (var i = 0; i < filterKeyWords.length; i++) {
for (var j = 0; j < filterKeyWords[i].length; j++) {
if(article.contains(filterKeyWords[i][j])) return true;
}
}
return false;
}
function eliminateOnInsert(e) {
element = $(e.target);
id = element.attr('id');
if(id && id.startsWith('u_jsonp')) {
parent = element.parent();
if(parent) {
id = parent.attr('id');
if(id && id.startsWith('hyperfeed_story_id') && toBeFiltered(parent)) {
parent.hide();
}
}
}
}
(function(){
divs=$('div');
divs = divs.filter(function(i, div){
id = div.getAttribute('id');
if(id) {
return id.startsWith('hyperfeed_story_id');
}
return false;
});
divs.each(function(i, div){
div = $(div);
if (toBeFiltered(div)) {
div.hide();
}
});
}());
$(document).on('DOMNodeInserted', eliminateOnInsert);
|
JavaScript
| 0.000003 |
@@ -681,34 +681,8 @@
));%0A
- console.log(article);%0A
|
e631def8bbec2abf3fd4f435681b5d417fd35000
|
add grunt watch option to run less task on start
|
src/themes/mobile/Gruntfile.js
|
src/themes/mobile/Gruntfile.js
|
/*eslint-env node */
module.exports = function (grunt) {
grunt.initConfig({
"bolt-init": {
"theme": {
config_dir: "config/bolt"
}
},
"bolt-build": {
"theme": {
config_js: "config/bolt/prod.js",
output_dir: "scratch",
main: "tinymce.themes.mobile.Theme",
filename: "theme",
generate_inline: true,
minimise_module_names: true,
files: {
src: ["src/main/js/Theme.js"]
}
}
},
copy: {
"theme": {
files: [
{
src: "scratch/inline/theme.raw.js",
dest: "dist/inline/theme.js"
}
]
},
"standalone": {
files: [
{
expand: true,
flatten: true,
src: ['src/main/css/**'],
dest: 'deploy-local/css',
filter: 'isFile'
},
{
expand: true,
flatten: true,
src: ['src/main/icons/**'],
dest: 'deploy-local/icons',
filter: 'isFile'
},
{
src: "../../../js/tinymce/tinymce.min.js",
dest: "deploy-local/js/tinymce.min.js"
},
{
src: "../../../js/tinymce/plugins/lists/plugin.min.js",
dest: "deploy-local/js/plugins/lists/plugin.min.js"
},
{
src: "scratch/inline/theme.js",
dest: "deploy-local/js/mobile_theme.js"
},
{
src: "index.html",
dest: "deploy-local/index.html"
}
]
}
},
eslint: {
options: {
config: "../../../.eslintrc"
},
src: [
"src"
]
},
uglify: {
options: {
beautify: {
ascii_only: true,
screw_ie8: false
},
compress: {
screw_ie8: false
}
},
"standalone": {
files: [
{
src: "deploy-local/js/mobile_theme.js",
dest: "deploy-local/js/mobile_theme.min.js"
}
]
},
"theme": {
files: [
{
src: "scratch/inline/theme.js",
dest: "dist/inline/theme.min.js"
}
]
}
},
less: {
development: {
options: {
plugins : [ new (require('less-plugin-autoprefix'))({browsers : [ "last 2 versions" ]}) ],
compress: true,
yuicompress: true,
optimization: 2
},
files: {
"src/main/css/mobile.css": "src/main/css/app/mobile-less.less" // destination file and source file
}
}
},
watch: {
styles: {
files: ['src/main/css/**/*.less'], // which files to watch
tasks: ['less'],
options: {
nospawn: true
}
}
}
});
grunt.task.loadTasks("../../../node_modules/@ephox/bolt/tasks");
grunt.task.loadTasks("../../../node_modules/grunt-contrib-copy/tasks");
grunt.task.loadTasks("../../../node_modules/grunt-contrib-uglify/tasks");
grunt.task.loadTasks("../../../node_modules/grunt-eslint/tasks");
grunt.task.loadTasks("../../../node_modules/grunt-contrib-less/tasks");
grunt.task.loadTasks("../../../node_modules/grunt-contrib-watch/tasks");
grunt.registerTask("default", ["bolt-init", "bolt-build", "copy", "eslint", "uglify:theme"]);
grunt.registerTask("standalone", [ "bolt-build", "copy:standalone", "uglify:standalone"]);
};
|
JavaScript
| 0 |
@@ -2849,16 +2849,41 @@
nospawn:
+ true,%0A atBegin:
true%0A
|
b90af209f6909521022de959496299cac4bf2ad8
|
Remove gulp-mocha depen
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var contribs = require('gulp-contribs');
var mocha = require('gulp-mocha');
gulp.task('lint', function () {
gulp.src(['test/specs/**/*.js', '!test/fixtures/**', 'lib/*'])
.pipe(jshint('test/specs/.jshintrc'))
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'))
});
gulp.task('contribs', function () {
gulp.src('README.md')
.pipe(contribs())
.pipe(gulp.dest("./"))
});
gulp.task('test', function () {
gulp.src('test/specs/cli-new/*.js')
.pipe(mocha())
.pipe(gulp.dest("./"))
});
gulp.task('default', ['lint']);
|
JavaScript
| 0.000002 |
@@ -102,43 +102,8 @@
s');
-%0Avar mocha = require('gulp-mocha');
%0A%0Agu
@@ -459,139 +459,8 @@
);%0A%0A
-gulp.task('test', function () %7B%0A gulp.src('test/specs/cli-new/*.js')%0A .pipe(mocha())%0A .pipe(gulp.dest(%22./%22))%0A%7D);%0A%0A
gulp
|
bd4ad7ef8b081ae5aeefa2f7d254abca14151379
|
Fix indentation
|
src/main.js
|
src/main.js
|
/**
* @namespace
*/
var Cache = function () {
/**
* Default values
*/
var DEFAULT = {
prefix: '_cache',
ttl: 604800,
provider: 'localStorage'
};
var eventSubscribers = {
cacheAdded: [],
cacheRemoved: []
};
/**
* Group all functions that are shared across all providers
*/
var _this = {
getProvider: function (name) {
switch (name) {
case 'localStorage':
return localStorageProvider;
case 'array':
return arrayProvider;
}
},
/**
* Accept keys as array e.g: {blogId:"2",action:"view"} and convert it to unique string
*/
generateKey: function (object) {
var generatedKey = DEFAULT.prefix + '_',
keyArray = [];
for (var key in object){
if(object.hasOwnProperty(key))
{
keyArray.push(key);
}
}
keyArray.sort();
for(var i=0; i<keyArray.length; i++){
generatedKey += keyArray[i] + '_' + object[keyArray[i]];
if(i !== (keyArray.length - 1)){
generatedKey += '__';
}
}
return generatedKey;
},
generateContextKey: function(key,value){
return DEFAULT.prefix + '_context_' + key + '_' + value;
},
/**
* Get current time (compared to Epoch time) in seconds
*/
getCurrentTime: function(){
var timestamp = new Date().getTime();
return Math.floor(timestamp/1000);
},
/**
* Return default values
*/
getDefault: function(){
return DEFAULT;
},
/**
* Return subscribers
*
* @returns {{cacheAdded: Array, cacheRemoved: Array}}
*/
getEventSubscribers: function(){
return eventSubscribers;
},
/**
* Dispatch event to subscribers
*
* @param event Event name
* @param object Object will be sent to subscriber
*/
dispatchEvent: function(event, object){
var callbacks = eventSubscribers[event];
if(callbacks.length < 1){
return;
}
for(var index = 0; index < callbacks.length; index++){
if(typeof(callbacks[index]) !== 'undefined' && _this.isFunction(callbacks[index])){
callbacks[index](object);
}
}
},
/**
* Check if x is a function
*
* @param x
* @returns {boolean}
*/
isFunction: function(x){
return Object.prototype.toString.call(x) == '[object Function]';
}
};
/**
* Initiate providers as local variables
*/
var localStorageProvider = new LocalStorageProvider(_this),
arrayProvider = new ArrayProvider(_this);
/**
* Public functions
*/
return {
/**
* @method Cache.use
* @description Switch provider. available providers are: 'localStorage','array'
*
* @param provider
*/
use: function(provider) {
DEFAULT.provider = provider;
return this;
},
/**
* @method Cache.get
* @description Get cache by array key
*
* @param key - Array key
* @returns {string}
* @example
* Cache.get({blogId:"2",action:"view"});
*/
get: function(key){
return _this.getProvider(DEFAULT.provider).get(key);
},
/**
* @method Cache.set
* @description Save data for key
*
* @param key - Array key
* @param value - value must be a string
* @param ttl - Time to live in seconds
* @param contexts - Contexts
* @returns {Cache}
*/
set: function(key, value, ttl, contexts){
_this.getProvider(DEFAULT.provider).set(key, value, ttl, contexts);
return this;
},
/**
* @method Cache.setPrefix
* @description Set prefix for cache key (default: _cache)
*
* @param prefix
* @returns {Cache}
*/
setPrefix: function(prefix){
DEFAULT.prefix = prefix;
return this;
},
/**
* @method Cache.getPrefix
* @description Get prefix for cache key
*
* @returns {string}
*/
getPrefix: function(){
return DEFAULT.prefix;
},
/**
* @method Cache.removeByKey
*
* @param key
* @returns {Cache}
*/
removeByKey: function(key){
_this.getProvider(DEFAULT.provider).removeByKey(key);
return this;
},
/**
* @method Cache.removeByContext
*
* @param context
* @returns {Cache}
*/
removeByContext: function(context){
_this.getProvider(DEFAULT.provider).removeByContext(context);
return this;
},
/**
* @method Cache.on
* @description Subscribe to an event
*
* @param event
* @param callback
*/
on: function(event, callback){
eventSubscribers[event].push(callback);
},
/**
* @method Cache.unsubscribe
* @description Unsubscribe to an event
*
* @param event
* @param callback
*/
unsubscribe: function(event, callback){
var callbacks = eventSubscribers[event];
for(var i = 0; i < callbacks.length; i++){
if(callbacks[i] === callback){
delete callbacks[i];
break;
}
}
}
};
};
|
JavaScript
| 0.017244 |
@@ -2813,24 +2813,28 @@
x)%7B%0A
+
return Objec
|
c44e669611d4e5d16a26068edae5926a476c0c4d
|
Use jquery(document) instead of jquery('document').
|
js/index.js
|
js/index.js
|
"use strict";
/*
* lisTours bundle entry point (index.js).
*/
var lisTours = {}; /* the lisTours library, created by this module */
(function(){
var that = this;
var TOUR_ID_KEY = 'lisTourId';
var MS = 100;
//adf: doubled this from previous value to accomodate slow gene searches;
//maybe there's a better approach.
var MAX_MS = 20000;
var dependenciesLoaded = false;
var $ = null;
if(! window.console )
{
// support console.log on old IE versions, if it doesn't exist
require.ensure(['console-shim'], function(require) {
require('console-shim');
});
}
/* loadDeps() : use webpack lazy loading to load the dependencies of
* lisTours only if a tour is requested or tour in progress.
*/
this.loadDeps = function(cb) {
require.ensure(['jquery',
'!style!css!../css/bootstrap-tour-standalone.min.css',
'!style!css!../css/lis-tours.css',
'./bootstrap-tour-loader.js',
'./tours/index.js'],
function(require) {
// JQuery: load our version of jquery and stash it in a global
// var, taking care not to conflict with existing, older, jquery,
// e.g. drupal7 requires jquery 1.4.4 (Bootstrap Tours requires
// jquery Deferred/Promise classes)
$ = window.__jquery = require('jquery').noConflict(true);
// load the bootstrap tours css
require('!style!css!../css/bootstrap-tour-standalone.min.css');
require('!style!css!../css/lis-tours.css');
// load a customized bootstrap tour js (consumes our __jquery version)
require('./bootstrap-tour-loader.js');
// load tour definitions
require('./tours/index.js');
// callback fn
cb.call(that);
});
};
/* go() : force a tour to start at step 0.
*/
this.go = function(tourId) {
that.loadDeps(function() {
var tour = that.tours[tourId];
if(! tour) {
localStorage.removeItem(TOUR_ID_KEY);
throw 'failed to load tour id: ' + tourId;
}
tour.init();
tour.end();
tour.restart();
localStorage[TOUR_ID_KEY] = tourId;
});
};
/* resume() : restore a tour at whatever step bootstrap tour has
* retained state.
*/
this.resume = function(tourId) {
that.loadDeps(function() {
var tour = that.tours[tourId];
if(! tour) {
localStorage.removeItem(TOUR_ID_KEY);
throw 'failed to load tour id: ' + tourId;
}
tour.init();
if(tour.ended()) {
//console.log('removing tour id: ' + tourId) ;
localStorage.removeItem(TOUR_ID_KEY);
}
else {
var force = true;
tour.start(force);
}
})
};
this.tours = {};
/* register() : each tour object must register, so we can lookup the
* tour object by it's tag name.
*/
this.register = function(tour) {
var name = tour._options.name;
that.tours[name] = tour;
};
this.waitForContent = function(tour, cb) {
var promise = new $.Deferred();
var elapsed = 0;
function waiter() {
var res = cb();
if(res) {
promise.resolve();
return;
}
else {
elapsed += MS;
if(elapsed >= MAX_MS) {
tour.end();
throw 'error: dynamic content timeout ' + elapsed + ' ms : ' + cb;
}
//console.log('waiting for dynamic content from callback ' + cb);
setTimeout(waiter, MS);
}
}
setTimeout(waiter, MS);
return promise;
};
/* init() : lookup the most recent tour id, and load it's module, to
* enable tour to resume automatically.
*/
this.init = function() {
var tourId = localStorage.getItem(TOUR_ID_KEY);
if(tourId) {
that.resume(tourId);
}
};
if('jQuery' in window) {
jQuery('document').ready(that.init);
}
else {
// lazy load our jquery, if there is not one already.
require.ensure(['jquery'], function(require) {
window.__jquery = require('jquery').noConflict(true);
window.__jquery('document').ready(that.init);
});
}
}.call(lisTours));
// make the lisTours library available globally
module.exports = lisTours;
window.lisTours = lisTours;
//console.log('lisTours loaded');
|
JavaScript
| 0.000001 |
@@ -10,18 +10,17 @@
ct%22;%0A%0A/*
-
%0A
+
* lisT
@@ -396,19 +396,17 @@
= null;%0A
-
%0A
+
if(! w
@@ -491,20 +491,16 @@
't exist
-
%0A req
@@ -1653,19 +1653,17 @@
);%0A %7D;%0A
-
%0A
+
/* go(
@@ -2784,19 +2784,17 @@
r;%0A %7D;%0A
-
%0A
+
this.w
@@ -3287,21 +3287,17 @@
e;%0A %7D;%0A
-
%0A
+
/* ini
@@ -3542,19 +3542,17 @@
%7D%0A %7D;%0A%0A
-
%0A
+
if('jQ
@@ -3577,33 +3577,32 @@
%0A jQuery(
-'
document
').ready(tha
@@ -3581,33 +3581,32 @@
jQuery(document
-'
).ready(that.ini
@@ -3790,22 +3790,16 @@
t(true);
-
%0A w
@@ -3817,17 +3817,16 @@
ery(
-'
document
').r
@@ -3821,17 +3821,16 @@
document
-'
).ready(
@@ -3857,11 +3857,9 @@
%7D%0A
-
%0A
+
%7D.ca
@@ -3977,16 +3977,16 @@
sTours;%0A
+
//consol
@@ -4011,9 +4011,8 @@
aded');%0A
-%0A
|
e15f5374c59598c01b4c4102662e1cce5a9f18b4
|
Test fetchnuti useru z meho API #9.2
|
fb_setup.js
|
fb_setup.js
|
var isLoggedIn = false;
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
loginUserIntoApplication();
document.getElementById('login_btn').style = "display: none";
document.getElementById('logout_btn').style = "display: block";
if(somePlaceIsSelected){
document.getElementById('actions').style = "visibility: visible";
}
isLoggedIn = true;
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
document.getElementById('login_btn').style = "display: block";
document.getElementById('logout_btn').style = "display: none";
document.getElementById('actions').style = "visibility: hidden";
isLoggedIn = false;
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Přihlašte se pomocí Facebooku.';
document.getElementById('login_btn').style = "display: block";
document.getElementById('logout_btn').style = "display: none";
document.getElementById('actions').style = "visibility: hidden";
isLoggedIn = false;
}
}
function subscribeToEvents() {
FB.Event.subscribe('auth.logout', logout_event);
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '177757152673157',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.5' // use graph api version 2.5
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function loginUserIntoApplication() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me',{ fields: 'name, email' }, function(response) {
console.log('Successful login for: ' + response.name + " "+response.email);
makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (responseText) {
var alreadyExists = false;
if(responseText){
var users = JSON.parse(responseText);
for (id in users){
if(users[id].email == response.email){
alreadyExists = true;
break;
};
}
}
if(!alreadyExists){
var data = "name="+response.name+"&email="+response.email;
makeCorsRequest("POST", "https://ivebeenthereapi-matyapav.rhcloud.com/users", data, function (responseText) {
console.log(responseText);
})
}
});
document.getElementById('status').innerHTML =
'Přihlášen jako, ' + response.name + '!';
});
}
function fblogin()
{
FB.login(function (response) {
if (response.authResponse) {
checkLoginState();
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
var logout_event = function(response) {
console.log("logout_event");
console.log(response.status);
console.log(response);
checkLoginState();
}
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Make the actual CORS request.
function makeCorsRequest(method, url, data, callback) {
// This is a sample server that supports CORS.
var xhr = createCORSRequest(method, url);
if (!xhr) {
alert('CORS not supported');
return null;
}
// Response handlers.
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
return null;
};
if(data && method == "POST"){
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data)
}else{
xhr.send();
}
}
|
JavaScript
| 0 |
@@ -4386,32 +4386,43 @@
console.log(
+JSON.parse(
responseText);%0A
@@ -4410,32 +4410,41 @@
se(responseText)
+.message)
;%0A
|
5fbf3d791e5df4cad73a4b3aa647bb8028b33aa0
|
Update Component split lazy loading
|
src/main.js
|
src/main.js
|
import Vue from './Vue'
import App from './App'
import About from './components/Aboutme'
import Profile from './components/Profile'
import Contact from './components/Contact'
import Products from './components/ProductList'
import NotFoundComponent from './NotFound'
import store from './store'
import VueRouter from 'vue-router'
const router = new VueRouter({
mode: 'history',
root: '/',
routes: [
{path: '/contact', component: Contact},
{path: '/about', component: About},
{path: '/profile/:username', component: Profile},
{path: '/products', component: Products},
{path: '/', redirect: '/about'},
{path: '*', component: NotFoundComponent}
]
})
Vue.use(VueRouter)
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
render: h => h(App),
router
})
|
JavaScript
| 0.000001 |
@@ -52,281 +52,599 @@
ort
-About from './components/Aboutme'%0Aimport Profile from './components/Profile'%0Aimport Contact from './components/Contact'%0Aimport Products from './components/ProductList'%0Aimport NotFoundComponent from './NotFound'%0Aimport store from './store'%0Aimport VueRouter from 'vue-router'
+store from './store'%0Aimport VueRouter from 'vue-router'%0A%0A// Component split lazy loading%0Aconst About = resolve =%3E %7B%0A // require.ensure is Webpack's special syntax for a code-split point.%0A require.ensure(%5B'./components/Aboutme.vue'%5D, () =%3E %7B%0A resolve(require('./components/Aboutme.vue'))%0A %7D)%0A%7D%0A%0Aconst Profile = resolve =%3E require(%5B'./components/Profile.vue'%5D, resolve)%0Aconst Contact = resolve =%3E require(%5B'./components/Contact.vue'%5D, resolve)%0Aconst Products = resolve =%3E require(%5B'./components/ProductList.vue'%5D, resolve)%0Aconst NotFound = resolve =%3E require(%5B'./NotFound.vue'%5D, resolve)
%0A%0Aco
@@ -972,25 +972,16 @@
NotFound
-Component
%7D%0A %5D%0A%7D)
|
d4ee13ddb2ecd79b1f709042585fa1b1415e8cbb
|
Update loader.js
|
js/loader.js
|
js/loader.js
|
/**
* CJ Ramki
* Access the CJ Ramki contents from JavaScript side.
*
* Copyright (c) 2014 CJ Ramki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* */
function loadFeed(url, element, num = null) {
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed(url);
if (num !== null) {
feed.includeHistoricalEntries();
feed.setNumEntries(num);
}
feed.load(function (result) {
if (!result.error) {
var container = document.getElementById(element);
//Feed title Section
var feedTitle = document.createElement('h2');
//use ".feed_title" in css to style Title of the Feed
feedTitle.class = 'feed_title';
feedTitle.innerHTML = result.feed.title;
container.appendChild(feedTitle);
//Feed Entries section
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var post = document.createElement('h3');
var postTitle = document.createElement("a");
postTitle.class = 'post_title';
//use ".post_title" in css to style Title of the Post
postTitle.href = entry.link;
postTitle.appendChild(document.createTextNode(entry.title));
post.appendChild(postTitle);
//Feed Content Snippet section
var content = document.createElement('div');
//use ".post_content" in css to style Title of the Post
content.class = 'post_content';
content.innerHTML = entry.contentSnippet;
container.appendChild(post);
container.appendChild(content);
}
}
});
}
google.setOnLoadCallback(initialize);
}
|
JavaScript
| 0 |
@@ -1193,28 +1193,51 @@
, num = null
+, enableContent = false
) %7B%0A
-
google.l
@@ -1786,24 +1786,28 @@
dTitle.class
+Name
= 'feed_tit
@@ -2089,69 +2089,8 @@
i%5D;%0A
- var post = document.createElement('h3');%0A
@@ -2154,60 +2154,8 @@
%22);%0A
- postTitle.class = 'post_title';%0A
@@ -2217,32 +2217,88 @@
tle of the Post%0A
+ postTitle.className = 'post_title';%0A
@@ -2439,34 +2439,194 @@
post
-.appendChild(postTitle);%0A%0A
+Title.appendChild(document.createElement('br'));%0A container.appendChild(postTitle);%0A //alert(content);%0A if (enableContent) %7B%0A
@@ -2664,32 +2664,36 @@
Snippet section%0A
+
@@ -2737,24 +2737,28 @@
ent('div');%0A
+
@@ -2834,32 +2834,36 @@
+
content.class =
@@ -2859,16 +2859,20 @@
nt.class
+Name
= 'post
@@ -2882,16 +2882,20 @@
ntent';%0A
+
@@ -2960,32 +2960,36 @@
+
+
container.append
@@ -2994,19 +2994,22 @@
ndChild(
-pos
+conten
t);%0A
@@ -3028,39 +3028,9 @@
-container.appendChild(content);
+%7D
%0A
|
af63f4098f5d0c58deb0523d9baafdc2fdf80927
|
Improve logger.
|
js/logger.js
|
js/logger.js
|
/* global console */
/* exported Log */
/* Magic Mirror
* Logger
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
// This logger is very simple, but needs to be extended.
// This system can eventually be used to push the log messages to an external target.
var Log = (function() {
return {
info: function(message) {
console.info(message);
},
log: function(message) {
console.log(message);
},
error: function(message) {
console.error(message);
},
warn: function(message) {
console.warn(message);
},
group: function(message) {
console.group(message);
},
groupCollapsed: function(message) {
console.groupCollapsed(message);
},
groupEnd: function() {
console.groupEnd();
},
time: function(message) {
console.time(message);
},
timeEnd: function(message) {
console.timeEnd(message);
},
timeStamp: function(message) {
console.timeStamp(message);
}
};
})();
|
JavaScript
| 0.000001 |
@@ -315,39 +315,32 @@
%09info: function(
-message
) %7B%0A%09%09%09console.i
@@ -342,24 +342,38 @@
ole.info
-(message
+.apply(this, arguments
);%0A%09%09%7D,%0A
@@ -380,39 +380,32 @@
%09%09log: function(
-message
) %7B%0A%09%09%09console.l
@@ -406,24 +406,38 @@
sole.log
-(message
+.apply(this, arguments
);%0A%09%09%7D,%0A
@@ -446,39 +446,32 @@
error: function(
-message
) %7B%0A%09%09%09console.e
@@ -474,24 +474,38 @@
le.error
-(message
+.apply(this, arguments
);%0A%09%09%7D,%0A
@@ -513,39 +513,32 @@
%09warn: function(
-message
) %7B%0A%09%09%09console.w
@@ -540,24 +540,38 @@
ole.warn
-(message
+.apply(this, arguments
);%09%0A%09%09%7D,
@@ -581,39 +581,32 @@
group: function(
-message
) %7B%0A%09%09%09console.g
@@ -609,24 +609,38 @@
le.group
-(message
+.apply(this, arguments
);%09%0A%09%09%7D,
@@ -659,39 +659,32 @@
apsed: function(
-message
) %7B%0A%09%09%09console.g
@@ -696,24 +696,38 @@
ollapsed
-(message
+.apply(this, arguments
);%0A%09%09%7D,%0A
@@ -788,39 +788,32 @@
%09time: function(
-message
) %7B%0A%09%09%09console.t
@@ -815,24 +815,38 @@
ole.time
-(message
+.apply(this, arguments
);%0A%09%09%7D,%0A
@@ -857,39 +857,32 @@
meEnd: function(
-message
) %7B%0A%09%09%09console.t
@@ -887,24 +887,38 @@
.timeEnd
-(message
+.apply(this, arguments
);%0A%09%09%7D,%0A
@@ -939,23 +939,16 @@
unction(
-message
) %7B%0A%09%09%09c
@@ -967,16 +967,30 @@
tamp
-(message
+.apply(this, arguments
);%0A%09
|
bf034b805df72c309437c1acab9f6ae408bf34ec
|
disable xml linter
|
gulpfile.js
|
gulpfile.js
|
/*
* sublime-gulpfile.js
*
* Copyright (c) 2017 Jan T. Sott
* Licensed under the MIT license.
*/
// Dependencies
const gulp = require('gulp');
const debug = require('gulp-debug');
const jsonLint = require('gulp-jsonlint');
const xmlVal = require('gulp-xml-validator');
const ymlVal = require('gulp-yaml-validate');
// Supported files
const jsFiles = [
'lib/*.js',
'src/*.js',
];
const jsonFiles = [
'!node_modules/**/*',
'**/*.JSON-sublime-syntax',
'**/*.JSON-tmLanguage',
'**/*.JSON-tmTheme',
'**/*.sublime-build',
'**/*.sublime-commands',
'**/*.sublime-completions',
'**/*.sublime-keymap',
'**/*.sublime-macro',
'**/*.sublime-menu',
'**/*.sublime-settings',
'**/*.sublime-theme',
'messages.json'
];
const xmlFiles = [
'!node_modules/**/*',
'**/*.plist',
'**/*.PLIST-sublime-syntax',
'**/*.PLIST-tmLanguage',
'**/*.PLIST-tmTheme',
'**/*.sublime-snippet',
'**/*.tmCommand',
'**/*.tmLanguage',
'**/*.tmPreferences',
'**/*.tmSnippet',
'**/*.tmTheme',
'**/*.xml'
];
const ymlFiles = [
'!node_modules/**/*',
'**/*.sublime-syntax',
'**/*.YAML-tmLanguage',
'**/*.YAML-tmTheme'
];
// Available tasks
gulp.task('lint', ['lint:json', 'lint:xml', 'lint:yml']);
// Lint JSON
gulp.task('lint:json', function(){
return gulp.src(jsonFiles)
.pipe(debug({title: 'json-lint'}))
.pipe(jsonLint())
.pipe(jsonLint.failAfterError())
.pipe(jsonLint.reporter());
});
// Validate XML
gulp.task('lint:xml', function() {
return gulp.src(xmlFiles)
.pipe(debug({title: 'xml-validator'}))
.pipe(xmlVal());
});
// Validate YAML
gulp.task('lint:yml', function() {
return gulp.src(ymlFiles)
.pipe(debug({title: 'yml-validator'}))
.pipe(ymlVal());
});
|
JavaScript
| 0.000001 |
@@ -1248,20 +1248,8 @@
on',
- 'lint:xml',
'li
|
e5b23ebd27a5f364533845ecc7e99d9cdc6c93d7
|
add request timeout
|
src/js/services/jsonrpc.js
|
src/js/services/jsonrpc.js
|
'use strict';
module.exports = function(app) {
app.factory('jsonrpc', ['$http', '$q', function($http, $q) {
var jsonrpc = {};
var call = function(session, object, method, args) {
var deferred = $q.defer();
$http.post(jsonrpc.apiUrl, {
jsonrpc: '2.0',
id: 1,
method: 'call',
params: [session, object, method, args]
})
.success(function(data) {
if (data.error) {
return deferred.reject('JSON RPC Error: ' + data.error.message +
' (code ' + data.error.code + ')');
}
deferred.resolve(data.result[1]);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
};
jsonrpc.login = function(apiUrl, username, password) {
jsonrpc.apiUrl = apiUrl;
return call('00000000000000000000000000000000', 'session', 'login',
{'username': 'root', 'password': 'doener', 'timeout': 3600})
.then(function(data) {
jsonrpc.session = data.ubus_rpc_session;
});
};
jsonrpc.call = function(object, method, args) {
return call(jsonrpc.session, object, method, args);
};
return jsonrpc;
}]);
};
|
JavaScript
| 0.000001 |
@@ -363,16 +363,49 @@
, args%5D%0A
+ %7D, %7B%0A timeout: 1000%0A
%7D)
@@ -1004,16 +1004,16 @@
d':
-'doener'
+password
, 't
|
1a5d72aa08d57b97086b24d78e1db28acb7f0147
|
Use spaceUnoccupied() when adding pieces to board
|
lib/board.js
|
lib/board.js
|
var TwoDimensionalFixedArray = require('./two_dementional_fixed_array.js');
var _ = require('lodash');
var np = require('named-parameters');
module.exports = function(args) {
parsedArgs = np.parse(args).
require('army1').
require('army2').
values();
var rowCount = 8;
var colCount = 8;
var spaces = new TwoDimensionalFixedArray({ rowCount: rowCount, colCount: colCount });
var armyData = [];
armyData.push({
army: parsedArgs.army1,
activePieces: []
});
armyData.push({
army: parsedArgs.army2,
activePieces: []
});
return {
rowCount: rowCount,
colCount: colCount,
bounds: bounds,
addPiece: addPiece,
couldTake: couldTake,
canMoveIntoSpace: canMoveIntoSpace,
activePieces: activePieces,
location: location
};
function addPiece(args) {
parsedArgs = np.parse(args).
require('piece').
require('location').
values();
var piece = parsedArgs.piece;
var location = parsedArgs.location;
existing_piece = spaces.get({ location: location });
if (existing_piece === undefined) {
addToActivePieces(piece);
spaces.set({ item: piece, location: location });
} else {
throw('space taken');
}
}
function bounds() {
return {
minRow: 0,
maxRow: colCount - 1,
minCol: 0,
maxCol: colCount - 1
};
}
function couldTake(args) {
var parsedArgs = np.parse(args).
require('location').
require('piece').
values();
var location = parsedArgs.location;
targetPiece = spaces.get({ location: location });
return parsedArgs.piece.army !== targetPiece.army;
}
function canMoveIntoSpace(args) {
var parsedArgs = np.parse(args).
require('location', 'object').
require('piece', 'object').
values();
var location = parsedArgs.location;
return spaceUnoccupied(location);
}
function spaceUnoccupied(location){
return spaces.get({ location: location }) === undefined;
}
function dataFor(army) {
data = _.find(armyData, function(data) {
return data.army === army;
});
if(data) {
return data;
} else {
throw('data not found');
}
}
function addToActivePieces(piece) {
dataFor(piece.army).activePieces.push(piece);
}
function location(piece) {
return spaces.find(piece);
}
function activePieces(args) {
parsedArgs = np.parse(args).
require('army').
values();
return _.clone(dataFor(parsedArgs.army).activePieces);
}
};
|
JavaScript
| 0.000001 |
@@ -1001,98 +1001,37 @@
-existing_piece = spaces.get(%7B location: location %7D);%0A%0A if (existing_piece === undefined
+if (spaceUnoccupied(location)
) %7B%0A
|
84ba33d502f5269616295a0b1d66291d901595e7
|
Update gulpfile
|
gulpfile.js
|
gulpfile.js
|
JavaScript
| 0 |
@@ -0,0 +1,1100 @@
+var gulp = require('gulp');%0Avar sass = require('gulp-sass');%0Avar sasslint = require('gulp-sass-lint');%0Avar sourcemaps = require('gulp-sourcemaps');%0Avar rename = require('gulp-rename');%0Avar header = require('gulp-header');%0A%0Avar pkg = require('./package.json');%0Avar banner = '/*! %3C%25= pkg.name %25%3E: v.%3C%25= pkg.version %25%3E, last updated on: %3C%25= new Date() %25%3E */%5Cn';%0A%0A///////////////////////////////////%0A// Build Tasks%0A///////////////////////////////////%0A%0A%0A%0A%0A%0A///////////////////////////////////%0A// Development Tasks%0A///////////////////////////////////%0A%0Agulp.task('styles:dev', function() %7B%0A return gulp.src('./scss/**/*.s+(a%7Cc)ss')%0A .pipe(sasslint(%7BconfigFile: '.ubs-sass-lint.yml'%7D)) %0A .pipe(sasslint.format())%0A .pipe(sasslint.failOnError(false)) %0A .pipe(sourcemaps.init()) %0A .pipe(sass(%7BoutputStyle: 'expanded'%7D))%0A //.pipe(rename(%7Bextname: '.dev.css'%7D))%0A .pipe(header(banner, %7Bpkg : pkg%7D))%0A .pipe(sourcemaps.write('.')) %0A .pipe(gulp.dest('./css'))%0A .pipe(notify(notifyMsg));%0A%7D);%0A%0Agulp.task('default', %5B'styles:dev'%5D);
|
|
02ad4da8633ae84d6ca2e3f8223af3793bec48d3
|
Update Sites.js
|
js/Sites.js
|
js/Sites.js
|
function Button(name, url, type, img) {
document.write('<a class="oldbutton" href="http://' + url + '">' + name + '<br>');
document.write('<small class="extra2">' + type + '</small><br>');
document.write('<img src="http://' + img + '" alt="' + name + '" width="90" height="90">');
document.write('</a> ');
}
function NedGames() {
Button("NedGames", "games.nedhome.ml", "NedGames", "nedhome.ml/imgs/games.png");
}
function B(name, url, type, img) {
Button(name, url, type, img);
}
function NedTool(name, url, img) {
Button(name, url, "NedTool", img)
}
function OutherSite(name, url, img) {
Button(name, url, "Outher Site", img)
}
function SocialMedia(name, url, img) {
Button(name, url, "Social Media", img);
}
function NewLine(type) {
if(type == "p") {
document.write("</p>")
} else if(type == "br") {
document.write("<br>")
}
}
|
JavaScript
| 0.000001 |
@@ -269,18 +269,18 @@
width=%22
-90
+88
%22 height
@@ -285,10 +285,10 @@
ht=%22
-90
+75
%22%3E')
|
b8521aa87683b4f575c5be8b9606008d6ec0e8ef
|
Use lumber opts for check.
|
js/lumber.js
|
js/lumber.js
|
/*
LUMBER.js
Crafted with <3 by John Otander(@4lpine).
MIT Licensed
*/
function hasLumberDependencies() {
return "d3" in window &&
"addEventListener" in window &&
"querySelector" in document &&
Array.prototype.forEach
}
var lumber = {}
/*
getGraphs
Select all the DOM elements with the class '.lumber'.
Returns:
Array of all DOM elements with the class '.lumber'.
*/
lumber.getGraphs = lumber_getGraphs;
function lumber_getGraphs() {
return document.querySelectorAll(".lumber");
}
lumber.graph = lumber_graph;
function lumber_graph(chartDiv) {
chartDiv = d3.select(chartDiv);
lumberOpts = {}
lumberOpts.data = chartDiv.attr("data-lumber-values").split(",");
lumberOpts.width = chartDiv.attr("data-lumber-width") || 500;
lumberOpts.height = chartDiv.attr("data-lumber-height") || 250;
lumberOpts.type = chartDiv.attr("data-lumber-type") || "bar";
lumberOpts.yAxis = chartDiv.attr("data-lumber-y-axis-label") || "Y Axis";
lumberOpts.xAxis = chartDiv.attr("data-lumber-x-axis-label") || "X Axis";
if (lumber.type == "bar") { lumber.barChart(chartDiv, lumberOpts); }
else if (lumber.type == "pie") { lumber.pieChart(chartDiv, lumberOpts); }
else if (lumber.type == "line") { lumber.lineChart(chartDiv, lumberOpts); }
else if (lumber.type == "histogram") { lumber.histogram(chartDiv, lumberOpts); }
else if (lumber.type == "scatterplot") { lumber.scatterplot(chartDiv, lumberOpts); }
}
/*
barChart
Create a lovely bar chart that is so beautiful no one will even care what
the data even means.
This will use the lumberOpts parameter to create a bar chart within the
chartDiv. The chartDiv is assumed to be an svg DOM element.
Params:
chartDiv = string for selection, for example "#chart" or ".lumber-chart"
lumberOpts = options hash of information for creating the chart.
Requirements (as keys in lumberOpts):
type = Specified by the lumber-type data attribute
data = The data is expected to be a data attribute with the form:
'x1:y1,x2:y2,...,xn:yn'
yAxis = Utilizes the lumber-y-axis-label data attribute
xAxis = Utilizes the lumber-x-axis-label data attribute
width = Specified by the lumber-width data attribute
height = Specified by the lumber-height data attribute
*/
lumber.barChart = lumber_barChart;
function lumber_barChart(chartDiv, lumberOpts) {
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = lumberOpts.width - margin.left - margin.right,
height = lumberOpts.height - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left").ticks(2, "%");
x.domain(lumberOpts.data.map(function(d) { return d; }))
y.domain([0, d3.max(lumberOpts.data, function(d) { return d; })])
var chart = chartDiv
.attr("width", lumberOpts.width)
.attr("height", lumberOpts.height)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("y", 30)
.attr("x", margin.left - 6)
.attr("dx", ".71em")
.style("text-anchor", "end")
.text(lumberOpts.xAxis);
chart.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text(lumberOpts.yAxis);
chart.selectAll(".bar")
.data(lumberOpts.data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d); })
.attr("y", function(d) { return y(d); })
.attr("height", function(d) { return height - y(d); })
.attr("width", x.rangeBand());
}
lumber.pieChart = lumber_pieChart;
function lumber_pieChart(chartDiv, lumberOpts) {
// ...
}
lumber.lineChart = lumber_lineChart;
function lumber_lineChart(chartDiv, lumberOpts) {
// ...
}
lumber.histogram = lumber_histogram;
function lumber_histogram(chartDiv, lumberOpts) {
// ...
}
lumber.scatterplot = lumber_scatterplot;
function lumber_scatterplot(chartDiv, lumberOpts) {
// ...
}
function type(d) {
d.value = +d.value; // coerce to number
return d;
}
if (!hasLumberDependencies()) {
console.log("Missing dependencies for lumber.js.");
}
|
JavaScript
| 0 |
@@ -1082,32 +1082,36 @@
%22;%0A%0A if (lumber
+Opts
.type == %22bar%22)
@@ -1178,32 +1178,36 @@
else if (lumber
+Opts
.type == %22pie%22)
@@ -1269,32 +1269,36 @@
else if (lumber
+Opts
.type == %22line%22)
@@ -1360,32 +1360,36 @@
else if (lumber
+Opts
.type == %22histog
@@ -1459,16 +1459,20 @@
(lumber
+Opts
.type ==
|
00510c5c99a00660f822281103d92596f68a8929
|
Fix empty body
|
lib/middleware/apiGatewayProxyRest/lib/request.js
|
lib/middleware/apiGatewayProxyRest/lib/request.js
|
const { DEFAULT } = require("./constant.js");
const Headers = require("./headers.js");
class Request {
constructor(event, context) {
this.method = event.httpMethod;
this.version = DEFAULT;
if (event.queryStringParameters && (event.queryStringParameters.v || event.queryStringParameters.version)) {
if (event.queryStringParameters.v) {
this.version = event.queryStringParameters.v;
} else {
this.version = event.queryStringParameters.version;
}
}
this.path = event.path;
this.headers = new Headers(event.headers);
this.body = null;
if (event.body) {
this.body = JSON.parse(event.body);
}
this.parameters = {};
if (event.queryStringParameters) {
this.parameters = event.queryStringParameters;
}
this.user = null;
if (event.requestContext && event.requestContext.authorizer && Object.keys(event.requestContext.authorizer).length > 0) {
this.user = Object.assign({}, event.requestContext.authorizer);
}
if (event.requestContext && event.requestContext.requestId) {
this.requestId = event.requestContext.requestId;
}
if (event.requestContext && event.requestContext.identity && event.requestContext.identity.caller) {
if (this.user === null) {
this.user = {};
}
this.user.caller = event.requestContext.identity.caller;
}
if (event.requestContext && event.requestContext.identity && event.requestContext.identity.userArn) {
if (this.user === null) {
this.user = {};
}
this.user.userArn = event.requestContext.identity.userArn;
}
if (event.requestContext && event.requestContext.identity && event.requestContext.identity.user) {
if (this.user === null) {
this.user = {};
}
this.user.user = event.requestContext.identity.user;
}
this._route = null;
this.originalEvent = event;
this.context = context;
}
set route(route) {
this._route = route;
Object.assign(this.parameters, route.parameters);
return this;
}
get route() {
return this._route;
}
}
module.exports = Request;
|
JavaScript
| 0.999853 |
@@ -647,20 +647,18 @@
.body =
-null
+%7B%7D
;%0A
|
9e6487d08ac96ecd0ccdebb4b6d8051b4fc062fb
|
handle error when test server is already running
|
gulpfile.js
|
gulpfile.js
|
// TODO: add more test specs (see matchHeight.spec.js)
// TODO: travis CI
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var header = require('gulp-header');
var eslint = require('gulp-eslint');
var gulpBump = require('gulp-bump');
var changelog = require('gulp-conventional-changelog');
var tag = require('gulp-tag-version');
var sequence = require('run-sequence');
var replace = require('gulp-replace');
var webdriver = require('gulp-webdriver');
var webserver = require('gulp-webserver');
var selenium = require('selenium-standalone');
var browserStack = require('gulp-browserstack');
var staticTransform = require('connect-static-transform');
var privateConfig = require('./test/conf/private.conf.js').config;
var pkg = require('./package.json');
var server;
gulp.task('release', function(callback) {
var type = process.argv[4] || 'minor';
sequence('lint', 'test', 'build', 'bump:' + type, 'changelog', 'tag', callback);
});
gulp.task('build', function() {
return gulp.src(pkg.main)
.pipe(replace("version = 'master'", "version = '" + pkg.version + "'"))
.pipe(uglify())
.pipe(header(banner, { pkg: pkg }))
.pipe(rename({ suffix: '-min' }))
.pipe(gulp.dest('.'));
});
gulp.task('lint', function() {
return gulp.src(pkg.main)
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
var bump = function(options) {
return gulp.src(['package.json', 'bower.json'])
.pipe(gulpBump(options))
.pipe(gulp.dest('.'));
};
gulp.task('bump:patch', function() {
return bump({ type: 'patch' });
});
gulp.task('bump:minor', function() {
return bump({ type: 'minor' });
});
gulp.task('bump:major', function() {
return bump({ type: 'major' });
});
gulp.task('tag', function() {
return gulp.src('package.json')
.pipe(tag({ prefix: '' }));
});
gulp.task('changelog', function () {
return gulp.src('CHANGELOG.md')
.pipe(changelog())
.pipe(gulp.dest('.'));
});
gulp.task('serve', function() {
server = gulp.src('.')
.pipe(webserver({
host: '0.0.0.0',
//livereload: true,
directoryListing: true,
middleware: function(req, res, next) {
var ieMode = (req._parsedUrl.query || '').replace('=','');
if (ieMode in emulateIEMiddleware) {
emulateIEMiddleware[ieMode](req, res, next);
} else {
next();
}
}
}));
});
gulp.task('selenium', function(done) {
console.log('Setting up Selenium server...');
selenium.install({
logger: function(message) { console.log(message); }
}, function(err) {
if (err) {
done(err);
return;
}
console.log('Starting Selenium server...');
selenium.start(function(err, child) {
console.log('Selenium server started');
selenium.child = child;
done(err);
});
});
});
gulp.task('test', ['serve', 'selenium'], function(done) {
var error;
console.log('Starting webdriver...');
var finish = function(err) {
console.log('Webdriver stopped');
selenium.child.kill();
console.log('Selenium server stopped');
if (server) {
try {
server.emit('kill');
} catch(e) {}
console.log('Web server stopped');
}
done(error || err);
};
gulp.src('test/conf/local.conf.js')
.pipe(webdriver())
.on('error', function(err) { error = err; })
.on('finish', finish);
});
gulp.task('test:cloud', ['serve'], function(done) {
gulp.src('test/conf/cloud.conf.js')
.pipe(browserStack.startTunnel({
key: privateConfig.key,
hosts: [{
name: 'localhost',
port: 8000,
sslFlag: 0
}]
}))
.pipe(webdriver())
.pipe(browserStack.stopTunnel())
.on('finish', function(err) {
if (server) {
try {
server.emit('kill');
} catch(e) {}
console.log('Web server stopped');
}
done(err);
});
});
gulp.task('test:cloud:all', function(done) {
return gulp
.src('test/conf/cloud-all.conf.js')
.pipe(browserStack.startTunnel({
key: privateConfig.key,
hosts: [{
name: 'localhost',
port: 8000,
sslFlag: 0
}]
}))
.pipe(webdriver())
.pipe(browserStack.stopTunnel());
});
var banner = [
'/*',
'* <%= pkg.name %> v<%= pkg.version %> by @liabru',
'* <%= pkg.homepage %>',
'* License <%= pkg.license %>',
'*/',
''
].join('\n');
var emulateIEMiddlewareFactory = function(version) {
return staticTransform({
root: __dirname,
match: /(.+)\.html/,
transform: function (path, text, send) {
send(text.replace('content="IE=edge,chrome=1"', 'content="IE=' + version + '"'));
}
});
};
var emulateIEMiddleware = {
'ie8': emulateIEMiddlewareFactory(8),
'ie9': emulateIEMiddlewareFactory(9),
'ie10': emulateIEMiddlewareFactory(10)
};
|
JavaScript
| 0 |
@@ -2093,24 +2093,223 @@
unction() %7B%0A
+ process.on('uncaughtException', function(err) %7B%0A if (err.errno === 'EADDRINUSE') %7B%0A console.log('Server already running (or port is otherwise in use)');%0A %7D%0A %7D); %0A%0A
server =
|
b9627f7677558bdaa9f3d7821971385395da6153
|
remove useless log
|
controller/express/api/script/run.js
|
controller/express/api/script/run.js
|
'use strict';
const express = require("express");
const router = express.Router();
const fs = require('fs');
const path = require('path');
router.post("/", function (req, res) {
let {thread} = req.modules;
let {name, lib} = req.body;
if (!name) return res.send({err: new Error('not defined name')});
const WORKSPACE_PATH = req.DIR.WORKSPACE_PATH;
const TMP_PATH = path.resolve(WORKSPACE_PATH, `${name}.satbook`);
let args = req.body;
args.WORKSPACE_PATH = WORKSPACE_PATH;
args.TMP_PATH = TMP_PATH;
req.saturn.workspace.save(args)
.then(()=> {
if (!thread.log[name]) thread.log[name] = [];
thread.log[name].push({module: `${name}`, status: `data`, msg: `installing dependencies...`});
thread.status[name] = true;
lib = JSON.parse(lib);
let npmlibs = ['flowpipe'];
let npms = lib.value.match(/require\([^\)]+\)/gim);
for (let i = 0; i < npms.length; i++) {
npms[i] = npms[i].replace(/ /gim, '');
npms[i] = npms[i].replace(/\n/gim, '');
npms[i] = npms[i].replace(/\t/gim, '');
npms[i] = npms[i].replace("require('", '');
npms[i] = npms[i].replace("')", '');
let exists = true;
try {
require(npms[i]);
} catch (e) {
exists = false;
}
let list = fs.readdirSync(path.resolve(__dirname, '..', '..', '..', 'node_modules'));
for (let j = 0; j < list.length; j++)
if (list[j] == npms[i])
exists = false;
if (fs.existsSync(path.resolve(WORKSPACE_PATH, npms[i]))) {
exists = true;
}
if (fs.existsSync(path.resolve(WORKSPACE_PATH, 'node_modules'))) {
list = fs.readdirSync(path.resolve(WORKSPACE_PATH, 'node_modules'));
for (let j = 0; j < list.length; j++)
if (list[j] == npms[i])
exists = true;
}
if (!exists)
npmlibs.push(npms[i]);
}
console.log(npmlibs);
return thread.install(npmlibs, WORKSPACE_PATH);
}).then(()=> {
thread.log[name].push({module: `${name}`, status: `data`, msg: `installed dependencies...`});
thread.status[name] = false;
return thread.run(name);
})
.then(()=> {
res.send({status: true});
});
});
module.exports = router;
|
JavaScript
| 0.000002 |
@@ -2246,42 +2246,8 @@
%7D%0A%0A
- console.log(npmlibs);%0A
|
7737214f3979f7b0807d09a9ddbe7837a1589304
|
Fix `gulp clean`
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var del = require('del');
var gulp = require('gulp-help')(require('gulp'));
var babel = require('gulp-babel');
// `gulp build`
// -----------------------------------------------------------------------------
gulp.task('build',
'Compile everything.',
['scripts']
);
// `gulp scripts`
// -----------------------------------------------------------------------------
var scripts = {
source: 'source/**/*.js',
target: '.'
};
gulp.task('scripts',
'Compile scripts to ES5.',
['scripts:clean'],
function() {
return gulp.src(scripts.source)
.pipe(babel())
.pipe(gulp.dest(scripts.target))
;
}
);
gulp.task('scripts:clean', false, function(done) {
del(scripts.target + '/*.{js,js.map}', done);
});
// `gulp clean`
// -----------------------------------------------------------------------------
gulp.task('clean',
'Remove all built files.',
['scripts:clean']
);
|
JavaScript
| 0.000001 |
@@ -694,16 +694,22 @@
%7B%0A del(
+%5B%0A
scripts.
@@ -719,17 +719,21 @@
get + '/
-*
+index
.%7Bjs,js.
@@ -737,16 +737,20 @@
js.map%7D'
+%0A %5D
, done);
|
20a379c25e113fd2586690581b3c2ff9027a4b2d
|
update for new api
|
src/tools/connectAudioNodes.js
|
src/tools/connectAudioNodes.js
|
const {find, filter, forEach, pluck, propEq} = require('ramda');
const asArray = require('./asArray');
const connect = require('./connect');
module.exports = function (virtualNodes, handleConnectionToOutput = ()=>{}) {
forEach((virtualAudioNode) =>
forEach((connection) => {
if (connection === 'output') {
return handleConnectionToOutput(virtualAudioNode);
}
if (Object.prototype.toString.call(connection) === '[object Object]') {
const {id, destination} = connection;
const destinationVirtualAudioNode = find(propEq('id', id))(virtualNodes);
return connect(virtualAudioNode,
destinationVirtualAudioNode.audioNode[destination]);
}
const destinationVirtualAudioNode = find(propEq('id', connection))(virtualNodes);
if (destinationVirtualAudioNode.isCustomVirtualNode) {
return forEach(connect(virtualAudioNode),
pluck('audioNode',
filter(propEq('input', 'input'),
destinationVirtualAudioNode.virtualNodes)));
}
connect(virtualAudioNode, destinationVirtualAudioNode.audioNode);
}, asArray(virtualAudioNode.output)), filter(propEq('connected', false),
virtualNodes));
};
|
JavaScript
| 0 |
@@ -1,19 +1,21 @@
const %7B
-find
+equals
, filter
@@ -24,16 +24,22 @@
forEach,
+ keys,
pluck,
@@ -44,16 +44,24 @@
, propEq
+, values
%7D = requ
@@ -151,16 +151,146 @@
ect');%0A%0A
+const isPlainOldObject = x =%3E equals(Object.prototype.toString.call(x),%0A '%5Bobject Object%5D');%0A%0A
module.e
@@ -301,17 +301,8 @@
ts =
- function
(vi
@@ -306,21 +306,21 @@
(virtual
-Nodes
+Graph
, handle
@@ -346,15 +346,18 @@
= ()
+
=%3E
+
%7B%7D)
-%7B
+=%3E
%0A f
@@ -367,80 +367,207 @@
ach(
-(virtualAudioNode) =%3E%0A forEach((connection) =%3E %7B%0A if (connection
+id =%3E %7B%0A const virtualNode = virtualGraph%5Bid%5D;%0A if (virtualNode.connected) %7B%0A return;%0A %7D%0A forEach(output =%3E %7B%0A if (output
===
@@ -575,24 +575,40 @@
'output') %7B%0A
+
retu
@@ -638,29 +638,24 @@
tput(virtual
-Audio
Node);%0A
@@ -659,218 +659,155 @@
-%7D%0A%0A if (Object.prototype.toString.call(connection) === '%5Bobject Object%5D') %7B%0A const %7Bid, destination%7D = connection;%0A const destinationVirtualAudioNode = find(propEq('id', id))(virtualNodes);%0A%0A
+ %7D%0A%0A if (isPlainOldObject(output)) %7B%0A const %7Bid, destination%7D = output;%0A
@@ -828,29 +828,24 @@
nect(virtual
-Audio
Node,%0A
@@ -865,159 +865,188 @@
-destinationVirtualAudioNode.audioNode%5Bdestination%5D);%0A %7D%0A%0A const destinationVirtualAudioNode = find(propEq('id', connection))(virtualNodes);%0A%0A
+ virtualGraph%5Bid%5D.audioNode%5Bdestination%5D);%0A %7D%0A%0A const destinationVirtualAudioNode = virtualGraph%5Boutput%5D;%0A%0A
@@ -1098,24 +1098,40 @@
tualNode) %7B%0A
+
retu
@@ -1152,29 +1152,24 @@
nect(virtual
-Audio
Node),%0A
@@ -1186,16 +1186,32 @@
+
+
pluck('a
@@ -1250,16 +1250,32 @@
+
+
filter(p
@@ -1335,16 +1335,39 @@
+
+ values(
destinat
@@ -1401,24 +1401,25 @@
Nodes)))
+)
;%0A
%7D%0A%0A
@@ -1406,27 +1406,59 @@
))));%0A
-%7D%0A%0A
+ %7D%0A%0A
connec
@@ -1462,29 +1462,24 @@
nect(virtual
-Audio
Node, destin
@@ -1520,10 +1520,46 @@
-%7D,
+ %7D,%0A
asA
@@ -1566,29 +1566,24 @@
rray(virtual
-Audio
Node.output)
@@ -1587,76 +1587,23 @@
ut))
-, filter(propEq('connected', false),%0A
+;%0A %7D,%0A
@@ -1612,31 +1612,25 @@
-
+keys(
virtual
-Nodes
+Graph
));%0A
-%7D;%0A
|
53cc9d1430d41030d19b72576d420d460c925003
|
Save one line of code (#10225)
|
src/utils/keyboardFocus.js
|
src/utils/keyboardFocus.js
|
// @flow weak
import keycode from 'keycode';
import warning from 'warning';
import contains from 'dom-helpers/query/contains';
import ownerDocument from 'dom-helpers/ownerDocument';
import addEventListener from '../utils/addEventListener';
const internal = {
focusKeyPressed: false,
};
export function focusKeyPressed(pressed) {
if (typeof pressed !== 'undefined') {
internal.focusKeyPressed = Boolean(pressed);
}
return internal.focusKeyPressed;
}
export function detectKeyboardFocus(instance, element, callback, attempt = 1) {
warning(instance.keyboardFocusCheckTime, 'Material-UI: missing instance.keyboardFocusCheckTime');
warning(
instance.keyboardFocusMaxCheckTimes,
'Material-UI: missing instance.keyboardFocusMaxCheckTimes',
);
instance.keyboardFocusTimeout = setTimeout(() => {
const doc = ownerDocument(element);
if (
focusKeyPressed() &&
(doc.activeElement === element || contains(element, doc.activeElement))
) {
callback();
} else if (attempt < instance.keyboardFocusMaxCheckTimes) {
detectKeyboardFocus(instance, element, callback, attempt + 1);
}
}, instance.keyboardFocusCheckTime);
}
const FOCUS_KEYS = ['tab', 'enter', 'space', 'esc', 'up', 'down', 'left', 'right'];
function isFocusKey(event) {
return FOCUS_KEYS.indexOf(keycode(event)) !== -1;
}
const handleKeyUpEvent = event => {
if (isFocusKey(event)) {
internal.focusKeyPressed = true;
}
};
export function listenForFocusKeys(win) {
// The event listener will only be added once per window.
// Duplicate event listeners will be ignored by addEventListener.
// Also, this logic is client side only, we don't need a teardown.
addEventListener(win, 'keyup', handleKeyUpEvent);
}
|
JavaScript
| 0 |
@@ -179,66 +179,8 @@
nt';
-%0Aimport addEventListener from '../utils/addEventListener';
%0A%0Aco
@@ -1636,16 +1636,20 @@
down.%0A
+win.
addEvent
@@ -1661,13 +1661,8 @@
ner(
-win,
'key
|
09722256033b5b08d84a6acdde1e40d76b93a779
|
Add space
|
src/main.js
|
src/main.js
|
function leadingZero(number) {
var retval = number;
if (number < 10) {
retval = '0' + number;
}
return retval;
}
function now() {
var today = new Date();
return leadingZero(today.getDate())
+ '.' + leadingZero(today.getMonth() + 1)
+ '.' + leadingZero(today.getFullYear())
+ " " + leadingZero(today.getHours())
+ ":" + leadingZero(today.getMinutes())
+ ":" + leadingZero(today.getSeconds());
}
var header = "<!DOCTYPE html><html><head></head><body>"
+ "DEICHMANSKE BIBLIOTEK<br>"
+ "Tlf: 23432900<br>"
+ "[email protected]<br>"
+ "Kvittering på innlevert materiale<br>"
+ now() + "<br>"
+ " <br><hr>";
function getInner(contents) {
var retval;
if (contents.firstChild === null) {
retval = "";
} else if (contents.firstChild.nodeType !== Node.TEXT_NODE) {
retval = contents.firstChild.innerText;
} else {
retval = contents.innerText.trim();
}
return retval;
}
function getRow(table) {
var data = [];
var headers = [];
for (var r = 0, n = table.rows.length; r < n; r++) {
var rowdata = [];
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
var contents = table.rows[r].cells[c];
rowdata[c] = getInner(contents);
}
if (r === 0) {
headers = rowdata;
} else {
data[r] = rowdata;
}
}
var string = header;
for (var i = 1, l = data.length; i < l; i++) {
for (var k = 0, f = data[i].length; k < f; k++) {
string += headers[k] + ": " + data[i][k] + "<br>";
}
string += "<hr>";
}
string += " <br> <br><body></html>";
return string;
}
printWindow = window.open("");
printWindow.document.write(getRow(document.getElementById("checkedintable")));
printWindow.print();
printWindow.close();
|
JavaScript
| 0.030891 |
@@ -1466,24 +1466,25 @@
%7D%0A %7D%0A
+%0A
var stri
@@ -1492,24 +1492,25 @@
g = header;%0A
+%0A
for (var
@@ -1548,18 +1548,16 @@
i++) %7B%0A
-%0A%0A
@@ -1708,24 +1708,25 @@
hr%3E%22;%0A %7D%0A
+%0A
string +
@@ -1760,24 +1760,25 @@
y%3E%3C/html%3E%22;%0A
+%0A
return s
|
3d6138c325f8de0b4f7b719c2b05b8b73bb2cad2
|
Rename 'gulp serve' to 'gulp server' to use 'gulp serve' as alias for 'gulp dev'.
|
gulpfile.js
|
gulpfile.js
|
var browserSync = require('browser-sync');
var del = require('del');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpSequence = require('gulp-sequence');
var merge = require('merge-stream');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var sass = require('gulp-sass');
var scsslint = require('gulp-scss-lint');
var concat = require('gulp-concat');
var templateCache = require('gulp-angular-templatecache');
var REMOVE_LINE_TOKEN = /.*@@gulp-remove-line.*/g;
// build task
gulp.task('default', ['build']);
// start scss watch mode
gulp.task('dev', gulpSequence('dev:sass', 'serve'));
gulp.task('serve', ['dev']); //alias
// create normal and minified versions
gulp.task('build', gulpSequence('clean', ['build:sass', 'build:js'], ['copy:module', 'copy:sass', 'copy:docs']));
// create readable css from scss files
gulp.task('dev:sass', function () {
return gulp.src('source/stylesheets/*.scss')
.pipe(scsslint())
.pipe(sass({outputStyle: 'compact'}).on('warning', gutil.log))
.pipe(gulp.dest('.tmp/css'))
.pipe(browserSync.stream());
});
// create minified css files
gulp.task('build:sass', function () {
return gulp.src('source/stylesheets/*.scss')
.pipe(scsslint())
.pipe(sass({outputStyle: 'compact'}).on('error', gutil.log))
.pipe(gulp.dest('dist/stylesheets/css'))
.pipe(sass({outputStyle: 'compressed'}).on('error', gutil.log))
.pipe(rename(function (path) {
path.basename += ".min";
return path;
}))
.pipe(gulp.dest('dist/stylesheets/css'))
});
//copy scss files
gulp.task('copy:sass', function () {
return gulp.src('source/stylesheets/**/*')
.pipe(replace(REMOVE_LINE_TOKEN, ''))
.pipe(replace('../../bower_components', '../../..'))
.pipe(gulp.dest('dist/stylesheets/'));
});
gulp.task('copy:docs', function () {
var docs = gulp.src('source/docs/**')
.pipe(gulp.dest('dist/docs/'));
var css = gulp.src('dist/stylesheets/css/**')
.pipe(gulp.dest('dist/docs/css'));
return merge(docs, css);
});
gulp.task('copy:module', function () {
var comps = gulp.src('source/components/**/*.scss')
.pipe(gulp.dest('dist/components/'));
var module = gulp.src('source/*.*')
.pipe(gulp.dest('dist/'));
return merge(comps, module);
});
gulp.task('build:js', function () {
var precompiledTemplates = gulp.src(['source/**/*.html', '!source/docs/**/*.html'])
.pipe(templateCache('templateCache.js', {module : 'msm.components.ui'}));
var componentScripts = gulp.src('source/components/**/*.js');
return merge(precompiledTemplates, componentScripts)
.pipe(concat('mindsmash-ui.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('serve', function () {
browserSync({
notify: false,
port: 8000,
ui: {
port: 8080
},
file: true,
server: {
baseDir: 'source/docs',
routes: {
'/css': '.tmp/css/',
'/bower_components': 'bower_components',
'/components': 'source/components',
'/*.js': 'source/'
}
}
});
gulp.watch([
'!source/docs/bower_components/',
'source/docs/*'
]).on('change', browserSync.reload);
gulp.watch(['source/stylesheets/**/*.scss', 'source/components/**/*.scss'],
['dev:sass']);
});
// delete dist and .tmp folder
gulp.task('clean', function () {
return del.sync(['dist/**', '.tmp/**']);
});
|
JavaScript
| 0 |
@@ -627,16 +627,17 @@
, 'serve
+r
'));%0Agul
@@ -2694,16 +2694,17 @@
k('serve
+r
', funct
|
0265ad9ce1f1079aaa6b539a8a53e501b006c8ba
|
add pretty print CLI support
|
fix2json.js
|
fix2json.js
|
#! /usr/bin/env node
var fs = require('fs')
var _ = require('underscore');
var xpath = require('xpath');
var DOMParser = require('xmldom').DOMParser;
var readline = require('readline');
var StringDecoder = require('string_decoder').StringDecoder;
var decoder = new StringDecoder();
var delim = String.fromCharCode(01); // ASCII start-of-header
if (!process.argv[3]) {
console.error("Usage: fix2json <data dictionary xml file> <FIX message file>");
process.exit(1);
} else {
var dictname = process.argv[2];
var filename = process.argv[3];
var tags = {};
try {
tags = readDataDictionary(dictname);
} catch(dictionaryException) {
console.error("Could not read dictionary file " + dictname + ", error: " + dictionaryException);
process.exit(1);
}
var rd = readline.createInterface({
input: fs.createReadStream(filename),
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
var msg = extractFields(line);
var keys = Object.keys(msg);
var record = {};
_.each(keys, function(key, keyIndex, keyList) {
var tag = tags[key] ? tags[key].name : key;
if (key.length > 0) {
var val = msg[key];
record[tag] = mnemonify(key, val);
}
});
console.log(decoder.write(JSON.stringify(record))); // JSON.stringify(record, undefined, 4) to pretty print
});
}
function extractFields(record) {
var field = {};
var fields = record.split(delim);
for (var i = 0; i < fields.length; i++) {
var both = fields[i].split('=');
field[both[0].replace("\n", '').replace("\r", '')] = both[1];
}
return field;
}
function mnemonify(tag, val) {
return tags[tag] ? (tags[tag].values ? (tags[tag].values[val] ? tags[tag].values[val] : val) : val) : val;
}
function readDataDictionary(fileLocation) {
var xml = fs.readFileSync(fileLocation).toString();
var dom = new DOMParser().parseFromString(xml);
var nodes = xpath.select("//fix/fields/field", dom);
var dictionary = {};
for (var i = 0; i < nodes.length; i++) {
var tagNumber = nodes[i].attributes[0].value
var tagName = nodes[i].attributes[1].value;
var valElem = nodes[i].getElementsByTagName('value');
var values = {};
for (var j = 0; j < valElem.length; j++) {
values[valElem[j].attributes[0].value] = valElem[j].attributes[1].value.replace(/_/g, ' ');
}
dictionary[tagNumber] = {
name: tagName,
values: values
};
}
return dictionary;
}
|
JavaScript
| 0 |
@@ -337,16 +337,36 @@
f-header
+%0Avar pretty = false;
%0A%0Aif (!p
@@ -415,16 +415,21 @@
fix2json
+ %5B-p%5D
%3Cdata d
@@ -498,17 +498,16 @@
else %7B%0A
-%0A
%09var dic
@@ -515,41 +515,207 @@
name
- = process.argv%5B2%5D; %0A %09var
+;%09%0A %09var filename;%0A%09var output;%0A%0A%09if (process.argv%5B2%5D === '-p') %7B%0A%09%09pretty = true;%0A%09%09dictname = process.argv%5B3%5D;%0A%09%09filename = process.argv%5B4%5D;%0A%09%7D else %7B%0A%09%09dictname = process.argv%5B2%5D; %0A %09%09
file
@@ -739,16 +739,20 @@
gv%5B3%5D;%09%0A
+%09%7D%0A%0A
%09var tag
@@ -1409,34 +1409,29 @@
;%0A%09%09
-console.log(decoder.write(
+%0A%09%09output = pretty ?
JSON
@@ -1451,15 +1451,25 @@
cord
-))); //
+, undefined, 4) :
JSO
@@ -1490,39 +1490,49 @@
cord
-, undefined, 4) to pretty print
+);%0A%0A%09%09console.log(decoder.write(output));
%0A%09%7D)
|
76816e941c481f47880717411953eccd40fa07e4
|
fix test.lint.fix task
|
lib/resources/content/package-scripts.template.js
|
lib/resources/content/package-scripts.template.js
|
const {series, crossEnv, concurrent, rimraf} = require('nps-utils')
// @if model.integrationTestRunner.id='protractor'
const {config: {port : E2E_PORT}} = require('./test/protractor.conf')
// @endif
module.exports = {
scripts: {
default: 'nps webpack',
test: {
// @if testRunners.jest
default: 'nps test.jest',
// @endif
// @if testRunners.jest
// @if model.transpiler.id='babel'
jest: {
default: series(
rimraf('test/coverage-jest'),
crossEnv('BABEL_TARGET=node jest')
),
accept: crossEnv('BABEL_TARGET=node jest -u'),
watch: crossEnv('BABEL_TARGET=node jest --watch'),
},
// @endif
// @if model.transpiler.id='typescript'
jest: {
default: series(
rimraf('test/coverage-jest'),
'jest'
),
accept: 'jest -u',
watch: 'jest --watch',
},
// @endif
// @endif
// @if testRunners.karma
// @if !testRunners.jest
default: 'nps test.karma',
// @endif
karma: {
default: series(
rimraf('test/coverage-karma'),
'karma start test/karma.conf.js'
),
watch: 'karma start test/karma.conf.js --auto-watch --no-single-run',
debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug'
},
// @endif
lint: {
default: 'eslint src',
fix: 'eslint --fix'
},
all: concurrent({
// @if testRunners.karma
// @if testRunners.protractor
browser: series.nps('test.karma', 'e2e'),
// @endif
// @if !testRunners.protractor
browser: series.nps('test.karma'),
// @endif
// @endif
// @if !testRunners.karma
// @if testRunners.protractor
browser: series.nps('e2e'),
// @endif
// @endif
// @if testRunners.jest
jest: 'nps test.jest',
// @endif
lint: 'nps test.lint'
})
},
// @if model.integrationTestRunner.id='protractor'
e2e: {
default: concurrent({
webpack: `webpack-dev-server --inline --port=${E2E_PORT}`,
protractor: 'nps e2e.whenReady',
}) + ' --kill-others --success first',
protractor: {
install: 'webdriver-manager update',
default: series(
'nps e2e.protractor.install',
'protractor test/protractor.conf.js'
),
debug: series(
'nps e2e.protractor.install',
'protractor test/protractor.conf.js --elementExplorer'
),
},
whenReady: series(
`wait-on --timeout 120000 http-get://localhost:${E2E_PORT}/index.html`,
'nps e2e.protractor'
),
},
// @endif
build: 'nps webpack.build',
webpack: {
default: 'nps webpack.server',
build: {
before: rimraf('dist'),
default: 'nps webpack.build.production',
development: {
default: series(
'nps webpack.build.before',
'webpack --progress -d'
),
extractCss: series(
'nps webpack.build.before',
'webpack --progress -d --env.extractCss'
),
serve: series.nps(
'webpack.build.development',
'serve'
),
},
production: {
inlineCss: series(
'nps webpack.build.before',
crossEnv('NODE_ENV=production webpack --progress -p --env.production')
),
default: series(
'nps webpack.build.before',
crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss')
),
serve: series.nps(
'webpack.build.production',
'serve'
),
}
},
server: {
default: `webpack-dev-server -d --devtool '#source-map' --inline --env.server`,
extractCss: `webpack-dev-server -d --devtool '#source-map' --inline --env.server --env.extractCss`,
hmr: `webpack-dev-server -d --devtool '#source-map' --inline --hot --env.server`
},
},
serve: 'http-server dist --cors',
},
}
|
JavaScript
| 0.000115 |
@@ -1442,16 +1442,20 @@
'eslint
+src
--fix'%0A
|
86fe9147fe57613dc61c79d8ace7f2d16871e3f1
|
Remove unused dependency
|
js/library-provider.js
|
js/library-provider.js
|
var mopidy = require('./mopidy');
var when = require('when');
var _ = require('underscore');
var LibraryProvider = function () {
this.getArtists = function() {
return mopidy.library.search(null).then(function(results) {
var artists = [];
_.each(results, function(result) {
if (result.hasOwnProperty("albums")) {
_.each(result.albums, function(album) {
if (album.hasOwnProperty("artists") && album.artists instanceof Array && album.artists.length) {
if (!album.artists[0].name) {
console.warn("Empty artist!");
console.log(album);
} else {
artists.push(album.artists[0].name);
}
} else {
console.log(album);
}
});
} else if (result.hasOwnProperty("tracks")) {
_.each(result.tracks, function(track) {
if (track.hasOwnProperty("artists") && track.artists instanceof Array && track.artists.length) {
if (!track.artists[0].name) {
console.warn("Empty artist!");
console.log(track);
} else {
artists.push(track.artists[0].name);
}
} else {
console.warn("Track witout arists!");
console.log(track);
}
});
} else {
console.warn("Unhandled search results.");
console.log(result);
}
});
return _.chain(artists).uniq().sortBy(function(name) {
return name;
}).value();
});
};
this.getAlbums = function(filter) {
return mopidy.library.search(filter).then(function(results) {
var albums = [];
_.each(results, function(result) {
// TODO: Album should be defined by (album, artist) tuple
if (result.hasOwnProperty("albums")) {
_.each(result.albums, function(album) {
if (!album.name) {
// TODO: Such case can happen, fallback to Unknwon album
// if artist is set
// console.warn("Empty album name!");
// console.log(album);
} else {
albums.push(album.name);
}
});
} else if (result.hasOwnProperty("tracks")) {
_.each(result.tracks, function(track) {
if (track.hasOwnProperty("album")) {
if (!track.album.name) {
// TODO: Such case can happen, fallback to Unknwon album
// if artist is set
// console.warn("Empty album!");
// console.log(track);
} else {
albums.push(track.album.name);
}
} else {
console.warn("Track witout album!");
console.log(track);
}
});
} else {
console.warn("Unhandled search results.");
console.log(result);
}
});
return _.chain(albums).uniq().sortBy(function(name) {
return name;
}).value();
});
};
this.getTracks = function(filter) {
return mopidy.library.search(filter).then(function(results) {
var tracks = [];
var uris = {};
_.each(results, function(result) {
if (result.hasOwnProperty("tracks")) {
_.each(result.tracks, function(track) {
tracks.push(track.name);
if (!uris.hasOwnProperty(track.name)) {
uris[track.name] = [];
}
uris[track.name].push(track.uri);
});
} else {
console.warn("Unhandled search results.");
console.log(result);
}
});
return {
tracks: _.chain(tracks).uniq().sortBy(function(name) { return name; }).value(),
uris: uris
};
});
};
};
module.exports = new LibraryProvider();
|
JavaScript
| 0.000002 |
@@ -31,36 +31,8 @@
');%0A
-var when = require('when');%0A
var
|
baa3cc9ba043fa6de3abe682f6ea5f1ddb06faab
|
Update script.js
|
script.js
|
script.js
|
/*! Simple fixed nav on scroll down based on #header element's height by cara-tm.com, MIT license */
function doOnScroll(){didScroll=!0}function addClass(e,d){document.classList?d.classList.add(e):d.className+=" s"}var didScroll=!1,nav=document.getElementById("menu"),header=document.getElementById("header");window.onscroll=doOnScroll,setInterval(function(){if(didScroll){didScroll=!1;var e=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop,d=header.clientHeight;e>d?addClass("fixed",nav):d>=e&&(nav.className=nav.className.replace(" fixed",""))}},70);
|
JavaScript
| 0 |
@@ -98,138 +98,27 @@
*/%0A
-function doOnScroll()%7BdidScroll=!0%7Dfunction addClass(e,d)%7Bdocument.classList?d.classList.add(e):d.className+=%22 s%22%7Dvar didScroll=!1
+var didScroll=false
,nav
@@ -217,17 +217,55 @@
OnScroll
-,
+;function doOnScroll()%7BdidScroll=true;%7D
setInter
@@ -307,16 +307,21 @@
oll=
-!1
+false
;var
-e
+top
=win
@@ -397,17 +397,22 @@
rollTop,
-d
+height
=header.
@@ -428,12 +428,23 @@
ght;
-e%3Ed?
+if(top%3Eheight)%7B
addC
@@ -464,16 +464,31 @@
nav)
-:d%3E=e&&(
+;%7Delse if(top%3C=height)%7B
nav.
@@ -535,13 +535,102 @@
,%22%22)
-)
+;%7D
%7D%7D,70);
+function addClass(s,a)%7Bif(document.classList)a.classList.add(s);else a.className+=%22 s%22;%7D
%0A
|
90651cb170c6dc03475ee4a473454edff83a1c59
|
Fix context event
|
src/main.js
|
src/main.js
|
import TinyEmitter from 'tiny-emitter';
import Internal from './internal';
import utils from './utils';
import { DEFAULT_OFFSET } from './constants';
/**
* Principal class. Will be passed as argument to others.
* @class Base
*/
export default class Base extends TinyEmitter {
constructor() {
if (!(this instanceof Base)) return new Base();
super();
this.counter = 0;
Base.Internal = new Internal(this);
}
/**
* @param {String|Element} element String or DOM node.
* @param {Number|Object|undefined} opt_offset Element offset.
*/
watch(element, opt_offset) {
utils.assert(typeof element === 'string' || utils.isElement(element),
'@param `element` should be string type or DOM Element!');
utils.assert(
typeof opt_offset === 'number' ||
typeof opt_offset === 'object' ||
typeof opt_offset === 'undefined',
'@param `opt_offset` should be number or Object or undefined!');
let offset;
const idx = ++this.counter;
const emitter = new TinyEmitter();
const node = utils.evaluate(element);
utils.assert(utils.isElement(node),
`Couldn't evaluate (${element}) to a valid DOM node`);
if (typeof opt_offset === 'number') {
offset = {
top: opt_offset,
bottom: opt_offset
};
} else {
offset = utils.mergeOptions(DEFAULT_OFFSET, opt_offset);
}
Base.Internal.watching[idx] = {
node : node,
emitter : emitter,
offset : offset,
dimensions : utils.offset(node)
};
reset(Base.Internal.watching[idx]);
function reset(item) {
item.isInViewport = false;
item.wasInViewport = false;
item.isAboveViewport = false;
item.wasAboveViewport = false;
item.isBelowViewport = false;
item.wasBelowViewport = false;
item.isPartialOut = false;
item.wasPartialOut = false;
item.isFullyOut = false;
item.wasFullyOut = false;
item.isFullyInViewport = false;
item.wasFullyInViewport = false;
}
return {
target: node,
update: function () {
reset(Base.Internal.watching[idx]);
Base.Internal.watching[idx].dimensions = utils.offset(node);
},
once: function (eventName, callback) {
emitter.once(eventName, callback);
return this;
},
on: function (eventName, callback) {
emitter.on(eventName, callback);
return this;
},
off: function (eventName, callback) {
emitter.off(eventName, callback);
return this;
}
};
}
/**
* @param {Number|undefined} offset How far to offset.
* @return {Boolean} Whether window is scrolled to bottom
*/
windowAtBottom(offset = 0) {
const scrolled = Base.Internal.lastXY[1];
const viewHeight = Base.Internal.viewport.h;
offset = parseInt(offset, 10);
return scrolled + viewHeight >= utils.getDocumentHeight() - offset;
}
/**
* @param {Number|undefined} offset How far to offset.
* @return {Boolean} Whether window is scrolled to top
*/
windowAtTop(offset = 0) {
const scrolled = Base.Internal.lastXY[1];
offset = parseInt(offset, 10);
return scrolled <= offset;
}
}
|
JavaScript
| 1 |
@@ -965,16 +965,40 @@
offset;%0A
+ const this_ = this;%0A
cons
@@ -2408,35 +2408,41 @@
ntName, callback
+, this
);%0A
-
return t
@@ -2528,32 +2528,38 @@
ntName, callback
+, this
);%0A retur
@@ -2611,32 +2611,32 @@
me, callback) %7B%0A
-
emitter.
@@ -2658,16 +2658,22 @@
callback
+, this
);%0A
|
bf7b1283448081d7eb35bc9779fbc116601532c0
|
improve gulpfile
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var del = require('del');
var fs = require('fs');
var gulp = require('gulp');
var concat = require('gulp-concat');
var concatCss = require('gulp-concat-css');
var connect = require('gulp-connect');
var data = require('gulp-data');
var gulpif = require('gulp-if');
var minifyCss = require('gulp-minify-css');
var nunjucksRender = require('gulp-nunjucks-render');
var renameRegex = require('gulp-regex-rename');
var showHelp = require('gulp-showhelp');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var ini = require('ini');
var proxy = require('proxy-middleware');
var runSequence = require('run-sequence');
var config = {
dev: true,
srcJS: ['src/main/webapp/js/lib/angular.js',
'src/main/webapp/js/lib/*.js',
'src/main/webapp/js/app.js',
'src/main/webapp/js/app/**/*module.js',
'src/main/webapp/js/app/**/*.js'
],
destJS: 'prd/js/',
outJS: 'game.js',
watchJS: 'src/main/webapp/js/app/**/*.js',
srcGameCss: ['src/main/webapp/css/*.css'],
outGameCSS: 'game.css',
srcSiteCSS: ['!src/main/webapp/css/createGame.css', '!src/main/webapp/css/gamePage.css', 'src/main/webapp/css/*.css'],
outSiteCSS: 'site.css',
destCSS: 'prd/css/',
watchCSS: 'src/main/webapp/css/*.css',
srcHtml: ['!src/main/webapp/WEB-INF/_*.html', 'src/main/webapp/WEB-INF/*.html'],
destHtml: 'prd',
watchHtml: 'src/main/webapp/WEB-INF/*.html',
scrPartials: 'src/main/webapp/js/app/**/*.html',
destPartials: 'prd/partials',
srcImg: 'src/main/webapp/img/**/*',
destImg: 'prd/img',
templates: {}
};
// We cannot use the default tags since they conflict with angular's
nunjucksRender.nunjucks.configure({
tags: {
variableStart: '${',
variableEnd: '}'
},
watch: false
});
gulp.task('default', ['help']);
gulp.task('help', function () {
showHelp.show(showHelp.taskNames().sort());
});
gulp.task('clean', function (cb) {
del('prd', cb);
}).help = 'clean production files.';
gulp.task('cleanall', ['clean'], function (cb) {
del('node_modules', cb);
}).help = 'launch clean and remove all node_modules.';
gulp.task('dev', function (cb) {
runSequence(
'load-dev-conf',
['build-js', 'build-css', 'build-html', 'build-partials', 'build-images'],
cb);
}).help = 'build all files for development.';
gulp.task('load-dev-conf', function () {
config.templates = ini.parse(fs.readFileSync('./config-dev.ini', 'utf-8'));
});
gulp.task('build-js', function () {
return gulp.src(config.srcJS)
.pipe(gulpif(config.dev, sourcemaps.init()))
.pipe(concat(config.outJS))
.pipe(uglify())
.pipe(gulpif(config.dev, sourcemaps.write()))
.pipe(gulp.dest(config.destJS));
});
gulp.task('build-css', ['build-game-css', 'build-site-css']);
gulp.task('build-game-css', function () {
return gulp.src(config.srcGameCss)
.pipe(gulpif(config.dev, sourcemaps.init()))
.pipe(concatCss(config.outGameCSS))
.pipe(minifyCss())
.pipe(gulpif(config.dev, sourcemaps.write()))
.pipe(gulp.dest(config.destCSS));
});
gulp.task('build-site-css', function () {
return gulp.src(config.srcSiteCSS)
.pipe(gulpif(config.dev, sourcemaps.init()))
.pipe(concatCss(config.outSiteCSS))
.pipe(minifyCss())
.pipe(gulpif(config.dev, sourcemaps.write()))
.pipe(gulp.dest(config.destCSS));
});
gulp.task('build-html', function () {
return gulp.src(config.srcHtml)
.pipe(data(function () {
var nunjucksConfig = config.templates;
return nunjucksConfig;
}))
.pipe(nunjucksRender())
.pipe(renameRegex(/(.*).html/, '$1/index.html'))
.pipe(renameRegex(/index\/index.html/, 'index.html'))
.pipe(gulp.dest(config.destHtml));
});
gulp.task('build-partials', function () {
return gulp.src(config.scrPartials)
.pipe(renameRegex(/\/partials/, ''))
.pipe(gulp.dest(config.destPartials));
});
gulp.task('build-images', function () {
return gulp.src(config.srcImg)
.pipe(gulp.dest(config.destImg));
});
gulp.task('watch', ['dev', 'serve'], function () {
watch(config.watchJS, function () {
gulp.start('build-js');
});
watch(config.watchCSS, function () {
gulp.start('build-css');
});
watch(config.watchHtml, function () {
gulp.start('build-html');
});
}).help = 'watch files for modification and rebuild them.';
gulp.task('serve', function () {
connect.server({
root: 'prd',
port: 8282,
middleware: function () {
return [(function () {
var url = require('url');
var options = url.parse('http://localhost:8080/api');
options.route = '/api';
return proxy(options);
})()];
}
});
}).help = 'start a small server to ease devolopment of the frontend';
gulp.task('prod', function (cb) {
runSequence(
'clean',
'load-prod-conf',
['build-js', 'build-css', 'build-html', 'build-images', 'build-partials'],
cb);
}).help = 'build all files for production.';
gulp.task('load-prod-conf', function (cb) {
config.dev = false;
config.templates = ini.parse(fs.readFileSync('./config-prod.ini', 'utf-8'));
cb();
});
|
JavaScript
| 0 |
@@ -963,53 +963,8 @@
s',%0A
- watchJS: 'src/main/webapp/js/app/**/*.js',%0A
sr
@@ -1204,49 +1204,8 @@
/',%0A
- watchCSS: 'src/main/webapp/css/*.css',%0A
sr
@@ -1308,58 +1308,11 @@
,%0A
-watchHtml: 'src/main/webapp/WEB-INF/*.html',%0A scr
+src
Part
@@ -3708,18 +3708,18 @@
config.s
-c
r
+c
Partials
@@ -3999,21 +3999,19 @@
(config.
-watch
+src
JS, func
@@ -4073,16 +4073,18 @@
fig.
-watchCSS
+srcGameCss
, fu
@@ -4145,21 +4145,19 @@
(config.
-watch
+src
Html, fu
@@ -4200,24 +4200,180 @@
ml');%0A %7D);%0A
+ watch(config.srcPartials, function () %7B%0A gulp.start('build-partials');%0A %7D);%0A watch(config.srcImg, function () %7B%0A gulp.start('build-images')%0A %7D);%0A
%7D).help = 'w
|
ae21483bae5c0148f7f5cc67fe414ea1c82cb432
|
update copyright dates from daily grunt work
|
js/phetcommon-tests.js
|
js/phetcommon-tests.js
|
// Copyright 2017-2020, University of Colorado Boulder
/**
* Unit tests for phetcommon. Please run once in phet brand and once in brand=phet-io to cover all functionality.
*
* @author Sam Reid (PhET Interactive Simulations)
*/
import qunitStart from '../../chipper/js/sim-tests/qunitStart.js';
import './model/FractionTests.js';
import './util/StringUtilsTests.js';
// Since our tests are loaded asynchronously, we must direct QUnit to begin the tests
qunitStart();
|
JavaScript
| 0 |
@@ -14,17 +14,17 @@
2017-202
-0
+2
, Univer
|
57d335952293299d32e9f6f08e4f69dd8e929f17
|
Remove stray massive log call
|
script.js
|
script.js
|
"use strict";
var fs = require('fs');
var exec = require('child_process').exec;
var csv = require('csv');
var plotter = exec('R --no-save --interactive', {
env: process.env,
});
var plotter_cb_queue = [];
plotter.stdin.write('repl = TRUE; source("plots.R")\n');
plotter.stdout.on('data', function (data) {
if (data.match('--DONE--') != null)
plotter_cb_queue.shift(0)();
//console.log('stdout: ' + data);
});
plotter.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
var submitPlot = function (dir, expr, cb) {
plotter_cb_queue.push(cb);
plotter.stdin.write('setwd("' + dir + '"); ' + expr + ';\n');
}
$(function() {
//$('.btn-group').button();
/*$('#logs-othert').toggle(function() {
console.log('toggle');
//$('.btn-group').button('reset')
});
*/
var fill = function(name, div, opts) {
for (var i in opts) {
var active = i == 0 ? 'active' : '';
div.append('<label class="btn btn-primary mh50 ' + active + '">' +
'<input type="radio" name="' + name + '" value="' + opts[i] + '"> ' + opts[i] +
'</label>');
}
div.append('<label class="btn btn-primary mh50">' +
'<input type="radio" name="' + name + '" value="__other__">' +
'<input type="text" name="' + name + '-other" class="form-control" placeholder="' + name + '">' +
'</label>');
};
fill('logs', $('#logs'), [
'same',
'diff',
'diff-oldstale',
'diff-oldminstale',
]);
fill('timing', $('#timing'), [
'LAN',
'WAN',
'Delay1pct',
'Down',
'P1',
'P2',
'L1',
'Deian',
'BadRecv',
]);
fill('algorithm', $('#algorithm'), [
'submission',
'hesitant',
'hesitant2',
'nograntnobump',
'stalelognobump',
'zookeeper',
'zookeeper2',
]);
fill('terms', $('#terms'), [
'same',
'diff',
]);
fill('cluster', $('#cluster'), [
'3',
'5',
'7',
'9',
'5-2+2',
]);
var crypto = require('crypto');
var form = $('#form');
var args = $('#args', form);
form.change(function() {
setTimeout(function() {
form.submit();
}, 0);
});
$('#pin').click(function() {
$('#pinned').prepend($('#graph').clone().removeProp('id'));
});
var getArg = function(name) {
var v = $('.active [name=' + name + ']', form).val();
if (v == '__other__')
v = $('[name=' + name + '-other]', form).val();
return ' --' + name + '=' + v + ' ';
}
var zeropad = function(minlen, s) {
while (s.length < minlen)
s = "0" + s;
return s;
}
form.submit(function() {
var trace = $('#trace').val();
var effargs = (args.val() +
getArg('logs') +
getArg('terms') +
getArg('timing') +
getArg('algorithm') +
getArg('cluster') +
'--trace ' + trace + ' ');
console.log(effargs);
var sha1sum = crypto.createHash('sha1');
sha1sum.update(effargs);
// nonce so that browser doesn't cache old graph
// (defeats point of update(effargs), though)
var nonce = crypto.randomBytes(8).toString();
sha1sum.update(nonce);
var dir = 'explore/' + sha1sum.digest('hex');
try {
fs.mkdirSync(dir);
} catch (e) {
if (e.code != "EEXIST")
throw e;
}
console.log('Running ./main ' + effargs);
var sim = exec('../../main ' + effargs, {
cwd: dir,
env: process.env,
});
sim.on('error', function (e) {
console.log(e);
});
sim.stdout.on('data', function (data) {
//console.log('stdout: ' + data);
});
sim.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
sim.on('exit', function (code) {
console.log('sim exited with code ' + code);
if (code != 0)
return;
$('#runs').html('');
csv()
.from.path(dir + '/samples.csv', {
columns: true
})
.to.array(function (data) {
console.log("finished reading samples.csv");
data.forEach(function (row) {
if (row.run >= trace)
return;
var link = $('<a></a>')
.prop('href', '')
.append((row.election_time / 1e3).toFixed(0))
.click(function() {
fs.readFile(dir + '/trace' + zeropad(6, row.run.toString()) + '.html',
{encoding: 'utf8', flag: 'r'},
function (err, data) {
if (err)
console.log(err);
console.log(data);
$('#fulltrace').html('' + data);
});
submitPlot(dir, 'timeline(' + row.run + ')', function() {
console.log('R done');
$('#timeline').prop('src', dir + '/timeline' + zeropad(6, row.run.toString()) + '.svg');
});
return false;
});
$('#runs').append(link).append(' ');
});
})
.transform(function(row){
row.election_time = parseInt(row.election_time);
row.run = parseInt(row.run);
return row;
});
console.log('Running R');
/*
var plot = exec('Rscript ../../plots.R', {
cwd: dir,
env: process.env,
});
plot.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
plot.stderr.on('data', function (data) {
//console.log('stderr: ' + data);
});
plot.on('close', function (code) {
console.log('plot exited with code ' + code);
$('#graph').prop('src', dir + '/Rplots.svg');
});
*/
submitPlot(dir, 'cdf()', function() {
console.log('R done');
$('#graph').prop('src', dir + '/Rplots.svg');
});
});
return false;
});
form.submit();
});
|
JavaScript
| 0 |
@@ -4426,45 +4426,8 @@
r);%0A
- console.log(data);%0A
|
74e58510511442f00c8da849136587b9b453590c
|
Fix cache expiry logic.
|
lib/cache.js
|
lib/cache.js
|
/**
* Copyright 2013 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.
*/
var fs = require('fs');
/**
* @const
* @private
* Path to the temporary directory.
* @type {String}
*/
Cache.TMP_DIR_ = __dirname + '/../.cache';
/**
* @const
* @private
* Default encoding for cached files.
* @type {String}
*/
Cache.ENCODING_ = 'utf-8';
/**
* @const
* @private
* Default expires time in micro seconds.
* @type {Number}
*/
Cache.EXPIRES_IN_ = 5 * 60 * 1000;
/**
* @constructor
* Cache constructor.
* @param {String} opt_opts Optional options.
*/
function Cache(opt_opts) {
this.opts = opt_opts || {};
this.opts.path = this.opts.path || Cache.TMP_DIR_;
if (!fs.existsSync(this.opts.path)) {
fs.mkdirSync(this.opts.path, '700');
}
}
/**
* Loads discovery data from cache
* @param {object} api
* @return {object?} Returns the cached discovery data if exists
* or not expired.
*/
Cache.prototype.load = function(api) {
var path = this.getPath(api);
// check if file exists and not expired
if (!fs.existsSync(path)) {
return null;
}
if (this.isExpired(path)) {
// delete the expired cache file
fs.unlinkSync(path);
return null;
}
var data = fs.readFileSync(this.getPath(api), Cache.ENCODING_);
return data && JSON.parse(data);
};
/**
* Writes api discovery data to the cache.
* @param {object} api
* @param {object} data
*/
Cache.prototype.write = function(api, data) {
data && fs.writeFileSync(
this.getPath(api), JSON.stringify(data), Cache.ENCODING_);
};
/**
* Checks whether the file at path is expired or not
* @param {[type]} path The path of the file to check.
* @return {Boolean} Returns true or false depending on the expiration.
*/
Cache.prototype.isExpired = function(path) {
var expiresIn = this.opts.expiresIn || Cache.EXPIRES_IN_;
return new Date(fs.statSync(path).mtime).getTime() - expiresIn < 0;
};
/**
* Gets the path where the api data is stored at.
* @param {[type]} api
* @return {string} Path to the data file.
*/
Cache.prototype.getPath = function(api) {
return this.opts.path + '/' + api.name + api.version + '-rest';
};
/**
* Exports Cache.
* @type {Cache}
*/
module.exports = Cache;
|
JavaScript
| 0 |
@@ -2401,16 +2401,29 @@
return
+ Date.now() -
new Dat
@@ -2459,17 +2459,17 @@
tTime()
--
+%3E
expires
@@ -2474,12 +2474,8 @@
esIn
- %3C 0
;%0A%7D;
|
f6f1e054c3991162b5e105844efe6b3a6e759d51
|
Improve some more stuff
|
commands/weather/weather-alt.js
|
commands/weather/weather-alt.js
|
// Credit goes to https://github.com/kurisubrooks/midori
const { Command } = require('discord.js-commando');
const moment = require('moment');
const request = require('request-promise');
const winston = require('winston');
const config = require('../../settings');
const version = require('../../package').version;
module.exports = class WeatherCommand extends Command {
constructor(client) {
super(client, {
name: 'weather-alt',
aliases: ['w-alt'],
group: 'weather',
memberName: 'weather-alt',
description: 'Get the weather.',
format: '<location>',
guildOnly: true,
args: [
{
key: 'location',
prompt: 'What location would you like to have information on?\n',
type: 'string'
}
]
});
}
async run(msg, args) {
const location = args.location;
if (!config.GoogleAPIKey) return msg.reply('my Commander has not set the Google API Key. Go yell at him.');
if (!config.WeatherAPIKey) return msg.reply('my Commander has not set the Weather API Key. Go yell at him.');
let locationURI = encodeURIComponent(location.replace(/ /g, '+'));
return request({
uri: `https://maps.googleapis.com/maps/api/geocode/json?address=${locationURI}&key=${config.GoogleAPIKey}`,
headers: { 'User-Agent': `Hamakaze ${version} (https://github.com/iCrawl/Hamakaze/)` },
json: true
}).then(response => {
if (response.status !== 'OK') return this.handleNotOK(msg, response.body.status);
if (response.results.length === 0) return msg.reply('I couldn\'t find a place with the location you provded me');
return request({
uri: `https://api.darksky.net/forecast/${config.WeatherAPIKey}/${response.results[0].geometry.location.lat},${response.results[0].geometry.location.lng}?exclude=minutely,hourly,flags&units=auto`,
headers: { 'User-Agent': `Hamakaze ${version} (https://github.com/iCrawl/Hamakaze/)` },
json: true
}).then(res => {
let datetime = moment().utcOffset(res.timezone).format('D MMMM, h:mma');
let condition = res.currently.summary;
let icon = res.currently.icon;
let chanceofrain = Math.round((res.currently.precipProbability * 100) / 5) * 5;
let temperature = Math.round(res.currently.temperature * 10) / 10;
let temperatureMin = Math.round(res.daily.data[0].temperatureMin * 10) / 10;
let temperatureMax = Math.round(res.daily.data[0].temperatureMax * 10) / 10;
let feelslike = Math.round(res.currently.apparentTemperature * 10) / 10;
let humidity = Math.round(res.currently.humidity * 100);
let windspeed = res.currently.windSpeed;
let embed = {
color: 3447003,
fields: [
{
name: 'Los Angeles',
value: `${this.getBase(icon)}`,
inline: true
},
{
name: 'Condition',
value: `${condition}`,
inline: true
},
{
name: 'Temperature',
value: `${temperature}`,
inline: true
},
{
name: 'High / Low',
value: `${temperatureMax}\n${temperatureMin}`,
inline: true
},
{
name: 'Feels like',
value: `${feelslike}`,
inline: true
},
{
name: 'Humidity',
value: `${humidity}`,
inline: true
},
{
name: 'Chance of rain',
value: `${chanceofrain}`,
inline: true
},
{
name: 'Windspeed',
value: `${windspeed}`,
inline: true
}
],
footer: {
icon_url: msg.client.user.avatarURL, // eslint-disable-line camelcase
text: `${datetime}`
}
};
return msg.channel.sendMessage('', { embed })
.catch(error => { winston.error(error); });
}).catch(error => {
return winston.error(error);
});
}).catch(error => {
winston.error(error);
return msg.say(`Error: Status code ${error.status || error.response} from Google.`);
});
}
handleNotOK(msg, status) {
if (status === 'ZERO_RESULTS') {
return { plain: `${msg.author}, your request returned no results.` };
} else if (status === 'REQUEST_DENIED') {
return { plain: `Error: Geocode API Request was denied.` };
} else if (status === 'INVALID_REQUEST') {
return { plain: `Error: Invalid Request,` };
} else if (status === 'OVER_QUERY_LIMIT') {
return { plain: `${msg.author}, Query Limit Exceeded. Try again tomorrow.` };
} else {
return { plain: `Error: Unknown.` };
}
}
getBase(icon) {
if (icon === 'clear-night' || icon === 'partly-cloudly-night') return `☁`;
if (icon === 'rain') return `🌧`;
if (icon === 'snow' || icon === 'sleet' || icon === 'fog' || icon === 'wind') return `🌫`;
if (icon === 'cloudy') return `☁`;
return `☀`;
}
getUnit(units) {
let unit = units.find(un => un.types.includes('country'));
if (unit === undefined) return 'm/s';
if (unit.short_name === 'US' || unit.short_name === 'GB') return 'mph';
if (unit.short_name === 'CA') return 'kph';
return 'm/s';
}
};
|
JavaScript
| 0 |
@@ -2872,19 +2872,20 @@
erature%7D
+%C2%B0
%60,%0A
-
%09%09%09%09%09%09%09i
@@ -2972,16 +2972,17 @@
tureMax%7D
+%C2%B0
%5Cn$%7Btemp
@@ -2992,16 +2992,17 @@
tureMin%7D
+%C2%B0
%60,%0A%09%09%09%09%09
@@ -3087,16 +3087,17 @@
elslike%7D
+%C2%B0
%60,%0A%09%09%09%09%09
@@ -3179,16 +3179,17 @@
umidity%7D
+%25
%60,%0A%09%09%09%09%09
@@ -3281,16 +3281,17 @@
eofrain%7D
+%25
%60,%0A%09%09%09%09%09
@@ -3374,17 +3374,85 @@
indspeed
-%7D
+.toFixed(2)%7D $%7Bthis.getUnit(response.results%5B0%5D.address_components)%7D
%60,%0A%09%09%09%09%09
|
ca75342cf09113341c6e53aaea09c01ca6e5bb47
|
improve default form object initialization forforms with prop-less children
|
src/utils/defaultFormObject.js
|
src/utils/defaultFormObject.js
|
import FormObject from '../object/FormObject'
import compact from 'lodash/compact'
import flatten from 'lodash/flatten'
import React from 'react'
export default function defaultFormObject(model, children) {
const properties = collectPropertiesFromAllChildren(children)
let formObject = class DefaultFormObject extends FormObject {
static get properties() {
return properties
}
static get model() {
return model
}
}
// formObject.__defineGetter__('properties', function() { return ['query'] })
// formObject.__defineGetter__('model', function() { return 'search' })
return formObject
}
function collectPropertiesFromAllChildren(children) {
let properties = []
React.Children.map(children, child => {
if (child.props.attribute) properties.push(child.props.attribute)
if (child.props.children) {
const recursiveProperties =
collectPropertiesFromAllChildren(child.props.children)
properties.push(recursiveProperties)
}
})
return compact(flatten(properties))
}
|
JavaScript
| 0 |
@@ -741,16 +741,45 @@
ld =%3E %7B%0A
+ if (!child.props) return%0A
if (
|
594747da97ed613e62eef1d675f34604ef12b9d2
|
Add debug line
|
lib/cache.js
|
lib/cache.js
|
/*
* Copyright (c) 2012, Joyent, Inc. All rights reserved.
*
* Cache client wrapper.
*/
var assert = require('assert-plus');
var redis = require('redis');
var sprintf = require('util').format;
var common = require('./common');
var VM_KEY = 'vmapi:vms:%s';
var SERVER_KEY = 'vmapi:servers:%s:vms';
var STATUS_KEY = 'vmapi:vms:status';
function Cache(options) {
assert.object(options, 'redis options');
assert.object(options.log, 'redis options.log');
this.options = options;
this.log = options.log;
attemptConnect.call(this);
}
function attemptConnect() {
var self = this;
var log = this.log;
var timeout = null;
var client = this.client = redis.createClient(
this.options.port || 6379, // redis default port
this.options.host || '127.0.0.1',
{ max_attempts: 1 });
function onReady() {
clearTimeout(timeout);
timeout = null;
// VMAPI's DB Index
client.select(4);
log.info('Redis client connected');
}
function onError(err) {
log.error(err, 'Cache client error');
}
function onEnd() {
client.end();
self.client = null;
log.error('Cache client disconnected');
log.info('Re-attempting connection to Redis');
if (!timeout) {
attemptConnect.call(self);
}
}
function timeoutCallback() {
attemptConnect.call(self);
}
client.once('ready', onReady);
client.on('error', onError);
client.once('end', onEnd);
timeout = setTimeout(timeoutCallback, 10000);
}
Cache.prototype.connected = function () {
return this.client && this.client.connected;
};
Cache.prototype.set = function (hash, object, callback) {
return this.client.hmset(hash, object, callback);
};
Cache.prototype.get = function (hash, callback) {
return this.client.hgetall(hash, callback);
};
Cache.prototype.del = function (key, callback) {
return this.client.del(key, callback);
};
Cache.prototype.getKey = function (hash, key, callback) {
return this.client.hget(hash, key, callback);
};
Cache.prototype.getKeys = function (hash, callback) {
return this.client.hkeys(hash, callback);
};
Cache.prototype.setKey = function (hash, key, value, callback) {
return this.client.hset(hash, key, value, callback);
};
Cache.prototype.delKey = function (hash, key, callback) {
return this.client.hdel(hash, key, callback);
};
Cache.prototype.getHashes = function (hashes, callback) {
var multi = this.client.multi();
for (var i = 0; i < hashes.length; i++) {
multi.hgetall(hashes[i]);
}
multi.exec(callback);
};
Cache.prototype.exists = function (key, callback) {
this.client.exists(key, callback);
};
/**
* VM helper functions
*/
/*
* Gets a list of VMs from a list of uuids
*/
Cache.prototype.getVms = function (uuids, callback) {
assert.arrayOfString(uuids, 'VM UUIDs');
var vmKeys = [];
for (var i = 0; i < uuids.length; i++) {
vmKeys.push(sprintf(VM_KEY, uuids[i]));
}
return this.getHashes(vmKeys, callback);
};
Cache.prototype.setVm = function (uuid, vm, callback) {
var vmKey = sprintf(VM_KEY, uuid);
var hash = common.vmToHash(vm);
return this.set(vmKey, hash, callback);
};
Cache.prototype.getVm = function (uuid, callback) {
var vmKey = sprintf(VM_KEY, uuid);
return this.get(vmKey, callback);
};
Cache.prototype.getVmsForServer = function (server, callback) {
var serverKey = sprintf(SERVER_KEY, server);
return this.getKeys(serverKey, callback);
};
Cache.prototype.setVmsForServer = function (server, hash, callback) {
var self = this;
var serverKey = sprintf(SERVER_KEY, server);
this.del(serverKey, function (err) {
if (err) {
callback(err);
return;
}
self.set(serverKey, hash, callback);
});
};
Cache.prototype.getState = function (uuid, callback) {
return this.getKey(STATUS_KEY, uuid, callback);
};
Cache.prototype.setState = function (uuid, state, callback) {
return this.setKey(STATUS_KEY, uuid, state, callback);
};
Cache.prototype.delState = function (uuid, callback) {
return this.delKey(STATUS_KEY, uuid, callback);
};
Cache.prototype.setVmState =
function (uuid, zoneState, timestamp, server, persisted, cb) {
var self = this;
var stateStamp;
if (persisted) {
stateStamp = zoneState + ';' + timestamp;
} else {
stateStamp = zoneState + ';' + timestamp + ';false';
}
var machineState = (zoneState == 'running' || zoneState == 'shutting_down')
? 'running'
: 'stopped';
function onSaveState(stateErr) {
if (stateErr) {
cb(stateErr);
return;
}
self.getVm(uuid, onGetVm);
}
function onGetVm(readErr, cached) {
if (readErr) {
cb(readErr);
return;
}
if (!cached) {
cached = { uuid: uuid };
}
// The first time we see a zone its server_uuid is null because it
// probably was automatically allocated by DAPI
if (!cached['server_uuid']) {
cached['server_uuid'] = server;
}
cached.state = machineState;
cached['zone_state'] = stateStamp;
self.setVm(uuid, common.translateVm(cached, false),
function (writeErr) {
if (writeErr) {
cb(writeErr);
return;
}
cb();
});
}
self.setState(uuid, stateStamp, onSaveState);
};
Cache.prototype.existsVm = function (uuid, callback) {
var vmKey = sprintf(VM_KEY, uuid);
this.exists(vmKey, callback);
};
module.exports = Cache;
|
JavaScript
| 0 |
@@ -1733,32 +1733,104 @@
ct, callback) %7B%0A
+ // ZAPI-163%0A this.log.debug('Calling hmset with', hash, object);%0A
return this.
|
dd08e56b96d382f63d14d97586488105179ede5d
|
Fix e2e test failure due to config property change.
|
core/tests/protractor_utils/users.js
|
core/tests/protractor_utils/users.js
|
// Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities for user creation, login and privileging when
* carrying out end-to-end testing with protractor.
*
* @author Jacob Davis ([email protected])
*/
var forms = require('./forms.js');
var general = require('./general.js');
var admin = require('./admin.js');
var login = function(email, isSuperAdmin) {
// Use of element is not possible because the login page is non-angular.
// The full url is also necessary.
var driver = browser.driver;
driver.get(general.SERVER_URL_PREFIX + general.LOGIN_URL_SUFFIX);
driver.findElement(protractor.By.name('email')).clear();
driver.findElement(protractor.By.name('email')).sendKeys(email);
if (isSuperAdmin) {
driver.findElement(protractor.By.name('admin')).click();
}
driver.findElement(protractor.By.id('submit-login')).click();
};
var logout = function() {
var driver = browser.driver;
driver.get(general.SERVER_URL_PREFIX + general.LOGIN_URL_SUFFIX);
driver.findElement(protractor.By.id('submit-logout')).click();
};
// The user needs to log in immediately before this method is called. Note
// that this will fail if the user already has a username.
var _completeSignup = function(username) {
browser.get('/signup?return_url=http%3A%2F%2Flocalhost%3A4445%2F');
element(by.css('.protractor-test-username-input')).sendKeys(username);
element(by.css('.protractor-test-agree-to-terms-checkbox')).click();
element(by.css('.protractor-test-register-user')).click();
};
var createUser = function(email, username) {
login(email);
_completeSignup(username);
general.waitForSystem();
logout();
};
var createAndLoginUser = function(email, username) {
login(email);
_completeSignup(username);
};
var createModerator = function(email, username) {
login(email, true);
_completeSignup(username);
admin.editConfigProperty(
'Email addresses of moderators', 'List', function(listEditor) {
listEditor.addItem('Unicode').setValue(email);
});
logout();
};
var createAdmin = function(email, username) {
login(email, true);
_completeSignup(username);
admin.editConfigProperty(
'Email addresses of admins', 'List', function(listEditor) {
listEditor.addItem('Unicode').setValue(email);
});
logout();
};
exports.login = login;
exports.logout = logout;
exports.createUser = createUser;
exports.createAndLoginUser = createAndLoginUser;
exports.createModerator = createModerator;
exports.createAdmin = createAdmin;
|
JavaScript
| 0 |
@@ -2460,37 +2460,31 @@
rty(%0A '
-Email address
+Usernam
es of modera
@@ -2556,37 +2556,40 @@
code').setValue(
-email
+username
);%0A %7D);%0A logou
@@ -2733,21 +2733,15 @@
'
-Email address
+Usernam
es o
@@ -2825,21 +2825,24 @@
etValue(
-email
+username
);%0A %7D);
|
f80ba68d2026c8663f9036b23ac53d45b02d172b
|
fix in ngcontroller
|
templates/ngcontroller.js
|
templates/ngcontroller.js
|
(function (angular) {
'use strict'
// https://github.com/johnpapa/angularjs-styleguide#controllers
angular
.module('$1')
.controller('$2', $2)
/* @ngInject */
function $2 ($scope) {
var vm = this
activate()
// -------
function activate () {
}
// deregister event handlers
$scope.$on('$destroy', function () {})
}
}(window.angular))
|
JavaScript
| 0.000001 |
@@ -185,16 +185,17 @@
ion $2 (
+%5C
$scope)
@@ -323,20 +323,23 @@
+%5C
$scope.
+%5C
$on('
+%5C
$des
|
a4b921e236449687b515bf3a51710e00164a1930
|
Make search selector more selective
|
packages/telescope-search/lib/client/views/search.js
|
packages/telescope-search/lib/client/views/search.js
|
// see: http://stackoverflow.com/questions/1909441/jquery-keyup-delay
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Meteor.startup(function () {
Template[getTemplate('search')].helpers({
canSearch: function () {
return canView(Meteor.user());
},
searchQuery: function () {
return Session.get("searchQuery");
},
searchQueryEmpty: function () {
return !!Session.get("searchQuery") ? '' : 'empty';
}
});
Template[getTemplate('search')].events({
'keyup, search .search-field': function(e){
e.preventDefault();
var val = $(e.target).val(),
$search = $('.search');
if(val==''){
// if search field is empty, just do nothing and show an empty template
$search.addClass('empty');
Session.set('searchQuery', '');
Router.go('/search', null, {replaceState: true});
}else{
// if search field is not empty, add a delay to avoid firing new searches for every keystroke
delay(function(){
Session.set('searchQuery', val);
$search.removeClass('empty');
// Update the querystring.
var opts = {query: 'q=' + encodeURIComponent(val)};
// if we're already on the search page, do a replaceState. Otherwise,
// just use the pushState default.
if(getCurrentRoute().indexOf('/search') === 0) {
opts.replaceState = true;
}
Router.go('search', null, opts);
}, 700 );
}
}
});
});
|
JavaScript
| 0.000237 |
@@ -599,16 +599,30 @@
'keyup
+ .search-field
, search
|
0d3ddfdc36d4315b1b6764d50348bfe978e9ee51
|
Add todo to get charts when getting user. Remove old commented code.
|
shared/model/user.js
|
shared/model/user.js
|
/*
* Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved.
*
* This file is part of BoxCharter.
*
* BoxCharter is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* BoxCharter is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BoxCharter. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* User model.
* @module user
*/
const { db, pgp } = require('../../server/db/db_connection')
const { checkPass } = require('../../server/utilities/password_utils')
/**
* User object.
* @class
*/
class User {
/**
* User constructor
* @constructor
* @param {string} id - user_id
* @param {string} email - email
* @param {string} firstName - first name
* @param {string} lastName - last name
* @param {string} salt - password salt
* @param {string} hash - password hash
*/
constructor(id, email, firstName, lastName, salt, hash) {
this.id = id
this.email = email
this.firstName = firstName
this.lastName = lastName
this.salt = salt
this.hash = hash
}
}
/**
* Return a User object for the given criteria.
* @function
* @param {string} lookupColumn - The column for which the given data applies
* @param {string} userData - The user data for the colum indicated
* @return {Promise} - Returns a Promise which resolves to a User object,
* or null if no user found.
*/
User.getUser = function (lookupColumn, userData) {
const query = `SELECT * FROM users WHERE ${lookupColumn}=$1`
return db.one(query, [userData])
.then(u =>
new User(
u.user_id,
u.email,
u.first_name,
u.last_name,
u.password_salt,
u.password_hash)
)
.catch((err) => {
if (err.code === pgp.queryResultErrorCode.noData) {
return null
}
throw err
})
}
/**
* Return a User object for a given email.
* @function
* @param {string} email - Email for which to find a user.
* @return {Promise} - Returns a Promise which resolves to a User object,
* or null if no user found.
*/
User.getByEmail = function (email) {
return User.getUser('email', email)
}
/**
* Return a User object for a given user_id.
* @function
* @param {number} id - ID for which to find a user.
* @return {Promise} - Returns a Promise which resolves to a User object,
* or null if no user found.
*/
User.getById = function (id) {
return User.getUser('user_id', id)
}
/**
* Check password against entered password.
* @method
* @param {string} enteredPass - Password entered.
* @returns {boolean} - Whether or not the password matched.
*/
User.prototype.checkPassword = function (enteredPass) {
return checkPass(this, enteredPass)
}
// var Sequelize = require('Sequelize')
// var db = require('./db')
// var procError = require('../utilities/err')
//
// //////////////////////////////////////////////////////////////////////////////
// // User
// //////////////////////////////////////////////////////////////////////////////
//
// //////////
// // table
// const User = db.sequelize.define('user', {
// userId: {
// type: Sequelize.INTEGER,
// autoIncrement: true,
// primaryKey: true,
// },
// email: {
// type: Sequelize.STRING,
// allowNull: false,
// unique: true,
// },
// passwordHash: {
// type: Sequelize.STRING,
// allowNull: false,
// },
// passwordSalt: {
// type: Sequelize.STRING,
// allowNull: false,
// },
// firstName: {
// type: Sequelize.STRING,
// },
// lastName: {
// type: Sequelize.STRING,
// },
// // don't need joinedAt, since timestamps is true by default, and
// // createdAt, updatedAt will automatically be populated
// })
//
//
// ///////////
// // methods
// // // Adding a class level method
// // User.classLevelMethod = function() {
// // return 'foo';
// // };
//
// User.getUser = function(whereClause) {
// return this.find({
// where: whereClause,
// attributes: {
// exclude: [
// 'passwordHash',
// 'passwordSalt',
// ]
// },
// raw: true
// })
// .then(u => {
//
// // TODO: actually make list of charts here, not just dummy!
// u.charts = []
//
// return Promise.resolve(u)
//
// })
// }
//
// User.getByEmail = function(targetEmail) {
// return this.getUser({email: targetEmail})
// }
//
// User.getById = function(targetId) {
// return this.getUser({userId: targetId})
// }
//
// // // Adding an instance level method
// // User.prototype.instanceLevelMethod = function() {
// // return 'bar';
// // };
//
// // def get_data(self):
// // """Return a dict of user details."""
// //
// // charts = [
// // { 'title': chart.title,
// // 'chartId': chart.chart_id,
// // 'createdAt': chart.created_at,
// // 'updatedAt': chart.modified_at }
// // for chart in self.charts
// // ]
// //
// // return {
// // 'charts': charts,
// // 'userId': self.user_id,
// // 'email': self.email,
// // 'firstName': self.first_name,
// // 'lastName': self.last_name
// // }
module.exports = {
User,
}
|
JavaScript
| 0 |
@@ -2130,16 +2130,52 @@
rd_hash)
+%0A%0A // TODO: get charts here too
%0A )%0A
@@ -3220,2558 +3220,8 @@
%0A%7D%0A%0A
-// var Sequelize = require('Sequelize')%0A// var db = require('./db')%0A// var procError = require('../utilities/err')%0A//%0A// //////////////////////////////////////////////////////////////////////////////%0A// // User%0A// //////////////////////////////////////////////////////////////////////////////%0A//%0A// //////////%0A// // table%0A// const User = db.sequelize.define('user', %7B%0A// userId: %7B%0A// type: Sequelize.INTEGER,%0A// autoIncrement: true,%0A// primaryKey: true,%0A// %7D,%0A// email: %7B%0A// type: Sequelize.STRING,%0A// allowNull: false,%0A// unique: true,%0A// %7D,%0A// passwordHash: %7B%0A// type: Sequelize.STRING,%0A// allowNull: false,%0A// %7D,%0A// passwordSalt: %7B%0A// type: Sequelize.STRING,%0A// allowNull: false,%0A// %7D,%0A// firstName: %7B%0A// type: Sequelize.STRING,%0A// %7D,%0A// lastName: %7B%0A// type: Sequelize.STRING,%0A// %7D,%0A// // don't need joinedAt, since timestamps is true by default, and%0A// // createdAt, updatedAt will automatically be populated%0A// %7D)%0A//%0A//%0A// ///////////%0A// // methods%0A// // // Adding a class level method%0A// // User.classLevelMethod = function() %7B%0A// // return 'foo';%0A// // %7D;%0A//%0A// User.getUser = function(whereClause) %7B%0A// return this.find(%7B%0A// where: whereClause,%0A// attributes: %7B%0A// exclude: %5B%0A// 'passwordHash',%0A// 'passwordSalt',%0A// %5D%0A// %7D,%0A// raw: true%0A// %7D)%0A// .then(u =%3E %7B%0A//%0A// // TODO: actually make list of charts here, not just dummy!%0A// u.charts = %5B%5D%0A//%0A// return Promise.resolve(u)%0A//%0A// %7D)%0A// %7D%0A//%0A// User.getByEmail = function(targetEmail) %7B%0A// return this.getUser(%7Bemail: targetEmail%7D)%0A// %7D%0A//%0A// User.getById = function(targetId) %7B%0A// return this.getUser(%7BuserId: targetId%7D)%0A// %7D%0A//%0A// // // Adding an instance level method%0A// // User.prototype.instanceLevelMethod = function() %7B%0A// // return 'bar';%0A// // %7D;%0A//%0A// // def get_data(self):%0A// // %22%22%22Return a dict of user details.%22%22%22%0A// //%0A// // charts = %5B%0A// // %7B 'title': chart.title,%0A// // 'chartId': chart.chart_id,%0A// // 'createdAt': chart.created_at,%0A// // 'updatedAt': chart.modified_at %7D%0A// // for chart in self.charts%0A// // %5D%0A// //%0A// // return %7B%0A// // 'charts': charts,%0A// // 'userId': self.user_id,%0A// // 'email': self.email,%0A// // 'firstName': self.first_name,%0A// // 'lastName': self.last_name%0A// // %7D%0A%0A
modu
|
fbf4aa40f1a0ad567654ff0be3fd5dfd3ffdadb0
|
Clean up
|
script.js
|
script.js
|
var res
function convertTemp (to, from) {
if (to === 'K') return from // If Kelvin, just return it
else if (to === 'C') return from - 273.15 // If Celsius, calculate and return Celsius, simple enough
else from *= 1.8 // Both Rankine and Fahrenheit multiply Kelvin by 1.8
if (to === 'F') return from - 459.67 // If Fahrenheit, calculate and return Fahrenheit..
else return from // otherwise, return Rankine
}
function decimalRound (dp, num) {
return Math.round(num * (Math.pow(10, dp))) / Math.pow(10, dp)
}
function getTemp (unit, dp, temperature) {
// Convert to correct unit and round to correct decimal points
return decimalRound(dp, convertTemp(unit, temperature))
}
function setTemp (temperature, unit = 'C', dp = 2) {
window.temp.innerHTML = getTemp(unit, dp, temperature) + '°' + unit
}
// TODO
function getCond (conditions, id) {
var prefix = ''
// Determine the appropriate prefix based on weather ids found here:
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
if (id >= 200 && id <= 399 ||
id === 781 ||
id >= 900 && id <= 902 ||
id >= 952 && id <= 956 ||
id >= 958 && id <= 962) prefix = 'there is a'
else if (id >= 500 && id <= 721 ||
id >= 741 && id <= 761 ||
id === 906 || id === 957) prefix = 'there is'
else if (id === 731 || id === 771 ||
id >= 802 && id <= 804) prefix = 'there are'
else if (id === 800) prefix = 'the'
else if (id === 801) prefix = 'there are a'
else if (id >= 903 && id <= 905 ||
id === 950 || id === 951) prefix = "it's"
return prefix + ' ' + conditions.toLowerCase()
}
function setCond (weather) {
window.cond.innerHTML = getCond(weather.description, weather.id)
}
function setBgColor (res, unit = 'C') {
let roundTemp = Math.round(temperature)
document.body.style.backgroundColor = `rgb(${128 + roundTemp}, 0, ${128 - roundTemp}`
}
function cycleUnit () {
switch (window.temp.innerHTML.split('°')[1]) {
case 'C': setTemp(res.main.temp, 'F'); break
case 'F': setTemp(res.main.temp, 'K'); break
case 'K': setTemp(res.main.temp, 'R'); break
case 'R': setTemp(res.main.temp, 'C'); break
}
}
var req = new window.XMLHttpRequest()
req.addEventListener('load', () => {
console.log(req.responseURL)
// Make res global?
res = JSON.parse(req.responseText)
setTemp(res.main.temp)
setCond(res.weather[0])
})
document.addEventListener('DOMContentLoaded', () => {
// TODO: Move out of DOMContentLoaded
// Get the users geolocation
navigator.geolocation.getCurrentPosition((pos) => {
let [lat, lon] = [decimalRound(2, pos.coords.latitude), decimalRound(2, pos.coords.longitude)]
console.log(lat, lon)
// Complete the Ajax request to OpenWeatherMap with user geolocation and send
req.open('GET', `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}`, true)
req.send()
})
// Click on the temperature to change unit of measurement
window.temp.addEventListener('click', cycleUnit)
})
|
JavaScript
| 0 |
@@ -883,16 +883,8 @@
%0A%7D%0A%0A
-// TODO%0A
func
@@ -1807,181 +1807,8 @@
%0A%7D%0A%0A
-function setBgColor (res, unit = 'C') %7B%0A let roundTemp = Math.round(temperature)%0A document.body.style.backgroundColor = %60rgb($%7B128 + roundTemp%7D, 0, $%7B128 - roundTemp%7D%60%0A%7D%0A%0A
func
@@ -2158,61 +2158,8 @@
%3E %7B%0A
- console.log(req.responseURL)%0A // Make res global?%0A
re
@@ -2304,49 +2304,8 @@
=%3E %7B
-%0A%0A // TODO: Move out of DOMContentLoaded
%0A /
@@ -2390,19 +2390,19 @@
%3E %7B%0A
-let
+var
%5Blat, l
@@ -2408,32 +2408,16 @@
lon%5D = %5B
-decimalRound(2,
pos.coor
@@ -2431,25 +2431,8 @@
tude
-), decimalRound(2
, po
@@ -2453,36 +2453,10 @@
tude
-)
%5D%0A
- console.log(lat, lon)
%0A
|
f7cdc4de26ff6bb1016ee5b57b80acd739f7b939
|
Correctly assigning the original row index
|
src/DGTable.RowCollection.js
|
src/DGTable.RowCollection.js
|
/*
The MIT License (MIT)
Copyright (c) 2014 Daniel Cohen Gindi ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* global DGTable, _, Backbone */
DGTable.RowCollection = (function () {
'use strict';
// Define class RowCollection
var RowCollection = function() {
// Instantiate an Array. Seems like the `.length = ` of an inherited Array does not work well.
// I will not use the IFRAME solution either in fear of memory leaks, and we're supporting large datasets...
var collection = [];
// Synthetically set the 'prototype'
_.extend(collection, RowCollection.prototype);
// Call initializer
collection.initialize.apply(collection, arguments);
return collection;
};
// Inherit Array
RowCollection.prototype = [];
// Add events model from Backbone
_.extend(RowCollection.prototype, Backbone.Events);
RowCollection.prototype.initialize = function(options) {
options = options || {};
/** @field {String} filterColumn */
this.filterColumn = null;
/** @field {String} filterString */
this.filterString = null;
/** @field {Boolean} filterCaseSensitive */
this.filterCaseSensitive = false;
/** @field {string} sortColumn */
this.sortColumn = options.sortColumn == null ? [] : options.sortColumn;
};
/**
* @param {Object|Object[]} rows Row or array of rows to add to this collection
* @param {number?} at Position to insert rows. This will prevent the sort if it is active.
*/
RowCollection.prototype.add = function (rows, at) {
var isArray = ('splice' in rows && 'length' in rows), i, len;
if (isArray) {
if (at) {
for (i = 0, len = rows.length; i < len; i++) {
this.splice(at++, 0, rows[i]);
}
} else {
for (i = 0, len = rows.length; i < len; i++) {
this.push(rows[i]);
}
}
} else {
if (at) {
this.splice(at, 0, rows);
} else {
this.push(rows);
}
}
};
/**
* @param {Object|Object[]=} rows Row or array of rows to add to this collection
*/
RowCollection.prototype.reset = function (rows) {
this.length = 0;
if (rows) {
this.add(rows);
}
};
/**
* @param {string} columnName name of the column to filter on
* @param {string} filter keyword to filter by
* @param {boolean=false} caseSensitive is the filter case sensitive?
* @returns {DGTable.RowCollection} success result
*/
RowCollection.prototype.filteredCollection = function (columnName, filter, caseSensitive) {
filter = filter.toString();
if (filter && columnName != null) {
var rows = new RowCollection({ sortColumn: this.sortColumn });
this.filterColumn = columnName;
this.filterString = filter;
this.filterCaseSensitive = caseSensitive;
var originalRowIndex = 0;
for (var i = 0, len = this.length, row; i < len; i++) {
row = this[i];
if (this.shouldBeVisible(row)) {
row['__i'] = originalRowIndex++;
rows.push(row);
}
}
return rows;
} else {
this.filterColumn = null;
this.filterString = null;
return null;
}
};
/**
* @param {Array} row
* @returns {boolean}
*/
RowCollection.prototype.shouldBeVisible = function (row) {
if (row && this.filterColumn) {
var actualVal = row[this.filterColumn];
if (actualVal == null) {
return false;
}
actualVal = actualVal.toString();
var filterVal = this.filterString;
if (!this.filterCaseSensitive) {
actualVal = actualVal.toUpperCase();
filterVal = filterVal.toUpperCase();
}
return actualVal.indexOf(filterVal) !== -1;
}
return true;
};
(function(){
var nativeSort = RowCollection.prototype.sort;
function getDefaultComparator(column, descending) {
var lessVal = descending ? 1 : -1, moreVal = descending ? -1 : 1;
return function(leftRow, rightRow) {
var col = column, leftVal = leftRow[col], rightVal = rightRow[col];
return leftVal < rightVal ? lessVal : (leftVal > rightVal ? moreVal : 0);
};
}
/**
* @param {Boolean=false} silent
* @returns {DGTable.RowCollection} self
*/
RowCollection.prototype.sort = function(silent) {
if (this.sortColumn.length) {
var comparators = [], i, returnVal;
for (i = 0; i < this.sortColumn.length; i++) {
returnVal = {};
this.trigger('requiresComparatorForColumn', returnVal, this.sortColumn[i].column, this.sortColumn[i].descending);
comparators.push(_.bind(returnVal.comparator || getDefaultComparator(this.sortColumn[i].column, this.sortColumn[i].descending), this));
}
if (comparators.length === 1) {
nativeSort.call(this, comparators[0]);
} else {
var len = comparators.length,
value,
comparator = function(leftRow, rightRow) {
for (i = 0; i < len; i++) {
value = comparators[i](leftRow, rightRow);
if (value !== 0) {
return value;
}
}
return value;
};
nativeSort.call(this, comparator);
}
if (!silent) {
this.trigger('sort');
}
}
return this;
};
})();
return RowCollection;
})();
|
JavaScript
| 0.998902 |
@@ -4100,46 +4100,8 @@
ve;%0A
- var originalRowIndex = 0;%0A
@@ -4281,26 +4281,9 @@
%5D =
-originalRowIndex++
+i
;%0A
|
f4345cb42d1e2efb7e643f0ef020253e9fafc1a6
|
add comments
|
src/victory-util/add-events.js
|
src/victory-util/add-events.js
|
import React from "react";
import {
defaults, assign, isFunction, partialRight, pick, without, isEqual, cloneDeep, get
} from "lodash";
import Events from "./events";
import VictoryTransition from "../victory-transition/victory-transition";
const areVictoryPropsEqual = (a, b) => (
Object.keys(a).reduce((equal, key) => {
if (!equal) { return false; } // exit early if inequality found
const aProp = a[key];
const bProp = b[key];
if (key === "sharedEvents") { // go deeper on these props
return areVictoryPropsEqual(aProp, bProp);
} else if (key === "getEvents" || key === "getEventState") {
return true; // mark these props equal at all times
} else {
return isEqual(aProp, bProp);
}
}, true)
);
export default (WrappedComponent) => {
return class addEvents extends WrappedComponent {
componentWillMount() {
if (isFunction(super.componentWillMount)) {
super.componentWillMount();
}
this.state = this.state || {};
this.stateCopy = {}; // start with an empty object so any change triggers rerender
const getScopedEvents = Events.getScopedEvents.bind(this);
this.getEvents = partialRight(Events.getEvents.bind(this), getScopedEvents);
this.getEventState = Events.getEventState.bind(this);
this.setupEvents(this.props);
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.animating || get(nextProps, "sharedEvents.events.length")) {
return true;
}
const stateChange = !isEqual(this.stateCopy, nextState);
this.stateCopy = cloneDeep(this.state); // save state copy, as events.js must mutate in-place
if (stateChange) {
return true;
}
if (!areVictoryPropsEqual(this.props, nextProps)) {
return true;
}
return false;
}
componentWillUpdate(newProps) {
if (isFunction(super.componentWillReceiveProps)) {
super.componentWillReceiveProps();
}
this.setupEvents(newProps);
}
setupEvents(props) {
const { sharedEvents } = props;
const components = WrappedComponent.expectedComponents;
this.componentEvents = Events.getComponentEvents(props, components);
this.getSharedEventState = sharedEvents && isFunction(sharedEvents.getEventState) ?
sharedEvents.getEventState : () => undefined;
this.baseProps = this.getBaseProps(props);
this.dataKeys = Object.keys(this.baseProps).filter((key) => key !== "parent");
this.hasEvents = props.events || props.sharedEvents || this.componentEvents;
this.events = this.getAllEvents(props);
}
getBaseProps(props) {
const sharedParentState = this.getSharedEventState("parent", "parent");
const parentState = this.getEventState("parent", "parent");
const baseParentProps = defaults({}, parentState, sharedParentState);
const parentPropsList = baseParentProps.parentControlledProps;
const parentProps = parentPropsList ? pick(baseParentProps, parentPropsList) : {};
const modifiedProps = defaults({}, parentProps, props);
return isFunction(WrappedComponent.getBaseProps) ?
WrappedComponent.getBaseProps(modifiedProps) : {};
}
getAllEvents(props) {
if (Array.isArray(this.componentEvents)) {
return Array.isArray(props.events) ?
this.componentEvents.concat(...props.events) : this.componentEvents;
}
return props.events;
}
getComponentProps(component, type, index) {
const { role } = WrappedComponent;
const key = this.dataKeys && this.dataKeys[index] || index;
const baseProps = this.baseProps[key][type] || this.baseProps[key];
if (!baseProps && !this.hasEvents) {
return undefined;
}
if (this.hasEvents) {
const baseEvents = this.getEvents(this.props, type, key);
const componentProps = defaults(
{ index, key: `${role}-${type}-${key}` },
this.getEventState(key, type),
this.getSharedEventState(key, type),
component.props,
baseProps
);
const events = defaults(
{}, Events.getPartialEvents(baseEvents, key, componentProps), componentProps.events
);
return assign(
{}, componentProps, { events }
);
}
return defaults(
{ index, key: `${role}-${type}-${key}` },
component.props,
baseProps
);
}
renderContainer(component, children) {
const isContainer = component.type && component.type.role === "container";
const parentProps = isContainer ? this.getComponentProps(component, "parent", "parent") : {};
return React.cloneElement(component, parentProps, children);
}
animateComponent(props, animationWhitelist) {
return (
<VictoryTransition animate={props.animate} animationWhitelist={animationWhitelist}>
{React.createElement(this.constructor, props)}
</VictoryTransition>
);
}
// Used by `VictoryLine` and `VictoryArea`
renderContinuousData(props) {
const { dataComponent, labelComponent, groupComponent } = props;
const dataKeys = without(this.dataKeys, "all");
const labelComponents = dataKeys.reduce((memo, key) => {
const labelProps = this.getComponentProps(labelComponent, "labels", key);
if (labelProps && labelProps.text !== undefined && labelProps.text !== null) {
memo = memo.concat(React.cloneElement(labelComponent, labelProps));
}
return memo;
}, []);
const dataProps = this.getComponentProps(dataComponent, "data", "all");
const children = [React.cloneElement(dataComponent, dataProps), ...labelComponents];
return this.renderContainer(groupComponent, children);
}
renderData(props) {
const { dataComponent, labelComponent, groupComponent } = props;
const dataComponents = this.dataKeys.map((_dataKey, index) => {
const dataProps = this.getComponentProps(dataComponent, "data", index);
return React.cloneElement(dataComponent, dataProps);
});
const labelComponents = this.dataKeys.map((_dataKey, index) => {
const labelProps = this.getComponentProps(labelComponent, "labels", index);
if (labelProps.text !== undefined && labelProps.text !== null) {
return React.cloneElement(labelComponent, labelProps);
}
return undefined;
}).filter(Boolean);
const children = [...dataComponents, ...labelComponents];
return this.renderContainer(groupComponent, children);
}
};
};
|
JavaScript
| 0 |
@@ -1021,73 +1021,168 @@
y =
-%7B%7D; // start with an empty object so any change triggers rerender
+cloneDeep(%7B ...this.state %7D); // idk why cloneDeep(this.state) doesn't work,%0A // but using cloneDeep(this.state) fails, as the first state change is missed
%0A
@@ -1485,24 +1485,33 @@
%7B%0A if (
+%0A
this.props.a
@@ -1519,16 +1519,93 @@
imating
+// cannot use props.animate, as this is set to null during animation%0A
%7C%7C get(n
@@ -1643,16 +1643,44 @@
length%22)
+ // for parent events%0A
) %7B%0A
@@ -1701,24 +1701,271 @@
e;%0A %7D%0A%0A
+ // save state copy; state is edited in-place so this.state is the SAME OBJECT has nextState.%0A // i tried to replace _.extend in events.js with data copies, but that broke events;%0A // there must be logic that relies on the mutation%0A
const
@@ -2064,62 +2064,8 @@
te);
- // save state copy, as events.js must mutate in-place
%0A
|
71b835d057de94244bc4e8877a30f41ec1da6ea1
|
Fix for gulp watch
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var notify = require("gulp-notify");
var preen = require('preen');
var sourcemaps = require('gulp-sourcemaps');
var imagemin = require('gulp-imagemin');
var autoprefixer = require('gulp-autoprefixer');
var jshint = require('gulp-jshint');
var path = require('path');
var del = require('del');
var pump = require('pump');
var paths = {
sass: ['scss/**/*.scss'],
index: 'app/index.html',
scripts: ['app/js/app.js', 'app/js/**/*.js'],
styles: 'app/scss/**/*.*',
templates: 'app/templates/**/*.*',
images: 'app/img/**/*.*',
lib: 'www/lib/**/*.*',
//Destination folders
destImages: './www/img/',
destTemplates: './www/templates/'
};
gulp.task('serve:before', ['watch']);
gulp.task('default', ['sass', 'index', 'scripts', 'styles', 'templates', 'images', 'lib']);
gulp.task('serve', function (done) {
sh.exec('ionic serve', done);
});
gulp.task('sass', function (done) {
gulp.src('./scss/ionic.app.scss')
.pipe(sass())
.on('error', sass.logError)
.pipe(gulp.dest('./www/css/'))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest('./www/css/'))
.on('end', done);
});
gulp.task('index', function () {
return gulp.src(paths.index)
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(gulp.dest("./www/"))
.pipe(notify({ message: 'Index built' }));
});
gulp.task('scripts', function (done) {
pump([
gulp.src(paths.scripts),
jshint(),
jshint.reporter('default', { verbose: true }),
//jshint.reporter('fail'), //Fail if jshint show errors in console
sourcemaps.init(),
concat("app.js"),
sourcemaps.write(),
gulp.dest("./www/build/"),
rename('app.min.js'),
uglify(),
gulp.dest("./www/build/"),
notify({ message: 'Scripts built' })
],
done
);
});
gulp.task('styles', function () {
return gulp.src(paths.styles)
.pipe(sourcemaps.init())
.pipe(sass())
.on('error', sass.logError)
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(concat('style.css'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./www/css/'))
.pipe(rename({ suffix: '.min' }))
.pipe(minifyCss())
.pipe(gulp.dest('./www/css/'))
.pipe(notify({ message: 'Styles built' }));
});
function MinifyTemplates(path, destPath) {
return gulp.src(path)
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(gulp.dest(destPath || paths.destTemplates));
}
gulp.task('templates', ['clean-templates'], function (done) {
MinifyTemplates(paths.templates).on('end', function () {
gulp.src('').pipe(notify({ message: 'Templates built' }));
done();
});
});
function MinifyImages(path, destPath) {
return gulp.src(path)
.pipe(imagemin({ optimizationLevel: 5 }))
.pipe(gulp.dest(destPath || paths.destImages));
}
gulp.task('images', ['clean-images'], function (done) {
MinifyImages(paths.images).on('end', function () {
gulp.src('').pipe(notify({ message: 'Images built' }));
done();
});
});
gulp.task('lib', function (done) {
//https://forum.ionicframework.com/t/how-to-manage-bower-overweight/17997/10?u=jdnichollsc
preen.preen({}, function () {
gulp.src('').pipe(notify({ message: 'Lib built' }));
done();
});
});
gulp.task('clean-images', function () {
return del(paths.destImages);
});
gulp.task('clean-templates', function () {
return del(paths.destTemplates);
});
gulp.task('watch', function () {
gulp.watch(paths.sass, ['sass']);
gulp.watch(paths.index, ['index']);
gulp.watch(paths.scripts, ['scripts']);
gulp.watch(paths.styles, ['styles']);
gulp.watch(paths.templates, function (event) {
var destPathFile = path.join('./www', path.relative(path.join(__dirname, './app'), event.path));
if (event.type === "deleted") {
del(destPathFile);
} else {
var pathFile = path.relative(__dirname, event.path);
var destPath = path.dirname(destPathFile);
MinifyTemplates(pathFile, destPath).on('end', function () {
gulp.src('').pipe(notify({ message: 'Template built' }));
});
}
});
gulp.watch(paths.images, function (event) {
var destPathFile = path.join('./www', path.relative(path.join(__dirname, './app'), event.path));
if (event.type === "deleted") {
del(destPathFile);
} else {
var pathFile = path.relative(__dirname, event.path);
var destPath = path.dirname(destPathFile);
MinifyImages(pathFile, destPath).on('end', function () {
gulp.src('').pipe(notify({ message: 'Image built' }));
});
}
});
gulp.watch(paths.lib, ['lib']);
});
gulp.task('install', ['git-check'], function () {
return bower.commands.install()
.on('log', function (data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
gulp.task('git-check', function (done) {
if (!sh.which('git')) {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
}
done();
});
/* GitHub Page - http(s)://<username>.github.io/<projectname>
TODO: Execute the following steps if you don't want to publish your code to GitHub Pages like a demo.
- Uninstall the gulp plugins from package.json:
npm uninstall gulp-gh-pages --save-dev
npm uninstall merge2 --save-dev
- Remove the folder './gh-pages'
- Remove the code below
*/
var ghPages = require('gulp-gh-pages');
var merge2 = require('merge2');
gulp.task('deploy-files', function () {
var sourcePath = [
'./www/**/*',
'!./www/pre.db'
];
return merge2(
gulp.src('./gh-pages/**/*'),
gulp.src(sourcePath, { base: './' })
)
.pipe(ghPages());
});
gulp.task('deploy', ['deploy-files'], function () {
return gulp.src('').pipe(notify({ message: 'GitHub Page updated' }));
});
|
JavaScript
| 0 |
@@ -1022,21 +1022,27 @@
p.task('
-serve
+ionic:watch
:before'
@@ -1053,17 +1053,16 @@
watch'%5D)
-;
%0A%0Agulp.t
@@ -6884,16 +6884,18 @@
pdated' %7D));%0A%7D);
+%0A%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.