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
|
---|---|---|---|---|---|---|---|
ede9c96dd235b0947aa82081606c2557e6e8ddbb
|
Update the template strings to use the right Meetup API base
|
api/auth/index.js
|
api/auth/index.js
|
'use strict';
const Wreck = require('Wreck');
const Joi = require('Joi');
const Boom = require('Boom');
const jwt = require('jsonwebtoken');
function register(server, options, next) {
const meetup = server.settings.app.meetup;
function getOauthParams(options) {
return `client_id=${meetup.oauthClientId}&client_secret=${meetup.oauthClientSecret}&grant_type=${options.grant_type}&redirect_uri=http%3A%2F%2Flocalhost%3A8080`;
}
server.route({
method: 'GET',
path: '/oauth2/authorize',
config: {
handler(request, reply) {
let url = `${server.settings.app.meetup.authBase}/oauth2/authorize?client_id=${meetup.oauthClientId}&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080`;
reply.redirect(url);
}
}
});
server.route({
method: 'POST',
path: '/oauth2/access',
config: {
validate: {
query: {
code: Joi.string().required()
}
},
handler(request, reply) {
let queryParams = `${getOauthParams({grant_type: 'authorization_code'})}&code=${request.query.code}`;
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
payload: queryParams
};
Wreck.post(`${server.settings.app.meetup.authBase}/oauth2/access`, config, (err, response, payload) => {
if (err) {
reply(Boom.badImplementation('Server error, could not complete authentication'));
}
if (response.statusCode === 200) {
let json = JSON.parse(payload);
let token = jwt.sign(json, server.settings.app.jwtKey, {algorithm: 'HS256'});
reply({token: token});
} else {
console.log(JSON.parse(payload));
reply(Boom.create(response.statusCode, 'Meetup could not complete authentication', payload));
}
});
}
}
});
server.route({
method: 'POST',
path: '/oauth2/refresh',
config: {
auth: 'token',
handler(request, reply) {
let queryParams = `${getOauthParams({grant_type: 'refresh_token'})}&refresh_token=${request.auth.credentials.refresh_token}`;
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
payload: queryParams
};
Wreck.post(`${server.settings.app.meetup.apiBase}/oauth2/access`, config, (err, response, payload) => {
if (err) {
reply(Boom.badImplementation('Server error, could not complete authentication'));
}
if (response.statusCode === 200) {
let json = JSON.parse(payload);
console.log(json);
let token = jwt.sign(json, server.settings.app.jwtKey, {algorithm: 'HS256'});
reply({token: token});
} else {
console.log(JSON.parse(payload));
reply(Boom.create(response.statusCode, 'Meetup could not complete authentication', payload));
}
});
}
}
});
next();
}
register.attributes = {
name: 'auth'
};
module.exports.register = register;
|
JavaScript
| 0 |
@@ -430,24 +430,30 @@
lhost%253A8080
+/login
%60;%0A %7D%0A%0A
@@ -761,16 +761,22 @@
t%253A8080
+/login
%60;%0A
|
ef6bed3927ee73ea91d9adeec447c8abe0fa7e8f
|
Test cases fixes
|
test/widget/controllers/widget.item.spec.controller2.js
|
test/widget/controllers/widget.item.spec.controller2.js
|
describe('Unit : Controller - WidgetItemCtrl2', function () {
// load the controller's module
beforeEach(module('placesWidget'));
var $q, WidgetItem, scope, COLLECTIONS, DB, $routeParams, Buildfire, $rootScope, GeoDistance, Messaging, Location, EVENTS, PATHS, AppConfig, placesInfo, Orders, OrdersItems, item;
beforeEach(inject(function (_$q_, _$routeParams_, $controller, _$rootScope_, _Buildfire_, _DB_, _COLLECTIONS_, _AppConfig_, _Messaging_, _EVENTS_, _PATHS_, _Location_, _Orders_, _GeoDistance_, _$timeout_, _OrdersItems_) {
scope = _$rootScope_.$new();
DB = _DB_;
COLLECTIONS = _COLLECTIONS_;
Orders = _Orders_;
OrdersItems = _OrdersItems_;
Messaging = _Messaging_;
EVENTS = _EVENTS_;
PATHS = _PATHS_;
Location = _Location_;
$q = _$q_;
AppConfig = _AppConfig_;
$routeParams = _$routeParams_;
GeoDistance = _GeoDistance_;
Buildfire = _Buildfire_;
$rootScope = _$rootScope_;
WidgetItem = $controller('WidgetItemCtrl', {
$scope: scope,
$routeParams: $routeParams,
DB: DB,
COLLECTIONS: COLLECTIONS,
Buildfire: Buildfire,
$rootScope: $rootScope,
Orders: Orders,
OrdersItems: OrdersItems,
Messaging: Messaging,
EVENTS: EVENTS,
PATHS: PATHS,
Location: Location,
AppConfig: AppConfig,
placesInfo: null,
GeoDistance: GeoDistance,
item: null
});
})
)
;
describe('Units: units should be Defined', function () {
it('it should pass if WidgetSections is defined', function () {
expect(WidgetItem).not.toBeUndefined();
});
});
});
|
JavaScript
| 0.000001 |
@@ -1805,16 +1805,17 @@
+x
it('it s
|
25ba3e0e9a769fa1de0f52f0e2808312b8b37865
|
add arduino port autolocation
|
servometer-host/lib/servometer.js
|
servometer-host/lib/servometer.js
|
const Readline = require('@serialport/parser-readline')
const SerialPort = require('serialport'),
https = require('https');
function handleSerialData(data) {
console.log('serial incoming -> ', data);
}
function handleSerialError(err) {
console.error('error on serial connection: ', err);
}
/*
servometer host application
This nodeJS application handles requesting metrics data from an API
and sending it over serial USB to the arduino for servo action
@author Jacob Quatier
*/
function ServoMeter(options) {
if (!options) {
throw new Error("ServoMeter options was empty. configure API endpoint and serial port");
}
this._serialPort = options.serialPort;
this._httpOptions = options.httpOptions;
this.formatSerialData = options.formatSerialData;
}
ServoMeter.prototype.start = function() {
var self = this;
console.log('starting ServoMeter');
const port = new SerialPort(self._serialPort);
port.pipe(new Readline({ delimiter: '\n' }))
function refreshMetrics(){
self.refreshMetrics(port);
}
port.on('open', function() {
console.log('serial connection opened on ' + self._serialPort);
// wait 1 second to make sure serial is established
setTimeout(refreshMetrics, 1000)
// refresh every 10 seconds
setInterval(refreshMetrics, 10000)
});
// output any data sent back FROM the arduino (for confirmation)
port.on('data', handleSerialData);
port.on('error', handleSerialError);
};
ServoMeter.prototype.refreshMetrics = function(port) {
var self = this;
// call metrics api using the configured http options object
var req = https.request(self._httpOptions, function(res) {
console.log('recieved API status code: ', res.statusCode, ' -- ', res.headers.date);
var response = '';
// buffer the response until it ends
res.on('data', function(data) {
response += data;
});
res.on('end', function() {
// format & write out the string
port.write(self.formatSerialData(response));
});
});
req.on('error', function(e) {
console.error('Error requesting metrics: ', e);
});
req.end();
}
module.exports = ServoMeter;
|
JavaScript
| 0 |
@@ -293,16 +293,499 @@
rr);%0A%7D%0A%0A
+function findSerialPort() %7B%0A return new Promise((resolve, reject) =%3E %7B%0A SerialPort.list((err, ports) =%3E %7B%0A const arduinoPort = ports.find(port =%3E port.manufacturer && port.manufacturer.includes('arduino'));%0A if (!arduinoPort) %7B%0A return reject(new Error('Unable to auto-locate Arduino port, try configuring the %5BserialPort%5D option'));%0A %7D%0A console.log(%60Found Arduino @ $%7BarduinoPort.comName%7D%60)%0A return resolve(arduinoPort.comName);%0A %7D);%0A %7D);%0A%7D%0A%0A
/*%0A ser
@@ -1286,16 +1286,22 @@
.start =
+ async
functio
@@ -1364,16 +1364,94 @@
ter');%0A%0A
+ if(!self._serialPort) %7B%0A self._serialPort = await findSerialPort();%0A %7D%0A%0A
const
|
67fdc7a898cfc60afb67dfbb6752d36734083908
|
Clear search results when we're kill switched
|
src/actions/search.js
|
src/actions/search.js
|
/*---------------------------------------------------------------------------*\
| search.js |
\*---------------------------------------------------------------------------*/
import { v4 as uuidv4 } from 'uuid';
import store from '../store';
const setQuery = (query, uuid) => ({ type: 'search/setQuery', query, uuid });
const showResults = (results) => ({ type: 'search/showResults', results });
export const setSelected = (index) => ({ type: 'search/setSelected', index });
export const clearSearch = () => ({ type: 'search/clearSearch' });
const EASTER_EGGS = {
porn: [
'https://www.pornhub.com/',
],
rickroll: [
'https://spool.video/rick-astley/never-gonna-give-you-up',
],
};
export const executeSearch = (query) => {
return async (dispatch) => {
if (!query) {
dispatch(clearSearch());
return;
}
const uuid = uuidv4();
dispatch(setQuery(query, uuid));
const normalizedQuery = query.normalize();
if (normalizedQuery in EASTER_EGGS) {
const webpage = EASTER_EGGS[normalizedQuery].choice();
window.location.href = webpage;
}
const urlQueryString = new URLSearchParams(`q=${query}&uuid=${uuid}`);
const url = `${process.env.REACT_APP_API}/v1/songs/search?${urlQueryString}`;
const response = await fetch(url);
if (response.status !== 200) {
console.error(`GET ${url} returned ${response.status} status code`)
return;
}
const data = await response.json();
if (data.metadata.uuid === store.getState().search.uuid) {
dispatch(showResults(data.songs));
recordQuery(query);
}
};
};
const recordQuery = (query) => {
const uuid = uuidv4();
const urlQueryString = new URLSearchParams(`uuid=${uuid}`);
const url = `${process.env.REACT_APP_API}/v1/queries?${urlQueryString}`;
const [method, body] = ['POST', new FormData()];
body.append('q', query);
fetch(url, { method, body })
.catch(console.error);
};
|
JavaScript
| 0 |
@@ -1464,16 +1464,49 @@
code%60)%0A
+ dispatch(showResults(%5B%5D));%0A
re
|
e8cb5e8a607e052be1b046b9c6befbf74b336dd9
|
use the created askus button where we can [PT #177032848]
|
applications/primo2/load.js
|
applications/primo2/load.js
|
function getBranchName() {
let branchName = '/'; // default. Use for prod
if (window.location.hostname === 'search.library.uq.edu.au') {
if (/vid=61UQ_DEV/.test(window.location.href)) {
branchName = '/primo-prod-dev/';
}
} else {
if (/vid=61UQ_DEV/.test(window.location.href)) {
branchName = '/primo-sand-box-dev/';
} else if (/vid=61UQ/.test(window.location.href)) {
branchName = '/primo-sand-box/';
}
}
return branchName;
}
function loadLibraryTitleStyleSheet(shadowDom) {
linkTag = document.createElement('link');
linkTag.setAttribute('href', '//assets.library.uq.edu.au' + getBranchName() + 'reusable-components/primo2/webcomponents/custom-styles.css');
linkTag.setAttribute('rel', 'stylesheet');
shadowDom.appendChild(linkTag);
}
function reAddSiteHeaderTitle(shadowDom) {
console.log('reAddSiteHeaderTitle');
const textOfLink = document.createTextNode('Library');
const siteTitleLinkShadow = document.createElement('a');
siteTitleLinkShadow.setAttribute('id', 'site-title');
siteTitleLinkShadow.setAttribute('href', 'http://www.library.uq.edu.au');
siteTitleLinkShadow.setAttribute('class', 'uq-site-header__title');
siteTitleLinkShadow.appendChild(textOfLink);
const uqSiteHeaderTitleContainerLeftShadow = document.createElement('div');
uqSiteHeaderTitleContainerLeftShadow.setAttribute('class', 'uq-site-header__title-container__left');
uqSiteHeaderTitleContainerLeftShadow.appendChild(siteTitleLinkShadow);
const uqSiteHeaderTitleContainerShadow = document.createElement('div');
uqSiteHeaderTitleContainerShadow.setAttribute('class', 'uq-site-header__title-container');
uqSiteHeaderTitleContainerShadow.appendChild(uqSiteHeaderTitleContainerLeftShadow);
const uqSiteHeaderShadow = document.createElement('div');
uqSiteHeaderShadow.setAttribute('class', 'uq-site-header');
uqSiteHeaderShadow.appendChild(uqSiteHeaderTitleContainerShadow);
shadowDom.appendChild(uqSiteHeaderShadow);
}
function isAskusButtonPresent() {
// we dont want to insert the button more than once, as it listens for it disappearing
const askusButton = document.querySelectorAll('askus-button');
return !!askusButton && askusButton.length > 0;
}
function isAskusButtonInPrimoLoginbar() {
// we dont want to insert the button more than once, as it listens for it disappearing
const parentDiv = document.getElementsByTagName('prm-search-bookmark-filter')[0] || false;
const askusButton = !!parentDiv && parentDiv.querySelectorAll('askus-button');
return !!askusButton && askusButton.length > 0;
}
// we only want to create the askus button once, as it makes api calls, so dont crreate it until we can use it
function uqheaderPresent() {
const uqheader = document.querySelectorAll('uq-header');
return !!uqheader && uqheader.length > 0;
}
function moveUQItemsOnPage() {
const mergeAreas = setInterval(() => {
// this method:
// initially moves the askus button into the primo login bar
// moves the primo login bar up a bit to shorten the header
// however, certain page events WIPE the uq-site-header shadowdom, so this listener will then:
// recreate the site title "Library" and recreate and move the askus button again
if (uqheaderPresent() && !isAskusButtonPresent()) {
console.log('create ask us button');
askusButton = document.createElement('askus-button');
}
if (uqheaderPresent() && !isAskusButtonInPrimoLoginbar()) {
console.log('move askus button');
const primoLoginBarUtilityArea = document.getElementsByTagName('prm-search-bookmark-filter')[0] || false;
let askusButton = document.getElementsByTagName('askus-button')[0] || false;
!!askusButton && !!primoLoginBarUtilityArea && primoLoginBarUtilityArea.prepend(askusButton);
// the pane background-color muting is overriden by certain primo styling, so dont do it on primo
const askusShadow = !!askusButton && askusButton.shadowRoot || false;
const askusPane = !!askusShadow && askusShadow.getElementById("askus-pane") || false;
!!askusPane && (askusPane.style.backgroundColor = 'initial');
// then shift the primo login bar up a bit, to visually merge the 2 rows
const primoLoginBar = document.getElementsByClassName('top-nav-bar layout-row ')[0] || false;
!!primoLoginBar && (primoLoginBar.style.marginTop = '-61px');
}
// if the library site label "Library" isnt present, reinsert it
const uqSiteHeader = document.querySelector('uq-site-header') || false;
const shadowDom = !!uqSiteHeader && uqSiteHeader.shadowRoot || false;
const libraryTitle = !!shadowDom && shadowDom.getElementById('site-title');
if (!libraryTitle && !!shadowDom) {
loadLibraryTitleStyleSheet(shadowDom);
reAddSiteHeaderTitle(shadowDom);
}
}, 300); // check for div periodically as when they click the eg personalise checkbox, we have to reinsert the elements
}
moveUQItemsOnPage();
|
JavaScript
| 0 |
@@ -2373,91 +2373,84 @@
//
-we dont want to insert the button more than once, as it listens for it disappear
+does the button already exist, or did we just create it and it needs mov
ing
+?
%0A
@@ -2761,17 +2761,16 @@
dont cr
-r
eate it
@@ -3356,16 +3356,41 @@
n again%0A
+ let askusButton;%0A
@@ -3445,57 +3445,8 @@
) %7B%0A
- console.log('create ask us button');%0A
@@ -3753,36 +3753,194 @@
se;%0A
+// we re-use the created askus if we can, because when its created we cant querySe
le
+c
t
+it for some unknown reason%0A if (!askusButton) %7B%0A
askusButton = do
@@ -3946,36 +3946,29 @@
ocument.
-getElementsByTagName
+querySelector
('askus-
@@ -3975,19 +3975,16 @@
button')
-%5B0%5D
%7C%7C fals
@@ -3985,16 +3985,30 @@
%7C false;
+%0A %7D
%0A%0A
|
0a62d682ef609c439aa8ac7c9e4e56e4bbc652bb
|
Fix tests on index controller, people data
|
test/karma/unit/controllers/index.spec.js
|
test/karma/unit/controllers/index.spec.js
|
'use strict';
(function() {
describe('startupwichita controllers', function() {
describe('IndexController', function() {
// Load the controllers module
beforeEach(module('startupwichita'));
var scope, IndexController, $httpBackend, peopleData;
peopleData = [
{
'name': 'Seth Etter',
'emailHash': '98ausdp9f8jap98djfasdf',
'featured': true,
'tagline': 'JavaScript Dude',
},
{
'name': 'Jacob Walker',
'emailHash': '98ausdp9f8jap98djfasdf',
'featured': true,
'tagline': 'PHP Dude',
},
{
'name': 'Jonathan Van Winkle',
'emailHash': '98ausdp9f8jap98djfasdf',
'featured': true,
'tagline': 'Design Dude',
},
{
'name': 'Jim Rice',
'emailHash': '98ausdp9f8jap98djfasdf',
'featured': true,
'tagline': 'Growler Dude',
},
{
'name': 'Kenton Hansen',
'emailHash': '98ausdp9f8jap98djfasdf',
'featured': true,
'tagline': 'Startup Dude',
}
];
beforeEach(inject(function($controller, $rootScope, _$httpBackend_) {
scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
IndexController = $controller('IndexController', {
$scope: scope
});
}));
it('should expose some global scope', function() {
expect(scope.global).toBeTruthy();
});
it('should expose the Gravatar service', function() {
expect(scope.gravatar).toBeTruthy();
});
it('should have featured people', function() {
$httpBackend.expectGET('/api/v1/users?featured=true').respond(peopleData);
scope.getFeaturedUsers();
$httpBackend.flush();
expect(scope.featuredUsers).toEqual(peopleData);
});
});
});
})();
|
JavaScript
| 0 |
@@ -2309,16 +2309,24 @@
redUsers
+%5B0%5D.name
).toEqua
@@ -2337,16 +2337,186 @@
opleData
+%5B0%5D.name);%0A expect(scope.featuredUsers%5B1%5D.name).toEqual(peopleData%5B1%5D.name);%0A expect(scope.featuredUsers%5B2%5D.name).toEqual(peopleData%5B2%5D.name
);%0A
|
286f4abdca4648f3a61e7039e1deeb342d1e5452
|
Add form class
|
packages/ember-forms/lib/form.js
|
packages/ember-forms/lib/form.js
|
/**
@class
EF.Form is a view that contains several fields and can respond to its events,
providing the field's normalized data.
It will automatically bind to the values of an object, if provided.
myForm = EF.Form.create({
objectBinding: 'App.someObject',
template: Ember.Handlebars.compile(
'{{field title }}' +
'{{field body as="textarea"}}' +
'{{form buttons}}'
),
save: function(data){ this.get('object').setProperties(data); }
});
@extends Ember.View
*/
EF.Form = Ember.View.extend({
tagName: 'form',
classNameBindings: ['name'],
attributeBindings: ['action'],
fieldViews: Ember.A(),
buttons: ['submit'],
content: null,
isForm: true,
name: Ember.computed(function(){
var constructor = this.getPath('content.constructor');
if(constructor && constructor.isClass){
var className = constructor.toString().split('.').pop();
return Ember.String.decamelize(className);
}
}).property('content'),
/**
It returns this form fields data in an object.
myForm.data();
Would return:
{
title: 'Some post title',
content: 'The post content'
}
*/
data: Ember.computed(function(){
var data = {};
this.get('fieldViews').forEach(function(field){
var fieldData = field.get('data');
for(var key in fieldData){
data[key] = fieldData[key];
}
});
return data;
}).volatile(),
submit: function(){
this.save(this.get('data'));
return false;
},
/**
This event will be fired when the form is sent, and will receive the form
data as argument. Override it to perform some operation like setting the
properties of an object.
myForm = EF.Form.create({
[...]
save: function(data){
this.get('object').setProperties(data);
}
});
*/
save: function(data){ }
});
|
JavaScript
| 0.000001 |
@@ -604,16 +604,46 @@
name'%5D,%0A
+ classNames: %5B'ember-form'%5D,%0A
attrib
|
ad257b646d868f4240f666a420543bf654380ce7
|
Fix name of form (platforms -> platform)
|
src/components/topic/platforms/CreatePlatformContainer.js
|
src/components/topic/platforms/CreatePlatformContainer.js
|
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';
import { reset } from 'redux-form';
import { push } from 'react-router-redux';
import PlatformWizard from './builder/PlatformWizard';
import { topicCreatePlatform, setTopicNeedsNewSnapshot, fetchPlatformsInTopicList, fetchTopicSummary } from '../../../actions/topicActions';
import { updateFeedback } from '../../../actions/appActions';
import { platformChannelDataFormatter, topicQueryAsString } from '../../util/topicUtil';
const DEFAULT_SELECTED_NUMBER = 5;
const localMessages = {
platformNotSaved: { id: 'platform.create.notSaved', defaultMessage: 'That didn\'t work for some reason!' },
platformSaved: { id: 'platform.create.saved', defaultMessage: 'That worked!' },
duplicateName: { id: 'platform.create.invalid', defaultMessage: 'Duplicate name. Choose a unique platform name.' },
openWebSaved: { id: 'platform.create.openWebSaved', defaultMessage: 'We created a new Open Web platform' },
twitterSaved: { id: 'platform.create.twitterSaved', defaultMessage: 'We created a new Twitter platform' },
redditSaved: { id: 'platform.create.reddit.saved', defaultMessage: 'We created a new Reddit platform' },
};
const CreatePlatformContainer = (props) => {
const { topicInfo, location, handleDone, selectedPlatform } = props;
const initialValues = { numberSelected: DEFAULT_SELECTED_NUMBER, selectedPlatform };
// default to any solr seed query they might be using already
const initAndTopicInfoValues = { ...initialValues, ...topicInfo, query: topicInfo.solr_seed_query };
return (
<PlatformWizard
topicId={topicInfo.topics_id}
startStep={0}
currentStep={0}
initialValues={initAndTopicInfoValues}
location={location}
onDone={(id, values) => handleDone(initAndTopicInfoValues, values)}
/>
);
};
CreatePlatformContainer.propTypes = {
// from dispatch
submitDone: PropTypes.func.isRequired,
handleDone: PropTypes.func.isRequired,
// from state
values: PropTypes.object,
selectedPlatform: PropTypes.object.isRequired,
// from context:
topicInfo: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
intl: PropTypes.object.isRequired,
};
const mapStateToProps = (state, ownProps) => ({
topicId: parseInt(ownProps.params.topicId, 10),
topicInfo: state.topics.selected.info,
selectedPlatform: state.topics.selected.platforms.selected,
});
const mapDispatchToProps = (dispatch, { intl }) => ({
submitDone: (topicInfo, formValues) => {
const formatPlatformChannelData = platformChannelDataFormatter(formValues.selectedPlatform.platform);
const infoForQuery = {
platform_type: formValues.selectedPlatform.platform,
platform_query: topicQueryAsString(formValues.query),
platform_source: formValues.selectedPlatform.source,
platform_channel: formatPlatformChannelData ? JSON.stringify(formatPlatformChannelData(formValues)) : JSON.stringify(formValues),
start_date: topicInfo.start_date,
end_date: topicInfo.end_date,
};
return dispatch(topicCreatePlatform(topicInfo.topics_id, infoForQuery))
.then((results) => {
if (results.success) {
const platformSavedMessage = intl.formatMessage(localMessages.platformSaved);
dispatch(setTopicNeedsNewSnapshot(true)); // user feedback
dispatch(updateFeedback({ classes: 'info-notice', open: true, message: platformSavedMessage })); // user feedback
dispatch(fetchPlatformsInTopicList(topicInfo.topics_id)); // force refetch of newly configured platforms
dispatch(push(`/topics/${topicInfo.topics_id}/summary`));
dispatch(reset('platforms')); // it is a wizard so we have to do this by hand
dispatch(fetchTopicSummary(topicInfo.topics_id)); // force refetch of newly configured platforms
} else {
const platformNotSavedMessage = intl.formatMessage(localMessages.platformNotSaved);
dispatch(updateFeedback({ open: true, message: platformNotSavedMessage })); // user feedback
}
});
},
});
function mergeProps(stateProps, dispatchProps, ownProps) {
return { ...stateProps, ...dispatchProps, ...ownProps, handleDone: (topicId, formValues) => dispatchProps.submitDone(stateProps.topicInfo, formValues, stateProps) };
}
export default
injectIntl(
connect(mapStateToProps, mapDispatchToProps, mergeProps)(
CreatePlatformContainer
)
);
|
JavaScript
| 0.00001 |
@@ -3744,17 +3744,16 @@
platform
-s
')); //
|
0a6844c2d9ac4c4c67cee668f25db1ce742a8951
|
Refactor ciscospark Migrate Avatar to packages
|
packages/plugin-avatar/test/unit/spec/avatar-url-batcher.js
|
packages/plugin-avatar/test/unit/spec/avatar-url-batcher.js
|
/**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/
import {assert} from '@ciscospark/test-helper-chai';
import Avatar, {config} from '../../';
// import '@ciscospark/test-helper-sinon';
import {MockSpark} from '@ciscospark/test-helper-mock-spark';
describe(`Services`, () => {
describe(`Avatar`, () => {
describe(`AvatarUrlBatcher`, () => {
let batcher;
let spark;
beforeEach(() => {
spark = new MockSpark({
children: {
avatar: Avatar
}
});
spark.config.avatar = config.avatar;
batcher = spark.avatar.batcher;
console.warn(JSON.stringify(spark, null, `\t`));
});
describe(`#fingerprintRequest(item)`, () => {
it(`returns 'uuid - size'`, () => {
assert.equal(batcher.fingerprintRequest({uuid: `uuid1`, size: 80}), `uuid1 - 80`);
});
});
});
});
});
|
JavaScript
| 0 |
@@ -140,18 +140,8 @@
atar
-, %7Bconfig%7D
fro
@@ -156,59 +156,15 @@
/';%0A
-//
import
-'@ciscospark/test-helper-sinon';%0Aimport %7B
Mock
@@ -168,17 +168,16 @@
ockSpark
-%7D
from '@
@@ -479,25 +479,24 @@
%7D);%0A
-%0A
spark.co
@@ -491,140 +491,102 @@
-spark.config.avatar = config.avatar;%0A batcher = spark.avatar.batcher;%0A console.warn(JSON.stringify(spark, null, %60%5Ct%60))
+console.warn('spark: %3C' + JSON.stringify(spark) + '%3E');%0A batcher = spark.avatar.batcher
;%0A
|
646dbc1b26e10be6bef38f16b4e84a2c9e8ec6ee
|
Fix a major regression in v1.1.1
|
lib/director/http/index.js
|
lib/director/http/index.js
|
var events = require('events'),
qs = require('querystring'),
util = require('util'),
director = require('../../director'),
responses = require('./responses');
//
// ### Expose all HTTP methods and responses
//
exports.methods = require('./methods');
Object.keys(responses).forEach(function (name) {
exports[name] = responses[name];
})
//
// ### function Router (routes)
// #### @routes {Object} **Optional** Routing table for this instance.
// Constuctor function for the HTTP Router object responsible for building
// and dispatching from a given routing table.
//
var Router = exports.Router = function (routes) {
//
// ### Extend the `Router` prototype with all of the RFC methods.
//
this.params = {};
this.routes = {};
this.methods = ['on', 'after', 'before'];
this.scope = [];
this._methods = {};
this.recurse = 'forward';
this._attach = [];
this.extend(exports.methods.concat(['before', 'after']));
this.configure();
this.mount(routes || {});
};
//
// Inherit from `director.Router`.
//
util.inherits(Router, director.Router);
//
// ### function configure (options)
// #### @options {Object} **Optional** Options to configure this instance with
// Configures this instance with the specified `options`.
//
Router.prototype.configure = function (options) {
options = options || {};
// useful when using connect's bodyParser
this.stream = options.stream || false;
director.Router.prototype.configure.call(this, options);
}
//
// ### function on (method, path, route)
// #### @method {string} **Optional** Method to use
// #### @path {string} Path to set this route on.
// #### @route {Array|function} Handler for the specified method and path.
// Adds a new `route` to this instance for the specified `method`
// and `path`.
//
Router.prototype.on = function (method, path) {
var args = Array.prototype.slice.call(arguments, 2),
route = args.pop(),
options = args.pop();
if (options && options.stream) {
route.stream = true;
}
director.Router.prototype.on.call(this, method, path, route);
};
//
// ### function attach (func)
// ### @func {function} Function to execute on `this` before applying to router function
// Ask the router to attach objects or manipulate `this` object on which the
// function passed to the http router will get applied
Router.prototype.attach = function (func) {
this._attach.push(func);
};
//
// ### function dispatch (method, path)
// #### @req {http.ServerRequest} Incoming request to dispatch.
// #### @res {http.ServerResponse} Outgoing response to dispatch.
// #### @callback {function} **Optional** Continuation to respond to for async scenarios.
// Finds a set of functions on the traversal towards
// `method` and `path` in the core routing table then
// invokes them based on settings in this instance.
//
Router.prototype.dispatch = function (req, res, callback) {
//
// Dispatch `HEAD` requests to `GET`
//
var method = req.method === 'HEAD' ? 'get' : req.method.toLowerCase(),
url = decodeURI(req.url.split('?', 1)[0]),
fns = this.traverse(method, url, this.routes, ''),
thisArg = { req: req, res: res },
self = this,
runlist,
stream,
error;
if (this._attach) {
for (var i in this._attach) {
this._attach[i].call(thisArg);
}
}
if (!fns || fns.length === 0) {
error = new exports.NotFound('Could not find path: ' + req.url)
if (typeof this.notfound === 'function') {
this.notfound.call(thisArg, callback);
}
else if (callback) {
callback.call(thisArg, error, req, res);
}
return false;
}
if (this.recurse === 'forward') {
fns = fns.reverse();
}
runlist = this.runlist(fns);
stream = this.stream || runlist.some(function (fn) { return fn.stream === true });
function parseAndInvoke() {
error = self.parse(req);
if (error) {
if (callback) {
callback.call(thisArg, error, req, res);
}
return false;
}
self.invoke(runlist, thisArg, callback);
}
if (!stream) {
//
// If there is no streaming required on any of the functions on the
// way to `path`, then attempt to parse the fully buffered request stream
// once it has emitted the `end` event.
//
if (req.readable) {
//
// If the `http.ServerRequest` is still readable, then await
// the end event and then continue
//
req.once('end', parseAndInvoke)
}
else {
//
// Otherwise, just parse the body now.
//
parseAndInvoke();
}
}
else {
this.invoke(runlist, thisArg, callback);
}
return true;
};
//
// ### @parsers {Object}
// Lookup table of parsers to use when attempting to
// parse incoming responses.
//
Router.prototype.parsers = {
'application/x-www-form-urlencoded': qs.parse,
'application/json': JSON.parse
};
//
// ### function parse (req)
// #### @req {http.ServerResponse|BufferedStream} Incoming HTTP request to parse
// Attempts to parse `req.body` using the value found at `req.headers['content-type']`.
//
Router.prototype.parse = function (req) {
function mime(req) {
var str = req.headers['content-type'] || '';
return str.split(';')[0];
}
var parser = this.parsers[mime(req)],
body;
if (parser) {
req.body = req.body || '';
if (req.chunks) {
req.chunks.forEach(function (chunk) {
req.body += chunk;
});
}
try {
req.body = req.body && req.body.length
? parser(req.body)
: {};
}
catch (err) {
return new exports.BadRequest('Malformed data');
}
}
};
|
JavaScript
| 0.000002 |
@@ -1427,24 +1427,31 @@
%7C false;%0A%0A
+return
director.Rou
|
2fed7e5b8973788cab6883185fe16049a8325736
|
fix js validatoin regex
|
chords/static/chords/js/forms_validation.js
|
chords/static/chords/js/forms_validation.js
|
$(function() {
function applyValidationError(obj, validates) {
if (validates)
obj.closest('.form-group').removeClass('has-error');
else
obj.closest('.form-group').addClass('has-error');
return validates;
}
function applyValidationGlyphicon(obj, validates) {
if (validates) {
obj.closest('.form-group').addClass('has-success has-feedback');
obj.closest('.form-group').removeClass('has-error');
obj.siblings('span.glyphicon').addClass('glyphicon-ok');
obj.siblings('span.glyphicon').removeClass('glyphicon-remove');
obj.siblings('span.sr-only').text('(success)');
} else {
obj.closest('.form-group').addClass('has-error has-feedback');
obj.closest('.form-group').removeClass('has-success');
obj.siblings('span.glyphicon').addClass('glyphicon-remove');
obj.siblings('span.glyphicon').removeClass('glyphicon-ok');
obj.siblings('span.sr-only').text('(error)');
}
return validates;
}
/**
* @param {String} password
* @return True if password is valid, else False
*/
function passwordIsValid(password) {
return password.length >= 5;
}
/**
* @param {Object} pass1
* @return True if password is valid, else False
*/
function validatePassword1(pass1, pass2) {
validatePassword2(pass1, pass2);
return applyValidationGlyphicon(pass1, passwordIsValid(pass1.val()));
}
/**
* @param {Object} pass1
* @param {Object} pass2
* @return True if passwords are valid, else False
*/
function validatePassword2(pass1, pass2) {
return applyValidationGlyphicon(pass2, passwordIsValid(pass1.val()) && pass1.val() == pass2.val());
}
$('#new_password1').keyup(function() {
validatePassword1($(this), $('#new_password2'));
});
$('#new_password2').keyup(function() {
validatePassword2($('#new_password1'), $(this));
});
$('#password1').keyup(function() {
validatePassword1($(this), $('#password2'));
});
$('#password2').keyup(function() {
validatePassword2($('#password1'), $(this));
});
$('#password_change_form').submit(function(event) {
var pass1 = $('#new_password1');
var pass2 = $('#new_password2');
var oldpass = $('#old_password');
var v1 = (! applyValidationError(oldpass, oldpass.val() != ''))
var v2 = (! validatePassword1(pass1, pass2))
var v3 = (! validatePassword2(pass1, pass2))
if (v1 || v2 || v3)
event.preventDefault();
});
$('#password_reset_confirm_form').submit(function(event) {
var pass1 = $('#new_password1');
var pass2 = $('#new_password2');
if (! validatePassword1(pass1, pass2))
event.preventDefault();
if (! validatePassword2(pass1, pass2))
event.preventDefault();
});
$('#registration_form').submit(function(event) {
var username = $('#username');
var email = $('#email');
var pass1 = $('#password1');
var pass2 = $('#password2');
var v1 = (! applyValidationError(username, /^[\w@+-.]{1,30}$/.test(username.val())))
var v2 = (! applyValidationError(email, email.val() != ''))
var v3 = (! validatePassword1(pass1, pass2))
var v4 = (! validatePassword2(pass1, pass2))
if (v1 || v2 || v3 || v4)
event.preventDefault();
});
$('#add_song_form').submit(function(event) {
var title = $('#id_title');
var artist = $('#id_artist_txt');
var content = $('#id_content');
if (! applyValidationError(content, $.trim(content.val()) != '')) {
event.preventDefault();
var _top = content.position().top;
$(window).scrollTop(_top);
}
if (! applyValidationError(artist, $.trim(artist.val()) != '')) {
event.preventDefault();
var _top = artist.parent().siblings('label').position().top;
$(window).scrollTop(_top);
}
if (! applyValidationError(title, $.trim(title.val()) != '')) {
event.preventDefault();
var _top = title.parent().siblings('label').position().top;
$(window).scrollTop(_top);
}
});
$('#contact_form').submit(function(event) {
var name = $('#id_name');
var email = $('#id_email');
var subject = $('#id_subject');
var body = $('#id_body');
var v1 = (! applyValidationError(name, $.trim(name.val()) != ''));
var v2 = (! applyValidationError(email, $.trim(email.val()) != ''));
var v3 = (! applyValidationError(subject, $.trim(subject.val()) != ''));
var v4 = (! applyValidationError(body, $.trim(body.val()) != ''));
if (v1 || v2 || v3 || v4)
event.preventDefault();
});
/**
* After validating the form, perform an AJAX POST request in order to save
* the new comment in the database and append it to the page. After
* successfully posting a comment, ignore the recaptcha field.
*/
$('#comment_form').submit(function(event) {
event.preventDefault();
var content = $('#id_content');
if (! applyValidationError(content, $.trim(content.val()) != ''))
return;
var data = {
csrfmiddlewaretoken : $('[name="csrfmiddlewaretoken"]').attr('value'),
user : $('#id_user').attr('value'),
song : $('#id_song').attr('value'),
content : $('#id_content').val(),
};
if ($('.g-recaptcha').css('display') == 'none')
data['testing'] = 'True';
else
data['g-recaptcha-response'] = $('#g-recaptcha-response').val();
var url = $('#comment_form').attr('action');
$.post(url, data, function(data) {
$('#comments_row').append(data);
content.val('');
$('.g-recaptcha').css('display', 'none');
});
});
});
|
JavaScript
| 0.998889 |
@@ -2947,11 +2947,11 @@
%5B%5Cw@
+.
+-
-.
%5D%7B1,
|
152775047110d0e85e309321b8aa35f0c6f1d996
|
change isUndefined to isEmpty which covers more cases
|
src/lookupStream.js
|
src/lookupStream.js
|
var _ = require('lodash');
var parallelStream = require('pelias-parallel-stream');
var peliasConfig = require( 'pelias-config' ).generate();
var regions = require('../data/regions');
var peliasLogger = require( 'pelias-logger' );
var getAdminLayers = require( './getAdminLayers' );
//defaults to nowhere
var optsArg = {
transports: []
};
//only prints to suspect records log if flag is set
if (peliasConfig.logger.suspectFile === true){
optsArg.transports.push(new peliasLogger.winston.transports.File( {
filename: 'suspect_wof_records.log',
timestamp: false
}));
}
var logger = peliasLogger.get( 'wof-admin-lookup', optsArg );
regions.isSupported = function(country, name) {
return this.hasOwnProperty(country) && this[country].hasOwnProperty(name);
};
regions.getCode = function(countries, regions) {
if (_.isEmpty(countries) || _.isEmpty(regions)) {
return undefined;
}
var country = countries[0].name;
var region = regions[0].name;
if (this.isSupported(country, region)) {
return this[country][region];
}
return undefined;
};
function setFields(values, doc, wofFieldName, abbreviation) {
try {
if (!_.isEmpty(values)) {
doc.addParent(wofFieldName, values[0].name, values[0].id.toString(), abbreviation);
}
}
catch (err) {
logger.info('invalid value', {
centroid: doc.getCentroid(),
result: {
type: wofFieldName,
values: values,
abbreviation: abbreviation
}
});
}
}
function hasCountry(result) {
return _.isEmpty(result.country);
}
function hasAnyMultiples(result) {
return Object.keys(result).some(function(element) {
return result[element].length > 1;
});
}
function createLookupStream(resolver, config) {
if (!resolver) {
throw new Error('createLookupStream requires a valid resolver to be passed in as the first parameter');
}
config = config || peliasConfig;
var maxConcurrentReqs = 1;
if (config.imports.adminLookup && config.imports.adminLookup.maxConcurrentReqs) {
maxConcurrentReqs = config.imports.adminLookup.maxConcurrentReqs;
}
var stream = parallelStream(maxConcurrentReqs, function (doc, enc, callback) {
// don't do anything if there's no centroid
if (_.isEmpty(doc.getCentroid())) {
return callback(null, doc);
}
resolver.lookup(doc.getCentroid(), function (err, result) {
// assume errors at this point are fatal, so pass them upstream to kill stream
if (err) {
logger.error(err);
return callback(new Error('PIP server failed: ' + (err.message || JSON.stringify(err))));
}
// log results w/o country OR any multiples
if (hasCountry(result)) {
logger.info('no country', {
centroid: doc.getCentroid(),
result: result
});
}
if (hasAnyMultiples(result)) {
logger.info('multiple values', {
centroid: doc.getCentroid(),
result: result
});
}
var regionCode = regions.getCode(result.country, result.region);
var countryCode = getCountryCode(result);
// set code if available
if (!_.isUndefined(countryCode)) {
doc.setAlpha3(countryCode);
}
setFields(result.country, doc, 'country', countryCode);
setFields(result.macroregion, doc, 'macroregion');
if (!_.isEmpty(result.region)) { // if there are regions, use them
setFields(result.region, doc, 'region', regionCode);
} else { // go with dependency for region (eg - Puerto Rico is a dependency)
setFields(result.dependency, doc, 'region');
}
setFields(result.macrocounty, doc, 'macrocounty');
setFields(result.county, doc, 'county');
setFields(result.locality, doc, 'locality');
setFields(result.localadmin, doc, 'localadmin');
setFields(result.borough, doc, 'borough');
setFields(result.neighbourhood, doc, 'neighbourhood');
callback(null, doc);
}, getAdminLayers(doc.getLayer()));
},
function end() {
if (typeof resolver.end === 'function') {
resolver.end();
}
});
return stream;
}
function getCountryCode(result) {
if (result.country && result.country.length > 0 && result.country[0].hasOwnProperty('abbr')) {
return result.country[0].abbr;
}
return undefined;
}
module.exports = {
createLookupStream: createLookupStream
};
|
JavaScript
| 0.000046 |
@@ -3140,17 +3140,13 @@
_.is
-Undefined
+Empty
(cou
|
bba8856672caf298786d07dea1de929b947c43a7
|
fix broken tests based on updated component
|
src/components/Stocks/Strains/StrainDetailsList.test.js
|
src/components/Stocks/Strains/StrainDetailsList.test.js
|
import React from "react"
import { shallow } from "enzyme"
import StrainDetailsList from "./StrainDetailsList"
import ItemDisplay from "../ItemDisplay"
import LeftDisplay from "../LeftDisplay"
import RightDisplay from "../RightDisplay"
import Grid from "@material-ui/core/Grid"
import { data } from "./mockStrainData"
describe("Stocks/Strains/StrainDetailsList", () => {
const wrapper = shallow(<StrainDetailsList data={data} />)
describe("initial render", () => {
it("renders without crashing", () => {
expect(wrapper).toHaveLength(1)
})
it("always renders initial components", () => {
expect(wrapper.dive().find(Grid)).toHaveLength(2)
expect(wrapper.dive().find(ItemDisplay)).toHaveLength(8)
expect(wrapper.dive().find(LeftDisplay)).toHaveLength(15)
expect(wrapper.dive().find(RightDisplay)).toHaveLength(17)
})
})
})
|
JavaScript
| 0.000001 |
@@ -787,9 +787,9 @@
th(1
-5
+6
)%0A
@@ -852,9 +852,9 @@
th(1
-7
+6
)%0A
|
82d73918ac188e8e44bab79452dde219a3d5775b
|
Fix prettier
|
shared/util/kbfs-notifications.js
|
shared/util/kbfs-notifications.js
|
// @flow
import _ from 'lodash'
import {
KbfsCommonFSErrorType,
KbfsCommonFSNotificationType,
KbfsCommonFSStatusCode,
} from '../constants/types/flow-types'
import path from 'path'
import {parseFolderNameToUsers} from './kbfs'
import type {FSNotification} from '../constants/types/flow-types'
type DecodedKBFSError = {
'title': string,
'body': string,
}
function usernamesForNotification(notification: FSNotification) {
return parseFolderNameToUsers(null, notification.filename.split(path.sep)[3] || notification.filename).map(
i => i.username
)
}
function tlfForNotification(notification: FSNotification): string {
// The notification.filename is canonical platform independent path.
// To get the TLF we can look at the first 3 directories.
// /keybase/private/gabrielh/foo.txt => /keybase/private/gabrielh
return notification.filename.split(path.sep).slice(0, 4).join(path.sep)
}
export function decodeKBFSError(user: string, notification: FSNotification): DecodedKBFSError {
console.log('Notification (kbfs error):', notification)
const tlf = tlfForNotification(notification)
switch (notification.errorType) {
case KbfsCommonFSErrorType.accessDenied:
let prefix = user ? `${user} does` : 'You do'
return {
title: 'Keybase: Access denied',
body: `${prefix} not have ${notification.params.mode} access to ${notification.filename}`,
}
case KbfsCommonFSErrorType.userNotFound:
return {
title: 'Keybase: User not found',
body: `${notification.params.username} is not a Keybase user`,
}
case KbfsCommonFSErrorType.revokedDataDetected:
return {
title: 'Keybase: Possibly revoked data detected',
body: `${tlf} was modified by a revoked or bad device. Use 'keybase log send' to file an issue with the Keybase admins.`,
}
case KbfsCommonFSErrorType.notLoggedIn:
return {
title: `Keybase: Permission denied in ${tlf}`,
body: "You are not logged into Keybase. Try 'keybase login'.",
}
case KbfsCommonFSErrorType.timeout:
return {
title: `Keybase: ${_.capitalize(notification.params.mode)} timeout in ${tlf}`,
body: `The ${notification.params.mode} operation took too long and failed. Please run 'keybase log send' so our admins can review.`,
}
case KbfsCommonFSErrorType.rekeyNeeded:
return notification.params.rekeyself === 'true'
? {
title: 'Keybase: Files need to be rekeyed',
body: `Please open one of your other computers to unlock ${tlf}`,
}
: {
title: 'Keybase: Friends needed',
body: `Please ask another member of ${tlf} to open Keybase on one of their computers to unlock it for you.`,
}
case KbfsCommonFSErrorType.overQuota:
const usageBytes = parseInt(notification.params.usageBytes, 10)
const limitBytes = parseInt(notification.params.limitBytes, 10)
const usedGB = (usageBytes / 1e9).toFixed(1)
const usedPercent = Math.round(100 * usageBytes / limitBytes)
return {
title: 'Keybase: Out of space',
body: `Action needed! You are using ${usedGB}GB (${usedPercent}%) of your quota. Please delete some data.`,
}
default:
return {
title: 'Keybase: KBFS error',
body: `${notification.status}`,
}
}
// This code came from the kbfs team but this isn't plumbed through the protocol. Leaving this for now
// if (notification.errorType === KbfsCommonFSErrorType.notImplemented) {
// if (notification.feature === '2gbFileLimit') {
// return ({
// title: 'Keybase: Not yet implemented',
// body: `You just tried to write a file larger than 2GB in ${tlf}. This limitation will be removed soon.`
// })
// } else if (notification.feature === '512kbDirLimit') {
// return ({
// title: 'Keybase: Not yet implemented',
// body: `You just tried to write too many files into ${tlf}. This limitation will be removed soon.`
// })
// } else {
// return ({
// title: 'Keybase: Not yet implemented',
// body: `You just hit a ${notification.feature} limitation in KBFS. It will be fixed soon.`
// })
// }
// } else {
// return ({
// title: 'Keybase: KBFS error',
// body: `${notification.status}`
// })
// }
}
export function kbfsNotification(notification: FSNotification, notify: any, getState: any) {
const action = {
[KbfsCommonFSNotificationType.encrypting]: 'Encrypting and uploading',
[KbfsCommonFSNotificationType.decrypting]: 'Decrypting',
[KbfsCommonFSNotificationType.signing]: 'Signing and uploading',
[KbfsCommonFSNotificationType.verifying]: 'Verifying and downloading',
[KbfsCommonFSNotificationType.rekeying]: 'Rekeying',
}[notification.notificationType]
if (action === undefined) {
// Ignore notification types we don't care about.
return
}
// KBFS fires a notification when it initializes. We prompt the user to log
// send if there is an error.
if (notification.notificationType === KbfsCommonFSNotificationType.initialized &&
notification.statusCode === KbfsCommonFSStatusCode.error &&
notification.errorType === KbfsCommonFSErrorType.diskCacheErrorLogSend) {
console.log(`KBFS failed to initialize its disk cache. Please send logs.`)
let title = `KBFS: Disk cache not initialized`
let body = `Please Send Feedback to Keybase`
let rateLimitKey = body
notify(title, {body}, 10, rateLimitKey)
}
// KBFS fires a notification when it changes state between connected
// and disconnected (to the mdserver). For now we just log it.
if (notification.notificationType === KbfsCommonFSNotificationType.connection) {
const state = notification.statusCode === KbfsCommonFSStatusCode.start ? 'connected' : 'disconnected'
console.log(`KBFS is ${state}`)
return
}
const usernames = usernamesForNotification(notification).join(' & ')
let title = `KBFS: ${action}`
let body = `Chat or files with ${usernames} ${notification.status}`
let user = getState().config.username
let rateLimitKey
const isError = notification.statusCode === KbfsCommonFSStatusCode.error
// Don't show starting or finished, but do show error.
if (isError) {
if (notification.errorType === KbfsCommonFSErrorType.exdevNotSupported) {
// Ignored for now.
// TODO: implement the special popup window (DESKTOP-3637)
return
}
;({title, body} = decodeKBFSError(user, notification))
rateLimitKey = body // show unique errors
} else {
switch (action) {
case 'Rekeying': // limit all rekeys, no matter the tlf
rateLimitKey = 'rekey'
break
default:
rateLimitKey = usernames // by tlf
}
}
notify(title, {body}, 10, rateLimitKey)
}
|
JavaScript
| 0 |
@@ -5017,32 +5017,37 @@
an error.%0A if (
+%0A
notification.not
@@ -5104,34 +5104,32 @@
tialized &&%0A
-
-
notification.sta
@@ -5172,18 +5172,16 @@
rror &&%0A
-
noti
@@ -5246,16 +5246,19 @@
rLogSend
+%0A
) %7B%0A
|
3072c914cce3479b7b5e9c2dd46db6dddd6eb8a4
|
Make ToOneAttribute class public
|
source/Vibrato/datastore/record/ToOneAttribute.js
|
source/Vibrato/datastore/record/ToOneAttribute.js
|
// -------------------------------------------------------------------------- \\
// File: ToOneAttribute.js \\
// Module: DataStore \\
// Requires: RecordAttribute.js \\
// Author: Neil Jenkins \\
// License: © 2010–2012 Opera Software ASA. All rights reserved. \\
// -------------------------------------------------------------------------- \\
/*global O */
"use strict";
( function ( NS, undefined ) {
var ToOneAttribute = NS.Class({
Extends: NS.RecordAttribute,
willCreateInStore: function ( record, propKey, storeKey ) {
var propValue = record.get( propKey );
if ( propValue && !propValue.get( 'id' ) ) {
record.get( 'store' ).attrMapsToStoreKey(
propValue.get( 'storeKey' ),
storeKey, this.key || propKey );
}
},
willSet: function ( propValue, propKey, record ) {
if ( ToOneAttribute.parent.willSet.call(
this, propValue, propKey, record ) ) {
if ( !propValue.get( 'storeKey' ) ) {
throw new Error( 'O.ToOneAttribute: ' +
'Cannot set connection to record not saved to store.' );
}
var oldPropValue = record.get( propKey ),
storeKey = record.get( 'storeKey' ),
store = record.get( 'store' ),
attrKey = this.key || propKey;
if ( storeKey ) {
if ( oldPropValue && !oldPropValue.get( 'id' ) ) {
store.attrNoLongerMapsToStoreKey(
oldPropValue.get( 'storeKey' ),
storeKey, attrKey );
}
if ( propValue && !propValue.get( 'id' ) ) {
store.attrMapsToStoreKey(
propValue.get( 'storeKey' ),
storeKey, attrKey );
}
}
return true;
}
return false;
},
call: function ( record, propValue, propKey ) {
var result = ToOneAttribute.parent.call.call(
this, record, propValue, propKey );
if ( result && typeof result === 'string' ) {
result = record.get( 'store' ).getRecord( this.type, result );
}
return result || null;
}
});
NS.Record.toOne = function ( options ) {
return new ToOneAttribute( options );
};
}( O ) );
|
JavaScript
| 0.000001 |
@@ -2501,16 +2501,53 @@
%7D%0A%7D);%0A%0A
+NS.ToOneAttribute = ToOneAttribute;%0A%0A
NS.Recor
|
f324648d1c0b5b2cd234ddad7b6a162384400c89
|
fix 'function($window) is not using explicit annotation and cannot be invoked in strict mode'
|
cmelo-sticky.js
|
cmelo-sticky.js
|
angular.module('cmelo.angularSticky', [])
.directive('cmeloSticky', function ($window) {
return {
restrict: 'A',
link: function (scope, elem) {
var wrapper = elem;
var nodename = elem.eq(0)[0].nodeName.toLowerCase();
var el = elem;
if (nodename === 'body') {
wrapper = angular.element($window);
}
function getScrolltop (el) {
if (nodename === 'body') {
return document.querySelector('html').scrollTop +
document.querySelector('body').scrollTop;
} else {
return el.eq(0)[0].scrollTop;
}
}
function getOffset(el) {
if (!el) { return Infinity; }
return el.offsetTop + el.offsetParent.offsetTop;
}
function getClosest(el, attribute) {
for (; el && el !== document &&
el.nodeType === 1; el = el.parentNode) {
if (el.hasAttribute(attribute)) { return el; }
}
return null;
}
wrapper.on('scroll', function () {
var stickers_all = document.querySelectorAll('[cmelo-sticky-top]');
var stickers = [];
angular.forEach(stickers_all, function (sticker) {
var parent = getClosest(sticker, 'cmelo-sticky');
if (parent === elem.eq(0)[0]) {
stickers.push(sticker);
}
});
angular.forEach(stickers, function (sticker, i) {
var top = parseInt(sticker.getAttribute('cmelo-sticky-top'));
if (isNaN(top)) { top = 0; }
var offset_top = getOffset(sticker);
var offset_next = getOffset(stickers[i+1]);
var height = sticker.offsetHeight;
var scroll_top = getScrolltop(el);
var diff = scroll_top - offset_top + top;
var next_diff = scroll_top + top + height - offset_next;
if (next_diff > 0) { diff -= next_diff; }
if (sticker.nodeName.toLowerCase() === 'thead') {
var parent_diff = diff + height -
sticker.offsetParent.offsetHeight;
if (parent_diff > 0) {
diff -= parent_diff;
}
}
var sticker_el = angular.element(sticker);
if (diff > 0) {
sticker_el.addClass('cmelo-sticky-on');
sticker_el.css({
transform: 'translateY(' + diff + 'px)'
});
} else {
sticker_el.removeClass('cmelo-sticky-on');
sticker_el.css({
transform: 'translateY(0px)'
});
}
});
});
}
};
})
;
|
JavaScript
| 0 |
@@ -66,16 +66,28 @@
Sticky',
+ %5B'$window',
functio
@@ -2442,16 +2442,15 @@
%09%09%7D;%0D%0A%09%7D
+%5D
)
-%0D%0A
%0D%0A;%0D%0A
|
1abfa6b6f7a5d6e9f4f7632c2e506797f1a486e9
|
Fix lint errors
|
src/geo/leaflet/leaflet-cartodb-webgl-layer-group-view.js
|
src/geo/leaflet/leaflet-cartodb-webgl-layer-group-view.js
|
// require('d3.cartodb');// TODO: The 'd3.cartodb' module doens't currently export L.CartoDBd3Layer
// and it's currently relying on window.L so weed to do the following trick.
// Check out: https://github.com/CartoDB/d3.cartodb/issues/93 for more info
// var CartoDBd3Layer = window.L.CartoDBd3Layer;
var TC = require('tangram.cartodb');
var LeafletLayerView = require('./leaflet-layer-view');
var GeoJSONDataProvider = require('../data-providers/geojson/data-provider');
var LeafletCartoDBVectorLayerGroupView = L.TileLayer.extend({
includes: [
LeafletLayerView.prototype
],
options: {
minZoom: 0,
maxZoom: 28,
tileSize: 256,
zoomOffset: 0,
tileBuffer: 50
},
events: {
featureOver: null,
featureOut: null,
featureClick: null
},
initialize: function (layerGroupModel, map) {
LeafletLayerView.call(this, layerGroupModel, this, map);
layerGroupModel.bind('change:urls', this._onURLsChanged, this);
this.tangram = new TC(map);
layerGroupModel.each(this._onLayerAdded, this);
layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this));
},
onAdd: function (map) {
},
_onLayerAdded: function (layer) {
var self = this;
layer.bind('change:meta', function (e) {
self.tangram.addLayer(e.attributes);
});
},
_onURLsChanged: function (e, res) {
this.tangram.addDataSource(res.tiles[0]);
}
});
module.exports = LeafletCartoDBVectorLayerGroupView;
|
JavaScript
| 0.000396 |
@@ -1,306 +1,4 @@
-// require('d3.cartodb');// TODO: The 'd3.cartodb' module doens't currently export L.CartoDBd3Layer%0A// and it's currently relying on window.L so weed to do the following trick.%0A// Check out: https://github.com/CartoDB/d3.cartodb/issues/93 for more info%0A// var CartoDBd3Layer = window.L.CartoDBd3Layer;%0A
var
@@ -89,86 +89,8 @@
w');
-%0Avar GeoJSONDataProvider = require('../data-providers/geojson/data-provider');
%0A%0Ava
@@ -128,16 +128,23 @@
pView =
+window.
L.TileLa
|
4dace04ebfe112328a36e3b2f74a49bdfc8f8372
|
Remove default export
|
src/components/with-drag-and-drop/with-drag-and-drop.js
|
src/components/with-drag-and-drop/with-drag-and-drop.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import { DragSource, DropTarget } from 'react-dnd';
// TODO move to constants file?
const ItemTypes = {
TABLE_ROW: 'TableRow'
};
const itemSource = {
canDrag(props) { // eslint-disable-line no-unused-vars
return document.activeElement.getAttribute('icon') === "list_view";
},
beginDrag(props) {
return {
index: props.index
};
}
};
const itemTarget = {
hover(props, monitor, component) {
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
}
// Determine rectangle on screen
const hoverBoundingRect = ReactDOM.findDOMNode(component).getBoundingClientRect();
// Get vertical middle
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
// Determine mouse position
const clientOffset = monitor.getClientOffset();
// Get pixels to the top
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
// Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return;
}
// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return;
}
// Time to actually perform the action
props.moveItem(dragIndex, hoverIndex);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().index = hoverIndex;
}
};
class WithDragAndDrop extends React.Component {
render() {
const { connectDragSource, connectDropTarget } = this.props;
return connectDragSource(connectDropTarget(this.props.children));
}
}
WithDragAndDrop = DropTarget( // eslint-disable-line no-class-assign
ItemTypes.TABLE_ROW, itemTarget, connect => ({
connectDropTarget: connect.dropTarget()
})
)(WithDragAndDrop);
WithDragAndDrop = DragSource( // eslint-disable-line no-class-assign
ItemTypes.TABLE_ROW, itemSource, (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
})
)(WithDragAndDrop);
export default WithDragAndDrop;
|
JavaScript
| 0 |
@@ -105,16 +105,68 @@
ct-dnd';
+%0Aimport DraggableContext from './draggable-context';
%0A%0A// TOD
@@ -2542,15 +2542,11 @@
ort
-default
+%7B%0A
Wit
@@ -2557,10 +2557,32 @@
gAndDrop
+,%0A DraggableContext%0A%7D
;%0A
|
9ef9daed8a51285187e6cebbd5057c10b853e48b
|
Remove unprintable character from makeElement.
|
api/extractDOM.js
|
api/extractDOM.js
|
// provides extractDOM
(function($, Mobify) {
// During capturing, we will usually end up hiding our </head>/<body ... > boundary
// within <plaintext> capturing element. To construct shadow DOM, we need to rejoin
// head and body content, iterate through it to find head/body boundary and expose
// opening <body ... > tag as a string.
var guillotine = function(captured) {
// Consume comments without grouping to avoid catching
// <body> inside a comment, common with IE conditional comments.
var bodySnatcher = /<!--(?:[\s\S]*?)-->|(<\/head\s*>|<body[\s\S]*$)/gi;
captured = $.extend({}, captured);
//Fallback for absence of </head> and <body>
var rawHTML = captured.bodyContent = captured.headContent + captured.bodyContent;
captured.headContent = '';
// Search rawHTML for the head/body split.
for (var match; match = bodySnatcher.exec(rawHTML); match) {
// <!-- comment --> . Skip it.
if (!match[1]) continue;
if (match[1][1] == '/') {
// Hit </head. Gather <head> innerHTML. Also, take trailing content,
// just in case <body ... > is missing or malformed
captured.headContent = rawHTML.slice(0, match.index);
captured.bodyContent = rawHTML.slice(match.index + match[1].length);
} else {
// Hit <body. Gather <body> innerHTML.
// If we were missing a </head> before, now we can pick up everything before <body
captured.headContent = captured.head || rawHTML.slice(0, match.index);
captured.bodyContent = match[0];
// Find the end of <body ... >
var parseBodyTag = /^((?:[^>'"]*|'[^']*?'|"[^"]*?")*>)([\s\S]*)$/.exec(match[0]);
// Will skip this if <body was malformed (e.g. no closing > )
if (parseBodyTag) {
// Normal termination. Both </head> and <body> were recognized and split out
captured.bodyTag = parseBodyTag[1];
captured.bodyContent = parseBodyTag[2];
}
break;
}
}
return captured;
}
// Transform a primitive <tag attr="value" ...> into corresponding DOM element
// Unlike $('<tag>'), correctly handles <head>, <body> and <html>
, makeElement = function(html) {
var match = html.match(/^<(\w+)([\s\S]*)/i);
var el = document.createElement(match[1]);
$.each($('<div' + match[2])[0].attributes, function(i, attr) {
el.setAttribute(attr.nodeName, attr.nodeValue);
});
return el;
}
, html = Mobify.html || {};
$.extend(html, {
// 1. Get the original markup from the document.
// 2. Disable the markup.
// 3. Construct the source pseudoDOM.
extractDOM: function() {
// Extract escaped markup out of the DOM
var captured = guillotine(html.extractHTML());
Mobify.timing.addPoint('Recovered Markup');
// Disable attributes that can cause loading of external resources
var disabledHead = this.disable(captured.headContent)
, disabledBody = this.disable(captured.bodyContent);
Mobify.timing.addPoint('Disabled Markup');
// Reinflate HTML strings back into declawed DOM nodes.
var div = document.createElement('div');
var headEl = makeElement(captured.headTag);
var bodyEl = makeElement(captured.bodyTag);
var htmlEl = makeElement(captured.htmlTag);
var result = {
'doctype' : captured.doctype
, '$head' : $(headEl)
, '$body' : $(bodyEl)
, '$html' : $(htmlEl)
};
for (div.innerHTML = disabledHead; div.firstChild; headEl.appendChild(div.firstChild));
for (div.innerHTML = disabledBody; div.firstChild; bodyEl.appendChild(div.firstChild));
htmlEl.appendChild(headEl);
htmlEl.appendChild(bodyEl);
Mobify.timing.addPoint('Built Passive DOM');
return result;
}
});
})(Mobify.$, Mobify);
|
JavaScript
| 0.000001 |
@@ -2550,17 +2550,8 @@
%5D);%0A
- %C2%A0
%0A
|
e17ba2069a526d24bc941c7df60c8f4aee822c99
|
Fix ref cycle of Async JS contexts
|
src/mainjs/async.js
|
src/mainjs/async.js
|
/*
* Copyright 2017 Jiří Janoušek <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var Async = {};
Async.nextPromiseId = 1;
Async.promises = {}
Async.MAX_PROMISE_ID = 32767;
Async.begin = function (func) {
var ctx = {};
while (this.promises[this.nextPromiseId]) {
if (this.nextPromiseId === this.MAX_PROMISE_ID) {
this.nextPromiseId = 1;
} else {
this.nextPromiseId++;
}
}
this.promises[this.nextPromiseId] = ctx;
ctx.id = this.nextPromiseId;
ctx.promise = new Promise(function(resolve, reject){ctx.resolve = resolve; ctx.reject = reject;});
try {
func(ctx);
} catch (error) {
ctx.reject(error);
delete this.promises[ctx.id];
}
return ctx.promise;
}
Async.call = function(path, params) {
return this.begin((ctx) => Nuvola._callIpcMethodAsync(path, params || null, ctx.id));
}
Async.respond = function(id, response, error) {
var ctx = this.promises[id];
if (ctx) {
delete this.promises[id];
if (error) {
ctx.reject(error);
} else {
ctx.resolve(response);
}
} else {
throw new Error("Promise " + id + " not found.");
}
}
Nuvola.Async = Async;
|
JavaScript
| 0.000001 |
@@ -1904,16 +1904,94 @@
rror);%0A%09
+%09this.remove(ctx);%0A%09%7D%0A%09return ctx.promise;%0A%7D%0A%0AAsync.remove = function (ctx) %7B%0A
%09delete
@@ -2015,33 +2015,94 @@
.id%5D
-;
%0A%09
-%7D%0A%09return ctx.promise;
+// Break reference cycles%0A%09delete ctx.promise%0A%09delete ctx.reject%0A%09delete ctx.resolve
%0A%7D%0A%0A
@@ -2323,36 +2323,8 @@
) %7B%0A
-%09%09delete this.promises%5Bid%5D;%0A
%09%09if
@@ -2397,16 +2397,36 @@
e);%0A%09%09%7D%0A
+%09%09this.remove(ctx);%0A
%09%7D else
|
9e8474998556246562fa60fdf10506f8815d712e
|
refactor splun analytics for es6
|
lib/core/analytics/splunk.js
|
lib/core/analytics/splunk.js
|
(function(root) {
'use strict';
var availity = root.availity;
availity.core.factory('avSplunkAnalytics', function($log, avLogMessagesResource, $location) {
var SplunkAnalyticsService = function() {};
var proto = SplunkAnalyticsService.prototype;
proto.trackEvent = function(properties) {
properties.url = $location.$$absUrl || 'N/A';
properties.level = properties.level || 'info';
return avLogMessagesResource[properties.level](properties);
};
proto.trackPageView = function(url) {
var properties = {
event: 'page',
level: 'info',
url: url || $location.$$absUrl()
};
return avLogMessagesResource[properties.level](properties);
};
proto.isEnabled = function() {
return true;
};
return new SplunkAnalyticsService();
});
})(window);
|
JavaScript
| 0.000055 |
@@ -1,24 +1,4 @@
-(function(root) %7B%0A
'use
@@ -8,21 +8,22 @@
rict';%0A%0A
- var
+import
availit
@@ -28,28 +28,27 @@
ity
-= root.availity
+from '../module'
;%0A%0A
-
avai
@@ -144,137 +144,54 @@
%0A%0A
- var SplunkAnalyticsService = function() %7B%7D;%0A%0A var proto = SplunkAnalyticsService.prototype;%0A%0A proto.trackEvent = function
+class SplunkAnalyticsService %7B%0A%0A trackEvent
(pro
@@ -197,24 +197,25 @@
operties) %7B%0A
+%0A
proper
@@ -379,29 +379,22 @@
);%0A %7D
-;
%0A%0A
-proto.
trackPag
@@ -402,20 +402,8 @@
View
- = function
(url
@@ -417,11 +417,11 @@
-var
+let
pro
@@ -604,21 +604,14 @@
%7D
-;
%0A%0A
-proto.
isEn
@@ -619,19 +619,8 @@
bled
- = function
() %7B
@@ -644,21 +644,23 @@
e;%0A %7D
-;
%0A%0A
+%7D%0A%0A
return
@@ -694,23 +694,9 @@
();%0A
-
%7D);%0A%0A
-%7D)(window);%0A
|
58698268063afcd71ab8dd7fd6d1fe7599212490
|
remove unnecessary promise
|
lib/check-self-update/fetch-module-registry-info.js
|
lib/check-self-update/fetch-module-registry-info.js
|
const parseJson = require('./parse-json');
const requestPromise = require('./request-promise');
const getModuleRegistryUrl = require('./get-module-registry-url');
/* Fetches a json object with module info when given its name */
const fetchModuleRegistryInfo = (name) => {
return new Promise((resolve, reject) => {
const url = getModuleRegistryUrl(name);
requestPromise(url).then(parseJson).then(resolve).catch(reject);
})
}
module.exports = fetchModuleRegistryInfo;
|
JavaScript
| 0.000622 |
@@ -270,56 +270,10 @@
=%3E %7B
-%0A return new Promise((resolve, reject) =%3E %7B
%0A%0A
-
co
@@ -310,19 +310,25 @@
(name);%0A
+%0A
-
+return
request
@@ -359,43 +359,10 @@
son)
-.then(resolve).catch(reject);%0A%0A %7D)
+;%0A
%0A%7D%0A%0A
|
9bdd69fc11e600734b4519ae60213fc3963570d1
|
add rate limiter
|
apiserver.js
|
apiserver.js
|
var querystring = require('querystring');
var express = require('express');
var Busboy = require('busboy');
var app = express();
var ejs = require('ejs');
var crypto = require('crypto');
var nodefn = require('when/node');
var site = require('./site');
var util = require('util');
var microformat = require('./microformat');
app.set('views', './template');
app.set('view engine', 'ejs');
// store the last code issued by the auth endpoint in memory
var lastIssuedCode = null;
function parsePost(req, res, next) {
if (req.method === 'POST') {
var busboy = new Busboy({headers: req.headers});
req.post = {};
busboy.on('field', function (fieldname, val) {
req.post[fieldname] = val;
});
busboy.on('finish', function () {
next();
});
req.pipe(busboy);
} else {
next();
}
}
function logger(req, res, next) {
var parms = (req.method == 'POST' ? req.post : req.query);
util.log(util.format('%s %s %s', req.ip, req.method, req.url));
if (Object.keys(parms).length > 0)
console.log(util.format('%s', util.inspect(req.method == 'POST' ? req.post : req.query)));
next();
}
app.use(parsePost);
app.use(logger);
app.get('/auth', function(req, res) {
res.render('authform', req.query);
});
app.post('/auth', function(req, res) {
if (req.post.password === site.password) {
nodefn.call(crypto.randomBytes, 18).
then(function (buf) {
var code = buf.toString('base64');
lastIssuedCode = {
code: code,
client_id: req.post.client_id,
scope: req.post.scope,
date: new Date()
};
res.redirect(req.post.redirect_uri + '?' +
querystring.stringify({code: code, state: req.post.state, me: site.url}));
});
} else {
util.log('Failed password authentication from ' + req.ip);
res.sendStatus(401);
}
});
app.post('/token', function(req, res) {
if (lastIssuedCode !== null &&
lastIssuedCode.code === req.post.code &&
((new Date() - lastIssuedCode.date) < 60 * 1000)) {
site.generateToken(lastIssuedCode.client_id, lastIssuedCode.scope).
then(function (result) {
lastIssuedCode = null;
if (result === undefined) {
res.sendStatus(500);
} else {
res.type('application/x-www-form-urlencoded');
res.send(querystring.stringify({access_token: result.token, scope: result.scope, me: site.url}));
}
});
} else {
util.log('Failed token request from ' + req.ip);
res.sendStatus(401);
}
});
app.post('/micropub', function(req, res) {
site.hasAuthorization(req, 'post').
then(function(authorized) {
if (!authorized) {
util.log('Failed micropub post from ' + req.ip);
res.sendStatus(401);
} else {
site.getSlug(null).
then(function (slug) {
var entry = new microformat.Entry(slug);
entry.published[0] = new Date().toISOString();
entry.author[0] = {
url: [site.url]
};
entry.content[0] = {
value: req.post.content,
html: req.post.content
};
return entry;
}).
then(site.store).
then(site.generateIndex).
then(function () {
res.sendStatus(201);
});
}
});
});
app.get('/tokens', function(req, res) {
site.listTokens().then(res.json.bind(res));
});
var server = app.listen(process.argv[2], function (){
var address = server.address();
console.log('Listening on %s:%s', address.address, address.port);
});
|
JavaScript
| 0.000001 |
@@ -865,16 +865,417 @@
%7D%0A%7D%0A%0A
+function rateLimit(count, cooldown) %7B%0A var lastreq = new Date();%0A var capacity = count;%0A return function(req, res, next) %7B%0A capacity = Math.min(capacity + (new Date() - lastreq) * (count / cooldown), count);%0A if (capacity %3E= 1) %7B%0A capacity--;%0A lastreq = new Date();%0A next();%0A %7D else %7B%0A res.sendStatus(429);%0A %7D%0A %7D;%0A%7D%0A%0A
function
@@ -1296,24 +1296,24 @@
es, next) %7B%0A
-
var parm
@@ -1713,32 +1713,62 @@
pp.post('/auth',
+ rateLimit(3, 1000 * 60 * 10),
function(req, r
@@ -2445,32 +2445,32 @@
01);%0A %7D%0A%7D);%0A%0A
-
app.post('/token
@@ -2471,16 +2471,41 @@
/token',
+ rateLimit(3, 1000 * 60),
functio
|
d3bebf7ccbae7f4d786458a246aece86a07190d8
|
add a catch statement here
|
api/services/SyncService.js
|
api/services/SyncService.js
|
var Promise = require('promise');
var log4js = require('log4js');
var logger = log4js.getLogger();
var SlackWebhook = require('slack-webhook');
var slack = process.env.SLACK_WEBHOOK ? new SlackWebhook(process.env.SLACK_WEBHOOK, {
defaults: {
username: 'JukeBot'
}
}) : null;
module.exports = {
addVideo: addVideo,
sendAddMessages: sendAddMessages
};
function addVideo(video) {
logger.info('Adding video ' + video.key)
return new Promise(function(resolve, reject) {
Video.findOne({
playing: true
}).exec(function(err, current) {
if (!current) {
video.startTime = new Date();
video.playing = true;
video.played = true;
setTimeout(endCurrentVideo, video.durationSeconds * 1000);
video.save(function() {
resolve(video);
});
} else {
resolve(video);
}
});
});
}
function sendAddMessages(video) {
return new Promise(function(resolve, reject) {
Video.publishCreate(video);
if (slack) {
slack.send({
text: '@' + video.user + ' added a song to the playlist' + (video.playing ? ' and it\'s playing now' : '') + '! <' + sails.config.serverUrl + '|Listen to JukeBot>',
attachments: [formatSlackAttachment(video)]
}).then(function() {
resolve(video);
});
} else {
resolve(video);
}
});
}
function formatSlackAttachment(video) {
return {
title: video.title,
title_link: 'https://www.youtube.com/watch?v=' + video.key,
thumb_url: video.thumbnail
};
}
function endCurrentVideo() {
Video.findOne({
playing: true
}).exec(function(err, current) {
current.playing = false;
current.save(function() {
logger.info('Publishing end song ' + current.key);
Video.publishUpdate(current.id, current);
findNextVideo();
});
});
}
function findNextVideo() {
Video.find({
played: false
}).sort('createdAt ASC').exec(function(err, upcoming) {
if (upcoming.length > 0) {
startVideo(upcoming[0]);
}
});
}
function startVideo(video) {
video.playing = true;
video.played = true;
video.startTime = new Date();
logger.info('Setting timeout');
setTimeout(endCurrentVideo, video.durationSeconds * 1000);
video.save(function() {
logger.info('Stopping video ' + video.key);
Video.publishUpdate(video.id, video);
if (slack) {
slack.send({
text: '*' + video.title + '* is now playing! <' + sails.config.serverUrl + '|Listen to JukeBot>',
'mrkdwn': true
}).then(function() {
logger.info('Started playing video ' + video.key);
});
} else {
logger.info('Started playing video ' + video.key);
}
});
}
|
JavaScript
| 0.000381 |
@@ -2247,35 +2247,37 @@
%0A video
+%0A
.save(
-function() %7B%0A
+() =%3E %7B%0A
logg
@@ -2316,24 +2316,26 @@
o.key);%0A
+
Video.publis
@@ -2352,32 +2352,34 @@
deo.id, video);%0A
+
if (slack) %7B
@@ -2377,32 +2377,34 @@
(slack) %7B%0A
+
slack.send(%7B%0A
@@ -2392,32 +2392,34 @@
slack.send(%7B%0A
+
text: '*
@@ -2516,16 +2516,18 @@
+
'mrkdwn'
@@ -2535,24 +2535,26 @@
true%0A
+
+
%7D).then(func
@@ -2554,32 +2554,34 @@
en(function() %7B%0A
+
logger.i
@@ -2621,36 +2621,40 @@
deo.key);%0A
+
%7D);%0A
+
%7D else %7B%0A
@@ -2648,32 +2648,34 @@
%7D else %7B%0A
+
+
logger.info('Sta
@@ -2709,22 +2709,100 @@
o.key);%0A
+
%7D%0A
+
-%7D
+ %7D)%0A .catch((e) =%3E logger.info(%60Unable to save video $%7Bvideo.key%7D - $%7Be%7D%60
);%0A%7D%0A
|
6529aa52ee1b3f62c2293c9b355b42c507439334
|
Fix Admin and Founder User Create
|
server/boot/userScript.js
|
server/boot/userScript.js
|
var methodDisabler = require('../../public/methodDisabler.js')
var relationMethodPrefixes = [
'login',
'logout'
]
module.exports = function (app) {
var User = app.models.client
var Role = app.models.Role
var RoleMapping = app.models.RoleMapping
var users = [{
id: 98989878,
username: 'MrWooJ',
email: '[email protected]',
password: 'Fl13r4lAlirezaPass',
time: 1234567891,
companyName: "Flieral",
registrationCountry: "US",
registrationIPAddress: "0.0.0.0",
emailVerified: true
},
{
id: 98989857,
username: 'Mohammad4x',
email: '[email protected]',
password: 'Fl13r4lMohammadPass',
time: 1234567891,
companyName: "Flieral",
registrationCountry: "US",
registrationIPAddress: "0.0.0.0",
emailVerified: true
},
{
id: 98989873,
username: 'Support',
email: '[email protected]',
password: 'Fl13r4lSupportPass',
time: 1234567891,
companyName: "Flieral",
registrationCountry: "US",
registrationIPAddress: "0.0.0.0",
emailVerified: true
}
]
User.replaceOrCreate(users, null, function (err, users) {
if (err)
throw err
var role1 = {
name: 'founder'
}
Role.create(role1, function (err, role) {
if (err)
throw err
role.principals.create({
principalType: RoleMapping.USER,
principalId: users[0].id
}, function (err, principal) {
if (err)
throw err
})
role.principals.create({
principalType: RoleMapping.USER,
principalId: users[1].id
}, function (err, principal) {
if (err)
throw err
})
})
var role2 = {
name: 'admin'
}
Role.create(role2, function (err, role) {
if (err)
throw err
role.principals.create({
principalType: RoleMapping.USER,
principalId: users[2].id
}, function (err, principal) {
if (err)
throw err
})
})
})
}
|
JavaScript
| 0 |
@@ -1,156 +1,78 @@
-var methodDisabler = require('../../public/methodDisabler.js')%0Avar relationMethodPrefixes = %5B%0A 'login',%0A 'logout'%0A%5D%0A%0Amodule.exports = function (app) %7B
+module.exports = function (app) %7B%0A var mongoDs = app.dataSources.mongoDs%0A
%0A v
@@ -193,28 +193,8 @@
%5B%7B%0A
- id: 98989878,%0A
@@ -455,28 +455,8 @@
%7B%0A
- id: 98989857,%0A
@@ -722,28 +722,8 @@
%7B%0A
- id: 98989873,%0A
@@ -989,95 +989,37 @@
%0A%0A
-User.replaceOrCreate(users, null, function (err, users) %7B%0A if (err)%0A throw err%0A
+function createRoles(users) %7B
%0A
@@ -1053,32 +1053,33 @@
'founder'%0A %7D%0A
+%0A
Role.create(
@@ -1843,16 +1843,303 @@
%0A %7D)%0A
+ %7D%0A%0A User.create(users, function (err, users) %7B%0A if (err) %7B%0A User.find(%7B%0A where: %7B%0A 'companyName': 'Flieral'%0A %7D%0A %7D, function (err, users) %7B%0A if (err)%0A throw err%0A createRoles(users)%0A %7D)%0A %7D else%0A createRoles(users)%0A
%7D)%0A%0A%7D%0A
|
f980b4d16e786ac3909b11d5f1926fdd735464ef
|
fix regression
|
app/assets/javascripts/discourse/models/action_summary.js
|
app/assets/javascripts/discourse/models/action_summary.js
|
/**
A data model for summarizing actions a user has taken, for example liking a post.
@class ActionSummary
@extends Discourse.Model
@namespace Discourse
@module Discourse
**/
Discourse.ActionSummary = Discourse.Model.extend({
// Description for the action
description: function() {
var action = this.get('actionType.name_key');
if (this.get('acted')) {
if (this.get('count') <= 1) {
return Em.String.i18n('post.actions.by_you.' + action);
} else {
return Em.String.i18n('post.actions.by_you_and_others.' + action, { count: this.get('count') - 1 });
}
} else {
return Em.String.i18n('post.actions.by_others.' + action, { count: this.get('count') });
}
}.property('count', 'acted', 'actionType'),
canAlsoAction: function() {
if (this.get('hidden')) return false;
return this.get('can_act');
}.property('can_act', 'hidden'),
// Remove it
removeAction: function() {
this.set('acted', false);
this.set('count', this.get('count') - 1);
this.set('can_act', true);
return this.set('can_undo', false);
},
// Perform this action
act: function(opts) {
var action = this.get('actionType.name_key');
// Mark it as acted
this.set('acted', true);
this.set('count', this.get('count') + 1);
this.set('can_act', false);
this.set('can_undo', true);
if(action === 'notify_moderators' || action === 'notify_user') {
this.set('can_undo',false);
this.set('can_clear_flags',false);
}
// Add ourselves to the users who liked it if present
if (this.present('users')) {
this.users.pushObject(Discourse.get('currentUser'));
}
// Create our post action
var actionSummary = this;
Discourse.ajax({
url: Discourse.getURL("/post_actions"),
type: 'POST',
data: {
id: this.get('post.id'),
post_action_type_id: this.get('id'),
message: (opts ? opts.message : void 0) || ""
}
}).then(null, function (error) {
actionSummary.removeAction();
var message = $.parseJSON(error.responseText).errors;
bootbox.alert(message);
});
},
// Undo this action
undo: function() {
this.removeAction();
// Remove our post action
return Discourse.ajax({
url: Discourse.getURL("/post_actions/") + (this.get('post.id')),
type: 'DELETE',
data: {
post_action_type_id: this.get('id')
}
});
},
clearFlags: function() {
var actionSummary = this;
return Discourse.ajax(Discourse.getURL("/post_actions/clear_flags"), {
type: "POST",
data: {
post_action_type_id: this.get('id'),
id: this.get('post.id')
}
}).then(function(result) {
actionSummary.set('post.hidden', result.hidden);
actionSummary.set('count', 0);
});
},
loadUsers: function() {
var actionSummary = this;
Discourse.ajax(Discourse.getURL("/post_actions/users"), {
data: {
id: this.get('post.id'),
post_action_type_id: this.get('id')
}
}).then(function (result) {
var users = Em.A();
actionSummary.set('users', users);
result.each(function(u) {
users.pushObject(Discourse.User.create(u));
});
});
}
});
|
JavaScript
| 0.000001 |
@@ -1724,36 +1724,44 @@
Summary = this;%0A
+%0A
+return
Discourse.ajax(%7B
|
42d85a5db73b0fbb41d3910f84c9d45e8395cab8
|
Refactor loop
|
mac/resources/open_ASND.js
|
mac/resources/open_ASND.js
|
define(function() {
'use strict';
var DELTAS = new Int8Array([0, -49, -36, -25, -16, -9, -4, -1, 0, 1, 4, 9, 16, 25, 36, 49]);
function open(item) {
return item.getBytes().then(function(bytes) {
var samples = new Uint8Array(2 * (bytes.length - 20));
var value = 0x80;
for (var i = 0; i < samples.length; i++) {
var index = 20 + (i >> 1);
value += (i % 2) ? DELTAS[bytes[index] >> 4] : DELTAS[bytes[index] & 0xf];
value &= 0xff;
samples[i] = value; // (value << 24 >> 24) + 128;
}
item.setRawAudio({
channels: 1,
samplingRate: 11000,
bytesPerSample: 1,
samples: samples,
});
});
}
return open;
});
|
JavaScript
| 0.000008 |
@@ -199,24 +199,58 @@
on(bytes) %7B%0A
+ bytes = bytes.subarray(20);%0A
var sa
@@ -276,17 +276,16 @@
ray(2 *
-(
bytes.le
@@ -292,14 +292,8 @@
ngth
- - 20)
);%0A
@@ -341,21 +341,19 @@
0; i %3C
-sampl
+byt
es.lengt
@@ -376,31 +376,37 @@
va
-r index = 20 + (i %3E%3E 1)
+lue += DELTAS%5Bbytes%5Bi%5D & 0xf%5D
;%0A
@@ -421,68 +421,86 @@
lue
-+= (i %25 2) ? DELTAS%5Bbytes%5Bindex%5D %3E%3E 4%5D : DELTAS%5Bbytes%5Bindex%5D
+&= 0xff;%0A samples%5Bi*2%5D = value;%0A value += deltas%5B(bytes%5Bi%5D %3E%3E 4)
& 0
@@ -544,16 +544,22 @@
amples%5Bi
+*2 + 1
%5D = valu
@@ -564,38 +564,8 @@
lue;
- // (value %3C%3C 24 %3E%3E 24) + 128;
%0A
|
8a9bb542baf3e7909fa4e9570e61b5eb8ef03400
|
Fix uglify problem
|
client/api-box.js
|
client/api-box.js
|
var apiData = function (options) {
options = options || {};
if (typeof options === "string") {
options = {name: options};
}
var root = DocsData[options.name];
if (! root) {
console.log("API Data not found: " + options.name);
}
if (_.has(options, 'options')) {
root = _.clone(root);
var includedOptions = options.options.split(';');
root.options = _.filter(root.options, function (option) {
return _.contains(includedOptions, option.name);
});
}
return root;
};
var typeLink = function (displayName, url) {
return "<a href='" + url + "'>" + displayName + "</a>";
};
var toOrSentence = function (array) {
if (array.length === 1) {
return array[0];
} else if (array.length === 2) {
return array.join(" or ");
}
return _.initial(array).join(", ") + ", or " + _.last(array);
};
var typeNameTranslation = {
"function": "Function",
EJSON: typeLink("EJSON-able Object", "#ejson"),
EJSONable: typeLink("EJSON-able Object", "#ejson"),
"Tracker.Computation": typeLink("Tracker.Computation", "#tracker_computation"),
MongoSelector: [
typeLink("Mongo Selector", "#selectors"),
typeLink("Object ID", "#mongo_object_id"),
"String"
],
MongoModifier: typeLink("Mongo Modifier", "#modifiers"),
MongoSortSpecifier: typeLink("Mongo Sort Specifier", "#sortspecifiers"),
MongoFieldSpecifier: typeLink("Mongo Field Specifier", "#fieldspecifiers"),
JSONCompatible: "JSON-compatible Object",
EventMap: typeLink("Event Map", "#eventmaps"),
DOMNode: typeLink("DOM Node", "https://developer.mozilla.org/en-US/docs/Web/API/Node"),
"Blaze.View": typeLink("Blaze.View", "#blaze_view"),
Template: typeLink("Blaze.Template", "#blaze_template"),
DOMElement: typeLink("DOM Element", "https://developer.mozilla.org/en-US/docs/Web/API/element"),
MatchPattern: typeLink("Match Pattern", "#matchpatterns"),
"DDP.Connection": typeLink("DDP Connection", "#ddp_connect")
};
Template.autoApiBox.helpers({
apiData: apiData,
typeNames: function typeNames (nameList) {
// change names if necessary
nameList = _.map(nameList, function (name) {
// decode the "Array.<Type>" syntax
if (name.slice(0, 7) === "Array.<") {
// get the part inside angle brackets like in Array<String>
name = name.match(/<([^>]+)>/)[1];
if (name && typeNameTranslation.hasOwnProperty(name)) {
return "Array of " + typeNameTranslation[name] + "s";
}
if (name) {
return "Array of " + name + "s";
}
console.log("no array type defined");
return "Array";
}
if (typeNameTranslation.hasOwnProperty(name)) {
return typeNameTranslation[name];
}
if (DocsData[name]) {
return typeNames(DocsData[name].type);
}
return name;
});
nameList = _.flatten(nameList);
return toOrSentence(nameList);
},
signature: function () {
var signature;
var escapedLongname = _.escape(this.longname);
if (this.istemplate || this.ishelper) {
if (this.istemplate) {
signature = "{{> ";
} else {
signature = "{{ ";
}
signature += escapedLongname;
var params = this.params;
var paramNames = _.map(params, function (param) {
var name = param.name;
name = name + "=" + name;
if (param.optional) {
return "[" + name + "]";
}
return name;
});
signature += " " + paramNames.join(" ");
signature += " }}";
} else {
var beforeParens;
if (this.scope === "instance") {
beforeParens = "<em>" + apiData(this.memberof).instancename + "</em>." + this.name;
} else if (this.kind === "class") {
beforeParens = "new " + escapedLongname;
} else {
beforeParens = escapedLongname;
}
signature = beforeParens;
// if it is a function, and therefore has arguments
if (_.contains(["function", "class"], this.kind)) {
var params = this.params;
var paramNames = _.map(params, function (param) {
if (param.optional) {
return "[" + param.name + "]";
}
return param.name;
});
signature += "(" + paramNames.join(", ") + ")";
}
}
return signature;
},
importName() {
const noImportNeeded = !this.module
|| this.scope === 'instance'
|| this.ishelper
|| this.istemplate;
// override the above we've explicitly decided to (i.e. Template.foo.X)
if (!noImportNeeded || this.importfrompackage) {
if (this.memberof) {
return this.memberof.split('.')[0];
} else {
return this.name;
}
}
},
id: function () {
if (Session.get("fullApi") && nameToId[this.longname]) {
return nameToId[this.longname];
}
// fallback
return this.longname.replace(/[.#]/g, "-");
},
paramsNoOptions: function () {
return _.reject(this.params, function (param) {
return param.name === "options";
});
},
fullApi: function () {
return Session.get("fullApi");
}
});
Template.apiBoxTitle.helpers({
link: function () {
return '#/' + (Session.get("fullApi") ? 'full' : 'basic') + '/' + this.id;
}
});
Template.autoApiBox.onRendered(function () {
this.$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
|
JavaScript
| 0.000399 |
@@ -4337,16 +4337,27 @@
portName
+: function
() %7B%0A
|
a4f1c4fed9d66d80d6213ecc6ba7ee4b60190c45
|
fix last color variables
|
source/views/components/toolbar/toolbar-button.js
|
source/views/components/toolbar/toolbar-button.js
|
// @flow
import * as React from 'react'
import {StyleSheet, View, Text, Platform} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import * as c from '../../components/colors'
const buttonStyles = StyleSheet.create({
button: {
flexDirection: 'row',
alignItems: 'center',
marginRight: 8,
paddingHorizontal: 8,
paddingVertical: 0,
marginVertical: 8,
borderWidth: 1,
borderRadius: 2,
},
activeButton: {
backgroundColor: c.accent,
borderColor: c.accent,
},
inactiveButton: {
borderColor: c.iosDisabledText,
},
activeText: {
color: c.white,
},
inactiveText: {
color: c.iosDisabledText,
},
textWithIcon: {
paddingRight: 8,
},
})
type ButtonPropsType = {
iconName?: string,
title: string,
isActive: boolean,
}
export function ToolbarButton({title, iconName, isActive}: ButtonPropsType) {
let icon
if (!iconName) {
icon = null
} else if (Platform.OS === 'ios') {
icon = iconName
} else if (Platform.OS === 'android') {
icon = iconName
}
let activeButtonStyle = isActive
? buttonStyles.activeButton
: buttonStyles.inactiveButton
let activeContentStyle = isActive
? buttonStyles.activeText
: buttonStyles.inactiveText
let textWithIconStyle = icon ? buttonStyles.textWithIcon : null
let activeTextStyle = {
fontWeight: isActive && Platform.OS === 'android' ? 'bold' : 'normal',
}
return (
<View style={[buttonStyles.button, activeButtonStyle]}>
<Text style={[activeContentStyle, textWithIconStyle, activeTextStyle]}>
{title}
</Text>
{icon ? <Icon name={icon} size={18} style={activeContentStyle} /> : null}
</View>
)
}
|
JavaScript
| 0.000002 |
@@ -463,39 +463,73 @@
: c.
-accent,%0A%09%09borderColor: c.accent
+toolbarButtonBackground,%0A%09%09borderColor: c.toolbarButtonBackground
,%0A%09%7D
@@ -617,13 +617,31 @@
: c.
-white
+toolbarButtonForeground
,%0A%09%7D
|
4ae7562dfc7ba63ae746aa4c8595407b41598a7a
|
fix merge conflict
|
src/main/webapp/WEB-INF/themes/desktop/resource/js/pages/search_results.js
|
src/main/webapp/WEB-INF/themes/desktop/resource/js/pages/search_results.js
|
(function ($) {
function handleUndefinedMetric(metric) {
return metric == undefined ? 'None' : metric;
}
function appendOrRemoveLink(link, metric) {
metric = handleUndefinedMetric(metric);
if (metric == 'None') {
link.html(link.html() + ' ' + metric);
link.contents().unwrap();
} else {
link.append(metric);
}
}
$(document).ready(function() {
$('.search-results-alm').each(function () {
var $alm = $(this);
var doi = $alm.data('doi');
$alm.getArticleSummary(doi, function (almData) { //success function
var almLinks = $alm.find('a');
var viewsLink = $(almLinks[0]);
appendOrRemoveLink(viewsLink, almData.viewed);
var citationsLink = $(almLinks[1]);
appendOrRemoveLink(citationsLink, almData.cited);
var savesLink = $(almLinks[2]);
appendOrRemoveLink(savesLink, almData.saved);
var sharesLink = $(almLinks[3]);
appendOrRemoveLink(sharesLink, almData.shared);
$alm.siblings('.search-results-alm-loading').fadeOut('slow', function () {
$alm.fadeIn();
})
}, function () { //error function
$alm.siblings('.search-results-alm-loading').fadeOut('slow', function () {
$alm.siblings('.search-results-alm-error').fadeIn();
})
});
});
});
})(jQuery);
|
JavaScript
| 0.000001 |
@@ -1334,16 +1334,111 @@
%0A %7D);
+%0A%0A $('#sortOrder').on('change', function() %7B%0A $(this).parents('form').submit();%0A %7D);
%0A %7D);%0A%7D
|
8ce92a58fa63fb5592f03fd43002b9616234c809
|
fix binding creation
|
src/auth0/handlers/actionBindings.js
|
src/auth0/handlers/actionBindings.js
|
import DefaultHandler from './default';
import log from '../../logger';
const triggers = [
'post-login',
'credentials-exchange'
];
function wait(n) { return new Promise(resolve => setTimeout(resolve, n)); }
async function createBindingWithRetryAndTimeout(client, params, data, retry) {
let binding = {};
try {
if (retry > 0) {
binding = await client.createActionBinding(params, data);
}
} catch (err) {
await wait(1000);
binding = await createBindingWithRetryAndTimeout(client, params, data, retry - 1);
}
return binding;
}
export default class ActionBindingHandler extends DefaultHandler {
constructor(options) {
super({
...options,
type: 'actionBindings'
});
}
async getType() {
if (this.existing) {
return this.existing;
}
// in case client version does not support actions
if (
!this.client.actionBindings
|| typeof this.client.actionBindings.getAll !== 'function'
) {
return [];
}
const bindingsResult = [];
try {
await Promise.all(
triggers.map(trigger => this.client.actionBindings
.getAll({ trigger_id: trigger, detached: true })
.then(b => b.bindings.forEach(binding => bindingsResult.push({ detached: true, ...binding }))))
);
// get all attached bindings
await Promise.all(
triggers.map(trigger => this.client.actionBindings
.getAll({ trigger_id: trigger, detached: false })
.then(b => b.bindings.forEach(binding => bindingsResult.push({ detached: false, ...binding }))))
);
this.existing = bindingsResult;
return this.existing;
} catch (err) {
if (err.statusCode === 404 || err.statusCode === 501) {
return [];
}
throw err;
}
}
async detachBinding(binding, detached) {
const params = { trigger_id: binding.trigger_id };
const existing = await this.getType();
let attachedList = [];
existing.forEach((existingBinding) => {
if (!existingBinding.detached) {
attachedList.push({ id: existingBinding.id });
}
});
if (!detached) {
attachedList.push({ id: binding.id });
} else {
attachedList = attachedList.filter(id => id === binding.id);
}
delete params.binding_id;
await this.client.actionBindings.updateList(params, {
bindings: attachedList
});
}
// Create Binding creates a atacched binding
async createActionBinding(data) {
const retries = 10;
const params = { trigger_id: data.trigger_id };
const actionBinding = { ...data };
const created = await createBindingWithRetryAndTimeout(this.client, params, actionBinding, retries);
if (!created) {
throw new Error(`Couldn't create binding after ${retries} retries`);
}
// connect binding
await this.detachBinding(created, false);
return created;
}
async createActionBindings(creates) {
await this.client.pool
.addEachTask({
data: creates || [],
generator: item => this.createActionBinding(item)
.then((data) => {
this.didCreate({ binding_id: data.id });
this.created += 1;
})
.catch((err) => {
throw new Error(
`Problem creating ${this.type} ${this.objString(item)}\n${err}`
);
})
})
.promise();
}
async deleteActionBinding(binding) {
// detach binding
await this.detachBinding(binding, true);
// delete binding
await this.client.actionBindings.delete({
trigger_id: binding.trigger_id,
binding_id: binding.id
});
}
async deleteActionBindings(dels) {
if (this.config('AUTH0_ALLOW_DELETE') === 'true' || this.config('AUTH0_ALLOW_DELETE') === true) {
await this.client.pool
.addEachTask({
data: dels || [],
generator: item => this.deleteActionBinding(item)
.then(() => {
this.didDelete({ binding_id: item.id });
this.deleted += 1;
})
.catch((err) => {
throw new Error(`Problem deleting ${this.type} ${this.objString(item)}\n${err}`);
})
})
.promise();
} else {
log.warn(`Detected the following actions bindings should be deleted. Doing so may be destructive.\nYou can enable deletes by setting 'AUTH0_ALLOW_DELETE' to true in the config
\n${dels.map(i => this.objString(i)).join('\n')}`);
}
}
async calcChanges(action, bindingsTriggers, existing) {
// Calculate the changes required between two sets of assets.
let del = [ ...existing ];
const create = [];
bindingsTriggers.forEach((binding) => {
const found = existing.find(
existingActionBinding => existingActionBinding.trigger_id === binding.trigger_id
);
if (found) {
del = del.filter(e => e !== found);
} else {
create.push({
display_name: action.name,
action_id: action.id,
trigger_id: binding.trigger_id
});
}
});
// Figure out what needs to be deleted and created
return { del, create };
}
async processChanges(changes) {
log.info(
`Start processChanges for actions bindings [delete:${changes.del.length}], [create:${changes.create.length}]`
);
const myChanges = [ { del: changes.del }, { create: changes.create } ];
await Promise.all(
myChanges.map(async (change) => {
switch (true) {
case change.del && change.del.length > 0:
await this.deleteActionBindings(change.del);
break;
case change.create && change.create.length > 0:
await this.createActionBindings(changes.create);
break;
default:
break;
}
})
);
}
}
|
JavaScript
| 0 |
@@ -1943,18 +1943,18 @@
let at
-t
a
+c
chedList
@@ -2045,34 +2045,34 @@
ed) %7B%0A at
-t
a
+c
chedList.push(%7B
@@ -2135,34 +2135,34 @@
ched) %7B%0A at
-t
a
+c
chedList.push(%7B
@@ -2201,18 +2201,18 @@
at
-t
a
+c
chedList
@@ -2216,18 +2216,18 @@
ist = at
-t
a
+c
chedList
@@ -2372,18 +2372,18 @@
ings: at
-t
a
+c
chedList
@@ -2587,15 +2587,66 @@
= %7B
-...data
+action_id: data.action_id, display_name: data.display_name
%7D;%0A
|
f34b2418cf100799b5f689d961515bd6085056b3
|
Remove extraneous showmatch routes
|
client/app/app.js
|
client/app/app.js
|
angular.module( 'moviematch', [
'moviematch.auth',
'moviematch.match',
'moviematch.prefs',
'moviematch.sessions',
'moviematch.services',
'moviematch.showmatch',
'ngRoute'
])
.config( function ( $routeProvider ) {
$routeProvider
.when( '/signin', {
templateUrl: 'app/auth/signin.html',
controller: 'AuthController'
})
.when( '/signup', {
templateUrl: 'app/auth/signup.html',
controller: 'AuthController'
})
.when( '/match', {
templateUrl: 'app/match/match.html',
controller: 'MatchController'
})
.when( '/sessions', {
templateUrl: 'app/sessions/joinsessions.html',
controller: 'SessionsController'
})
.when( '/lobby', {
templateUrl: 'app/sessions/sessionlobby.html',
controller: 'SessionsController'
.when( '/showmatch', {
templateUrl: 'app/showmatch/showmatch.html',
controller: 'ShowmatchController'
})
.when( '/showmatch', {
templateUrl: 'app/showmatch/showmatch.html',
controller: 'ShowmatchController'
})
.when( '/showmatch', {
templateUrl: 'app/showmatch/showmatch.html',
controller: 'ShowmatchController'
})
.otherwise({
redirectTo: '/signin'
});
});
|
JavaScript
| 0.000271 |
@@ -811,251 +811,8 @@
er'%0A
- .when( '/showmatch', %7B%0A templateUrl: 'app/showmatch/showmatch.html',%0A controller: 'ShowmatchController'%0A %7D)%0A .when( '/showmatch', %7B%0A templateUrl: 'app/showmatch/showmatch.html',%0A controller: 'ShowmatchController'%0A
|
2ff6de7c92cb4f8f7c18a61d3a1ca9987959b04c
|
fix mp3 to ogg
|
client-raspberry/core/js/controller/home.js
|
client-raspberry/core/js/controller/home.js
|
var controller = angular.module('myLazyClock.controller.home', []);
controller.controller('myLazyClock.controller.home', ['$rootScope', '$scope', '$state', '$localStorage', 'GApi', 'ngAudio', '$interval', 'hotkeys', '$rootScope', '$localStorage',
function homeCtl($rootScope, $scope, $state, $localStorage, GApi, ngAudio, $interval, hotkeys, $rootScope, $localStorage) {
$scope.sound = ngAudio.load("sounds/ring.ogg");
$scope.sound.loop = true;
$scope.sound.volume = 1;
$rootScope.volumeUI = 4;
$scope.alarmClockEvents = [];
$scope.soundStop = false;
$rootScope.darkMode = false;
var interval1;
var interval2;
$scope.stop = function() {
if($scope.sound.progress == 0) {
$rootScope.darkMode = !$rootScope.darkMode;
}
$scope.soundStop = true;
$scope.sound.stop();
}
hotkeys.add({
combo: 's',
description: 'stop ring',
callback: $scope.stop
});
$scope.reload = function() {
getAlarmClockEvent();
}
hotkeys.add({
combo: 'r',
description: 'reload all',
callback: $scope.reload
});
$scope.volumeUp = function() {
if ($localStorage.volume < 4) {
setVolume($rootScope.volumeUI+1);
}
}
hotkeys.add({
combo: 'p',
description: 'up volume',
callback: $scope.volumeUp
});
$scope.volumeDown = function() {
if ($localStorage.volume > 0) {
setVolume($rootScope.volumeUI-1);
}
}
hotkeys.add({
combo: 'm',
description: 'down volume',
callback: $scope.volumeDown
});
if ($localStorage.volume == undefined)
setVolume(4);
else
setVolume($localStorage.volume);
function setVolume(value) {
$scope.sound.volume = (value*0.25).toFixed(2);
$rootScope.volumeUI = value;
$localStorage.volume = value;
}
var secondsSinceLastReload = 0;
var getAlarmClockEvent = function() {
console.log('reload after : '+secondsSinceLastReload)
secondsSinceLastReload = 0;
GApi.execute('myLazyClock', 'alarmClock.item', {alarmClockId: $localStorage.alarmClockId}).then(function(resp) {
$rootScope.alarmClock = resp;
if(resp.user == undefined) {
$interval.cancel(interval1);
$interval.cancel(interval2);
$state.go('webapp.signin');
}
//$scope.sound = ngAudio.load("sounds/"+resp.ringtone+".ogg");
$scope.sound.play();
setVolume($localStorage.volume);
GApi.execute('myLazyClock', 'clockevent.list', {alarmClockId: $localStorage.alarmClockId}).then(function(resp) {
$scope.alarmClockEvents = resp.items;
$scope.error = undefined;
}, function(resp) {
$scope.error = resp;
});
}, function() {
$interval.cancel(interval1);
$interval.cancel(interval2);
$state.go('webapp.signin');
});
}
var getAlarmClockEventLoop = function() {
var update = function() {
var now = new Date().getTime();
if(secondsSinceLastReload == 240) // 4heures en minutes
getAlarmClockEvent();
if($scope.clockEvent != undefined) {
if ($scope.clockEvent.wakeUpDate-now > ($scope.clockEvent.travelDuration*1000)-60000 && $scope.clockEvent.wakeUpDate-now < ($scope.clockEvent.travelDuration*1000)+60000) //
getAlarmClockEvent();
}
secondsSinceLastReload++;
}
update();
interval1 = $interval(function() {
update();
}, 60000);
}
var ringCtl = function() {
var updateRing = function() {
var nextEvent;
var now = new Date().getTime();
if($scope.alarmClockEvents != undefined) {
for(var i= 0; i < $scope.alarmClockEvents.length; i++){
if($scope.alarmClockEvents[i]['wakeUpDate'] == undefined ) {
$scope.alarmClockEvents[i]['wakeUpDate'] = $scope.alarmClockEvents[i]['beginDateTime']-$scope.alarmClockEvents[i]['travelDuration']*1000-$rootScope.alarmClock.preparationTime*1000;
}
if(i == 0)
nextEvent = $scope.alarmClockEvents[i];
else {
if($scope.alarmClockEvents[i]['wakeUpDate'] < nextEvent.wakeUpDate)
nextEvent = $scope.alarmClockEvents[i];
}
if (($scope.alarmClockEvents[i]['wakeUpDate']-now) <= -600000 || (($scope.alarmClockEvents[i]['wakeUpDate']-now) < -1000 && ($scope.alarmClockEvents[i]['wakeUpDate']-now) >= -600000) && $scope.soundStop) {
$scope.sound.stop();
if (i > -1) {
$scope.alarmClockEvents.splice(i--, 1);
}
}
};
}
$scope.clockEvent = nextEvent;
if (nextEvent != undefined) {
if (($scope.clockEvent.wakeUpDate-now) < 0 && ($scope.clockEvent.wakeUpDate-now) >= -1000) {
$scope.sound.play();
$rootScope.darkMode = false;
$scope.soundStop = false;
}
if (($scope.clockEvent.wakeUpDate-now) < -1000 && ($scope.clockEvent.wakeUpDate-now) > -600000) {
$scope.sound.play();
}
}
}
updateRing();
interval2 = $interval(function() {
updateRing();
}, 1000);
}
getAlarmClockEvent();
getAlarmClockEventLoop();
ringCtl();
}
]);
|
JavaScript
| 0.000168 |
@@ -2708,18 +2708,16 @@
-//
$scope.s
@@ -2773,45 +2773,8 @@
%22);%0A
- $scope.sound.play();%0A
|
b56a32d7cb97e6535fbabff1770e06e68585571f
|
Improve forbidden vs not authorized
|
lib/middleware/apiGatewayProxy/lib/authorization.js
|
lib/middleware/apiGatewayProxy/lib/authorization.js
|
const Next = require('./next.js');
const Route = require('./route.js');
const Request = require("./request.js");
const Response = require("./response.js");
const AUTHORIZATION = "apiGatewayProxy.authorization";
class Authorization extends Next {
constructor() {
super();
this._rolesTree = smash.config.get(AUTHORIZATION);
}
_isInTree(role) {
if (typeof role !== 'string') {
throw new Error("First parameter of _isInTree() must be a string, " + this.typeOf(role));
}
if (typeof this._rolesTree.roles === 'object') {
for (let key in this._rolesTree.roles) {
if (key === role) {
return true;
}
}
} else if (this._rolesTree !== undefined) {
throw new Error("Authorization's configuration is not correct");
}
return false;
}
_findParents(role, findedRoles) {
if (typeof role !== 'string') {
throw new Error("First parameter of _findParents() must be a string, " + this.typeOf(role));
}
if (Array.isArray(findedRoles) === false) {
findedRoles = [];
}
for (let key in this._rolesTree.roles) {
if (this._rolesTree.roles[key].childrens) {
if (this._rolesTree.roles[key].childrens.indexOf(role) !== -1) {
findedRoles.push(key);
this._findParents(key, findedRoles);
}
}
}
return findedRoles;
}
buildRouteAuthorizations(route) {
if (!route || route.constructor !== Route) {
throw new Error("First parameter of buildRouteAuthorizations() must be Route object type, " + this.typeOf(route));
}
const authorizations = route.authorizations;
if (authorizations !== null) {
for (let i = 0, length = authorizations.length; i < length; i++) {
if (this._isInTree(authorizations[i]) === true) {
route.addAuthorizations(this._findParents(authorizations[i]));
}
}
}
return this;
}
handleRequest(request, response) {
if (request === undefined || request === null || request.constructor !== Request) {
this.error("First parameter of handleRequest() must be Request object type, " + this.typeOf(request));
return response.internalServerError("Internal server error");
}
if (response === undefined || response === null || response.constructor !== Response) {
this.error("Second parameter of handleRequest() must be Response object type, " + this.typeOf(response));
return response.internalServerError("Internal server error");
}
let route = null;
for (let i = 0, length = request.routes.length; i < length; i++) {
if (request.routes[i].authorizations === null) {
route = request.routes[i];
break;
} else if (request.user && request.routes[i].hasRoles(request.user.roles) === true) {
route = request.routes[i];
break;
}
}
if (route === null) {
this.info("Not authorized " + (request.user ? (request.user.username ? request.user.username + " " + request.user.roles.join(" ") : "anonymous") : "anonymous") + " on path " + request.path);
response.forbidden("not authorized");
} else {
request.route = route;
this.next(request, response);
}
}
}
module.exports = Authorization;
|
JavaScript
| 0 |
@@ -3252,37 +3252,10 @@
-this.info(%22Not authorized %22 +
+if
(re
@@ -3269,11 +3269,11 @@
ser
-? (
+&&
requ
@@ -3293,10 +3293,52 @@
name
- ?
+) %7B%0A this.info(%22Forbidden %22 +
req
@@ -3397,26 +3397,151 @@
%22)
-: %22anonymous%22) : %22
++ %22 on path %22 + request.path);%0A response.forbidden(%22Forbidden%22);%0A %7D else %7B%0A this.info(%22Not authorized
anon
@@ -3545,22 +3545,16 @@
nonymous
-%22) + %22
on path
@@ -3577,32 +3577,36 @@
h);%0A
+
response.forbidd
@@ -3602,20 +3602,24 @@
nse.
-forbidden(%22n
+notAuthorized(%22N
ot a
@@ -3627,24 +3627,38 @@
thorized%22);%0A
+ %7D%0A
%7D el
|
b7a4beee28d3058ea37dc007c14d7eb1a564356b
|
make tooltips visible on tablets via onclick handlers.
|
src/main/webapp/WEB-INF/themes/desktop/resource/js/pages/search_results.js
|
src/main/webapp/WEB-INF/themes/desktop/resource/js/pages/search_results.js
|
(function ($) {
function handleUndefinedOrZeroMetric(metric) {
return metric == undefined || metric == 0 ? 'None' : metric;
}
function appendOrRemoveLink(link, metric) {
metric = handleUndefinedOrZeroMetric(metric);
if (metric == 'None') {
link.html(link.html() + ' ' + metric);
link.contents().unwrap();
} else {
link.append(metric);
}
}
$(document).ready(function() {
$('.search-results-alm').each(function () {
var $alm = $(this);
var doi = $alm.data('doi');
$alm.getArticleSummary(doi, function (almData) { //success function
var almLinks = $alm.find('a');
var viewsLink = $(almLinks[0]);
appendOrRemoveLink(viewsLink, almData.viewed);
var citationsLink = $(almLinks[1]);
appendOrRemoveLink(citationsLink, almData.cited);
var savesLink = $(almLinks[2]);
appendOrRemoveLink(savesLink, almData.saved);
var sharesLink = $(almLinks[3]);
appendOrRemoveLink(sharesLink, almData.shared);
$alm.siblings('.search-results-alm-loading').fadeOut('slow', function () {
$alm.fadeIn();
})
}, function () { //error function
$alm.siblings('.search-results-alm-loading').fadeOut('slow', function () {
$alm.siblings('.search-results-alm-error').fadeIn();
})
});
});
$('#sortOrder').on('change', function() {
$(this).parents('form').submit();
});
$('#resultsPerPageDropdown').on('change', function() {
// Due to the way the CSS for the page currently works, it's difficult to have the <form>
// extend all the way down to this dropdown, so we instead set a hidden field here.
$('#resultsPerPage').val($('#resultsPerPageDropdown').val());
$('#searchControlBarForm').submit();
});
});
})(jQuery);
|
JavaScript
| 0 |
@@ -1822,16 +1822,830 @@
%0A %7D);
+%0A%0A // Code to make tooltips around disabled controls work on tablets.%0A%0A var $visibleTooltip;%0A%0A function hideTooltip($tooltip) %7B%0A $tooltip.css('opacity', '0');%0A $tooltip.css('visibility', 'hidden');%0A $tooltip.css('z-index', '-1');%0A %7D%0A%0A function showTooltip($tooltip) %7B%0A $tooltip.css('opacity', '1.0');%0A $tooltip.css('visibility', 'visible');%0A $tooltip.css('z-index', '1');%0A %7D%0A%0A $('%5Bdata-js-tooltip-hover=trigger%5D').on('click', function() %7B%0A%0A // Since the two icons are close together, we have to hide the adjacent%0A // tooltip first if it is visible.%0A if ($visibleTooltip !== undefined) %7B%0A hideTooltip($visibleTooltip);%0A %7D%0A $visibleTooltip = $(this).find('%5Bdata-js-tooltip-hover=target%5D');%0A showTooltip($visibleTooltip);%0A %7D);
%0A %7D);%0A%7D
|
4007e69b05105ce0e3833f4df0122a7de535e2fe
|
Define defaultConf in function diveSync()
|
diveSync.js
|
diveSync.js
|
var fs = require('fs'),
append = require('append');
// default options
var defaultOpt = {
recursive: true,
all: false,
directories: false,
filter: function filter() {
return true;
}
};
// general function
var diveSync = function(dir, opt, action) {
// action is the last argument
action = arguments[arguments.length - 1];
// ensure opt is an object
if (typeof opt != 'object')
opt = {};
opt = append(defaultOpt, opt);
// apply filter
if (!opt.filter(dir, true)) return;
try {
// read the directory
var list = fs.readdirSync(dir);
// for every file in the list
list.forEach(function (file) {
if (opt.all || file[0] != '.') {
// full path of that file
var path = dir + '/' + file;
// get the file's stats
var stat = fs.statSync(path);
// if the file is a directory
if (stat && stat.isDirectory()) {
// call the action if enabled for directories
if (opt.directories)
action(null, path);
// dive into the directory
if (opt.recursive)
diveSync(path, opt, action);
} else {
// apply filter
if (!opt.filter(path, false)) return;
// call the action
action(null, path);
}
}
});
} catch(err) {
action(err);
}
};
module.exports = diveSync;
|
JavaScript
| 0 |
@@ -50,16 +50,82 @@
end');%0A%0A
+// general function%0Avar diveSync = function(dir, opt, action) %7B%0A
// defau
@@ -135,16 +135,18 @@
options%0A
+
var defa
@@ -158,16 +158,18 @@
t = %7B%0A
+
+
recursiv
@@ -177,16 +177,18 @@
: true,%0A
+
all: f
@@ -195,16 +195,18 @@
alse,%0A
+
+
director
@@ -217,16 +217,18 @@
false,%0A
+
filter
@@ -245,24 +245,26 @@
filter() %7B%0A
+
return t
@@ -274,77 +274,16 @@
;%0A
-%7D%0A%7D;%0A%0A// general function%0Avar diveSync = function(dir, opt, action) %7B
+ %7D%0A %7D;
%0A%0A
|
a3e3eb490c3bdfb44a69ec402b85ce601c8d0a7a
|
Add H1 to the Shared Content page
|
ui/features/content_shares/react/ReceivedContentView.js
|
ui/features/content_shares/react/ReceivedContentView.js
|
/*
* Copyright (C) 2019 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas 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, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React, {useState, lazy, useCallback} from 'react'
import {useScope as useI18nScope} from '@canvas/i18n'
import CanvasLazyTray from '@canvas/trays/react/LazyTray'
import ContentHeading from './ContentHeading'
import ReceivedTable from './ReceivedTable'
import PreviewModal from './PreviewModal'
import {Text} from '@instructure/ui-text'
import {Spinner} from '@instructure/ui-spinner'
import useFetchApi from '@canvas/use-fetch-api-hook'
import doFetchApi from '@canvas/do-fetch-api-effect'
import Paginator from '@canvas/instui-bindings/react/Paginator'
import {showFlashAlert} from '@canvas/alerts/react/FlashAlert'
const I18n = useI18nScope('content_share')
const CourseImportPanel = lazy(() => import('./CourseImportPanel'))
const NoContent = () => <Text size="large">{I18n.t('No content has been shared with you.')}</Text>
export default function ReceivedContentView() {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
const [shares, setShares] = useState([])
const [responseMeta, setResponseMeta] = useState({})
const [currentPage, setCurrentPage] = useState(1)
const [currentContentShare, setCurrentContentShare] = useState(null)
const [whichModalOpen, setWhichModalOpen] = useState(null)
const sharesUrl = '/api/v1/users/self/content_shares'
const handleSetShares = useCallback(
data => {
setShares(data)
const message = I18n.t(
{
one: '1 shared item loaded.',
other: '%{count} shared items loaded.'
},
{count: data.length}
)
showFlashAlert({message, srOnly: true, type: 'info'})
},
[setShares]
)
useFetchApi({
success: handleSetShares,
meta: setResponseMeta,
error: setError,
loading: setIsLoading,
path: `${sharesUrl}/received`,
params: {page: currentPage}
})
function removeShareFromList(doomedShare) {
setShares(shares.filter(share => share.id !== doomedShare.id))
}
// Handle an update to a read state from the displayed table
function onUpdate(share_id, updateParms) {
doFetchApi({
method: 'PUT',
path: `${sharesUrl}/${share_id}`,
body: updateParms
})
.then(r => {
const {id, read_state} = r.json
setShares(shares.map(share => (share.id === id ? {...share, read_state} : share)))
})
.catch(setError)
}
function markRead(share) {
onUpdate(share.id, {read_state: 'read'})
}
function onPreview(share) {
setCurrentContentShare(share)
setWhichModalOpen('preview')
markRead(share)
}
function onImport(share) {
setCurrentContentShare(share)
setWhichModalOpen('import')
}
function onRemove(share) {
// eslint-disable-next-line no-alert
const shouldRemove = window.confirm(I18n.t('Are you sure you want to remove this item?'))
if (shouldRemove) {
doFetchApi({path: `${sharesUrl}/${share.id}`, method: 'DELETE'})
.then(() => removeShareFromList(share))
.catch(err =>
showFlashAlert({message: I18n.t('There was an error removing the item'), err})
)
}
}
function closeModal() {
setWhichModalOpen(null)
}
function renderBody() {
const someContent = Array.isArray(shares) && shares.length > 0
if (isLoading) return <Spinner renderTitle={I18n.t('Loading')} />
if (someContent)
return (
<ReceivedTable
shares={shares}
onPreview={onPreview}
onImport={onImport}
onRemove={onRemove}
onUpdate={onUpdate}
/>
)
return <NoContent />
}
function renderPagination() {
if (responseMeta.link) {
const last = parseInt(responseMeta.link.last.page, 10)
if (!Number.isNaN(last)) {
return (
<Paginator
loadPage={setCurrentPage}
page={currentPage}
pageCount={last}
margin="small 0 0 0"
/>
)
}
}
}
if (error) throw new Error('Retrieval of Received Shares failed')
return (
<>
<ContentHeading
svgUrl="/images/gift.svg"
heading={I18n.t('Received Content')}
description={I18n.t(
'The list below is content that has been shared with you. You can preview the ' +
'content, import it into your course, or remove it from the list.'
)}
/>
{renderBody()}
{renderPagination()}
<PreviewModal
open={whichModalOpen === 'preview'}
share={currentContentShare}
onDismiss={closeModal}
/>
<CanvasLazyTray
label={I18n.t('Import...')}
open={whichModalOpen === 'import'}
placement="end"
padding="medium"
onDismiss={closeModal}
>
<CourseImportPanel
contentShare={currentContentShare}
onClose={closeModal}
onImport={markRead}
/>
</CanvasLazyTray>
</>
)
}
|
JavaScript
| 0.000441 |
@@ -994,16 +994,129 @@
wModal'%0A
+import %7BScreenReaderContent%7D from '@instructure/ui-a11y-content'%0Aimport %7BHeading%7D from '@instructure/ui-heading'%0A
import %7B
@@ -4854,16 +4854,138 @@
%0A %3C%3E%0A
+ %3CScreenReaderContent%3E%0A %3CHeading level=%22h1%22%3E%7BI18n.t('Shared Content')%7D%3C/Heading%3E%0A %3C/ScreenReaderContent%3E%0A
%3CC
|
7b69c2becded1b168ae2c54203b83d23762bc2b6
|
Update lime-state.js
|
lib/lime-state.js
|
lib/lime-state.js
|
var lime_log = require('./utils/log')
module.exports = {
project_path: null,
target: null,
system: null,
is_consumer:false,
flags: {
debug: false,
verbose: false,
build_only: false,
launch_only: false
},
init:function(state) {
this.system = this.get_system();
this.set(state);
lime_log.debug('state:' + JSON.stringify(this));
},
set_project:function(path) {
this.project_path = path;
if(this.project_path) this.valid = true;
lime_log.debug('set: lime file / ' + this.project_path);
},
set:function(state) {
this.set_project(state.project_path);
this.target = state.target || this.system;
this.is_consumer = state.is_consumer;
if(state.flags) {
this.flags.debug = state.flags.debug;
this.flags.verbose = state.flags.verbose;
this.flags.build_only = state.flags.build_only;
this.flags.launch_only = state.flags.launch_only;
this.flags.use_simulator = state.flags.use_simulator;
}
}, //set
unset:function() {
this.valid = false;
this.project_path = null;
this.target = this.system;
this.is_consumer = false;
//not sure these should be unset
// this.flags.debug = false;
// this.flags.verbose = false;
// this.flags.build_only = false;
// this.flags.launch_only = false;
},
as_args: function(plus_args) {
var args = [];
args.push(this.project_path);
args.push(this.target);
if(this.flags.debug) {
args.push('-debug');
}
if(this.flags.verbose) {
args.push('-verbose');
}
if(this.flags.use_simulator && ['ios', 'blackberry', 'tizen', 'webos'].indexOf(this.target) != -1) {
args.push('-simulator');
}
if(this.flags.use_simulator && this.target == 'android') {
args.push('-emulator');
}
if(plus_args) {
args = args.concat(plus_args);
}
return args;
},
get_system:function() {
var s = process.platform;
switch(s) {
case 'darwin': return 'mac'; break;
case 'linux': return 'linux'; break;
case 'win32': return 'windows'; break;
}
return 'unknown';
},
} //module.exports
|
JavaScript
| 0.000002 |
@@ -720,27 +720,59 @@
rget %7C%7C
-this.system
+atom.config.get('lime.lime_default_target')
;%0A
|
d613975febe44415f4187a94d716359fc1653a22
|
Add descriptions to generation/node/printer
|
src/babel/generation/node/printer.js
|
src/babel/generation/node/printer.js
|
/**
* [Please add a description.]
*/
export default class NodePrinter {
constructor(generator, parent) {
this.generator = generator;
this.parent = parent;
}
/**
* [Please add a description.]
*/
plain(node, opts) {
return this.generator.print(node, this.parent, opts);
}
/**
* [Please add a description.]
*/
sequence(nodes, opts = {}) {
opts.statement = true;
return this.generator.printJoin(this, nodes, opts);
}
/**
* [Please add a description.]
*/
join(nodes, opts) {
return this.generator.printJoin(this, nodes, opts);
}
/**
* [Please add a description.]
*/
list(items, opts = {}) {
if (opts.separator == null) {
opts.separator = ",";
if (!this.generator.format.compact) opts.separator += " ";
}
return this.join(items, opts);
}
/**
* [Please add a description.]
*/
block(node) {
return this.generator.printBlock(this, node);
}
/**
* [Please add a description.]
*/
indentOnComments(node) {
return this.generator.printAndIndentOnComments(this, node);
}
}
|
JavaScript
| 0 |
@@ -4,35 +4,62 @@
%0A *
-%5BPlease add a description.%5D
+Printer for nodes, needs a %60generator%60 and a %60parent%60.
%0A */
@@ -208,35 +208,27 @@
*
-%5BPlease add a description.%5D
+Print a plain node.
%0A
@@ -331,35 +331,48 @@
*
-%5BPlease add a description.%5D
+Print a sequence of nodes as statements.
%0A
@@ -509,35 +509,49 @@
*
-%5BPlease add a descript
+Print a sequence of nodes as express
ion
+s
.
-%5D
%0A
@@ -652,35 +652,79 @@
*
-%5BPlease add a description.%5D
+Print a list of nodes, with a customizable separator (defaults to %22,%22).
%0A
@@ -943,35 +943,32 @@
*
-%5BPlease add a description.%5D
+Print a block-like node.
%0A
@@ -1057,35 +1057,39 @@
*
-%5BPlease add a description.%5D
+Print node and indent comments.
%0A
|
989c3239e43cecd7a3054295961c5ada2a69b676
|
Update jQuery fileupload callback to fire when all current uploads have finished
|
app/assets/javascripts/sufia/save_work/uploaded_files.es6
|
app/assets/javascripts/sufia/save_work/uploaded_files.es6
|
export class UploadedFiles {
// Monitors the form and runs the callback if any files are added
constructor(form, callback) {
this.form = form
$('#fileupload').bind('fileuploadcompleted', callback)
}
get hasFileRequirement() {
let fileRequirement = this.form.find('li#required-files')
return fileRequirement.size() > 0
}
get hasFiles() {
let fileField = this.form.find('input[name="uploaded_files[]"]')
return fileField.size() > 0
}
get hasNewFiles() {
// In a future release hasFiles will include files already on the work plus new files,
// but hasNewFiles() will include only the files added in this browser window.
return this.hasFiles
}
}
|
JavaScript
| 0 |
@@ -184,17 +184,12 @@
load
-completed
+stop
', c
|
4999194d2f76ffb058ab0b9539bdbe6e0a6486f3
|
fix bookmark post
|
server/src/controllers/BookmarkController.js
|
server/src/controllers/BookmarkController.js
|
const {Bookmark} = require('../models')
module.exports = {
async index (req, res) {
try {
const {songId, userId} = req.query
const bookmark = await Bookmark.findOne({
where: {
SongId: songId,
UserId: userId
}
})
res.send(bookmark)
} catch (err) {
res.status(500).send({
error: 'Server error trying to get bookmark!'
})
}
},
async post (req, res) {
try {
const {songId, userId} = req.body.params
const bookmark = await Bookmark.findOne({
where: {
SongId: songId,
UserId: userId
}
})
console.log('------------------------------------')
console.log(`songId:${songId}, userId:${userId}`)
console.log('------------------------------------')
if (bookmark) {
return res.status(400).send({
error: 'You already have this set as a bookmark!'
})
}
const newBookmark = await Bookmark.create(req.body)
console.log('------------------------------------')
console.log(newBookmark)
console.log('------------------------------------')
res.send(newBookmark)
} catch (err) {
res.status(500).send({
error: 'Server error trying to create bookmark!'
})
}
},
async delete (req, res) {
try {
const {bookmarkId} = req.params
const bookmark = await Bookmark.findById(bookmarkId)
await bookmark.destroy()
res.send(bookmark)
} catch (err) {
res.status(500).send({
error: 'Server error trying to delete bookmark!'
})
}
}
}
|
JavaScript
| 0.000001 |
@@ -491,24 +491,17 @@
req.body
-.params
%0A
+
co
@@ -741,16 +741,44 @@
erId%7D%60)%0A
+ console.log(req.body)%0A
co
@@ -1015,24 +1015,72 @@
.create(
-req.body
+%7B%0A SongId: songId,%0A UserId: userId%0A %7D
)%0A
|
67620c5779de3d0c3776dff4dfca0500bfc109ff
|
Allow passing a stateless component as TabBarComponent (#35)
|
src/KeyboardAwareTabBarComponent.js
|
src/KeyboardAwareTabBarComponent.js
|
import React from 'react'
import PropTypes from 'prop-types';
import { Keyboard, Platform } from 'react-native'
export default class KeyboardAwareTabBarComponent extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
isVisible: true
}
}
componentWillMount() {
const keyboardShowEvent = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow';
const keyboardHideEvent = Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide';
this.keyboardWillShowSub = Keyboard.addListener(keyboardShowEvent, this.keyboardWillShow);
this.keyboardWillHideSub = Keyboard.addListener(keyboardHideEvent, this.keyboardWillHide);
}
componentWillUnmount() {
this.keyboardWillShowSub.remove();
this.keyboardWillHideSub.remove();
}
keyboardWillShow = (event) => {
this.setState({
isVisible: false
})
}
keyboardWillHide = (event) => {
this.setState({
isVisible: true
})
}
render() {
const { TabBarComponent, ...componentProps } = this.props;
const { isVisible } = this.state;
return isVisible
? <TabBarComponent {...componentProps} />
: null
}
}
KeyboardAwareTabBarComponent.propTypes = {
TabBarComponent: PropTypes.node.isRequired,
};
|
JavaScript
| 0 |
@@ -1257,12 +1257,53 @@
pes.
-node
+oneOfType(%5B PropTypes.node, PropTypes.func %5D)
.isR
|
5b840325b355955b273d82114a04e1a099eb4ff8
|
load from either flat or nested dir structure
|
lib/localTasks.js
|
lib/localTasks.js
|
var path = require('path');
exports.load = function(grunt, plugin) {
grunt.loadTasks(path.join(__dirname, '..', 'node_modules', plugin, 'tasks'));
};
|
JavaScript
| 0.001851 |
@@ -69,24 +69,114 @@
%7B%0A
-grunt.loadTasks(
+var nestedTaskPath = path.join(__dirname, '..', 'node_modules', plugin, 'tasks');%0A var dedupedTaskPath =
path
@@ -189,32 +189,44 @@
__dirname, '..',
+ '..', '..',
'node_modules',
@@ -242,14 +242,285 @@
'tasks')
+;%0A var taskPath;%0A%0A try %7B%0A // try npm2 style nested depedencies first.%0A require.resolve(nestedTaskPath);%0A taskPath = nestedTaskPath;%0A %7D catch(e) %7B%0A // fallback to npm3 style nested depedencies.%0A taskPath = dedupedTaskPath;%0A %7D%0A%0A grunt.loadTasks(taskPath
);%0A%7D;%0A
|
51621dcc607c9fc374c65650db173ebcbc4b5727
|
Tidy up
|
client/app/app.js
|
client/app/app.js
|
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import angularComponent from 'angular-component';
import Common from './common/common';
import Components from './components/components';
import AppComponent from './app.component';
import uiRouterTitle from 'angular-ui-router-title';
// import Filters from './filters/unsafe/unsafe';
// import Filters from './filters/filters';
// import 'normalize.css';
angular.module('app', [
uiRouter,
'ui.router.title',
// 'jquery/src/core',
// Filters,
Common.name,
Components.name
])
.config(($locationProvider) => {
$locationProvider.html5Mode(true);
})
.config(($urlRouterProvider) => {
$urlRouterProvider.otherwise('^/');
})
.component('app', AppComponent);
|
JavaScript
| 0.000027 |
@@ -573,32 +573,52 @@
locationProvider
+, $urlRouterProvider
) =%3E %7B%0A $locati
@@ -649,46 +649,8 @@
e);%0A
-%7D)%0A%0A.config(($urlRouterProvider) =%3E %7B%0A
$u
|
b9f1694e0b655a7f8ecfe644ff5e39ed1d3f6bd6
|
fix app
|
client/app/app.js
|
client/app/app.js
|
import angular from 'angular';
import 'bootstrap/dist/css/bootstrap.min.css';
import uiBootstrap from 'angular-ui-bootstrap';
import uiRouter from 'angular-ui-router';
import Common from './common/common';
import Components from './components/components';
import AppComponent from './app.component';
import 'normalize.css';
angular.module('app', [
uiRouter,
Common.name,
Components.name
])
.config(($locationProvider) => {
"ngInject";
// @see: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions
// #how-to-configure-your-server-to-work-with-html5mode
$locationProvider.html5Mode(true).hashPrefix('!');
})
.component('app', AppComponent);
|
JavaScript
| 0.000004 |
@@ -296,32 +296,8 @@
nt';
-%0Aimport 'normalize.css';
%0A%0Aan
@@ -320,16 +320,32 @@
p', %5B%0A
+'ui.bootstrap',%0A
uiRout
@@ -348,18 +348,16 @@
Router,%0A
-
Common
@@ -365,18 +365,16 @@
name,%0A
-
-
Componen
@@ -385,13 +385,16 @@
ame%0A
-
%5D)%0A
+
.c
@@ -428,16 +428,21 @@
%3E %7B%0A
+
+
%22ngInjec
@@ -445,16 +445,21 @@
nject%22;%0A
+
// @
@@ -535,16 +535,21 @@
estions%0A
+
// #
@@ -600,16 +600,21 @@
ml5mode%0A
+
$loc
@@ -666,11 +666,21 @@
;%0A
-%7D)%0A
+ %7D)%0A
.c
|
76431700612d93574d043c6320d836d51ad7321a
|
fix test
|
test/unit/server/applicationModel.spec.js
|
test/unit/server/applicationModel.spec.js
|
/********************************************************** {COPYRIGHT-TOP} ****
* Licensed Materials - Property of IBM
*
* (C) Copyright IBM Corp. 2014 All Rights Reserved
*
* US Government Users Restricted Rights - Use, duplication, or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
********************************************************* {COPYRIGHT-END} ****/
/*jshint expr: true*/
var path = require('path');
var appHome = path.join(process.cwd(), 'app');
global.appHome = appHome;
var rewire = require('rewire');
var chai = require('chai');
var expect = chai.expect;
chai.config.includeStack = false;
var rewire_revert = false;
describe('Application Model', function() {
var applicationModel = rewire('../../../api/models/application');
before(function() {
// mock DB results using rewire
applicationModel.__set__('APPS', [{
id: 8888,
name: 'Cool Beans',
lastUpdated: '2015-10-09T04:04:00',
status: 'online'
}, {
id: 9999,
name: 'My Test App',
lastUpdated: '2015-11-09T14:14:00',
status: 'online'
}]);
});
describe("application model", function() {
describe("#getAllApplications()", function() {
it("respond with all applications", function() {
var apps = applicationModel.getAllApplications();
expect(apps.length).to.equal(2);
});
});
describe("#getApplicationById", function() {
it("respond with matching application", function() {
var apps = applicationModel.getApplicationById(8888);
expect(apps.id).to.equal(8898);
});
});
});
});
|
JavaScript
| 0.000002 |
@@ -1587,17 +1587,17 @@
equal(88
-9
+8
8);%0A
|
229c2a966b5cbd40d403d8ea3a8275bd49e6fc50
|
Update ko.js
|
lib/locales/ko.js
|
lib/locales/ko.js
|
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'ko',
dictionary: {
'Autoscale': '자동 크기지정',
'Box Select': '박스 선택',
'Click to enter Colorscale title': '클릭하여 Colorscale 제목을 지정합니다',
'Click to enter Component A title': '클릭하여 A데이터의 제목을 지정합니다 ',
'Click to enter Component B title': '클릭하여 B데이터의 제목을 지정합니다',
'Click to enter Component C title': '클릭하여 C데이터의 제목을 지정합니다',
'Click to enter Plot title': '클릭하여 차트 제목을 지정합니다',
'Click to enter X axis title': '클릭하여 X축 제목을 지정합니다',
'Click to enter Y axis title': '클릭하여 Y축 제목을 지정합니다',
'Click to enter radial axis title': '클릭하여 원형 축 제목을 지정합니다',
'Compare data on hover': 'hover 위의 데이터와 비교합니다',
'Double-click on legend to isolate one trace': '범례를 더블 클릭하여 하나의 트레이스를 분리합니다',
'Double-click to zoom back out': '더블 클릭하여 줌을 해제합니다',
'Download plot as a png': '.png 이미지 파일로 차트를 다운로드 합니다',
'Download plot': '차트를 다운로드 합니다',
'Edit in Chart Studio': 'Chart Studio를 수정합니다',
'IE only supports svg. Changing format to svg.': 'IE는 svg만을 지원합니다. 포맷을 svg로 변경하세요',
'Lasso Select': '올가미 선택',
'Orbital rotation': '궤도 수정',
'Pan': '이동',
'Produced with Plotly': 'Plotly 제공',
'Reset': 초기화',
'Reset axes': '축 초기화',
'Reset camera to default': 'camera를 기본값으로 초기화',
'Reset camera to last save': 'camera를 마지막으로 저장한 값으로 초기화',
'Reset view': 'view 초기화',
'Reset views': 'views 초기화',
'Show closest data on hover': 'hover에 근접한 데이터 보이기',
'Snapshot succeeded': 'Snapshot 성공',
'Sorry, there was a problem downloading your snapshot!': '죄송합니다, snapshot을 다운로드 중 문제가 발생했습니다!',
'Taking snapshot - this may take a few seconds': 'snapshot을 찍습니다 - 이것은 몇 초가 소요될 수 있습니다',
'Toggle Spike Lines': '스위치로 Lines을 고정합니다',
'Toggle show closest data on hover': '스위치로 hover와 가장 가까운 데이터를 보여줍니다',
'Turntable rotation': 'Turntable 회전',
'Zoom': '확대(줌)',
'Zoom in': '확대(줌 인)',
'Zoom out': '축소(줌 아웃)',
'close': '닫기',
'high': '높음',
'low': '낮음',
'max': '최댓값',
'mean ± σ': '평균 ± σ',
'mean': '평균',
'median': '중간 값',
'min': '최솟값',
'new text': '새로운 텍스트',
'open': '열기',
'q1': 'q1',
'q3': 'q3',
'source': '소스',
'target': '타겟',
},
format: {
days: ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'],
shortDays: ['일', '월', '화', '수', '목', '금', '토'],
months: [
'1월', '2월', '3월', '4월', '5월', '6월',
'7월', '8월', '9월', '10월', '11월', '12월'
],
shortMonths: [
'1월', '2월', '3월', '4월', '5월', '6월',
'7월', '8월', '9월', '10월', '11월', '12월'
],
date: '%Y-%m-%d'
}
};
|
JavaScript
| 0.000001 |
@@ -1475,16 +1475,17 @@
Reset':
+'
%EC%B4%88%EA%B8%B0%ED%99%94',%0A
|
3fb91f7a59eda078378bc944bd4a998336a30825
|
Handle close popup clicks
|
assets/javascript/widget.js
|
assets/javascript/widget.js
|
(function() {
'use strict';
function listenToClick(element, name, fn) {
if (document.addEventListener) {
element.addEventListener(name, fn, false);
} else {
element.attachEvent((name === 'click') ? 'onclick' : name, fn);
}
}
function handleClicks(elem, fn) {
if (document.addEventListener) {
// For all major browsers, except IE 8 and earlier
elem.addEventListener("click", fn, false);
elem.addEventListener("touchstart", fn, false);
} else if (document.attachEvent) {
// For IE 8 and earlier versions
elem.attachEvent("onclick", fn, false);
elem.attachEvent("touchstart", fn, false);
}
};
function hasClass(el, className) {
if (el.classList)
return el.classList.contains(className)
else
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}
function my_addClass(el, className) {
if (el.classList)
el.classList.add(className)
else if (!hasClass(el, className)) el.className += " " + className
}
function my_removeClass(el, className) {
if (el.classList)
el.classList.remove(className)
else if (hasClass(el, className)) {
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
el.className=el.className.replace(reg, ' ')
}
}
function scrollTop(element, to, duration) {
var start = element.scrollTop,
change = to - start,
currentTime = 0,
increment = 20;
var animateScroll = function(){
currentTime += increment;
var val = Math.easeInOutQuad(currentTime, start, change, duration);
element.scrollTop = val;
if(currentTime < duration) {
setTimeout(animateScroll, increment);
}
};
animateScroll();
}
//t = current time
//b = start value
//c = change in value
//d = duration
Math.easeInOutQuad = function (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
}
function each(o, cb, s){
var n;
if (!o){
return 0;
}
s = !s ? o : s;
if (o instanceof Array){
// Indexed arrays, needed for Safari
for (n=0; n<o.length; n++) {
if (cb.call(s, o[n], n, o) === false){
return 0;
}
}
} else {
// Hashtables
for (n in o){
if (o.hasOwnProperty(n)) {
if (cb.call(s, o[n], n, o) === false){
return 0;
}
}
}
}
return 1;
}
domready(function() {
var
scrollElements,
inValidRange,
setVisibility,
setVisibilityAll,
resetScroll;
scrollElements = document.querySelectorAll('[data-scroll-element]');
inValidRange = function(offset, limit) {
return offset >= 0 && offset < limit;
};
setVisibility = function(element, nextOffset, limit) {
if(inValidRange(nextOffset, limit)) {
my_removeClass(element, 'disabled');
} else {
my_addClass(element, 'disabled');
}
};
setVisibilityAll = function(elements, newOffset) {
var
scrollElement,
increment,
nextOffset,
limit;
each(elements, function(el) {
scrollElement = document.querySelector(el.dataset.scrollElement);
increment = parseInt(el.dataset.scrollIncrement);
nextOffset = newOffset + increment;
limit = parseInt(scrollElement.dataset.scrollLimit);
setVisibility(el, nextOffset, limit);
});
};
resetScroll = function(element) {
element.scrollTop = 0;
element.dataset.scrollOffset = 0;
};
each(document.querySelectorAll('[data-clipboard-target]'), function(el) {
var
clipboard,
notification;
clipboard = new Clipboard(el);
var notify = function(clipboardNotification, notificationText) {
notification = document.getElementById(clipboardNotification.slice(1));
notification.textContent = notificationText;
my_addClass(notification, 'in');
setTimeout(function() {
my_removeClass(notification, 'in');
}, 1400);
};
var notifySuccess = function(e) {
notify(e.trigger.dataset.clipboardNotification, "Copied!");
};
var notifyFailure = function(e) {
//if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
};
clipboard.on('success', notifySuccess);
clipboard.on('error', notifyFailure);
handleClicks(el, function(e) {
if (window.parent.squatch.eventBus) {
window.parent.squatch.eventBus.dispatch('copy_btn_clicked', e.type);
}
});
});
each(scrollElements, function(el) {
var
element,
increment,
limit,
offset,
nextOffset,
newOffset;
element = document.querySelector(el.dataset.scrollElement);
increment = parseInt(el.dataset.scrollIncrement);
limit = parseInt(element.dataset.scrollLimit.valueOf());
offset = parseInt(element.dataset.scrollOffset.valueOf());
element.dataset.scrollLimit = limit;
nextOffset = offset + increment;
setVisibility(el, nextOffset, limit);
// Force IE to forget previous scroll top value
resetScroll(element);
listenToClick(el, 'click', function() {
offset = parseInt(element.dataset.scrollOffset);
newOffset = offset + increment;
if (inValidRange(newOffset, limit)) {
scrollTop(element, document.getElementById(newOffset).offsetTop, 400);
element.dataset.scrollOffset = newOffset;
setVisibilityAll(scrollElements, newOffset);
}
});
});
each(document.querySelectorAll('[data-moment]'), function(el) {
var time = moment(parseInt(el.textContent));
el.textContent = time.fromNow();
});
});
})();
|
JavaScript
| 0.000001 |
@@ -5980,16 +5980,283 @@
%0A %7D);
+%0A%0A each(document.getElementsByClassName('squatch-header-close'), function(el) %7B%0A handleClicks(el, function(e) %7B%0A if (window.parent.squatch.eventBus) %7B%0A window.parent.squatch.eventBus.dispatch('close_popup', e.type);%0A %7D%0A %7D);%0A %7D);
%0A %7D);%0A%0A
|
da87de26bcdae388e4492a9e3ef119f3babf368b
|
Fix error when loading the LikertScale
|
client/src/components/graphs/LikertScale.js
|
client/src/components/graphs/LikertScale.js
|
import React, { useEffect, useRef } from "react"
import * as d3 from "d3"
import PropTypes from "prop-types"
import Text from "react-svg-text"
import useDimensions from "react-use-dimensions"
const LikertScale = ({ onChange, value, levels, width, height, readonly }) => {
const cursorRef = useRef(null)
const axisRef = useRef(null)
const [containerRef, containerBox] = useDimensions()
const containerHeight = containerBox.height || 0
const containerWidth = containerBox.width || 0
const containerX = containerBox.x || 0
const MARGIN = 20
const scaleYPosition = containerHeight - 30
const scale = d3
.scaleLinear()
.domain([0, 10])
.range([MARGIN, containerWidth - 2 * MARGIN])
const x = scale(Number(value !== undefined ? value : 50))
useEffect(() => {
if (readonly) {
return
}
const handleDrag = d3.drag().on("drag", function() {
const me = d3.select(cursorRef.current)
const newX = Math.min(
Math.max(d3.event.x, scale.range()[0]),
scale.range()[1]
)
me.attr("transform", `translate(${newX} ${scaleYPosition})`)
onChange(scale.invert(newX))
})
handleDrag(d3.select(cursorRef.current))
}, [onChange, scale, scaleYPosition, readonly])
useEffect(() => {
d3.select(cursorRef.current).attr(
"transform",
`translate(${x} ${scaleYPosition})`
)
}, [x, scaleYPosition])
useEffect(() => {
const axis = d3.axisBottom(scale)
d3.select(axisRef.current).call(axis)
}, [scale])
let activeColor = null
return (
<svg
height={height}
width={width}
xmlns="http://www.w3.org/2000/svg"
ref={containerRef}
onClick={e =>
!readonly && e.clientX && onChange(scale.invert(e.clientX - containerX))}
>
{levels.map((level, index) => {
const startX = scale(index === 0 ? 0 : levels[index - 1].endValue)
const endX = scale(level.endValue)
const active = x <= endX && (x > startX || index === 0)
const fillColor = d3.color(level.color)
active && (activeColor = d3.hsl(level.color))
fillColor.opacity = active ? 0.4 : 0.15
return (
<React.Fragment key={`level-${index}`}>
<rect
style={{ fill: fillColor, stroke: "gray", strokeWidth: 1 }}
y={0}
x={startX}
height={containerHeight - 11}
width={endX - startX}
/>
<Text
fill={active ? "black" : "gray"}
fontWeight={active ? "bold" : "normal"}
x={startX + 2}
y={2}
style={{ pointerEvents: "none" }}
width={endX - startX - 4}
verticalAnchor="start"
>
{level.label}
</Text>
</React.Fragment>
)
})}
)}
<g ref={axisRef} transform={`translate(0 ${scaleYPosition})`} />
<g ref={cursorRef}>
<polygon
points="0,0 13,13 13,30 -13,30 -13,13"
style={{
stroke: "gray",
fill: "" + activeColor,
strokeWidth: 1,
cursor: readonly ? null : "pointer"
}}
/>
<text
fill={activeColor?.l < 0.5 ? "white" : "black"}
fontWeight="bold"
x={-11}
y={25}
style={{ pointerEvents: "none" }}
>
{Number(value).toFixed(value < scale.domain()[1] ? 1 : 0)}
</text>
</g>
</svg>
)
}
LikertScale.propTypes = {
value: PropTypes.number,
onChange: PropTypes.func,
levels: PropTypes.arrayOf(
PropTypes.shape({
color: PropTypes.string,
endValue: PropTypes.number.isRequired,
tooltip: PropTypes.string,
label: PropTypes.string
})
).isRequired,
width: PropTypes.string.isRequired,
height: PropTypes.string.isRequired,
readonly: PropTypes.bool
}
LikertScale.defaultProps = {
value: 0,
levels: [
{
color: "red",
endValue: 3
},
{
color: "#FFBF00",
endValue: 7
},
{
color: "green",
endValue: 10
}
],
height: "65",
width: "100%"
}
export default LikertScale
|
JavaScript
| 0.005802 |
@@ -2366,16 +2366,28 @@
height=%7B
+Math.max(0,
containe
@@ -2398,16 +2398,17 @@
ght - 11
+)
%7D%0A
@@ -2414,32 +2414,44 @@
width=%7B
+Math.max(0,
endX - startX%7D%0A
@@ -2443,24 +2443,25 @@
ndX - startX
+)
%7D%0A
|
70318714303873463ff771fd867a10b24a1ec17f
|
Remove unncessary check
|
client/src/pages/organizations/Approvals.js
|
client/src/pages/organizations/Approvals.js
|
import React, {Component} from 'react'
import {Table} from 'react-bootstrap'
import Fieldset from 'components/Fieldset'
import LinkTo from 'components/LinkTo'
export default class OrganizationApprovals extends Component {
render() {
let org = this.props.organization
let approvalSteps = org.approvalSteps
return <Fieldset id="approvals" title="Approval process">
{approvalSteps.map((step, idx) =>
<Fieldset title={`Step ${idx + 1}: ${step.name}`} key={'step_' + idx}>
<Table>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
{step.approvers.map((position, approverIdx) =>
<tr key={position.uuid} id={`step_${idx}_approver_${approverIdx}`} >
<td>{position.person
? <td>{position.person && <LinkTo person={position.person} />}</td>
: <td className="text-danger">Unfilled</td>}</td>
<td><LinkTo position={position} /></td>
</tr>
)}
</tbody>
</Table>
</Fieldset>
)}
{approvalSteps.length === 0 && <em>This organization doesn't have any approval steps</em>}
</Fieldset>
}
}
|
JavaScript
| 0 |
@@ -749,24 +749,25 @@
%09%09%09%09%09%09%09%3Ctd%3E%7B
+(
position.per
@@ -773,45 +773,51 @@
rson
-%0A%09%09%09%09%09%09%09%09%09%09? %3Ctd%3E%7Bposition.person &&
+ && position.person.uuid)%0A%09%09%09%09%09%09%09%09%09%09? %3Ctd%3E%7B
%3CLin
|
21f294d4aa2364cca03642e71e4872e945e64904
|
Use route names instead of paths.
|
client/views/hosts/hostCreate/hostCreate.js
|
client/views/hosts/hostCreate/hostCreate.js
|
Template.HostCreate.events({
'submit form' : function (event, template) {
event.preventDefault();
// Define form field variables.
var hostname = event.target.hostname.value,
type = event.target.type.value,
version = event.target.version.value;
// Need more validation here.
if (hostname.length) {
// Create sort field sequence value.
var total = Hosts.find().count();
if (total == 0) {
var seq = total;
} else {
var seq = total++;
}
// Insert data into document.
Hosts.insert({
hostname: hostname,
type: type,
version: version,
hostCreated: new Date,
sort: seq
});
// Reset form.
template.find('form').reset();
Router.go('/');
}
}
});
|
JavaScript
| 0 |
@@ -775,17 +775,20 @@
ter.go('
-/
+home
');%0A
|
b75cd318f5b073d2cd5738173ee0951d272ad518
|
Update dev logging methods
|
js/web-worker.js
|
js/web-worker.js
|
(function ($) {
'use strict';
var WebWorker = null,
BrowserWorker = null,
context = null,
className = null,
defaultContext = window,
defaultClassName = 'WebWorker',
Event = null,
eventPrefix = 'webworker:',
Error = null;
var console = {
log: function (data, suppressNoise) {
var console = window.console;
suppressNoise = suppressNoise || false;
if (suppressNoise) {
console.log(data);
}
else {
console.log({
'>>>>>>>> internal': true,
'log': data
});
}
return;
},
warn: window.console.warn,
error: window.console.error
};
context = context || defaultContext;
className = className || defaultClassName;
WebWorker = context[className] || null;
if (WebWorker !== null) {
return;
}
BrowserWorker = window.Worker;
WebWorker = function () {
this._constructor.apply(this, arguments);
return;
};
WebWorker.prototype.$ = null;
WebWorker.prototype._workerUrl = null;
WebWorker.prototype._worker = null;
WebWorker.prototype._lastError = null;
WebWorker.prototype._constructor = function (opts) {
var $scriptElement = null,
scriptContents = null,
blob = null,
workerUrl = null;
this.$ = $(this);
opts = opts || null;
if (opts === null) {
this.throwError(Error.INVALID_ARGUMENTS);
return;
}
if (typeof opts === 'string') {
opts = $.trim(opts);
try {
$scriptElement = $(opts);
}
catch (err) {
// Cannot be resolved as a selector
}
if ($scriptElement !== null && $scriptElement.length > 0) {
// Matching script element found
// Create a blob URL with its contents
scriptContents = $scriptElement.text();
blob = new Blob([scriptContents], { type: "text/javascript" });
workerUrl = window.URL.createObjectURL(blob);
}
else {
//this.throwError(Error.UNKNOWN);
workerUrl = opts;
}
}
this._workerUrl = workerUrl;
this._createWorker();
this.on(Event.INITIALIZED, function () {
console.log('Initialize event triggered', true);
return;
});
this._triggerEvent(Event.INITIALIZED);
return;
};
WebWorker.prototype.getUrl = function () {
return this._workerUrl;
};
WebWorker.prototype._createWorker = function () {
var worker = this;
worker._worker = new BrowserWorker(worker._workerUrl);
worker.on(Event.WORKER_LOADED, function () {
console.log('worker has loaded');
return;
});
worker.on('message', function () {
var args = arguments;
console.log(args);
if (typeof args[0] === 'object') {
console.log(args[0].thobda, true);
console.log(args[0].thobda.method, true);
}
return;
});
$(worker._worker).on('message', function (event) {
console.log(event, true);
var actionMessage = event.originalEvent.data;
console.log(actionMessage, true);
if ((typeof actionMessage === 'object') && ('action' in actionMessage) && actionMessage.action === 'trigger') {
worker._triggerEvent.apply(worker, actionMessage.data.args);
return;
}
worker.trigger.apply(worker, [event]);
return;
});
worker._assignEventHandlers();
worker._initializeWorker();
return;
};
WebWorker.prototype._assignEventHandlers = function () {
//console.log('pending');
return;
};
WebWorker.prototype._initializeWorker = function () {
this._worker.postMessage({
action: 'init',
data: {
args: [
]
}
});
return;
};
WebWorker.prototype.terminate = function () {
this._worker.terminate();
return;
};
WebWorker.prototype._triggerEvent = function (eventType, data, extendedProps) {
var argsLength = arguments.length,
event = null;
eventType = eventType || null;
data = data || null;
extendedProps = extendedProps || null;
if (argsLength === 1 && (typeof eventType === 'object')) {
event = eventType;
eventType = event.type;
}
if (eventType === null) {
return;
}
if (event === null) {
event = $.Event(eventType, extendedProps);
}
event.data = data;
this.trigger(event);
return;
};
WebWorker.prototype.on = function () {
var $worker = this.$;
$worker.on.apply($worker, arguments);
return this;
};
WebWorker.prototype.once = function () {
var $worker = this.$;
$worker.once.apply($worker, arguments);
return this;
};
WebWorker.prototype.off = function () {
var $worker = this.$;
$worker.off.apply($worker, arguments);
return this;
};
WebWorker.prototype.trigger = function () {
var $worker = this.$;
$worker.trigger.apply($worker, arguments);
return this;
};
WebWorker.prototype.throwError = function (error) {
this._lastError = error;
WebWorker._lastError = error;
throw new Error(error);
return;
};
WebWorker.prototype.getLastError = function () {
return this._lastError;
};
// Static
WebWorker._lastError = null;
Event = {
INITIALIZED: 'init',
WORKER_LOADED: 'worker-loaded'
};
WebWorker.Event = Event;
// Add eventPrefix to all event types
for (var key in Event) {
Event[key] = eventPrefix + Event[key];
}
Error = {
UNKNOWN: "An unknown error occured.",
INVALID_ARGUMENTS: "Invalid arguments were supplied to this method. Please check the documentation on the supported arguments for this method."
};
WebWorker.Error = Error;
WebWorker.throwError = WebWorker.prototype.throwError;
WebWorker.noConflict = function (context, className) {
context = context || defaultContext;
className = className || defaultClassName;
context[className] = WebWorker;
return WebWorker;
};
WebWorker.noConflict(context, className);
return;
})(jQuery);
|
JavaScript
| 0.000001 |
@@ -293,32 +293,93 @@
null;%0A%0A var
+windowConsole = window.console,%0A console = null;%0A%0A
console = %7B%0A
@@ -424,51 +424,8 @@
) %7B%0A
- var console = window.console;%0A%0A
@@ -514,33 +514,39 @@
-c
+windowC
onsole.log(data)
@@ -588,33 +588,39 @@
-c
+windowC
onsole.log(%7B%0A
@@ -789,26 +789,25 @@
warn: window
-.c
+C
onsole.warn,
@@ -824,26 +824,25 @@
rror: window
-.c
+C
onsole.error
|
fe9060a6fa754a66fb2c163ffe645527e6f108a6
|
Optimize once event removal Aphabetize map rule options in JSDoc Update reset method JSDoc description User dot notation in reset event filter
|
js/wee.screen.js
|
js/wee.screen.js
|
(function(W) {
'use strict';
var events = [],
bound,
current,
/**
* Bind individual rule
*
* @private
* @param {object} conf - breakpoint rules
* @param {Array} [conf.args] - callback arguments
* @param {function} conf.callback
* @param {boolean} [conf.each=false] - execute for each matching breakpoint
* @param {boolean} [conf.init=true] - check event on load
* @param {int} [conf.max] - maximum breakpoint value
* @param {int} [conf.min] - minimum breakpoint value
* @param {boolean} [conf.once=false] - only execute the callback once
* @param {object} [conf.scope] - callback scope
* @param {int} [conf.size] - specific breakpoint value
* @param {boolean} [conf.watch=true] - check event on screen resize
* @param {string} [conf.namespace] - namespace the event
*/
_addRule = function(conf) {
if (conf.callback) {
// Only setup watching when enabled
if (conf.watch !== false) {
events.push(conf);
// Only attach event once
if (! bound) {
var run = _run.bind(this, false, 0);
bound = 1;
events = [conf];
// Attach resize event
W._win.addEventListener('resize', run);
}
}
// Evaluate rule immediately if not disabled
if (conf.init !== false) {
_run(true, [conf]);
}
}
},
/**
* Check mapped rules for matching conditions
*
* @private
* @param {boolean} [init=false] - initial page load
* @param {Array} [rules] - breakpoint rules
*/
_run = function(init, rules) {
var size = W.screen.size();
// If breakpoint has been hit or resize logic initialized
if (size && (init || size !== current)) {
var evts = rules || events,
i = 0;
for (; i < evts.length; i++) {
var evt = evts[i];
if (_eq(evt, size, init)) {
var f = init && ! current;
_exec(evt, {
dir: f ? 0 : (size > current ? 1 : -1),
init: f,
prev: current,
size: size
});
}
}
// Cache current value
current = size;
}
},
/**
* Compare event rules against current size
*
* @private
* @param {object} evt
* @param {number} size
* @param {boolean} init
* @returns {boolean}
*/
_eq = function(evt, size, init) {
var sz = evt.size,
mn = evt.min,
mx = evt.max,
ex = evt.each || init;
// Check match against rules
return (! sz && ! mn && ! mx) ||
(sz && sz === size) ||
(mn && size >= mn && (ex || current < mn) && (! mx || size <= mx)) ||
(mx && size <= mx && (ex || current > mx) && (! mn || size >= mn));
},
/**
* Execute matching breakpoint callback
*
* @private
* @param {object} evt
* @param {object} data
*/
_exec = function(evt, data) {
W.$exec(evt.callback, {
args: evt.args ? [data].concat(evt.args) : [data],
scope: evt.scope
});
// Disable future execution if once
if (evt.once) {
events = events.filter(function(el) {
return el !== evt;
});
}
};
W.screen = {
/**
* Get current breakpoint value
*
* @returns {number} size
*/
size: function() {
return parseFloat(
getComputedStyle(W._html, null)
.getPropertyValue('font-family')
.replace(/[^0-9\.]+/g, '')
);
},
/**
* Map conditional events to breakpoint values
*
* @param {(Array|object)} rules - breakpoint rules
* @param {Array} [rules.args] - callback arguments
* @param {function} rules.callback
* @param {boolean} [rules.each=false] - execute for each matching breakpoint
* @param {boolean} [rules.init=true] - check event on load
* @param {int} [rules.max] - maximum breakpoint value
* @param {int} [rules.min] - minimum breakpoint value
* @param {boolean} [rules.once=false] - only execute the callback once
* @param {object} [rules.scope] - callback scope
* @param {int} [rules.size] - specific breakpoint value
* @param {boolean} [rules.watch=true] - check event on screen resize
* @param {string} [rules.namespace] - namespace the event
*/
map: function(rules) {
var sets = W.$toArray(rules),
i = 0;
// Delay check to prevent incorrect IE value
for (; i < sets.length; i++) {
_addRule(sets[i]);
}
},
/**
* Evaluate the current breakpoint
*/
run: function() {
_run(true);
},
/**
* Reset all bound events
*
* @param {string} [namespace] - remove screen events in this namespace
*/
reset: function(namespace) {
events = namespace ?
events.filter(function(el) {
return el['namespace'] !== namespace;
}) :
[];
}
};
})(Wee);
|
JavaScript
| 0 |
@@ -2932,69 +2932,38 @@
ents
- = events.filter(function(el) %7B%0A%09%09%09%09%09return el !== evt;%0A%09%09%09%09%7D
+.splice(events.indexOf(evt), 1
);%0A%09
@@ -3680,32 +3680,93 @@
reakpoint value%0A
+%09%09 * @param %7Bstring%7D %5Brules.namespace%5D - namespace the event%0A
%09%09 * @param %7Bboo
@@ -4010,69 +4010,8 @@
ize%0A
-%09%09 * @param %7Bstring%7D %5Brules.namespace%5D - namespace the event%0A
%09%09 *
@@ -4305,27 +4305,35 @@
* Re
-set all
+move events from
bound
-event
+rule
s%0A%09%09
@@ -4521,10 +4521,9 @@
n el
-%5B'
+.
name
@@ -4531,10 +4531,8 @@
pace
-'%5D
!==
|
eb98a92b02257e095e03880d2043d81248f84cb4
|
Fix #18
|
src/ef.js
|
src/ef.js
|
// Import everything
import parse from './lib/parser.js'
import typeOf from 'ef-core/src/lib/utils/type-of.js'
import { mixStr } from 'ef-core/src/lib/utils/literals-mix.js'
import parseEft from 'eft-parser'
import { version } from '../package.json'
// Import core components
import {
create as createComponent,
createElement,
mapAttrs,
EFNodeWrapper,
EFTextFragment,
Fragment,
scoped,
onNextRender,
inform,
exec,
bundle,
isPaused,
setDOMImpl,
declareNamespace,
mountOptions
} from 'ef-core'
// Set parser
let parser = parseEft
/**
* @typedef {import('ef-core/src/ef-core.js').EFMountOption} EFMountOption
* @typedef {import('ef-core/src/ef-core.js').EFMountConfig} EFMountConfig
* @typedef {import('ef-core/src/ef-core.js').EFAST} EFAST
* @typedef {import('ef-core/src/ef-core.js').EFBaseClass} EFBaseClass
* @typedef {import('ef-core/src/ef-core.js').EFEventHandlerArg} EFEventHandlerArg
* @typedef {import('ef-core/src/ef-core.js').EFEventHandlerMethod} EFEventHandlerMethod
* @typedef {import('ef-core/src/ef-core.js').EFSubscriberHandlerArg} EFSubscriberHandlerArg
* @typedef {import('ef-core/src/ef-core.js').EFSubscriberHandlerMethod} EFSubscriberHandlerMethod
* @typedef {import('ef-core/src/ef-core.js').EFTemplateScope} EFTemplateScope
* @typedef {import('ef-core/src/ef-core.js').Fragment} Fragment
* @typedef {import('ef-core/src/ef-core.js').EFNodeWrapper} EFNodeWrapper
* @typedef {import('ef-core/src/ef-core.js').EFTextFragment} EFTextFragment
* @typedef {import('ef-core/src/ef-core.js').EFEventOptions} EFEventOptions
*/
// eslint-disable-next-line valid-jsdoc
/**
* Return a brand new class for the new component
* @param {string|EFAST} value - Template or AST for the component
*/
const create = (value) => {
const valType = typeOf(value)
if (valType === 'string') value = parse(value, parser)
else if (valType !== 'array') throw new TypeError('Cannot create new component without proper template or AST!')
return createComponent(value)
}
/**
* Change parser
* @param {Function} newParser - Parser you want to change with
* @returns {void}
*/
const setParser = (newParser) => {
parser = newParser
}
// eslint-disable-next-line valid-jsdoc
/**
* Tagged template to quickly create an inline ef component class
* @param {...*} args - String literal
*/
const t = (...args) => create(mixStr(...args))
let coreVersion = version
if (process.env.NODE_ENV !== 'production') {
coreVersion = `${version}+debug`
}
export {
t,
create,
createElement,
mapAttrs,
EFNodeWrapper,
EFTextFragment,
Fragment,
scoped,
onNextRender,
inform,
exec,
bundle,
isPaused,
setParser,
parseEft,
mountOptions,
setDOMImpl,
declareNamespace,
coreVersion as version
}
if (process.env.NODE_ENV !== 'production') console.info(`[EF] ef.js v${coreVersion} initialized!`)
|
JavaScript
| 0 |
@@ -369,32 +369,48 @@
ent,%0A%09Fragment,%0A
+%09toEFComponent,%0A
%09scoped,%0A%09onNext
|
31813756f04ae3ba02f11865bf4e7eb72f9c52a5
|
remove graphql-config (#731)
|
src/generate/runtime-config-helpers/getCodegenConfig.js
|
src/generate/runtime-config-helpers/getCodegenConfig.js
|
const fs = require('fs');
const { pascalCase } = require('pascal-case');
const { importSchema } = require('graphql-import');
const { isObjectType } = require('graphql');
let schemaString = fs
.readFileSync('./schema.graphql')
.toString()
.replace(/extend type/g, `type`);
schemaString = `${schemaString}
## Federation Types
scalar _FieldSet
directive @external on FIELD_DEFINITION
directive @requires(fields: _FieldSet!) on FIELD_DEFINITION
directive @provides(fields: _FieldSet!) on FIELD_DEFINITION
directive @key(fields: _FieldSet!) on OBJECT | INTERFACE
directive @extends on OBJECT
scalar Upload
`
.replace('@entity(embedded: Boolean)', '@entity(embedded: Boolean, additionalFields: [AdditionalEntityFields])')
.replace(
'@union(discriminatorField: String)',
'@union(discriminatorField: String, additionalFields: [AdditionalEntityFields])',
)
.replace('@chimp(embedded: Boolean)', '@chimp(embedded: Boolean, additionalFields: [AdditionalEntityFields])');
const schema = importSchema(schemaString, {}, { out: 'GraphQLSchema' });
const typeMap = schema.getTypeMap();
const getConfig = (type) => (type.toConfig ? type.toConfig().astNode : type.astNode);
const mappers = {};
for (const typeName in typeMap) {
const type = schema.getType(typeName);
if (isObjectType(type)) {
if (getConfig(type)) {
if (!['Query', 'Mutation', 'Subscription'].includes(getConfig(type).name.value)) {
mappers[typeName] = `${pascalCase(typeName)}DbObject`;
}
}
}
}
module.exports = function ({ contextType } = {}) {
return {
overwrite: true,
schema: schemaString,
generates: {
'generated/graphql/types.ts': {
config: {
contextType: contextType || '~app/context#GqlContext',
idFieldName: 'id',
objectIdType: 'string',
federation: true,
mappers,
scalars: {
Upload: 'Promise<GraphQLFileUpload>',
},
},
plugins: [
'typescript',
'typescript-resolvers',
'typescript-operations',
'chimp-graphql-codegen-plugin',
{ add: 'export {GqlContext};' },
{
add: `
import { ReadStream } from "fs-capacitor";
interface GraphQLFileUpload {
filename: string;
mimetype: string;
encoding: string;
createReadStream(options?:{encoding?: string, highWaterMark?: number}): ReadStream;
}`,
},
],
},
},
};
};
|
JavaScript
| 0 |
@@ -79,71 +79,40 @@
%7B i
-mportSchema %7D = require('graphql-import');%0Aconst %7B isObjectType
+sObjectType, Source, buildSchema
%7D =
@@ -955,76 +955,107 @@
');%0A
+%0A
const s
-chema = importSchema(schemaString, %7B%7D, %7B out: 'GraphQLSchema'
+ource = new Source(schemaString);%0Aconst schema = buildSchema(source, %7B assumeValidSDL: true
%7D);
|
07e24a2602f4ccf2cb898ddb72b746a021661faf
|
make add ons can pass the masonry object
|
src/Ractive-decorators-masonryjs.js
|
src/Ractive-decorators-masonryjs.js
|
/*
ractive-decorators-masonryjs
============================
Version 0.0.1.
Ractive decorator for masonry.js
==========================
Troubleshooting: If you're using a module system in your app (AMD or
something more nodey) then you may need to change the paths below,
where it says `require( 'ractive' )` or `define([ 'ractive' ]...)`.
==========================
Usage: Include this file on your page below Ractive, e.g:
<script src='lib/ractive.js'></script>
<script src='lib/ractive-decorators-masonryjs.js'></script>
Or, if you're using a module loader, require this module:
// requiring the plugin will 'activate' it - no need to use
// the return value
require( 'ractive-decorators-masonryjs' );
<< more specific instructions for this plugin go here... >>
*/
(function ( global, factory ) {
'use strict';
// AMD environment
if ( typeof define === 'function' && define.amd ) {
define([ 'ractive', 'masonry' ], factory );
}
// Common JS (i.e. node/browserify)
else if ( typeof module !== 'undefined' && module.exports && typeof require === 'function' ) {
factory( require( 'ractive' ), require( 'masonry' ) );
}
// browser global
else if ( global.Ractive && global.Masonry ) {
factory( global.Ractive, global.Masonry );
}
else {
throw new Error( 'Could not find Ractive or Masonry! It must be loaded before the ractive-decorators-masonryjs plugin' );
}
}( typeof window !== 'undefined' ? window : this, function ( Ractive, Masonry ) {
'use strict';
var masonryItemDecorator = function(node, content) {
var container = document.querySelector(masonryItemDecorator.parentNodeId);
var msnry = new Masonry( container, masonryItemDecorator.masonryOptions );
//msnry.addItems(node);
return {
teardown: function() {}
}
};
masonryItemDecorator.parentInfo = this;
masonryItemDecorator.parentNodeId = '#container';
masonryItemDecorator.masonryOptions = {
columnWidth: 250,
itemSelector: '.item'
};
Ractive.decorators.masonryItem = masonryItemDecorator;
}));
|
JavaScript
| 0 |
@@ -1584,16 +1584,18 @@
nt) %7B%0A%09%09
+//
var cont
@@ -1663,16 +1663,18 @@
eId);%0A%09%09
+//
var msnr
@@ -1742,18 +1742,64 @@
ns );%0A%09%09
-//
+var msnry = masonryItemDecorator.parentNodes;%0A%09%09
msnry.ad
@@ -1861,16 +1861,18 @@
%7D%0A%09%7D;%0A%0A%09
+//
masonryI
@@ -1904,16 +1904,18 @@
this;%0A%09
+//
masonryI
@@ -1956,16 +1956,118 @@
ainer';%0A
+%09masonryItemDecorator.parentNodeId = '#container';%0A%09masonryItemDecorator.parentNodes = new Masonry();%0A
%09masonry
|
d956307fb81bc0b6561ec13a0cf1655c4d6ffc6c
|
Remove assert on event.name (handled somewhere else)
|
lib/middleware.js
|
lib/middleware.js
|
const assert = require('assert');
'use strict';
/**
* Once middleware will block an event if there is already a scheduled event
* @param {Event} event the event to check
* @param {DBWrkr} wrkr wrkr instance to work with
* @param {function} done callback
*/
function once(event, wrkr, done) {
assert(typeof event.name === 'string', 'event must be a valid event');
const findSpec = {
name: event.name
};
if (event.tid) findSpec.tid = event.tid;
wrkr.find(findSpec, (err, events) => {
if (err) return done(err);
// Mark event as Blocked, DBWrkr.publish will not store it
if (events.length) {
event.__blocked = true;
}
event.when = event.once;
if (typeof event.when === 'number') { // ms
event.when = new Date(Date.now()+event.when);
}
delete event.once;
return done();
});
}
// Exports
module.exports = {
once: once
};
|
JavaScript
| 0 |
@@ -1,38 +1,4 @@
-const assert = require('assert');%0A
'use
@@ -261,81 +261,8 @@
e) %7B
-%0A assert(typeof event.name === 'string', 'event must be a valid event');
%0A%0A
|
b5e8a275b8f745dbf38909f2098623dc7afd72da
|
Make calls to validation pipeline in main middleware
|
lib/middleware.js
|
lib/middleware.js
|
/**
Resource Middleware
@description main definition of middleware
@exports @default {function} remoteResourceMiddleware
**/
/* eslint no-unused-vars:0 */
require('core-js/library/fn/object/assign');
import fetch from 'isomorphic-fetch';
import RemoteResource from './RemoteResource';
import { APIError, CallProcessingError } from './errors';
import * as utils from './utils';
/**
@name remoteResourceMiddleware
@desc provides a function that can be used to configure the middleware's
behavior, returning valid Redux middleware
@param {object} conf
@param {object} injectedHeaders headers to be injected on every outgoing req
@param {object} statusActions HTTP Status codes w/ corresponding types
or functions that will be emitted when the status code is received
@returns {function} ReduxMiddleware
**/
export default function remoteResourceMiddleware(_conf) {
const conf = Object.assign({
injectedHeaders: {},
statusActions: {}
}, _conf || {});
return store => next => action => {
// if we don't find our symbol don't even bother
if (action.hasOwnProperty && !action.hasOwnProperty(RemoteResource))
return next(action);
const callOpts = action[RemoteResource];
store.dispatch(action);
};
}
/**
@private
@name cacheLookup
@desc consults the given state cache mapping to see if we already have a value
note that this will *not* run when using actionable HTTP methods like POST
@param {string} method HTTP verb, used to determine if we should cache
@param {function} cacheMapping
@param {boolean} nocache
@param {function} emitSuccessOnCacheHit
@returns {Promise<boolean>} result
@TODO allow `cacheMapping` to return a value that will be supplied to the
success event if `emitSuccessOnCacheHit` is true after the whole thing
short circuits
**/
function cacheLookup(state, { method, cacheMapping, nocache }) {
const stepName = '#cacheLookup';
if (!utils.isCacheableRequest(method) || !cacheMapping || nocache)
return Promise.resolve(false);
try {
return Promise.resolve(cacheMapping(state));
} catch (error) {
const msg = 'Error thrown while evaluating cache mapping';
return Promise.reject(new CallProcessingError(msg, stepName, error));
}
}
/**
@private
@name buildHeaders
@desc builds a flat header map by evaluating each k/v in the given headers
object, optionally injecting any headers from the top level configuration,
will evaluate promises & functions passing in the state.
If a header val is a function that returns false the header will be skipped
NOTE: headers given in the action *will* overwrite globally injected headers
@param {object} state
@param {object} headers flat map w/ a mix of values, functions, or promises
@param {object|string} body used to determine if we'll be sending JSON
@param {object} injectedHeaders optional
@returns {Promise<object|CallProcessingError}
**/
function buildHeaders(state, { headers, body }, { injectedHeaders }) {
const stepName = '#buildHeaders';
let headerMap = Object.assign({}, injectedHeaders || {}, actionHeaders);
if (
body &&
typeof body === 'object' &&
!headerMap.hasOwnProperty('Content-Type')
) headerMap['Content-Type'] = 'application/json';
let ps = Object.keys(headerMap).map(header => {
const headerVal = headerMap[header];
if (typeof headerVal === 'function')
try {
return { key: header, value: headerVal(state) };
} catch (error) {
const msg = `Error thrown when evaluating header function ${header}`;
return Promise.reject(new CallProcessingError(msg, stepName, error));
}
else if (utils.isPromise(headerVal))
return headerVal.then(v => ({ key: header, value: v }));
// if you're not a promise but still an object we don't want you
else if (typeof headerVal === 'object')
return Promise.reject(
new CallProcessingError(`Object given for header ${header}`, stepName)
);
// I guess it's just a plain value
else return { key: header, value: headerVal };
});
return Promise.all(ps).then(p => p
.filter(pair => pair.value !== false)
.reduce((acc, pair) => { acc[pair.key] = pair.value; return acc; }, {})
);
}
/**
@private
@name parseBody
@desc detects if the request body is an object, if so will attempt to parse
it as JSON, otherwise just returning it; if body is a function it will be
called with the state passed in - supports promises
@param {object} state
@param {any} body
@returns {Promise<string>} parsedBody
**/
function parseBody(state, body) {
const stepName = '#parseBody';
if (utils.isPromise(body))
return body.then(realBody => parseBody(realBody));
else if (typeof body === 'object')
try {
// TODO: can this even fail?
return Promise.resolve(JSON.stringify(body));
} catch (error) {
return Promise.reject(new CallProcessingError(
'Error parsing body', stepName, error
));
}
else if (typeof body === 'function')
try {
return Promise.resolve(body(state));
} catch (error) {
return Promise.reject(new CallProcessingError(
'Error occurred while evaluating body function', stepName, error
));
}
}
|
JavaScript
| 0.000001 |
@@ -1222,33 +1222,483 @@
e%5D;%0A
+%0A
-store.dispatch(action
+const validationPipeline = %5B%0A cacheLookup(store.getState(), callOpts),%0A buildHeaders(store.getState(), callOpts, conf),%0A parseBody(store.getState(), callOpts.body)%0A %5D;%0A%0A return Promise.all(validationPipeline)%0A%0A // TODO: fill in w/ lifecycle method calls & HTTP request%0A .then(() =%3E console.log(%22We're validated!%22))%0A%0A // TODO: obviously this is temporary,%0A // dispatch the error lifecycle w/ the error%0A .catch(error =%3E %7B throw error; %7D
);%0A
|
cbc5a723cea25f39c321eb49f3091c367d3a83b3
|
fix trailing slash check for Windows
|
lib/middleware.js
|
lib/middleware.js
|
var path = require('path')
var fs = require('fs')
var handlebars = require('handlebars')
var url = require('url')
var mime = require('mime')
var errorTemplate = handlebars.compile(fs.readFileSync(path.resolve(__dirname, '../templates/error.html')).toString())
module.exports = function(watcher) {
return function broccoliMiddleware(request, response, next) {
watcher.then(function(hash) {
var directory = path.normalize(hash.directory)
var pathname = url.parse(request.url).pathname
var filename = path.normalize(path.join(directory, decodeURIComponent(pathname)))
var stat, lastModified, type, charset, buffer
// this middleware is for development use only
// contains null byte or escapes directory
if (filename.indexOf('\0') !== -1 || filename.indexOf(directory) !== 0) {
response.writeHead(400)
response.end()
return
}
// handle document index
if (filename[filename.length - 1] === '/') {
filename = path.join(filename, 'index.html')
}
try {
stat = fs.statSync(filename)
} catch (e) {
// 404
next()
return
}
// if directory redirect with trailing slash
if (stat.isDirectory()) {
response.setHeader('Location', pathname + '/')
response.writeHead(301)
response.end()
return
}
lastModified = stat.mtime.toUTCString()
response.setHeader('Last-Modified', lastModified)
// nginx style treat last-modified as a tag since browsers echo it back
if (request.headers['if-modified-since'] === lastModified) {
response.writeHead(304)
response.end()
return
}
type = mime.lookup(filename)
charset = mime.charsets.lookup(type)
if (charset) {
type += '; charset=' + charset
}
// we don't want stale build files
response.setHeader('Cache-Control', 'private, max-age=0, must-revalidate')
response.setHeader('Content-Length', stat.size)
response.setHeader('Content-Type', type)
// read file sync so we don't hold open the file creating a race with
// the builder (Windows does not allow us to delete while the file is open).
buffer = fs.readFileSync(filename)
response.writeHead(200)
response.end(buffer)
}, function(buildError) {
var context = {
message: buildError.message || buildError,
file: buildError.file,
treeDir: buildError.treeDir,
line: buildError.line,
column: buildError.column,
stack: buildError.stack
}
response.setHeader('Content-Type', 'text/html')
response.writeHead(500)
response.end(errorTemplate(context))
}).catch(function(err) { console.log(err) })
}
}
|
JavaScript
| 0 |
@@ -454,24 +454,22 @@
var
-pathname
+urlObj
= url.p
@@ -489,17 +489,8 @@
url)
-.pathname
%0A
@@ -507,31 +507,16 @@
ename =
-path.normalize(
path.joi
@@ -547,16 +547,23 @@
mponent(
+urlObj.
pathname
@@ -564,17 +564,16 @@
thname))
-)
%0A v
@@ -955,19 +955,24 @@
1%5D ===
-'/'
+path.sep
) %7B%0A
@@ -988,29 +988,10 @@
ame
++
=
- path.join(filename,
'in
@@ -995,25 +995,24 @@
'index.html'
-)
%0A %7D%0A%0A
@@ -1211,24 +1211,55 @@
ectory()) %7B%0A
+ urlObj.pathname += '/'%0A
resp
@@ -1289,22 +1289,26 @@
n',
-pathname + '/'
+url.format(urlObj)
)%0A
|
c5c56e6eb948bdf49ae96331dce5f7bfaae7dfce
|
move return false to the right place. Fixes #1720
|
lib/less/to-css-visitor.js
|
lib/less/to-css-visitor.js
|
(function (tree) {
tree.toCSSVisitor = function(env) {
this._visitor = new tree.visitor(this);
this._env = env;
};
tree.toCSSVisitor.prototype = {
isReplacing: true,
run: function (root) {
return this._visitor.visit(root);
},
visitRule: function (ruleNode, visitArgs) {
if (ruleNode.variable) {
return [];
}
return ruleNode;
},
visitMixinDefinition: function (mixinNode, visitArgs) {
return [];
},
visitExtend: function (extendNode, visitArgs) {
return [];
},
visitComment: function (commentNode, visitArgs) {
if (commentNode.isSilent(this._env)) {
return [];
}
return commentNode;
},
visitMedia: function(mediaNode, visitArgs) {
mediaNode.accept(this._visitor);
visitArgs.visitDeeper = false;
if (!mediaNode.rules.length) {
return [];
}
return mediaNode;
},
visitDirective: function(directiveNode, visitArgs) {
if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) {
return [];
}
if (directiveNode.name === "@charset") {
// Only output the debug info together with subsequent @charset definitions
// a comment (or @media statement) before the actual @charset directive would
// be considered illegal css as it has to be on the first line
if (this.charset) {
if (directiveNode.debugInfo) {
var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n");
comment.debugInfo = directiveNode.debugInfo;
return this._visitor.visit(comment);
}
return [];
}
this.charset = true;
}
return directiveNode;
},
checkPropertiesInRoot: function(rules) {
var ruleNode;
for(var i = 0; i < rules.length; i++) {
ruleNode = rules[i];
if (ruleNode instanceof tree.Rule && !ruleNode.variable) {
throw { message: "properties must be inside selector blocks, they cannot be in the root.",
index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null};
}
}
},
visitRuleset: function (rulesetNode, visitArgs) {
var rule, rulesets = [];
if (rulesetNode.firstRoot) {
this.checkPropertiesInRoot(rulesetNode.rules);
}
if (! rulesetNode.root) {
rulesetNode.paths = rulesetNode.paths
.filter(function(p) {
var i;
if (p[0].elements[0].combinator.value === ' ') {
p[0].elements[0].combinator = new(tree.Combinator)('');
}
for(i = 0; i < p.length; i++) {
if (p[i].getIsReferenced() && p[i].getIsOutput()) {
return true;
}
return false;
}
});
// Compile rules and rulesets
for (var i = 0; i < rulesetNode.rules.length; i++) {
rule = rulesetNode.rules[i];
if (rule.rules) {
// visit because we are moving them out from being a child
rulesets.push(this._visitor.visit(rule));
rulesetNode.rules.splice(i, 1);
i--;
continue;
}
}
// accept the visitor to remove rules and refactor itself
// then we can decide now whether we want it or not
if (rulesetNode.rules.length > 0) {
rulesetNode.accept(this._visitor);
}
visitArgs.visitDeeper = false;
this._mergeRules(rulesetNode.rules);
this._removeDuplicateRules(rulesetNode.rules);
// now decide whether we keep the ruleset
if (rulesetNode.rules.length > 0 && rulesetNode.paths.length > 0) {
rulesets.splice(0, 0, rulesetNode);
}
} else {
rulesetNode.accept(this._visitor);
visitArgs.visitDeeper = false;
if (rulesetNode.firstRoot || rulesetNode.rules.length > 0) {
rulesets.splice(0, 0, rulesetNode);
}
}
if (rulesets.length === 1) {
return rulesets[0];
}
return rulesets;
},
_removeDuplicateRules: function(rules) {
// remove duplicates
var ruleCache = {},
ruleList, rule, i;
for(i = rules.length - 1; i >= 0 ; i--) {
rule = rules[i];
if (rule instanceof tree.Rule) {
if (!ruleCache[rule.name]) {
ruleCache[rule.name] = rule;
} else {
ruleList = ruleCache[rule.name];
if (ruleList instanceof tree.Rule) {
ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)];
}
var ruleCSS = rule.toCSS(this._env);
if (ruleList.indexOf(ruleCSS) !== -1) {
rules.splice(i, 1);
} else {
ruleList.push(ruleCSS);
}
}
}
}
},
_mergeRules: function (rules) {
var groups = {},
parts,
rule,
key;
for (var i = 0; i < rules.length; i++) {
rule = rules[i];
if ((rule instanceof tree.Rule) && rule.merge) {
key = [rule.name,
rule.important ? "!" : ""].join(",");
if (!groups[key]) {
parts = groups[key] = [];
} else {
rules.splice(i--, 1);
}
parts.push(rule);
}
}
Object.keys(groups).map(function (k) {
parts = groups[k];
if (parts.length > 1) {
rule = parts[0];
rule.value = new (tree.Value)(parts.map(function (p) {
return p.value;
}));
}
});
}
};
})(require('./tree'));
|
JavaScript
| 0.00004 |
@@ -3448,25 +3448,9 @@
- return false;
+%7D
%0A
@@ -3462,33 +3462,45 @@
-%7D
+return false;
%0A
|
8e10d4221b8231f4de72130a8014bb79c9b277d0
|
Tweak stars size on retina devices
|
src/assets/js/main.js
|
src/assets/js/main.js
|
(function () {
function initTwinklingStars() {
particlesJS('stars', {
particles: {
number: {
value: 180,
density: {
enable: true,
value_area: 600
}
},
color: {
value: '#ffffff'
},
shape: {
type: 'circle'
},
opacity: {
value: 1,
random: true,
anim: {
enable: true,
speed: 3,
opacity_min: 0
}
},
size: {
value: 1.5,
random: true,
anim: {
enable: true,
speed: 1,
size_min: 0.5,
sync: false
}
},
line_linked: {
enable: false
},
move: {
enable: true,
speed: 50,
direction: 'none',
random: true,
straight: true,
out_mode: 'bounce'
}
},
retina_detect: true
});
}
window.onload = function () {
document.body.className = '';
initTwinklingStars();
}
window.onresize = function () {
clearTimeout(window.onResizeEnd);
window.onResizeEnd = setTimeout(initTwinklingStars, 250);
}
window.ontouchmove = function () {
return false;
}
window.onorientationchange = function () {
document.body.scrollTop = 0;
}
}());
|
JavaScript
| 0 |
@@ -40,20 +40,37 @@
ngStars(
+devicePixelRatio
) %7B%0A
+%0A
@@ -810,16 +810,35 @@
lue: 1.5
+ / devicePixelRatio
,%0A
@@ -1002,16 +1002,35 @@
min: 0.5
+ / devicePixelRatio
,%0A
@@ -1531,32 +1531,96 @@
= function () %7B%0A
+ initTwinklingStars(window.devicePixelRatio / 1.5 %7C%7C 1);%0A
document
@@ -1645,38 +1645,8 @@
'';%0A
- initTwinklingStars();%0A
|
c8246cbc6ff6f1772b6fbf2e0efcf8bbb99593e5
|
Make server-side handlebars loading a tiny bit more sane.
|
lib/loader/transformers.js
|
lib/loader/transformers.js
|
'use strict';
var path = require('path');
var util = require('util');
var Handlebars = require('handlebars');
function SourceTransformer(source) {
this.source = source;
}
module.exports.SourceTransformer = SourceTransformer;
SourceTransformer.prototype.findDependencies = function() {
return [];
};
SourceTransformer.prototype.functionStringWithDependencies = function(dependencyList) {
return '(function(){})';
};
SourceTransformer.prototype.evaluate = function(dependencyMap) {
var values = [];
var dependencyList = [];
for (var dependencyPath in dependencyMap) {
var obj = dependencyMap[dependencyPath];
dependencyList.push(dependencyPath);
values.push(obj);
}
var functionString = this.functionStringWithDependencies(dependencyList);
var result = eval(functionString).apply({}, values);
return result;
};
var JavaScriptSourceTransformer = function() {
SourceTransformer.apply(this, arguments);
};
util.inherits(JavaScriptSourceTransformer, SourceTransformer);
JavaScriptSourceTransformer.prototype.findDependencies = function() {
var dependencies = {};
var source = this.source.replace(/^\s*\/\/.*$/, '');
source = source.replace(/^\/\*.+?\*\//m, '');
source.split(/[\n\r]+/).every(function(line) {
line = line.trim();
if (!line) {
return true;
}
// 'use strict';
var result = /^['"].+['"];?$/.exec(line);
if (result) {
return true;
}
var result = /^var\s+\w+\s*=\s*([\w.]+)\s*;?$/.exec(line);
if (!result) {
return false;
}
dependencies[result[1]] = 1;
return true;
});
var dependencyPaths = Object.keys(dependencies);
return dependencyPaths;
};
JavaScriptSourceTransformer.prototype.functionStringWithDependencies = function(dependencyList) {
var source = this.source;
var aliases = [];
for (var i = 0; i < dependencyList.length; i++) {
var dependencyPath = dependencyList[i];
var alias = dependencyPath.replace(/[^a-zA-Z0-9_]/g, '_') + '_' + (+new Date());
// Replace all foo.bar with foo_bar_12345 aliases.
source = source.split(dependencyPath).join(alias);
aliases.push(alias);
}
// Build a function with the given source, using aliases as arguments.
// Then call the function with the actual objects in the correct order.
var functionDefinition = '(function(' + aliases.join(',') + ') { ' + source + ' })';
return functionDefinition;
};
function HandlebarsSourceTransformer() {
SourceTransformer.apply(this, arguments);
}
util.inherits(HandlebarsSourceTransformer, SourceTransformer);
HandlebarsSourceTransformer.prototype.findDependencies = function() {
var handlebarsLib = path.dirname(require.resolve('handlebars'));
var runtimeDist = path.resolve(handlebarsLib, '..', 'dist/handlebars.runtime.js');
return [runtimeDist];
};
HandlebarsSourceTransformer.prototype.functionStringWithDependencies = function(dependencyList) {
var template = Handlebars.precompile(this.source);
var wrapped = [
'(function() {',
' if (typeof Handlebars == "undefined") {',
' var Handlebars = require("handlebars");',
' }',
' return Handlebars.VM.template(' + template + ', Handlebars);',
'})'].join('\n');
return wrapped;
};
var TRANSFORMERS = {};
function setTransformer(extension, fn) {
TRANSFORMERS[extension] = fn;
}
module.exports.setTransformer = setTransformer;
function getTransformer(extension) {
return TRANSFORMERS[extension] || SourceTransformer;
}
module.exports.getTransformer = getTransformer;
setTransformer('.js', JavaScriptSourceTransformer);
setTransformer('.html', HandlebarsSourceTransformer);
|
JavaScript
| 0 |
@@ -2889,38 +2889,24 @@
= function(
-dependencyList
) %7B%0A var te
@@ -2987,57 +2987,18 @@
ion(
-) %7B',%0A ' if (typeof Handlebars == %22undefined%22
+Handlebars
) %7B'
@@ -3006,21 +3006,22 @@
%0A '
- var
+return
Handleb
@@ -3027,21 +3027,40 @@
bars
- = require(%22h
+.VM.template(' + template + ', H
andl
@@ -3064,17 +3064,16 @@
ndlebars
-%22
);',%0A
@@ -3078,103 +3078,242 @@
'
- %7D',%0A ' return Handlebars.VM.template(' + template + ', Handlebars);',%0A '%7D)'%5D.join('%5Cn'
+%7D)'%5D.join('%5Cn');%0A return wrapped;%0A%7D;%0A%0AHandlebarsSourceTransformer.prototype.evaluate = function(dependencyMap) %7B%0A var functionString = this.functionStringWithDependencies();%0A var result = eval(functionString).apply(%7B%7D, %5BHandlebars%5D
);%0A
@@ -3324,22 +3324,22 @@
urn
-wrapped
+result
;%0A%7D;%0A%0A%0A
+%0A
var
|
4deeb93aea76ccbed63572b33ac2bc741c973140
|
update urls (#19101)
|
src/applications/static-pages/i18Select/utilities/urls.js
|
src/applications/static-pages/i18Select/utilities/urls.js
|
// glossary of 'pages' that are translated
// each page has english, spanish, and tagalog urls
// when adding a page, make sure that all the translation urls for the new page are live before updating this file
export default {
faq: {
en: '/coronavirus-veteran-frequently-asked-questions',
es: '/coronavirus-veteran-frequently-asked-questions-esp',
tl: '/coronavirus-veteran-frequently-asked-questions-tag',
},
vaccine: {
en: '/health-care/covid-19-vaccine',
es: '/health-care/covid-19-vaccine-esp',
tl: '/health-care/covid-19-vaccine-tag',
},
booster: {
en: '/health-care/covid-19-vaccine/booster-shots-and-additional-doses',
es:
'/health-care/covid-19-vaccine-esp/booster-shots-and-additional-doses-esp',
tl:
'/health-care/covid-19-vaccine-tag/booster-shots-and-additional-doses-tag',
},
vaccineRecord: {
en: '/health-care/covid-19-vaccine/vaccine-record',
es: '/health-care/covid-19-vaccine-esp/vaccine-record-esp',
tl: '/health-care/covid-19-vaccine-tag/vaccine-record-tag',
},
about: {
en: '/health-care/covid-19-vaccine/about-covid-19-vaccine',
es: '/health-care/covid-19-vaccine/about-covid-19-vaccine-esp',
tl: '/health-care/covid-19-vaccine/about-covid-19-vaccine-tag',
},
};
|
JavaScript
| 0 |
@@ -1155,32 +1155,36 @@
covid-19-vaccine
+-esp
/about-covid-19-
@@ -1227,32 +1227,36 @@
covid-19-vaccine
+-tag
/about-covid-19-
|
849f0e309cc5e8a458f17a939135b434d2781ac3
|
correct index.js for require.js 2.1.10
|
app/index.js
|
app/index.js
|
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var AmdGenerator = module.exports = function AmdGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.on('end', function () {
this.installDependencies({ skipInstall: options['skip-install'] });
});
this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};
util.inherits(AmdGenerator, yeoman.generators.Base);
AmdGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// have Yeoman greet the user.
console.log(this.yeoman);
var prompts = [
{
name: 'githubAccount',
message: 'What is your github account?'
},
{
name: 'moduleName',
message: 'What is the name of your AMD module (the slug-name of the Github repository)?'
},
{
name: 'objectName',
message: 'What is the name of the object?'
}
];
this.prompt(prompts, function (props) {
this.githubAccount = props.githubAccount;
this.moduleName = props.moduleName;
this.objectName = props.objectName;
cb();
}.bind(this));
};
AmdGenerator.prototype.app = function app() {
this.mkdir('src');
this.template('src/_amd-module.js', 'src/' + this.moduleName + '.js');
this.mkdir('example');
this.template('example/_app.js', 'example/app.js');
this.template('example/_index.html', 'example/index.html');
this.copy('example/main.css', 'example/main.css');
this.copy('example/require-2.1.9.min.js', 'example/require-2.1.9.min.js');
this.mkdir('dist');
this.mkdir('doc');
this.template('_gruntfile.js', 'Gruntfile.js');
this.copy('bowerrc', '.bowerrc');
this.template('_package.json', 'package.json');
this.template('_bower.json', 'bower.json');
this.template('_README.md', 'README.md');
this.copy('gitignore', '.gitignore');
this.copy('gitattributes', '.gitattributes');
this.copy('jscs.json', '.jscs.json');
};
AmdGenerator.prototype.projectfiles = function projectfiles() {
this.copy('editorconfig', '.editorconfig');
this.copy('jshintrc', '.jshintrc');
};
|
JavaScript
| 0.000082 |
@@ -1472,33 +1472,34 @@
ple/require-2.1.
-9
+10
.min.js', 'examp
@@ -1517,9 +1517,10 @@
2.1.
-9
+10
.min
|
316182d77bf9962889fb1651075e35e35f5113b3
|
remove first log on test env
|
app/index.js
|
app/index.js
|
'use strict';
let express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser'),
morgan = require('morgan'),
multer = require('multer'),
config = require('../config'),
middlewares = require('./middlewares'),
routes = require('./routes'),
app = express();
app
.use(cors())
.use(bodyParser.json({ strict: false }))
.use(bodyParser.urlencoded({ extended: true }))
.use(multer())
.use(middlewares.resHandler)
.use(middlewares.authentication.initialize())
.use('/', routes.docker)
.use('/v:version', routes.docker)
.use('/api', routes.api)
.listen(config.port, () => {
console.log('Listenning on port: %s', config.port);
})
.on('upgrade', routes.upgrade);
if (config.logging) {
app.use(morgan(config.logger));
}
module.exports = app;
|
JavaScript
| 0 |
@@ -603,16 +603,42 @@
() =%3E %7B%0A
+ if (config.logging) %7B%0A
consol
@@ -683,16 +683,20 @@
.port);%0A
+ %7D%0A
%7D)%0A.on('
|
bc10c4c3bc8a8431c2a9dba113e4ed4fd816cdbe
|
Fix bug using err
|
app/index.js
|
app/index.js
|
'use strict';
var fs = require('fs');
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var GenesisGenerator = module.exports = function GenesisGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.on('end', function () {
this.installDependencies({ skipInstall: options['skip-install'] });
});
this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};
util.inherits(GenesisGenerator, yeoman.generators.Base);
GenesisGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// welcome message
var welcome =
"\n .---------------------------------------." +
"\n | |" +
"\n | " + "G E N E S I S S K E L E T O N".yellow.bold + " |" +
"\n | |" +
"\n | " + "You're moments away from".red + " |" +
"\n | " + "your next great app!".red + " |" +
"\n | |" +
"\n '---------------------------------------'" +
"\n";
this.log.writeln(welcome);
var prompts = [];
try {
var pkg = require(path.join(process.cwd(), 'package.json'));
} catch (e) {}
if (!pkg) {
prompts.push({
name: 'initNpm',
message: 'Would you like to setup ' + 'package.json'.yellow + ' first?',
default: 'Y/n'
});
}
this.prompt(prompts, function (err, props) {
if (err) {
return this.emit('error', err);
}
for (var prop in props) {
this[prop] = (/y/i).test(props[prop]);
}
cb();
}.bind(this));
};
GenesisGenerator.prototype.npm = function npm() {
var done = this.async();
if (this.initNpm) {
var cb = function(err) {
this.log.ok('Initialized ' + 'package.json'.yellow);
done(err);
}.bind(this);
this.spawnCommand('npm', ['init'], cb).on('exit', cb);
} else {
this.log.ok('Already initialized ' + 'package.json'.yellow);
done();
}
}
GenesisGenerator.prototype.clone = function clone() {
var cb = this.async();
var branch = this.options.branch || 'master';
if (this.options.feature) {
branch = 'feature/' + this.options.feature;
}
try {
var originalPkg = require(path.join(process.cwd(), 'package.json'));
} catch (e) {}
this.remote('ericclemmons', 'genesis-skeleton', branch, function(err, remote) {
this.log.ok('Downloaded latest Genesis Skeleton (' + branch.yellow + ')');
if (originalPkg) {
var remotePath = path.join(remote.cachePath, 'package.json');
var remotePkg = JSON.parse(fs.readFileSync(remotePath));
var props = ['scripts', 'dependencies', 'peerDependencies'];
for (var key in props) {
var prop = props[key];
if (!originalPkg[prop]) {
originalPkg[prop] = {};
}
this._.extend(originalPkg[prop], remotePkg[prop] || {});
}
fs.writeFileSync(remotePath, JSON.stringify(originalPkg, null, 2) + "\n");
this.log.ok('Merged Genesis Skeleton package into existing ' + 'package.json'.yellow);
}
remote.directory('.', '.');
cb();
}.bind(this), true);
};
GenesisGenerator.prototype.cleanup = function cleanup() {
this.log.ok('Generated Genesis Skeleton');
};
|
JavaScript
| 0.000001 |
@@ -1506,21 +1506,16 @@
nction (
-err,
props) %7B
@@ -1519,68 +1519,8 @@
) %7B%0A
- if (err) %7B%0A return this.emit('error', err);%0A %7D%0A%0A
|
08a47c85f8f68122daa175090833e7edf525665f
|
Include dotfiles when copying client directory
|
app/index.js
|
app/index.js
|
const Generator = require('yeoman-generator')
const humps = require('humps')
module.exports = class ReactZeal extends Generator {
prompting() {
return this.prompt([
{
type: 'input',
name: 'name',
message: 'Your project name',
default: kabob(this.appname)
}
]).then(function(answers) {
this.appName = kabob(answers.name)
}.bind(this))
}
writing() {
this.fs.copyTpl(
this.templatePath('package.json'),
this.destinationPath('package.json'),
{ appName: this.appName }
)
this.fs.copy(this.templatePath('client'), this.destinationPath('client'))
this.fs.copy(
this.templatePath('.eslintrc.json'),
this.destinationPath('.eslintrc.json')
)
this.fs.copy(
this.templatePath('.sass-lint.yml'),
this.destinationPath('.sass-lint.yml')
)
this.fs.copy(
this.templatePath('yarn.lock'),
this.destinationPath('yarn.lock')
)
this._mergeGitIgnore()
}
_mergeGitIgnore() {
const template = this.fs.read(this.templatePath('gitignore'))
const existing = this.fs.read(this.destinationPath('.gitignore'), {
defaults: ''
})
this.fs.write(
this.destinationPath('.gitignore'),
existing + '\n\n' + template
)
}
}
function kabob(string) {
return humps.decamelize(humps.camelize(string), { separator: '-' })
}
|
JavaScript
| 0 |
@@ -573,16 +573,23 @@
fs.copy(
+%0A
this.tem
@@ -608,16 +608,22 @@
lient'),
+%0A
this.de
@@ -645,16 +645,59 @@
client')
+,%0A %7B globOptions: %7B dot: true %7D %7D%0A
)%0A%0A t
|
8d08add0bf876df798aa30fc3ba119276f8b4e7d
|
Remove unused file
|
app/index.js
|
app/index.js
|
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';
import configureStore from './store/configureStore';
import './app.global.css';
const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('root')
);
|
JavaScript
| 0.000002 |
@@ -294,35 +294,8 @@
re';
-%0Aimport './app.global.css';
%0A%0Aco
|
f0774a8889e7c0775c224730437a8630fb32d824
|
disable es5
|
lib/model/blob.js
|
lib/model/blob.js
|
"use strict";
var Promise = require('bluebird')
, _ = require('lodash')
, mime = require('mime-types')
, marked = require('marked')
, babel = require('babel-core')
// , url_join = require('url-join')
, dot = require('dotparser')
, man = require('taskmill-core-man')
, git = require('taskmill-core-git')
, Repository = require('../git/repository')
;
class Blob {
constructor(remote, filename, options = {}) {
let { branch, text } = options;
this.text = text;
this.branch = branch;
this.remote = remote;
this.filename = filename;
this.mime_type = mime.lookup(filename);
}
metadata(fields = {}) {
let ret = {};
switch(this.mime_type) {
case 'application/javascript':
ret = Blob.metadata_js(this.text, fields);
break;
case 'text/x-markdown':
ret = Blob.metadata_md(this.text, fields);
break;
}
return ret;
}
static metadata_js(text, fields = {}) {
let ret = {};
if (fields.ast || fields.manual || fields.es5) {
try {
let es6 = babel.transform(text); // => { code, map, ast }
if (fields.ast) {
ret.ast = es6.ast;
}
if (fields.manual) {
ret.manual = man.get(es6);
}
if (fields.es5) {
ret.es5 = es6.code;
}
} catch(err) {}
}
return ret;
}
static metadata_md(text, fields = {}) {
let ret = {
markdown : {
options : { gfm : true }
}
};
if (fields.ast || fields.block) {
try {
let ast = marked.lexer(text, ret.markdown.options);
if (fields.ast) {
ret.ast = ast;
}
if (fields.block) {
ret.block = _.chain(ast)
.map((b) => {
try {
if (b.type == 'code') {
switch(b.lang) {
case 'dot':
return { type : 'dot', text : b.text, dot : dot(b.text) };
default:
return _.extend({ type : 'js', text : b.text }, Blob.metadata_js(b.text, { manual : fields.manual }));
}
}
} catch(err) {}
})
.reject(_.isEmpty)
.value();
}
} catch(err) {}
}
return ret;
}
}
module.exports = Blob;
|
JavaScript
| 0.000001 |
@@ -1341,32 +1341,35 @@
%7D%0A%0A
+ //
if (fields.es5)
@@ -1375,26 +1375,29 @@
) %7B%0A
+//
+
ret.es5 = es
@@ -1403,32 +1403,35 @@
s6.code;%0A
+ //
%7D%0A %7D catch
|
a5b0b5bae45417eb6c7f80c79539f904387ed6d0
|
Correct call to makeID()
|
lib/model/edge.js
|
lib/model/edge.js
|
// edge.js
//
// An edge in the social graph, from follower to followed
//
// Copyright 2011,2012 StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var DatabankObject = require('databank').DatabankObject,
IDMaker = require('../idmaker').IDMaker,
dateFormat = require('dateformat'),
_ = require('underscore');
var Edge = DatabankObject.subClass('edge');
exports.Edge = Edge;
Edge.schema = { pkey: 'id',
fields: ['from',
'to',
'published',
'updated'],
indices: ['from.id', 'to.id'] };
Edge.beforeCreate = function(props, callback) {
if (!_(props).has('from') ||
!_(props.from).has('id') ||
!_(props.from).has('objectType') ||
!_(props).has('to') ||
!_(props.to).has('id') ||
!_(props.to).has('objectType')) {
callback(new Error("Invalid Edge"), null);
return;
}
var now = dateFormat(new Date(), "isoDateTime", true);
props.published = props.updated = now;
props.id = IDMaker.newId();
// XXX: store from, to by reference
callback(null, props);
};
Edge.prototype.beforeUpdate = function(props, callback) {
var immutable = ['from', 'to', 'id', 'published'],
i, prop;
for (i = 0; i < immutable.length; i++) {
prop = immutable[i];
if (_(props).has(prop)) {
delete props[prop];
}
}
var now = dateFormat(new Date(), "isoDateTime", true);
props.updated = now;
// XXX: store from, to by reference
callback(null, props);
};
Edge.prototype.beforeSave = function(callback) {
if (!_(this).has('from') ||
!_(this.from).has('id') ||
!_(this.from).has('objectType') ||
!_(this).has('to') ||
!_(this.to).has('id') ||
!_(this.to).has('objectType')) {
callback(new Error("Invalid Edge"), null);
return;
}
var now = dateFormat(new Date(), "isoDateTime", true);
this.updated = now;
if (!_(this).has('id')) {
this.id = IDMaker.newId();
if (!_(this).has('published')) {
this.published = now;
}
}
callback(null);
};
|
JavaScript
| 0.000001 |
@@ -1495,37 +1495,38 @@
ps.id = IDMaker.
-newId
+makeID
();%0A%0A // XXX:
|
5fae94a29821f6b64efd1f888c74c3391043732f
|
Support externally provided fragment
|
server/get-limited-users-fragment.js
|
server/get-limited-users-fragment.js
|
'use strict';
var once = require('timers-ext/once')
, getObjectsSetFragment = require('../model/get-objects-set-fragment')
, max = Math.max;
var normalize = function (limitedUsers, applicable, preferred, limit) {
var gap;
limitedUsers._postponed_ += 1;
// Remove ones which do not belong
limitedUsers.forEach(function (user) {
if (!applicable.has(user)) limitedUsers.delete(user);
});
// Remove eventual oversize
while (limitedUsers.size > limit) limitedUsers.delete(limitedUsers.first);
// Fill if possible
gap = max(limit - limitedUsers.size, 0);
if (gap) {
preferred.some(function (user) {
if (limitedUsers.has(user)) return;
limitedUsers.add(user);
if (!--gap) return true;
});
if (gap) {
applicable.some(function (user) {
if (limitedUsers.has(user)) return;
limitedUsers.add(user);
if (!--gap) return true;
});
}
}
limitedUsers._postponed_ -= 1;
};
module.exports = function (limitedUsers, applicable, preferred, userPass/*, options*/) {
var options = Object(arguments[4]), limit = Number(options.limit);
if (isNaN(limit)) limit = 10;
normalize(limitedUsers, applicable, preferred, limit);
limitedUsers.on('change', once(function () {
normalize(limitedUsers, applicable, preferred, limit);
}));
return getObjectsSetFragment(limitedUsers, userPass);
};
|
JavaScript
| 0 |
@@ -1329,14 +1329,32 @@
userPass
+, options.fragment
);%0A%7D;%0A
|
d74fa80ac1a1a8918b732ecb2c88ce5457470c08
|
fix dir copying and add install dependencies step
|
app/index.js
|
app/index.js
|
'use strict';
var generators = require('yeoman-generator');
var mkdirp = require('mkdirp');
var fs = require('fs-extra');
function copyDir(toPath, fromPath, done) {
fs.copy(toPath, fromPath, function(err) {
if (err) {
throw new Error(err);
}
done();
});
}
module.exports = generators.Base.extend({
constructor: function() {
// Calling the super constructor is important so our generator is correctly set up
generators.Base.apply(this, arguments);
this.argument('appname', { type: String, required: true });
// And you can then access it later on this way; e.g. CamelCased
// this.appname = _.camelCase(this.appname);
// add some flags
this.option('public', {
type: Boolean,
defaults: false,
desc: 'Whether this should be a public NPM project'
});
},
writing: {
gulpfile: function() {
copyDir('gulpfile.js', 'gulpfile.js', this.async());
},
packageJSON: function() {
this.fs.copyTpl(
this.templatePath('_package.json'),
this.destinationPath('package.json'),
{
'public': this.options['public']
}
);
},
git: function() {
this.fs.copy(
this.templatePath('gitignore'),
this.destinationPath('.gitignore'));
},
editorConfig: function() {
this.fs.copy(
this.templatePath('editorconfig'),
this.destinationPath('.editorconfig')
);
},
linting: function() {
this.fs.copy(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
this.fs.copy(
this.templatePath('eslintignore'),
this.destinationPath('.eslintignore')
);
},
coverage: function() {
this.fs.copy(
this.templatePath('istanbul.yml'),
this.destinationPath('.istanbul.yml')
);
},
app: function() {
this.fs.copy(
this.templatePath('app.js'),
this.destinationPath('app.js')
);
},
testing: function() {
copyDir('tests', 'tests', this.async());
},
jsdoc: function() {
copyDir('jsdoc', 'jsdoc', this.async());
},
misc: function() {
mkdirp('src/js');
}
}
});
|
JavaScript
| 0 |
@@ -133,28 +133,28 @@
copyDir(
-to
+from
Path,
-from
+to
Path, do
@@ -173,20 +173,20 @@
opy(
-to
+from
Path,
-from
+to
Path
@@ -655,24 +655,25 @@
.appname);%0A%0A
+%0A
// add s
@@ -826,16 +826,173 @@
;%0A %7D,%0A%0A
+ _copyDir: function(fromPath, toPath) %7B%0A copyDir(%0A this.templatePath(fromPath),%0A this.destinationPath(toPath),%0A this.async()%0A );%0A %7D,%0A%0A
writin
@@ -1021,32 +1021,38 @@
ction() %7B%0A
+this._
copyDir('gulpfil
@@ -1071,30 +1071,16 @@
file.js'
-, this.async()
);%0A %7D
@@ -1235,16 +1235,49 @@
%7B%0A
+ appName: this.appname,%0A
@@ -2205,32 +2205,38 @@
ction() %7B%0A
+this._
copyDir('tests',
@@ -2243,30 +2243,16 @@
'tests'
-, this.async()
);%0A %7D
@@ -2280,24 +2280,30 @@
n() %7B%0A
+this._
copyDir('jsd
@@ -2318,22 +2318,8 @@
doc'
-, this.async()
);%0A
@@ -2378,16 +2378,69 @@
;%0A %7D%0A
+ %7D,%0A%0A install: function() %7B%0A this.npmInstall();%0A
%7D%0A%7D);%0A
|
1fa08d8e6e6c9181c1099e67217067cf5d2ba7e0
|
Include hidden files in initial project setup
|
app/index.js
|
app/index.js
|
'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var _ = require('underscore');
var path = require('path');
var fs = require('fs');
var CfsgGenerator = module.exports = function CfsgGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.argument('appname', { type: String, required: false });
this.hookFor('cfsg:legal', {
args: args
});
this.on('end', function () {
this.installDependencies({
bower: false,
npm: true,
skipInstall: options['skip-install']
});
});
this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};
util.inherits(CfsgGenerator, yeoman.generators.Base);
CfsgGenerator.prototype.askFor = function askFor() {
var cb = this.async();
var prompts = [];
if (!this.appname) {
prompts.push({
name: 'appname',
message: 'What is the name of the project?',
default: 'My App'
});
}
this.prompt(prompts, function (props) {
_.extend(this, props);
cb();
}.bind(this));
};
CfsgGenerator.prototype.app = function app() {
var sourceRoot = this.sourceRoot();
var sourceFiles = this.expand(path.join(sourceRoot, '**/*'));
var templatePrefix = '_';
sourceFiles.forEach(function (sourcePath) {
var relativePath = path.relative(sourceRoot, sourcePath);
var stats = fs.statSync(sourcePath);
if (stats.isDirectory()) {
this.mkdir(relativePath);
} else {
var fileName = path.basename(relativePath);
if (fileName.charAt(0) === templatePrefix) {
var destination = path.join(
path.dirname(relativePath),
path.basename(relativePath).substr(1)
);
this.template(relativePath, destination);
} else {
this.copy(relativePath, relativePath);
}
}
}.bind(this));
};
|
JavaScript
| 0 |
@@ -1219,16 +1219,29 @@
'**/*')
+, %7Bdot: true%7D
);%0A var
|
25f61ac50ce11fe4d36c2a9a56d6ce13193cf0b0
|
use env vars to set ft.com homepage link text and url
|
server/routers/live-figures/index.js
|
server/routers/live-figures/index.js
|
'use strict';
var app = require('../../util/app');
var service = require('../../service');
var _ = require('lodash');
var debug = require('debug')('liveblog');
/**
* A fragment containing all the figures used on the liveblog.
*/
function* liveblogFragment(next) {
var data = _.zipObject(['stateOfPlay', 'votesVsSeats', 'seatResult'], yield Promise.all([
service.stateOfPlay(5),
service.votesVsSeats(),
service.seatResult(),
]));
console.log('data', data.seatResult);
debug(JSON.stringify(data.votesVsSeats, null, 2));
this.set('Cache-Control', // jshint ignore:line
'public, max-age=10, stale-while-revalidate=3600, stale-if-error=3600');
this.set('Surrogate-Control', 'max-age=60'); // jshint ignore:line
yield this.render('liveblog-fragment', data); // jshint ignore:line
yield next;
}
/**
* A fragment containing only the figure used on the FT.com homepage (i.e. a modified 'state of play').
*/
function* ftcomFragment(next) {
var data = {
stateOfPlay: yield service.stateOfPlay(6)
};
// alter the template data to suit the homepage
data.stateOfPlay.headline = 'UK GENERAL ELECTION';
data.stateOfPlay.showRosette = true;
var longerNames = {
'Lab': 'Labour',
'LD': 'Lib Dems',
'Con': 'Conservatives'
};
data.stateOfPlay.parties.forEach(function (party) {
party.label = longerNames[party.label] || party.label;
});
data.stateOfPlay.linkText = 'Election Live Blog »';
data.stateOfPlay.linkURL = 'http://training.blogs.ft.com/westminster/liveblogs/2015-04-22-2/';
debug(JSON.stringify(data.votesVsSeats, null, 2));
this.set('Cache-Control', // jshint ignore:line
'public, max-age=10, stale-while-revalidate=3600, stale-if-error=3600');
this.set('Surrogate-Control', 'max-age=60'); // jshint ignore:line
yield this.render('ftcom-fragment', data); // jshint ignore:line
yield next;
}
/**
* A mockup page that imitates the real liveblog, for testing components in situ.
*/
function* liveblogMockup(next) {
yield this.render('liveblog-mockup'); // jshint ignore:line
yield next;
}
/**
* A mockup page that imitates the real FT.com homepage, for testing components in situ.
*/
function* ftcomMockup(next) {
yield this.render('ftcom-mockup'); // jshint ignore:line
yield next;
}
/**
* A fragment for a single constituency result
*/
function* seatResultFragment(next) {
this.set('Cache-Control', // jshint ignore:line
'public, max-age=10, stale-while-revalidate=3600, stale-if-error=3600');
this.set('Surrogate-Control', 'max-age=60'); // jshint ignore:line
var seat = service.db.seats().findOne({id: this.params.seat});
this.assert(seat, 404, 'Seat not found'); // jshint ignore:line
yield this.render('seat-result-fragment', seat); // jshint ignore:line
;
yield next;
}
module.exports = function main() {
return app()
.router()
.get('liveblog-mockup', '/liveblog-mockup', liveblogMockup) // mockup page for testing functionality
.get('liveblog-fragment', '/liveblog-fragment', liveblogFragment) // a fragment of all the widget fragments
.get('ftcom-mockup', '/ftcom-mockup', ftcomMockup) // mockup page for testing functionality
.get('ftcom-fragment', '/ftcom-fragment', ftcomFragment) // a fragment of all the widget fragments
.get('ftcom-fragment', '/seat-result-fragment/:seat', seatResultFragment);
};
|
JavaScript
| 0 |
@@ -1430,127 +1430,110 @@
t =
-'Election Live Blog %C2%BB';%0A data.stateOfPlay.linkURL = 'http://training.blogs.ft.com/westminster/liveblogs/2015-04-22-2/'
+process.env.FTCOM_HOMEPAGE_LINK_TEXT;%0A data.stateOfPlay.linkURL = process.env.FTCOM_HOMEPAGE_LINK_URL
;%0A%0A
|
c59d5f9ea69e39ffaf87b18630c0caef21ce6d00
|
rebase catchup with removing heights for grid
|
assets/src/dashboard/components/cardGallery/components.js
|
assets/src/dashboard/components/cardGallery/components.js
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import styled from 'styled-components';
import { rgba } from 'polished';
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import { KEYBOARD_USER_SELECTOR } from '../../constants';
export const GalleryContainer = styled.div`
${({ maxWidth }) => `
display: flex;
justify-content: space-around;
width: 100%;
max-width: ${maxWidth}px;
`}
`;
GalleryContainer.propTypes = {
maxWidth: PropTypes.number.isRequired,
};
export const MiniCardsContainer = styled.div`
${({ rowHeight, gap }) => `
display: grid;
grid-template-columns: repeat(3, auto);
grid-auto-rows: ${rowHeight}px;
grid-gap: ${gap}px;
`}
`;
MiniCardsContainer.propTypes = {
rowHeight: PropTypes.number.isRequired,
gap: PropTypes.number.isRequired,
};
export const ItemContainer = styled.div`
${({ width }) => `
display: flex;
justify-content: space-around;
width: ${width ? `${width}px` : '100%'};
`}
`;
ItemContainer.propTypes = {
width: PropTypes.number.isRequired,
};
export const MiniCardButton = styled.button(
({ width, height, theme, isSelected }) => `
display: flex;
align-items: center;
justify-content: center;
width: ${width}px;
height: ${height}px;
overflow: hidden;
padding: 0;
background-color: transparent;
border: ${
isSelected ? theme.borders.bluePrimary : theme.borders.transparent
};
border-width: 2px;
${KEYBOARD_USER_SELECTOR} &:focus {
border-radius: 0;
border-color: ${rgba(theme.colors.bluePrimary, 0.5)};
outline: none;
}
`
);
MiniCardButton.propTypes = {
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
isSelected: PropTypes.bool,
};
export const MiniCard = styled.div(
({ width, theme }) => `
position: relative;
width: ${width}px;
cursor: pointer;
border: ${theme.borders.gray75};
`
);
MiniCard.propTypes = {
width: PropTypes.number.isRequired,
containerHeight: PropTypes.number.isRequired,
};
export const ActiveCard = styled.div(
({ width, theme }) => `
position: relative;
box-sizing: border-box;
width: ${width}px;
border: ${theme.storyPreview.border};
height: ${containerHeight}px;
border: ${theme.borders.gray75};
box-shadow: ${theme.storyPreview.shadow};
`
);
ActiveCard.propTypes = {
width: PropTypes.number.isRequired,
containerHeight: PropTypes.number.isRequired,
};
|
JavaScript
| 0 |
@@ -2580,56 +2580,8 @@
ed,%0A
- containerHeight: PropTypes.number.isRequired,%0A
%7D;%0A%0A
@@ -2723,84 +2723,8 @@
px;%0A
- border: $%7Btheme.storyPreview.border%7D;%0A height: $%7BcontainerHeight%7Dpx;%0A
@@ -2826,32 +2826,32 @@
d.propTypes = %7B%0A
+
width: PropTyp
@@ -2876,55 +2876,7 @@
ed,%0A
- containerHeight: PropTypes.number.isRequired,%0A
%7D;%0A
|
5e358b72a64347dcb82003ec6579612b86a2a960
|
optimize onTouchTap to ArrowStepItem
|
src/_ArrowStepItem/ArrowStepItem.js
|
src/_ArrowStepItem/ArrowStepItem.js
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import './ArrowStepItem.css';
export default class ArrowStepItem extends Component {
constructor(props) {
super(props);
this.touchTapHandler = this::this.touchTapHandler;
}
touchTapHandler(e) {
e.preventDefault();
setTimeout(() => {
const {activatedStep, finishedStep, index, onTouchTap} = this.props;
activatedStep !== index && finishedStep >= index && onTouchTap && onTouchTap(index, e);
}, 0);
}
render() {
const {className, style, activatedStep, finishedStep, index, value, isFirst, isLast} = this.props,
itemClassName = (isFirst ? ' first' : '') + (isLast ? ' last' : '')
+ (activatedStep == index ? ' activated' : (finishedStep >= index ? ' finished' : ''))
+ (className ? ' ' + className : '');
return (
<div className={'arrow-step-item' + itemClassName}
style={style}
onTouchTap={this.touchTapHandler}>
<div className="arrow-step-item-content">
<div className="number">
{index + 1}
</div>
<div className="title">
{value.title}
</div>
</div>
{
isFirst ?
null
:
(
<div className="triangle-wrapper triangle-wrapper-left">
<div className={`triangle-top
${activatedStep == index ? ' activated' : (finishedStep >= index ? ' finished' : '')}`}>
</div>
<div className={`triangle-bottom
${activatedStep == index ? ' activated' : (finishedStep >= index ? ' finished' : '')}`}>
</div>
</div>
)
}
{
isLast ?
null
:
(
<div className="triangle-wrapper triangle-wrapper-right">
<div className={`triangle-middle
${activatedStep == index ? ' activated' : (finishedStep >= index ? ' finished' : '')}`}>
</div>
</div>
)
}
</div>
);
}
};
ArrowStepItem.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
index: PropTypes.number,
activatedStep: PropTypes.number,
finishedStep: PropTypes.number,
value: PropTypes.object,
isFirst: PropTypes.bool,
isLast: PropTypes.bool,
onTouchTap: PropTypes.func
};
ArrowStepItem.defaultProps = {
className: '',
style: null,
index: 0,
activatedStep: 0,
finishedStep: 0,
value: null,
isFirst: true,
isLast: true
};
|
JavaScript
| 0 |
@@ -330,39 +330,8 @@
();%0A
- setTimeout(() =%3E %7B%0A
@@ -403,20 +403,16 @@
.props;%0A
-
@@ -503,23 +503,8 @@
e);%0A
- %7D, 0);%0A
|
0fd1f7eecb6093edfa18342de989ab0c774f4096
|
Use 'key' prop instead of autoIncrement on areas and student stores
|
app/helpers/db.js
|
app/helpers/db.js
|
import treo from 'treo'
let schema = treo.schema()
.version(1)
.addStore('courses', { key: 'clbid' })
.addIndex('clbid', 'clbid', { unique: true })
.addIndex('credits', 'credits')
.addIndex('crsid', 'crsid')
.addIndex('dept', 'dept')
.addIndex('depts', 'depts', { multi: true })
.addIndex('deptnum', 'deptnum')
.addIndex('desc', 'desc')
.addIndex('gereqs', 'gereqs', { multi: true })
.addIndex('groupid', 'groupid')
.addIndex('grouptype', 'grouptype')
.addIndex('halfcredit', 'halfcredit')
.addIndex('level', 'level')
.addIndex('name', 'name')
.addIndex('notes', 'notes')
.addIndex('num', 'num')
.addIndex('pf', 'pf')
.addIndex('places', 'places', { multi: true })
.addIndex('profs', 'profs', { multi: true })
.addIndex('sect', 'sect')
.addIndex('sem', 'sem')
.addIndex('term', 'term')
.addIndex('times', 'times', { multi: true })
.addIndex('title', 'title')
.addIndex('type', 'type')
.addIndex('year', 'year')
.addIndex('sourcePath', 'sourcePath')
.addStore('areas', { increment: true })
.addIndex('type', 'type', { multi: true })
.addIndex('sourcePath', 'sourcePath')
.addStore('students', { increment: true })
import treoPromise from 'treo/plugins/treo-promise'
import queryTreoDatabase from './queryTreoDatabase'
let db = treo('gobbldygook', schema)
.use(queryTreoDatabase())
.use(treoPromise())
window.eraseDatabase = () => {
window.database.drop().then(() => {
console.log('Database dropped')
localStorage.clear()
console.log('localStorage cleared')
})
}
window.database = db
export default db
|
JavaScript
| 0 |
@@ -1043,39 +1043,41 @@
('areas', %7B
-increment: true
+key: 'sourcePath'
%7D)%0A%09%09%09.addI
@@ -1185,23 +1185,17 @@
, %7B
-increment: true
+key: 'id'
%7D)%0A
|
c577e3a386bf5ce0dd5a8785a284546ccff33fdc
|
update Yeoman copy scripts
|
app/index.js
|
app/index.js
|
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var updateNotifier = require('update-notifier');
var pkg = require('../package.json');
var KickoffGenerator = yeoman.generators.Base.extend({
init: function () {
this.on('end', function () {
if (!this.options['skip-install']) {
this.installDependencies({ skipInstall: this.options['skip-install'],
callback: function () {
// Emit a new event - dependencies installed
this.emit('dependenciesInstalled');
}.bind(this) });
}
});
// Now you can bind to the dependencies installed event
this.on('dependenciesInstalled', function () {
this.spawnCommand('grunt', ['start']);
});
},
askFor: function () {
var done = this.async();
// Checks for available update and returns an instance
var notifier = updateNotifier({
packageName: pkg.name,
packageVersion: pkg.version,
updateCheckInterval: 1000 * 60 // Every hour
});
var kickoffWelcome = chalk.magenta('\n ## ## ###### #### ## ## #### ###### ######\n ## ## ## ## ## ## ## ## ## ## ##\n #### ## ## #### ## ## #### ####\n ## ## ## ## ## ## ## ## ## ## ##\n ## ## ###### #### ## ## #### ## ##') + '\n\n A Yeoman generator for the Kickoff front-end framework\n\n Created by ' + chalk.yellow('@MrMartineau') + ' & ' + chalk.green('@AshNolan_') + '\n ' + chalk.cyan('http://tmwagency.github.io/kickoff/') + '\n';
// Have Yeoman greet the user.
this.log(kickoffWelcome);
if (notifier.update) {
// Check for npm package update and print message if needed
var updateMessage = chalk.yellow(' ┌────────────────────────────────────────────────┐\n │') + ' Update available: ' + chalk.green(notifier.update.latest) + chalk.gray(' (current: ' + pkg.version + ')') + ' '+ chalk.yellow('│\n │') + ' Run ' + chalk.cyan('npm update -g ' + pkg.name) + ' to update. ' + chalk.yellow('│\n └────────────────────────────────────────────────┘\n');
this.log(updateMessage);
}
var prompts = [
{
name: 'projectName',
message: 'Project name',
default: 'Kickoff'
},
{
name: 'devNames',
message: 'What are the project developer\'s names?',
default: 'The Kickoff Team'
},
{
name: 'jsNamespace',
message: 'Choose your javascript namespace',
default: 'KO'
},
{
name: 'statix',
type: 'confirm',
message: 'Do you want to use Kickoff Statix?',
default: false
},
{
name: 'browserify',
type: 'confirm',
message: 'Do you want to use Browserify?',
default: false
},
{
name: 'jsLibs',
type: 'checkbox',
message: 'Which Javascript libraries would you like to use?',
choices: [
{
name: 'jQuery 1.x - only choose one jQuery version',
value: 'jquery1'
},
{
name: 'jQuery 2.x - only choose one jQuery version',
value: 'jquery2'
},
{
name: 'trak.js - Universal event tracking API',
value: 'trak'
},
{
name: 'Swiftclick - Eliminates the 300ms click event delay on touch devices',
value: 'swiftclick'
},
{
name: 'Cookies - JavaScript Client-Side Cookie Manipulation Library',
value: 'cookies'
}
]
},
{
name: 'shims',
type: 'confirm',
message: 'Do you want to include the default Javascript shims? (These are generated by the \'grunt shimly\' command',
default: false
}
];
this.prompt(prompts, function (props) {
for (var key in props) {
this[key] = props[key];
}
done();
}.bind(this));
},
app: function () {
this.template('_index.html', 'index.html');
this.template('_docs/_styleguide.html', '_docs/styleguide.html');
this.template('_docs/_index.html', '_docs/index.html');
this.directory('scss', 'scss');
// Grunt configs
this.template('_grunt-configs/_css.js', '_grunt-configs/css.js');
this.template('_grunt-configs/_icons.js', '_grunt-configs/icons.js');
this.template('_grunt-configs/_javascript.js', '_grunt-configs/javascript.js');
this.template('_grunt-configs/_server.js', '_grunt-configs/server.js');
this.template('_grunt-configs/_utilities.js', '_grunt-configs/utilities.js');
this.template('_grunt-configs/_watch.js', '_grunt-configs/watch.js');
this.template('js/_script.js', 'js/script.js');
this.directory('js/libs', 'js/libs');
this.directory('js/dist', 'js/dist');
this.template('js/helpers/_helpers.js', 'js/helpers/helpers.js');
this.copy('js/helpers/console.js', 'js/helpers/console.js');
this.copy('js/helpers/log.js', 'js/helpers/log.js');
this.copy('js/helpers/shims.js', 'js/helpers/shims.js');
this.template('_Gruntfile.js', 'Gruntfile.js');
this.template('_package.json', 'package.json');
this.template('_bower.json', 'bower.json');
this.template('_humans.txt', 'humans.txt');
this.template('_jshintrc', '.jshintrc');
this.copy('editorconfig', '.editorconfig');
this.copy('gitignore', '.gitignore');
this.copy('bowerrc', '.bowerrc');
this.copy('jscs.json', '.jscs.json');
if (this.browserify) {
this.directory('js/modules', 'js/modules');
}
if (this.statix) {
this.directory('statix/src', 'statix/src');
this.directory('statix/dist', 'statix/dist');
this.template('statix/src/templates/includes/_html_start.hbs', 'statix/src/templates/includes/html_start.hbs');
}
}
});
module.exports = KickoffGenerator;
|
JavaScript
| 0 |
@@ -4450,24 +4450,96 @@
/watch.js');
+%0A%09%09this.template('_grunt-configs/_tests.js', '_grunt-configs/tests.js');
%0A%0A%09%09this.tem
@@ -5297,24 +5297,72 @@
jscs.json');
+%0A%09%09this.copy('scss-lint.yml', '.scss-lint.yml');
%0A%0A%09%09if (this
|
7ac2d911f5d5d99a8875b5854581c6de64fc3612
|
remove unused block
|
app/login.js
|
app/login.js
|
// @flow
/*jshint esversion: 6 */
/*jslint node: true */
"use strict";
const electron = require("electron");
const {ipcRenderer} = electron;
// FIXME: Unused variables
const minLoginLen = 4;
const minPasswdLen = 8;
/*
function checkLoginInfo() {
if (document.getElementById("username").value.length >= minLoginLen && document.getElementById("pswd").value.length >= minPasswdLen)
{
document.getElementById("btSubmit").disabled = false;
} else {
document.getElementById("btSubmit").disabled = true;
}
}*/
function doLogin() {
ipcRenderer.send("verify-login-info", document.getElementById("username").value, document.getElementById("pswd").value);
}
ipcRenderer.on("verify-login-response", function (event, resp) {
let data = JSON.parse(resp);
if (data.response === "OK") {
location.href = "./wallet.html";
console.log("Login was successful - redirecting to wallet.html");
} else {
document.getElementById("login_pswd_info").style.display = "block";
}
});
|
JavaScript
| 0.000003 |
@@ -140,404 +140,8 @@
n;%0A%0A
-// FIXME: Unused variables%0Aconst minLoginLen = 4;%0Aconst minPasswdLen = 8;%0A%0A/*%0Afunction checkLoginInfo() %7B%0A if (document.getElementById(%22username%22).value.length %3E= minLoginLen && document.getElementById(%22pswd%22).value.length %3E= minPasswdLen)%0A %7B%0A document.getElementById(%22btSubmit%22).disabled = false;%0A %7D else %7B%0A document.getElementById(%22btSubmit%22).disabled = true;%0A %7D%0A%7D*/%0A%0A
func
|
4663da6c3994ae6e23ac993eac23dc2896753371
|
revert test
|
src/component/ResponsiveContainer.js
|
src/component/ResponsiveContainer.js
|
/**
* @fileOverview Wrapper component to make charts adapt to the size of parent * DOM
*/
import React, { PropTypes, Component } from 'react';
import ReactResizeDetector from 'react-resize-detector';
import _ from 'lodash';
import { isPercent } from '../util/DataUtils';
import { warn } from '../util/LogUtils';
class ResponsiveContainer extends Component {
static displayName = 'ResponsiveContainer';
static propTypes = {
aspect: PropTypes.number,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
minHeight: PropTypes.number,
minWidth: PropTypes.number,
maxHeight: PropTypes.number,
children: PropTypes.node.isRequired,
debounce: PropTypes.number,
};
static defaultProps = {
width: '100%',
height: '100%',
debounce: 0,
};
constructor(props) {
super(props);
this.state = {
containerWidth: -1,
containerHeight: -1,
};
this.handleResize = props.debounce > 0 ?
_.debounce(this.updateDimensionsImmediate, props.debounce) :
this.updateDimensionsImmediate;
}
/* eslint-disable react/no-did-mount-set-state */
componentDidMount() {
this.mounted = true;
const size = this.getContainerSize();
if (size) {
this.setState(size);
}
}
componentWillUnmount() {
this.mounted = false;
}
getContainerSize() {
if (!this.container) { return null; }
return {
containerWidth: this.container.clientWidth,
containerHeight: this.container.clientHeight,
};
}
updateDimensionsImmediate = () => {
if (!this.mounted) { return; }
const newSize = this.getContainerSize();
if (newSize) {
const { containerWidth: oldWidth, containerHeight: oldHeight } = this.state;
const { containerWidth, containerHeight } = newSize;
if (containerWidth !== oldWidth || containerHeight !== oldHeight) {
this.setState({ containerWidth, containerHeight });
}
}
};
renderChart() {
const { containerWidth, containerHeight } = this.state;
if (containerWidth < 0 || containerHeight < 0) { return null; }
const { aspect, width, height, minWidth, minHeight, children } = this.props;
warn(isPercent(width) || isPercent(height),
`The width(%s) and height(%s) are both fixed numbers,
maybe you don't need to use a ResponsiveContainer.`,
width, height
);
warn(!aspect || aspect > 0,
'The aspect(%s) must be greater than zero.',
aspect);
const calculatedWidth = isPercent(width) ? containerWidth : width;
let calculatedHeight = isPercent(height) ? containerHeight : height;
if (aspect && aspect > 0) {
// Preserve the desired aspect ratio
calculatedHeight = calculatedWidth / aspect;
// if maxHeight is set, overwrite if calculatedHeight is greater than maxHeight
if(maxHeight && (calculatedHeight > maxHeight)) calculatedHeight = maxHeight;
}
warn(calculatedWidth > 0 && calculatedHeight > 0,
`The width(%s) and height(%s) of chart should be greater than 0,
please check the style of container, or the props width(%s) and height(%s),
or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
height and width.`,
calculatedWidth, calculatedHeight, width, height, minWidth, minHeight, aspect
);
return React.cloneElement(children, {
width: calculatedWidth,
height: calculatedHeight,
});
}
render() {
const { minWidth, minHeight, width, height, maxHeight } = this.props;
const style = { width, height, minWidth, minHeight, maxHeight };
return (
<div
className="recharts-responsive-container"
style={style}
ref={(node) => { this.container = node; }}
>
{this.renderChart()}
<ReactResizeDetector handleWidth handleHeight onResize={this.handleResize} />
</div>
);
}
}
export default ResponsiveContainer;
|
JavaScript
| 0.000001 |
@@ -663,41 +663,8 @@
er,%0A
- maxHeight: PropTypes.number,%0A
@@ -2796,178 +2796,8 @@
ct;%0A
- // if maxHeight is set, overwrite if calculatedHeight is greater than maxHeight%0A if(maxHeight && (calculatedHeight %3E maxHeight)) calculatedHeight = maxHeight;%0A
@@ -3382,27 +3382,16 @@
, height
-, maxHeight
%7D = thi
@@ -3457,19 +3457,8 @@
ight
-, maxHeight
%7D;%0A
|
d624619cf8c8bbf93f44cbc11ec7790808ca98b7
|
Make sure to add trailing slash to Sandstorm host specified by query parameter.
|
app/lib/routes.js
|
app/lib/routes.js
|
// GLOBAL SUBSCRIPTIONS
FlowRouter.subscriptions = function() {
this.register('messages', Meteor.subscribe('messages'));
};
// ROUTES
// Pre render triggers
FlowRouter.triggers.enter([getSandstormServer]);
FlowRouter.triggers.enter([onlyAdmin.bind(this, 'login')], {
only: ['review', 'admin']
});
FlowRouter.triggers.enter([redirectOnSmallDevice.bind(this, null)], {
only: ['review', 'admin']
});
FlowRouter.triggers.exit([hideTooltips, history]);
function hideTooltips() {
Tooltips && Tooltips.hide();
}
function history(context) {
if (context.route.name !== 'notFound') {
if (FlowRouter.history) FlowRouter.history.push(context.path);
else FlowRouter.history = [context.path];
FlowRouter.history = FlowRouter.history.splice(FlowRouter.history.length - 2, 2);
}
}
// Utility function to redirect (either to App Market home or a given route)
// if there is no logged in user
function onlyLoggedIn(route) {
if (!Meteor.userId()) FlowRouter.go(route || 'appMarket');
}
// Utility function to redirect (either to App Market home or a given route)
// if the user is not an admin
function onlyAdmin(route) {
if (!Roles.userIsInRole(Meteor.userId(), 'admin')) FlowRouter.go(route || 'appMarket');
}
// Utility function to redirect (either to App Market home or a given route)
// if the device is not a desktop
function redirectOnSmallDevice(route) {
if (!Meteor.Device.isDesktop()) FlowRouter.go(route || 'appMarket');
}
// We have to do this in each route at present, as Flow Router doesn't
// pass query params to middleware (yet)
function getSandstormServer(context) {
if (context.queryParams.host) {
AppMarket.sandstormHost = context.queryParams.host;
amplify.store('sandstormHost', context.queryParams.host);
var allHosts = amplify.store('sandstormHostHistory') || [];
allHosts = _.unique(allHosts.concat(context.queryParams.host));
amplify.store('sandstormHostHistory', allHosts);
}
}
// Subscription callback which checks it the supplied app exists when the
// sub is ready, and redirects to a not found page if it isn't
function checkAppExists() {
Meteor.defer(function() {
var app = Apps.find(FlowRouter.getParam('appId')).count();
if (!app) FlowRouter.go('notFound', {object: 'app'});
});
}
function checkAuthorExists() {
Meteor.defer(function() {
var authorApps = Apps.find({authorName: FlowRouter.getParam('authorName')}).count();
if (!author) FlowRouter.go('notFound', {object: 'author'});
});
}
FlowRouter.route('/login', {
name: 'login',
action: function(params, queryParams) {
FlowLayout.render('MasterLayout', {mainSection: 'Login'});
}
});
FlowRouter.route('/not-found/:object', {
name: 'notFound',
action: function(params, queryParams) {
FlowLayout.render('MasterLayout', {mainSection: 'NotFound'});
}
});
FlowRouter.route('/app/:appId', {
name: 'singleApp',
action: function(params, queryParams) {
FlowLayout.render('MasterLayout', {mainSection: 'SingleApp'});
}
});
FlowRouter.route('/', {
name: 'appMarket',
action: function(params, queryParams) {
FlowLayout.render('MasterLayout', {mainSection: 'Home'});
}
});
FlowRouter.route('/author/:authorName', {
name: 'appMarketAuthor',
action: function(params, queryParams) {
FlowLayout.render('MasterLayout', {mainSection: 'AppsByAuthor'});
}
});
FlowRouter.route('/genre/:genre', {
name: 'appMarketGenre',
action: function(params, queryParams) {
if (params.genre !== s.capitalize(params.genre))
FlowRouter.setParams({genre: s.capitalize(params.genre)});
if (params.genre === 'Popular') FlowLayout.render('MasterLayout', {mainSection: 'Popular'});
else FlowLayout.render('MasterLayout', {mainSection: 'Genre', genre: FlowRouter.getParam('genre')});
}
});
FlowRouter.route('/search', {
name: 'appSearch',
action: function(params, queryParams) {
FlowLayout.render('MasterLayout', {mainSection: 'Search'});
}
});
FlowRouter.route('/installed', {
name: 'installedApps',
action: function(params, queryParams) {
var user = Meteor.users.findOne(Meteor.userId());
FlowRouter.current().firstVisit = (typeof(user && user.autoupdateApps) === 'undefined');
FlowLayout.render('MasterLayout', {mainSection: 'InstalledApps'});
}
});
FlowRouter.route('/apps-by-me', {
name: 'appsByMe',
foo: 'bar',
action: function(params, queryParams) {
FlowLayout.render('MasterLayout', {mainSection: 'AppsByMe'});
}
});
FlowRouter.route('/upload', {
name: 'upload',
action: function(params, queryParams) {
FlowLayout.render('MasterLayout', {mainSection: 'Upload'});
}
});
FlowRouter.notFound = {
action: function() {
Meteor.defer(function() {FlowRouter.go('notFound', {object: 'page'});});
}
};
FlowRouter.routeCategories = {
'login': 'login',
'singleApp': 'appMarket',
'appMarket': 'appMarket',
'appMarketAuthor': 'appMarket',
'appMarketGenre': 'appMarket',
'appSearch': 'appMarket',
'installedApps': 'installedApps',
'appsByMe': 'appsByMe',
'edit': 'upload',
'upload': 'upload',
'review': 'admin',
'admin': 'admin'
};
|
JavaScript
| 0 |
@@ -1638,28 +1638,13 @@
-AppMarket.sandstormH
+var h
ost
@@ -1671,16 +1671,102 @@
s.host;%0A
+ if (host.slice(-1) != '/') host = host + '/';%0A AppMarket.sandstormHost = host;%0A
ampl
@@ -1792,36 +1792,16 @@
mHost',
-context.queryParams.
host);%0A
@@ -1863,16 +1863,16 @@
%7C%7C %5B%5D;%0A
+
allH
@@ -1903,36 +1903,16 @@
.concat(
-context.queryParams.
host));%0A
|
34d8bb59e7fd1ca513c6a996ecb74e580e43f993
|
Clean way to mapDispatchtoprops
|
src/components/course/CoursesPage.js
|
src/components/course/CoursesPage.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import {connect} from 'react-redux';
import * as courseActions from '../../actions/courseActions';
class CoursesPage extends React.Component {
constructor(props, context){
super(props, context);
this.state = {
course: {title: ""}
};
this.onTitleChange = this.onTitleChange.bind(this);
this.onClickSave = this.onClickSave.bind(this);
}
onTitleChange(event) {
const course = this.state.course;
course.title = event.target.value;
this.setState({course: course});
}
onClickSave() {
// alert(`Saving ${this.state.course.title}`);
this.props.dispatch(courseActions.createCourse(this.state.course));// NOT GOOD WAY
}
courseRow(course, index) {
return (
<div key={index}> {course.title} </div>
);
}
render() {
return (
<div className="jumbotron">
<h1>Courses</h1>
{this.props.courses.map(this.courseRow)}
<h2>Add Course</h2>
<input
type="text"
onChange={this.onTitleChange}
value={this.state.course.title}
/>
<input
type="submit"
value="Save"
onClick={this.onClickSave}
/>
</div>
);
}
}
CoursesPage.propTypes = {
dispatch: PropTypes.func.isRequired,
courses: PropTypes.array.isRequired
};
function mapStateToProps(state, ownProps) {
return{
courses: state.courses //reducer
};
}
export default connect(mapStateToProps)(CoursesPage);
// export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage); // Ommiting mapDispatchToProps inject dispatch to props
|
JavaScript
| 0 |
@@ -681,24 +681,27 @@
itle%7D%60);%0A
+ //
this.props.
@@ -772,16 +772,75 @@
OOD WAY%0A
+ this.props.createCourse(this.state.course);// GOOD WAY%0A
%7D%0A%0A c
@@ -1393,16 +1393,19 @@
es = %7B%0A
+ //
dispatc
@@ -1437,204 +1437,422 @@
red,
-%0A courses: PropTypes.array.isRequired%0A%7D;%0A%0Afunction mapStateToProps(state, ownProps) %7B%0A return%7B%0A courses: state.courses //reducer%0A %7D;%0A%7D%0A%0A%0Aexport default connect(mapStateToProps)(CoursesPage);
+ // required when Ommiting mapDispatchToProps%0A courses: PropTypes.array.isRequired,%0A createCourse: PropTypes.func.isRequired%0A%7D;%0A%0Afunction mapStateToProps(state, ownProps) %7B%0A return%7B%0A courses: state.courses //reducer%0A %7D;%0A%7D%0A%0Afunction mapDispatchToProps(dispatch) %7B%0A // return bindActionCreators(%7Breducer%7D, dispatch)%0A return %7B%0A createCourse: course =%3E dispatch(courseActions.createCourse(course))%0A %7D;%0A%7D%0A%0A
%0A//
@@ -1893,28 +1893,8 @@
rops
-, mapDispatchToProps
)(Co
@@ -1957,12 +1957,86 @@
ch to props%0A
+export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);%0A
|
52fd50d94071ce00ac1e5002af3aaca8b554a427
|
Fix language card component (#27)
|
src/components/languageCard/index.js
|
src/components/languageCard/index.js
|
import React from "react"
import './style.css';
import {Link} from "gatsby";
import _capitalize from "lodash/capitalize"
import Image from "../../layout/image"
const LanguageCard = ({ data }) => {
return (
<div className="container">
<div className="row">
{data.map(item => {
return (
<div className="card">
<Link key={item.node.id} to={`/docs/${item.node.id}/`}>
<div className="card-body">
<div className="card-image">
<Image path={`flags/${item.node.slug}.png`} className="card-title rounded-circle w-100px" alt={item.node.slug} />
</div>
<div className="card-text">
<span>{_capitalize(item.node.name)} ({item.node.id})</span>
</div>
{item.node.authors && (
item.node.authors.map(author => {
return (
<React.Fragment key={author.id}>
{author.github_avatar && <img src={author.github_avatar} className="author-avatar rounded-circle" alt={author.name}/>}
</React.Fragment>
)
})
)}
</div>
</Link>
</div>
)
})}
</div>
</div>
)
}
export default LanguageCard;
|
JavaScript
| 0 |
@@ -317,32 +317,51 @@
%3Cdiv
+ key=%7Bitem.node.id%7D
className=%22card
@@ -382,35 +382,16 @@
%3CLink
- key=%7Bitem.node.id%7D
to=%7B%60/d
|
01da8696967b8b98a7731e3710675095839a97c9
|
Fix choice descriptors edge case
|
src/components/mixins/descriptors.js
|
src/components/mixins/descriptors.js
|
/*
* Set of function to facilitate the display and edition of metadata in
* entity lists.
*/
import { mapGetters } from 'vuex'
export const descriptorMixin = {
created () {
},
mounted () {
},
beforeDestroy () {
},
computed: {
...mapGetters([
'selectedAssets',
'selectedShots',
'selectedEdits'
]),
descriptorLength () {
if (this.shotMetadataDescriptors.length !== undefined) {
return this.shotMetadataDescriptors.length
}
if (this.assetMetadataDescriptors.length !== undefined) {
return this.assetMetadataDescriptors.length
}
if (this.editMetadataDescriptors.length !== undefined) {
return this.editMetadataDescriptors.length
}
return 0
}
},
methods: {
onAddMetadataClicked () {
this.$emit('add-metadata')
},
emitMetadataChanged (entry, descriptor, value) {
this.$emit('metadata-changed', {
entry, descriptor, value
})
},
onMetadataFieldChanged (entry, descriptor, event) {
if (this.selectedShots.has(entry.id)) {
// if the line is selected, also modify the cells of the other selected lines
this.selectedShots.forEach((shot, _) => {
this.emitMetadataChanged(shot, descriptor, event.target.value)
})
} else if (this.selectedAssets.has(entry.id)) {
// if the line is selected, also modify the cells of the other selected lines
this.selectedAssets.forEach((asset, _) => {
this.emitMetadataChanged(asset, descriptor, event.target.value)
})
} else if (this.selectedEdits.has(entry.id)) {
// if the line is selected, also modify the cells of the other selected lines
this.selectedEdits.forEach((edit, _) => {
this.emitMetadataChanged(edit, descriptor, event.target.value)
})
} else {
this.emitMetadataChanged(entry, descriptor, event.target.value)
}
},
onMetadataChecklistChanged (entry, descriptor, option, event) {
var values = this.getMetadataChecklistValues(descriptor, entry)
values[option] = event.target.checked
event.target.value = JSON.stringify(values)
this.onMetadataFieldChanged(entry, descriptor, event)
},
onSortByMetadataClicked () {
const columnId = this.lastMetadaDataHeaderMenuDisplayed
const column =
this.currentProduction.descriptors.find(d => d.id === columnId)
this.$emit('change-sort', {
type: 'metadata',
column: column.field_name,
name: column.name
})
this.showMetadataHeaderMenu()
},
onEditMetadataClicked () {
this.$emit('edit-metadata', this.lastMetadaDataHeaderMenuDisplayed)
this.showMetadataHeaderMenu()
},
onDeleteMetadataClicked () {
this.$emit('delete-metadata', this.lastMetadaDataHeaderMenuDisplayed)
this.showMetadataHeaderMenu()
},
showMetadataHeaderMenu (columnId, event) {
const headerMenuEl = this.$refs.headerMetadataMenu.$el
if (headerMenuEl.className === 'header-menu') {
headerMenuEl.className = 'header-menu hidden'
} else {
headerMenuEl.className = 'header-menu'
const headerElement = event.srcElement.parentNode.parentNode
const headerBox = headerElement.getBoundingClientRect()
const left = headerBox.left - 3
const top = headerBox.bottom + 11
const width = Math.max(100, headerBox.width - 1)
headerMenuEl.style.left = left + 'px'
headerMenuEl.style.top = top + 'px'
headerMenuEl.style.width = width + 'px'
}
this.lastMetadaDataHeaderMenuDisplayed = columnId
},
getDescriptorChoicesOptions (descriptor) {
const values = descriptor.choices.map(c => ({ label: c, value: c }))
return [{ label: '', value: '' }, ...values]
},
getMetadataFieldValue (descriptor, entity) {
return entity.data ? entity.data[descriptor.field_name] || '' : ''
},
getDescriptorChecklistValues (descriptor) {
const values = descriptor.choices.reduce(
function (result, c) {
if (c.startsWith('[x] ')) {
result.push({ text: c.slice(4), checked: true })
} else if (c.startsWith('[ ] ')) {
result.push({ text: c.slice(4), checked: false })
}
return result
},
[]
)
return values.length === descriptor.choices.length ? values : []
},
getMetadataChecklistValues (descriptor, entity) {
var values = {}
try {
values = JSON.parse(this.getMetadataFieldValue(descriptor, entity))
} catch {
values = {}
}
this.getDescriptorChecklistValues(descriptor).forEach(
function (option) {
if (!(option.text in values)) {
values[option.text] = option.checked
}
}
)
return values
},
/*
* Determine what is the next input by building a reference key and
* retrieve it from the main reference array.
* The next input is determined from the arrow key used. If the key is
* not an arrow nothing is done.
*/
keyMetadataNavigation (listWidth, listHeight, i, j, key) {
if (key === 'ArrowDown') {
i = i + 1
if (i >= listHeight) i = 0
} else if (key === 'ArrowLeft') {
j = j - 1
if (j < 0) j = listWidth - 1
} else if (key === 'ArrowRight') {
j = j + 1
if (j >= listWidth) j = 0
} else if (key === 'ArrowUp') {
i = i - 1
if (i < 0) i = listHeight - 1
} else {
return
}
const ref = `editor-${i}-${j}`
const input = this.$refs[ref][0]
input.focus()
}
}
}
|
JavaScript
| 0.000011 |
@@ -4094,55 +4094,58 @@
uce(
-%0A function (result, c) %7B%0A if (c
+(result, choice) =%3E %7B%0A if (choice && choice
.sta
@@ -4155,34 +4155,32 @@
With('%5Bx%5D ')) %7B%0A
-
result
@@ -4186,32 +4186,37 @@
t.push(%7B text: c
+hoice
.slice(4), check
@@ -4231,26 +4231,24 @@
%7D)%0A
-
%7D else if (c
@@ -4247,16 +4247,31 @@
se if (c
+hoice && choice
.startsW
@@ -4287,34 +4287,32 @@
')) %7B%0A
-
result.push(%7B te
@@ -4316,16 +4316,21 @@
text: c
+hoice
.slice(4
@@ -4354,30 +4354,26 @@
%7D)%0A
- %7D%0A
+%7D%0A
retu
@@ -4388,18 +4388,16 @@
t%0A
-
%7D,%0A
@@ -4401,19 +4401,10 @@
- %5B%5D%0A
+%5B%5D
)%0A
|
13cbc74e735b93c937406e8a1f2a19940d46fb39
|
Remove extraneous merge
|
src/components/util/resolve-cells.js
|
src/components/util/resolve-cells.js
|
import React, { Children } from "react";
import omit from "lodash.omit";
import merge from "lodash.merge";
import resolveCellDefaults from "./resolve-cell-defaults";
import resolveColumnCounts from "./resolve-column-counts";
import resolveCellStyles from "./resolve-cell-styles";
const resolveCells = (props) => {
// Resolve the final style defaults for each cell
const childProps = omit(props, ["children", "style"]);
const childrenWithDefaults = Children.map(
props.children, (child) => {
return React.cloneElement(
child, resolveCellDefaults(
merge({}, childProps, child.props)
)
);
}
);
// Add column counts to each cell's props
const childrenWithColumnCounts = resolveColumnCounts({
children: childrenWithDefaults,
breakpoints: props.breakpoints
});
// Resolve the final cell styles
return Children.map(childrenWithColumnCounts, (child) => {
return React.cloneElement(child, merge({}, {
style: resolveCellStyles(child.props)
}));
});
};
export default resolveCells;
|
JavaScript
| 0.00512 |
@@ -951,26 +951,16 @@
t(child,
- merge(%7B%7D,
%7B%0A
@@ -1004,17 +1004,16 @@
)%0A %7D)
-)
;%0A %7D);%0A
|
0aa1dd77df285a102b3a21781b4402d94400e0a0
|
Fix function header for parseQuery
|
src/api/utils/query-parser/index.js
|
src/api/utils/query-parser/index.js
|
class QueryParser {
/*
Tokenize the input query, and then parse the tokens into a
MongoDB-compatible format.
*/
static generateFilter (query, keyMap) {
let response = {}
// Split query into tokens
let q = QueryParser.tokenize(query)
// Start Mongo-DB compatible filter
let filter = { $and: [] }
// Parse each token
for (let i = 0; i < q.length; i++) {
filter.$and[i] = { $or: [] }
for (let j = 0; j < q[i].length; j++) {
q[i][j] = QueryParser.parseToken(q[i][j])
// Verify that the key is valid
if (!keyMap.hasOwnProperty(q[i][j].key)) {
let err = new Error(`Filter key '${q[i][j].key}' is not supported.`)
err.status = 400
response.error = err
return response
}
// Form Mongo-DB compatible filter from key type
filter.$and[i].$or[j] = {}
filter.$and[i].$or[j][keyMap[q[i][j].key].value] = keyMap[q[i][j].key].type(q[i][j].filter)
}
}
response.tokens = q
response.filter = filter
return response
}
/*
Split query into individual tokens.
*/
static tokenize (query) {
let pieces = query.split(' AND ')
for (let i = 0; i < pieces.length; i++) {
pieces[i] = pieces[i].trim().split(' OR ')
for (let j = 0; j < pieces[i].length; j++) {
pieces[i][j] = pieces[i][j].trim()
}
}
return pieces
}
/*
Parse token to retrieve key and filter information.
*/
static parseToken (token) {
let response = {}
response = {
raw: token,
key: token.slice(0, token.indexOf(':')).trim(),
filter: token.slice(token.indexOf(':') + 1).trim()
}
if (response.filter.indexOf('-') === 0) {
// Negation
response.filter = {
operator: '-',
value: response.filter.substring(1)
}
} else if (response.filter.indexOf('>=') === 0) {
response.filter = {
operator: '>=',
value: response.filter.substring(2)
}
} else if (response.filter.indexOf('<=') === 0) {
response.filter = {
operator: '<=',
value: response.filter.substring(2)
}
} else if (response.filter.indexOf('>') === 0) {
response.filter = {
operator: '>',
value: response.filter.substring(1)
}
} else if (response.filter.indexOf('<') === 0) {
response.filter = {
operator: '<',
value: response.filter.substring(1)
}
} else {
response.filter = {
operator: undefined,
value: response.filter
}
}
if (isNaN(parseFloat(response.filter.value)) || !isFinite(response.filter.value)) {
// Is not a number
response.filter.value = response.filter.value.substring(1,
response.filter.value.length - 1)
} else {
response.filter.value = parseFloat(response.filter.value)
}
return response
}
/*
Form the MongoDB-compatible filter for strings.
*/
static String (filter) {
if (filter.operator === '-') {
return {
$regex: '^((?!' + escapeRe(filter.value) + ').)*$',
$options: 'i'
}
}
return { $regex: '(?i).*' + escapeRe(filter.value) + '.*' }
}
/*
Form the MongoDB-compatible filter for numbers.
*/
static Number (filter) {
if (filter.operator === '>') {
return { $gt: filter.value }
} else if (filter.operator === '<') {
return { $lt: filter.value }
} else if (filter.operator === '>=') {
return { $gte: filter.value }
} else if (filter.operator === '<=') {
return { $lte: filter.value }
} else if (filter.operator === '-') {
return -filter.value
} else {
// Assume equality if no operator
return filter.value
}
}
/*
Form the MongoDB-compatible filter for dates.
*/
static Date (filter) {
}
/*
Form the MongoDB-compatible filter for times.
*/
static Time (filter) {
}
}
function escapeRe (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')
}
export default QueryParser
|
JavaScript
| 0.000005 |
@@ -131,22 +131,18 @@
tic
-generateFilt
+parseQu
er
+y
(qu
|
0c8e0921f60b9644f533885a3ac7f83e988ff7e3
|
Simplify radar navigation
|
src/app/patients/patients.config.js
|
src/app/patients/patients.config.js
|
(function() {
'use strict';
var app = angular.module('radar.patients');
app.config(['$stateProvider', function($stateProvider) {
$stateProvider.state('patients', {
url: '/patients',
templateUrl: 'app/patients/patient-list.html',
controller: ['$scope', '$controller', 'PatientListController', function($scope, $controller, PatientListController) {
$controller(PatientListController, {$scope: $scope});
}]
});
$stateProvider.state('patient', {
url: '/patients/:patientId',
abstract: true,
templateUrl: 'app/patients/patient-detail.html',
controller: 'PatientDetailController',
resolve: {
patient: ['$stateParams', 'store', function($stateParams, store) {
return store.findOne('patients', $stateParams.patientId);
}]
}
});
$stateProvider.state('patient.all', {
url: '/all',
templateUrl: 'app/patients/all.html'
});
}]);
// TODO refactor into state and cohort flag
app.constant('patientFeatures', {
ADDRESSES: {
text: 'Addresses',
state: 'patient.addresses({patientId: patient.id})'
},
ALIASES: {
text: 'Aliases',
state: 'patient.aliases({patientId: patient.id})'
},
DEMOGRAPHICS: {
text: 'Demographics',
state: 'patient.demographics({patientId: patient.id})'
},
DIAGNOSES: {
text: 'Diagnoses',
state: 'patient.diagnoses({patientId: patient.id, cohortId: cohort.id})'
},
DIALYSIS: {
text: 'Dialysis',
state: 'patient.dialysis({patientId: patient.id})'
},
COHORTS: {
text: 'Cohorts',
state: 'patient.cohorts({patientId: patient.id})'
},
COMORBIDITIES: {
text: 'Comorbidities',
state: 'patient.comorbidities({patientId: patient.id})'
},
FAMILY_HISTORY: {
text: 'Family History',
state: 'patient.familyHistory({patientId: patient.id, cohortId: cohort.id})'
},
GENETICS: {
text: 'Genetics',
state: 'patient.genetics({patientId: patient.id, cohortId: cohort.id})'
},
HOSPITALISATIONS: {
text: 'Hospitalisations',
state: 'patient.hospitalisations({patientId: patient.id})'
},
INS_CLINICAL_FEATURES: {
text: 'Clinical Features',
state: 'patient.insClinicalFeatures({patientId: patient.id})'
},
MEDICATIONS: {
text: 'Medications',
state: 'patient.medications({patientId: patient.id})'
},
META: {
text: 'Meta',
state: 'patient.meta({patientId: patient.id})'
},
NEPHRECTOMIES: {
text: 'Nephrectomies',
state: 'patients.nephrectomies({patientId: patient.id})'
},
NUMBERS: {
text: 'Numbers',
state: 'patient.numbers({patientId: patient.id})'
},
PATHOLOGY: {
text: 'Pathology',
state: 'patient.pathology({patientId: patient.id})'
},
PLASMAPHERESIS: {
text: 'Plasmapheresis',
state: 'patient.plasmapheresis({patientId: patient.id})'
},
RENAL_IMAGING: {
text: 'Renal Imaging',
state: 'patient.renalImaging({patientId: patient.id})'
},
RESULTS: {
text: 'Results',
state: 'patient.results.list({patientId: patient.id})'
},
SALT_WASTING_CLINICAL_FEATURES: {
text: 'Clinical Features',
state: 'patient.saltWastingClinicalFeatures({patientId: patient.id})'
},
TRANSPLANTS: {
text: 'Transplants',
state: 'patient.transplants({patientId: patient.id})'
},
UNITS: {
text: 'Units',
state: 'patient.units({patientId: patient.id})'
}
});
app.constant('standardPatientFeatures', [
'DEMOGRAPHICS',
'RESULTS',
'COMORBIDITIES',
'PATHOLOGY',
'MEDICATIONS',
'DIALYSIS',
'PLASMAPHERESIS',
'TRANSPLANTS',
'HOSPITALISATIONS',
'COHORTS',
'UNITS'
]);
})();
|
JavaScript
| 0.000001 |
@@ -3658,161 +3658,8 @@
S',%0A
- 'RESULTS',%0A 'COMORBIDITIES',%0A 'PATHOLOGY',%0A 'MEDICATIONS',%0A 'DIALYSIS',%0A 'PLASMAPHERESIS',%0A 'TRANSPLANTS',%0A 'HOSPITALISATIONS',%0A
|
db695471ac0461f36821dc2cac6ca8aa53947eed
|
clean up enable AP
|
app/public/app.js
|
app/public/app.js
|
"use strict";
/***
* Define the app and inject any modules we wish to
* refer to.
***/
var app = angular.module("RpiWifiConfig", []);
/******************************************************************************\
Function:
AppController
Dependencies:
...
Description:
Main application controller
\******************************************************************************/
app.controller("AppController", ["PiManager", "$scope", "$location",
function(PiManager, $scope, $location) {
// Scope variable declaration
$scope.scan_results = [];
$scope.selected_cell = null;
$scope.scan_running = false;
$scope.network_passcode = "";
$scope.show_passcode_entry_field = false;
$scope.show_success = false;
// Scope filter definitions
$scope.orderScanResults = function(cell) {
return parseInt(cell.signal_strength);
}
$scope.foo = function() { console.log("foo"); }
$scope.bar = function() { console.log("bar"); }
// Scope function definitions
$scope.rescan = function() {
$scope.scan_results = [];
$scope.selected_cell = null;
$scope.scan_running = true;
PiManager.rescan_wifi().then(function(response) {
console.log(response.data);
if (response.data.status == "SUCCESS") {
$scope.scan_results = response.data.scan_results;
}
$scope.scan_running = false;
});
}
$scope.change_selection = function(cell) {
$scope.network_passcode = "";
$scope.selected_cell = cell;
$scope.show_passcode_entry_field = (cell != null) ? true : false;
}
$scope.submit_selection = function() {
if (!$scope.selected_cell) return;
var wifi_info = {
wifi_ssid: $scope.selected_cell["ssid"],
wifi_passcode: $scope.network_passcode,
};
PiManager.enable_wifi(wifi_info).then(function(response) {
console.log(response.data);
if (response.data.status == "SUCCESS") {
console.log("AP Enabled - nothing left to do...");
$scope.show_passcode_entry_field = false;
$scope.show_success = true;
}
});
}
// Defer load the scanned results from the rpi
$scope.rescan();
}]
);
/*****************************************************************************\
Service to hit the rpi wifi config server
\*****************************************************************************/
app.service("PiManager", ["$http",
function($http) {
return {
rescan_wifi: function() {
return $http.get("/api/rescan_wifi");
},
enable_wifi: function(wifi_info) {
return $http.post("/api/enable_wifi", wifi_info);
}
};
}]
);
/*****************************************************************************\
Directive to show / hide / clear the password prompt
\*****************************************************************************/
app.directive("rwcPasswordEntry", function() {
return {
restrict: "E",
scope: {
visible: "=",
passcode: "=",
reset: "&",
submit: "&",
},
replace: true, // Use provided template (as opposed to static
// content that the modal scope might define in the
// DOM)
template: [
"<div class='rwc-password-entry-container' ng-class='{\"hide-me\": !visible}'>",
" <div class='box'>",
" <input type = 'password' placeholder = 'Passcode...' ng-model = 'passcode' />",
" <div class = 'btn btn-cancel' ng-click = 'reset(null)'>Cancel</div>",
" <div class = 'btn btn-ok' ng-click = 'submit()'>Submit</div>",
" </div>",
"</div>",
],
// Link function to bind modal to the app
link: function(scope, element, attributes) {
},
};
});
/*****************************************************************************\
Directive to show / hide / clear the password prompt
\*****************************************************************************/
app.directive("rwcSuccess", function() {
return {
restrict: "E",
scope: {
visible: "=",
submit: "&",
},
replace: true, // Use provided template (as opposed to static
// content that the modal scope might define in the
// DOM)
template: [
"<div class='rwc-success-container' ng-class='{\"hide-me\": !visible}'>",
" <div class='box'>",
" <h1 ng-model = 'success' >Looks Good, you can disconnect from JunctionBox</h1>",
" <div class = 'btn btn-ok' ng-click = 'submit()'>OK</div>",
" </div>",
"</div>"
].join("\n"),
// Link function to bind modal to the app
link: function(scope, element, attributes) {
},
};
});
|
JavaScript
| 0 |
@@ -4243,16 +4243,27 @@
%5D
+.join(%22%5Cn%22)
,%0A%0A
|
4a478a8ab1a46c64107e3b7aa300cca9a557f66d
|
Send an error if not logged in (GET /api/session/user)
|
app/routes/api.js
|
app/routes/api.js
|
// Api routes (/api)
/**
* Module dependencies
*/
const express = require('express');
const path = require('path');
// Init
const app = express();
// GET /session/user
app.get('/session/user', (req, res) => {
res.json(req.user);
});
// Export
module.exports = app;
|
JavaScript
| 0 |
@@ -225,16 +225,66 @@
req.user
+ %7C%7C %7B error: %22You don't appear to be logged in.%22 %7D
);%0A%7D);%0A%0A
|
cb9f36e86d228bccfb7c85155f9c0dacfb706dd9
|
revert unbox change (#15067)
|
shared/chat/inbox/container/index.js
|
shared/chat/inbox/container/index.js
|
// @flow
import * as I from 'immutable'
import * as React from 'react'
import * as Constants from '../../../constants/chat2'
import * as Types from '../../../constants/types/chat2'
import * as Chat2Gen from '../../../actions/chat2-gen'
import * as RouteTreeGen from '../../../actions/route-tree-gen'
import * as Inbox from '..'
import {namedConnect} from '../../../util/container'
import type {Props as _Props, RowItem, RowItemSmall, RowItemBig} from '../index.types'
import normalRowData from './normal'
import filteredRowData from './filtered'
import ff from '../../../util/feature-flags'
type OwnProps = {|
routeState: I.RecordOf<{
smallTeamsExpanded: boolean,
}>,
navigateAppend: (...Array<any>) => any,
|}
const mapStateToProps = state => {
const metaMap = state.chat2.metaMap
const filter = state.chat2.inboxFilter
const username = state.config.username
const inboxVersion = state.chat2.inboxVersion
const {allowShowFloatingButton, rows, smallTeamsExpanded} = filter
? filteredRowData(metaMap, filter, username)
: normalRowData(metaMap, state.chat2.smallTeamsExpanded, inboxVersion)
const neverLoaded = !state.chat2.inboxHasLoaded
const _canRefreshOnMount = neverLoaded && !Constants.anyChatWaitingKeys(state)
return {
_canRefreshOnMount,
_selectedConversationIDKey: Constants.getSelectedConversation(state),
allowShowFloatingButton,
filter,
neverLoaded,
rows,
smallTeamsExpanded,
}
}
const mapDispatchToProps = (dispatch, {navigateAppend}) => ({
_onSelect: (conversationIDKey: Types.ConversationIDKey) =>
dispatch(Chat2Gen.createSelectConversation({conversationIDKey, reason: 'inboxFilterChanged'})),
_onSelectNext: (rows, selectedConversationIDKey, direction) => {
const goodRows: Array<RowItemSmall | RowItemBig> = rows.reduce((arr, row) => {
if (row.type === 'small' || row.type === 'big') {
arr.push(row)
}
return arr
}, [])
const idx = goodRows.findIndex(row => row.conversationIDKey === selectedConversationIDKey)
if (goodRows.length) {
const {conversationIDKey} = goodRows[(idx + direction + goodRows.length) % goodRows.length]
dispatch(Chat2Gen.createSelectConversation({conversationIDKey, reason: 'inboxFilterArrow'}))
}
},
_refreshInbox: () => dispatch(Chat2Gen.createInboxRefresh({reason: 'componentNeverLoaded'})),
onNewChat: () =>
dispatch(
ff.newTeamBuildingForChat
? RouteTreeGen.createNavigateAppend({
path: [{props: {}, selected: 'newChat'}],
})
: Chat2Gen.createSetPendingMode({pendingMode: 'searchingForUsers'})
),
onUntrustedInboxVisible: (conversationIDKeys: Array<Types.ConversationIDKey>) =>
dispatch(
Chat2Gen.createMetaNeedsUpdating({
conversationIDKeys,
reason: 'untrusted inbox visible',
})
),
toggleSmallTeamsExpanded: () => dispatch(Chat2Gen.createToggleSmallTeamsExpanded()),
})
// This merge props is not spreading on purpose so we never have any random props that might mutate and force a re-render
const mergeProps = (stateProps, dispatchProps, ownProps) => {
return {
_canRefreshOnMount: stateProps._canRefreshOnMount,
_refreshInbox: dispatchProps._refreshInbox,
allowShowFloatingButton: stateProps.allowShowFloatingButton,
filter: stateProps.filter,
neverLoaded: stateProps.neverLoaded,
onNewChat: dispatchProps.onNewChat,
onSelectDown: () =>
dispatchProps._onSelectNext(stateProps.rows, stateProps._selectedConversationIDKey, 1),
onSelectUp: () => dispatchProps._onSelectNext(stateProps.rows, stateProps._selectedConversationIDKey, -1),
onUntrustedInboxVisible: dispatchProps.onUntrustedInboxVisible,
rows: stateProps.rows,
smallTeamsExpanded: stateProps.smallTeamsExpanded,
toggleSmallTeamsExpanded: dispatchProps.toggleSmallTeamsExpanded,
}
}
type Props = $Diff<
{|
..._Props,
_refreshInbox: () => void,
_canRefreshOnMount: boolean,
|},
{
filterFocusCount: number,
focusFilter: () => void,
}
>
type State = {
filterFocusCount: number,
}
class InboxWrapper extends React.PureComponent<Props, State> {
state = {
filterFocusCount: 0,
}
_focusFilter = () => {
this.setState(p => ({filterFocusCount: p.filterFocusCount + 1}))
}
_onSelectUp = () => this.props.onSelectUp()
_onSelectDown = () => this.props.onSelectDown()
componentDidMount() {
if (this.props._canRefreshOnMount) {
this.props._refreshInbox()
}
}
_isExpanded(rows: Array<RowItem>) {
return rows.length > 5 && rows[5].type === 'small'
}
componentDidUpdate(prevProps) {
const loadedForTheFirstTime = prevProps.rows.length === 0 && this.props.rows.length > 0
// See if the first 6 are small, this implies it's expanded
const wasExpanded = this._isExpanded(prevProps.rows)
const isExpanded = this._isExpanded(this.props.rows)
if (loadedForTheFirstTime || (isExpanded && !wasExpanded)) {
const toUnbox = this.props.rows.slice(0, 20).reduce((arr, row) => {
if (row.type === 'small' || row.type === 'big') {
arr.push(row.conversationIDKey)
}
return arr
}, [])
if (toUnbox.length) {
this.props.onUntrustedInboxVisible(toUnbox)
}
}
}
render() {
const Component = Inbox.default
const {_refreshInbox, _canRefreshOnMount, ...rest} = this.props
return (
<Component
{...rest}
filterFocusCount={this.state.filterFocusCount}
focusFilter={this._focusFilter}
onSelectUp={this._onSelectUp}
onSelectDown={this._onSelectDown}
/>
)
}
}
export default namedConnect<OwnProps, _, _, _, _>(mapStateToProps, mapDispatchToProps, mergeProps, 'Inbox')(
InboxWrapper
)
|
JavaScript
| 0 |
@@ -407,17 +407,8 @@
ops,
- RowItem,
Row
@@ -4502,106 +4502,8 @@
%7D%0A%0A
- _isExpanded(rows: Array%3CRowItem%3E) %7B%0A return rows.length %3E 5 && rows%5B5%5D.type === 'small'%0A %7D%0A%0A
co
@@ -4528,24 +4528,24 @@
revProps) %7B%0A
+
const lo
@@ -4702,53 +4702,84 @@
nst
-wasExpanded = this._isExpanded(prevProps.rows
+smallRowsPlusOne = prevProps.rows.slice(0, 6).filter(r =%3E r.type === 'small'
)%0A
@@ -4790,38 +4790,67 @@
nst
-isE
+e
xpanded
- = this._isExpanded(
+ForTheFirstTime = smallRowsPlusOne.length === 5 &&
this
@@ -4860,17 +4860,27 @@
ops.rows
-)
+.length %3E 5
%0A if
@@ -4909,36 +4909,31 @@
%7C%7C
-(isE
+e
xpanded
- && !wasExpanded)
+ForTheFirstTime
) %7B%0A
|
223158bfc2836de771a92278125b1af8a0c1fb99
|
Add missing empty line
|
lib/node_modules/@stdlib/utils/timeit/lib/timeit.js
|
lib/node_modules/@stdlib/utils/timeit/lib/timeit.js
|
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isFunction = require( '@stdlib/assert/is-function' );
var isArray = require( '@stdlib/assert/is-array' );
var copy = require( '@stdlib/utils/copy' );
var cwd = require( '@stdlib/utils/cwd' );
var defaults = require( './defaults.json' );
var validate = require( './validate.js' );
var evaluate = require( './vm_evaluate.js' );
var transform = require( './transform.js' );
// VARIABLES //
var FILENAME = 'timeit.js';
var MIN_TIME = 0.1; // seconds
var ITERATIONS = 10; // 10^1
var MAX_ITERATIONS = 10000000000; // 10^10
// MAIN //
/**
* Times a snippet.
*
* @param {string} code - snippet to time
* @param {Options} [options] - function options
* @param {string} [options.before=""] - setup code
* @param {string} [options.after=""] - cleanup code
* @param {(PositiveInteger|null)} [options.iterations=1e6] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {boolean} [options.asynchronous=false] - boolean indicating whether a snippet is asynchronous
* @param {Callback} clbk - callback to invoke upon completion
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {void}
*
* @example
* var code = '';
* code += 'var x = Math.pow( Math.random(), 3 );';
* code += 'if ( x !== x ) {';
* code += 'throw new Error( \'Something went wrong.\' );';
* code += '}';
*
* timeit( code, done );
*
* function done( error, results ) {
* if ( error ) {
* throw error;
* }
* console.dir( results );
* }
*/
function timeit( code, options, clbk ) {
var results;
var opts;
var dir;
var err;
var idx;
var cb;
if ( !isString( code ) ) {
throw new TypeError( 'invalid input argument. First argument must be a primitive string. Value: `' + code + '`.' );
}
opts = copy( defaults );
if ( arguments.length === 2 ) {
cb = options;
} else {
cb = clbk;
err = validate( opts, options );
if ( err ) {
throw err;
}
}
if ( !isFunction( cb ) ) {
throw new TypeError( 'invalid input argument. Callback argument must be a function. Value: `' + cb + '`.' );
}
results = new Array( opts.repeats );
dir = cwd();
idx = 0;
// Pretest to check for early returns and/or errors...
try {
evaluate( code, opts, FILENAME, dir, onTest );
} catch ( error ) {
err = new Error( 'evaluation error. Encountered an error when evaluating snippet. '+error.message );
return done( err );
}
/**
* Evaluates a code snippet on the next turn of the event loop. Waiting until the next turn avoids the current turn being bogged down by a long running queue.
*
* @private
* @param {Callback} clbk - callback
*/
function next( clbk ) {
process.nextTick( onTick );
/**
* Callback invoked upon next turn of event loop.
*
* @private
*/
function onTick() {
evaluate( code, opts, FILENAME, dir, clbk );
} // end FUNCTION onTick()
} // end FUNCTION next()
/**
* Callback invoked after completing pretest.
*
* @private
* @param {(Error|null)} error - error object
* @param {NonNegativeIntegerArray} time - results
* @returns {void}
*/
function onTest( error, time ) {
if ( error ) {
return done( error );
}
if ( !isArray( time ) || time.length !== 2 ) {
// This should only happen if someone is a bad actor and attempts to call the `done` callback without providing timing results.
error = new Error( 'evaluation error. Did not receive timing results.' );
return done( error );
}
if ( opts.iterations === null ) {
opts.iterations = ITERATIONS;
return next( onRun );
}
// Begin timing the snippet...
return next( onFinish );
} // end FUNCTION onTest()
/**
* Callback invoked upon running a pre-run to determine the number of iterations.
*
* @private
* @param {(Error|null)} error - error object
* @param {NonNegativeIntegerArray} time - results
* @returns {void}
*/
function onRun( error, time ) {
var t;
if ( error ) {
return done( error );
}
t = time[ 0 ] + ( time[ 1 ]/1e9 );
if (
t < MIN_TIME &&
opts.iterations < MAX_ITERATIONS
) {
opts.iterations *= 10;
return next( onRun );
}
// Begin timing the snippet...
return next( onFinish );
} // end FUNCTION onRun()
/**
* Callback invoked upon executing code.
*
* @private
* @param {(Error|null)} error - error object
* @param {NonNegativeIntegerArray} time - results
* @returns {void}
*/
function onFinish( error, time ) {
if ( error ) {
return done( error );
}
results[ idx ] = time;
idx += 1;
if ( idx < opts.repeats ) {
return next( onFinish );
}
done( null, results );
} // end FUNCTION onFinish()
/**
* Callback invoked upon completion.
*
* @private
* @param {(Error|null)} error - error object
* @param {ArrayArray} results - raw results
*/
function done( error, results ) {
var out;
if ( !error ) {
out = transform( results, opts.iterations );
}
// Avoid releasing the zalgo:
process.nextTick( onTick );
/**
* Callback invoked upon the next tick.
*
* @private
* @returns {void}
*/
function onTick() {
if ( error ) {
return cb( error );
}
cb( null, out );
} // end FUNCTION onTick()
} // end FUNCTION done()
} // end FUNCTION timeit()
// EXPORTS //
module.exports = timeit;
|
JavaScript
| 0.999999 |
@@ -2900,16 +2900,17 @@
Tick );%0A
+%0A
%09%09/**%0A%09%09
|
b8a4ae6bcb022b5109f4c8994cf9d4615337f155
|
remove lint warning
|
src/containers/email/emailReducer.js
|
src/containers/email/emailReducer.js
|
const reducer = (state = [], action) => {
switch (action.type) {
case "EMAILDRAFT_GET_ALL_SUCCESS":
return action.response;
case "EMAILDRAFT_SAVE_ONE_SUCCESS":
return [...state, action.response];
case "EMAILDRAFT_UPDATE_ONE_SUCCESS":
return [...state.filter(draft => draft.id == action.response.id), action.response];
case "EMAILDRAFT_DELETE_ONE_SUCCESS":
return state.filter(draft => draft.id !== action.response);
default:
return state;
}
};
export default reducer;
|
JavaScript
| 0.000001 |
@@ -335,16 +335,17 @@
ft.id ==
+=
action.
|
d989ee81a7c5b9ff24a337b7b8c638ebfd293730
|
test directory overwrite
|
shared_tests/onMoveEntryRequested.js
|
shared_tests/onMoveEntryRequested.js
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
'use strict';
module.exports = function(onMoveEntryRequested, onGetMetadataRequested) {
describe('onMoveEntryRequested', function() {
it('should be able to move a file ', function(done) {
var source = 'dir11/11.txt';
var target = '11_moved.txt';
var statSource = {
entryPath: '/' + source
};
var statTarget = {
entryPath: '/' + target
};
var copyOptions = {
sourcePath: '/' + source,
targetPath: '/' + target
};
var onError = function(error) {
throw new Error(error);
};
var postMoveSuccess = function(data) {
data.name.should.equal(target);
done();
};
onGetMetadataRequested(statTarget, function() {
throw new Error('File should not be at target location before moving.');
}, function() {
onMoveEntryRequested(copyOptions, function() {
onGetMetadataRequested(statTarget, function(data) {
onGetMetadataRequested(statSource, function() {
throw new Error('File should not be at source location after ' +
'moving.');
}, function() {
postMoveSuccess(data);
})
}, function() {
throw new Error('File should be at target location after moving.');
});
}, onError);
});
});
it('should be able to move a directory ', function(done) {
var source = 'dir11';
var target = '11_moved';
var statSource = {
entryPath: '/' + source
};
var statTarget = {
entryPath: '/' + target
};
var copyOptions = {
sourcePath: '/' + source,
targetPath: '/' + target
};
var onError = function(error) {
throw new Error(error);
};
var postMoveSuccess = function(data) {
data.name.should.equal(target);
done();
};
onGetMetadataRequested(statTarget, function() {
throw new Error('Directory should not be at target location before moving.');
}, function() {
onMoveEntryRequested(copyOptions, function() {
onGetMetadataRequested(statTarget, function(data) {
onGetMetadataRequested(statSource, function() {
throw new Error('Directory should not be at source location after ' +
'moving.');
}, function() {
postMoveSuccess(data);
})
}, function() {
throw new Error('Directory should be at target location after moving.');
});
}, onError);
});
});
});
};
|
JavaScript
| 0.000001 |
@@ -1640,17 +1640,1273 @@
irectory
-
+', function(done) %7B%0A var source = 'dir11';%0A var target = '11_moved';%0A%0A var statSource = %7B%0A entryPath: '/' + source%0A %7D;%0A%0A var statTarget = %7B%0A entryPath: '/' + target%0A %7D;%0A%0A var copyOptions = %7B%0A sourcePath: '/' + source,%0A targetPath: '/' + target%0A %7D;%0A%0A var onError = function(error) %7B%0A throw new Error(error);%0A %7D;%0A%0A var postMoveSuccess = function(data) %7B%0A data.name.should.equal(target);%0A done();%0A %7D;%0A%0A onGetMetadataRequested(statTarget, function() %7B%0A throw new Error('Directory should not be at target location before moving.');%0A %7D, function() %7B%0A onMoveEntryRequested(copyOptions, function() %7B%0A onGetMetadataRequested(statTarget, function(data) %7B%0A onGetMetadataRequested(statSource, function() %7B%0A throw new Error('Directory should not be at source location after ' +%0A 'moving.');%0A %7D, function() %7B%0A postMoveSuccess(data);%0A %7D)%0A %7D, function() %7B%0A throw new Error('Directory should be at target location after moving.');%0A %7D);%0A %7D, onError);%0A %7D);%0A %7D);%0A%0A it('should not overwrite existing files/directories
', funct
|
49bb89e5977f409ddde4d0f3ecf158f556f7b5e5
|
remove redundant route
|
app/src/routes.js
|
app/src/routes.js
|
import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import { Provider } from 'react-redux';
import store, { history } from './store';
/* eslint-disable */
import App from 'components/App';
import * as Pages from 'pages';
/* eslint-enable */
const routes = (
<Provider store={store}>
<Router
history={history} // Scroll to top on route transitions
onUpdate={() => window.scrollTo(0, 0)} // eslint-disable-line
>
<Route path="/" component={App}>
<IndexRoute component={Pages.LandingPage} />
<Route path="articles/:id" component={Pages.PostPage} />
<Route path="/admin/content-dashboard" component={Pages.ContentDashboardPage} />
<Route path="/login" component={Pages.LoginPage} />
<Route path="/signup" component={Pages.SignupPage} />
<Route path="admin/new-story" component={Pages.CmsEditorPage} />
<Route path="/articles/:articleId" component={Pages.SingleArticlePage} />
<Route path="/martin" component={Pages.MartinPage} />
<Route path="*" component={Pages.NotFoundPage} />
</Route>
</Router>
</Provider>
);
export default routes;
|
JavaScript
| 0.000143 |
@@ -905,89 +905,8 @@
/%3E%0A
- %3CRoute path=%22/articles/:articleId%22 component=%7BPages.SingleArticlePage%7D /%3E
%0A
|
f78dc7b68f87da3eb3fc87c15b4005630b1d56f2
|
add member number when exporting trades
|
server/download/trades.js
|
server/download/trades.js
|
Router.route('/download-trades', function() {
var data = Trades.find({}, {sort: {createdAt: -1}}).fetch();
var fields = [
{
key: 'priceType',
title: 'Price type'
},
{
key: 'exchangeRateProvider',
title: 'Exchange rate provider',
transform: function (val) {
return ExchangeRateProviders.findOne(val).name;
}
},
{
key: 'exchangeRate',
title: 'Exchange rate',
type: 'number'
},
{
key: 'percentageFee',
title: 'Base fee (%)',
type: 'number'
},
{
key: 'companyPrice',
title: 'Company price',
type: 'number'
},
{
key: 'subtotal',
title: 'Subtotal',
type: 'number'
},
{
key: 'flatFee',
title: 'Flat fee',
type: 'number'
},
{
key: 'percentageFeeForAmountReceived',
title: 'Payment method fee (%)',
type: 'number'
},
{
key: 'calculatedFeeForAmountReceived',
title: 'Calculated fee',
type: 'number'
},
{
key: 'amountReceived',
title: 'Amount received',
type: 'number'
},
{
key: 'paymentMethodForAmountReceived',
title: 'Payment method',
transform: function (val) {
var paymentMethod = PaymentMethods.findOne(val);
var currency = Currencies.findOne(paymentMethod.currency);
return paymentMethod.name + ' (' + currency.code + ')';
}
},
{
key: 'amountSent',
title: 'Amount sent',
type: 'number'
},
{
key: 'paymentMethodForAmountSent',
title: 'Payment method',
transform: function (val) {
var paymentMethod = PaymentMethods.findOne(val);
var currency = Currencies.findOne(paymentMethod.currency);
return paymentMethod.name + ' (' + currency.code + ')';
}
},
// {
// key: 'marketValue',
// title: 'Market value',
// type: 'number'
// },
// {
// key: 'marketValueCurrency',
// title: 'Market value currency',
// transform: function (val) {
// return Currencies.findOne(val).code;
// }
// },
// {
// key: 'member',
// title: 'Member number',
// type: 'number',
// transform: function (val) {
// return Members.findOne(val).number;
// }
// },
{
key: 'createdBy',
title: 'Employee',
transform: function (val) {
return Meteor.users.findOne(val).profile.name;
}
},
{
key: 'createdAt',
title: 'Date',
transform: function (val) {
return moment(val).format('M/D/YYYY HH:mm:ss');
}
}
];
var title = 'Trades';
var file = Excel.export(title, fields, data);
var headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
};
this.response.writeHead(200, headers);
this.response.end(file, 'binary');
}, { where: 'server' });
|
JavaScript
| 0 |
@@ -177,38 +177,44 @@
type'%0A %7D,%0A
+ //
%7B%0A
+ //
key: 'exchang
@@ -228,24 +228,27 @@
ovider',%0A
+ //
title: 'E
@@ -271,26 +271,29 @@
vider',%0A
+//
+
transform: f
@@ -303,32 +303,35 @@
tion (val) %7B%0A
+ //
return Exch
@@ -366,32 +366,35 @@
l).name;%0A
+ //
%7D%0A
%7D,%0A %7B%0A
@@ -373,32 +373,35 @@
;%0A // %7D%0A
+ //
%7D,%0A %7B%0A
@@ -1867,36 +1867,30 @@
%7D%0A %7D,%0A
- //
%7B%0A
- //
key: 'mar
@@ -1900,29 +1900,26 @@
Value',%0A
-//
-
title: 'Mark
@@ -1928,27 +1928,24 @@
value',%0A
- //
type: 'nu
@@ -1953,38 +1953,29 @@
ber'%0A
- //
%7D,%0A
- //
%7B%0A
- //
key:
@@ -1997,29 +1997,26 @@
rency',%0A
-//
-
title: 'Mark
@@ -2034,27 +2034,24 @@
rrency',%0A
- //
transform
@@ -2064,35 +2064,32 @@
tion (val) %7B%0A
- //
return Curr
@@ -2113,35 +2113,32 @@
l).code;%0A
- //
%7D%0A
// %7D,%0A /
@@ -2129,30 +2129,21 @@
%0A
- //
%7D,%0A
- //
%7B%0A
- //
k
@@ -2151,35 +2151,32 @@
y: 'member',%0A
- //
title: 'Membe
@@ -2185,27 +2185,24 @@
number',%0A
- //
type: 'nu
@@ -2203,35 +2203,32 @@
e: 'number',%0A
- //
transform: fu
@@ -2242,31 +2242,28 @@
(val) %7B%0A
-//
-
return Membe
@@ -2285,35 +2285,32 @@
.number;%0A
- //
%7D%0A
// %7D,%0A %7B
@@ -2289,35 +2289,32 @@
ber;%0A %7D%0A
- //
%7D,%0A %7B%0A
|
66581754fb66a13aeb346c6b1529ee21c2766ca1
|
Fix linter error on Heroku
|
src/mockApi/middleware.js
|
src/mockApi/middleware.js
|
/* eslint-disable complexity */
/* eslint-disable callback-return */
/* eslint-disable fp/no-let */
/* eslint-disable fp/no-mutation */
import isPlainObject from 'lodash/isPlainObject';
import { ApiError, RequestError } from 'redux-api-middleware/lib/errors' ;
import { normalizeTypeDescriptors } from 'redux-api-middleware/lib/util';
import CALL_MOCK_API from './CALL_MOCK_API';
const SUCCESS_DELAY = 1000;
const defaultResponse = {
ok: true,
};
const isMockRSAA = (action) => isPlainObject(action) && action.hasOwnProperty(CALL_MOCK_API);
const validateMockRSAA = (action) => {
const validationErrors = [];
for (const key in action) {
if (key !== [CALL_MOCK_API]) {
validationErrors.push(`Invalid root key: ${key}`);
}
}
const callAPI = action[CALL_MOCK_API];
if (!isPlainObject(callAPI)) {
validationErrors.push('[CALL_MOCK_API] property must be a plain JavaScript object');
}
const { mockResponse } = callAPI;
if (typeof mockResponse === 'undefined') {
validationErrors.push('[CALL_MOCK_API] must have a mockResponse property');
} else if (isPlainObject(mockResponse)) {
if (mockResponse.ok !== false && typeof mockResponse.responseJSON === 'undefined') {
validationErrors.push(
'[CALL_MOCK_API] must have a mockResponse.responseJSON if mockResponse.ok is true or undefined');
}
} else if (typeof mockResponse !== 'function') {
validationErrors.push(
'mockResponse must be a plain js object or a function that resolves to one');
}
return validationErrors;
};
/**
* A Redux middleware that processes RSAA actions.
*
* @type {ReduxMiddleware}
* @access public
*/
export default function mockApiMiddleware({ dispatch, getState }) {
return (next) => (async) (action) => {
// Do not process actions without a [CALL_API] property
if (!isMockRSAA(action)) {
return next(action);
}
// Try to dispatch an error request FSA for invalid RSAAs
const validationErrors = validateMockRSAA(action);
if (validationErrors.length) {
throw validationErrors;
}
// Parse the validated RSAA action
const callAPI = action[CALL_MOCK_API];
let { endpoint, headers } = callAPI;
const { bailout, types } = callAPI;
const [requestType, successType, failureType] = normalizeTypeDescriptors(types);
// Should we bail out?
try {
if ((typeof bailout === 'boolean' && bailout) ||
(typeof bailout === 'function' && bailout(getState()))) {
return null;
}
} catch (err) {
return next({
...requestType,
payload: new RequestError('[CALL_API].bailout function failed'),
error: true,
});
}
// Process [CALL_API].endpoint function
if (typeof endpoint === 'function') {
try {
endpoint = endpoint(getState());
} catch (err) {
return next({
...requestType,
payload: new RequestError('[CALL_API].endpoint function failed'),
error: true,
});
}
}
// Process [CALL_API].headers function
if (typeof headers === 'function') {
try {
headers = headers(getState());
} catch (err) {
return next({
...requestType,
payload: new RequestError('[CALL_API].headers function failed'),
error: true,
});
}
}
// We can now dispatch the request FSA
dispatch(requestType);
// get fake response
let res = {};
if (typeof callAPI.mockResponse === 'function') {
res = { ...defaultResponse, ...callAPI.mockResponse(action) };
} else {
res = { ...defaultResponse, ...callAPI.mockResponse };
}
// Process the server response
if (res.ok) {
return new Promise((resolve) => {
setTimeout(() => {
const nextAction = next({ ...successType, payload: typeof successType.payload === 'function'
? successType.payload(
action,
getState(),
{
...res,
json: () => ({ then: (callback) => callback(res.responseJSON) }),
headers: {
get: () => 'json',
},
}
)
: res.responseJSON,
});
resolve(nextAction);
}, SUCCESS_DELAY);
});
}
return next({
...failureType,
payload: new ApiError(res.status, res.statusText, res.responseJSON),
error: true,
});
};
}
|
JavaScript
| 0.013286 |
@@ -252,17 +252,16 @@
/errors'
-
;%0Aimport
|
6c835fb6cd73b4145c73cb3241bdc98e692476a9
|
refactor corona
|
src/modal/Corona/index.js
|
src/modal/Corona/index.js
|
import { scaleLinear } from 'd3-scale';
import { mouse } from 'd3-selection';
import cloneDeep from 'lodash-es/cloneDeep';
import { AbstractStackedCartesianChart } from '../../base';
import { CoronaOptions } from './Corona-Options';
import createCartesianStackedOpt from '../../options/createCartesianStackedOpt';
import { Stacks } from '../../data';
import applyVoronoi from '../../canvas/voronoi/apply';
import drawCanvas from './draw-canvas';
import highlight from './highlight';
import transparentColor from "./get-transparent-color";
import getRadius from './get-radius';
import animateStates from "./tween-states";
class Corona extends AbstractStackedCartesianChart {
constructor(canvasId, _userOptions) {
super(canvasId, _userOptions);
}
_animate() {
const [innerRadius, outerRadius] = getRadius(this._options);
const dataRange = [this._data.minY, this._data.maxY];
const radiusScale = scaleLinear()
.domain(dataRange.map(d=>this._getMetric().scale(d)))
.range([innerRadius, outerRadius]);
const rawRadiusScale = radiusScale.copy().domain(dataRange);
const initialState = this.previousState
? this.previousState
: this._data.nested.map(d => {
return {
key: d.key,
c: this._c(d),
s: d.key,
range: dataRange,
alpha: 0,
strokeAlpha: this._options.plots.strokeOpacity,
values: d.values.map((e, i) => {
return {
key: d.key,
angle: Math.PI * 2 * i / d.values.length,
r: innerRadius,
r0: innerRadius,
r1: innerRadius,
data: e.data,
d: e
}
})
}
});
const finalState = this._data.nested.map(d => {
return {
key: d.key,
c: this._c(d),
s: d.key,
range: dataRange,
alpha: this._options.plots.areaOpacity,
strokeAlpha: this._options.plots.strokeOpacity,
values: d.values.map((e, i) => {
return {
key: d.key,
angle: Math.PI * 2 * i / d.values.length,
r: radiusScale(e.y),
r0: rawRadiusScale(e.y0),
r1: rawRadiusScale(e.y1),
data: e.data,
d: e
}
})
}
});
// cache finalState as the initial state of next animation call
this.previousState = finalState;
let that = this;
const ctx = that._frontContext;
const opt = that._options;
animateStates(initialState,
finalState,
opt.animation.duration.update,
ctx,
opt).then(res=>{
that._voronoi = applyVoronoi(ctx, opt, finalState.reduce((acc, p)=>{
acc = acc.concat(p.values.map(d=>{
return {
s: p.key,
label: that._getDimensionVal(d.data),
metric: d.data[p.key],
x: d.r * Math.sin(d.angle) + opt.chart.width / 2,
y: opt.chart.height - (d.r * Math.cos(d.angle) + opt.chart.height / 2),
c: p.c,
d: d,
data: d.data
}
}));
return acc;
}, []));
/**
* callback for when the mouse moves across the overlay
*/
function mouseMoveHandler() {
// get the current mouse position
const [mx, my] = mouse(this);
const QuadtreeRadius = 100;
// use the new diagram.find() function to find the Voronoi site
// closest to the mouse, limited by max distance voronoiRadius
const closest = that._voronoi.find(mx, my, QuadtreeRadius);
if (closest) {
const fadeOpacity = 0.1;
const optCopy = cloneDeep(opt);
optCopy.plots.levelColor = transparentColor(optCopy.plots.levelColor, fadeOpacity);
optCopy.plots.strokeOpacity = 0;
drawCanvas(ctx,
finalState.map(d=>{
const p = d;
p.alpha = d.key === closest.data.s
? 0.4
: fadeOpacity;
p.strokeAlpha = d.key === closest.data.s
? 1
: 0;
return p;
}),
optCopy);
highlight(ctx, opt, closest.data);
} else {
drawCanvas(ctx, res, opt);
}
}
function mouseOutHandler() {
drawCanvas(ctx, res, opt);
}
that._frontCanvas.on('mousemove', mouseMoveHandler);
that._frontCanvas.on('mouseout', mouseOutHandler);
that._listeners.call('rendered');
});
}
stackLayout() {
this._options.plots.stackLayout = true;
this._options.plots.stackMethod = Stacks.Zero;
this.update();
};
expandLayout() {
this._options.plots.stackLayout = true;
this._options.plots.stackMethod = Stacks.Expand;
this.update();
};
groupedLayout() {
this._options.plots.stackLayout = false;
this.update();
};
createOptions(_userOpt) {
return createCartesianStackedOpt(CoronaOptions, _userOpt);
};
}
export default Corona;
|
JavaScript
| 0.999999 |
@@ -3194,26 +3194,19 @@
x, opt,
-finalState
+res
.reduce(
@@ -4666,26 +4666,19 @@
-finalState
+res
.map(d=%3E
|
d0d9be8cf50c8dc75ac8f52d377cb1c205deba7c
|
Fix json writing
|
lib/naviserver.js
|
lib/naviserver.js
|
#!/usr/bin/env node
'use strict';
var utils = require('./utils.js');
var udp = require('./udp.js');
var sources = require('./sources.js');
var jsonsource = require('./jsonsource.js');
var winston = require('winston');
var Bacon = require("baconjs").Bacon;
exports.startApp = function () {
var optimist = sources.usages()
.usage('$0: Http server and router for navigational data (NMEA 0183 & NMEA 2000)')
.describe('u', 'Broadcast nmea 0183 via udp on port 7777')
.describe('b', 'Broadcast address for udp broadcast')
.describe('writejson', 'Write the internal json stream to [filename]')
.describe('p', 'http port')
.demand('boat')
.describe('boat', 'boat configuration, loaded from lib/boats/ directory')
.options('p', {default: 8080})
.wrap(70);
var argv = optimist.argv;
if (argv.help) {
optimist.showHelp();
process.exit(0);
}
var express = require('express');
var app = express();
var path = require('path')
var oneDay = 86400000;
app.get("/swipe*", function(req,res) {
res.sendfile(path.resolve(__dirname + '/../webapp/swipe.html'));
});
app.get('/api/0.1/vessels', function (request, response) {
response.json([
{
name: 'Cassiopeia',
href: '../vessel/byName/cassiopeia'
},
{
name: 'Freya',
href: '../vessel/byName/freya'
},
{
name: 'Plaka',
href: '../vessel/byName/plaka'
}
]);
});
app.use(express.static(__dirname + '/../webapp/', { maxAge: oneDay }));
var server = require('http').createServer(app);
server.listen(Number(process.env.PORT || argv.p));
var primus = new require('primus')(server, {
parser: 'JSON'
});
var connectionEventsAsIntegers = new Bacon.Bus();
var hasActiveClients = connectionEventsAsIntegers.scan(0, function(x,y){return x +y;}).map(function(v) { return v > 0;});
var streamSources = sources.configure(argv, hasActiveClients);
require('./boats/' + argv.boat + '.js').boat.configureStreams(streamSources);
if (argv.u) {
udp.create(streamSources.nmea.raw, argv);
}
if (argv.writejson) {
jsonsource.startWriting(streamSources.nmea)
}
primus.on('connection', function (spark) {
spark['unsubscribe'] = [];
connectionEventsAsIntegers.push(1);
winston.info('Connect:' + spark.id + " " + JSON.stringify(spark.query));
if (spark.query['pgn'] != undefined) {
[].concat(spark.query['pgn']).map(function (pgn) {
var stream = streamconfig.out.pgn.pgnStream(pgn);
spark['unsubscribe'].push(stream.subscribe(function (event) {
spark.write(event.value());
}))
});
} else if (spark.query['gaugedata'] != undefined) {
spark['unsubscribe'].push(streamSources.gaugeData.subscribe(function (event) {
spark.write(event.value());
}));
} else {
spark['unsubscribe'].push(streamSources.n2k.subscribe(function (event) {
spark.write(event.value());
}));
spark['unsubscribe'].push(streamSources.nmea.json.subscribe(function (event) {
spark.write(event.value());
}));
}
}
)
;
primus.on('disconnection', function (spark) {
connectionEventsAsIntegers.push(-1);
winston.info("Disconnect:" + spark.id);
spark['unsubscribe'].map(function (unsubscribeF) {
unsubscribeF();
});
});
return server;
}
|
JavaScript
| 0.999344 |
@@ -2171,19 +2171,58 @@
ources.n
-mea
+2k.all, streamSources.nmea, argv.writejson
)%0A %7D%0A%0A%0A
|
371db934b97615f7afd9f1f71a2dff583ca93d55
|
fix param naming;
|
src/wordbreaker-russian/rules/if-vowels-before-and-after.js
|
src/wordbreaker-russian/rules/if-vowels-before-and-after.js
|
// 117
// При переносе слов нельзя ни оставлять в конце строки,
// ни переносить на другую строку часть слова, не составляющую слога.
import isVowel from './../utils/is-vowel'
export default function ifVowelsBeforeAndAfter (pos, arr) {
let before = false
let after = false
for (let i = pos + 1; i < arr.length; i++) {
if (isVowel(arr[i])) {
after = true
break
}
}
for (let i = pos; i >= 0; i--) {
if (isVowel(arr[i])) {
before = true
break
}
}
return before && after
}
|
JavaScript
| 0.000001 |
@@ -224,19 +224,20 @@
r (pos,
-arr
+word
) %7B%0A
@@ -309,19 +309,20 @@
1; i %3C
-arr
+word
.length;
@@ -341,35 +341,36 @@
if (isVowel(
-arr
+word
%5Bi%5D)) %7B%0A
@@ -482,11 +482,12 @@
wel(
-arr
+word
%5Bi%5D)
|
688572c25b4912656cbb2641bc69d7ba37d0998c
|
Update food.js
|
server/lib/models/food.js
|
server/lib/models/food.js
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const requiredString = {type: String, required: true};
const foodSchema = new Schema({
name: requiredString,
barcode: {type: Number, default: 0},
servingSize: {type: Number, default: 0},
servingUnit: {type: Number, default: 'g'},
Calories: {type: Number, default: 0},
totalCarbs: {type: Number, default: 0},
sugars: {type: Number, default: 0},
fiber: {type: Number, default: 0},
totalFats: {type: Number, default: 0},
saturatedFats: {type: Number, default: 0},
unsaturatedFats: {type: Number, default: 0},
totalProtein: {type: Number, default: 0},
vetted: Boolean,
uploadedBy: {type: String, default: 'user'},
});
module.exports = mongoose.model('Food', foodSchema);
|
JavaScript
| 0.000002 |
@@ -283,38 +283,38 @@
ingUnit: %7Btype:
-Number
+String
, default: 'g'%7D,
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.