commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
e052265d4e9415b63bb2fd81fb983bdd30754944 | web/test/components/portal/Portal.js | web/test/components/portal/Portal.js | import DomMock from '../../helpers/dom-mock';
import jsdom from 'mocha-jsdom';
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { Portal } from '../../../portal/src/containers/Portal';
import FBLogin from '../../../portal/src/components/FBLogin';
DomMock('<html><body></body></html>');
describe('[Portal] Testing Portal Component', () => {
jsdom({ skipWindowCheck: true });
const props = {
loading: false,
token: 'xxxx',
account: {},
subject: '',
surveyID: '',
editSubject: false,
preview: '',
previewID: '',
routing: {},
editSubjectActions: () => {},
subjectActions: () => {},
questionsActions: () => {},
previewActions: () => {},
accountActions: () => {}
};
it('Portal: FB Login', () => {
const content = TestUtils.renderIntoDocument(
<Portal {...props}/>
);
const fb = TestUtils.scryRenderedComponentsWithType(content, FBLogin);
expect(fb.length).toEqual(1);
});
});
| import DomMock from '../../helpers/dom-mock';
import jsdom from 'mocha-jsdom';
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { Portal } from '../../../portal/src/containers/Portal';
import FBLogin from '../../../portal/src/components/FBLogin';
import Subject from '../../../portal/src/components/Popup/Subject';
DomMock('<html><body></body></html>');
describe('[Portal] Testing Portal Component', () => {
jsdom({ skipWindowCheck: true });
const props = {
loading: false,
token: 'xxxx',
account: {},
subject: '',
surveyID: '',
editSubject: false,
preview: '',
previewID: '',
routing: {},
editSubjectActions: () => {},
subjectActions: () => {},
questionsActions: () => {},
previewActions: () => {},
accountActions: () => {}
};
it('Portal: FB Login', () => {
const content = TestUtils.renderIntoDocument(<Portal {...props} />);
const fb = TestUtils.scryRenderedComponentsWithType(content, FBLogin);
expect(fb.length).toEqual(1);
});
it('Portal: edit subject popup', () => {
const editProps = Object.assign({}, props,
{ editSubject: true });
const content = TestUtils.renderIntoDocument(<Portal {...editProps} />);
const subject = TestUtils.findRenderedComponentWithType(content, Subject);
expect(subject).toExist();
});
});
| Add edit subject unit test in portal | Add edit subject unit test in portal
| JavaScript | mit | trendmicro/serverless-survey-forms,trendmicro/serverless-survey-forms | ---
+++
@@ -5,6 +5,7 @@
import TestUtils from 'react-addons-test-utils';
import { Portal } from '../../../portal/src/containers/Portal';
import FBLogin from '../../../portal/src/components/FBLogin';
+import Subject from '../../../portal/src/components/Popup/Subject';
DomMock('<html><body></body></html>');
@@ -29,10 +30,16 @@
};
it('Portal: FB Login', () => {
- const content = TestUtils.renderIntoDocument(
- <Portal {...props}/>
- );
+ const content = TestUtils.renderIntoDocument(<Portal {...props} />);
const fb = TestUtils.scryRenderedComponentsWithType(content, FBLogin);
expect(fb.length).toEqual(1);
});
+
+ it('Portal: edit subject popup', () => {
+ const editProps = Object.assign({}, props,
+ { editSubject: true });
+ const content = TestUtils.renderIntoDocument(<Portal {...editProps} />);
+ const subject = TestUtils.findRenderedComponentWithType(content, Subject);
+ expect(subject).toExist();
+ });
}); |
36c92e1e7c1ebeffec6f8f1d4597a4c3aceabbac | src/systems/tracked-controls-webxr.js | src/systems/tracked-controls-webxr.js | var registerSystem = require('../core/system').registerSystem;
/**
* Tracked controls system.
* Maintain list with available tracked controllers.
*/
module.exports.System = registerSystem('tracked-controls-webxr', {
init: function () {
this.controllers = [];
this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
this.onInputSourcesChange = this.onInputSourcesChange.bind(this);
this.addSessionEventListeners();
this.el.sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
},
addSessionEventListeners: function () {
var sceneEl = this.el;
if (!sceneEl.xrSession) { return; }
this.onInputSourcesChange();
sceneEl.xrSession.addEventListener('inputsourceschange', this.onInputSourcesChange);
},
onInputSourcesChange: function () {
this.controllers = this.el.xrSession.getInputSources();
this.el.emit('controllersupdated', undefined, false);
}
});
| var registerSystem = require('../core/system').registerSystem;
var utils = require('../utils');
/**
* Tracked controls system.
* Maintain list with available tracked controllers.
*/
module.exports.System = registerSystem('tracked-controls-webxr', {
init: function () {
this.controllers = [];
this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
},
tick: function () {
this.throttledUpdateControllerList();
},
updateControllerList: function () {
var oldControllersLength = this.controllers.length;
if (!this.el.xrSession) { return; }
this.controllers = this.el.xrSession.getInputSources();
if (oldControllersLength === this.controllers.length) { return; }
this.el.emit('controllersupdated', undefined, false);
}
});
| Use system tick to retrieve controllers instead of unreliable inputsourceschange event. | Use system tick to retrieve controllers instead of unreliable inputsourceschange event.
| JavaScript | mit | aframevr/aframe,chenzlabs/aframe,ngokevin/aframe,aframevr/aframe,chenzlabs/aframe,ngokevin/aframe | ---
+++
@@ -1,4 +1,5 @@
var registerSystem = require('../core/system').registerSystem;
+var utils = require('../utils');
/**
* Tracked controls system.
@@ -7,21 +8,18 @@
module.exports.System = registerSystem('tracked-controls-webxr', {
init: function () {
this.controllers = [];
- this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
- this.onInputSourcesChange = this.onInputSourcesChange.bind(this);
- this.addSessionEventListeners();
- this.el.sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
+ this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
},
- addSessionEventListeners: function () {
- var sceneEl = this.el;
- if (!sceneEl.xrSession) { return; }
- this.onInputSourcesChange();
- sceneEl.xrSession.addEventListener('inputsourceschange', this.onInputSourcesChange);
+ tick: function () {
+ this.throttledUpdateControllerList();
},
- onInputSourcesChange: function () {
+ updateControllerList: function () {
+ var oldControllersLength = this.controllers.length;
+ if (!this.el.xrSession) { return; }
this.controllers = this.el.xrSession.getInputSources();
+ if (oldControllersLength === this.controllers.length) { return; }
this.el.emit('controllersupdated', undefined, false);
}
}); |
10693276f09beaf3cc46782a8b698fa8fb4f7a70 | http-random-user/src/main.js | http-random-user/src/main.js | import Cycle from '@cycle/core';
import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';
function main(sources) {
const getRandomUser$ = sources.DOM.select('.get-random').events('click')
.map(() => {
const randomNum = Math.round(Math.random() * 9) + 1;
return {
url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum),
key: 'users',
method: 'GET'
};
});
const user$ = sources.HTTP
.filter(res$ => res$.request.key === 'users')
.mergeAll()
.map(res => res.body)
.startWith(null);
const vtree$ = user$.map(user =>
div('.users', [
button('.get-random', 'Get random user'),
user === null ? null : div('.user-details', [
h1('.user-name', user.name),
h4('.user-email', user.email),
a('.user-website', {href: user.website}, user.website)
])
])
);
return {
DOM: vtree$,
HTTP: getRandomUser$
};
}
Cycle.run(main, {
DOM: makeDOMDriver('#main-container'),
HTTP: makeHTTPDriver()
});
| import Cycle from '@cycle/core';
import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';
function main(sources) {
const getRandomUser$ = sources.DOM.select('.get-random').events('click')
.map(() => {
const randomNum = Math.round(Math.random() * 9) + 1;
return {
url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum),
category: 'users',
method: 'GET'
};
});
const user$ = sources.HTTP
.filter(res$ => res$.request.category === 'users')
.mergeAll()
.map(res => res.body)
.startWith(null);
const vtree$ = user$.map(user =>
div('.users', [
button('.get-random', 'Get random user'),
user === null ? null : div('.user-details', [
h1('.user-name', user.name),
h4('.user-email', user.email),
a('.user-website', {href: user.website}, user.website)
])
])
);
return {
DOM: vtree$,
HTTP: getRandomUser$
};
}
Cycle.run(main, {
DOM: makeDOMDriver('#main-container'),
HTTP: makeHTTPDriver()
});
| Rename http-random-user key to category | Rename http-random-user key to category
| JavaScript | mit | mikekidder/cycle-examples,cyclejs/cycle-examples,mikekidder/cycle-examples,cyclejs/cycle-examples,mikekidder/cycle-examples | ---
+++
@@ -8,13 +8,13 @@
const randomNum = Math.round(Math.random() * 9) + 1;
return {
url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum),
- key: 'users',
+ category: 'users',
method: 'GET'
};
});
const user$ = sources.HTTP
- .filter(res$ => res$.request.key === 'users')
+ .filter(res$ => res$.request.category === 'users')
.mergeAll()
.map(res => res.body)
.startWith(null); |
c23457181f01c0df8b9a262edbe0113ca550c504 | client/app/serializers/site.js | client/app/serializers/site.js | import DS from 'ember-data';
var SiteSerializer = DS.RESTSerializer.extend({
serialize: function(site, options) {
var fields = [ 'name', 'tagline', 'description', 'moreDesc', 'joinText' ];
var result = { };
fields.forEach(function(field) {
result[field] = site.get(field);
});
if (options && options.includeId) {
result['id'] = site.get('id');
}
return result;
}
});
export default SiteSerializer;
| import DS from 'ember-data';
var SITE_SERIALIZER_FIELDS = [ 'name', 'tagline', 'description', 'moreDesc', 'joinText' ];
var SiteSerializer = DS.RESTSerializer.extend({
serialize: function(site, options) {
var result = site.getProperties(SITE_SERIALIZER_FIELDS);
if (options && options.includeId) {
result['id'] = site.get('id');
}
return result;
}
});
export default SiteSerializer;
| Use more idiomatic ember api | Use more idiomatic ember api
| JavaScript | mit | aymerick/kowa,aymerick/kowa | ---
+++
@@ -1,13 +1,10 @@
import DS from 'ember-data';
+
+var SITE_SERIALIZER_FIELDS = [ 'name', 'tagline', 'description', 'moreDesc', 'joinText' ];
var SiteSerializer = DS.RESTSerializer.extend({
serialize: function(site, options) {
- var fields = [ 'name', 'tagline', 'description', 'moreDesc', 'joinText' ];
- var result = { };
-
- fields.forEach(function(field) {
- result[field] = site.get(field);
- });
+ var result = site.getProperties(SITE_SERIALIZER_FIELDS);
if (options && options.includeId) {
result['id'] = site.get('id'); |
6d7aa555c3b2d554fe74cc0df4186c88965a21de | ckanext/googleanalytics/fanstatic_library/googleanalytics_event_tracking.js | ckanext/googleanalytics/fanstatic_library/googleanalytics_event_tracking.js | // Add Google Analytics Event Tracking to resource download links.
this.ckan.module('google-analytics', function(jQuery, _) {
return {
options: {
googleanalytics_resource_prefix: ''
},
initialize: function() {
jQuery('a.resource-url-analytics').on('click', function() {
var resource_prefix = this.options.googleanalytics_resource_prefix;
var resource_url = resource_prefix + encodeURIComponent(jQuery(this).prop('href'));
if (resource_url) {
_gaq.push(['_trackPageview', resource_url]);
}
});
}
}
});
| // Add Google Analytics Event Tracking to resource download links.
this.ckan.module('google-analytics', function(jQuery, _) {
return {
options: {
googleanalytics_resource_prefix: ''
},
initialize: function() {
jQuery('a.resource-url-analytics').on('click', function() {
var resource_url = encodeURIComponent(jQuery(this).prop('href'));
if (resource_url) {
_gaq.push(['_trackEvent', 'Resource', 'Download', resource_url]);
}
});
}
}
});
| Fix resource download event tracking js | Fix resource download event tracking js
| JavaScript | agpl-3.0 | ckan/ckanext-googleanalytics,ckan/ckanext-googleanalytics,ckan/ckanext-googleanalytics | ---
+++
@@ -6,10 +6,9 @@
},
initialize: function() {
jQuery('a.resource-url-analytics').on('click', function() {
- var resource_prefix = this.options.googleanalytics_resource_prefix;
- var resource_url = resource_prefix + encodeURIComponent(jQuery(this).prop('href'));
+ var resource_url = encodeURIComponent(jQuery(this).prop('href'));
if (resource_url) {
- _gaq.push(['_trackPageview', resource_url]);
+ _gaq.push(['_trackEvent', 'Resource', 'Download', resource_url]);
}
});
} |
48d7d841ffad787aca5652732e1a302ac5ab610e | grunt/config/sass.js | grunt/config/sass.js | // Compile SCSS files into CSS (dev mode is not compressed)
module.exports = {
dev: {
options: {
style: 'expanded'
},
files: {
'preview/vizabi.css': 'src/assets/style/vizabi.scss'
}
},
prod: {
options: {
style: 'compressed'
},
files: {
'dist/vizabi.css': 'src/assets/style/vizabi.scss'
}
},
preview: {
options: {
style: 'compressed'
},
files: {
'preview_src/assets/css/main.css': 'preview_src/assets/sass/main.scss'
}
}
}; | // Compile SCSS files into CSS (dev mode is not compressed)
module.exports = {
dev: {
options: {
style: 'expanded'
},
files: {
'dist/vizabi.css': 'src/assets/style/vizabi.scss'
}
},
prod: {
options: {
style: 'compressed'
},
files: {
'dist/vizabi.css': 'src/assets/style/vizabi.scss'
}
},
preview: {
options: {
style: 'compressed'
},
files: {
'preview_src/assets/css/main.css': 'preview_src/assets/sass/main.scss'
}
}
}; | Fix CSS not updating on development mode | Fix CSS not updating on development mode
| JavaScript | bsd-3-clause | acestudiooleg/vizabi,sergey-filipenko/vizabi,vizabi/vizabi,logicerpsolution/vizabi,maximhristenko/vizabi,logicerpsolution/vizabi,buchslava/vizabi,TBAPI-0KA/vizabi,jdk137/vizabi,alliance-timur/vizabi,sergey-filipenko/vizabi,alliance-timur/vizabi,dab2000/vizabi,logicerpsolution/vizabi,acestudiooleg/vizabi,maximhristenko/vizabi,Gapminder/vizabi,vizabi/vizabi,Rathunter/vizabi,IncoCode/vizabi,alliance-timur/vizabi,homosepian/vizabi,IncoCode/vizabi,maximhristenko/vizabi,Gapminder/vizabi,Rathunter/vizabi,homosepian/vizabi,jdk137/vizabi,IncoCode/vizabi,acestudiooleg/vizabi,TBAPI-0KA/vizabi,buchslava/vizabi,TBAPI-0KA/vizabi,homosepian/vizabi,jdk137/vizabi,Rathunter/vizabi,sergey-filipenko/vizabi,dab2000/vizabi,dab2000/vizabi,Gapminder/vizabi,buchslava/vizabi | ---
+++
@@ -5,7 +5,7 @@
style: 'expanded'
},
files: {
- 'preview/vizabi.css': 'src/assets/style/vizabi.scss'
+ 'dist/vizabi.css': 'src/assets/style/vizabi.scss'
}
},
prod: { |
4d9fdf55de26dc1a26b6a181b01e433d0b035ed2 | packages/telescope-pages/lib/client/routes.js | packages/telescope-pages/lib/client/routes.js | Telescope.config.adminMenu.push({
route: 'pages',
label: 'Pages',
description: 'manage_static_pages'
});
Telescope.config.preloadSubscriptions.push('pages');
PageController = RouteController.extend({
getTitle: function () {
return Pages.collection.findOne({slug: this.params.slug}).title;
},
data: function () {
return Pages.collection.findOne({slug: this.params.slug});
}
});
Meteor.startup(function () {
Router.onBeforeAction(Router._filters.isAdmin, {only: ['pages']});
Router.route('/page/:slug', {
name: 'page',
controller: PageController
});
Router.route('/pages', {
name: 'pages',
controller: Telescope.controllers.admin
});
});
| Telescope.config.adminMenu.push({
route: 'pages',
label: 'Pages',
description: 'manage_static_pages'
});
Telescope.config.preloadSubscriptions.push('pages');
PageController = RouteController.extend({
currentPage: function () {
return Pages.collection.findOne({slug: this.params.slug});
},
getTitle: function () {
return this.currentPage() && this.currentPage().title;
},
data: function () {
return this.currentPage();
}
});
Meteor.startup(function () {
Router.onBeforeAction(Router._filters.isAdmin, {only: ['pages']});
Router.route('/page/:slug', {
name: 'page',
controller: PageController
});
Router.route('/pages', {
name: 'pages',
controller: Telescope.controllers.admin
});
});
| Handle case where Pages collection isn't loaded yet (although that should never happen…) | Handle case where Pages collection isn't loaded yet (although that should never happen…)
| JavaScript | mit | TodoTemplates/Telescope,MeteorHudsonValley/Telescope,hoihei/Telescope,tupeloTS/telescopety,NodeJSBarenko/Telescope,HelloMeets/HelloMakers,Scalingo/Telescope,manriquef/Vulcan,aykutyaman/Telescope,tupeloTS/grittynashville,Scalingo/Telescope,TribeMedia/Screenings,sungwoncho/Telescope,JstnEdr/Telescope,StEight/Telescope,evilhei/itForum,pombredanne/Telescope,almogdesign/Telescope,TelescopeJS/Screenings,jrmedia/oilgas,StEight/Telescope,enginbodur/TelescopeLatest,bshenk/projectIterate,rizakaynak/Telescope,huaiyudavid/rentech,guillaumj/Telescope,SachaG/Zensroom,youprofit/Telescope,ibrahimcesar/Screenings,wende/quickformtest,maxtor3569/Telescope,maxtor3569/Telescope,nhlennox/gbjobs,jamesrhymer/iwishcitiescould,nhlennox/gbjobs,geoclicks/Telescope,adhikariaman01/Telescope,manriquef/Vulcan,TribeMedia/Telescope,covernal/Telescope,SachaG/swpsub,tupeloTS/grittynashville,sabon/great-balls-of-fire,mavidser/Telescope,aichane/digigov,StEight/Telescope,lewisnyman/Telescope,STANAPO/Telescope,WeAreWakanda/telescope,faaez/Telescope,eruwinu/presto,Leeibrah/telescope,evilhei/itForum,basemm911/questionsociety,Discordius/Telescope,danieltynerbryan/ProductNews,geoclicks/Telescope,TodoTemplates/Telescope,lpatmo/cb2,hoihei/Telescope,dominictracey/Telescope,sethbonnie/StartupNews,ryeskelton/Telescope,covernal/Telescope,SachaG/fundandexit,wduntak/tibetalk,xamfoo/change-route-in-iron-router,capensisma/Asteroid,nishanbose/Telescope,parkeasz/Telescope,faaez/Telescope,bengott/Telescope,SachaG/Gamba,MeteorHudsonValley/Telescope,sophearak/Telescope,Alekzanther/LawScope,nathanmelenbrink/theRecord,yourcelf/Telescope,Discordius/Lesswrong2,Healdb/Telescope,SachaG/Gamba,azukiapp/Telescope,veerjainATgmail/Telescope,zires/Telescope,jonmc12/heypsycho,sabon/great-balls-of-fire,guillaumj/Telescope,capensisma/Asteroid,jamesrhymer/iwishcitiescould,acidsound/Telescope,edjv711/presto,sabon/great-balls-of-fire,Discordius/Telescope,codebuddiesdotorg/cb-v2,tylermalin/Screenings,silky/GitXiv,lpatmo/cb-links,jonmc12/heypsycho,VulcanJS/Vulcan,lpatmo/cb2,sdeveloper/Telescope,georules/iwishcitiescould,enginbodur/TelescopeLatest,rtluu/immersive,kakedis/Telescope,johndpark/Telescope,Healdb/Telescope,johndpark/Telescope,wangleihd/Telescope,TelescopeJS/Screenings,aichane/digigov,SSOCIETY/webpages,xamfoo/change-route-in-iron-router,dima7b/stewardsof,queso/Telescope,zarkem/ironhacks,Healdb/Telescope,sungwoncho/Telescope,iraasta/quickformtest,Air2air/Telescope,JstnEdr/Telescope,silky/GitXiv,eruwinu/presto,STANAPO/Telescope,sethbonnie/StartupNews,caglarsayin/Telescope,zires/Telescope,julienlapointe/telescope-nova-social-news,zarkem/ironhacks,nathanmelenbrink/theRecord,aichane/digigov,Eynaliyev/Screenings,aykutyaman/Telescope,ahmadassaf/Telescope,bengott/Telescope,tylermalin/Screenings,tommytwoeyes/Telescope,danieltynerbryan/ProductNews,caglarsayin/Telescope,bharatjilledumudi/india-shop,Leeibrah/telescope,zires/Telescope,geverit4/Telescope,rizakaynak/Telescope,cloudunicorn/fundandexit,gzingraf/GreenLight-Pix,Alekzanther/LawScope,Daz2345/dhPulse,parkeasz/Telescope,bharatjilledumudi/StockX,sdeveloper/Telescope,WeAreWakanda/telescope,TelescopeJS/Screenings,LuisHerranz/Telescope,cydoval/Telescope,sing1ee/Telescope,georules/iwishcitiescould,mr1azl/Telescope,tepk/Telescope,wduntak/tibetalk,guillaumj/Telescope,silky/GitXiv,ahmadassaf/Telescope,manriquef/Vulcan,SachaG/Zensroom,geverit4/Telescope,metstrike/Telescope,Discordius/Lesswrong2,aykutyaman/Telescope,johndpark/Telescope,lpatmo/cb-links,IQ2022/Telescope,youprofit/Telescope,jbschaff/StartupNews,veerjainATgmail/Telescope,mr1azl/Telescope,bharatjilledumudi/StockX,azukiapp/Telescope,basemm911/questionsociety,pombredanne/Telescope,iraasta/quickformtest,delgermurun/Telescope,acidsound/Telescope,queso/Telescope,dima7b/stewardsof,SachaG/bjjbot,TribeMedia/Screenings,VulcanJS/Vulcan,SachaG/Zensroom,azukiapp/Telescope,tepk/Telescope,jbschaff/StartupNews,eruwinu/presto,dominictracey/Telescope,xamfoo/change-route-in-iron-router,sophearak/Telescope,Discordius/Lesswrong2,nathanmelenbrink/theRecord,sungwoncho/Telescope,wende/quickformtest,youprofit/Telescope,wangleihd/Telescope,adhikariaman01/Telescope,SachaG/bjjbot,Leeibrah/telescope,IQ2022/Telescope,SachaG/swpsub,ibrahimcesar/Screenings,jrmedia/oilgas,julienlapointe/telescope-nova-social-news,dima7b/stewardsof,simbird/Test,cloudunicorn/fundandexit,mavidser/Telescope,caglarsayin/Telescope,NodeJSBarenko/Telescope,TribeMedia/Telescope,wunderkraut/WunderShare,cydoval/Telescope,nishanbose/Telescope,ryeskelton/Telescope,simbird/Test,IQ2022/Telescope,rtluu/immersive,delgermurun/Telescope,Daz2345/dhPulse,metstrike/Telescope,jamesrhymer/iwishcitiescould,arbfay/Telescope,MeteorHudsonValley/Telescope,tepk/Telescope,SSOCIETY/webpages,Code-for-Miami/miami-graph-telescope,TribeMedia/Screenings,edjv711/presto,mavidser/Telescope,pombredanne/Telescope,aozora/Telescope,samim23/GitXiv,bshenk/projectIterate,evilhei/itForum,bengott/Telescope,sophearak/Telescope,edjv711/presto,dominictracey/Telescope,Scalingo/Telescope,yourcelf/Telescope,huaiyudavid/rentech,Discordius/Lesswrong2,wduntak/tibetalk,SachaG/swpsub,Air2air/Telescope,HelloMeets/HelloMakers,wunderkraut/WunderShare,hoihei/Telescope,mr1azl/Telescope,TodoTemplates/Telescope,Daz2345/dhPulse,tupeloTS/telescopety,tupeloTS/grittynashville,capensisma/Asteroid,sdeveloper/Telescope,tommytwoeyes/Telescope,STANAPO/Telescope,SachaG/fundandexit,Code-for-Miami/miami-graph-telescope,jbschaff/StartupNews,TribeMedia/Telescope,kakedis/Telescope,kakedis/Telescope,Daz2345/Telescope,wunderkraut/WunderShare,JstnEdr/Telescope,SachaG/Gamba,gzingraf/GreenLight-Pix,jonmc12/heypsycho,Alekzanther/LawScope,rtluu/immersive,maxtor3569/Telescope,aozora/Telescope,bharatjilledumudi/StockX,msavin/Telescope,nhlennox/gbjobs,tommytwoeyes/Telescope,tylermalin/Screenings,automenta/sernyl,msavin/Telescope,codebuddiesdotorg/cb-v2,geverit4/Telescope,cloudunicorn/fundandexit,huaiyudavid/rentech,iraasta/quickformtest,sing1ee/Telescope,Daz2345/Telescope,Eynaliyev/Screenings,enginbodur/TelescopeLatest,faaez/Telescope,simbird/Test,sing1ee/Telescope,sethbonnie/StartupNews,ryeskelton/Telescope,metstrike/Telescope,almogdesign/Telescope,tupeloTS/telescopety,automenta/sernyl,Code-for-Miami/miami-graph-telescope,rizakaynak/Telescope,arbfay/Telescope,lpatmo/cb-links,almogdesign/Telescope,NodeJSBarenko/Telescope,Discordius/Telescope,bharatjilledumudi/india-shop,delgermurun/Telescope,wende/quickformtest,Discordius/Telescope,julienlapointe/telescope-nova-social-news,zarkem/ironhacks,lewisnyman/Telescope,lewisnyman/Telescope,SSOCIETY/webpages,lpatmo/cb2,basemm911/questionsociety,automenta/sernyl,em0ney/Telescope,em0ney/Telescope,em0ney/Telescope,LuisHerranz/Telescope,Daz2345/Telescope,samim23/GitXiv,Air2air/Telescope,parkeasz/Telescope,bharatjilledumudi/india-shop,Eynaliyev/Screenings,ibrahimcesar/Screenings,SachaG/fundandexit,geoclicks/Telescope,covernal/Telescope,yourcelf/Telescope,acidsound/Telescope,georules/iwishcitiescould,queso/Telescope,arbfay/Telescope,nishanbose/Telescope,WeAreWakanda/telescope,aozora/Telescope,SachaG/bjjbot,cydoval/Telescope,danieltynerbryan/ProductNews,LuisHerranz/Telescope,samim23/GitXiv,ahmadassaf/Telescope,msavin/Telescope,bshenk/projectIterate,adhikariaman01/Telescope,gzingraf/GreenLight-Pix,HelloMeets/HelloMakers,wangleihd/Telescope,veerjainATgmail/Telescope,jrmedia/oilgas,codebuddiesdotorg/cb-v2 | ---
+++
@@ -7,11 +7,14 @@
Telescope.config.preloadSubscriptions.push('pages');
PageController = RouteController.extend({
+ currentPage: function () {
+ return Pages.collection.findOne({slug: this.params.slug});
+ },
getTitle: function () {
- return Pages.collection.findOne({slug: this.params.slug}).title;
+ return this.currentPage() && this.currentPage().title;
},
data: function () {
- return Pages.collection.findOne({slug: this.params.slug});
+ return this.currentPage();
}
});
|
9a2f2f3110d6aaa67fe7ac63d3f96bdd83636f21 | app/utils/constants.js | app/utils/constants.js | import packageJson from './package.json';
module.exports = {
backendRoot: 'https://obscure-woodland-71302.herokuapp.com/',
flaskRoot: 'http://localhost:5000',
/* flaskRoot: 'http://catapp-staging.herokuapp.com/',*/
/* graphQLRoot: (process.env.NODE_ENV !== 'production') ? '//localhost:5000/graphql' : '//catappdatabase.herokuapp.com/graphql', */
graphQLRoot: '//catappdatabase.herokuapp.com/graphql',
newGraphQLRoot: '//catappdatabase2.herokuapp.com/graphql',
whiteLabel: false,
suBranding: false,
appBar: true,
version: packageJson.version,
gaTrackingId: 'UA-109061730-1',
apps: [
{
title: 'Activity Maps',
route: '/activityMaps',
}, {
title: 'AtoML',
}, {
title: 'CatKit Slab Generator',
route: '/catKitDemo',
}, {
title: 'GraphiQL Console',
route: '/graphQLConsole',
}, {
title: 'Pourbaix Diagrams',
}, {
title: 'Publications',
route: '/publications',
}, {
title: 'Scaling Relations',
}, {
/* title: 'Upload Datasets',*/
/* route: '/upload',*/
/* }, {*/
title: 'Wyckoff Bulk Generator',
route: '/bulkGenerator',
}, {
title: 'Your Next App ...',
route: '/yourNextApp',
},
],
};
| import packageJson from './package.json';
module.exports = {
backendRoot: 'https://obscure-woodland-71302.herokuapp.com/',
/* flaskRoot: 'http://localhost:5000',*/
flaskRoot: 'http://catapp-staging.herokuapp.com/',
/* graphQLRoot: (process.env.NODE_ENV !== 'production') ? '//localhost:5000/graphql' : '//catappdatabase.herokuapp.com/graphql', */
graphQLRoot: '//catappdatabase.herokuapp.com/graphql',
newGraphQLRoot: '//catappdatabase2.herokuapp.com/graphql',
whiteLabel: false,
suBranding: false,
appBar: true,
version: packageJson.version,
gaTrackingId: 'UA-109061730-1',
apps: [
{
title: 'Activity Maps',
route: '/activityMaps',
}, {
title: 'AtoML',
}, {
title: 'CatKit Slab Generator',
route: '/catKitDemo',
}, {
title: 'GraphiQL Console',
route: '/graphQLConsole',
}, {
title: 'Pourbaix Diagrams',
}, {
title: 'Publications',
route: '/publications',
}, {
title: 'Scaling Relations',
}, {
/* title: 'Upload Datasets',*/
/* route: '/upload',*/
/* }, {*/
title: 'Wyckoff Bulk Generator',
route: '/bulkGenerator',
}, {
title: 'Your Next App ...',
route: '/yourNextApp',
},
],
};
| Put all URLs to public | Put all URLs to public
| JavaScript | mit | mhoffman/CatAppBrowser,mhoffman/CatAppBrowser | ---
+++
@@ -2,8 +2,8 @@
module.exports = {
backendRoot: 'https://obscure-woodland-71302.herokuapp.com/',
- flaskRoot: 'http://localhost:5000',
- /* flaskRoot: 'http://catapp-staging.herokuapp.com/',*/
+ /* flaskRoot: 'http://localhost:5000',*/
+ flaskRoot: 'http://catapp-staging.herokuapp.com/',
/* graphQLRoot: (process.env.NODE_ENV !== 'production') ? '//localhost:5000/graphql' : '//catappdatabase.herokuapp.com/graphql', */
graphQLRoot: '//catappdatabase.herokuapp.com/graphql',
newGraphQLRoot: '//catappdatabase2.herokuapp.com/graphql', |
82da6073179d7c4107c313093d6c2cab88e017fc | server/sessions/sessionsController.js | server/sessions/sessionsController.js | var Session = require( './sessions' );
module.exports = {
getAllSessions: function(request, response) {
Session.findAll()
.then( function(sessions) {
response.send(sessions);
})
},
addSession: function(request, response) {
var sessionName = request.body.sessionName;
Session.create( {
sessionName: sessionName
} ).then( function() {
response.status = 201;
response.end();
} )
}
};
| var helpers = require( '../config/helpers' );
var Session = require( './sessions' );
module.exports = {
getAllSessions: function( reqw, res, next ) {
Session.findAll()
.then( function( sessions ) {
response.send( sessions );
})
},
addSession: function( req, res, next ) {
var sessionName = request.body.sessionName;
Session.create( {
sessionName: sessionName
} ).then( function() {
response.status = 201;
response.end();
} )
},
getSessionByName: function( req, res, next ) {
var sessionName = request.params.sessionName;
Session.findOne( { where: { sessionName: sessionName } } )
.then( function( session ) {
response.json( session );
}, function( err ) {
helpers.errorHandler( err, request, response, next );
});
}
};
| Add endpoint for retrieving a single session | Add endpoint for retrieving a single session
| JavaScript | mpl-2.0 | CantillatingZygote/rubiginouschanticleer,RubiginousChanticleer/rubiginouschanticleer,RubiginousChanticleer/rubiginouschanticleer,CantillatingZygote/rubiginouschanticleer | ---
+++
@@ -1,15 +1,16 @@
+var helpers = require( '../config/helpers' );
var Session = require( './sessions' );
module.exports = {
- getAllSessions: function(request, response) {
+ getAllSessions: function( reqw, res, next ) {
Session.findAll()
- .then( function(sessions) {
- response.send(sessions);
+ .then( function( sessions ) {
+ response.send( sessions );
})
},
- addSession: function(request, response) {
+ addSession: function( req, res, next ) {
var sessionName = request.body.sessionName;
Session.create( {
@@ -18,6 +19,17 @@
response.status = 201;
response.end();
} )
+ },
+
+ getSessionByName: function( req, res, next ) {
+ var sessionName = request.params.sessionName;
+
+ Session.findOne( { where: { sessionName: sessionName } } )
+ .then( function( session ) {
+ response.json( session );
+ }, function( err ) {
+ helpers.errorHandler( err, request, response, next );
+ });
}
}; |
44160a484f20585b95dd034f4a40c5138cac0c45 | hobbes/extensions.js | hobbes/extensions.js | require('./extensions/es5');
require('./extensions/json');
// Based on Crockford's http://javascript.crockford.com/inheritance.html
if (!Function.prototype.inherits) {
Function.prototype.inherits = function (parent) {
// Use new instance of parent as prototype
var d = {}, p = (this.prototype = new parent());
this.prototype['uber'] = function (name) {
if (!(name in d)) {
d[name] = 0;
}
var f, r, t = d[name], v = parent.prototype;
if (t) {
while (t) {
v = v.constructor.prototype;
t -= 1;
}
f = v[name];
} else {
f = p[name];
if (f == this[name]) {
f = v[name];
}
}
d[name] += 1;
r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
d[name] -= 1;
return r;
};
// copy constructor members
for (var prop in parent) {
if (parent.hasOwnProperty(prop)) {
this[prop] = parent[prop];
}
}
// fix constructor reference
this.prototype.constructor = this;
return this;
}
}
| require('./extensions/es5');
require('./extensions/json');
// Based on Crockford's http://javascript.crockford.com/inheritance.html
if (!Function.prototype.inherits) {
Function.prototype.inherits = function (parent, constructorMembers) {
// Use new instance of parent as prototype
var d = {}, p = (this.prototype = new parent());
this.prototype['uber'] = function (name) {
if (!(name in d)) {
d[name] = 0;
}
var f, r, t = d[name], v = parent.prototype;
if (t) {
while (t) {
v = v.constructor.prototype;
t -= 1;
}
f = v[name];
} else {
f = p[name];
if (f == this[name]) {
f = v[name];
}
}
d[name] += 1;
r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
d[name] -= 1;
return r;
};
// copy constructor members
for (var prop in parent) {
if (parent.hasOwnProperty(prop)) {
this[prop] = parent[prop];
}
}
// prefill constructor members
if (constructorMembers) {
for (var prop in constructorMembers) this[prop] = constructorMembers[prop];
}
// fix constructor reference
this.prototype.constructor = this;
return this;
}
}
| Add optional initialization hash to `inherits` | Add optional initialization hash to `inherits`
| JavaScript | mit | knuton/hobbes,knuton/hobbes,knuton/hobbes,knuton/hobbes | ---
+++
@@ -3,7 +3,7 @@
// Based on Crockford's http://javascript.crockford.com/inheritance.html
if (!Function.prototype.inherits) {
- Function.prototype.inherits = function (parent) {
+ Function.prototype.inherits = function (parent, constructorMembers) {
// Use new instance of parent as prototype
var d = {}, p = (this.prototype = new parent());
this.prototype['uber'] = function (name) {
@@ -34,6 +34,10 @@
this[prop] = parent[prop];
}
}
+ // prefill constructor members
+ if (constructorMembers) {
+ for (var prop in constructorMembers) this[prop] = constructorMembers[prop];
+ }
// fix constructor reference
this.prototype.constructor = this;
return this; |
7b7739a4df8788cb1f163e0ad8fedf01f0a55071 | app/js/app.js | app/js/app.js | window.ContactManager = {
Models: {},
Collections: {},
Views: {},
start: function(data) {
var contacts = new ContactManager.Collections.Contacts(data.contacts),
router = new ContactManager.Router();
router.on('route:home', function() {
router.navigate('contacts', {
trigger: true,
replace: true
});
});
router.on('route:showContacts', function() {
var contactsView = new ContactManager.Views.Contacts({
collection: contacts
});
$('.main-container').html(contactsView.render().$el);
});
router.on('route:newContact', function() {
var newContactForm = new ContactManager.Views.ContactForm();
$('.main-container').html(newContactForm.render().$el);
});
router.on('route:editContact', function(id) {
console.log('Edit contact');
});
Backbone.history.start();
}
};
| window.ContactManager = {
Models: {},
Collections: {},
Views: {},
start: function(data) {
var contacts = new ContactManager.Collections.Contacts(data.contacts),
router = new ContactManager.Router();
router.on('route:home', function() {
router.navigate('contacts', {
trigger: true,
replace: true
});
});
router.on('route:showContacts', function() {
var contactsView = new ContactManager.Views.Contacts({
collection: contacts
});
$('.main-container').html(contactsView.render().$el);
});
router.on('route:newContact', function() {
var newContactForm = new ContactManager.Views.ContactForm();
newContactForm.on('form:submitted', function(attrs) {
attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1);
contacts.add(attrs);
router.navigate('contacts', true);
});
$('.main-container').html(newContactForm.render().$el);
});
router.on('route:editContact', function(id) {
console.log('Edit contact');
});
Backbone.history.start();
}
};
| Add new contact on form submitted | Add new contact on form submitted
| JavaScript | mit | dmytroyarmak/backbone-contact-manager,SomilKumar/backbone-contact-manager,EaswarRaju/angular-contact-manager,vinnu-313/backbone-contact-manager,SomilKumar/backbone-contact-manager,giastfader/backbone-contact-manager,vinnu-313/backbone-contact-manager,hrundik/angular-contact-manager,giastfader/backbone-contact-manager,hrundik/angular-contact-manager,hrundik/angular-contact-manager | ---
+++
@@ -25,6 +25,12 @@
router.on('route:newContact', function() {
var newContactForm = new ContactManager.Views.ContactForm();
+ newContactForm.on('form:submitted', function(attrs) {
+ attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1);
+ contacts.add(attrs);
+ router.navigate('contacts', true);
+ });
+
$('.main-container').html(newContactForm.render().$el);
});
|
15ee70dd5bfaa06eedfda8a75f6c7c796c6bbd2a | bot/utilities/media.js | bot/utilities/media.js | var settings = require(process.cwd() + '/settings.js').settings;
var request = require('request');
module.exports.currentLink = "";
module.exports.currentName = "";
module.exports.currentID = "";
module.exports.currentType = "";
module.exports.currentDJName = "";
module.exports.getLink = function(bot, callback) {
var media = bot.getMedia();
if(!media) return callback();
if(media.type === 'soundcloud') {
var options = {
url: 'https://api.soundcloud.com/tracks/' + media.fkid + '.json?client_id=' + settings.SOUNDCLOUDID
};
var responseBack = function(error, response, body) {
if(!error){
var body = JSON.parse(body);
return callback(body.permalink_url);
}
else {
bot.log("info", "BOT", "Soundcloud Error: " + error);
return callback('Error... http://google.com');
}
}
request(options, responseBack);
}
else {
return callback('http://www.youtube.com/watch?v=' + media.fkid);
}
}; | var settings = require(process.cwd() + '/settings.js').settings;
var request = require('request');
module.exports.currentLink = "";
module.exports.currentName = "";
module.exports.currentID = "";
module.exports.currentType = "";
module.exports.currentDJName = "";
module.exports.getLink = function(bot, callback) {
var media = bot.getMedia();
if(!media) return callback();
if(media.type === 'soundcloud') {
var options = {
url: 'https://api.soundcloud.com/tracks/' + media.fkid + '.json?client_id=' + settings.SOUNDCLOUDID
};
var responseBack = function(error, response, body) {
if(!error){
try{
var json = JSON.parse(body);
return callback(json.permalink_url);
}
catch(e){
bot.log("error", "BOT", "Soundcloud API error fetching song! Could be caused by invalid Soundcloud API key");
return callback('https://api.dubtrack.fm/song/' + media.id + '/redirect');
}
}
else {
bot.log("error", "BOT", "Soundcloud Error: " + error);
return callback('https://api.dubtrack.fm/song/' + media.id + '/redirect');
}
};
request(options, responseBack);
}
else {
return callback('http://www.youtube.com/watch?v=' + media.fkid);
}
}; | Add fallback if invalid or no Soundcloud API key is set | Add fallback if invalid or no Soundcloud API key is set
| JavaScript | mit | coryshaw1/SteveBot,the2hill/TonerBot | ---
+++
@@ -19,14 +19,20 @@
var responseBack = function(error, response, body) {
if(!error){
- var body = JSON.parse(body);
- return callback(body.permalink_url);
+ try{
+ var json = JSON.parse(body);
+ return callback(json.permalink_url);
+ }
+ catch(e){
+ bot.log("error", "BOT", "Soundcloud API error fetching song! Could be caused by invalid Soundcloud API key");
+ return callback('https://api.dubtrack.fm/song/' + media.id + '/redirect');
+ }
}
else {
- bot.log("info", "BOT", "Soundcloud Error: " + error);
- return callback('Error... http://google.com');
+ bot.log("error", "BOT", "Soundcloud Error: " + error);
+ return callback('https://api.dubtrack.fm/song/' + media.id + '/redirect');
}
- }
+ };
request(options, responseBack);
} |
061d634b72d081d49532be98e2248f14bf7112d6 | quick-sort.js | quick-sort.js | // Program to sort an array using recursion
function quickSort(arr) {
if(arr.length == 0) {
return [];
}
var left = [], right = [], pivot = arr[0];
for(var i = 1; i < arr.length; i++) {
if(arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat(pivot, quickSort(right));
}
// test case
// expect output to be [1, 2, 3, 4, 5]
console.log(quickSort([5, 4, 3, 2, 1])); | // Program to sort an array using recursion
function quickSort(arr) {
if(arr.length == 0) {
return [];
}
var left = [], right = [], pivot = arr[0];
// compare first element in array to the rest
for(var i = 1; i < arr.length; i++) {
// if element being looked at is less than first element, put it in left array--else put it in right array
if(arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
// apply same loop to left and right arrays (broken down from original array) and merge them with pivot element, where left array lies to the left of pivot element and right array lies to the right of pivot element
return quickSort(left).concat(pivot, quickSort(right));
}
// test case
// expect output to be [1, 2, 3, 4, 5]
console.log(quickSort([5, 4, 3, 2, 1]));
| Add pseudocode to quick sort function | Add pseudocode to quick sort function
| JavaScript | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -1,16 +1,20 @@
// Program to sort an array using recursion
+
function quickSort(arr) {
if(arr.length == 0) {
return [];
}
var left = [], right = [], pivot = arr[0];
+ // compare first element in array to the rest
for(var i = 1; i < arr.length; i++) {
+ // if element being looked at is less than first element, put it in left array--else put it in right array
if(arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
+ // apply same loop to left and right arrays (broken down from original array) and merge them with pivot element, where left array lies to the left of pivot element and right array lies to the right of pivot element
return quickSort(left).concat(pivot, quickSort(right));
}
|
cf2cde301e150254d023068d79d8bcc2e959fb4d | server.js | server.js | /** hapijs default hello world **/
'use strict';
const Hapi = require('hapi');
// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000
});
// Add the route
server.route({
method: 'GET',
path:'/hello',
handler: function (request, reply) {
return reply('hello world');
}
});
// Start the server
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
}); | /** hapijs default hello world **/
'use strict';
const Hapi = require('hapi');
// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
port: 8000
});
// Add the route
server.route({
method: 'GET',
path:'/hello',
handler: function (request, reply) {
return reply('hello world');
}
});
// Start the server
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
}); | Remove host from hapijs so it is not binding to a specific host | Remove host from hapijs so it is not binding to a specific host
| JavaScript | mit | ResistanceCalendar/resistance-calendar-api,ResistanceCalendar/resistance-calendar-api | ---
+++
@@ -7,7 +7,6 @@
// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
- host: 'localhost',
port: 8000
});
|
dbefbfdc2dc8645899c4af16cf0cbcd765070554 | server.js | server.js | <<<<<<< HEAD
var port = process.env.PORT || 8080;
var StaticServer = require('static-server');
var server = new StaticServer({
rootPath: '.', // required, the root of the server file tree
port: port, // optional, defaults to a random port
=======
var StaticServer = require('static-server');
var server = new StaticServer({
rootPath: '.', // required, the root of the server file tree
port: 8080, // optional, defaults to a random port
>>>>>>> 386263d3a6f904dc6ced91fcf8c4cf5bdb2a003b
cors: '*', // optional, defaults to undefined
followSymlink: true, // optional, defaults to a 404 error
});
server.start(function () {
console.log('Server listening to', server.port);
}); | var port = process.env.PORT || 8080;
var StaticServer = require('static-server');
var server = new StaticServer({
rootPath: '.', // required, the root of the server file tree
port: port, // optional, defaults to a random port
cors: '*', // optional, defaults to undefined
followSymlink: true, // optional, defaults to a 404 error
});
server.start(function () {
console.log('Server listening to', server.port);
}); | Use port env to keep heroku happy | Use port env to keep heroku happy
| JavaScript | mit | orangedrink/head-game,orangedrink/head-game | ---
+++
@@ -1,15 +1,8 @@
-<<<<<<< HEAD
var port = process.env.PORT || 8080;
var StaticServer = require('static-server');
var server = new StaticServer({
rootPath: '.', // required, the root of the server file tree
port: port, // optional, defaults to a random port
-=======
-var StaticServer = require('static-server');
-var server = new StaticServer({
- rootPath: '.', // required, the root of the server file tree
- port: 8080, // optional, defaults to a random port
->>>>>>> 386263d3a6f904dc6ced91fcf8c4cf5bdb2a003b
cors: '*', // optional, defaults to undefined
followSymlink: true, // optional, defaults to a 404 error
}); |
8f62c8e39c747e88b28498e1bc44204340479dc5 | server.js | server.js | const path = require('path')
const express = require('express')
const app = express()
const port = process.env.PORT ? process.env.PORT : 8081
const dist = path.join(__dirname, 'public')
function ensureSecure(req, res, next) { // eslint-disable-line
if (req.secure) {
return next()
}
res.redirect(`https://${req.hostname} ${req.url}`)
}
app.use(express.static(dist))
app.all('*', ensureSecure)
app.get('*', (req, res) => {
res.sendFile(path.join(dist, 'index.html'))
})
app.listen(port, (error) => {
if (error) {
console.log(error) // eslint-disable-line no-console
}
console.info('Express is listening on port %s.', port) // eslint-disable-line no-console
})
| const path = require('path')
const express = require('express')
const app = express()
const port = process.env.PORT ? process.env.PORT : 8081
const dist = path.join(__dirname, 'public')
app.use(express.static(dist))
app.all('/*', function (req, res, next) { // eslint-disable-line
if (/^http$/.test(req.protocol)) {
const host = req.headers.host.replace(/:[0-9]+$/g, '') // strip the port # if any
return res.redirect(`https://${host}${req.url}`, 301)
}
return next()
})
app.get('*', (req, res) => {
res.sendFile(path.join(dist, 'index.html'))
})
app.listen(port, (error) => {
if (error) {
console.log(error) // eslint-disable-line no-console
}
console.info('Express is listening on port %s.', port) // eslint-disable-line no-console
})
| Update ensure secure express middleware | Update ensure secure express middleware
| JavaScript | mit | developer239/workbox-webpack-react,developer239/workbox-webpack-react | ---
+++
@@ -7,16 +7,16 @@
const dist = path.join(__dirname, 'public')
-function ensureSecure(req, res, next) { // eslint-disable-line
- if (req.secure) {
- return next()
+app.use(express.static(dist))
+
+app.all('/*', function (req, res, next) { // eslint-disable-line
+ if (/^http$/.test(req.protocol)) {
+ const host = req.headers.host.replace(/:[0-9]+$/g, '') // strip the port # if any
+ return res.redirect(`https://${host}${req.url}`, 301)
}
- res.redirect(`https://${req.hostname} ${req.url}`)
-}
-
-app.use(express.static(dist))
-app.all('*', ensureSecure)
+ return next()
+})
app.get('*', (req, res) => {
res.sendFile(path.join(dist, 'index.html')) |
ef0394aa91480462ebee8857d2f35fdd40402c9a | app/assets/javascripts/conversations.js | app/assets/javascripts/conversations.js | var conversations = {
onRespondLaterClick: function() {
var $listItem = $(this).parents('.conversation-row').parent();
var path = $(this).attr('data-account-conversation-path');
var pushToEndOfQueue = function() {
var $list = $listItem.parent();
$listItem.remove().appendTo($list);
}
$.post(path, { conversation: { respond_later: true }, _method: 'patch' }, pushToEndOfQueue);
return false;
},
onArchiveClick: function() {
var $listItem = $(this).parents('.conversation-row').parent();
var path = $(this).attr('data-account-conversation-path');
var removeFromQueue = function() {
if ($listItem.siblings().length == 0) {
$('.empty-state').show();
}
$listItem.remove();
}
$.post(path, { conversation: { archive: true }, _method: 'patch' }, removeFromQueue);
return false;
}
}
$(document).on("ready", function(){
$('.list').delegate('.respond-later', 'click', conversations.onRespondLaterClick);
$('.list').delegate('.archive', 'click', conversations.onArchiveClick);
$("textarea[data-autosize]").autosize();
$('.participants-expand-icon').click(function () {
$('.participants-list', $(this).closest('.detail')).toggle();
$(this).toggleClass('expanded');
});
});
| var conversations = {
onRespondLaterClick: function() {
var $listItem = $(this).parents('.conversation-row').parent();
var path = $(this).attr('data-account-conversation-path');
var pushToEndOfQueue = function() {
var $list = $listItem.parent();
$listItem.remove().appendTo($list);
}
$.post(path, { conversation: { respond_later: true }, _method: 'patch' }, pushToEndOfQueue);
return false;
},
onArchiveClick: function() {
var $listItem = $(this).parents('.conversation-row').parent();
var path = $(this).attr('data-account-conversation-path');
var removeFromQueue = function() {
if ($listItem.siblings().length == 0) {
$('.empty-state').show();
}
$listItem.remove();
}
$.post(path, { conversation: { archive: true }, _method: 'patch' }, removeFromQueue);
return false;
}
}
$(document).on("ready", function() {
$('.list').delegate('.respond-later', 'click', conversations.onRespondLaterClick);
$('.list').delegate('.archive', 'click', conversations.onArchiveClick);
});
$(document).on('ready page:load', function() {
$("textarea[data-autosize]").autosize();
$('.participants-expand-icon').click(function () {
$('.participants-list', $(this).closest('.detail')).toggle();
$(this).toggleClass('expanded');
});
});
| Make sure the info button works with turbolinks | Make sure the info button works with turbolinks
| JavaScript | agpl-3.0 | asm-helpful/helpful-web,asm-helpful/helpful-web,asm-helpful/helpful-web,asm-helpful/helpful-web | ---
+++
@@ -30,9 +30,12 @@
}
}
-$(document).on("ready", function(){
+$(document).on("ready", function() {
$('.list').delegate('.respond-later', 'click', conversations.onRespondLaterClick);
$('.list').delegate('.archive', 'click', conversations.onArchiveClick);
+});
+
+$(document).on('ready page:load', function() {
$("textarea[data-autosize]").autosize();
$('.participants-expand-icon').click(function () { |
9a6ce516d1e96f5c9f5d54e07f94a9d68783ec4d | app/components/partials/Footer/index.js | app/components/partials/Footer/index.js | import React from 'react';
const styles = {
footer: {
padding: '10px',
position: 'fixed',
left: '0px',
bottom: '0px',
height: '45px',
width: '100%',
background: 'linear-gradient(rgba(255, 255, 255, 0.75), rgba(255, 255, 255, 1))',
},
};
function Footer() {
return (
<footer style={styles.footer}>
© Ruah Logistics
</footer>
);
}
export default Footer;
| import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';
const styles = {
footer: {
padding: '5px',
position: 'fixed',
left: '0px',
display: 'flex',
flexDirection: 'row',
bottom: '0px',
height: '50px',
width: '100%',
background: 'linear-gradient(rgba(255, 255, 255, 0.75), rgba(255, 255, 255, 1))',
},
};
export default class Footer extends React.Component {
state = {
modalOpen: false,
}
render() {
return (
<footer style={styles.footer}>
<div style={{ padding: '5px' }}>© Ruah Logistics</div>
<div style={{ flex: 1 }} > </div>
<FlatButton onTouchTap={() => this.setState({ modalOpen: true })}>Support</FlatButton>
<Dialog
title="Getting Help"
modal={false}
open={this.state.modalOpen}
onRequestClose={() => this.setState({ modalOpen: false })}
>
For all support issues email aaron@teamruah.com with a description of your issue. You can expect to hear back within 30 minutes of emailing.
</Dialog>
</footer>
);
}
}
| Support button in the footer | Support button in the footer
| JavaScript | mit | aaronlangford31/ruah-web,aaronlangford31/ruah-web | ---
+++
@@ -1,23 +1,41 @@
import React from 'react';
+import FlatButton from 'material-ui/FlatButton';
+import Dialog from 'material-ui/Dialog';
const styles = {
footer: {
- padding: '10px',
+ padding: '5px',
position: 'fixed',
left: '0px',
+ display: 'flex',
+ flexDirection: 'row',
bottom: '0px',
- height: '45px',
+ height: '50px',
width: '100%',
background: 'linear-gradient(rgba(255, 255, 255, 0.75), rgba(255, 255, 255, 1))',
},
};
-function Footer() {
- return (
- <footer style={styles.footer}>
- © Ruah Logistics
- </footer>
- );
+export default class Footer extends React.Component {
+ state = {
+ modalOpen: false,
+ }
+
+ render() {
+ return (
+ <footer style={styles.footer}>
+ <div style={{ padding: '5px' }}>© Ruah Logistics</div>
+ <div style={{ flex: 1 }} > </div>
+ <FlatButton onTouchTap={() => this.setState({ modalOpen: true })}>Support</FlatButton>
+ <Dialog
+ title="Getting Help"
+ modal={false}
+ open={this.state.modalOpen}
+ onRequestClose={() => this.setState({ modalOpen: false })}
+ >
+ For all support issues email aaron@teamruah.com with a description of your issue. You can expect to hear back within 30 minutes of emailing.
+ </Dialog>
+ </footer>
+ );
+ }
}
-
-export default Footer; |
0a3cf3af3f6be773a2bbd56e4f6f8e28e7b07e77 | web/jasmine/spec/specIntelliasTest.js | web/jasmine/spec/specIntelliasTest.js | describe("Checking correctly data in object projects", function() {
it("Length of object should to equal 4", function() {
expect(projects.length).toEqual(4)
});
var i = 0;
while(i < projects.length) {
(function (project) {
it('project "' + project.name + '" should be active', function () {
expect(project.active).toBe(true);
});
it('project "' + projects[i].name + '" should contain users', function () {
expect(project.users.length).toBeGreaterThan(0)
});
})(projects[i]);
i++;
}
it('Estimate for project "' + projects[1].name + '" should to be less than 2000', function() {
expect(projects[1].estimate).toBeLessThan(1500)
});
});
describe("Jquery Jasmine test", function() {
beforeEach(function () {
loadFixtures('test.html');
});
it('This document should contain id container ', function() {
expect($('#container')).toBeDefined();
});
it('Header should contain tag "h1" ', function() {
expect($('.header').find("h1")).toBeDefined();
});
it('h1 should contain text "Intellias" ', function() {
expect($('.header').find("h1").text().match(/Intellias/i)).toBeDefined();
});
});
| Deploy functionality related with testing. | Deploy functionality related with testing.
| JavaScript | mit | sfedyna/test-intellias,sfedyna/test-intellias,sfedyna/test-intellias | ---
+++
@@ -1,3 +1,50 @@
+describe("Checking correctly data in object projects", function() {
+
+ it("Length of object should to equal 4", function() {
+ expect(projects.length).toEqual(4)
+ });
+
+ var i = 0;
+ while(i < projects.length) {
+ (function (project) {
+
+ it('project "' + project.name + '" should be active', function () {
+ expect(project.active).toBe(true);
+ });
+
+ it('project "' + projects[i].name + '" should contain users', function () {
+ expect(project.users.length).toBeGreaterThan(0)
+ });
+
+ })(projects[i]);
+
+ i++;
+ }
+
+ it('Estimate for project "' + projects[1].name + '" should to be less than 2000', function() {
+ expect(projects[1].estimate).toBeLessThan(1500)
+ });
+});
+describe("Jquery Jasmine test", function() {
+beforeEach(function () {
+ loadFixtures('test.html');
+});
+
+it('This document should contain id container ', function() {
+ expect($('#container')).toBeDefined();
+});
+
+it('Header should contain tag "h1" ', function() {
+ expect($('.header').find("h1")).toBeDefined();
+});
+
+it('h1 should contain text "Intellias" ', function() {
+ expect($('.header').find("h1").text().match(/Intellias/i)).toBeDefined();
+});
+
+});
+
+ | |
3836a6ede8f391a1039dd1aed2b82674bc1f94b5 | assets/js/main.js | assets/js/main.js | function setStyle(style) {
var range, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand(style, false, null);
document.designMode = "off";
}
}
Mousetrap.bind('mod+b', function(e) {
e.preventDefault();
setStyle("bold");
});
Mousetrap.bind('mod+i', function(e) {
e.preventDefault();
setStyle("italic");
});
Mousetrap.bind('mod+u', function(e) {
e.preventDefault();
setStyle("underline");
});
| function setStyle(style, param) {
var range, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand(style, false, param);
document.designMode = "off";
}
}
Mousetrap.bind('mod+b', function(e) {
e.preventDefault();
setStyle("bold");
});
Mousetrap.bind('mod+i', function(e) {
e.preventDefault();
setStyle("italic");
});
Mousetrap.bind('mod+u', function(e) {
e.preventDefault();
setStyle("underline");
});
function addImage(e) {
e.stopPropagation();
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
setStyle("insertImage", event.target.result);
};
reader.readAsDataURL(file);
}
var pad = document.getElementById('pad');
pad.addEventListener('drop', addImage, false);
| Add function to add images by draggin from desktop | Add function to add images by draggin from desktop
| JavaScript | mit | guilhermecomum/minimal-editor | ---
+++
@@ -1,4 +1,4 @@
-function setStyle(style) {
+function setStyle(style, param) {
var range, sel;
if (window.getSelection) {
@@ -11,7 +11,7 @@
sel.removeAllRanges();
sel.addRange(range);
}
- document.execCommand(style, false, null);
+ document.execCommand(style, false, param);
document.designMode = "off";
}
}
@@ -30,3 +30,20 @@
e.preventDefault();
setStyle("underline");
});
+
+function addImage(e) {
+ e.stopPropagation();
+ e.preventDefault();
+
+ var file = e.dataTransfer.files[0],
+ reader = new FileReader();
+
+ reader.onload = function (event) {
+ setStyle("insertImage", event.target.result);
+ };
+
+ reader.readAsDataURL(file);
+}
+
+var pad = document.getElementById('pad');
+pad.addEventListener('drop', addImage, false); |
d2337b21a2378d9ffb0243534338c8092ff78e63 | src/app/services/navigationService.js | src/app/services/navigationService.js | 'use strict';
var angular = require('angular');
module.exports = angular.module('myApp.services.navigationService', [
])
.service('NavigationService', function (
) {
return {
getMainNavItems: function () {
return [
{
title: 'Projects',
url: '/#/',
path: '/'
},
{
title: 'About',
url: '/#/about',
path: '/about'
},
{
title: 'Resume',
url: 'http://bit.ly/1cGjA8X'
}
];
}
};
});
| 'use strict';
var angular = require('angular');
module.exports = angular.module('myApp.services.navigationService', [
])
.service('NavigationService', function (
) {
return {
getMainNavItems: function () {
return [
{
title: 'Projects',
url: '/#/',
path: '/'
},
{
title: 'About',
url: '/#/about',
path: '/about'
},
{
title: 'Play',
url: '/#/play',
path: '/play'
},
{
title: 'Resume',
url: 'http://bit.ly/1cGjA8X'
}
];
}
};
});
| Add play to the navigation | Add play to the navigation
| JavaScript | mit | SirKettle/myPortfolio,SirKettle/myPortfolio | ---
+++
@@ -20,6 +20,11 @@
path: '/about'
},
{
+ title: 'Play',
+ url: '/#/play',
+ path: '/play'
+ },
+ {
title: 'Resume',
url: 'http://bit.ly/1cGjA8X'
} |
5b50833ca0595d0939d53e54dc289910431dbeb7 | src/app/Chat/Message/MessageResult.js | src/app/Chat/Message/MessageResult.js | /* @flow */
import React from 'react'
import type { MessageResult } from 'types'
import styles from './style.css'
type RollsProps = {
rolls: Array<number>
}
const Rolls = (props: RollsProps) => {
return <span>
{props.rolls.map((roll, i, arr) => (
<span>
<span className={styles.roll}>
{ roll }
</span>
{(i + 1 !== arr.length) ? ' + ' : null}
</span>
))}
</span>
}
type ModProps = {
mod: number
}
const Mod = (props: ModProps) => {
if (props.mod == 0) {
return null
}
return <span>
{' + '}
<span className={styles.mod}>{props.mod}</span>
</span>
}
type Props = {
result: ?MessageResult
}
const Result = (props: Props) => {
if (!props.result) {
return null
}
let { mod, rolls, total } = props.result
return (
<div className={styles.result}>
<Rolls rolls={rolls} />
<Mod mod={mod} />
{' = '}
<span className={styles.total}>{total}</span>
</div>
)
}
export default Result
| /* @flow */
import React from 'react'
import type { MessageResult } from 'types'
import styles from './style.css'
type RollsProps = {
rolls: Array<number>
}
const Rolls = (props: RollsProps) => {
return <span>
{props.rolls.map((roll, i, arr) => (
<span key={i}>
<span className={styles.roll}>
{ roll }
</span>
{(i + 1 !== arr.length) ? ' + ' : null}
</span>
))}
</span>
}
type ModProps = {
mod: number
}
const Mod = (props: ModProps) => {
if (props.mod == 0) {
return null
}
return <span>
{' + '}
<span className={styles.mod}>{props.mod}</span>
</span>
}
type Props = {
result: ?MessageResult
}
const Result = (props: Props) => {
if (!props.result) {
return null
}
let { mod, rolls, total } = props.result
return (
<div className={styles.result}>
<Rolls rolls={rolls} />
<Mod mod={mod} />
{' = '}
<span className={styles.total}>{total}</span>
</div>
)
}
export default Result
| Fix React warning regarding 'key' prop in render. | Fix React warning regarding 'key' prop in render.
| JavaScript | mit | jsonnull/aleamancer,jsonnull/aleamancer | ---
+++
@@ -9,7 +9,7 @@
const Rolls = (props: RollsProps) => {
return <span>
{props.rolls.map((roll, i, arr) => (
- <span>
+ <span key={i}>
<span className={styles.roll}>
{ roll }
</span> |
ec559a4be4b2dc852cfa7ca82d792918896801bd | src/fx.js | src/fx.js | // Zepto.js
// (c) 2010, 2011 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
(function($, undefined){
var supportedTransforms = [
'scale scaleX scaleY',
'translate', 'translateX', 'translateY', 'translate3d',
'skew', 'skewX', 'skewY',
'rotate', 'rotateX', 'rotateY', 'rotateZ', 'rotate3d',
'matrix'
];
$.fn.anim = function(properties, duration, ease, callback){
var transforms = [], cssProperties = {}, key, that = this, wrappedCallback;
for (key in properties)
if (supportedTransforms.indexOf(key)>0)
transforms.push(key + '(' + properties[key] + ')');
else
cssProperties[key] = properties[key];
wrappedCallback = function(){
that.css({'-webkit-transition':'none'});
callback && callback();
}
if (duration > 0)
this.one('webkitTransitionEnd', wrappedCallback);
else
setTimeout(wrappedCallback, 0);
setTimeout(function () {
that.css(
$.extend({
'-webkit-transition': 'all ' + (duration !== undefined ? duration : 0.5) + 's ' + (ease || ''),
'-webkit-transform': transforms.join(' ')
}, cssProperties)
);
}, 0);
return this;
}
})(Zepto);
| // Zepto.js
// (c) 2010, 2011 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
(function($, undefined){
var supportedTransforms = [
'scale scaleX scaleY',
'translate', 'translateX', 'translateY', 'translate3d',
'skew', 'skewX', 'skewY',
'rotate', 'rotateX', 'rotateY', 'rotateZ', 'rotate3d',
'matrix'
];
$.fn.anim = function(properties, duration, ease, callback){
var transforms = [], cssProperties = {}, key, that = this, wrappedCallback;
for (key in properties)
if (supportedTransforms.indexOf(key)>0)
transforms.push(key + '(' + properties[key] + ')');
else
cssProperties[key] = properties[key];
wrappedCallback = function(){
that.css({'-webkit-transition':'none'});
callback && callback();
}
if (duration > 0)
this.one('webkitTransitionEnd', wrappedCallback);
else
setTimeout(wrappedCallback, 0);
if (transforms.length > 0) {
cssProperties['-webkit-transform'] = transforms.join(' ')
}
cssProperties['-webkit-transition'] = 'all ' + (duration !== undefined ? duration : 0.5) + 's ' + (ease || '');
setTimeout(function () {
that.css(cssProperties);
}, 0);
return this;
}
})(Zepto);
| Refactor usage cssProperties in $.fn.anim | Refactor usage cssProperties in $.fn.anim
| JavaScript | mit | huaziHear/zepto,Genie77998/zepto,zhangwei001/zepto,fbiz/zepto,wubian0517/zepto,yuhualingfeng/zepto,alatvanas9/zepto,treejames/zepto,nerdgore/zepto,afgoulart/zepto,kolf/zepto,assgod/zepto,wanglam/zepto,dajbd/zepto,wanglam/zepto,leolin1229/zepto,zhangwei001/zepto,vincent1988/zepto,GerHobbelt/zepto,zhengdai/zepto,GerHobbelt/zepto,liyandalmllml/zepto,evilemon/zepto,clearwind/zepto,behind2/zepto,nerdgore/zepto,mscienski/zepto,wushuyi/zepto,SlaF/zepto,midare/zepto,evilemon/zepto,alatvanas9/zepto,wushuyi/zepto,yuhualingfeng/zepto,leolin1229/zepto,yinchuandong/zepto,waiter/zepto,alatvanas9/zepto,vivijiang/zepto,modulexcite/zepto,baiyanghese/zepto,mmcai/zepto,chenruixuan/zepto,xueduany/zepto,wushuyi/zepto,YongX/zepto,philip8728/zepto,liuweifeng/zepto,laispace/zepto,zhangbg/zepto,fgnass/zepto-node,mscienski/zepto,eric-seekas/zepto,treejames/zepto,honeinc/zepto,zhangbg/zepto,midare/zepto,behind2/zepto,changfengliu/zepto,treejames/zepto,mmcai/zepto,SallyRice/zepto,fbiz/zepto,evilemon/zepto,Genie77998/zepto,webcoding/zepto,eric-seekas/zepto,Jiasm/zepto,GerHobbelt/zepto,huaziHear/zepto,zhengdai/zepto,yinchuandong/zepto,liyandalmllml/zepto,changfengliu/zepto,dajbd/zepto,JimmyVV/zepto,Jiasm/zepto,xuechunL/zepto,wyfyyy818818/zepto,rayrc/zepto,pandoraui/zepto,zhangbg/zepto,waiter/zepto,assgod/zepto,leolin1229/zepto,linqingyicen/zepto,chenruixuan/zepto,philip8728/zepto,xuechunL/zepto,YongX/zepto,yubin-huang/zepto,changfengliu/zepto,vivijiang/zepto,SallyRice/zepto,pandoraui/zepto,xueduany/zepto,wyfyyy818818/zepto,xueduany/zepto,yubin-huang/zepto,kolf/zepto,noikiy/zepto,modulexcite/zepto,webcoding/zepto,kolf/zepto,vincent1988/zepto,xwcoder/zepto-patch,noikiy/zepto,JimmyVV/zepto,yuhualingfeng/zepto,xwcoder/zepto-patch,webcoding/zepto,YongX/zepto,afgoulart/zepto,honeinc/zepto,modulexcite/zepto-node,zhengdai/zepto,waiter/zepto,rayrc/zepto,chenruixuan/zepto,behind2/zepto,121595113/zepto,yinchuandong/zepto,dajbd/zepto,SallyRice/zepto,yubin-huang/zepto,Genie77998/zepto,assgod/zepto,eric-seekas/zepto,121595113/zepto,modulexcite/zepto,philip8728/zepto,zhangwei001/zepto,noikiy/zepto,fbiz/zepto,liuweifeng/zepto,vivijiang/zepto,wyfyyy818818/zepto,huaziHear/zepto,rayrc/zepto,pandoraui/zepto,liuweifeng/zepto,xwcoder/zepto-patch,SlaF/zepto,JimmyVV/zepto,nerdgore/zepto,afgoulart/zepto,wanglam/zepto,laispace/zepto,midare/zepto,modulexcite/zepto-node,linqingyicen/zepto,mscienski/zepto,Jiasm/zepto,xuechunL/zepto,liyandalmllml/zepto,clearwind/zepto,vincent1988/zepto,baiyanghese/zepto,wubian0517/zepto,linqingyicen/zepto,SlaF/zepto,clearwind/zepto,honeinc/zepto,wubian0517/zepto,mmcai/zepto | ---
+++
@@ -30,13 +30,14 @@
else
setTimeout(wrappedCallback, 0);
+ if (transforms.length > 0) {
+ cssProperties['-webkit-transform'] = transforms.join(' ')
+ }
+
+ cssProperties['-webkit-transition'] = 'all ' + (duration !== undefined ? duration : 0.5) + 's ' + (ease || '');
+
setTimeout(function () {
- that.css(
- $.extend({
- '-webkit-transition': 'all ' + (duration !== undefined ? duration : 0.5) + 's ' + (ease || ''),
- '-webkit-transform': transforms.join(' ')
- }, cssProperties)
- );
+ that.css(cssProperties);
}, 0);
return this; |
27bf060e5aa061b748b8e20deb7215e800c9c249 | client/config/index.js | client/config/index.js | 'use strict'
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
| 'use strict'
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8081,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
| Change port for client development | Change port for client development
| JavaScript | agpl-3.0 | 1element/sc,1element/sc,1element/sc | ---
+++
@@ -25,7 +25,7 @@
},
dev: {
env: require('./dev.env'),
- port: 8080,
+ port: 8081,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/', |
1039880516112abc388e660ab8e6cb782deea42e | clients/web/js/util.js | clients/web/js/util.js | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
module.exports = {
shortName: shortName,
firstShortName: firstShortName,
randomHex: randomHex
};
// Note, shortName and firstShortName are duplicated between JS and Go.
function shortName(fullName) {
// Split into components and see if any is an email address. A very
// sophisticated technique is used to determine if the component is an email
// address: presence of an "@" character.
var parts = fullName.split('/'); // security.ChainSeparator
for (var j = 0; j < parts.length; j++) {
var p = parts[j];
if (p.indexOf('@') > 0) {
return p;
}
}
return '';
}
function firstShortName(blessings) {
if (!blessings || blessings.length === 0) {
return 'unknown';
}
for (var i = 0; i < blessings.length; i++) {
var sn = shortName(blessings[i]);
if (sn) return sn;
}
return blessings[0];
}
function randomBytes(len) {
len = len || 1;
var array = new Int8Array(len);
window.crypto.getRandomValues(array);
return new Buffer(array);
}
function randomHex(len) {
return randomBytes(Math.ceil(len/2)).toString('hex').substr(0, len);
}
| // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var security = require('vanadium').security;
module.exports = {
shortName: shortName,
firstShortName: firstShortName,
randomHex: randomHex
};
// Note, shortName and firstShortName are duplicated between JS and Go.
function shortName(fullName) {
// Split into components and see if any is an email address. A very
// sophisticated technique is used to determine if the component is an email
// address: presence of an "@" character.
var parts = fullName.split(security.ChainSeparator.val);
for (var j = 0; j < parts.length; j++) {
var p = parts[j];
if (p.indexOf('@') > 0) {
return p;
}
}
return '';
}
function firstShortName(blessings) {
if (!blessings || blessings.length === 0) {
return 'unknown';
}
for (var i = 0; i < blessings.length; i++) {
var sn = shortName(blessings[i]);
if (sn) return sn;
}
return blessings[0];
}
function randomBytes(len) {
len = len || 1;
var array = new Int8Array(len);
window.crypto.getRandomValues(array);
return new Buffer(array);
}
function randomHex(len) {
return randomBytes(Math.ceil(len/2)).toString('hex').substr(0, len);
}
| Fix chat to use security.ChainSeperator instead of hard-coded value. | Fix chat to use security.ChainSeperator instead of hard-coded value.
Change-Id: Ie83886089e802cad27d69df8b53b421f6a2aef72
| JavaScript | bsd-3-clause | vanadium/chat,vanadium/chat,vanadium/chat,vanadium/chat,vanadium/chat | ---
+++
@@ -1,6 +1,8 @@
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
+
+var security = require('vanadium').security;
module.exports = {
shortName: shortName,
@@ -14,7 +16,7 @@
// Split into components and see if any is an email address. A very
// sophisticated technique is used to determine if the component is an email
// address: presence of an "@" character.
- var parts = fullName.split('/'); // security.ChainSeparator
+ var parts = fullName.split(security.ChainSeparator.val);
for (var j = 0; j < parts.length; j++) {
var p = parts[j];
if (p.indexOf('@') > 0) { |
2298e7cc99cd4d9c68c963046049969b0a076754 | generators/app/templates/Component.js | generators/app/templates/Component.js | import React, { Component } from 'react';
import s from './<%= componentName %>.scss';
import withStyles from '../withStyles';
class <%= componentName %> extends Component {
render() {
return <div></div>;
}
}
export default withStyles(<%= componentName %>, s);
| import React, { Component } from 'react';
<% if (componentStyleExtension !== 'none') { -%>
import withStyles from '../withStyles';
import s from './LoginPage.scss';
<% } -%>
class <%= componentName %> extends Component {
render() {
return <div></div>;
}
}
<% if (componentStyleExtension !== 'none') { -%>
export default withStyles(<%= componentName %>, s);
<% } else { -%>
export default <%= componentName %>;
<% } -%>
| Fix importing styles where there's none | Fix importing styles where there's none
| JavaScript | mit | gfpacheco/generator-react-starter-kit-component | ---
+++
@@ -1,6 +1,8 @@
import React, { Component } from 'react';
-import s from './<%= componentName %>.scss';
+<% if (componentStyleExtension !== 'none') { -%>
import withStyles from '../withStyles';
+import s from './LoginPage.scss';
+<% } -%>
class <%= componentName %> extends Component {
@@ -10,4 +12,8 @@
}
+<% if (componentStyleExtension !== 'none') { -%>
export default withStyles(<%= componentName %>, s);
+<% } else { -%>
+export default <%= componentName %>;
+<% } -%> |
1f6fb464187db286087d2ec5a4c954c28c31e624 | spec/mobiread_test.js | spec/mobiread_test.js |
var loadFileUrl = function (url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // synchronous
// retrieve data unprocessed as a binary string
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send();
if (xhr.status === 200) {
return xhr.response; // Note: not xhr.responseText
} else {
throw new Error("File not found");
}
}
describe("MobiRead", function() {
it("should complain of missing file", function() {
var loadMissing = function() {
data = loadFileUrl("nosuchfile");
}
expect(loadMissing).toThrow();
});
it("should load and parse a valid file", function() {
var data;
var loadIt = function() {
data = loadFileUrl("http://localhost/~dmd/current/jsebook/data/testbook.mobi");
}
expect(loadIt).not.toThrow();
});
it("should complain of wrong file type", function() {
});
});
|
var loadFileUrl = function (url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // synchronous
// retrieve data unprocessed as a binary string
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send();
if (xhr.status === 200) {
return xhr.response; // Note: not xhr.responseText
} else {
throw new Error("File not found");
}
}
describe("MobiRead", function() {
it("should complain of missing file", function() {
var loadMissing = function() {
data = loadFileUrl("nosuchfile");
}
expect(loadMissing).toThrow();
});
it("should load and parse a valid file", function() {
var data;
var loadIt = function() {
data = loadFileUrl("http://localhost/~dmd/jsebook/data/testbook.mobi");
}
expect(loadIt).not.toThrow();
});
it("should complain of wrong file type", function() {
});
});
| Update location of local test file | Update location of local test file
| JavaScript | mit | daviddrysdale/jsebook,daviddrysdale/jsebook | ---
+++
@@ -22,7 +22,7 @@
it("should load and parse a valid file", function() {
var data;
var loadIt = function() {
- data = loadFileUrl("http://localhost/~dmd/current/jsebook/data/testbook.mobi");
+ data = loadFileUrl("http://localhost/~dmd/jsebook/data/testbook.mobi");
}
expect(loadIt).not.toThrow();
}); |
11d1ad864ca23f9c5243ab85a015168e0a9faa34 | src/templates/infinite-scroll-link.js | src/templates/infinite-scroll-link.js | import React from 'react'
import Link from 'gatsby-link'
export default class InfiniteScrollLink extends React.Component {
constructor (props) {
super(props)
const observerOptions = {
root: null,
rootMargin: '0px',
threshold: 0.25
}
this.observerCallback = this.observerCallback.bind(this)
this.state = {
observer: new window.IntersectionObserver(this.observerCallback(props.callback || (() => {})), observerOptions)
}
}
componentDidMount () {
this.state.observer.observe(document.querySelector('#infinite-scroll-link'))
}
componentWillUnmount () {
if (this.state.observer.unobserve instanceof Function) {
this.state.observer.unobserve(document.querySelector('#infinite-scroll-link'))
}
}
observerCallback (callback) {
return (entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
callback(this.props.url)
}
})
}
}
render () {
return (
<Link id='infinite-scroll-link'
to={this.props.url}>
{ this.props.linkName }
</Link>
)
}
}
| import React from 'react'
import Link from 'gatsby-link'
export default class InfiniteScrollLink extends React.Component {
constructor (props) {
super(props)
const observerOptions = {
root: null,
rootMargin: '0px',
threshold: 0.25
}
const callback = props.callback || (() => {})
this.observerCallback = this.observerCallback.bind(this)
this.onClick = this.onClick.bind(this, callback)
this.observer = new window.IntersectionObserver(this.observerCallback(callback), observerOptions)
this.callbackCalls = 0
this.MAX_CALLBACK_CALLS = 3
}
componentDidMount () {
this.observer.observe(document.querySelector('#infinite-scroll-link'))
}
componentWillUnmount () {
if (this.observer.unobserve instanceof Function) {
this.observer.unobserve(document.querySelector('#infinite-scroll-link'))
}
}
observerCallback (callback) {
return (entries) => {
if (this.callbackCalls < this.MAX_CALLBACK_CALLS) {
entries.forEach(entry => {
if (entry.isIntersecting) {
callback(this.props.url)
this.callbackCalls += 1
}
})
}
}
}
onClick (callback, event) {
event.preventDefault()
callback(this.props.url)
this.callbackCalls = 1
}
render () {
return (
<Link id='infinite-scroll-link'
to={this.props.url}
onClick={this.onClick}>
{ this.props.linkName }
</Link>
)
}
}
| Define a maximum number of calls to get more events; Request user action before requesting more; Remove unnecessary use of component state. | Define a maximum number of calls to get more events;
Request user action before requesting more;
Remove unnecessary use of component state.
| JavaScript | mit | LuisLoureiro/placard-wrapper | ---
+++
@@ -10,38 +10,52 @@
rootMargin: '0px',
threshold: 0.25
}
+ const callback = props.callback || (() => {})
this.observerCallback = this.observerCallback.bind(this)
-
- this.state = {
- observer: new window.IntersectionObserver(this.observerCallback(props.callback || (() => {})), observerOptions)
- }
+ this.onClick = this.onClick.bind(this, callback)
+ this.observer = new window.IntersectionObserver(this.observerCallback(callback), observerOptions)
+ this.callbackCalls = 0
+ this.MAX_CALLBACK_CALLS = 3
}
componentDidMount () {
- this.state.observer.observe(document.querySelector('#infinite-scroll-link'))
+ this.observer.observe(document.querySelector('#infinite-scroll-link'))
}
componentWillUnmount () {
- if (this.state.observer.unobserve instanceof Function) {
- this.state.observer.unobserve(document.querySelector('#infinite-scroll-link'))
+ if (this.observer.unobserve instanceof Function) {
+ this.observer.unobserve(document.querySelector('#infinite-scroll-link'))
}
}
observerCallback (callback) {
return (entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- callback(this.props.url)
- }
- })
+ if (this.callbackCalls < this.MAX_CALLBACK_CALLS) {
+ entries.forEach(entry => {
+ if (entry.isIntersecting) {
+ callback(this.props.url)
+
+ this.callbackCalls += 1
+ }
+ })
+ }
}
+ }
+
+ onClick (callback, event) {
+ event.preventDefault()
+
+ callback(this.props.url)
+
+ this.callbackCalls = 1
}
render () {
return (
<Link id='infinite-scroll-link'
- to={this.props.url}>
+ to={this.props.url}
+ onClick={this.onClick}>
{ this.props.linkName }
</Link>
) |
8d2e3aa557a754275062b829e74b71e98a162c6f | src/pages/workshops/drafts.js | src/pages/workshops/drafts.js | import React, { Fragment } from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
import { Container, Flex, Heading } from '@hackclub/design-system'
import storage from '../../storage'
import BG from '../../components/BG'
import Sheet from '../../components/Sheet'
import FeatherIcon from '../../components/FeatherIcon'
const Card = styled(Sheet)`
cursor: pointer;
> div {
justify-content: space-between;
text-align: left;
}
svg {
display: none;
@media (hover: none) {
display: block;
}
}
&:hover {
svg {
display: block;
}
}
`
const Name = styled(Heading.h3).attrs({
fontSize: [3, 4]
})`
max-width: 85%;
`
export default () => (
<Fragment>
<BG color="snow" />
<Container maxWidth={42} p={4}>
{storage.keys().map(key => (
<Link to="/workshops/submit">
<Card>
<Flex align="center">
<Name>{key.replace(/-/g, ' ')}</Name>
<FeatherIcon glyph="edit-3" />
</Flex>
</Card>
</Link>
))}
</Container>
</Fragment>
)
| import React, { Fragment } from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
import { Container, Flex, Box, Heading, Text } from '@hackclub/design-system'
import ReactMarkdown from 'react-markdown'
import storage from '../../storage'
import BG from '../../components/BG'
import Sheet from '../../components/Sheet'
import FeatherIcon from '../../components/FeatherIcon'
const Card = styled(Sheet)`
cursor: pointer;
> div {
justify-content: space-between;
text-align: left;
}
p {
margin: 0;
}
svg {
display: none;
@media (hover: none) {
display: block;
}
}
&:hover {
svg {
display: block;
}
}
`
const Left = styled(Box)`
max-width: 85%;
`
var truncate = (str, length) => {
const dots = str.length > length ? '...' : ''
return str.substring(0, length) + dots
}
export default () => (
<Fragment>
<BG color="snow" />
<Container maxWidth={42} p={4}>
{storage.keys().map(key => (
<Link to="/workshops/submit">
<Card>
<Flex align="center">
<Left>
<Heading.h3 fontSize={[3, 4]}>
{key.replace(/-/g, ' ')}
</Heading.h3>
<Text color="muted">
<ReactMarkdown
source={truncate(storage.get(key).content, 64)}
/>
</Text>
</Left>
<FeatherIcon glyph="edit-3" />
</Flex>
</Card>
</Link>
))}
</Container>
</Fragment>
)
| Add body to draft card | Add body to draft card
| JavaScript | mit | hackclub/website,hackclub/website,hackclub/website | ---
+++
@@ -1,7 +1,8 @@
import React, { Fragment } from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
-import { Container, Flex, Heading } from '@hackclub/design-system'
+import { Container, Flex, Box, Heading, Text } from '@hackclub/design-system'
+import ReactMarkdown from 'react-markdown'
import storage from '../../storage'
import BG from '../../components/BG'
@@ -14,6 +15,10 @@
> div {
justify-content: space-between;
text-align: left;
+ }
+
+ p {
+ margin: 0;
}
svg {
@@ -30,11 +35,14 @@
}
`
-const Name = styled(Heading.h3).attrs({
- fontSize: [3, 4]
-})`
+const Left = styled(Box)`
max-width: 85%;
`
+
+var truncate = (str, length) => {
+ const dots = str.length > length ? '...' : ''
+ return str.substring(0, length) + dots
+}
export default () => (
<Fragment>
@@ -44,7 +52,16 @@
<Link to="/workshops/submit">
<Card>
<Flex align="center">
- <Name>{key.replace(/-/g, ' ')}</Name>
+ <Left>
+ <Heading.h3 fontSize={[3, 4]}>
+ {key.replace(/-/g, ' ')}
+ </Heading.h3>
+ <Text color="muted">
+ <ReactMarkdown
+ source={truncate(storage.get(key).content, 64)}
+ />
+ </Text>
+ </Left>
<FeatherIcon glyph="edit-3" />
</Flex>
</Card> |
a85a6deefa094d1a79c9cdd7c7342605e6c27dda | js/functions.js | js/functions.js | function statusIdToText(id) {
if(id==0) {
return 'Offline';
}
else if(id==1) {
return 'Available';
}
else if(id==2) {
return 'Away';
}
else if(id==3){
return 'Occupied';
}
}
function getCurrentTimestamp(){
return Date.now();
}
function timestampToTimeOfDay(timestamp) {
var a = new Date(timestamp);
var hour = a.getHours();
if(hour<10){
hour= '0'+hour;
}
var min = a.getMinutes();
if(min<10){
min= '0'+min;
}
var time = hour + ':' + min;
return time;
}
function getFormattedDataURL(parameters) {
return "data.php?" + parameters.join("&");
} | function statusIdToText(id) {
if(id==0) {
return 'Offline';
}
else if(id==1) {
return 'Available';
}
else if(id==2) {
return 'Away';
}
else if(id==3){
return 'Occupied';
}
}
function getCurrentTimestamp(){
return Date.now() / 1000;
}
function timestampToTimeOfDay(timestamp) {
var a = new Date(timestamp);
var hour = a.getHours();
if(hour<10){
hour= '0'+hour;
}
var min = a.getMinutes();
if(min<10){
min= '0'+min;
}
var time = hour + ':' + min;
return time;
}
function getFormattedDataURL(parameters) {
return "data.php?" + parameters.join("&");
} | Fix timestamp function to give seconds | Fix timestamp function to give seconds
| JavaScript | mit | perrr/svada,perrr/svada | ---
+++
@@ -14,7 +14,7 @@
}
function getCurrentTimestamp(){
- return Date.now();
+ return Date.now() / 1000;
}
function timestampToTimeOfDay(timestamp) { |
274137fa8f11c6b53071c625ace15cffad526e9c | examples/client/services/account.js | examples/client/services/account.js | angular.module('MyApp')
.factory('Account', ['$http', '$window', function($http, $window) {
return {
getUserInfo: function() {
return $http.get('/api/me?token=' + $window.localStorage.token);
}
};
}]); | angular.module('MyApp')
.factory('Account', ['$http', '$window', function($http, $window) {
return {
getUserInfo: function() {
return $http.get('/api/me');
}
};
}]); | Remove token querystring from API call | Remove token querystring from API call
| JavaScript | mit | peterkim-ijet/satellizer,xxryan1234/satellizer,celrenheit/satellizer,jayzeng/satellizer,shikhardb/satellizer,maciekrb/satellizer,NikolayGalkin/satellizer,hsr-ba-fs15-dat/satellizer,amitport/satellizer,ELAPAKAHARI/satellizer,ELAPAKAHARI/satellizer,celrenheit/satellizer,redwood-strategic/satellizer,david300/satellizer,ELAPAKAHARI/satellizer,jskrzypek/satellizer,hsr-ba-fs15-dat/satellizer,maciekrb/satellizer,david300/satellizer,redwood-strategic/satellizer,amitport/satellizer,amitport/satellizer,jonbgallant/satellizer,gshireesh/satellizer,david300/satellizer,sahat/satellizer,hsr-ba-fs15-dat/satellizer,elanperach/satellizer,Manumental32/satellizer,themifycloud/satellizer,peterkim-ijet/satellizer,bnicart/satellizer,xscharlie/satellizer,gshireesh/satellizer,redwood-strategic/satellizer,david300/satellizer,marceldiass/satellizer,TheOneTheOnlyDavidBrown/satellizer,ABPFrameWorkGroup/satellizer,david300/satellizer,xxryan1234/satellizer,hsr-ba-fs15-dat/satellizer,celrenheit/satellizer,maciekrb/satellizer,david300/satellizer,jskrzypek/satellizer,gshireesh/satellizer,maciekrb/satellizer,baratheraja/satellizer,johan--/satellizer,andyskw/satellizer,xxryan1234/satellizer,burasu/satellizer,ELAPAKAHARI/satellizer,NikolayGalkin/satellizer,jskrzypek/satellizer,redwood-strategic/satellizer,bartekmis/satellizer,shubham13jain/satellizer,NikolayGalkin/satellizer,peterkim-ijet/satellizer,ELAPAKAHARI/satellizer,celrenheit/satellizer,david300/satellizer,eduardomb/satellizer,jskrzypek/satellizer,NikolayGalkin/satellizer,ezzaouia/satellizer,viniciusferreira/satellizer,AmreeshTyagi/satellizer,raycoding/satellizer,peterkim-ijet/satellizer,vebin/satellizer,amitport/satellizer,celrenheit/satellizer,gshireesh/satellizer,jskrzypek/satellizer,hsr-ba-fs15-dat/satellizer,memezilla/satellizer,peterkim-ijet/satellizer,romcyncynatus/satellizer,dgoguerra/satellizer,xxryan1234/satellizer,eduardomb/satellizer,expertmaksud/satellizer,celrenheit/satellizer,eduardomb/satellizer,jskrzypek/satellizer,hsr-ba-fs15-dat/satellizer,ELAPAKAHARI/satellizer,peterkim-ijet/satellizer,gregoriusxu/satellizer,xxryan1234/satellizer,IRlyDontKnow/satellizer,TechyTimo/CoderHunt,suratpyari/satellizer,thandaanda/satellizer,jskrzypek/satellizer,peterkim-ijet/satellizer,TechyTimo/carbon,manojpm/satellizer,celrenheit/satellizer,TechyTimo/CoderHunt,redwood-strategic/satellizer,NikolayGalkin/satellizer,eduardomb/satellizer,xxryan1234/satellizer,xxryan1234/satellizer,SkydiverFL/satellizer,heinbez/satellizer,ELAPAKAHARI/satellizer,jskrzypek/satellizer,NikolayGalkin/satellizer,david300/satellizer,gshireesh/satellizer,zawmyolatt/satellizer,gshireesh/satellizer,johan--/satellizer,thiagofesta/satellizer,david300/satellizer,eduardomb/satellizer,marfarma/satellizer,eduardomb/satellizer,gshireesh/satellizer,sahat/satellizer,xxryan1234/satellizer,amitport/satellizer,maciekrb/satellizer,18098924759/satellizer,redwood-strategic/satellizer,maciekrb/satellizer,NikolayGalkin/satellizer,maciekrb/satellizer,romcyncynatus/satellizer,ELAPAKAHARI/satellizer,gshireesh/satellizer,eduardomb/satellizer,jianwang195823/satellizer,amitport/satellizer,redwood-strategic/satellizer,hsr-ba-fs15-dat/satellizer,m-kostira/satellizer,NikolayGalkin/satellizer,jskrzypek/satellizer,eduardomb/satellizer,eduardomb/satellizer,gshireesh/satellizer,redwood-strategic/satellizer,rick4470/satellizer,celrenheit/satellizer,maciekrb/satellizer,peterkim-ijet/satellizer,amitport/satellizer,hsr-ba-fs15-dat/satellizer,TechyTimo/carbon,redwood-strategic/satellizer,xxryan1234/satellizer | ---
+++
@@ -2,7 +2,7 @@
.factory('Account', ['$http', '$window', function($http, $window) {
return {
getUserInfo: function() {
- return $http.get('/api/me?token=' + $window.localStorage.token);
+ return $http.get('/api/me');
}
};
}]); |
c109f3bb3d6eac0a3fd2a39717c5d34a27678567 | landing/utils/auth/login/login.controller.js | landing/utils/auth/login/login.controller.js | (() => {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['growl', '$window', '$http', '$routeSegment', 'TokenService', 'Endpoints'];
function LoginController(growl, $window, $http, $routeSegment, TokenService, Endpoints) {
const vm = this;
vm.data = {};
vm.login = login;
activate();
////
function activate() {
let authorizationToken = TokenService.get();
if (authorizationToken) {
TokenService.save(authorizationToken);
$window.location.pathname = '/app/';
}
}
function login() {
let req = {
email: vm.data.email,
password: vm.data.password
};
let config = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
let response = (res) => {
if (res.status == 200) {
if (res.data.success) {
TokenService.save(res.data.data.token);
window.localStorage.setItem('token', res.data.data.token);
$window.location.pathname = '/app/';
} else {
growl.info(res.data.data.message);
$routeSegment.chain[0].reload();
}
}
vm.form.$setUntouched();
vm.form.$setPristine();
vm.form.$setDirty();
};
$http.post(Endpoints.AUTH, req, config).then(response);
}
}
})();
| (() => {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['growl', '$window', '$http', '$routeSegment', 'TokenService', 'Endpoints'];
function LoginController(growl, $window, $http, $routeSegment, TokenService, Endpoints) {
const vm = this;
vm.data = {};
vm.login = login;
activate();
////
function activate() {
let authorizationToken = TokenService.get();
if (authorizationToken) {
TokenService.save(authorizationToken);
$window.location.pathname = '/app/';
}
}
function login() {
let req = {
email: vm.data.email,
password: vm.data.password
};
let config = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
let response = (res) => {
if (res.status == 200) {
if (res.data.success) {
TokenService.save(res.data.data.token);
window.localStorage.setItem('token', res.data.data.token);
$window.location.pathname = '/app/';
} else {
growl.info(res.data.data.message);
}
}
vm.form.$setUntouched();
vm.form.$setPristine();
vm.form.$setDirty();
};
$http.post(Endpoints.AUTH, req, config).then(response);
}
}
})();
| Fix bug with reloading on Login page | Fix bug with reloading on Login page
| JavaScript | mit | royalrangers-ck/rr-web-app,royalrangers-ck/rr-web-app,royalrangers-ck/rr-web-app,royalrangers-ck/rr-web-app | ---
+++
@@ -44,7 +44,6 @@
$window.location.pathname = '/app/';
} else {
growl.info(res.data.data.message);
- $routeSegment.chain[0].reload();
}
}
|
d2f2523243a192a5d03dae1c1b33a6cdccc27c04 | src/assets/scripts/service-worker/service-worker.js | src/assets/scripts/service-worker/service-worker.js | // JavaScript Document
// Scripts written by YOURNAME @ YOURCOMPANY
// no service worker for previews
self.addEventListener("fetch", (event) => {
if (event.request.url.match(/preview=true/)) {
return;
}
});
// set up caching
toolbox.precache(["/", "../media/logo.svg", "../media/spritesheet.svg", "../styles/modern.css", "../scripts/modern.js"]);
toolbox.router.get("../media/*", toolbox.cacheFirst);
toolbox.router.get("/wp-content/uploads/*", toolbox.cacheFirst);
toolbox.router.get("/*", toolbox.networkFirst, {NetworkTimeoutSeconds: 5});
| // JavaScript Document
// Scripts written by YOURNAME @ YOURCOMPANY
// no service worker for previews
self.addEventListener("fetch", (event) => {
if (event.request.url.match(/preview=true/)) {
return;
}
});
// set up caching
toolbox.precache(["/", "../media/logo.svg", "../media/spritesheet.svg", "../scripts/modern.js", "../styles/modern.css"]);
toolbox.router.get("../media/*", toolbox.cacheFirst);
toolbox.router.get("/wp-content/uploads/*", toolbox.cacheFirst);
toolbox.router.get("/*", toolbox.networkFirst, {NetworkTimeoutSeconds: 5});
| Correct order of files to cache | Correct order of files to cache
| JavaScript | mit | JacobDB/new-site,revxx14/new-site,JacobDB/new-site,revxx14/new-site,JacobDB/new-site | ---
+++
@@ -10,7 +10,7 @@
});
// set up caching
-toolbox.precache(["/", "../media/logo.svg", "../media/spritesheet.svg", "../styles/modern.css", "../scripts/modern.js"]);
+toolbox.precache(["/", "../media/logo.svg", "../media/spritesheet.svg", "../scripts/modern.js", "../styles/modern.css"]);
toolbox.router.get("../media/*", toolbox.cacheFirst);
toolbox.router.get("/wp-content/uploads/*", toolbox.cacheFirst);
toolbox.router.get("/*", toolbox.networkFirst, {NetworkTimeoutSeconds: 5}); |
575b107f092032f04d0169400d04e978449ac4af | src/devtools/model.js | src/devtools/model.js | // @flow
import type {Snapshot, SnapshotItem} from 'redux-ship';
export type State = {
logs: {action: mixed, snapshot: Snapshot<mixed, mixed>}[],
selectedLog: ?number,
selectedSnapshotItem: ?SnapshotItem<mixed, mixed>,
};
export const initialState: State = {
logs: [],
selectedLog: null,
selectedSnapshotItem: null,
};
export type Commit = {
type: 'AddLog',
action: mixed,
snapshot: Snapshot<mixed, mixed>,
} | {
type: 'SelectLog',
logIndex: number,
} | {
type: 'SelectSnapshotItem',
snapshotItem: SnapshotItem<mixed, mixed>,
};
export function reduce(state: State, commit: Commit): State {
switch (commit.type) {
case 'AddLog':
return {
...state,
logs: [
...state.logs,
{
action: commit.action,
snapshot: commit.snapshot,
}
],
selectedLog: typeof state.selectedLog !== 'number' ?
state.logs.length :
state.selectedLog,
selectedSnapshotItem: commit.snapshot[0] || null,
};
case 'SelectLog':
return commit.logIndex === state.selectedLog ? state : {
...state,
selectedLog: commit.logIndex,
selectedSnapshotItem: state.logs[commit.logIndex].snapshot[0] || null,
};
case 'SelectSnapshotItem':
return {
...state,
selectedSnapshotItem: commit.snapshotItem,
};
default:
return state;
}
}
| // @flow
import type {Snapshot, SnapshotItem} from 'redux-ship';
export type State = {
logs: {action: mixed, snapshot: Snapshot<mixed, mixed>}[],
selectedLog: ?number,
selectedSnapshotItem: ?SnapshotItem<mixed, mixed>,
};
export const initialState: State = {
logs: [],
selectedLog: null,
selectedSnapshotItem: null,
};
export type Commit = {
type: 'AddLog',
action: mixed,
snapshot: Snapshot<mixed, mixed>,
} | {
type: 'SelectLog',
logIndex: number,
} | {
type: 'SelectSnapshotItem',
snapshotItem: SnapshotItem<mixed, mixed>,
};
export function reduce(state: State, commit: Commit): State {
switch (commit.type) {
case 'AddLog':
return {
...state,
logs: [
...state.logs,
{
action: commit.action,
snapshot: commit.snapshot,
}
],
selectedLog: typeof state.selectedLog !== 'number' ?
state.logs.length :
state.selectedLog,
selectedSnapshotItem: typeof state.selectedLog !== 'number' ?
commit.snapshot[0] || null :
state.selectedSnapshotItem,
};
case 'SelectLog':
return commit.logIndex === state.selectedLog ? state : {
...state,
selectedLog: commit.logIndex,
selectedSnapshotItem: state.logs[commit.logIndex].snapshot[0] || null,
};
case 'SelectSnapshotItem':
return {
...state,
selectedSnapshotItem: commit.snapshotItem,
};
default:
return state;
}
}
| Fix bug to display the default snapshot item | Fix bug to display the default snapshot item
| JavaScript | mit | clarus/redux-ship-devtools,clarus/redux-ship-devtools | ---
+++
@@ -40,7 +40,9 @@
selectedLog: typeof state.selectedLog !== 'number' ?
state.logs.length :
state.selectedLog,
- selectedSnapshotItem: commit.snapshot[0] || null,
+ selectedSnapshotItem: typeof state.selectedLog !== 'number' ?
+ commit.snapshot[0] || null :
+ state.selectedSnapshotItem,
};
case 'SelectLog':
return commit.logIndex === state.selectedLog ? state : { |
9d12bf2ed95636b177dd3674a2e00f46b8efda2c | routes/priority_service_170315/intro/steps.js | routes/priority_service_170315/intro/steps.js | module.exports = {
'/': {
backLink: '/../priority_service_170301/filter/uncancelled',
next: '/what-you-need'
},
'/before-you-continue-overseas': {
backLink: '/../priority_service_170301/overseas/uncancelled',
next: '/what-you-need-overseas'
},
'/what-you-need': {
backLink: './',
next: '/you-need-a-photo'
},
'/what-you-need-overseas': {
backLink: '/../priority_service_170301/overseas/try-service',
next: '/you-need-a-photo-overseas'
},
'/you-need-a-photo': {
backLink: '../book-appointment/confirmation-scenario-1',
next: '/choose-photo-method'
},
'/you-need-a-photo-overseas': {
backLink: './what-you-need-overseas',
next: '/choose-photo-method'
},
'/you-need-a-photo-v3': {
backLink: './what-you-need',
next: '/choose-photo-method'
},
'/choose-photo-method': {
fields: ['choose-photo'],
next: '/../upload'
},
'/choose-photo-method-overseas': {
fields: ['choose-photo-overseas'],
next: '/../upload'
}
};
| module.exports = {
'/': {
backLink: '/../priority_service_170315/filter/uncancelled',
next: '/what-you-need'
},
'/before-you-continue-overseas': {
backLink: '/../priority_service_170315/overseas/uncancelled',
next: '/what-you-need-overseas'
},
'/what-you-need': {
backLink: './',
next: '/you-need-a-photo'
},
'/what-you-need-overseas': {
backLink: '/../priority_service_170315/overseas/try-service',
next: '/you-need-a-photo-overseas'
},
'/you-need-a-photo': {
backLink: '../book-appointment/confirmation-scenario-1',
next: '/choose-photo-method'
},
'/you-need-a-photo-overseas': {
backLink: './what-you-need-overseas',
next: '/choose-photo-method'
},
'/you-need-a-photo-v3': {
backLink: './what-you-need',
next: '/choose-photo-method'
},
'/choose-photo-method': {
fields: ['choose-photo'],
next: '/../upload'
},
'/choose-photo-method-overseas': {
fields: ['choose-photo-overseas'],
next: '/../upload'
}
};
| Fix back links in intro | Fix back links in intro
| JavaScript | mit | UKHomeOffice/passports-prototype,UKHomeOffice/passports-prototype | ---
+++
@@ -1,10 +1,10 @@
module.exports = {
'/': {
- backLink: '/../priority_service_170301/filter/uncancelled',
+ backLink: '/../priority_service_170315/filter/uncancelled',
next: '/what-you-need'
},
'/before-you-continue-overseas': {
- backLink: '/../priority_service_170301/overseas/uncancelled',
+ backLink: '/../priority_service_170315/overseas/uncancelled',
next: '/what-you-need-overseas'
},
'/what-you-need': {
@@ -12,7 +12,7 @@
next: '/you-need-a-photo'
},
'/what-you-need-overseas': {
- backLink: '/../priority_service_170301/overseas/try-service',
+ backLink: '/../priority_service_170315/overseas/try-service',
next: '/you-need-a-photo-overseas'
},
'/you-need-a-photo': { |
4cea628e0c215f2a13489022068f6e38cab5aaa4 | Libraries/Core/setUpReactRefresh.js | Libraries/Core/setUpReactRefresh.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
if (__DEV__) {
const NativeDevSettings = require('../NativeModules/specs/NativeDevSettings')
.default;
if (typeof NativeDevSettings.reload !== 'function') {
throw new Error('Could not find the reload() implementation.');
}
// This needs to run before the renderer initializes.
const ReactRefreshRuntime = require('react-refresh/runtime');
ReactRefreshRuntime.injectIntoGlobalHook(global);
const Refresh = {
performFullRefresh() {
NativeDevSettings.reload();
},
createSignatureFunctionForTransform:
ReactRefreshRuntime.createSignatureFunctionForTransform,
isLikelyComponentType: ReactRefreshRuntime.isLikelyComponentType,
getFamilyByType: ReactRefreshRuntime.getFamilyByType,
register: ReactRefreshRuntime.register,
performReactRefresh() {
if (ReactRefreshRuntime.hasUnrecoverableErrors()) {
NativeDevSettings.reload();
return;
}
ReactRefreshRuntime.performReactRefresh();
},
};
(require: any).Refresh = Refresh;
}
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
if (__DEV__) {
const DevSettings = require('../Utilities/DevSettings');
if (typeof DevSettings.reload !== 'function') {
throw new Error('Could not find the reload() implementation.');
}
// This needs to run before the renderer initializes.
const ReactRefreshRuntime = require('react-refresh/runtime');
ReactRefreshRuntime.injectIntoGlobalHook(global);
const Refresh = {
performFullRefresh(reason: string) {
DevSettings.reload(reason);
},
createSignatureFunctionForTransform:
ReactRefreshRuntime.createSignatureFunctionForTransform,
isLikelyComponentType: ReactRefreshRuntime.isLikelyComponentType,
getFamilyByType: ReactRefreshRuntime.getFamilyByType,
register: ReactRefreshRuntime.register,
performReactRefresh() {
if (ReactRefreshRuntime.hasUnrecoverableErrors()) {
DevSettings.reload('Fast Refresh - Unrecoverable');
return;
}
ReactRefreshRuntime.performReactRefresh();
},
};
(require: any).Refresh = Refresh;
}
| Add reloadWithReason to Fast Refresh | Add reloadWithReason to Fast Refresh
Summary: This diff adds reload reasons to Fast Refresh. This will help us understand why, for internal Facebook users, Fast Refresh is bailing out to a full reload so that we can improve it for everyone.
Reviewed By: cpojer
Differential Revision: D17499348
fbshipit-source-id: b6e73dc3f396c8531a0872f5572a13928450bb3b
| JavaScript | bsd-3-clause | pandiaraj44/react-native,myntra/react-native,pandiaraj44/react-native,hammerandchisel/react-native,exponent/react-native,javache/react-native,facebook/react-native,javache/react-native,hammerandchisel/react-native,janicduplessis/react-native,javache/react-native,exponentjs/react-native,arthuralee/react-native,janicduplessis/react-native,hoangpham95/react-native,facebook/react-native,arthuralee/react-native,exponentjs/react-native,myntra/react-native,exponentjs/react-native,facebook/react-native,pandiaraj44/react-native,janicduplessis/react-native,pandiaraj44/react-native,javache/react-native,exponent/react-native,myntra/react-native,janicduplessis/react-native,javache/react-native,myntra/react-native,hammerandchisel/react-native,myntra/react-native,facebook/react-native,hammerandchisel/react-native,pandiaraj44/react-native,exponentjs/react-native,myntra/react-native,facebook/react-native,hammerandchisel/react-native,janicduplessis/react-native,arthuralee/react-native,facebook/react-native,exponentjs/react-native,javache/react-native,hammerandchisel/react-native,javache/react-native,pandiaraj44/react-native,exponentjs/react-native,arthuralee/react-native,hoangpham95/react-native,janicduplessis/react-native,javache/react-native,facebook/react-native,exponentjs/react-native,exponent/react-native,exponent/react-native,exponent/react-native,myntra/react-native,janicduplessis/react-native,hoangpham95/react-native,hoangpham95/react-native,exponent/react-native,hoangpham95/react-native,hoangpham95/react-native,hoangpham95/react-native,exponent/react-native,exponentjs/react-native,janicduplessis/react-native,pandiaraj44/react-native,myntra/react-native,facebook/react-native,facebook/react-native,exponent/react-native,hammerandchisel/react-native,hoangpham95/react-native,hammerandchisel/react-native,pandiaraj44/react-native,javache/react-native,arthuralee/react-native,myntra/react-native | ---
+++
@@ -10,10 +10,9 @@
'use strict';
if (__DEV__) {
- const NativeDevSettings = require('../NativeModules/specs/NativeDevSettings')
- .default;
+ const DevSettings = require('../Utilities/DevSettings');
- if (typeof NativeDevSettings.reload !== 'function') {
+ if (typeof DevSettings.reload !== 'function') {
throw new Error('Could not find the reload() implementation.');
}
@@ -22,8 +21,8 @@
ReactRefreshRuntime.injectIntoGlobalHook(global);
const Refresh = {
- performFullRefresh() {
- NativeDevSettings.reload();
+ performFullRefresh(reason: string) {
+ DevSettings.reload(reason);
},
createSignatureFunctionForTransform:
@@ -37,7 +36,7 @@
performReactRefresh() {
if (ReactRefreshRuntime.hasUnrecoverableErrors()) {
- NativeDevSettings.reload();
+ DevSettings.reload('Fast Refresh - Unrecoverable');
return;
}
ReactRefreshRuntime.performReactRefresh(); |
d8b9ff420d60510c8d74de728923a60af78677b4 | node_modules_build/kwf-webpack/trl/trl-html-webpack-plugin.js | node_modules_build/kwf-webpack/trl/trl-html-webpack-plugin.js | 'use strict';
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');
class TrlHtmlWebpackPlugin extends HtmlWebpackPlugin
{
htmlWebpackPluginAssets(compilation, chunks) {
let language = this.options.language;
let ret = super.htmlWebpackPluginAssets(compilation, chunks);
chunks.forEach(chunk => {
chunk.files.forEach(file => {
if (fs.existsSync(compilation.options.output.path+'/' + language + '.' + file)) {
ret.js.unshift(ret.publicPath + language + '.' + file);
}
})
});
return ret;
}
}
module.exports = TrlHtmlWebpackPlugin;
| 'use strict';
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');
class TrlHtmlWebpackPlugin extends HtmlWebpackPlugin
{
htmlWebpackPluginAssets(compilation, chunks) {
let language = this.options.language;
let ret = super.htmlWebpackPluginAssets(compilation, chunks);
chunks.forEach(chunk => {
chunk.files.forEach(file => {
if (compilation.assets[language + '.' + file]) {
ret.js.unshift(ret.publicPath + language + '.' + file);
}
})
});
return ret;
}
}
module.exports = TrlHtmlWebpackPlugin;
| Fix trl: Don't access filesystem, file doesn't get written when using dev-server | Fix trl: Don't access filesystem, file doesn't get written when using dev-server
| JavaScript | bsd-2-clause | koala-framework/koala-framework,koala-framework/koala-framework | ---
+++
@@ -9,7 +9,7 @@
let ret = super.htmlWebpackPluginAssets(compilation, chunks);
chunks.forEach(chunk => {
chunk.files.forEach(file => {
- if (fs.existsSync(compilation.options.output.path+'/' + language + '.' + file)) {
+ if (compilation.assets[language + '.' + file]) {
ret.js.unshift(ret.publicPath + language + '.' + file);
}
}) |
3067aa2d3c4beb1a2aca4ff59d7d2b88d33c8b84 | app/components/gh-content-view-container.js | app/components/gh-content-view-container.js | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['gh-view', 'content-view-container'],
previewIsHidden: false,
resizeService: Ember.inject.service(),
calculatePreviewIsHidden: function () {
if (this.$('.content-preview').length) {
this.set('previewIsHidden', !this.$('.content-preview').is(':visible'));
}
},
didInsertElement: function () {
this._super(...arguments);
this.calculatePreviewIsHidden();
this.get('resizeService').on('debouncedDidResize',
Ember.run.bind(this, this.calculatePreviewIsHidden));
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['gh-view', 'content-view-container'],
previewIsHidden: false,
resizeService: Ember.inject.service(),
_resizeListener: null,
calculatePreviewIsHidden: function () {
if (this.$('.content-preview').length) {
this.set('previewIsHidden', !this.$('.content-preview').is(':visible'));
}
},
didInsertElement: function () {
this._super(...arguments);
this._resizeListener = Ember.run.bind(this, this.calculatePreviewIsHidden);
this.get('resizeService').on('debouncedDidResize', this._resizeListener);
this.calculatePreviewIsHidden();
},
willDestroy: function () {
this.get('resizeService').off('debouncedDidResize', this._resizeListener);
}
});
| Fix teardown of resize handler in content management screen | Fix teardown of resize handler in content management screen
refs #5659 ([comment](https://github.com/TryGhost/Ghost/issues/5659#issuecomment-137114898))
- cleans up resize handler on willDestroy hook of gh-content-view-container
| JavaScript | mit | TryGhost/Ghost-Admin,kevinansfield/Ghost-Admin,dbalders/Ghost-Admin,kevinansfield/Ghost-Admin,acburdine/Ghost-Admin,airycanon/Ghost-Admin,JohnONolan/Ghost-Admin,TryGhost/Ghost-Admin,JohnONolan/Ghost-Admin,acburdine/Ghost-Admin,dbalders/Ghost-Admin,airycanon/Ghost-Admin | ---
+++
@@ -8,6 +8,8 @@
resizeService: Ember.inject.service(),
+ _resizeListener: null,
+
calculatePreviewIsHidden: function () {
if (this.$('.content-preview').length) {
this.set('previewIsHidden', !this.$('.content-preview').is(':visible'));
@@ -16,8 +18,12 @@
didInsertElement: function () {
this._super(...arguments);
+ this._resizeListener = Ember.run.bind(this, this.calculatePreviewIsHidden);
+ this.get('resizeService').on('debouncedDidResize', this._resizeListener);
this.calculatePreviewIsHidden();
- this.get('resizeService').on('debouncedDidResize',
- Ember.run.bind(this, this.calculatePreviewIsHidden));
+ },
+
+ willDestroy: function () {
+ this.get('resizeService').off('debouncedDidResize', this._resizeListener);
}
}); |
2d5eeac4f046d09d7f2bab77f7f65a89a84d5f46 | app/js/components/service_edit_attribute.js | app/js/components/service_edit_attribute.js | 'use strict';
$(document).ready(function() {
function enableOrDisableAttributeField() {
var rows = $(this)
.parents('.attribute-row-wrapper')
.find('.form-row');
if ($(this).is(':checked')) {
rows.removeClass('disabled');
var motivation = rows.find('input.motivation');
motivation.removeAttr('disabled');
motivation.val(motivation.data('old-value'));
} else {
rows.addClass('disabled');
rows.find('input.motivation').attr('disabled', 'disabled');
var motivation = rows.find('input.motivation');
motivation.data('old-value', motivation.val());
motivation.val('');
}
}
$('input.requested').each(enableOrDisableAttributeField);
$('input.requested').on('change', enableOrDisableAttributeField);
});
| 'use strict';
$(document).ready(function() {
function enableOrDisableAttributeField() {
var rows = $(this)
.parents('.attribute-row-wrapper')
.find('.form-row');
if ($(this).is(':checked')) {
rows.removeClass('disabled');
var motivation = rows.find('input.motivation');
motivation.removeAttr('disabled');
if (motivation.data('old-value')) {
motivation.val(motivation.data('old-value'));
}
} else {
rows.addClass('disabled');
rows.find('input.motivation').attr('disabled', 'disabled');
var motivation = rows.find('input.motivation');
motivation.data('old-value', motivation.val());
motivation.val('');
}
}
$('input.requested').each(enableOrDisableAttributeField);
$('input.requested').on('change', enableOrDisableAttributeField);
});
| Fix service edit javascript bug | Fix service edit javascript bug
The value that was set was overwritten directly.
| JavaScript | apache-2.0 | SURFnet/sp-dashboard,SURFnet/sp-dashboard,SURFnet/sp-dashboard,SURFnet/sp-dashboard,SURFnet/sp-dashboard | ---
+++
@@ -11,7 +11,9 @@
var motivation = rows.find('input.motivation');
motivation.removeAttr('disabled');
- motivation.val(motivation.data('old-value'));
+ if (motivation.data('old-value')) {
+ motivation.val(motivation.data('old-value'));
+ }
} else {
rows.addClass('disabled');
rows.find('input.motivation').attr('disabled', 'disabled'); |
62b7d5f8a318de1ab1a9656e063127ae1377dae5 | waffle/templates/waffle/waffle.js | waffle/templates/waffle/waffle.js | (function(){
var FLAGS = {
{% for flag, value in flags %}'{{ flag }}': {% if value %}true{% else %}false{% endif %}{% if not forloop.last %},{% endif %}{% endfor %}
},
SWITCHES = {
{% for switch, value in switches %}'{{ switch }}': {% if value %}true{% else %}false{% endif %}{% if not forloop.last %},{% endif %}{% endfor %}
},
SAMPLES = {
{% for sample, value in samples %}'{{ sample }}': {% if value %}true{% else %}false{% endif %}{% if not forloop.last %},{% endif %}{% endfor %}
};
window.waffle = {
"flag_is_active": function waffle_flag(flag_name) {
{% if flag_default %}
if(FLAGS[flag_name] === undefined) return true;
{% endif %}
return !!FLAGS[flag_name];
},
"switch_is_active": function waffle_switch(switch_name) {
{% if switch_default %}
if(SWITCHES[switch_name] === undefined) return true;
{% endif %}
return !!SWITCHES[switch_name];
},
"sample_is_active": function waffle_sample(sample_name) {
{% if sample_default %}
if(SAMPLES[sample_name] === undefined) return true;
{% endif %}
return !!SAMPLES[sample_name];
}
};
})();
| (function(){
var FLAGS = {
{% for flag, value in flags %}'{{ flag }}': {% if value %}true{% else %}false{% endif %}{% if not forloop.last %},{% endif %}{% endfor %}
},
SWITCHES = {
{% for switch, value in switches %}'{{ switch }}': {% if value %}true{% else %}false{% endif %}{% if not forloop.last %},{% endif %}{% endfor %}
},
SAMPLES = {
{% for sample, value in samples %}'{{ sample }}': {% if value %}true{% else %}false{% endif %}{% if not forloop.last %},{% endif %}{% endfor %}
};
window.waffle = {
"get_flags": function get_flags() {
return FLAGS;
},
"flag_is_active": function waffle_flag(flag_name) {
{% if flag_default %}
if(FLAGS[flag_name] === undefined) return true;
{% endif %}
return !!FLAGS[flag_name];
},
"switch_is_active": function waffle_switch(switch_name) {
{% if switch_default %}
if(SWITCHES[switch_name] === undefined) return true;
{% endif %}
return !!SWITCHES[switch_name];
},
"sample_is_active": function waffle_sample(sample_name) {
{% if sample_default %}
if(SAMPLES[sample_name] === undefined) return true;
{% endif %}
return !!SAMPLES[sample_name];
}
};
})();
| Add get_flags method to access all flags | Add get_flags method to access all flags
| JavaScript | bsd-3-clause | webus/django-waffle,groovecoder/django-waffle,mwaaas/django-waffle-session,engagespark/django-waffle,webus/django-waffle,ilanbm/django-waffle,rodgomes/django-waffle,rlr/django-waffle,rodgomes/django-waffle,rlr/django-waffle,JeLoueMonCampingCar/django-waffle,crccheck/django-waffle,groovecoder/django-waffle,isotoma/django-waffle,mwaaas/django-waffle-session,festicket/django-waffle,isotoma/django-waffle,ilanbm/django-waffle,ilanbm/django-waffle,safarijv/django-waffle,hwkns/django-waffle,ilanbm/django-waffle,paulcwatts/django-waffle,paulcwatts/django-waffle,rsalmaso/django-waffle,mark-adams/django-waffle,mark-adams/django-waffle,rsalmaso/django-waffle,styleseat/django-waffle,crccheck/django-waffle,engagespark/django-waffle,rsalmaso/django-waffle,crccheck/django-waffle,webus/django-waffle,safarijv/django-waffle,TwigWorld/django-waffle,TwigWorld/django-waffle,isotoma/django-waffle,festicket/django-waffle,ekohl/django-waffle,engagespark/django-waffle,paulcwatts/django-waffle,ekohl/django-waffle,willkg/django-waffle,VladimirFilonov/django-waffle,VladimirFilonov/django-waffle,safarijv/django-waffle,rodgomes/django-waffle,TwigWorld/django-waffle,JeLoueMonCampingCar/django-waffle,crccheck/django-waffle,engagespark/django-waffle,VladimirFilonov/django-waffle,styleseat/django-waffle,willkg/django-waffle,safarijv/django-waffle,VladimirFilonov/django-waffle,rodgomes/django-waffle,festicket/django-waffle,hwkns/django-waffle,mwaaas/django-waffle-session,groovecoder/django-waffle,groovecoder/django-waffle,webus/django-waffle,styleseat/django-waffle,hwkns/django-waffle,paulcwatts/django-waffle,rlr/django-waffle,isotoma/django-waffle,mwaaas/django-waffle-session,rlr/django-waffle,JeLoueMonCampingCar/django-waffle,styleseat/django-waffle,mark-adams/django-waffle,mark-adams/django-waffle,festicket/django-waffle,JeLoueMonCampingCar/django-waffle,hwkns/django-waffle,rsalmaso/django-waffle | ---
+++
@@ -9,6 +9,9 @@
{% for sample, value in samples %}'{{ sample }}': {% if value %}true{% else %}false{% endif %}{% if not forloop.last %},{% endif %}{% endfor %}
};
window.waffle = {
+ "get_flags": function get_flags() {
+ return FLAGS;
+ },
"flag_is_active": function waffle_flag(flag_name) {
{% if flag_default %}
if(FLAGS[flag_name] === undefined) return true; |
9ec283d23a5c7f85e47e0e6ea8f78dce74d756c4 | src/main/webapp/controllers/maincontroller.js | src/main/webapp/controllers/maincontroller.js | ords.controller('mainController', function($rootScope,$location, User, Project) {
//
// If we're not logged in, redirect to login
//
$rootScope.user = User.get(
function successCallback() {
$rootScope.loggedIn="yes"
//
// Load initial projects
//
Project.query({}, function(data){
$rootScope.projects = data;
});
$location.path("/projects");
},
function errorCallback() {
$rootScope.loggedIn="no"
$location.path("/");
}
);
}); | ords.controller('mainController', function(AuthService) {
//
// Conduct auth check
//
AuthService.check();
}); | Use AuthService rather than custom controller code | Use AuthService rather than custom controller code
| JavaScript | apache-2.0 | ox-it/ords-ui,ox-it/ords-ui,ox-it/ords-ui,ox-it/ords-ui,ox-it/ords-ui | ---
+++
@@ -1,23 +1,8 @@
-ords.controller('mainController', function($rootScope,$location, User, Project) {
-
- //
- // If we're not logged in, redirect to login
- //
- $rootScope.user = User.get(
- function successCallback() {
- $rootScope.loggedIn="yes"
- //
- // Load initial projects
- //
- Project.query({}, function(data){
- $rootScope.projects = data;
- });
- $location.path("/projects");
- },
- function errorCallback() {
- $rootScope.loggedIn="no"
- $location.path("/");
- }
- );
+ords.controller('mainController', function(AuthService) {
+
+ //
+ // Conduct auth check
+ //
+ AuthService.check();
}); |
8e90194f7d38136be48bfebc8fc3c45d88dbc2d6 | shells/browser/shared/src/renderer.js | shells/browser/shared/src/renderer.js | /**
* In order to support reload-and-profile functionality, the renderer needs to be injected before any other scripts.
* Since it is a complex file (with imports) we can't just toString() it like we do with the hook itself,
* So this entry point (one of the web_accessible_resources) provcides a way to eagerly inject it.
* The hook will look for the presence of a global __REACT_DEVTOOLS_ATTACH__ and attach an injected renderer early.
* The normal case (not a reload-and-profile) will not make use of this entry point though.
*
* @flow
*/
import { attach } from 'src/backend/renderer';
Object.defineProperty(
window,
'__REACT_DEVTOOLS_ATTACH__',
({
enumerable: false,
configurable: true,
get() {
return attach;
},
}: Object)
);
| /**
* In order to support reload-and-profile functionality, the renderer needs to be injected before any other scripts.
* Since it is a complex file (with imports) we can't just toString() it like we do with the hook itself,
* So this entry point (one of the web_accessible_resources) provcides a way to eagerly inject it.
* The hook will look for the presence of a global __REACT_DEVTOOLS_ATTACH__ and attach an injected renderer early.
* The normal case (not a reload-and-profile) will not make use of this entry point though.
*
* @flow
*/
import { attach } from 'src/backend/renderer';
Object.defineProperty(
window,
'__REACT_DEVTOOLS_ATTACH__',
({
enumerable: false,
// This property needs to be configurable to allow third-party integrations
// to attach their own renderer. Note that using third-party integrations
// is not officially supported. Use at your own risk.
configurable: true,
get() {
return attach;
},
}: Object)
);
| Add comment about 3rd party integrations | Add comment about 3rd party integrations
| JavaScript | mit | facebook/react,TheBlasfem/react,mosoft521/react,terminatorheart/react,acdlite/react,acdlite/react,jzmq/react,chenglou/react,Simek/react,facebook/react,jzmq/react,flarnie/react,yungsters/react,rricard/react,flarnie/react,flarnie/react,camsong/react,ericyang321/react,tomocchino/react,Simek/react,camsong/react,camsong/react,flarnie/react,ericyang321/react,yungsters/react,terminatorheart/react,mosoft521/react,flarnie/react,billfeller/react,glenjamin/react,acdlite/react,trueadm/react,camsong/react,facebook/react,chenglou/react,yungsters/react,acdlite/react,trueadm/react,mosoft521/react,ericyang321/react,ArunTesco/react,mjackson/react,rickbeerendonk/react,chicoxyzzy/react,TheBlasfem/react,chenglou/react,cpojer/react,mjackson/react,TheBlasfem/react,mjackson/react,tomocchino/react,chenglou/react,terminatorheart/react,trueadm/react,rricard/react,glenjamin/react,acdlite/react,chicoxyzzy/react,cpojer/react,facebook/react,jzmq/react,chicoxyzzy/react,cpojer/react,terminatorheart/react,mjackson/react,ericyang321/react,chenglou/react,mjackson/react,rricard/react,yungsters/react,mjackson/react,rricard/react,TheBlasfem/react,tomocchino/react,Simek/react,Simek/react,cpojer/react,rricard/react,mosoft521/react,billfeller/react,trueadm/react,Simek/react,tomocchino/react,rricard/react,tomocchino/react,terminatorheart/react,trueadm/react,billfeller/react,glenjamin/react,trueadm/react,rickbeerendonk/react,jzmq/react,billfeller/react,jzmq/react,terminatorheart/react,cpojer/react,glenjamin/react,chenglou/react,flarnie/react,camsong/react,chicoxyzzy/react,mosoft521/react,jzmq/react,jzmq/react,facebook/react,mjackson/react,camsong/react,ericyang321/react,Simek/react,glenjamin/react,facebook/react,TheBlasfem/react,flarnie/react,chicoxyzzy/react,cpojer/react,billfeller/react,Simek/react,ArunTesco/react,camsong/react,rickbeerendonk/react,glenjamin/react,yungsters/react,yungsters/react,rickbeerendonk/react,rickbeerendonk/react,acdlite/react,ericyang321/react,acdlite/react,cpojer/react,tomocchino/react,chicoxyzzy/react,billfeller/react,billfeller/react,glenjamin/react,yungsters/react,chicoxyzzy/react,trueadm/react,ericyang321/react,tomocchino/react,chenglou/react,facebook/react,TheBlasfem/react,mosoft521/react,rickbeerendonk/react,rickbeerendonk/react,ArunTesco/react,mosoft521/react | ---
+++
@@ -15,6 +15,9 @@
'__REACT_DEVTOOLS_ATTACH__',
({
enumerable: false,
+ // This property needs to be configurable to allow third-party integrations
+ // to attach their own renderer. Note that using third-party integrations
+ // is not officially supported. Use at your own risk.
configurable: true,
get() {
return attach; |
b9f5c1d83112dd6cd4ac4ccfb3d1d7e2d74c072e | public/app/scripts/services/user.js | public/app/scripts/services/user.js | angular.module('publicApp').service('UserService', ['$http','$location', function($http, $location) {
var user = {
isLogged: false,
username: '',
login: function(username, password) {
user = this
$http.post('/api/v1/sessions', {
name: username,
password: password
}).success(function(response){
if (!!response.session.username) {
this.isLogged = true,
this.username = username
console.log('about to redirect to /gateway_account')
$location.path('/gatway_account');
} else {
$location.path('/admin/users/new');
}
}).error(function(){
})
}
}
return user
}])
| angular.module('publicApp').service('UserService', ['$http','$location', function($http, $location) {
var user = {
isLogged: false,
username: '',
updateSession: function(fn){
$http.get('/api/v1/sessions').success(function(resp){
console.log('response')
console.log(resp)
if (resp.success && resp.session) {
console.log('yes')
console.log(user)
user.isLogged = true
user.username = resp.session.username
console.log('user',user)
$location.path('/gateway_account')
}
})
},
login: function(username, password) {
$http.post('/api/v1/sessions', {
name: username,
password: password
}).success(function(response){
if (!!response.session.username) {
user.isLogged = true,
user.username = username
console.log('about to redirect to /gateway_account')
$location.path('/gateway_account');
} else {
$location.path('/admin/users/new');
}
}).error(function(){
})
}
}
return user
}])
| Add the updateSession method to the UserService | [FEATURE] Add the updateSession method to the UserService
| JavaScript | isc | zealord/gatewayd,Parkjeahwan/awegeeks,crazyquark/gatewayd,whotooktwarden/gatewayd,xdv/gatewayd,Parkjeahwan/awegeeks,xdv/gatewayd,whotooktwarden/gatewayd,crazyquark/gatewayd,zealord/gatewayd | ---
+++
@@ -3,17 +3,31 @@
isLogged: false,
username: '',
+ updateSession: function(fn){
+ $http.get('/api/v1/sessions').success(function(resp){
+ console.log('response')
+ console.log(resp)
+ if (resp.success && resp.session) {
+ console.log('yes')
+ console.log(user)
+ user.isLogged = true
+ user.username = resp.session.username
+ console.log('user',user)
+ $location.path('/gateway_account')
+ }
+ })
+ },
+
login: function(username, password) {
- user = this
$http.post('/api/v1/sessions', {
name: username,
password: password
}).success(function(response){
if (!!response.session.username) {
- this.isLogged = true,
- this.username = username
+ user.isLogged = true,
+ user.username = username
console.log('about to redirect to /gateway_account')
- $location.path('/gatway_account');
+ $location.path('/gateway_account');
} else {
$location.path('/admin/users/new');
} |
142e8924e238a5eeae8a74a826ea3f66a21d969b | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
// Important to import jquery_ujs before rails-bundle as that patches jquery xhr to use the authenticity token!
//= require rails-bundle
//= require turbolinks
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
// Important to import jquery_ujs before rails-bundle as that patches jquery xhr to use the authenticity token!
//= require rails-bundle
//= require turbolinks
| Add bootstrap-sprockets to js manifest | Add bootstrap-sprockets to js manifest
| JavaScript | mit | RomanovRoman/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,stevecj/term_palette_maker,stevecj/term_palette_maker,thiagoc7/react-webpack-rails-tutorial,RomanovRoman/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,csmalin/react-webpack-rails-tutorial,CerebralStorm/workout_logger,shakacode/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,jeffthemaximum/jeffline,roxolan/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,stevecj/term_palette_maker,StanBoyet/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,michaelgruber/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,mscienski/stpauls,roxolan/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,justin808/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,jeffthemaximum/jeffline,hoffmanc/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,CerebralStorm/workout_logger,stevecj/term_palette_maker,szyablitsky/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,shakacode/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,mscienski/stpauls,BadAllOff/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,jeffthemaximum/jeffline,shilu89757/react-webpack-rails-tutorial,jeffthemaximum/jeffline,RomanovRoman/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,CerebralStorm/workout_logger,BadAllOff/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,csmalin/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,suzukaze/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,suzukaze/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,CerebralStorm/workout_logger,suzukaze/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,RomanovRoman/react-webpack-rails-tutorial,csmalin/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,shakacode/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,roxolan/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,shakacode/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,kentwilliam/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,jeffthemaximum/jeffline,csmalin/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,phosphene/react-on-rails-cherrypick | ---
+++
@@ -13,6 +13,8 @@
//= require jquery
//= require jquery_ujs
+//= require bootstrap-sprockets
+
// Important to import jquery_ujs before rails-bundle as that patches jquery xhr to use the authenticity token!
//= require rails-bundle |
df1e74ea954460dd0379a11017d52d31b3f7df6c | src/scripts/config.js | src/scripts/config.js | 'use strict';
module.exports = {
CATEGORY_NAME_MAXLENGTH: 20,
NOTE_TITLE_MAXLENGTH: 20,
NOTE_BODY_MAXLENGTH: 500,
UNSPECIFIED_CATEGORY_NAME: 'Unspecified'
};
| 'use strict';
module.exports = {
CATEGORY_NAME_MAXLENGTH: 20,
NOTE_TITLE_MAXLENGTH: 20,
NOTE_BODY_MAXLENGTH: 1000,
UNSPECIFIED_CATEGORY_NAME: 'Unspecified'
};
| Increase note body max length | Increase note body max length
| JavaScript | mit | iuux/adrx-quicknotes,iuux/adrx-quicknotes | ---
+++
@@ -3,6 +3,6 @@
module.exports = {
CATEGORY_NAME_MAXLENGTH: 20,
NOTE_TITLE_MAXLENGTH: 20,
- NOTE_BODY_MAXLENGTH: 500,
+ NOTE_BODY_MAXLENGTH: 1000,
UNSPECIFIED_CATEGORY_NAME: 'Unspecified'
}; |
a353142806098899952ebaa5dfb799411422948a | test/unit/prototype/detach.js | test/unit/prototype/detach.js | /* eslint-env jasmine */
var editTypes = require('../helpers/edit-types')
var makeEditableElement = ('../helpers/make-editable-element')
var Edited = require('../../..')
describe('`detach` method', function () {
it('detaches the instance\'s event listener from the instance\'s element',
function () {
var element = makeEditableElement()
var onSensible = jasmine.createSpy()
var onAny = jasmine.createSpy()
var edited = new Edited(element, onSensible, onAny)
// just checking that the callback works
editTypes.characterAddition.triggerFunc.call(edited)
editTypes.space.triggerFunc.call(edited)
expect(onSensible.calls.count()).toBe(1)
expect(onAny.calls.count()).toBe(2)
// checking that `detach` method works
edited.detach()
editTypes.backwardsRemoval.triggerFunc.call(edited)
expect(onSensible.calls.count()).toBe(1)
expect(onAny.calls.count()).toBe(2)
})
})
| /* eslint-env jasmine */
var editTypes = require('../helpers/edit-types')
var makeEditableElement = require('../helpers/make-editable-element')
var Edited = require('../../..')
describe('`detach` method', function () {
it('detaches the instance\'s event listener from the instance\'s element',
function () {
var element = makeEditableElement()
var onSensible = jasmine.createSpy()
var onAny = jasmine.createSpy()
var edited = new Edited(element, onSensible, onAny)
// just checking that the callback works
editTypes.characterAddition.triggerFunc.call(edited)
editTypes.space.triggerFunc.call(edited)
expect(onSensible.calls.count()).toBe(1)
expect(onAny.calls.count()).toBe(2)
// checking that `detach` method works
edited.detach()
editTypes.backwardsRemoval.triggerFunc.call(edited)
expect(onSensible.calls.count()).toBe(1)
expect(onAny.calls.count()).toBe(2)
})
})
| Fix typo in unit test | Fix typo in unit test
| JavaScript | bsd-3-clause | PolicyStat/edited | ---
+++
@@ -1,6 +1,6 @@
/* eslint-env jasmine */
var editTypes = require('../helpers/edit-types')
-var makeEditableElement = ('../helpers/make-editable-element')
+var makeEditableElement = require('../helpers/make-editable-element')
var Edited = require('../../..')
describe('`detach` method', function () { |
0244e6d127837776eff2605fdd4d067eee8930d2 | elements/uql-apps-button/uql-apps-button.js | elements/uql-apps-button/uql-apps-button.js |
(function () {
Polymer({
is: 'uql-apps-button',
properties: {
/** Whether to display title of the button */
showTitle: {
type: Boolean,
value: true
},
/** Button title text */
buttonTitle: {
type: String,
value: "My Library"
},
/** Value of redirect URL */
redirectUrl: {
type: String,
value: "https://app.library.uq.edu.au/auth/mylibrary"
}
},
/** Redirects to the specified URL */
_myLibraryClicked: function() {
window.location.href = this.redirectUrl;
}
});
})(); |
(function () {
Polymer({
is: 'uql-apps-button',
properties: {
/** Whether to display title of the button */
showTitle: {
type: Boolean,
value: true
},
/** Button title text */
buttonTitle: {
type: String,
value: "My Library"
},
/** Value of redirect URL */
redirectUrl: {
type: String,
value: "https://www..library.uq.edu.au/mylibrary"
}
},
/** Redirects to the specified URL */
_myLibraryClicked: function() {
window.location.href = this.redirectUrl;
}
});
})(); | Change My Library auth url | Change My Library auth url
| JavaScript | mit | uqlibrary/uqlibrary-reusable-components,uqlibrary/uqlibrary-reusable-components,uqlibrary/uqlibrary-reusable-components | ---
+++
@@ -16,7 +16,7 @@
/** Value of redirect URL */
redirectUrl: {
type: String,
- value: "https://app.library.uq.edu.au/auth/mylibrary"
+ value: "https://www..library.uq.edu.au/mylibrary"
}
},
|
47359eac53865925a8e97c5dffc7d064da7858ed | src/js/app/modules/user/RegisterController.js | src/js/app/modules/user/RegisterController.js | /**
* Registers a new user. After signing up, the user gets an activation code per mail. With this
* code, the user can activate his account.
*/
app.controller('RegisterController', function($scope, $location, $http){
// $scope.user = {
// username: "henkie",
// fullname: "Henkie Henk",
// email: "henkie@henk.nl",
// password: "henkiehenk"
// };
// $scope.passwordretype = $scope.user.password;
/**
* Cancels the registration and takes the user back to the main page
*/
$scope.cancel = function(){
$location.path('/');
};
$scope.register = function(){
$http.post('/api/user/create', {
username: $scope.form.username.$modelValue,
email: $scope.form.email.$modelValue,
password: $scope.form.password.$modelValue
}).
success(function(data, status, headers, config) {
console.log("data, status, headers, config", data, status, headers, config);
$scope.registered = !$scope.registered;
}).
error(function(data, status, headers, config) {
console.log("data, status, headers, config", data, status, headers, config);
});
};
}); | /**
* Registers a new user. After signing up, the user gets an activation code per mail. With this
* code, the user can activate his account.
*/
app.controller('RegisterController', function($scope, $location, $http){
// $scope.user = {
// username: "henkie",
// fullname: "Henkie Henk",
// email: "henkie@henk.nl",
// password: "henkiehenk"
// };
// $scope.passwordretype = $scope.user.password;
/**
* Cancels the registration and takes the user back to the main page
*/
$scope.cancel = function(){
$location.path('/');
};
$scope.register = function(){
$http({
method: 'POST',
url: '/api/user/create',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
username: $scope.form.username.$modelValue,
email: $scope.form.email.$modelValue,
password: $scope.form.password.$modelValue
}
}).success(function(data, status, headers, config) {
console.log("data, status, headers, config", data, status, headers, config);
$scope.registered = !$scope.registered;
}).
error(function(data, status, headers, config) {
console.log("data, status, headers, config", data, status, headers, config);
});
};
}); | Use url encoded form data in http request | Use url encoded form data in http request
| JavaScript | mit | tuvokki/hunaJS,tuvokki/hunaJS | ---
+++
@@ -19,21 +19,29 @@
};
$scope.register = function(){
-
- $http.post('/api/user/create', {
+ $http({
+ method: 'POST',
+ url: '/api/user/create',
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
+ transformRequest: function(obj) {
+ var str = [];
+ for(var p in obj)
+ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
+ return str.join("&");
+ },
+ data: {
username: $scope.form.username.$modelValue,
email: $scope.form.email.$modelValue,
password: $scope.form.password.$modelValue
- }).
- success(function(data, status, headers, config) {
+ }
+ }).success(function(data, status, headers, config) {
console.log("data, status, headers, config", data, status, headers, config);
- $scope.registered = !$scope.registered;
+ $scope.registered = !$scope.registered;
}).
error(function(data, status, headers, config) {
console.log("data, status, headers, config", data, status, headers, config);
});
-
};
}); |
1eda62d0824e7f903d031429f1a029b1ba091a28 | tests/dummy/config/targets.js | tests/dummy/config/targets.js | /* eslint-env node */
module.exports = {
browsers: [
'ie 9',
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
]
};
| /* eslint-env node */
'use strict';
const browsers = [
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
];
const isCI = !!process.env.CI;
const isProduction = process.env.EMBER_ENV === 'production';
if (isCI || isProduction) {
browsers.push('ie 11');
}
module.exports = {
browsers
};
| Drop support for IE9 and IE10 in dummy app | Drop support for IE9 and IE10 in dummy app
| JavaScript | mit | jonathanKingston/ember-cli-eslint,ember-cli/ember-cli-eslint,jonathanKingston/ember-cli-eslint,ember-cli/ember-cli-eslint | ---
+++
@@ -1,10 +1,19 @@
/* eslint-env node */
+'use strict';
+
+const browsers = [
+ 'last 1 Chrome versions',
+ 'last 1 Firefox versions',
+ 'last 1 Safari versions'
+];
+
+const isCI = !!process.env.CI;
+const isProduction = process.env.EMBER_ENV === 'production';
+
+if (isCI || isProduction) {
+ browsers.push('ie 11');
+}
module.exports = {
- browsers: [
- 'ie 9',
- 'last 1 Chrome versions',
- 'last 1 Firefox versions',
- 'last 1 Safari versions'
- ]
+ browsers
}; |
22fa345844216bd692b62692b91d19e83b2565e1 | tests/reducers/errors-test.js | tests/reducers/errors-test.js | import errors from '../../src/reducers/errors';
import { GET_DATA_FAILED } from '../../src/actions/data';
describe('errors reducer', () => {
describe(`action type ${GET_DATA_FAILED}`, () => {
it('returns the error passed in an errors array', () => {
expect(errors([], {
type: GET_DATA_FAILED,
payload: {
errors: ['foo'],
},
})).toEqual(['foo']);
});
it('joins the new error with existing errors', () => {
expect(errors(['fizz', 'baz'], {
type: GET_DATA_FAILED,
payload: {
errors: ['foo'],
},
})).toEqual(['foo', 'fizz', 'baz']);
});
it('can accept multiple errors', () => {
expect(errors(['fizz', 'baz'], {
type: GET_DATA_FAILED,
payload: {
errors: ['foo', 'bar'],
},
})).toEqual(['foo', 'bar', 'fizz', 'baz']);
});
});
});
| import errors from '../../src/reducers/errors';
import { GET_DATA_FAILED } from '../../src/actions/data';
describe('errors reducer', () => {
describe(`action type ${GET_DATA_FAILED}`, () => {
it('returns the error passed in an errors array', () => {
expect(errors([], {
type: GET_DATA_FAILED,
payload: {
errors: ['foo'],
},
})).toEqual(['foo']);
});
it('joins the new error with existing errors', () => {
expect(errors(['fizz', 'baz'], {
type: GET_DATA_FAILED,
payload: {
errors: ['foo'],
},
})).toEqual(['foo', 'fizz', 'baz']);
});
it('can accept multiple errors', () => {
expect(errors(['fizz', 'baz'], {
type: GET_DATA_FAILED,
payload: {
errors: ['foo', 'bar'],
},
})).toEqual(['foo', 'bar', 'fizz', 'baz']);
});
});
describe('by default', () => {
it('does nothing', () => {
expect(errors({}, { type: 'foo' })).toEqual({});
});
it('preserves passed state', () => {
const state = { foo: 'bar' };
expect(errors(state, { type: 'foo' })).toEqual(state);
});
});
});
| Cover two uncovered lines in error reducer test | Cover two uncovered lines in error reducer test [skip ci]
| JavaScript | mit | bjacobel/react-redux-boilerplate,bjacobel/rak,bjacobel/react-redux-boilerplate,bjacobel/rak,bjacobel/rak | ---
+++
@@ -30,4 +30,15 @@
})).toEqual(['foo', 'bar', 'fizz', 'baz']);
});
});
+
+ describe('by default', () => {
+ it('does nothing', () => {
+ expect(errors({}, { type: 'foo' })).toEqual({});
+ });
+
+ it('preserves passed state', () => {
+ const state = { foo: 'bar' };
+ expect(errors(state, { type: 'foo' })).toEqual(state);
+ });
+ });
}); |
902d7e748e7f20ab64c60ff4b1c8b3bc55881ce7 | greatbigcrane/media/js/jquery.lineeditor.js | greatbigcrane/media/js/jquery.lineeditor.js | (function($) {
jQuery.fn.lineeditor = function (options, callback) {
return this.each(function () {
var el = this;
var $el = $(this);
if ( el.nodeName.toLowerCase() != 'textarea' ) { return; }
var hidden = $('<input type="hidden"/>').attr('id', el.id);
var container = $('<div class="lineeditor"></div>');
var val = $el.val();
hidden.val(val);
container.append(hidden);
container.append($('<a href="#add-line">Add Line</a>').click(addLine));
$.each(val.split("\n"),function(){
addLine(this);
});
$el.replaceWith(container);
function addLine(value) {
value = ( value.target ? value.preventDefault() && '' : value );
var node = $('<input type="text"/>').val(value?value.toString():'');
var delete_node = $('<a href="#delete" class="delete">Delete</a>').click(removeLine);
container.find('a:last').before(node, delete_node);
}
function removeLine(ev) {
ev.preventDefault();
$(this).prev().remove();
$(this).remove();
}
})
}
})(jQuery); | (function($) {
jQuery.fn.lineeditor = function (options, callback) {
return this.each(function () {
var el = this;
var $el = $(this);
if ( el.nodeName.toLowerCase() != 'textarea' ) { return; }
var hidden = $('<input type="hidden"/>').attr('id', el.id);
var container = $('<div class="lineeditor"></div>');
var val = $el.val();
hidden.val(val);
container.append(hidden);
container.append($('<a href="#add-line">Add Line</a>').click(addLine));
$.each(val.split("\n"),function(){
addLine(this);
});
$el.replaceWith(container);
function addLine(value) {
value = ( value.target ? value.preventDefault() && '' : value );
var node = $('<input type="text"/>').val(value?value.toString():'');
var delete_node = $('<a href="#delete" class="delete">Delete</a>').click(removeLine);
container.find('a:last').before(node, delete_node);
processValues();
}
function removeLine(ev) {
ev.preventDefault();
$(this).prev().remove();
$(this).remove();
processValues();
}
function processValues() {
var val = '';
container.find('input[type=text]').each(function(){
val += $(this).val() + "\n";
})
hidden.val(val);
}
})
}
})(jQuery); | Make sure the input value is kept up-to-date ... | Make sure the input value is kept up-to-date ...
| JavaScript | apache-2.0 | pnomolos/greatbigcrane,pnomolos/greatbigcrane | ---
+++
@@ -26,12 +26,22 @@
var node = $('<input type="text"/>').val(value?value.toString():'');
var delete_node = $('<a href="#delete" class="delete">Delete</a>').click(removeLine);
container.find('a:last').before(node, delete_node);
+ processValues();
}
function removeLine(ev) {
ev.preventDefault();
$(this).prev().remove();
$(this).remove();
+ processValues();
+ }
+
+ function processValues() {
+ var val = '';
+ container.find('input[type=text]').each(function(){
+ val += $(this).val() + "\n";
+ })
+ hidden.val(val);
}
}) |
0ec75f2cc954d2012d7be5cc1301f6153989b4de | modules/drinks/client/controllers/list-drinks.client.controller.js | modules/drinks/client/controllers/list-drinks.client.controller.js | (function () {
'use strict';
angular
.module('drinks', ['ngAnimate', 'toastr'])
.controller('DrinksListController', DrinksListController);
DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr'];
function DrinksListController(DrinksService, $state, $scope, toastr) {
var vm = this;
vm.AddToMenu = AddToMenu;
vm.mvOnMenu = mvOnMenu;
vm.mvOffMenu = mvOffMenu;
vm.drinks = DrinksService.query();
function AddToMenu(drink) {
drink.$update(successCallback, errorCallback);
function successCallback(res) {
$state.go('drinks.list', {
drinkId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
function mvOnMenu(drink) {
toastr.success(drink.drinkName + ' was added to tap!');
}
function mvOffMenu(drink) {
toastr.success(drink.drinkName + ' was removed from tap!');
}
}
})();
| (function () {
'use strict';
angular
.module('drinks', ['ngAnimate', 'toastr'])
.controller('DrinksListController', DrinksListController);
DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr'];
function DrinksListController(DrinksService, $state, $scope, toastr) {
var vm = this;
vm.AddToMenu = AddToMenu;
vm.mvOnMenu = mvOnMenu;
vm.mvOffMenu = mvOffMenu;
vm.drinks = DrinksService.query();
function AddToMenu(drink) {
drink.$update(successCallback, errorCallback);
function successCallback(res) {
$state.go('drinks.list', {
drinkId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
//Menu drink toggle notification via toastr
function mvOnMenu(drink) {
toastr.success(
drink.drinkName + ' was added to tap!',
{
closeHtml: '<button></button>'
}
);
}
function mvOffMenu(drink) {
toastr.success(
drink.drinkName + ' was removed from tap!'
);
}
}
})();
| Comment and toast delete tested | Comment and toast delete tested
| JavaScript | mit | UF-SE-3B/SwampHead-Brewery,UF-SE-3B/SwampHead-Brewery,UF-SE-3B/SwampHead-Brewery | ---
+++
@@ -29,12 +29,20 @@
}
}
+ //Menu drink toggle notification via toastr
function mvOnMenu(drink) {
- toastr.success(drink.drinkName + ' was added to tap!');
+ toastr.success(
+ drink.drinkName + ' was added to tap!',
+ {
+ closeHtml: '<button></button>'
+ }
+ );
+ }
+ function mvOffMenu(drink) {
+ toastr.success(
+ drink.drinkName + ' was removed from tap!'
+ );
}
- function mvOffMenu(drink) {
- toastr.success(drink.drinkName + ' was removed from tap!');
- }
}
})(); |
6eecd63cbe03ce0b0373b5a616621a1305071d25 | examples/instances.js | examples/instances.js | var instances = require('./../taillard');
var NEH = require('./../neh');
// Iterate over filtered Taillard instances
var filteredInstances = instances.filter(50, 20);
for(var i = 0; i < filteredInstances.length; i++) {
console.log(' name:', filteredInstances[i].name);
console.log(' number of jobs:', filteredInstances[i].numberOfJobs);
console.log(' number of machines:', filteredInstances[i].numberOfMachines);
console.log(' initial seed:', filteredInstances[i].initialSeed);
console.log(' lower bound:', filteredInstances[i].lowerBound);
console.log(' upper bound:', filteredInstances[i].upperBound);
console.log(' NEH makespan:', NEH.makespan(filteredInstances[i].data));
console.log('__________________________________________________');
}
| var instances = require('./../taillard');
var NEH = require('./../neh');
var seed = require('./../seed-random');
// Iterate over filtered Taillard instances
var filteredInstances = instances.filter(50, 20);
for(var i = 0; i < filteredInstances.length; i++) {
// Overwrite Math.random by number generator with seed
seed(filteredInstances[i].initialSeed, true);
console.log(' name:', filteredInstances[i].name);
console.log(' number of jobs:', filteredInstances[i].numberOfJobs);
console.log(' number of machines:', filteredInstances[i].numberOfMachines);
console.log(' initial seed:', filteredInstances[i].initialSeed);
console.log(' lower bound:', filteredInstances[i].lowerBound);
console.log(' upper bound:', filteredInstances[i].upperBound);
console.log(' NEH makespan:', NEH.makespan(filteredInstances[i].data));
console.log('__________________________________________________');
}
| Use number generator with seed | Use number generator with seed
| JavaScript | mit | manfredbork/flowshop | ---
+++
@@ -1,9 +1,13 @@
var instances = require('./../taillard');
var NEH = require('./../neh');
+var seed = require('./../seed-random');
// Iterate over filtered Taillard instances
var filteredInstances = instances.filter(50, 20);
for(var i = 0; i < filteredInstances.length; i++) {
+
+ // Overwrite Math.random by number generator with seed
+ seed(filteredInstances[i].initialSeed, true);
console.log(' name:', filteredInstances[i].name);
console.log(' number of jobs:', filteredInstances[i].numberOfJobs); |
88fb80bb09b7f73c27eff9e2bc5dc4551fdf8b71 | src/main/webapp/scripts/app/app.constants.js | src/main/webapp/scripts/app/app.constants.js | "use strict";
// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE
angular.module('publisherApp')
.constant('ENV', 'dev')
.constant('VERSION', '1.1.3-SNAPSHOT')
; | "use strict";
// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE
angular.module('publisherApp')
.constant('ENV', 'dev')
.constant('VERSION', '1.1.4-SNAPSHOT')
; | Update ngconstant version after releasing | Update ngconstant version after releasing
| JavaScript | apache-2.0 | EsupPortail/esup-publisher,EsupPortail/esup-publisher,GIP-RECIA/esup-publisher-ui,EsupPortail/esup-publisher,GIP-RECIA/esup-publisher-ui,EsupPortail/esup-publisher,GIP-RECIA/esup-publisher-ui | ---
+++
@@ -4,6 +4,6 @@
.constant('ENV', 'dev')
-.constant('VERSION', '1.1.3-SNAPSHOT')
+.constant('VERSION', '1.1.4-SNAPSHOT')
; |
5ef82e3cf4ee4d567a2a670278b1f93fe2cfe5e6 | dev/_/components/js/singleSourceModel.js | dev/_/components/js/singleSourceModel.js |
var AV = {}
AV.source = Backbone.Model.extend({
url: 'redirect.php',
defaults: {
name: '',
type: 'raw',
contentType: 'txt',
data: ''
}
});
|
var AV = {};
AV.source = Backbone.Model.extend({
url: 'redirect.php',
defaults: {
name: '',
type: 'raw',
contentType: 'txt',
data: ''
}
});
| Add missing semicolon, because JS is weird. | Add missing semicolon, because JS is weird.
| JavaScript | bsd-3-clause | Swarthmore/juxtaphor,Swarthmore/juxtaphor | ---
+++
@@ -1,5 +1,5 @@
-var AV = {}
+var AV = {};
AV.source = Backbone.Model.extend({
url: 'redirect.php', |
199aec30d6c5746f74f295f04c2509187ff0bcd5 | src/directives/conversationControl.js | src/directives/conversationControl.js | ;(function() {
'use strict';
angular.module('gebo-client-performatives.conversationControl',
['gebo-client-performatives.request',
'templates/server-reply-request.html',
'templates/client-reply-request.html',
'templates/server-propose-discharge-perform.html',
'templates/client-propose-discharge-perform.html',
'templates/server-reply-propose-discharge-perform.html',
'templates/client-reply-propose-discharge-perform.html',
'templates/server-perform.html']).
directive('conversationControl', function ($templateCache, Request) {
function _link(scope, element, attributes) {
attributes.$observe('sc', function(newValue) {
scope.sc = newValue;
});
attributes.$observe('email', function(newValue) {
scope.email = newValue;
});
if (scope.sc && scope.email) {
var directive = Request.getDirectiveName(scope.sc, scope.email);
element.html($templateCache.get('templates/' + directive + '.html'));
}
};
return {
restrict: 'E',
link: _link,
};
});
}());
| ;(function() {
'use strict';
angular.module('gebo-client-performatives.conversationControl',
['gebo-client-performatives.request',
'templates/server-reply-request.html',
'templates/client-reply-request.html',
'templates/server-propose-discharge-perform.html',
'templates/client-propose-discharge-perform.html',
'templates/server-reply-propose-discharge-perform.html',
'templates/client-reply-propose-discharge-perform.html',
'templates/server-perform.html']).
directive('conversationControl', function ($templateCache, Request) {
function _link(scope, element, attributes) {
attributes.$observe('sc', function(newValue) {
scope.sc = newValue;
});
attributes.$observe('email', function(newValue) {
scope.email = newValue;
});
if (scope.sc && scope.email) {
var directive = Request.getDirectiveName(scope.sc, scope.email);
element.html($templateCache.get('templates/' + directive + '.html'));
}
};
return {
restrict: 'E',
scope: true,
link: _link,
};
});
}());
| Create a new scope for this directive | Create a new scope for this directive
| JavaScript | mit | RaphaelDeLaGhetto/gebo-client-performatives | ---
+++
@@ -29,6 +29,7 @@
return {
restrict: 'E',
+ scope: true,
link: _link,
};
}); |
0fb5c958d6b210bfb1a55b9fb197b4c59e612951 | server/app.js | server/app.js | const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
module.exports = app;
| const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// Serve static assets
app.use(express.static(path.resolve('..', 'build')));
// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
res.sendFile(path.resolve('..', 'build', 'index.html'));
});
module.exports = app;
| Change where the files are stored in the server | Change where the files are stored in the server
| JavaScript | mit | escudero89/my-npc-manager,escudero89/my-npc-manager | ---
+++
@@ -8,11 +8,11 @@
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// Serve static assets
-app.use(express.static(path.resolve(__dirname, '..', 'build')));
+app.use(express.static(path.resolve('..', 'build')));
// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
- res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
+ res.sendFile(path.resolve('..', 'build', 'index.html'));
});
module.exports = app; |
82d5c2644f226b3f6e3403fd8234573691ab7917 | web-app/js/smartR/Heatmap/heatmapValidator.js | web-app/js/smartR/Heatmap/heatmapValidator.js | //# sourceURL=heatmapValidator.js
'use strict';
/**
* Heatmap Validator
*/
window.HeatmapValidator = (function() {
var validator = {
NO_SUBSET_ERR : 'No subsets are selected',
NO_HD_ERR : 'No high dimension data is selected.',
NUMERICAL_ERR : 'Input must be numeric'
};
validator.isEmptySubset = function (subsets) {
return subsets.length < 1;
};
validator.isEmptyHighDimensionalData = function (hd) {
return hd === '';
};
validator.isNumeric = function (val) {
return !isNaN(val);
};
return validator;
})();
| //# sourceURL=heatmapValidator.js
'use strict';
/**
* Heatmap Validator
*/
window.HeatmapValidator = (function() {
var validator = {
NO_SUBSET_ERR : 'No subsets are selected',
NO_HD_ERR : 'No high dimension data is selected.',
NUMERICAL_ERR : 'Input must be numeric'
};
validator.isEmptySubset = function (subsets) {
// we need to filter out nulls
return subsets.filter(function(x) { return x; }).length < 1;
};
validator.isEmptyHighDimensionalData = function (hd) {
return hd === '';
};
validator.isNumeric = function (val) {
return !isNaN(val);
};
return validator;
})();
| Fix validator for existance of subsets | Fix validator for existance of subsets
| JavaScript | apache-2.0 | thehyve/heim-SmartR,thehyve/naa-SmartR,agapow/smartr,thehyve/heim-SmartR,agapow/smartr,agapow/smartr,thehyve/heim-SmartR,agapow/smartr,thehyve/naa-SmartR,thehyve/naa-SmartR,thehyve/heim-SmartR | ---
+++
@@ -14,7 +14,8 @@
};
validator.isEmptySubset = function (subsets) {
- return subsets.length < 1;
+ // we need to filter out nulls
+ return subsets.filter(function(x) { return x; }).length < 1;
};
validator.isEmptyHighDimensionalData = function (hd) { |
f28561f4dcc6280c6f1b3bc3bbee3beb18209433 | src/main/features/core/customStyle.js | src/main/features/core/customStyle.js | import fs from 'fs';
Emitter.on('FetchMainAppCustomStyles', () => {
const mainAppPath = Settings.get('mainAppStyleFile');
const css = mainAppPath && fs.existsSync(mainAppPath) ? fs.readFileSync(mainAppPath, 'utf8') : '';
Emitter.sendToAll('LoadMainAppCustomStyles', css);
});
Emitter.on('FetchGPMCustomStyles', () => {
const gpmPath = Settings.get('gpmStyleFile');
const css = gpmPath && fs.existsSync(gpmPath) ? fs.readFileSync(gpmPath, 'utf8') : '';
Emitter.sendToGooglePlayMusic('LoadGPMCustomStyles', css);
});
| import fs from 'fs';
Emitter.on('FetchMainAppCustomStyles', () => {
const mainAppPath = Settings.get('mainAppStyleFile');
if (mainAppPath && fs.existsSync(mainAppPath)) {
fs.readFile(mainAppPath, 'utf8', (err, css) => {
Emitter.sendToAll('LoadMainAppCustomStyles', err ? '' : css);
});
}
});
Emitter.on('FetchGPMCustomStyles', () => {
const gpmPath = Settings.get('gpmStyleFile');
if (gpmPath && fs.existsSync(gpmPath)) {
fs.readFile(gpmPath, 'utf8', (err, css) => {
Emitter.sendToGooglePlayMusic('LoadGPMCustomStyles', err ? '' : css);
});
}
});
| Handle dumb paths being given to the custom CSS tooling | Handle dumb paths being given to the custom CSS tooling
| JavaScript | mit | petuhovskiy/Google-Play-Music-Desktop-Player-UNOFFICIAL-,petuhovskiy/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MarshallOfSound/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MarshallOfSound/Google-Play-Music-Desktop-Player-UNOFFICIAL-,petuhovskiy/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MarshallOfSound/Google-Play-Music-Desktop-Player-UNOFFICIAL- | ---
+++
@@ -2,12 +2,18 @@
Emitter.on('FetchMainAppCustomStyles', () => {
const mainAppPath = Settings.get('mainAppStyleFile');
- const css = mainAppPath && fs.existsSync(mainAppPath) ? fs.readFileSync(mainAppPath, 'utf8') : '';
- Emitter.sendToAll('LoadMainAppCustomStyles', css);
+ if (mainAppPath && fs.existsSync(mainAppPath)) {
+ fs.readFile(mainAppPath, 'utf8', (err, css) => {
+ Emitter.sendToAll('LoadMainAppCustomStyles', err ? '' : css);
+ });
+ }
});
Emitter.on('FetchGPMCustomStyles', () => {
const gpmPath = Settings.get('gpmStyleFile');
- const css = gpmPath && fs.existsSync(gpmPath) ? fs.readFileSync(gpmPath, 'utf8') : '';
- Emitter.sendToGooglePlayMusic('LoadGPMCustomStyles', css);
+ if (gpmPath && fs.existsSync(gpmPath)) {
+ fs.readFile(gpmPath, 'utf8', (err, css) => {
+ Emitter.sendToGooglePlayMusic('LoadGPMCustomStyles', err ? '' : css);
+ });
+ }
}); |
261f74e6601be137fbd707884bd245e81215ae69 | src/app/lib/feeder.js | src/app/lib/feeder.js | import events from 'events';
class Feeder extends events.EventEmitter {
queue = [];
pending = false;
changed = false;
constructor() {
super();
this.on('change', () => {
this.changed = true;
});
}
feed(data) {
this.queue = this.queue.concat(data);
this.emit('change');
}
clear() {
this.queue = [];
this.pending = false;
this.emit('change');
}
size() {
return this.queue.length;
}
next() {
if (this.queue.length === 0) {
this.pending = false;
return false;
}
const data = this.queue.shift();
this.pending = true;
this.emit('data', data);
this.emit('change');
return data;
}
isPending() {
return this.pending;
}
// Returns true if any state have changes
peek() {
const changed = this.changed;
this.changed = false;
return changed;
}
}
export default Feeder;
| import events from 'events';
class Feeder extends events.EventEmitter {
queue = [];
pending = false;
changed = false;
constructor() {
super();
this.on('change', () => {
this.changed = true;
});
}
get state() {
return {
queue: this.queue.length
};
}
feed(data) {
this.queue = this.queue.concat(data);
this.emit('change');
}
clear() {
this.queue = [];
this.pending = false;
this.emit('change');
}
size() {
return this.queue.length;
}
next() {
if (this.queue.length === 0) {
this.pending = false;
return false;
}
const data = this.queue.shift();
this.pending = true;
this.emit('data', data);
this.emit('change');
return data;
}
isPending() {
return this.pending;
}
// Returns true if any state have changes
peek() {
const changed = this.changed;
this.changed = false;
return changed;
}
}
export default Feeder;
| Return the state object using getter | Return the state object using getter
| JavaScript | mit | cncjs/cncjs,cncjs/cncjs,cheton/cnc.js,cheton/piduino-grbl,cheton/piduino-grbl,cheton/cnc,cheton/cnc.js,cheton/cnc.js,cncjs/cncjs,cheton/cnc,cheton/piduino-grbl,cheton/cnc | ---
+++
@@ -11,6 +11,11 @@
this.on('change', () => {
this.changed = true;
});
+ }
+ get state() {
+ return {
+ queue: this.queue.length
+ };
}
feed(data) {
this.queue = this.queue.concat(data); |
9d4d798038a75531741a31e1b5d62be0924c970e | components/box.js | components/box.js | import React from 'react'
import PropTypes from 'prop-types'
const Box = ({ children }) => (
<div>
{children}
<style jsx>{`
@import 'colors';
div {
background-color: $white;
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3);
padding: 1.6em 2em;
border-radius: 2px;
margin-bottom: 20px;
@media (max-width: 551px) {
padding: 0.6em 1em;
}
}
`}</style>
</div>
)
Box.propTypes = {
children: PropTypes.node
}
export default Box
| import React from 'react'
import PropTypes from 'prop-types'
const Box = ({ children, title }) => (
<div className='wrapper'>
{title && <h3>{title}</h3>}
<div className='inner'>
{children}
</div>
<style jsx>{`
@import 'colors';
.wrapper {
background-color: $white;
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3);
border-radius: 2px;
margin-bottom: 20px;
overflow: hidden;
}
h3 {
background: darken($blue, 7%);
color: $white;
margin: 0;
padding: 0.6em 1em;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
.inner {
padding: 1.6em 2em;
@media (max-width: 551px) {
padding: 1em;
}
}
`}</style>
</div>
)
Box.propTypes = {
children: PropTypes.node,
title: PropTypes.string
}
export default Box
| Allow specifying a title to Box component | Allow specifying a title to Box component
| JavaScript | mit | sgmap/inspire,sgmap/inspire | ---
+++
@@ -1,22 +1,39 @@
import React from 'react'
import PropTypes from 'prop-types'
-const Box = ({ children }) => (
- <div>
- {children}
+const Box = ({ children, title }) => (
+ <div className='wrapper'>
+ {title && <h3>{title}</h3>}
+ <div className='inner'>
+ {children}
+ </div>
<style jsx>{`
@import 'colors';
- div {
+ .wrapper {
background-color: $white;
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3);
- padding: 1.6em 2em;
border-radius: 2px;
margin-bottom: 20px;
+ overflow: hidden;
+ }
+
+ h3 {
+ background: darken($blue, 7%);
+ color: $white;
+ margin: 0;
+ padding: 0.6em 1em;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ .inner {
+ padding: 1.6em 2em;
@media (max-width: 551px) {
- padding: 0.6em 1em;
+ padding: 1em;
}
}
`}</style>
@@ -24,7 +41,8 @@
)
Box.propTypes = {
- children: PropTypes.node
+ children: PropTypes.node,
+ title: PropTypes.string
}
export default Box |
2e20144758ec8de935f924f70de092816422e770 | components/pages/Create/CreatePage.js | components/pages/Create/CreatePage.js | /**
* Created by allen on 02/06/2015.
*/
import React from "react";
import _Store from "../../../stores/_Store.js";
const defaultProps = {
title : "New To Do | Mega awesome To Do List"
};
export default React.createClass({
getDefaultProps : () => defaultProps,
getInitialState : () => {
return {
task : ""
}
},
handleTaskChange: function(event) {
this.setState({task: event.target.value});
},
render : function () {
return (
<div>
<h1>Add a To Do</h1>
<p>
<form>
<label>Title</label>
<input type="text" value={this.state.task} onChange={this.handleTaskChange} />
{this.state.task}
</form>
</p>
</div>
);
}
}); | /**
* Created by allen on 02/06/2015.
*/
import React from "react";
import _Store from "../../../stores/_Store.js";
const defaultProps = {
title : "New To Do | Mega awesome To Do List"
};
export default React.createClass({
getDefaultProps : () => defaultProps,
getInitialState : () => {
return {
task : ""
}
},
handleTaskChange: function(event) {
this.setState({task: event.target.value});
},
handleTaskAdd : function() {
if (this.state.task) {
console.log("Add:", this.state.task);
}
this.setState({
task : ""
});
event.preventDefault();
},
render : function () {
return (
<div>
<h1>Add a To Do</h1>
<p>
<form>
<div className="form-group">
<label htmlFor="taskText">Task:</label>
<input id="taskText" type="text" value={this.state.task}
className="form-control"
autoComplete="off"
onChange={this.handleTaskChange} placeholder="Type your to do here..."/>
</div>
<button onClick={this.handleTaskAdd} className="btn btn-default">Add</button>
</form>
</p>
</div>
);
}
}); | Tidy up and apply bootstrap styles to the add to do task page. | Tidy up and apply bootstrap styles to the add to do task page.
| JavaScript | mit | allenevans/react-isomorphic-demo | ---
+++
@@ -22,15 +22,32 @@
this.setState({task: event.target.value});
},
+ handleTaskAdd : function() {
+ if (this.state.task) {
+ console.log("Add:", this.state.task);
+ }
+
+ this.setState({
+ task : ""
+ });
+
+ event.preventDefault();
+ },
+
render : function () {
return (
<div>
<h1>Add a To Do</h1>
<p>
<form>
- <label>Title</label>
- <input type="text" value={this.state.task} onChange={this.handleTaskChange} />
- {this.state.task}
+ <div className="form-group">
+ <label htmlFor="taskText">Task:</label>
+ <input id="taskText" type="text" value={this.state.task}
+ className="form-control"
+ autoComplete="off"
+ onChange={this.handleTaskChange} placeholder="Type your to do here..."/>
+ </div>
+ <button onClick={this.handleTaskAdd} className="btn btn-default">Add</button>
</form>
</p>
</div> |
fbb128ca7c499d4ed3514554b9eba955c2860868 | config/env/all.js | config/env/all.js | 'use strict';
var path = require('path');
var rootPath = path.normalize(__dirname + '/../../..');
const REVIEW_STATE_FIELD = ''; // TODO: Adjust this to a new field GUID.
module.exports = {
root: rootPath,
ip: process.env.IP || '0.0.0.0',
port: process.env.PORT || 9000,
cip: {
baseURL: 'http://www.neaonline.dk/CIP',
username: process.env.CIP_USERNAME,
password: process.env.CIP_PASSWORD,
proxyMaxSockets: 10,
// rotationCategoryName: 'Rotationsbilleder', // TODO: Disable in indexing.
indexingRestriction: REVIEW_STATE_FIELD + ' is 3'
},
googleAnalyticsPropertyID: null,
// googleMapsAPIKey: '',
googleAPIKey: process.env.GOOGLE_API_KEY,
projectOxfordAPIKey: process.env.PROJECT_OXFORD_API_KEY,
esHost: process.env.ES_HOST || 'localhost:9200',
esAssetsIndex: process.env.ES_ASSETS_INDEX || 'assets',
categoryBlacklist: require('../category-blacklist.js'),
enableGeotagging: false,
filterOptions: require('../filter-options.json'),
sortOptions: require('../sort-options.json'),
assetFields: require('../asset-fields.json'),
assetLayout: require('../asset-layout.json'),
themeColor: '#262626',
appName: 'KBH Billeder',
};
| 'use strict';
var path = require('path');
var rootPath = path.normalize(__dirname + '/../..');
const REVIEW_STATE_FIELD = ''; // TODO: Adjust this to a new field GUID.
module.exports = {
root: rootPath,
ip: process.env.IP || '0.0.0.0',
port: process.env.PORT || 9000,
cip: {
baseURL: 'http://www.neaonline.dk/CIP',
username: process.env.CIP_USERNAME,
password: process.env.CIP_PASSWORD,
proxyMaxSockets: 10,
// rotationCategoryName: 'Rotationsbilleder', // TODO: Disable in indexing.
indexingRestriction: REVIEW_STATE_FIELD + ' is 3'
},
googleAnalyticsPropertyID: null,
// googleMapsAPIKey: '',
googleAPIKey: process.env.GOOGLE_API_KEY,
projectOxfordAPIKey: process.env.PROJECT_OXFORD_API_KEY,
esHost: process.env.ES_HOST || 'localhost:9200',
esAssetsIndex: process.env.ES_ASSETS_INDEX || 'assets',
categoryBlacklist: require('../category-blacklist.js'),
enableGeotagging: false,
filterOptions: require('../filter-options.json'),
sortOptions: require('../sort-options.json'),
assetFields: require('../asset-fields.json'),
assetLayout: require('../asset-layout.json'),
licenseMapping: require('../license-mapping.json'),
themeColor: '#262626',
appName: 'KBH Billeder',
};
| Add license mapping to config | Add license mapping to config
| JavaScript | mit | CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder | ---
+++
@@ -1,7 +1,7 @@
'use strict';
var path = require('path');
-var rootPath = path.normalize(__dirname + '/../../..');
+var rootPath = path.normalize(__dirname + '/../..');
const REVIEW_STATE_FIELD = ''; // TODO: Adjust this to a new field GUID.
@@ -29,6 +29,7 @@
sortOptions: require('../sort-options.json'),
assetFields: require('../asset-fields.json'),
assetLayout: require('../asset-layout.json'),
+ licenseMapping: require('../license-mapping.json'),
themeColor: '#262626',
appName: 'KBH Billeder',
}; |
448cee0d641ec8b3f75774a339d3044d6a86c037 | src/core/team-core.js | src/core/team-core.js | const {knex} = require('../util/database').connect();
import _ from 'lodash';
import {deepChangeKeyCase} from '../util';
function getTeams() {
return knex.raw(`SELECT teams.id, teams.name, SUM(COALESCE(action_types.value, 0)) AS score
FROM teams
LEFT JOIN actions ON teams.id = actions.team_id
LEFT JOIN action_types ON actions.action_type_id = action_types.id
GROUP BY teams.id, teams.name
ORDER BY score DESC, teams.id`)
.then(result => {
return _.map(result.rows, row => deepChangeKeyCase(row, 'camelCase'));
});
}
export {
getTeams
};
| const {knex} = require('../util/database').connect();
import _ from 'lodash';
import {deepChangeKeyCase} from '../util';
function getTeams() {
return knex.raw(`SELECT teams.id, teams.name, teams.image_path, SUM(COALESCE(action_types.value, 0)) AS score
FROM teams
LEFT JOIN actions ON teams.id = actions.team_id
LEFT JOIN action_types ON actions.action_type_id = action_types.id
GROUP BY teams.id, teams.name
ORDER BY score DESC, teams.id`)
.then(result => {
return _.map(result.rows, row => deepChangeKeyCase(row, 'camelCase'));
});
}
export {
getTeams
};
| Return also teams.image_path from getTeams | Return also teams.image_path from getTeams
| JavaScript | mit | futurice/wappuapp-backend,kaupunki-apina/prahapp-backend,futurice/wappuapp-backend,kaupunki-apina/prahapp-backend | ---
+++
@@ -3,7 +3,7 @@
import {deepChangeKeyCase} from '../util';
function getTeams() {
- return knex.raw(`SELECT teams.id, teams.name, SUM(COALESCE(action_types.value, 0)) AS score
+ return knex.raw(`SELECT teams.id, teams.name, teams.image_path, SUM(COALESCE(action_types.value, 0)) AS score
FROM teams
LEFT JOIN actions ON teams.id = actions.team_id
LEFT JOIN action_types ON actions.action_type_id = action_types.id |
70c1b3d7c216844748cc35bf1f71d23f568ce734 | config/js/main.js | config/js/main.js | (function() {
loadOptions();
submitHandler();
})();
function submitHandler() {
var $submitButton = $('#submitButton');
$submitButton.on('click', function() {
console.log('Submit');
var return_to = getQueryParam('return_to', 'pebblejs://close#');
document.location = return_to + encodeURIComponent(JSON.stringify(getAndStoreConfigData()));
});
}
function loadOptions() {
var $backgroundColorPicker = $('#backgroundColorPicker');
var $timeFormatCheckbox = $('#timeFormatCheckbox');
if (localStorage.backgroundColor) {
$backgroundColorPicker[0].value = localStorage.backgroundColor;
$timeFormatCheckbox[0].checked = localStorage.twentyFourHourFormat === 'true';
}
}
function getAndStoreConfigData() {
var $backgroundColorPicker = $('#backgroundColorPicker');
var $timeFormatCheckbox = $('#timeFormatCheckbox');
var options = {
backgroundColor: $backgroundColorPicker.val(),
twentyFourHourFormat: $timeFormatCheckbox[0].checked
};
localStorage.backgroundColor = options.backgroundColor;
localStorage.twentyFourHourFormat = options.twentyFourHourFormat;
console.log('Got options: ' + JSON.stringify(options));
return options;
}
function getQueryParam(variable, defaultValue) {
var query = location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] === variable) {
return decodeURIComponent(pair[1]);
}
}
return defaultValue || false;
}
| function submitHandler() {
var $submitButton = $('#submitButton');
$submitButton.on('click', function() {
console.log('Submit');
var return_to = getQueryParam('return_to', 'pebblejs://close#');
document.location = return_to + encodeURIComponent(JSON.stringify(getAndStoreConfigData()));
});
}
function loadOptions() {
var $backgroundColorPicker = $('#backgroundColorPicker');
var $timeFormatCheckbox = $('#timeFormatCheckbox');
if (localStorage.backgroundColor) {
$backgroundColorPicker[0].value = localStorage.backgroundColor;
$timeFormatCheckbox[0].checked = localStorage.twentyFourHourFormat === 'true';
}
}
function getAndStoreConfigData() {
var $backgroundColorPicker = $('#backgroundColorPicker');
var $timeFormatCheckbox = $('#timeFormatCheckbox');
var options = {
backgroundColor: $backgroundColorPicker.val(),
twentyFourHourFormat: $timeFormatCheckbox[0].checked
};
localStorage.backgroundColor = options.backgroundColor;
localStorage.twentyFourHourFormat = options.twentyFourHourFormat;
console.log('Got options: ' + JSON.stringify(options));
return options;
}
function getQueryParam(variable, defaultValue) {
var query = location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] === variable) {
return decodeURIComponent(pair[1]);
}
}
return defaultValue || false;
}
| Add loadOptions and wrap submit logic. | Add loadOptions and wrap submit logic.
| JavaScript | mit | nevraw/Fitbit-images,nevraw/Phi-Ocular,nevraw/Phi-Ocular,nevraw/Web,nevraw/Flux,nevraw/Quadrant,nevraw/Quadrant,nevraw/Edge,nevraw/Doodle,nevraw/Dual,nevraw/Test_Rocky,nevraw/Web,nevraw/IdentityCrisis,nevraw/Testing,nevraw/Quasar,nevraw/Testing,nevraw/SotoX,nevraw/Quasar,nevraw/Flux,nevraw/Doodle,nevraw/Flux,nevraw/IdentityCrisis,nevraw/Phi-Ocular,nevraw/Quadrant_Hybrid,nevraw/Flux,nevraw/SotoX,nevraw/IdentityCrisis,nevraw/Duo,nevraw/Web,nevraw/SotoX,nevraw/Edge,nevraw/Duo,nevraw/Quadrant_Hybrid,nevraw/Testing,nevraw/Quadrant_Hybrid,nevraw/SotoX,nevraw/pebble-slate-template,nevraw/Doodle,nevraw/Duo,nevraw/Duo,nevraw/Quasar,nevraw/Doodle,nevraw/pebble-slate-template,nevraw/Edge,nevraw/Quasar,nevraw/Quadrant_Hybrid,nevraw/Web,nevraw/Testing,nevraw/Phi-Ocular,nevraw/BinaryStars,nevraw/Quadrant,nevraw/Test_Rocky,nevraw/Quadrant,nevraw/Dual,nevraw/Edge,nevraw/BinaryStars,nevraw/IdentityCrisis | ---
+++
@@ -1,8 +1,3 @@
-(function() {
- loadOptions();
- submitHandler();
-})();
-
function submitHandler() {
var $submitButton = $('#submitButton');
|
520dc27f969ef79e0b64b2151f07c7f5f9f68be1 | app/components/Views/Section/Home/SearchBox.js | app/components/Views/Section/Home/SearchBox.js | /**
* Poster v0.1.0
* A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
*
* Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
* Date: 13 June, 2016
* License: MIT
*
* Section > Home -> [ SearchBox ]
*/
import React from "react";
export default
class SearchBox extends React.Component {
constructor() {
super();
}
render() {
return (
<div class="input-group">
<input type="text" class="form-control" placeholder="Search movies or people..." />
<span class="input-group-btn">
<button class="btn btn-default glyphicon glyphicon-search" type="button"></button>
</span>
</div>
);
}
}
| /**
* Poster v0.1.0
* A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
*
* Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
* Date: 13 June, 2016
* License: MIT
*
* Section > Home -> [ SearchBox ]
*/
import React from "react";
export default
class SearchBox extends React.Component {
constructor() {
super();
}
render() {
return (
<form class="input-group">
<input type="text" class="form-control" placeholder="Search movies or people..." />
<span class="input-group-btn">
<button class="btn btn-default glyphicon glyphicon-search" type="submit"></button>
</span>
</form>
);
}
}
| Change input box to <form> to enable search with Enter key. | Change input box to <form> to enable search with Enter key.
| JavaScript | mit | kushalpandya/poster,kushalpandya/poster | ---
+++
@@ -19,12 +19,12 @@
render() {
return (
- <div class="input-group">
+ <form class="input-group">
<input type="text" class="form-control" placeholder="Search movies or people..." />
<span class="input-group-btn">
- <button class="btn btn-default glyphicon glyphicon-search" type="button"></button>
+ <button class="btn btn-default glyphicon glyphicon-search" type="submit"></button>
</span>
- </div>
+ </form>
);
}
} |
b36bf2a38c0000449670e9a26c38395c9877389a | koans/AboutObjects.js | koans/AboutObjects.js | describe("About Objects", function () {
describe("Shorthand Syntax", function () {
it('should understand initailiser shorthand', function() {
function passThrough(one, two) {
return {
one,
two
}
}
var data = passThrough('one', 'two');
expect(typeof data).toEqual(FILL_ME_IN);
expect(data.one).toEqual(FILL_ME_IN);
expect(data.two).toEqual(FILL_ME_IN);
})
it('should understand method shorthand', function() {
var utils = {
uppercase(string) {
return string.toUpperCase();
}
};
expect(typeof utils.uppercase).toEqual(FILL_ME_IN);
expect(typeof utils.uppercase('upper')).toEqual(FILL_ME_IN);
})
});
describe('Computed Names', function() {
it('should understanding computed names usage', function() {
var car = 'ford';
var engine = 'Engine';
var carDetails = {
[car] : {
[car + 'Doors']: 4,
[car + engine]: 'v8',
[car + 'Model'] : 'Mustang'
}
}
expect(typeof FILL_ME_IN).toEqual('object');
expect(FILL_ME_IN).toEqual(4);
expect(FILL_ME_IN).toEqual('v8');
expect(FILL_ME_IN).toEqual('Mustang');
})
})
});
| describe("About Objects", function () {
describe("Shorthand Syntax", function () {
it('should understand initailiser shorthand', function() {
function passThrough(one, two) {
return {
one,
two
}
}
var data = passThrough('one', 'two');
expect(typeof data).toEqual(FILL_ME_IN);
expect(data.one).toEqual(FILL_ME_IN);
expect(data.two).toEqual(FILL_ME_IN);
})
it('should understand method shorthand', function() {
var utils = {
uppercase(string) {
return string.toUpperCase();
}
};
expect(typeof utils.uppercase).toEqual(FILL_ME_IN);
expect(typeof utils.uppercase('upper')).toEqual(FILL_ME_IN);
})
});
describe('Computed Names', function() {
it('should understand computed names usage', function() {
var car = 'ford';
var engine = 'Engine';
var carDetails = {
[car] : {
[car + 'Doors']: 4,
[car + engine]: 'v8',
[car + 'Model'] : 'Mustang'
}
}
expect(typeof FILL_ME_IN).toEqual('object');
expect(FILL_ME_IN).toEqual(4);
expect(FILL_ME_IN).toEqual('v8');
expect(FILL_ME_IN).toEqual('Mustang');
})
})
describe('Duplicate Literal Properties', function() {
it('should understand have duplicate keys are handled', function() {
var newJsStandard = {
name: 'harmony',
name: 'es6',
name: 'es2015'
};
expect(newJsStandard.name).toEqual(FILL_ME_IN);
})
})
});
| Add koan about object duplicate properties | feat: Add koan about object duplicate properties
| JavaScript | mit | tawashley/es6-javascript-koans,tawashley/es6-javascript-koans,tawashley/es6-javascript-koans | ---
+++
@@ -31,7 +31,7 @@
});
describe('Computed Names', function() {
- it('should understanding computed names usage', function() {
+ it('should understand computed names usage', function() {
var car = 'ford';
var engine = 'Engine';
@@ -50,4 +50,18 @@
})
})
+
+ describe('Duplicate Literal Properties', function() {
+
+ it('should understand have duplicate keys are handled', function() {
+ var newJsStandard = {
+ name: 'harmony',
+ name: 'es6',
+ name: 'es2015'
+ };
+
+ expect(newJsStandard.name).toEqual(FILL_ME_IN);
+ })
+
+ })
}); |
c110d65481448e454117a70104148283b4d263a3 | api/authenticate/index.js | api/authenticate/index.js | var async = require( 'async' );
var Validation = require( './validation' );
var Data = require( './data' );
var Output = require( './output' );
var utils = require( '../utils' );
exports.authenticate = function ( req, res ) {
async.waterfall( [
function ( callback ) {
Validation.forAuthenticate( req.body, callback );
},
function ( validatedRequest, callback ) {
Data.verifyCredentials( req.body.username, req.body.password );
},
function ( userData, callback ) {
Output.makeToken( userData, callback );
}
],
function ( err, output ) {
if ( err ) {
return utils.handleRouteError( err, res );
}
return res.json( output, 200 );
} );
};
| var async = require( 'async' );
var Validation = require( './validation' );
var Data = require( './data' );
var Output = require( './output' );
var utils = require( '../utils' );
exports.authenticate = function ( req, res ) {
async.waterfall( [
function ( callback ) {
Validation.forAuthenticate( req.body, callback );
},
function ( validatedRequest, callback ) {
Data.verifyCredentials( req.body.email, req.body.password, callback );
},
function ( userData, callback ) {
Output.makeToken( userData, callback );
}
],
function ( err, output ) {
if ( err ) {
return utils.handleRouteError( err, res );
}
return res.json( output, 200 );
} );
};
| Update function signature in req handler | Update function signature in req handler
| JavaScript | mit | projectweekend/Node-Backend-Seed | ---
+++
@@ -12,7 +12,7 @@
Validation.forAuthenticate( req.body, callback );
},
function ( validatedRequest, callback ) {
- Data.verifyCredentials( req.body.username, req.body.password );
+ Data.verifyCredentials( req.body.email, req.body.password, callback );
},
function ( userData, callback ) {
Output.makeToken( userData, callback ); |
7a4ed741ffa0bfd8044f7854ecf456b61ef4ff17 | src/lock/sso/index.js | src/lock/sso/index.js | import { Map } from 'immutable';
import LastLoginScreen from './last_login_screen';
import LoadingScreen from '../loading_screen';
import { ui, isConnectionEnabled } from '../index';
export function renderSSOScreens(m) {
if (!ui.rememberLastLogin(m)) return null;
// TODO: loading pin check belongs here?
if (m.getIn(["sso", "syncStatus"]) != "ok" || m.get("isLoadingPanePinned")) {
return new LoadingScreen();
}
const { name, strategy } = lastUsedConnection(m);
const skipped = m.getIn(["sso", "skipped"], false);
return !skipped && isConnectionEnabled(m, name)
? new LastLoginScreen()
: null;
}
export function lastUsedConnection(m) {
// { name, strategy }
return m.getIn(["sso", "lastUsedConnection"], Map()).toJS();
}
export function lastUsedUsername(m) {
return m.getIn(["sso", "lastUsedUsername"], "");
}
export function skipSSOLogin(m) {
return m.setIn(["sso", "skipped"], true);
}
| import { Map } from 'immutable';
import LastLoginScreen from './last_login_screen';
import LoadingScreen from '../loading_screen';
import { ui, isConnectionEnabled } from '../index';
export function renderSSOScreens(m) {
// TODO: loading pin check belongs here?
if (m.getIn(["sso", "syncStatus"]) != "ok" || m.get("isLoadingPanePinned")) {
return new LoadingScreen();
}
if (!ui.rememberLastLogin(m)) return null;
const { name, strategy } = lastUsedConnection(m);
const skipped = m.getIn(["sso", "skipped"], false);
return !skipped && isConnectionEnabled(m, name)
? new LastLoginScreen()
: null;
}
export function lastUsedConnection(m) {
// { name, strategy }
return m.getIn(["sso", "lastUsedConnection"], Map()).toJS();
}
export function lastUsedUsername(m) {
return m.getIn(["sso", "lastUsedUsername"], "");
}
export function skipSSOLogin(m) {
return m.setIn(["sso", "skipped"], true);
}
| Fix bug that prevented showing the loading screen | Fix bug that prevented showing the loading screen
| JavaScript | mit | mike-casas/lock,mike-casas/lock,mike-casas/lock | ---
+++
@@ -4,12 +4,12 @@
import { ui, isConnectionEnabled } from '../index';
export function renderSSOScreens(m) {
- if (!ui.rememberLastLogin(m)) return null;
-
// TODO: loading pin check belongs here?
if (m.getIn(["sso", "syncStatus"]) != "ok" || m.get("isLoadingPanePinned")) {
return new LoadingScreen();
}
+
+ if (!ui.rememberLastLogin(m)) return null;
const { name, strategy } = lastUsedConnection(m);
const skipped = m.getIn(["sso", "skipped"], false); |
2c4f837529ddf930b0c92158f20bc2bf4cddaa6c | src/states/Stats.js | src/states/Stats.js | class Stats extends Phaser.State {
create() {
this.totalScore = this.game.state.states['Main'].totalScore
this.game.stage.backgroundColor = '#DFF4FF';
let statsHeader = "STATS"
let continuePhrase = "Tap to Continue"
this.statsHeaderText = this.game.add.text(650, 50, statsHeader, { font: "250px Revalia", textalign: "center"});
this.continueText = this.game.add.text(820, 300, continuePhrase, { font: "50px Arial", textalign: "center"});
this.playerScore = this.game.add.text(20, 20, "Your score: " + this.totalScore, { font: "60px Arial", fill: "#fffff"});
}
update() {
if(this.game.input.activePointer.justPressed()) {
this.game.state.start('End');
}
}
}
export default Stats;
| class Stats extends Phaser.State {
create() {
this.totalScore = this.game.state.states['Main'].totalScore
this.game.stage.backgroundColor = '#DFF4FF';
let statsHeader = "STATS"
let continuePhrase = "Tap to Continue"
this.statsHeaderText = this.game.add.text(650, 50, statsHeader, { font: "250px Revalia", textalign: "center"});
this.continueText = this.game.add.text(820, 300, continuePhrase, { font: "50px Arial", textalign: "center"});
this.playerName = prompt("Please enter your name", "Player");
this.playerScore = this.game.add.text(20, 20, (this.playerName + "'s Score: " + this.totalScore), { font: "60px Arial", fill: "#fffff"});
}
update() {
if(this.game.input.activePointer.justPressed()) {
this.game.state.start('End');
}
}
}
export default Stats;
| Add playerName and playerScore to stats page | Add playerName and playerScore to stats page
| JavaScript | mit | joshmun/cornman-the-game,joshmun/cornman-the-game | ---
+++
@@ -9,8 +9,9 @@
this.statsHeaderText = this.game.add.text(650, 50, statsHeader, { font: "250px Revalia", textalign: "center"});
this.continueText = this.game.add.text(820, 300, continuePhrase, { font: "50px Arial", textalign: "center"});
- this.playerScore = this.game.add.text(20, 20, "Your score: " + this.totalScore, { font: "60px Arial", fill: "#fffff"});
+ this.playerName = prompt("Please enter your name", "Player");
+ this.playerScore = this.game.add.text(20, 20, (this.playerName + "'s Score: " + this.totalScore), { font: "60px Arial", fill: "#fffff"});
}
@@ -18,6 +19,7 @@
if(this.game.input.activePointer.justPressed()) {
this.game.state.start('End');
}
+
}
}
|
2507389838f8bbb2da5302882827f8e894ef6024 | src/util/filters.js | src/util/filters.js | export function filterByText(data, textFilter) {
if (textFilter === '') {
return data;
}
// case-insensitive
textFilter = textFilter.toLowerCase();
const exactMatches = [];
const substringMatches = [];
data.forEach(i => {
const name = i.name.toLowerCase();
if (name.split(' ').includes(textFilter)) {
exactMatches.push(i);
} else if (name.includes(textFilter)) {
substringMatches.push(i);
}
});
// return in order of importance in case sorting isn't done
return exactMatches.concat(substringMatches);
}
export function filterByCheckbox(data, checkboxFilters) {
let filtered = data;
Object.keys(checkboxFilters).forEach(i => {
const currentFilters = Object.keys(checkboxFilters[i]).filter(j => checkboxFilters[i][j]);
if (currentFilters.length) {
filtered = filtered.filter(j => currentFilters.includes(j.filterable[i]));
}
});
return filtered;
} | export function filterByText(data, textFilter) {
if (textFilter === '') {
return data;
}
// case-insensitive
textFilter = textFilter.toLowerCase();
const exactMatches = [];
const substringMatches = [];
data.forEach(i => {
const name = i.name.toLowerCase();
if (name.split(' ').includes(textFilter)) {
exactMatches.push(i);
} else if (name.includes(textFilter)) {
substringMatches.push(i);
}
});
// return in order of importance in case sorting isn't done
return exactMatches.concat(substringMatches);
}
export function filterByCheckbox(data, checkboxFilters) {
let filtered = data;
Object.keys(checkboxFilters).forEach(i => {
if (Object.keys(checkboxFilters[i]).some(j => checkboxFilters[i][j])) {
filtered = filtered.filter(j => checkboxFilters[i][j.filterable[i]]);
}
});
return filtered;
} | Improve checkbox filter performance by checking key instead of iterating | Improve checkbox filter performance by checking key instead of iterating
| JavaScript | agpl-3.0 | Johj/cqdb,Johj/cqdb | ---
+++
@@ -23,9 +23,8 @@
export function filterByCheckbox(data, checkboxFilters) {
let filtered = data;
Object.keys(checkboxFilters).forEach(i => {
- const currentFilters = Object.keys(checkboxFilters[i]).filter(j => checkboxFilters[i][j]);
- if (currentFilters.length) {
- filtered = filtered.filter(j => currentFilters.includes(j.filterable[i]));
+ if (Object.keys(checkboxFilters[i]).some(j => checkboxFilters[i][j])) {
+ filtered = filtered.filter(j => checkboxFilters[i][j.filterable[i]]);
}
});
|
fcdb11b2e4300e8195906a013355ac1eca64981f | spec/pageevaluatorSpec.js | spec/pageevaluatorSpec.js | /* global PageEvaluator */
describe("PageEvaluator", function () {
describe("getSelfReferences", function () {
it("should be able to return all self references", function () {
var anchor = document.createElement("a");
anchor.href = 'http://www.blablub';
var selfAnchor = document.createElement("a");
selfAnchor.href = '#blablub';
document.querySelectorAll = jasmine.createSpy("querySelectorAll spy").and.returnValue([anchor, selfAnchor]);
var selfReferences = PageEvaluator.evaluatePage();
expect(selfReferences.links).toContain('http://www.blablub');
expect(selfReferences.links.length).toBe(1);
});
});
}); | /* global PageEvaluator */
describe("PageEvaluator", function () {
describe("evaluatePage", function () {
it("should be able to return all external links", function () {
var anchor = document.createElement("a");
anchor.href = 'http://www.blablub';
var selfAnchor = document.createElement("a");
selfAnchor.href = '#blablub';
document.querySelectorAll = jasmine.createSpy("querySelectorAll spy").and.returnValue([anchor, selfAnchor]);
var selfReferences = PageEvaluator.evaluatePage();
expect(selfReferences.links).toContain('http://www.blablub');
expect(selfReferences.links.length).toBe(1);
});
it("should return every link just once", function () {
var firstAnchor = document.createElement("a");
firstAnchor.href = 'http://www.blablub';
var selfAnchor = document.createElement("a");
selfAnchor.href = '#blablub';
var secondAnchor = document.createElement("a");
secondAnchor.href = 'http://www.blablub';
document.querySelectorAll = jasmine.createSpy("querySelectorAll spy").and.returnValue([firstAnchor, selfAnchor, secondAnchor]);
var selfReferences = PageEvaluator.evaluatePage();
expect(selfReferences.links).toContain('http://www.blablub');
expect(selfReferences.links.length).toBe(1);
});
});
}); | Test for skipping already known links added. | Test for skipping already known links added.
| JavaScript | apache-2.0 | KaiHofstetter/link-stats | ---
+++
@@ -1,7 +1,7 @@
/* global PageEvaluator */
describe("PageEvaluator", function () {
- describe("getSelfReferences", function () {
- it("should be able to return all self references", function () {
+ describe("evaluatePage", function () {
+ it("should be able to return all external links", function () {
var anchor = document.createElement("a");
anchor.href = 'http://www.blablub';
@@ -16,5 +16,24 @@
expect(selfReferences.links).toContain('http://www.blablub');
expect(selfReferences.links.length).toBe(1);
});
+
+ it("should return every link just once", function () {
+
+ var firstAnchor = document.createElement("a");
+ firstAnchor.href = 'http://www.blablub';
+
+ var selfAnchor = document.createElement("a");
+ selfAnchor.href = '#blablub';
+
+ var secondAnchor = document.createElement("a");
+ secondAnchor.href = 'http://www.blablub';
+
+ document.querySelectorAll = jasmine.createSpy("querySelectorAll spy").and.returnValue([firstAnchor, selfAnchor, secondAnchor]);
+
+ var selfReferences = PageEvaluator.evaluatePage();
+
+ expect(selfReferences.links).toContain('http://www.blablub');
+ expect(selfReferences.links.length).toBe(1);
+ });
});
}); |
697e848fbe0a2cab8a56ea8641f82f17d9b86c99 | plugins/backbone.js | plugins/backbone.js | /**
* Backbone.js plugin
*
* Patches Backbone.Events callbacks.
*/
;(function(window, Raven, Backbone) {
'use strict';
// quit if Backbone isn't on the page
if (!Backbone) {
return;
}
function makeBackboneEventsOn(oldOn) {
return function BackboneEventsOn(name, callback, context) {
var _callback = callback._callback || callback;
callback = Raven.wrap(callback);
callback._callback = _callback;
return oldOn.call(this, name, callback, context);
};
}
// We're too late to catch all of these by simply patching Backbone.Events.on
var affectedObjects = [
Backbone.Events,
Backbone,
Backbone.Model.prototype,
Backbone.Collection.prototype,
Backbone.View.prototype,
Backbone.Router.prototype,
Backbone.History.prototype
], i = 0, l = affectedObjects.length;
for (; i < l; i++) {
var affected = affectedObjects[i];
affected.on = makeBackboneEventsOn(affected.on);
affected.bind = affected.on;
}
}(window, window.Raven, window.Backbone));
| /**
* Backbone.js plugin
*
* Patches Backbone.Events callbacks.
*/
;(function(window, Raven, Backbone) {
'use strict';
// quit if Backbone isn't on the page
if (!Backbone) {
return;
}
function makeBackboneEventsOn(oldOn) {
return function BackboneEventsOn(name, callback, context) {
var wrapCallback = function (cb) {
if (Object.prototype.toString.call(cb) === '[object Function]') {
var _callback = cb._callback || cb;
cb = Raven.wrap(cb);
cb._callback = _callback;
}
return cb;
};
if (Object.prototype.toString.call(name) === '[object Object]') {
// Handle event maps.
for (var key in name) {
if (name.hasOwnProperty(key)) {
name[key] = wrapCallback(name[key]);
}
}
} else {
callback = wrapCallback(callback);
}
return oldOn.call(this, name, callback, context);
};
}
// We're too late to catch all of these by simply patching Backbone.Events.on
var affectedObjects = [
Backbone.Events,
Backbone,
Backbone.Model.prototype,
Backbone.Collection.prototype,
Backbone.View.prototype,
Backbone.Router.prototype,
Backbone.History.prototype
], i = 0, l = affectedObjects.length;
for (; i < l; i++) {
var affected = affectedObjects[i];
affected.on = makeBackboneEventsOn(affected.on);
affected.bind = affected.on;
}
}(window, window.Raven, window.Backbone));
| Update Backbone.js plugin to handle event map syntax. | Update Backbone.js plugin to handle event map syntax.
| JavaScript | bsd-2-clause | housinghq/main-raven-js,janmisek/raven-js,vladikoff/raven-js,danse/raven-js,benoitg/raven-js,janmisek/raven-js,clara-labs/raven-js,vladikoff/raven-js,hussfelt/raven-js,getsentry/raven-js,getsentry/raven-js,grelas/raven-js,Mappy/raven-js,getsentry/raven-js,housinghq/main-raven-js,eaglesjava/raven-js,danse/raven-js,PureBilling/raven-js,grelas/raven-js,samgiles/raven-js,housinghq/main-raven-js,iodine/raven-js,chrisirhc/raven-js,malandrew/raven-js,eaglesjava/raven-js,chrisirhc/raven-js,malandrew/raven-js,benoitg/raven-js,iodine/raven-js,hussfelt/raven-js,clara-labs/raven-js,Mappy/raven-js,PureBilling/raven-js,Mappy/raven-js,samgiles/raven-js,getsentry/raven-js | ---
+++
@@ -13,9 +13,24 @@
function makeBackboneEventsOn(oldOn) {
return function BackboneEventsOn(name, callback, context) {
- var _callback = callback._callback || callback;
- callback = Raven.wrap(callback);
- callback._callback = _callback;
+ var wrapCallback = function (cb) {
+ if (Object.prototype.toString.call(cb) === '[object Function]') {
+ var _callback = cb._callback || cb;
+ cb = Raven.wrap(cb);
+ cb._callback = _callback;
+ }
+ return cb;
+ };
+ if (Object.prototype.toString.call(name) === '[object Object]') {
+ // Handle event maps.
+ for (var key in name) {
+ if (name.hasOwnProperty(key)) {
+ name[key] = wrapCallback(name[key]);
+ }
+ }
+ } else {
+ callback = wrapCallback(callback);
+ }
return oldOn.call(this, name, callback, context);
};
} |
82655073c6e807281c50ae9d8ea0fe63951ff10e | resources/assets/js/extra/maps.js | resources/assets/js/extra/maps.js | var map = L.map('map', {
attributionControl: false
}).setView([37.944, 24.115], 6);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
| var map = L.map('map', {
attributionControl: false
}).setView([37.944, 24.115], 6);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
var markers = new L.FeatureGroup();
setTimeout(function() {
for (var i=0; i<gis_nodes.length; i++) {
var node_marker = L.marker([gis_nodes[i]["latitude"], gis_nodes[i]["longitude"]]);
markers.addLayer(node_marker);
}
}, 1000);
var gis_remote_nodes_isPressed = false;
function gis_remote_nodes() {
if (!gis_remote_nodes_isPressed) {
map.addLayer(markers);
}
else {
removeAllMarkers();
}
gis_remote_nodes_isPressed = !gis_remote_nodes_isPressed;
return gis_remote_nodes_isPressed;
}
function removeAllMarkers(){
map.removeLayer(markers);
}
| Add node markers on the map after all nodes json data are fetched | Add node markers on the map after all nodes json data are fetched
| JavaScript | apache-2.0 | ehosp/eHOSP-Services-CE,ehosp/eHOSP-Services-CE,ehosp/eHOSP-Services-CE | ---
+++
@@ -3,3 +3,30 @@
}).setView([37.944, 24.115], 6);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
+
+
+var markers = new L.FeatureGroup();
+setTimeout(function() {
+ for (var i=0; i<gis_nodes.length; i++) {
+ var node_marker = L.marker([gis_nodes[i]["latitude"], gis_nodes[i]["longitude"]]);
+ markers.addLayer(node_marker);
+ }
+}, 1000);
+
+
+var gis_remote_nodes_isPressed = false;
+
+function gis_remote_nodes() {
+ if (!gis_remote_nodes_isPressed) {
+ map.addLayer(markers);
+ }
+ else {
+ removeAllMarkers();
+ }
+ gis_remote_nodes_isPressed = !gis_remote_nodes_isPressed;
+ return gis_remote_nodes_isPressed;
+}
+
+function removeAllMarkers(){
+ map.removeLayer(markers);
+} |
bfe90fd47754e44a02f0d9c364656ec20bf26f41 | src/sunstone/public/app/utils/tips.js | src/sunstone/public/app/utils/tips.js | define(function(require) {
require('foundation.tooltip');
//Replaces all class"tip" divs with an information icon that
//displays the tip information on mouseover.
var _setup = function(context, position) {
//For each tip in this context
$('.tip', context).each(function() {
var obj = $(this);
obj.removeClass('tip');
var tip = obj.html();
var tip_classes = ['has-tip']
if (position) {
tip_classes.push(position)
}
//replace the text with an icon and spans
obj.html('<span data-tooltip class="' + tip_classes.join(' ') + '" data-width="210" title="' + tip + '"><i class="fa fa-question-circle"></i></span>');
});
context.foundation('reflow', 'tooltip');
}
var _html = function(str) {
return '<span data-tooltip class="" data-width="210" title="' + str + '"><i class="fa fa-question-circle"></i></span>'
}
return {
'setup': _setup,
'html': _html
}
})
| define(function(require) {
require('foundation.tooltip');
//Replaces all class"tip" divs with an information icon that
//displays the tip information on mouseover.
var _setup = function(context, position) {
if (!context) {
context = $(document);
}
//For each tip in this context
$('.tip', context).each(function() {
var obj = $(this);
obj.removeClass('tip');
var tip = obj.html();
var tip_classes = ['has-tip']
if (position) {
tip_classes.push(position)
}
//replace the text with an icon and spans
obj.html('<span data-tooltip class="' + tip_classes.join(' ') + '" data-width="210" title="' + tip + '"><i class="fa fa-question-circle"></i></span>');
});
context.foundation('reflow', 'tooltip');
}
var _html = function(str) {
return '<span data-tooltip class="" data-width="210" title="' + str + '"><i class="fa fa-question-circle"></i></span>'
}
return {
'setup': _setup,
'html': _html
}
})
| Define context for setupTips if undefined | Define context for setupTips if undefined | JavaScript | apache-2.0 | unistra/one,abelCoronado93/one,ggalancs/one,alvarosimon/one,juanmont/one,OpenNebula/one,juanmont/one,goberle/one,abelCoronado93/one,unistra/one,OpenNebula/one,hsanjuan/one,ggalancs/one,ohamada/one,ohamada/one,baby-gnu/one,ohamada/one,juanmont/one,unistra/one,juanmont/one,atodorov-storpool/one,fasrc/one,OpenNebula/one,goberle/one,ggalancs/one,hsanjuan/one,unistra/one,OpenNebula/one,abelCoronado93/one,alvarosimon/one,tuxmea/one,ohamada/one,juanmont/one,OpenNebula/one,abelCoronado93/one,alvarosimon/one,fasrc/one,fasrc/one,tuxmea/one,fasrc/one,tuxmea/one,alvarosimon/one,baby-gnu/one,ohamada/one,goberle/one,alvarosimon/one,baby-gnu/one,unistra/one,baby-gnu/one,alvarosimon/one,fasrc/one,goberle/one,tuxmea/one,atodorov-storpool/one,atodorov-storpool/one,ohamada/one,hsanjuan/one,hsanjuan/one,abelCoronado93/one,goberle/one,abelCoronado93/one,ggalancs/one,unistra/one,baby-gnu/one,juanmont/one,abelCoronado93/one,hsanjuan/one,ohamada/one,tuxmea/one,hsanjuan/one,atodorov-storpool/one,tuxmea/one,ggalancs/one,abelCoronado93/one,tuxmea/one,atodorov-storpool/one,fasrc/one,OpenNebula/one,goberle/one,ggalancs/one,OpenNebula/one,alvarosimon/one,atodorov-storpool/one,unistra/one,atodorov-storpool/one,juanmont/one,tuxmea/one,fasrc/one,goberle/one,baby-gnu/one,unistra/one,ggalancs/one,OpenNebula/one,alvarosimon/one,juanmont/one,hsanjuan/one,goberle/one,baby-gnu/one,baby-gnu/one,OpenNebula/one,juanmont/one,fasrc/one,ggalancs/one,atodorov-storpool/one,hsanjuan/one,atodorov-storpool/one,ohamada/one | ---
+++
@@ -3,6 +3,10 @@
//Replaces all class"tip" divs with an information icon that
//displays the tip information on mouseover.
var _setup = function(context, position) {
+ if (!context) {
+ context = $(document);
+ }
+
//For each tip in this context
$('.tip', context).each(function() {
var obj = $(this);
@@ -16,6 +20,7 @@
//replace the text with an icon and spans
obj.html('<span data-tooltip class="' + tip_classes.join(' ') + '" data-width="210" title="' + tip + '"><i class="fa fa-question-circle"></i></span>');
});
+
context.foundation('reflow', 'tooltip');
}
|
a3e1f0d088052a9fee85e56a4a68b5527b692844 | example/app/entry-a.js | example/app/entry-a.js | var libA = require("./shared/lib-a");
var libB = require("./shared/lib-b");
console.log("entry-a:libA", libA);
console.log("entra-a:libB", libB);
| var libA = require("./shared/lib-a");
var libB = require("./shared/lib-b");
require("lodash");
console.log("entry-a:libA", libA);
console.log("entra-a:libB", libB);
| Add lodash to the build. | Add lodash to the build.
| JavaScript | mit | interlockjs/interlock,interlockjs/interlock | ---
+++
@@ -1,5 +1,6 @@
var libA = require("./shared/lib-a");
var libB = require("./shared/lib-b");
+require("lodash");
console.log("entry-a:libA", libA);
console.log("entra-a:libB", libB); |
bc1bd2e89a8b3713668ac2c0341875b0f59ac5ea | js/app/handlers/range-picker.js | js/app/handlers/range-picker.js | $(document).on('dp.change', '#ds-range-picker-from', function(e) {
var from = $('#ds-range-picker-from').data("DateTimePicker").getDate()
console.log('set from time: ' + moment(from).fromNow())
})
$(document).on('dp.change', '#ds-range-picker-until', function(e) {
var until = $('#ds-range-picker-until').data("DateTimePicker").getDate()
console.log('set until time: ' + moment(until).fromNow())
})
$(document).on('click', '.ds-recent-range-picker li, .ds-recent-range-picker a, .ds-custom-range-picker ul li, .ds-custom-range-picker ul li a', function(e) {
var range = $(e.target).attr('data-ds-range')
console.log(range)
if (range === 'custom') {
$('.ds-recent-range-picker').hide()
$('.ds-custom-range-picker').show()
// TODO - set initial values of from/until fields to something
// reasonable
} else if (range === 'recent') {
$('.ds-custom-range-picker').hide()
$('.ds-recent-range-picker').show()
} else {
ds.manager.set_time_range(range, null)
}
return false
})
| $(document).on('dp.change', '#ds-range-picker-from', function(e) {
var from = $('#ds-range-picker-from').data("DateTimePicker").getDate()
console.log('set from time: ' + moment(from).fromNow())
})
$(document).on('dp.change', '#ds-range-picker-until', function(e) {
var until = $('#ds-range-picker-until').data("DateTimePicker").getDate()
console.log('set until time: ' + moment(until).fromNow())
})
$(document).on('click', '.ds-recent-range-picker li, .ds-recent-range-picker a, .ds-custom-range-picker ul li, .ds-custom-range-picker ul li a', function(e) {
var range = $(e.target).attr('data-ds-range')
console.log(range)
if (range === 'custom') {
$('.ds-recent-range-picker').hide()
$('.ds-custom-range-picker').show()
var now = moment() // TODO: quantize to 15-min interval
$('#ds-range-picker-until').data("DateTimePicker").setDate(now)
// set to now -3 hours
// $('#ds-range-picker-from').data("DateTimePicker").setDate(moment())
} else if (range === 'recent') {
$('.ds-custom-range-picker').hide()
$('.ds-recent-range-picker').show()
} else {
ds.manager.set_time_range(range, null)
}
return false
})
| Set the 'until' field to now for now | Set the 'until' field to now for now
| JavaScript | apache-2.0 | section-io/tessera,urbanairship/tessera,jmptrader/tessera,tessera-metrics/tessera,Slach/tessera,section-io/tessera,tessera-metrics/tessera,aalpern/tessera,filippog/tessera,jmptrader/tessera,Slach/tessera,aalpern/tessera,filippog/tessera,urbanairship/tessera,aalpern/tessera,urbanairship/tessera,Slach/tessera,tessera-metrics/tessera,urbanairship/tessera,aalpern/tessera,tessera-metrics/tessera,filippog/tessera,Slach/tessera,section-io/tessera,tessera-metrics/tessera,jmptrader/tessera,urbanairship/tessera,section-io/tessera,jmptrader/tessera,aalpern/tessera,jmptrader/tessera | ---
+++
@@ -16,8 +16,10 @@
$('.ds-recent-range-picker').hide()
$('.ds-custom-range-picker').show()
- // TODO - set initial values of from/until fields to something
- // reasonable
+ var now = moment() // TODO: quantize to 15-min interval
+ $('#ds-range-picker-until').data("DateTimePicker").setDate(now)
+ // set to now -3 hours
+ // $('#ds-range-picker-from').data("DateTimePicker").setDate(moment())
} else if (range === 'recent') {
$('.ds-custom-range-picker').hide() |
26bf7d797840efe457fb08eb328e36dba2092d4f | test-support/helpers/ember-cognito.js | test-support/helpers/ember-cognito.js | /* global wait */
import { MockUser } from '../utils/ember-cognito';
import { set } from '@ember/object';
export function mockCognitoUser(app, userAttributes) {
const { __container__: container } = app;
const cognito = container.lookup('service:cognito');
set(cognito, 'user', MockUser.create(userAttributes));
return wait();
}
export function unmockCognitoUser(app) {
const { __container__: container } = app;
const cognito = container.lookup('service:cognito');
set(cognito, 'user', undefined);
return wait();
}
export function getAuthenticator(app) {
return app.__container__.lookup('authenticator:cognito');
}
| /* global wait */
import { MockUser } from '../utils/ember-cognito';
import Ember from 'ember';
const { set } = Ember;
export function mockCognitoUser(app, userAttributes) {
const { __container__: container } = app;
const cognito = container.lookup('service:cognito');
set(cognito, 'user', MockUser.create(userAttributes));
return wait();
}
export function unmockCognitoUser(app) {
const { __container__: container } = app;
const cognito = container.lookup('service:cognito');
set(cognito, 'user', undefined);
return wait();
}
export function getAuthenticator(app) {
return app.__container__.lookup('authenticator:cognito');
}
| Remove one more reference to @ember/object | Remove one more reference to @ember/object
| JavaScript | mit | paulcwatts/ember-cognito,paulcwatts/ember-cognito | ---
+++
@@ -1,6 +1,8 @@
/* global wait */
import { MockUser } from '../utils/ember-cognito';
-import { set } from '@ember/object';
+import Ember from 'ember';
+
+const { set } = Ember;
export function mockCognitoUser(app, userAttributes) {
const { __container__: container } = app; |
4118fe46abe8ebd048e4af13570e7b10ae3e886b | examples/weather-viewer/weatherman.js | examples/weather-viewer/weatherman.js | console.log ('I am the weatherman')
class Weather {
constructor (latitude, longitude) {
}
locate (latitude, longitude) {
const api = 'https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?'
+ 'lat=' + latitude
+ '&lon=' + longitude
+ '&appid=' + this.key
+ '&units=imperial'
return fetch (api)
.then (response => response.json ())
}
static get api () {
}
get key () // from openweathermap.org
{ return '62b74592e7bde09ede21693bce86460a' }
}
| class Weather {
constructor (latitude, longitude) {
}
locate (latitude, longitude) {
const api = 'https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?'
+ 'lat=' + latitude
+ '&lon=' + longitude
+ '&appid=' + this.key
+ '&units=imperial'
return fetch (api)
.then (response => response.json ())
}
static get api () {
}
get key () // from openweathermap.org
{ return '62b74592e7bde09ede21693bce86460a' }
}
| Remove console.log statement from weather-viewer | Remove console.log statement from weather-viewer
| JavaScript | mit | devpunks/snuggsi,devpunks/snuggsi,devpunks/snuggsi,snuggs/snuggsi,snuggs/snuggsi,snuggs/snuggsi,devpunks/snuggsi,snuggs/snuggsi,devpunks/snuggsi | ---
+++
@@ -1,5 +1,3 @@
-console.log ('I am the weatherman')
-
class Weather {
constructor (latitude, longitude) { |
4ed8a540fed8e419bcf9ad1dbcf3694dc12b27d7 | test/components/Shared/Button.spec.js | test/components/Shared/Button.spec.js | // component test
import React from "react";
import ReactTestUtils from "react-addons-test-utils";
import Button from "src/components/Shared/Button.js";
describe("Button component", () => {
it("should exist", () => {
Button.should.exist;
});
it("should be react element", () => {
ReactTestUtils.isElement(<Button />).should.be.ok;
});
describe("rendering", () => {
it("contain passed text as only child", () => {
const renderer = ReactTestUtils.createRenderer();
renderer.render(<Button text="TEST" />);
const button = renderer.getRenderOutput();
button.props.children
.should.be.equal("TEST");
});
it("should render Button as noncomposite component", () => {
const renderer = ReactTestUtils.createRenderer();
renderer.render(<Button />);
const output = renderer.getRenderOutput();
ReactTestUtils
.isCompositeComponent(output)
.should.be.not.ok;
});
it("should have wrapper if useWrapper is specified", () => {
const renderer = ReactTestUtils.createRenderer();
renderer.render(<Button useWrapper />);
const output = renderer.getRenderOutput();
ReactTestUtils
.isCompositeComponentWithType(output, Button)
.should.be.not.ok;
});
});
});
| // component test
import React from "react";
import ReactDOM from "react-dom";
import ReactTestUtils from "react-addons-test-utils";
import jsdom from "mocha-jsdom";
import Button from "src/components/Shared/Button.js";
describe("Button component", () => {
jsdom();
it("should exist", () => {
Button.should.exist;
});
it("should be react element", () => {
ReactTestUtils.isElement(<Button />).should.be.ok;
});
describe("rendering", () => {
it("contain passed text as only child", () => {
const renderer = ReactTestUtils.createRenderer();
renderer.render(<Button text="TEST" />);
const button = renderer.getRenderOutput();
button.props.children
.should.be.equal("TEST");
});
it("should render Button as noncomposite component", () => {
const renderer = ReactTestUtils.createRenderer();
renderer.render(<Button />);
const output = renderer.getRenderOutput();
ReactTestUtils
.isCompositeComponent(output)
.should.be.not.ok;
});
it("should have wrapper if useWrapper is specified", () => {
const renderer = ReactTestUtils.createRenderer();
renderer.render(<Button useWrapper />);
const output = renderer.getRenderOutput();
ReactTestUtils
.isCompositeComponentWithType(output, Button)
.should.be.not.ok;
});
it("should call click handler passed through props on click event", () => {
var wasCalled = false;
const button = ReactTestUtils.renderIntoDocument(
<Button clickHandler={() => wasCalled = true}/>
);
var node = ReactDOM.findDOMNode(button);
ReactTestUtils.Simulate.click(node);
wasCalled.should.equal(true);
})
});
});
| Add test for button click handler | Add test for button click handler
| JavaScript | mit | Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React | ---
+++
@@ -1,10 +1,14 @@
// component test
import React from "react";
+import ReactDOM from "react-dom";
import ReactTestUtils from "react-addons-test-utils";
+import jsdom from "mocha-jsdom";
import Button from "src/components/Shared/Button.js";
describe("Button component", () => {
+
+ jsdom();
it("should exist", () => {
Button.should.exist;
@@ -45,6 +49,16 @@
.should.be.not.ok;
});
+ it("should call click handler passed through props on click event", () => {
+ var wasCalled = false;
+ const button = ReactTestUtils.renderIntoDocument(
+ <Button clickHandler={() => wasCalled = true}/>
+ );
+ var node = ReactDOM.findDOMNode(button);
+ ReactTestUtils.Simulate.click(node);
+ wasCalled.should.equal(true);
+ })
+
});
}); |
e1351b93560897c8fd3516c5769f651a5c147c72 | src/dsp/Gain.js | src/dsp/Gain.js | /**
* @depends ../core/AudioletNode.js
*/
var Gain = new Class({
Extends: AudioletNode,
initialize: function(audiolet, gain) {
AudioletNode.prototype.initialize.apply(this, [audiolet, 2, 1]);
this.outputs[0].link(this.inputs[0]);
this.gain = new AudioletParameter(this, 1, gain || 1);
},
generate: function(inputBuffers, outputBuffers) {
var inputBuffer = inputBuffers[0];
var outputBuffer = outputBuffers[0];
if (inputBuffer.isEmpty) {
outputBuffer.isEmpty = true;
return;
}
// Local processing variables
var gain = this.gain;
var numberOfChannels = inputBuffer.numberOfChannels;
for (var i = 0; i < numberOfChannels; i++) {
var inputChannel = inputBuffer.getChannelData(i);
var outputChannel = outputBuffer.getChannelData(i);
var bufferLength = inputBuffer.length;
for (var j = 0; j < bufferLength; j++) {
outputChannel[j] = inputChannel[j] * gain.getValue(i);
}
}
}
});
| /**
* @depends ../core/AudioletNode.js
*/
var Gain = new Class({
Extends: AudioletNode,
initialize: function(audiolet, gain) {
AudioletNode.prototype.initialize.apply(this, [audiolet, 2, 1]);
this.outputs[0].link(this.inputs[0]);
this.gain = new AudioletParameter(this, 1, gain || 1);
},
generate: function(inputBuffers, outputBuffers) {
var inputBuffer = inputBuffers[0];
var outputBuffer = outputBuffers[0];
if (inputBuffer.isEmpty) {
outputBuffer.isEmpty = true;
return;
}
// Local processing variables
var gain = this.gain;
var numberOfChannels = inputBuffer.numberOfChannels;
for (var i = 0; i < numberOfChannels; i++) {
var inputChannel = inputBuffer.getChannelData(i);
var outputChannel = outputBuffer.getChannelData(i);
var bufferLength = inputBuffer.length;
for (var j = 0; j < bufferLength; j++) {
outputChannel[j] = inputChannel[j] * gain.getValue(j);
}
}
}
});
| Fix a stupid bug where gain read the value for the channel, not the sample | Fix a stupid bug where gain read the value for the channel, not the sample
| JavaScript | apache-2.0 | Kosar79/Audiolet,oampo/Audiolet,mcanthony/Audiolet,kn0ll/Audiolet,bobby-brennan/Audiolet,kn0ll/Audiolet,mcanthony/Audiolet,Kosar79/Audiolet,oampo/Audiolet,bobby-brennan/Audiolet,Kosar79/Audiolet | ---
+++
@@ -28,7 +28,7 @@
var outputChannel = outputBuffer.getChannelData(i);
var bufferLength = inputBuffer.length;
for (var j = 0; j < bufferLength; j++) {
- outputChannel[j] = inputChannel[j] * gain.getValue(i);
+ outputChannel[j] = inputChannel[j] * gain.getValue(j);
}
}
} |
c7ecb64e84b2704d7bb10def5d2cb908a9a0002f | test/unit/specs/Dashboard.spec.js | test/unit/specs/Dashboard.spec.js | import Vue from 'vue'
import Dashboard from 'src/components/Dashboard'
import axios from 'axios'
describe('Dashboard.vue', () => {
let sandbox
beforeEach(function() {
sandbox = sinon.sandbox.create()
sandbox.stub(axios, 'get').returns(Promise.resolve('hi'))
})
afterEach(() => {
sandbox.restore()
})
it('should render at least one game element', () => {
const vm = new Vue({
el: document.createElement('div'),
render: (h) => h(Dashboard)
})
expect(vm.$el.querySelector('.game')).to.exist
})
})
| import Vue from 'vue'
import Dashboard from 'src/components/Dashboard'
import axios from 'axios'
describe('Dashboard.vue', () => {
let sandbox
let vm
beforeEach(function() {
sandbox = sinon.sandbox.create()
sandbox.stub(axios, 'get').returns(Promise.resolve('hi'))
vm = new Vue({
el: document.createElement('div'),
render: (h) => h(Dashboard)
})
})
afterEach(() => {
sandbox.restore()
})
it('should render at least one game element', () => {
expect(vm.$el.querySelector('.game')).to.exist
})
})
| Move Vue element creation to beforeEach | Move Vue element creation to beforeEach
| JavaScript | mit | blakecontreras/play-me,blakecontreras/play-me | ---
+++
@@ -4,18 +4,19 @@
describe('Dashboard.vue', () => {
let sandbox
+ let vm
beforeEach(function() {
sandbox = sinon.sandbox.create()
sandbox.stub(axios, 'get').returns(Promise.resolve('hi'))
+ vm = new Vue({
+ el: document.createElement('div'),
+ render: (h) => h(Dashboard)
+ })
})
afterEach(() => {
sandbox.restore()
})
it('should render at least one game element', () => {
- const vm = new Vue({
- el: document.createElement('div'),
- render: (h) => h(Dashboard)
- })
expect(vm.$el.querySelector('.game')).to.exist
})
}) |
003572e5c7daceb12971aaef76d323902343e963 | corehq/apps/cloudcare/static/cloudcare/js/formplayer/hq.events.js | corehq/apps/cloudcare/static/cloudcare/js/formplayer/hq.events.js | /*global FormplayerFrontend */
/**
* hq.events.js
*
* This is framework for allowing messages from HQ
*/
FormplayerFrontend.module("HQ.Events", function(Events, FormplayerFrontend) {
Events.Receiver = function(allowedHost) {
this.allowedHost = allowedHost;
return receiver.bind(this);
};
var receiver = function(event) {
// For Chrome, the origin property is in the event.originalEvent object
var origin = event.origin || event.originalEvent.origin,
data = event.data,
returnValue = null,
success = true;
_.defaults(data, {
success: function() {},
error: function() {},
complete: function() {},
});
if (!origin.endsWith(this.allowedHost)) {
throw new Error('Disallowed origin ' + origin);
}
if (!data.hasOwnProperty('action')) {
throw new Error('Message must have action property');
}
if (!_.contains(_.values(Events.Actions), data.action)) {
throw new Error('Invalid action ' + data.action);
}
try {
switch (data.action) {
case Events.Actions.BACK:
FormplayerFrontend.trigger('navigation:back');
break;
}
} catch (e) {
success = false;
data.error(event, data, returnValue);
} finally {
data.complete(event, data, returnValue);
}
if (success) {
data.success(event, data, returnValue);
}
};
Events.Actions = {
BACK: 'back',
};
});
| /*global FormplayerFrontend */
/**
* hq.events.js
*
* This is framework for allowing messages from HQ
*/
FormplayerFrontend.module("HQ.Events", function(Events, FormplayerFrontend) {
Events.Receiver = function(allowedHost) {
this.allowedHost = allowedHost;
return receiver.bind(this);
};
var receiver = function(event) {
// For Chrome, the origin property is in the event.originalEvent object
var origin = event.origin || event.originalEvent.origin,
data = event.data,
success = true;
if (!origin.endsWith(this.allowedHost)) {
throw new Error('Disallowed origin ' + origin);
}
if (!data.hasOwnProperty('action')) {
throw new Error('Message must have action property');
}
if (!_.contains(_.values(Events.Actions), data.action)) {
throw new Error('Invalid action ' + data.action);
}
switch (data.action) {
case Events.Actions.BACK:
FormplayerFrontend.trigger('navigation:back');
break;
}
};
Events.Actions = {
BACK: 'back',
};
});
| Remove ability to have callbacks | Remove ability to have callbacks
| JavaScript | bsd-3-clause | qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -16,14 +16,8 @@
// For Chrome, the origin property is in the event.originalEvent object
var origin = event.origin || event.originalEvent.origin,
data = event.data,
- returnValue = null,
success = true;
- _.defaults(data, {
- success: function() {},
- error: function() {},
- complete: function() {},
- });
if (!origin.endsWith(this.allowedHost)) {
throw new Error('Disallowed origin ' + origin);
}
@@ -35,20 +29,10 @@
throw new Error('Invalid action ' + data.action);
}
- try {
- switch (data.action) {
- case Events.Actions.BACK:
- FormplayerFrontend.trigger('navigation:back');
- break;
- }
- } catch (e) {
- success = false;
- data.error(event, data, returnValue);
- } finally {
- data.complete(event, data, returnValue);
- }
- if (success) {
- data.success(event, data, returnValue);
+ switch (data.action) {
+ case Events.Actions.BACK:
+ FormplayerFrontend.trigger('navigation:back');
+ break;
}
};
|
16e675f5b899341172cff4fd1ee144faf934f8d1 | src/mainInstance.js | src/mainInstance.js | import { DEFAULT_CONFIG } from './core/config'
import { createCore } from './core/core'
import * as all from './factory'
import { ArgumentsError } from './error/ArgumentsError'
import { DimensionError } from './error/DimensionError'
import { IndexError } from './error/IndexError'
export function core (config) {
const mergedConfig = Object.assign({}, DEFAULT_CONFIG, config)
return createCore({
config: mergedConfig
})
}
export function create (config) {
const math = core(config)
math.create = create
math.core = core
// import the factory functions like createAdd as an array instead of object,
// else they will get a different naming (`createAdd` instead of `add`).
math['import'](Object.values(all))
math.error = {
ArgumentsError,
DimensionError,
IndexError
}
return math
}
| import { DEFAULT_CONFIG } from './core/config'
import { createCore } from './core/core'
import { values } from './utils/object'
import * as all from './factory'
import { ArgumentsError } from './error/ArgumentsError'
import { DimensionError } from './error/DimensionError'
import { IndexError } from './error/IndexError'
export function core (config) {
const mergedConfig = Object.assign({}, DEFAULT_CONFIG, config)
return createCore({
config: mergedConfig
})
}
export function create (config) {
const math = core(config)
math.create = create
math.core = core
// import the factory functions like createAdd as an array instead of object,
// else they will get a different naming (`createAdd` instead of `add`).
math['import'](values(all))
math.error = {
ArgumentsError,
DimensionError,
IndexError
}
return math
}
| Fix test broken on node.js 6 | Fix test broken on node.js 6
| JavaScript | apache-2.0 | josdejong/mathjs,FSMaxB/mathjs,josdejong/mathjs,FSMaxB/mathjs,FSMaxB/mathjs,FSMaxB/mathjs,josdejong/mathjs,josdejong/mathjs,josdejong/mathjs,FSMaxB/mathjs | ---
+++
@@ -1,5 +1,6 @@
import { DEFAULT_CONFIG } from './core/config'
import { createCore } from './core/core'
+import { values } from './utils/object'
import * as all from './factory'
import { ArgumentsError } from './error/ArgumentsError'
import { DimensionError } from './error/DimensionError'
@@ -21,7 +22,7 @@
// import the factory functions like createAdd as an array instead of object,
// else they will get a different naming (`createAdd` instead of `add`).
- math['import'](Object.values(all))
+ math['import'](values(all))
math.error = {
ArgumentsError, |
25cb4a7dd16e4dd3235ade582e78dab5afa72883 | src/loadNode.js | src/loadNode.js | var context = require('vm').createContext({
options: {
server: true,
version: 'dev'
},
Canvas: require('canvas'),
console: console,
require: require,
include: function(uri) {
var source = require('fs').readFileSync(__dirname + '/' + uri);
// For relative includes, we save the current directory and then add
// the uri directory to __dirname:
var oldDirname = __dirname;
__dirname = __dirname + '/' + uri.replace(/[^/]+$/, '');
require('vm').runInContext(source, context, uri);
__dirname = oldDirname;
}
});
context.include('paper.js');
context.Base.each(context, function(val, key) {
if (val && val.prototype instanceof context.Base) {
val._name = key;
// Export all classes through PaperScope:
context.PaperScope.prototype[key] = val;
}
});
context.PaperScope.prototype['Canvas'] = context.Canvas;
module.exports = new context.PaperScope(); | var fs = require('fs'),
vm = require('vm'),
path = require('path');
// Create the context within which we will run the source files:
var context = vm.createContext({
options: {
server: true,
version: 'dev'
},
// Node Canvas library: https://github.com/learnboost/node-canvas
Canvas: require('canvas'),
// Copy over global variables:
console: console,
require: require,
__dirname: __dirname,
__filename: __filename,
// Used to load and run source files within the same context:
include: function(uri) {
var source = fs.readFileSync(path.resolve(__dirname, uri), 'utf8');
// For relative includes, we save the current directory and then
// add the uri directory to __dirname:
var oldDirname = __dirname;
__dirname = path.resolve(__dirname, path.dirname(uri));
vm.runInContext(source, context, uri);
__dirname = oldDirname;
}
});
context.include('paper.js');
context.Base.each(context, function(val, key) {
if (val && val.prototype instanceof context.Base) {
val._name = key;
// Export all classes through PaperScope:
context.PaperScope.prototype[key] = val;
}
});
context.PaperScope.prototype['Canvas'] = context.Canvas;
require.extensions['.pjs'] = function(module, uri) {
var source = context.PaperScript.compile(fs.readFileSync(uri, 'utf8'));
var envVars = 'var __dirname = \'' + path.dirname(uri) + '\';' +
'var __filename = \'' + uri + '\';';
vm.runInContext(envVars, context);
var scope = new context.PaperScope();
context.PaperScript.evaluate(source, scope);
module.exports = scope;
};
module.exports = new context.PaperScope(); | Support running of PaperScript .pjs files. | Support running of PaperScript .pjs files.
| JavaScript | mit | superjudge/paper.js,iconexperience/paper.js,byte-foundry/paper.js,iconexperience/paper.js,byte-foundry/paper.js,proofme/paper.js,JunaidPaul/paper.js,Olegas/paper.js,luisbrito/paper.js,superjudge/paper.js,Olegas/paper.js,JunaidPaul/paper.js,lehni/paper.js,legendvijay/paper.js,fredoche/paper.js,proofme/paper.js,rgordeev/paper.js,iconexperience/paper.js,rgordeev/paper.js,luisbrito/paper.js,baiyanghese/paper.js,baiyanghese/paper.js,nancymark/paper.js,luisbrito/paper.js,fredoche/paper.js,ClaireRutkoske/paper.js,mcanthony/paper.js,li0t/paper.js,Olegas/paper.js,legendvijay/paper.js,nancymark/paper.js,nancymark/paper.js,fredoche/paper.js,superjudge/paper.js,li0t/paper.js,lehni/paper.js,ClaireRutkoske/paper.js,li0t/paper.js,byte-foundry/paper.js,baiyanghese/paper.js,legendvijay/paper.js,proofme/paper.js,EskenderDev/paper.js,EskenderDev/paper.js,ClaireRutkoske/paper.js,mcanthony/paper.js,rgordeev/paper.js,EskenderDev/paper.js,lehni/paper.js,chad-autry/paper.js,mcanthony/paper.js,JunaidPaul/paper.js | ---
+++
@@ -1,18 +1,28 @@
-var context = require('vm').createContext({
+var fs = require('fs'),
+ vm = require('vm'),
+ path = require('path');
+
+// Create the context within which we will run the source files:
+var context = vm.createContext({
options: {
server: true,
version: 'dev'
},
+ // Node Canvas library: https://github.com/learnboost/node-canvas
Canvas: require('canvas'),
+ // Copy over global variables:
console: console,
require: require,
+ __dirname: __dirname,
+ __filename: __filename,
+ // Used to load and run source files within the same context:
include: function(uri) {
- var source = require('fs').readFileSync(__dirname + '/' + uri);
- // For relative includes, we save the current directory and then add
- // the uri directory to __dirname:
+ var source = fs.readFileSync(path.resolve(__dirname, uri), 'utf8');
+ // For relative includes, we save the current directory and then
+ // add the uri directory to __dirname:
var oldDirname = __dirname;
- __dirname = __dirname + '/' + uri.replace(/[^/]+$/, '');
- require('vm').runInContext(source, context, uri);
+ __dirname = path.resolve(__dirname, path.dirname(uri));
+ vm.runInContext(source, context, uri);
__dirname = oldDirname;
}
});
@@ -28,4 +38,14 @@
});
context.PaperScope.prototype['Canvas'] = context.Canvas;
+require.extensions['.pjs'] = function(module, uri) {
+ var source = context.PaperScript.compile(fs.readFileSync(uri, 'utf8'));
+ var envVars = 'var __dirname = \'' + path.dirname(uri) + '\';' +
+ 'var __filename = \'' + uri + '\';';
+ vm.runInContext(envVars, context);
+ var scope = new context.PaperScope();
+ context.PaperScript.evaluate(source, scope);
+ module.exports = scope;
+};
+
module.exports = new context.PaperScope(); |
07b3370e26d4e6c3e2b4ddb7bb05747aa48f2b11 | src/util.js | src/util.js | /**
* Assign properties from `props` to `obj`
* @template O, P The obj and props types
* @param {O} obj The object to copy properties to
* @param {P} props The object to copy properties from
* @returns {O & P}
*/
export function assign(obj, props) {
for (let i in props) obj[i] = props[i];
return /** @type {O & P} */ (obj);
}
/**
* Remove a child node from its parent if attached.
* @param {Node} node The node to remove
*/
export function removeNode(node) {
let parentNode = node.parentNode;
if (parentNode) parentNode.removeChild(node);
}
| /**
* Assign properties from `props` to `obj`
* @template O, P The obj and props types
* @param {O} obj The object to copy properties to
* @param {P} props The object to copy properties from
* @returns {O & P}
*/
export function assign(obj, props) {
for (let i in props) obj[i] = props[i];
return /** @type {O & P} */ (obj);
}
/**
* Remove a child node from its parent if attached. This is a workaround for
* IE11 which doesn't support `Element.prototype.remove()`. Using this function
* is smaller than including a dedicated polyfill.
* @param {Node} node The node to remove
*/
export function removeNode(node) {
let parentNode = node.parentNode;
if (parentNode) parentNode.removeChild(node);
}
| Add note about IE11 for removeNode | Add note about IE11 for removeNode
| JavaScript | mit | developit/preact,developit/preact | ---
+++
@@ -11,7 +11,9 @@
}
/**
- * Remove a child node from its parent if attached.
+ * Remove a child node from its parent if attached. This is a workaround for
+ * IE11 which doesn't support `Element.prototype.remove()`. Using this function
+ * is smaller than including a dedicated polyfill.
* @param {Node} node The node to remove
*/
export function removeNode(node) { |
e3fb80c7f7129dc0d735f8128e5ba4df226911fe | src/routes/index.js | src/routes/index.js | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import CoreLayout from '../layouts/CoreLayout/CoreLayout';
import Home from './UI/containers/HomeContainer';
import ViewTOSContainer from './ViewTOS/containers/ViewTOSContainer';
export default () => (
<Route path='/' component={CoreLayout}>
<IndexRoute component={Home} />
<Route path='view-tos/:id' component={ViewTOSContainer} />
</Route>
);
| import React from 'react';
import { Route, IndexRoute } from 'react-router';
import CoreLayout from '../layouts/CoreLayout/CoreLayout';
import HomeContainer from './UI/containers/HomeContainer';
import ViewTOSContainer from './ViewTOS/containers/ViewTOSContainer';
export default () => (
<Route path='/' component={CoreLayout}>
<IndexRoute component={HomeContainer} />
<Route path='view-tos/:id' component={ViewTOSContainer} />
</Route>
);
| Rename Home in routes.js to HomeContainer | Rename Home in routes.js to HomeContainer
| JavaScript | mit | City-of-Helsinki/helerm-ui,City-of-Helsinki/helerm-ui,City-of-Helsinki/helerm-ui | ---
+++
@@ -1,12 +1,12 @@
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import CoreLayout from '../layouts/CoreLayout/CoreLayout';
-import Home from './UI/containers/HomeContainer';
+import HomeContainer from './UI/containers/HomeContainer';
import ViewTOSContainer from './ViewTOS/containers/ViewTOSContainer';
export default () => (
<Route path='/' component={CoreLayout}>
- <IndexRoute component={Home} />
+ <IndexRoute component={HomeContainer} />
<Route path='view-tos/:id' component={ViewTOSContainer} />
</Route>
); |
59ee5513e39ae0e3f0c3435a6b7a012be9947da0 | src/upnp-service.js | src/upnp-service.js | var upnp = require("peer-upnp");
var http = require("http");
var server = http.createServer();
var PORT = 8080;
// start server on port 8080.
server.listen(PORT);
// Create a UPnP Peer.
var peer = upnp.createPeer({
prefix: "/upnp",
server: server
}).on("ready",function(peer){
console.log("ready");
// advertise device after peer is ready
device.advertise();
}).on("close",function(peer){
console.log("closed");
}).start();
// Create a Basic device.
var device = peer.createDevice({
autoAdvertise: true,
uuid: "",
productName: "IoT Reference Platform",
productVersion: "1.04",
domain: "schemas-upnp-org",
type: "Basic",
version: "1",
friendlyName: "IOTRP-DEVICE",
manufacturer: "Intel",
manufacturerURL: "http://www.intel.com/content/www/us/en/homepage.html",
modelName: "Edison",
modelDescription: "Intel IoT Device",
modelNumber: "Edison",
modelURL: "",
serialNumber: "",
UPC: ""
});
| var upnp = require("peer-upnp");
var http = require("http");
var server = http.createServer();
var PORT = 8080;
var name="IOT-DEVICE";
var model="IoT Device";
var modelUrl="";
var version="1.00";
var serial="12345678";
var address="";
// Start server on port 8080.
server.listen(PORT);
// Create a UPnP Peer.
var peer = upnp.createPeer({
prefix: "/upnp",
server: server
}).on("ready",function(peer){
console.log("ready");
// Advertise device after peer is ready
device.advertise();
}).on("close",function(peer){
console.log("closed");
}).start();
// Create a Basic device.
var device = peer.createDevice({
autoAdvertise: true,
productName: "IoT Reference Platform",
domain: "schemas-upnp-org",
type: "Basic",
version: "1",
friendlyName: name,
manufacturer: "Intel",
manufacturerURL: "http://www.intel.com/content/www/us/en/homepage.html",
modelName: model,
modelDescription: "Intel IoT Device",
modelNumber: version,
modelURL: modelUrl,
serialNumber: serial,
presentationURL: address
});
| Add variables for easy configiration and customisation. | Add variables for easy configiration and customisation.
| JavaScript | mit | srware/iotrp-upnp-service,srware/iotrp-upnp-service | ---
+++
@@ -3,7 +3,14 @@
var server = http.createServer();
var PORT = 8080;
-// start server on port 8080.
+var name="IOT-DEVICE";
+var model="IoT Device";
+var modelUrl="";
+var version="1.00";
+var serial="12345678";
+var address="";
+
+// Start server on port 8080.
server.listen(PORT);
// Create a UPnP Peer.
@@ -12,7 +19,7 @@
server: server
}).on("ready",function(peer){
console.log("ready");
- // advertise device after peer is ready
+ // Advertise device after peer is ready
device.advertise();
}).on("close",function(peer){
console.log("closed");
@@ -21,19 +28,17 @@
// Create a Basic device.
var device = peer.createDevice({
autoAdvertise: true,
- uuid: "",
productName: "IoT Reference Platform",
- productVersion: "1.04",
domain: "schemas-upnp-org",
type: "Basic",
version: "1",
- friendlyName: "IOTRP-DEVICE",
+ friendlyName: name,
manufacturer: "Intel",
manufacturerURL: "http://www.intel.com/content/www/us/en/homepage.html",
- modelName: "Edison",
+ modelName: model,
modelDescription: "Intel IoT Device",
- modelNumber: "Edison",
- modelURL: "",
- serialNumber: "",
- UPC: ""
+ modelNumber: version,
+ modelURL: modelUrl,
+ serialNumber: serial,
+ presentationURL: address
}); |
ff1e5e08a86b7943b9cae4a472cbec3b73972917 | conversationStats.js | conversationStats.js | var accessToken = '';
var accessManager = Twilio.AccessManager(accessToken);
var client = Twilio.Conversations.Client(accessManager);
function handleConversationStats(conversation) {
console.log('Finish this next');
}
function onInviteAccepted(conversation) {
conversation.localMedia.attach('#local');
conversation.on('participantConnected', function(participant) {
participant.media.attach('#remote');
handleConversationStats(conversation);
});
}
client.listen().then(function () {
client.on('invite', function(invite) {
invite.accept().then(onInviteAccepted);
});
});
console.log('Hello Keeyon, s_haha_n, Niko, Gutomaia jer_dude, NichtBela and sir_majestic');
console.log('Also hello to Devin, Brent, Manny and Mheetu');
| var accessToken = '';
var accessManager = Twilio.AccessManager(accessToken);
var client = Twilio.Conversations.Client(accessManager);
function handleConversationStats(conversation) {
var dialog = conversation._dialogs.values().next().value;
var peerConnection = dialog.session.mediaHandler.peerConnection;
var selector = null;
var packets = 0;
setInterval(function() {
Works in FireFox
peerConnection.getStats(selector, function(report) {
for(var i in report) {
var currentReport = report[i];
if(currentReport.type === 'outboundrtp') {
console.log(currentReport);
packets += currentReport.packetsSent;
}
}
console.log('Number of packets sent so far: ' + packets);
}, function(error) {
console.log('Oh no I messed up: ' + error);
});
// Doesn't work in Chrome yet
// peerConnection.getStats(function(report) {
// console.log(report);
// for(var i in report) {
// var currentReport = report[i];
// if(currentReport.type === 'outboundrtp') {
// console.log(currentReport);
// packets += currentReport.packetsSent;
// }
// }
// console.log('Number of packets sent so far: ' + packets);
// }, selector, function(error) {
// console.log('Oh no I messed up: ' + error);
// });
}, 5000);
}
function standardizeReport(report) {
// Implement this next.
}
function onInviteAccepted(conversation) {
conversation.localMedia.attach('#local');
conversation.on('participantConnected', function(participant) {
participant.media.attach('#remote');
handleConversationStats(conversation);
});
}
client.listen().then(function () {
client.on('invite', function(invite) {
invite.accept().then(onInviteAccepted);
});
});
console.log('Hello Keeyon, s_haha_n, Niko, Gutomaia jer_dude, NichtBela and sir_majestic');
console.log('Also hello to Devin, Brent, Manny and Mheetu');
console.log('zykO rules and Trohnics is my pizza brother');
| Implement basic getStats call for FireFox | Implement basic getStats call for FireFox
| JavaScript | mit | sagnew/WebRTC-stats-with-Twilio-Video,sagnew/WebRTC-stats-with-Twilio-Video | ---
+++
@@ -3,7 +3,45 @@
var client = Twilio.Conversations.Client(accessManager);
function handleConversationStats(conversation) {
- console.log('Finish this next');
+ var dialog = conversation._dialogs.values().next().value;
+ var peerConnection = dialog.session.mediaHandler.peerConnection;
+ var selector = null;
+ var packets = 0;
+
+ setInterval(function() {
+ Works in FireFox
+ peerConnection.getStats(selector, function(report) {
+ for(var i in report) {
+ var currentReport = report[i];
+ if(currentReport.type === 'outboundrtp') {
+ console.log(currentReport);
+ packets += currentReport.packetsSent;
+ }
+ }
+ console.log('Number of packets sent so far: ' + packets);
+ }, function(error) {
+ console.log('Oh no I messed up: ' + error);
+ });
+
+ // Doesn't work in Chrome yet
+ // peerConnection.getStats(function(report) {
+ // console.log(report);
+ // for(var i in report) {
+ // var currentReport = report[i];
+ // if(currentReport.type === 'outboundrtp') {
+ // console.log(currentReport);
+ // packets += currentReport.packetsSent;
+ // }
+ // }
+ // console.log('Number of packets sent so far: ' + packets);
+ // }, selector, function(error) {
+ // console.log('Oh no I messed up: ' + error);
+ // });
+ }, 5000);
+}
+
+function standardizeReport(report) {
+ // Implement this next.
}
function onInviteAccepted(conversation) {
@@ -24,3 +62,4 @@
console.log('Hello Keeyon, s_haha_n, Niko, Gutomaia jer_dude, NichtBela and sir_majestic');
console.log('Also hello to Devin, Brent, Manny and Mheetu');
+console.log('zykO rules and Trohnics is my pizza brother'); |
d4fa0d6ee68cc5848c048426ad96b876c3ba919e | generators/app/templates/gulp_tasks/webpack.js | generators/app/templates/gulp_tasks/webpack.js | const gulp = require('gulp');
const gutil = require('gulp-util');
const webpack = require('webpack');
const webpackConf = require('../conf/webpack.conf');
const webpackDistConf = require('../conf/webpack-dist.conf');
<% if (framework !== 'react') { -%>
const browsersync = require('browser-sync');
<% } -%>
gulp.task('webpack:dev', done => {
webpackWrapper(false, webpackConf, done);
});
gulp.task('webpack:watch', done => {
webpackWrapper(true, webpackConf, done);
});
gulp.task('webpack:dist', done => {
webpackWrapper(false, webpackDistConf, done);
});
function webpackWrapper(watch, conf, done) {
const webpackBundler = webpack(conf);
const webpackChangeHandler = (err, stats) => {
if (err) {
conf.errorHandler('Webpack')(err);
}
gutil.log(stats.toString({
colors: true,
chunks: false,
hash: false,
version: false
}));
if (done) {
done();
done = null;
<% if (framework !== 'react') { -%>
} else {
browsersync.reload();
}
<% } else { -%>
}
<% } -%>
};
if (watch) {
webpackBundler.watch(200, webpackChangeHandler);
} else {
webpackBundler.run(webpackChangeHandler);
}
}
| const gulp = require('gulp');
const gutil = require('gulp-util');
const webpack = require('webpack');
const webpackConf = require('../conf/webpack.conf');
const webpackDistConf = require('../conf/webpack-dist.conf');
const gulpConf = require('../conf/gulp.conf');
<% if (framework !== 'react') { -%>
const browsersync = require('browser-sync');
<% } -%>
gulp.task('webpack:dev', done => {
webpackWrapper(false, webpackConf, done);
});
gulp.task('webpack:watch', done => {
webpackWrapper(true, webpackConf, done);
});
gulp.task('webpack:dist', done => {
webpackWrapper(false, webpackDistConf, done);
});
function webpackWrapper(watch, conf, done) {
const webpackBundler = webpack(conf);
const webpackChangeHandler = (err, stats) => {
if (err) {
gulpConf.errorHandler('Webpack')(err);
}
gutil.log(stats.toString({
colors: true,
chunks: false,
hash: false,
version: false
}));
if (done) {
done();
done = null;
<% if (framework !== 'react') { -%>
} else {
browsersync.reload();
}
<% } else { -%>
}
<% } -%>
};
if (watch) {
webpackBundler.watch(200, webpackChangeHandler);
} else {
webpackBundler.run(webpackChangeHandler);
}
}
| Fix errorHandler to come from gulp.conf | Fix errorHandler to come from gulp.conf
| JavaScript | mit | FountainJS/generator-fountain-webpack | ---
+++
@@ -4,6 +4,7 @@
const webpack = require('webpack');
const webpackConf = require('../conf/webpack.conf');
const webpackDistConf = require('../conf/webpack-dist.conf');
+const gulpConf = require('../conf/gulp.conf');
<% if (framework !== 'react') { -%>
const browsersync = require('browser-sync');
<% } -%>
@@ -25,7 +26,7 @@
const webpackChangeHandler = (err, stats) => {
if (err) {
- conf.errorHandler('Webpack')(err);
+ gulpConf.errorHandler('Webpack')(err);
}
gutil.log(stats.toString({
colors: true, |
f9e14c05bd39985b3a0baad55fb30e51b86e5229 | src/components/chat/AddChatMessage.js | src/components/chat/AddChatMessage.js | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
this.textInput.focus()
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
} | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
this.textInput.focus()
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick} disabled={(this.state.message.trim()=='')}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
} | Send button disabled as long as there is no message | Send button disabled as long as there is no message
| JavaScript | mit | axax/lunuc,axax/lunuc,axax/lunuc | ---
+++
@@ -29,7 +29,7 @@
return (
<div>
<textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
- <button onClick={this.onSendCick}>Send</button>
+ <button onClick={this.onSendCick} disabled={(this.state.message.trim()=='')}>Send</button>
</div>
)
} |
a0ffe902f0b63ec6f18d4339f6f0ff767907b3ca | tasks/concurrent.js | tasks/concurrent.js | 'use strict';
var lpad = require('lpad');
module.exports = function (grunt) {
grunt.registerMultiTask('concurrent', 'Run grunt tasks concurrently', function () {
var spawnOptions;
var cb = this.async();
var options = this.options();
// Set the tasks based on the config format
var tasks = this.data.tasks || this.data;
// Optionally log the task output
if (options.logConcurrentOutput) {
spawnOptions = { stdio: 'inherit' };
}
lpad.stdout(' ');
grunt.util.async.forEach(tasks, function (task, next) {
grunt.util.spawn({
grunt: true,
args: [task].concat(grunt.option.flags()),
opts: spawnOptions
}, function (err, result, code) {
if (err || code > 0) {
grunt.warn(result.stderr || result.stdout);
}
grunt.log.writeln('\n' + result.stdout);
next();
});
}, function () {
lpad.stdout();
cb();
});
});
};
| 'use strict';
var lpad = require('lpad');
var cpCache = [];
module.exports = function (grunt) {
grunt.registerMultiTask('concurrent', 'Run grunt tasks concurrently', function () {
var spawnOptions;
var cb = this.async();
var options = this.options();
// Set the tasks based on the config format
var tasks = this.data.tasks || this.data;
// Optionally log the task output
if (options.logConcurrentOutput) {
spawnOptions = { stdio: 'inherit' };
}
lpad.stdout(' ');
grunt.util.async.forEach(tasks, function (task, next) {
var cp = grunt.util.spawn({
grunt: true,
args: [task].concat(grunt.option.flags()),
opts: spawnOptions
}, function (err, result, code) {
if (err || code > 0) {
grunt.warn(result.stderr || result.stdout);
}
grunt.log.writeln('\n' + result.stdout);
next();
});
cpCache.push(cp);
}, function () {
lpad.stdout();
cb();
});
});
};
// make sure all child processes are killed when grunt exits
process.on('exit', function () {
cpCache.forEach(function (el) {
el.kill();
});
});
| Kill any hanging processes when grunt exits | Kill any hanging processes when grunt exits
| JavaScript | mit | ekashida/grunt-concurrent,nqdy666/grunt-concurrent,jimf/grunt-concurrent,sindresorhus/grunt-concurrent | ---
+++
@@ -1,5 +1,6 @@
'use strict';
var lpad = require('lpad');
+var cpCache = [];
module.exports = function (grunt) {
grunt.registerMultiTask('concurrent', 'Run grunt tasks concurrently', function () {
@@ -16,7 +17,7 @@
lpad.stdout(' ');
grunt.util.async.forEach(tasks, function (task, next) {
- grunt.util.spawn({
+ var cp = grunt.util.spawn({
grunt: true,
args: [task].concat(grunt.option.flags()),
opts: spawnOptions
@@ -27,9 +28,18 @@
grunt.log.writeln('\n' + result.stdout);
next();
});
+
+ cpCache.push(cp);
}, function () {
lpad.stdout();
cb();
});
});
};
+
+// make sure all child processes are killed when grunt exits
+process.on('exit', function () {
+ cpCache.forEach(function (el) {
+ el.kill();
+ });
+}); |
6b39b5481f6ff63353dd63749006423bb5aa8998 | tasks/contrib-ci.js | tasks/contrib-ci.js | /*
* grunt-contrib-internal
* http://gruntjs.com/
*
* Copyright (c) 2016 Tyler Kellen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var path = require('path');
grunt.registerTask('contrib-ci', 'Normalizes AppVeyor and Travis CI configs.', function(skipIfExists) {
skipIfExists = skipIfExists === true;
var travis = grunt.file.read(path.join(__dirname, '..', '.travis.yml'));
var appveyor = grunt.file.read(path.join(__dirname, '..', 'appveyor.yml'));
var taskTravis = path.join(process.cwd(), '.travis.yml');
if (!skipIfExists || !grunt.file.exists(taskTravis)) {
grunt.file.write(taskTravis, travis);
}
var taskAppveyor = path.join(process.cwd(), 'appveyor.yml');
if (!skipIfExists || !grunt.file.exists(taskAppveyor)) {
grunt.file.write(taskAppveyor, appveyor);
}
grunt.log.ok('Normalized .travis.yml and appveyor.yml for grunt-contrib.');
});
};
| /*
* grunt-contrib-internal
* http://gruntjs.com/
*
* Copyright (c) 2016 Tyler Kellen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var path = require('path');
grunt.registerTask('contrib-ci', 'Normalizes AppVeyor and Travis CI configs.', function(skipIfExists) {
skipIfExists = skipIfExists === "skipIfExists";
var travis = grunt.file.read(path.join(__dirname, '..', '.travis.yml'));
var appveyor = grunt.file.read(path.join(__dirname, '..', 'appveyor.yml'));
var taskTravis = path.join(process.cwd(), '.travis.yml');
if (!skipIfExists || !grunt.file.exists(taskTravis)) {
grunt.file.write(taskTravis, travis);
}
var taskAppveyor = path.join(process.cwd(), 'appveyor.yml');
if (!skipIfExists || !grunt.file.exists(taskAppveyor)) {
grunt.file.write(taskAppveyor, appveyor);
}
grunt.log.ok('Normalized .travis.yml and appveyor.yml for grunt-contrib.');
});
};
| Use skipIfExists instead of true | Use skipIfExists instead of true
| JavaScript | mit | gruntjs/grunt-contrib-internal | ---
+++
@@ -11,7 +11,7 @@
module.exports = function(grunt) {
var path = require('path');
grunt.registerTask('contrib-ci', 'Normalizes AppVeyor and Travis CI configs.', function(skipIfExists) {
- skipIfExists = skipIfExists === true;
+ skipIfExists = skipIfExists === "skipIfExists";
var travis = grunt.file.read(path.join(__dirname, '..', '.travis.yml'));
var appveyor = grunt.file.read(path.join(__dirname, '..', 'appveyor.yml'));
var taskTravis = path.join(process.cwd(), '.travis.yml'); |
46f34b40c88f5ddb680ae57e9eae14c640224272 | test/helpers/api.js | test/helpers/api.js | var
request = require('request'),
config = require('../../config');
exports.get = function () {
var query = arguments.length === 2 ? arguments[0] : null;
var callback = arguments[arguments.length - 1];
var options = {
uri: 'http://localhost:' + config.port + '/components',
timeout: 3000,
json: true
};
if (query) {
options.uri += '/' + query;
}
request.get(options, callback);
};
exports.search = function (query, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/?q=' + query,
timeout: 3000,
json: true
};
request.get(options, callback);
};
exports.getScript = function (pkg, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/' + pkg + '/script.js',
timeout: 3000
};
request.get(options, callback);
};
| var
request = require('request'),
config = require('../../config');
exports.get = function () {
var query = arguments.length === 2 ? arguments[0] : null;
var callback = arguments[arguments.length - 1];
var options = {
uri: 'http://localhost:' + config.port + '/components',
timeout: 3000,
json: true
};
if (query) {
options.uri += '/' + query;
}
request.get(options, callback);
};
exports.search = function (query, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/?q=' + query,
timeout: 3000,
json: true
};
request.get(options, callback);
};
exports.getScript = function (pkg, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/' + pkg + '/script.js',
timeout: 3000
};
request.get(options, callback);
};
exports.getBuild = function (pkg, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/' + pkg + '/build.js',
timeout: 3000
};
request.get(options, callback);
};
| Correct API helper scripts for getScript and getBuild | Correct API helper scripts for getScript and getBuild
| JavaScript | mit | web-audio-components/web-audio-components-service | ---
+++
@@ -36,3 +36,12 @@
request.get(options, callback);
};
+
+exports.getBuild = function (pkg, callback) {
+ var options = {
+ uri: 'http://localhost:' + config.port + '/components/' + pkg + '/build.js',
+ timeout: 3000
+ };
+
+ request.get(options, callback);
+}; |
bc5c67d28c74bc05d5d4578b230dacb97b7b638e | html/tools/js/nrs.modals.accountinfo.js | html/tools/js/nrs.modals.accountinfo.js | var NRS = (function(NRS, $, undefined) {
NRS.forms.setAccountInfoComplete = function(response, data) {
var name = $.trim(String(data.name));
if (name) {
$("#account_name").html(name.escapeHTML());
} else {
$("#account_name").html("No name set");
}
}
return NRS;
}(NRS || {}, jQuery)); | var NRS = (function(NRS, $, undefined) {
$("#account_info_modal").on("show.bs.modal", function(e) {
$("#account_info_name").val(NRS.accountInfo.name);
$("#account_info_description").val(NRS.accountInfo.description);
});
NRS.forms.setAccountInfoComplete = function(response, data) {
var name = $.trim(String(data.name));
if (name) {
$("#account_name").html(name.escapeHTML());
} else {
$("#account_name").html("No name set");
}
}
return NRS;
}(NRS || {}, jQuery)); | Set current account name/description when opening modal. | Set current account name/description when opening modal.
| JavaScript | mit | duckx/nxt,metrospark/czarcraft,duckx/nxt,Ziftr/nxt,Ziftr/nxt,fimkrypto/nxt,metrospark/czarcraft,fimkrypto/nxt,duckx/nxt,fimkrypto/nxt,fimkrypto/nxt,Ziftr/nxt,metrospark/czarcraft | ---
+++
@@ -1,4 +1,9 @@
var NRS = (function(NRS, $, undefined) {
+ $("#account_info_modal").on("show.bs.modal", function(e) {
+ $("#account_info_name").val(NRS.accountInfo.name);
+ $("#account_info_description").val(NRS.accountInfo.description);
+ });
+
NRS.forms.setAccountInfoComplete = function(response, data) {
var name = $.trim(String(data.name));
if (name) { |
e0f464f518765d28b95ab32563c5af7b9bef936c | test/steps/forms.js | test/steps/forms.js | var helper = require('massah/helper')
module.exports = (function() {
var library = helper.getLibrary()
.given('I enter \'(.*)\' in the \'(.*)\' field', function(value, field) {
this.driver.input('*[name="' + field + '"]').enter(value)
if (!this.params.fields) this.params.fields = {}
this.params.fields[field] = value
})
.then('the \'(.*)\' field has error \'(.*)\'', function(field, error) {
var selector = 'div.error span.help-inline'
this.driver.element(selector).text(function(text) {
text.should.equal(error)
})
this.driver.element('div.error input[name="' + field + '"]').then(
function() {},
function() { throw new Error('Expected error field') }
)
})
return library
})()
| var helper = require('massah/helper')
module.exports = (function() {
var library = helper.getLibrary()
.given('I enter \'(.*)\' in the \'(.*)\' field', function(value, field) {
this.driver.input('*[name="' + field + '"]').clear()
this.driver.input('*[name="' + field + '"]').enter(value)
if (!this.params.fields) this.params.fields = {}
this.params.fields[field] = value
})
.then('the \'(.*)\' field has error \'(.*)\'', function(field, error) {
var selector = 'div.error span.help-inline'
this.driver.element(selector).text(function(text) {
text.should.equal(error)
})
this.driver.element('div.error input[name="' + field + '"]').then(
function() {},
function() { throw new Error('Expected error field') }
)
})
return library
})()
| Clear form fields before entering new values | Clear form fields before entering new values
| JavaScript | apache-2.0 | pinittome/pinitto.me,pinittome/pinitto.me,pinittome/pinitto.me | ---
+++
@@ -3,7 +3,8 @@
module.exports = (function() {
var library = helper.getLibrary()
.given('I enter \'(.*)\' in the \'(.*)\' field', function(value, field) {
- this.driver.input('*[name="' + field + '"]').enter(value)
+ this.driver.input('*[name="' + field + '"]').clear()
+ this.driver.input('*[name="' + field + '"]').enter(value)
if (!this.params.fields) this.params.fields = {}
this.params.fields[field] = value
}) |
32eb10c7aa884fb03314be0cd5144064fc977a7d | src/shared/components/form/formEmail/formEmail.js | src/shared/components/form/formEmail/formEmail.js | import React, { Component } from 'react';
import FormInput from '../formInput/formInput';
class FormEmail extends Component {
render() {
const validEmailRegex = /(^[^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})/;
return (
<FormInput
{...this.props}
validationRegex={validEmailRegex}
validationErrorMessage="Must be a valid email"
ref={(child) => { this.inputRef = child; }}
/>
);
}
}
export default FormEmail;
| import React, { Component } from 'react';
import FormInput from '../formInput/formInput';
class FormEmail extends Component {
render() {
const validEmailRegex = /(^[^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})/;
return (
<FormInput
{...this.props}
validationRegex={validEmailRegex}
validationErrorMessage="Must be a valid email"
ref={(child) => { this.inputRef = child; }}
/>
);
}
}
export default FormEmail;
| Add blank line for readability | Add blank line for readability | JavaScript | mit | tal87/operationcode_frontend,hollomancer/operationcode_frontend,tal87/operationcode_frontend,hollomancer/operationcode_frontend,NestorSegura/operationcode_frontend,NestorSegura/operationcode_frontend,OperationCode/operationcode_frontend,tskuse/operationcode_frontend,tal87/operationcode_frontend,tskuse/operationcode_frontend,sethbergman/operationcode_frontend,tskuse/operationcode_frontend,hollomancer/operationcode_frontend,sethbergman/operationcode_frontend,OperationCode/operationcode_frontend,sethbergman/operationcode_frontend,OperationCode/operationcode_frontend,NestorSegura/operationcode_frontend | ---
+++
@@ -4,6 +4,7 @@
class FormEmail extends Component {
render() {
const validEmailRegex = /(^[^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})/;
+
return (
<FormInput
{...this.props} |
ab6c02edaa802dea6d4ee01ba4f56172d7605802 | app/javascripts/views/main_view.js | app/javascripts/views/main_view.js | Checklist.MainView = Ember.View.extend({
tagName: 'section',
templateName: 'main_view',
classNames: ['main'],
landingColorboxConfig: {
inline: true,
transition: 'fade',
close: 'x',
opacity: 0.8,
fixed: true,
maxWidth: 675,
innerWidth: 675,
open: true,
className: 'landing',
onClosed: function(event) {
$.cookie("Checklist.CONFIG.visited", true);
}
},
didInsertElement: function() {
var target = document.getElementById('loading');
var spinner = new Spinner(Checklist.CONFIG.spinner).spin(target);
if (!$.cookie("Checklist.CONFIG.visited")) {
$('#landing-btn').colorbox(this.get('landingColorboxConfig'));
}
},
closeLandingBox: function(event) {
$.colorbox.close();
},
doLocaleEN: function(event) {
Checklist.router.transitionTo('home.index', {locale: 'en'});
$('#landing-btn').colorbox(this.get('landingColorboxConfig'));
},
doLocaleES: function(event) {
Checklist.router.transitionTo('home.index', {locale: 'es'});
$('#landing-btn').colorbox(this.get('landingColorboxConfig'));
},
doLocaleFR: function(event) {
Checklist.router.transitionTo('home.index', {locale: 'fr'});
$('#landing-btn').colorbox(this.get('landingColorboxConfig'));
}
});
| Checklist.MainView = Ember.View.extend({
tagName: 'section',
templateName: 'main_view',
classNames: ['main'],
landingColorboxConfig: {
inline: true,
transition: 'fade',
close: 'x',
opacity: 0.8,
fixed: true,
maxWidth: 675,
innerWidth: 675,
open: true,
className: 'landing',
onClosed: function(event) {
$.cookie("Checklist.CONFIG.visited", true);
}
},
didInsertElement: function() {
var target = document.getElementById('loading');
var spinner = new Spinner(Checklist.CONFIG.spinner).spin(target);
var popup = location.href.split(/(&|\?)popup=/).pop()
if(popup !== undefined && popup == "0") {
$.cookie("Checklist.CONFIG.visited", true);
}
if (!$.cookie("Checklist.CONFIG.visited")) {
$('#landing-btn').colorbox(this.get('landingColorboxConfig'));
}
},
closeLandingBox: function(event) {
$.colorbox.close();
},
doLocaleEN: function(event) {
Checklist.router.transitionTo('home.index', {locale: 'en'});
$('#landing-btn').colorbox(this.get('landingColorboxConfig'));
},
doLocaleES: function(event) {
Checklist.router.transitionTo('home.index', {locale: 'es'});
$('#landing-btn').colorbox(this.get('landingColorboxConfig'));
},
doLocaleFR: function(event) {
Checklist.router.transitionTo('home.index', {locale: 'fr'});
$('#landing-btn').colorbox(this.get('landingColorboxConfig'));
}
});
| Hide initial popup if popup param is 0 | Hide initial popup if popup param is 0
| JavaScript | bsd-3-clause | unepwcmc/cites-checklist,unepwcmc/cites-checklist,unepwcmc/cites-checklist | ---
+++
@@ -22,6 +22,11 @@
didInsertElement: function() {
var target = document.getElementById('loading');
var spinner = new Spinner(Checklist.CONFIG.spinner).spin(target);
+
+ var popup = location.href.split(/(&|\?)popup=/).pop()
+ if(popup !== undefined && popup == "0") {
+ $.cookie("Checklist.CONFIG.visited", true);
+ }
if (!$.cookie("Checklist.CONFIG.visited")) {
$('#landing-btn').colorbox(this.get('landingColorboxConfig')); |
6475b88b11ff49d3b880a0f16a7951dcfc06af27 | src/wef.core.js | src/wef.core.js | /*!
* Wef
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
/**
* wef module
*/
(function(global) {
var wef = function() {
return new wef.prototype.init();
};
wef.prototype = {
constructor:wef,
version: "0.0.1",
init: function() {
return this;
}
};
wef.fn = wef.prototype;
wef.prototype.init.prototype = wef.prototype;
wef.fn.extend = function (receiver, giver) {
var tmp = receiver;
//both must be objects
if (typeof receiver === "object" && typeof giver === "object") {
if (tmp == null) {
tmp = {};
}
if (receiver == null) {
return tmp;
}
for (var property in giver) {
tmp[property] = giver[property];
}
return tmp
}
wef.f.error("InvalidArgumentException: incorrect argument type");
return null;
};
wef.fn.isFunction = function (obj) {
return typeof obj == "function";
};
wef.fn.isString = function (obj) {
return typeof obj == "string";
};
wef.fn.error = function (message) {
throw new Error(message);
};
//registering global variable
if (global.wef) {
throw new Error("wef has already been defined");
} else {
global.wef = wef();
}
})(window);
| /*!
* Wef
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
/**
* wef module
*/
(function(global) {
var wef = function() {
return new wef.prototype.init();
};
wef.prototype = {
constructor:wef,
version: "0.0.1",
init: function() {
return this;
}
};
wef.fn = wef.prototype;
wef.prototype.init.prototype = wef.prototype;
wef.fn.extend = function (receiver, giver) {
var tmp = receiver;
//both must be objects
if (typeof receiver === "object" && typeof giver === "object") {
if (tmp === null) {
tmp = {};
}
if (receiver === null) {
return tmp;
}
for (var property in giver) {
tmp[property] = giver[property];
}
return tmp
}
wef.f.error("InvalidArgumentException: incorrect argument type");
return null;
};
wef.fn.isFunction = function (obj) {
return typeof obj == "function";
};
wef.fn.isString = function (obj) {
return typeof obj == "string";
};
wef.fn.error = function (message) {
throw new Error(message);
};
//registering global variable
if (global.wef) {
throw new Error("wef has already been defined");
} else {
global.wef = wef();
}
})(window);
| Fix jslint warning in null checks | Fix jslint warning in null checks
| JavaScript | mit | diesire/wef,diesire/wef,diesire/wef | ---
+++
@@ -25,10 +25,10 @@
var tmp = receiver;
//both must be objects
if (typeof receiver === "object" && typeof giver === "object") {
- if (tmp == null) {
+ if (tmp === null) {
tmp = {};
}
- if (receiver == null) {
+ if (receiver === null) {
return tmp;
}
for (var property in giver) { |
297921acf811fc8508b5581d4e761403a288f2b8 | lib/webhooks/riskOrderStatus.js | lib/webhooks/riskOrderStatus.js | /* LIB */
const radial = require('../../radial');
const authenticate = require('./authenticate');
/* MODULES */
const xmlConvert = require('xml-js');
/* CONSTRUCTOR */
(function () {
var RiskOrderStatus = {};
/* PRIVATE VARIABLES */
/* PUBLIC VARIABLES */
/* PUBLIC FUNCTIONS */
RiskOrderStatus.parse = function (req, fn) {
authenticate('riskOrderStatus', req, function (err) {
if (err) {
return fn({
status: 401,
type: 'Authentication Failed',
message: err.message
});
}
var body = req.body;
var reply = body.RiskAssessmentReplyList;
return fn(null, reply);
});
};
/* NPM EXPORT */
if (typeof module === 'object' && module.exports) {
module.exports = RiskOrderStatus.parse;
} else {
throw new Error('This module only works with NPM in NodeJS environments.');
}
}());
| /* LIB */
const radial = require('../../radial');
const authenticate = require('./authenticate');
/* MODULES */
const xmlConvert = require('xml-js');
/* CONSTRUCTOR */
(function () {
var RiskOrderStatus = {};
/* PRIVATE VARIABLES */
/* PUBLIC VARIABLES */
/* PUBLIC FUNCTIONS */
RiskOrderStatus.parse = function (req, fn) {
authenticate('riskOrderStatus', req, function (err) {
if (err) {
return fn({
status: 401,
type: 'Authentication Failed',
message: err.message
});
}
var body = req.body;
var reply = body.RiskAssessmentReplyList || body.riskassessmentreplylist;
var list = reply.RiskAssessmentReply || reply.riskassessmentreply;
var replyList = [];
list.forEach(function (item) {
replyList.push({
orderId: item.OrderId || item.orderid,
responseCode: item.ResponseCode || item.responsecode,
storeId: item.StoreId || item.storeid,
reasonCode: item.ReasonCode || item.reasoncode,
reasonCodeDescription: item.ReasonCodeDescription || item.reasoncodedescription
});
});
return fn(null, replyList);
});
};
/* NPM EXPORT */
if (typeof module === 'object' && module.exports) {
module.exports = RiskOrderStatus.parse;
} else {
throw new Error('This module only works with NPM in NodeJS environments.');
}
}());
| Improve reply list response for risk status webhook. | Improve reply list response for risk status webhook.
| JavaScript | mit | giftnix/node-radial | ---
+++
@@ -30,9 +30,21 @@
}
var body = req.body;
- var reply = body.RiskAssessmentReplyList;
+ var reply = body.RiskAssessmentReplyList || body.riskassessmentreplylist;
+ var list = reply.RiskAssessmentReply || reply.riskassessmentreply;
- return fn(null, reply);
+ var replyList = [];
+ list.forEach(function (item) {
+ replyList.push({
+ orderId: item.OrderId || item.orderid,
+ responseCode: item.ResponseCode || item.responsecode,
+ storeId: item.StoreId || item.storeid,
+ reasonCode: item.ReasonCode || item.reasoncode,
+ reasonCodeDescription: item.ReasonCodeDescription || item.reasoncodedescription
+ });
+ });
+
+ return fn(null, replyList);
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.