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 |
|---|---|---|---|---|---|---|---|---|---|---|
6a8911b4c95529923a198c534c87615ed5833a18 | addon/components/mail-check.js | addon/components/mail-check.js | import Ember from 'ember';
import Mailcheck from 'mailcheck';
export default Ember.Component.extend({
type: 'email',
name: 'email',
value: '',
placeholder: '',
suggestion: '',
inputClass: 'mailcheck-input',
classNames: ['mailcheck'],
actions: {
mailcheck: function() {
var _this = this;
Mailcheck.run({
email: _this.value,
suggested: function(suggestion) {
var message = 'Did you mean ';
_this.set('hint', message);
_this.set('suggestion', suggestion.full);
},
empty: function() {
var email = _this.value;
if (isEmail(email)) {
return;
}
var message = 'You seem to be missing an email domain, like @gmail.com or @hotmail.com';
_this.set('hint', message);
_this.set('suggestion', null);
}
});
},
useSuggestion: function() {
this.set('value', this.get('suggestion'));
}
}
});
function isEmail(email) {
return Ember.isPresent(email) &&
/^([\w_\.\-\+])+\@([\w\-]+\.)+([\w]{2,10})+$/.test(email);
}
| import Ember from 'ember';
import Mailcheck from 'mailcheck';
export default Ember.Component.extend({
type: 'email',
name: 'email',
value: '',
placeholder: '',
suggestion: '',
inputClass: 'mailcheck-input',
classNames: ['mailcheck'],
actions: {
mailcheck: function() {
var _this = this;
Mailcheck.run({
email: _this.value,
suggested: function(suggestion) {
var message = 'Did you mean ';
_this.set('hint', message);
_this.set('suggestion', suggestion.full);
},
empty: function() {
var email = _this.value;
if (isEmail(email)) {
_this.set('hint', null);
_this.set('suggestion', null);
return;
}
var message = 'You seem to be missing an email domain, like @gmail.com or @hotmail.com';
_this.set('hint', message);
_this.set('suggestion', null);
}
});
},
useSuggestion: function() {
this.set('value', this.get('suggestion'));
}
}
});
function isEmail(email) {
return Ember.isPresent(email) &&
/^([\w_\.\-\+])+\@([\w\-]+\.)+([\w]{2,10})+$/.test(email);
}
| Hide hint when a valid email is input | Hide hint when a valid email is input
| JavaScript | mit | johnotander/ember-mailcheck,johnotander/ember-mailcheck | ---
+++
@@ -25,6 +25,8 @@
var email = _this.value;
if (isEmail(email)) {
+ _this.set('hint', null);
+ _this.set('suggestion', null);
return;
}
|
d8488c998a2094a1eaf44fcb2399f31b1491f8df | test/app.js | test/app.js | var request = require('supertest');
var app = require('../app.js');
describe('GET /', function() {
it('should return 200 OK', function(done) {
request(app)
.get('/')
.expect(200, done);
});
});
describe('GET /reset', function() {
it('should return 404', function(done) {
request(app)
.get('/reset')
.expect(404, done);
// this will fail
});
}); | var request = require('supertest');
var app = require('../app.js');
describe('GET /', function() {
it('should return 200 OK', function(done) {
request(app)
.get('/')
.expect(200, done);
});
});
describe('GET /login', function() {
it('should return 200 OK', function(done) {
request(app)
.get('/login')
.expect(200, done);
});
});
describe('GET /signup', function() {
it('should return 200 OK', function(done) {
request(app)
.get('/signup')
.expect(200, done);
});
});
describe('GET /api', function() {
it('should return 200 OK', function(done) {
request(app)
.get('/api')
.expect(200, done);
});
});
describe('GET /contact', function() {
it('should return 200 OK', function(done) {
request(app)
.get('/contact')
.expect(200, done);
});
});
describe('GET /random-url', function() {
it('should return 404', function(done) {
request(app)
.get('/reset')
.expect(404, done);
});
}); | Add additional supertest tests for /signup, /api, /contact and /login | Add additional supertest tests for /signup, /api, /contact and /login
| JavaScript | mit | quazar11/portfolio,suamorales/course-registration,duchangyu/project-starter,bowdenk7/express-typescript-starter,jochan/mddb,dborncamp/shuttles,cmubick/sufficientlyridiculous,ahng1996/balloon-fight,gdiab/hackathon-starter,ColdMonkey/vcoin,loiralae/WaterlooHacks-Winter-2016-v2,pvijeh/node-express-mongo-api,peterblazejewicz/hackathon-starter,shareonbazaar/bazaar,flashsnake-so/hackathon-starter,thomasythuang/Bugatti,gdiab/hackathon-starter,guilhermeasg/outspeak,jnaulty/brigadehub,webschoolfactory/tp-2019,fenwick67/fcc-voting-app,webschoolfactory/tp-2019,erood/creepy_ghost,nwhacks2016-travelRecommendation/travel-app,duchangyu/project-starter,denniskkim/jackson5,crystalrood/piggie,sinned/gifvision-node,stepheljobs/tentacool,benwells/admin.mrbenwells.com,wfpc92/cleansuit-backend,pvijeh/node-express-mongo-api,sfbrigade/brigadehub,colleenDunlap/Lake-Map,baby03201/hackathon-starter,ColdMonkey/vcoin,denniskkim/jackson5,ch4tml/fcc-voting-app,stenio123/ai-hackathon,tilast/lubiko,JeffRice/Geolocation-Demo,Jarvl/ENG2089-Project,webschoolfactory/tp-2019,devneel/spitsomebars,niallobrien/hackathon-starter-plus,rachidbch/learn,denniskkim/jackson5,ericmreid/pingypong,awarn/bitcoins-trader,jochan/mddb,ajijohn/brainprinter,awarn/cashier-analytics,awarn/cashier-analytics,teogenesmoura/SoftwareEng12016,erood/weight_tracker_app,vymarkov/hackathon-starter,Torone/toro-starter,LucienBrule/carpool,tendermario/binners-project,jakeki/futista_node,dafyddPrys/contingency,erood/creepy_ghost,uptownhr/resume,adamnuttall/typing-app,tendermario/binners-project,denniskkim/jackson5,uptownhr/lolgames,therebelrobot/brigadehub,backjo/OrganizationManager,colleenDunlap/PlayingOnInternet,denniskkim/jackson5,cmubick/sufficientlyridiculous,IsaacHardy/HOCO-FF-APP,colleenDunlap/PlayingOnInternet,bowdenk7/express-typescript-starter,KareemG/cirqulate,CodeJockey1337/frameworks_project4,GeneralZero/StarTreck-node,caofb/hackathon-starter,sfbrigade/brigadehub,peterblazejewicz/hackathon-starter,nikvi/STEM-W,caofb/hackathon-starter,guilhermeasg/outspeak,bewest/samedrop-collector,ibanzajoe/realTemp,MikeMichel/hackathon-starter,LucienBrule/carpool,Jarvl/ENG2089-Project,sinned/gifvision-node,flashsnake-so/hackathon-starter,projectsm/hfmp,Torone/toro-starter,dafyddPrys/contingency,CodeJockey1337/frameworks_project4,mackness/Routemetrics,sahat/hackathon-starter,niallobrien/hackathon-starter-plus,sinned/gifvision-node,HappyGenes/HappyGenes,CahalKearney/node-boilerplate,extraBitsStudios/find-a-condom,awarn/bitcoins-trader,CAYdenberg/wikode,ishan-marikar/hackathon-starter,rickitan/2014-Brazil-World-Cup-Pool,OperationSpark/Hackathon-Angel,mrwolfyu/meteo-bbb,thmr/tutm-nodejs-test,dborncamp/shuttles,erood/weight_tracker_app,rachidbch/Dokku1ClickDigitalOcean,rachidbch/learn,jnaulty/brigadehub,shareonbazaar/bazaar,LovelyHorse/goodfaith,hect1c/front-end-test,dischord01/hackathon-01,CAYdenberg/wikode,thmr/tutm-nodejs-test,ahng1996/balloon-fight,sahat/hackathon-starter,MikeMichel/hackathon-starter,JessedeGit/vegtable,ak-zul/hackathon-starter,nehiljain/rhime,bowdenk7/express-typescript-starter,denniskkim/jackson5,stenio123/ai-hackathon,benwells/admin.mrbenwells.com,wfpc92/cleansuit-backend,uptownhr/lolgames,LovelyHorse/goodfaith,baby03201/hackathon-starter,jakeki/futista_node,estimmerman/pennappsxiii,loiralae/WaterlooHacks-Winter-2016-v2,carlos-guzman/VChronos,BlueAccords/vr-cinema,nehiljain/rhime,backjo/LAHacks,ch4tml/fcc-voting-app,denniskkim/jackson5,EvelynSun/fcc-vote1,ajijohn/brainprinter,denniskkim/jackson5,MrMaksimize/hack-votr,shareonbazaar/bazaar,uptownhr/real-estate,projectsm/hfmp,bewest/samedrop-collector,OperationSpark/Hackathon-Angel,respectus/indel,cwesno/app_for_us,KareemG/cirqulate,yhnavein/express-starter,mostley/backstab,ReadingPlus/flog,uptownhr/resume,HappyGenes/HappyGenes,ak-zul/hackathon-starter,denniskkim/jackson5,colleenDunlap/Lake-Map,Yixuan-Angela/hackathon-starter,rachidbch/CIDokkuDigitalOcean,ajijohn/brainprinter,estimmerman/pennappsxiii,ReadingPlus/flog,mohi-io/mohi-io-api,suamorales/course-registration,ajijohn/brainprinter,jwalsh/hackbostonstrong2014-bostonrush,ibanzajoe/realTemp,JessedeGit/vegtable,quazar11/portfolio,mostley/backstab,dischord01/hackathon-01,peterblazejewicz/hackathon-starter,yhnavein/express-starter,DrJukka/hackathon-starter,DrJukka/hackathon-starter,Carlosreyesk/boards-api,fenwick67/fcc-voting-app,crystalrood/piggie,colleenDunlap/PlayingOnInternet,adamnuttall/typing-app,carlos-guzman/VChronos,BlueAccords/vr-cinema,rockaBe/betters-club,sahat/hackathon-starter,stepheljobs/tentacool,mrwolfyu/meteo-bbb,okeeffe/insurify,teogenesmoura/SoftwareEng12016,MikeMichel/hackathon-starter,ericmreid/pingypong,devneel/spitsomebars,dischord01/hackathon-01,hect1c/front-end-test,itsmomito/gitfood,thomasythuang/Bugatti,mackness/Routemetrics,nehiljain/rhime,uptownhr/real-estate,itsmomito/gitfood,Jarvl/ENG2089-Project,Yixuan-Angela/hackathon-starter,gurneyman/riToolkit,carlos-guzman/VChronos,crystalrood/piggie,rachidbch/CIDokkuDigitalOcean,therebelrobot/brigadehub,rachidbch/Dokku1ClickDigitalOcean,colleenDunlap/Lake-Map,respectus/indel,CahalKearney/node-boilerplate,nwhacks2016-travelRecommendation/travel-app,Carlosreyesk/boards-api,gurneyman/riToolkit,vymarkov/hackathon-starter,cwesno/app_for_us,ishan-marikar/hackathon-starter,EvelynSun/fcc-vote1,IsaacHardy/HOCO-FF-APP | ---
+++
@@ -9,11 +9,42 @@
});
});
-describe('GET /reset', function() {
+describe('GET /login', function() {
+ it('should return 200 OK', function(done) {
+ request(app)
+ .get('/login')
+ .expect(200, done);
+ });
+});
+
+describe('GET /signup', function() {
+ it('should return 200 OK', function(done) {
+ request(app)
+ .get('/signup')
+ .expect(200, done);
+ });
+});
+
+describe('GET /api', function() {
+ it('should return 200 OK', function(done) {
+ request(app)
+ .get('/api')
+ .expect(200, done);
+ });
+});
+
+describe('GET /contact', function() {
+ it('should return 200 OK', function(done) {
+ request(app)
+ .get('/contact')
+ .expect(200, done);
+ });
+});
+
+describe('GET /random-url', function() {
it('should return 404', function(done) {
request(app)
.get('/reset')
.expect(404, done);
- // this will fail
});
}); |
570f3636195ebbd2a1e36210eecf85deb9556843 | js/components/developer/choose-job-type-screen/index.js | js/components/developer/choose-job-type-screen/index.js | import React, { Component } from 'react';
import { Container, Content } from 'native-base';
import JobTypeCard from './jobTypeCard';
import GlobalStyle from '../../common/globalStyle';
// Temporary constants. These will be moved and implemented in another way in the future!
const EXAMPLE_IMAGE_URL = 'https://facebook.github.io/react/img/logo_og.png';
const JOBS = ['Snöskottning', 'Lövkrattning', 'Städning', 'Ogräsrensning'];
export default class ChooseJobTypeScreen extends Component {
static navigationOptions = {
title: 'Choose Job Type',
};
render() {
// Creates a JobTypeCard for each job in the JOBS array.
const jobTypeCards = JOBS.map((job, i) => <JobTypeCard key={job.concat(i)} title={job} subtitle={`Behöver du hjälp med ${job.toLowerCase()}?`} cover={EXAMPLE_IMAGE_URL} icon={EXAMPLE_IMAGE_URL} />);
return (
<Container>
<Content contentContainerStyle={GlobalStyle.padder}>
{jobTypeCards}
</Content>
</Container>
);
}
}
| import React, { Component } from 'react';
import { Container, Content, List } from 'native-base';
import JobTypeCard from './jobTypeCard';
import GlobalStyle from '../../common/globalStyle';
// Temporary constants. These will be moved and implemented in another way in the future!
const EXAMPLE_IMAGE_URL = 'https://facebook.github.io/react/img/logo_og.png';
const JOB_TYPES = ['Snöskottning', 'Lövkrattning', 'Städning', 'Ogräsrensning'];
export default class ChooseJobTypeScreen extends Component {
static navigationOptions = {
title: 'Choose Job Type',
};
renderRow = jobType => (
<JobTypeCard
title={jobType} subtitle={`Behöver du hjälp med ${jobType.toLowerCase()}?`}
cover={EXAMPLE_IMAGE_URL} icon={EXAMPLE_IMAGE_URL}
/>
);
render() {
return (
<Container>
<Content contentContainerStyle={GlobalStyle.padder}>
<List dataArray={JOB_TYPES} renderRow={this.renderRow} />
</Content>
</Container>
);
}
}
| Use List from NativeBase to display job types in ChooseJobTypeScreen | Use List from NativeBase to display job types in ChooseJobTypeScreen
| JavaScript | mit | justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client | ---
+++
@@ -1,26 +1,30 @@
import React, { Component } from 'react';
-import { Container, Content } from 'native-base';
+import { Container, Content, List } from 'native-base';
import JobTypeCard from './jobTypeCard';
import GlobalStyle from '../../common/globalStyle';
// Temporary constants. These will be moved and implemented in another way in the future!
const EXAMPLE_IMAGE_URL = 'https://facebook.github.io/react/img/logo_og.png';
-const JOBS = ['Snöskottning', 'Lövkrattning', 'Städning', 'Ogräsrensning'];
+const JOB_TYPES = ['Snöskottning', 'Lövkrattning', 'Städning', 'Ogräsrensning'];
export default class ChooseJobTypeScreen extends Component {
static navigationOptions = {
title: 'Choose Job Type',
};
+ renderRow = jobType => (
+ <JobTypeCard
+ title={jobType} subtitle={`Behöver du hjälp med ${jobType.toLowerCase()}?`}
+ cover={EXAMPLE_IMAGE_URL} icon={EXAMPLE_IMAGE_URL}
+ />
+ );
+
render() {
- // Creates a JobTypeCard for each job in the JOBS array.
- const jobTypeCards = JOBS.map((job, i) => <JobTypeCard key={job.concat(i)} title={job} subtitle={`Behöver du hjälp med ${job.toLowerCase()}?`} cover={EXAMPLE_IMAGE_URL} icon={EXAMPLE_IMAGE_URL} />);
-
return (
<Container>
<Content contentContainerStyle={GlobalStyle.padder}>
- {jobTypeCards}
+ <List dataArray={JOB_TYPES} renderRow={this.renderRow} />
</Content>
</Container>
); |
db7bc3914c1d83f6998be5840fbf43afd977d6ec | src/js/components/ServiceSearchFilter.js | src/js/components/ServiceSearchFilter.js | import mixin from 'reactjs-mixin';
import React from 'react';
import FilterInputText from './FilterInputText';
import QueryParamsMixin from '../mixins/QueryParamsMixin';
import ServiceFilterTypes from '../constants/ServiceFilterTypes';
const METHODS_TO_BIND = ['setSearchString'];
class ServiceSearchFilter extends mixin(QueryParamsMixin) {
static get defaultProps() {
return {
};
}
constructor() {
super();
this.state = {
searchString: ''
};
METHODS_TO_BIND.forEach((method) => {
this[method] = this[method].bind(this);
});
}
componentDidMount() {
this.updateFilterStatus();
}
componentWillReceiveProps() {
this.updateFilterStatus();
}
setSearchString(filterValue) {
this.setQueryParam(ServiceFilterTypes.TEXT, filterValue);
this.props.handleFilterChange(filterValue, ServiceFilterTypes.TEXT);
}
updateFilterStatus() {
let {state} = this;
let searchString =
this.getQueryParamObject()[ServiceFilterTypes.TEXT] || '';
if (searchString !== state.searchString) {
this.setState({searchString},
this.props.handleFilterChange.bind(null, searchString, ServiceFilterTypes.TEXT));
}
}
render() {
return (
<FilterInputText
searchString={this.state.searchString}
handleFilterChange={this.setSearchString} />
);
}
};
module.exports = ServiceSearchFilter;
| import mixin from 'reactjs-mixin';
import React from 'react';
import FilterInputText from './FilterInputText';
import QueryParamsMixin from '../mixins/QueryParamsMixin';
import ServiceFilterTypes from '../constants/ServiceFilterTypes';
const METHODS_TO_BIND = ['setSearchString'];
class ServiceSearchFilter extends mixin(QueryParamsMixin) {
static get defaultProps() {
return {
};
}
constructor() {
super();
this.state = {
searchString: ''
};
METHODS_TO_BIND.forEach((method) => {
this[method] = this[method].bind(this);
});
}
componentDidMount() {
this.updateFilterStatus();
}
componentWillReceiveProps() {
this.updateFilterStatus();
}
setSearchString(filterValue) {
this.setQueryParam(ServiceFilterTypes.TEXT, filterValue);
this.props.handleFilterChange(filterValue, ServiceFilterTypes.TEXT);
}
updateFilterStatus() {
let {state} = this;
let searchString =
this.getQueryParamObject()[ServiceFilterTypes.TEXT] || '';
if (searchString !== state.searchString) {
this.setState({searchString},
this.props.handleFilterChange.bind(null, searchString, ServiceFilterTypes.TEXT));
}
}
render() {
return (
<FilterInputText
handleFilterChange={this.setSearchString}
inverseStyle={true}
placeholder="Search"
searchString={this.state.searchString} />
);
}
};
module.exports = ServiceSearchFilter;
| Correct placeholder for input field | Correct placeholder for input field
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -52,8 +52,10 @@
render() {
return (
<FilterInputText
- searchString={this.state.searchString}
- handleFilterChange={this.setSearchString} />
+ handleFilterChange={this.setSearchString}
+ inverseStyle={true}
+ placeholder="Search"
+ searchString={this.state.searchString} />
);
}
}; |
ce99214f1f6285c0d631065cbb391f62a31ed31c | client/tests/end2end/protractor-sauce.config.js | client/tests/end2end/protractor-sauce.config.js | var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
| var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH];
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
| Add branch tag to saucelabs runs | Add branch tag to saucelabs runs
| JavaScript | agpl-3.0 | vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks | ---
+++
@@ -5,6 +5,7 @@
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
+browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH];
exports.config = {
framework: 'jasmine', |
e42b5abd256c9a6ef4a336985bd0de77759b4ef0 | src/SortOptions.js | src/SortOptions.js | 'use strict';
const ProgramError = require('./error/ProgramError');
class SortOptions
{
constructor(options = {})
{
this.path = 'sort';
this.unique = false;
this.numeric = false;
this.reverse = false;
this.stable = false;
this.merge = false;
this.ignoreCase = false;
this.sortByHash = false;
this.tmpDir = null;
this.bufferSize = null;
this.separator = '\t';
this.threads = null;
this.keys = [];
this.inMemoryBufferSize = 16000;
for (const k in options) {
if (!this.hasOwnProperty(k)) {
throw new ProgramError('Unknown option: ' + k);
}
this[k] = options[k];
}
}
/**
*
* @returns {SortOptions}
*/
clone()
{
return new SortOptions(this);
}
}
module.exports = SortOptions;
| 'use strict';
const ProgramError = require('./error/ProgramError');
class SortOptions
{
constructor(options = {})
{
this.path = 'sort';
this.unique = false;
this.numeric = false;
this.reverse = false;
this.stable = false;
this.merge = false;
this.ignoreCase = false;
this.sortByHash = false;
this.tmpDir = null;
this.bufferSize = 64 * 1024 * 1024;
this.separator = '\t';
this.threads = null;
this.keys = [];
this.inMemoryBufferSize = 16000;
for (const k in options) {
if (!this.hasOwnProperty(k)) {
throw new ProgramError('Unknown option: ' + k);
}
this[k] = options[k];
}
}
/**
*
* @returns {SortOptions}
*/
clone()
{
return new SortOptions(this);
}
}
module.exports = SortOptions;
| Set default buffer size to 64M | Set default buffer size to 64M | JavaScript | mit | avz/node-jl-sql-api | ---
+++
@@ -15,7 +15,7 @@
this.ignoreCase = false;
this.sortByHash = false;
this.tmpDir = null;
- this.bufferSize = null;
+ this.bufferSize = 64 * 1024 * 1024;
this.separator = '\t';
this.threads = null;
this.keys = []; |
515bb10c47efffa3c6a6de09339774154bcb7506 | website/gatsby-config.js | website/gatsby-config.js | module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `content`,
path: `${__dirname}/../content`,
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
icon: `${__dirname}/src/images/kitura.svg`
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images`,
options: {
// It's important to specify the maxWidth (in pixels) of
// the content container as this plugin uses this as the
// base for generating different widths of each image.
maxWidth: 1200,
},
},
`gatsby-remark-autolink-headers`,
`gatsby-remark-prismjs`],
}
},
`gatsby-transformer-yaml`,
`gatsby-plugin-sass`,
]
} | module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `content`,
path: `${__dirname}/../content`,
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
icon: `src/images/kitura.svg`
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images`,
options: {
// It's important to specify the maxWidth (in pixels) of
// the content container as this plugin uses this as the
// base for generating different widths of each image.
maxWidth: 1200,
},
},
`gatsby-remark-autolink-headers`,
`gatsby-remark-prismjs`],
}
},
`gatsby-transformer-yaml`,
`gatsby-plugin-sass`,
]
} | Update relative path for favicon | Update relative path for favicon
| JavaScript | apache-2.0 | IBM-Swift/kitura.io | ---
+++
@@ -10,7 +10,7 @@
{
resolve: `gatsby-plugin-manifest`,
options: {
- icon: `${__dirname}/src/images/kitura.svg`
+ icon: `src/images/kitura.svg`
},
},
{ |
ee2a5723a417eeac7609322cbd85b300cdd81cb7 | website/versionConfig.js | website/versionConfig.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @format
*/
// The versions here are used across the documentation
// To use it in normal mdx, you can import this file and use a variable e.g. {site.lithoVersion}
// To use it in codeblocks, use the component in /docs/component/versionedCodeBlock.js,
// and refer to the version as: e.g. {{site.lithoVersion}}
export const site = {
lithoVersion: '0.38.0',
lithoSnapshotVersion: '0.38.1-SNAPSHOT',
soloaderVersion: '0.9.0',
flipperVersion: '0.46.0',
};
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @format
*/
// The versions here are used across the documentation
// To use it in normal mdx, you can import this file and use a variable e.g. {site.lithoVersion}
// To use it in codeblocks, use the component in /docs/component/versionedCodeBlock.js,
// and refer to the version as: e.g. {{site.lithoVersion}}
export const site = {
lithoVersion: '0.40.0',
lithoSnapshotVersion: '0.40.1-SNAPSHOT',
soloaderVersion: '0.9.0',
flipperVersion: '0.46.0',
};
| Update Litho version for Docusaurus | Update Litho version for Docusaurus
Reviewed By: muraziz
Differential Revision: D27236872
fbshipit-source-id: ccab5ed8a444cbf1027070a0261c108c307642f7
| JavaScript | apache-2.0 | facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho | ---
+++
@@ -22,8 +22,8 @@
// and refer to the version as: e.g. {{site.lithoVersion}}
export const site = {
- lithoVersion: '0.38.0',
- lithoSnapshotVersion: '0.38.1-SNAPSHOT',
+ lithoVersion: '0.40.0',
+ lithoSnapshotVersion: '0.40.1-SNAPSHOT',
soloaderVersion: '0.9.0',
flipperVersion: '0.46.0',
}; |
e22a2dd76a1f2329b981f3d6caa64e658ed0a16e | public/javascripts/DV/models/chapter.js | public/javascripts/DV/models/chapter.js | DV.model.Chapters = function(viewer) {
this.viewer = viewer;
this.loadChapters();
};
DV.model.Chapters.prototype = {
// Load (or reload) the chapter model from the schema's defined sections.
loadChapters : function() {
var sections = this.viewer.schema.data.sections;
var chapters = this.chapters = this.viewer.schema.data.chapters = [];
_.each(sections, function(sec){ sec.id || (sec.id = parseInt(_.uniqueId())); });
DV._.each(sections, function(sec){ sec.id || (sec.id = parseInt( DV._.uniqueId())); });
var sectionIndex = 0;
for (var i = 0, l = this.viewer.schema.data.totalPages; i < l; i++) {
var section = sections[sectionIndex];
var nextSection = sections[sectionIndex + 1];
if (nextSection && (i >= (nextSection.page - 1))) {
sectionIndex += 1;
section = nextSection;
}
if (section && !(section.page > i + 1)) chapters[i] = section.id;
}
},
getChapterId: function(index){
return this.chapters[index];
},
getChapterPosition: function(chapterId){
for(var i = 0,len=this.chapters.length; i < len; i++){
if(this.chapters[i] === chapterId){
return i;
}
}
}
};
| DV.model.Chapters = function(viewer) {
this.viewer = viewer;
this.loadChapters();
};
DV.model.Chapters.prototype = {
// Load (or reload) the chapter model from the schema's defined sections.
loadChapters : function() {
var sections = this.viewer.schema.data.sections;
var chapters = this.chapters = this.viewer.schema.data.chapters = [];
DV._.each(sections, function(sec){ sec.id || (sec.id = parseInt( DV._.uniqueId())); });
var sectionIndex = 0;
for (var i = 0, l = this.viewer.schema.data.totalPages; i < l; i++) {
var section = sections[sectionIndex];
var nextSection = sections[sectionIndex + 1];
if (nextSection && (i >= (nextSection.page - 1))) {
sectionIndex += 1;
section = nextSection;
}
if (section && !(section.page > i + 1)) chapters[i] = section.id;
}
},
getChapterId: function(index){
return this.chapters[index];
},
getChapterPosition: function(chapterId){
for(var i = 0,len=this.chapters.length; i < len; i++){
if(this.chapters[i] === chapterId){
return i;
}
}
}
};
| Remove duplicated _.each loop on sections | Remove duplicated _.each loop on sections
Looks like the original line got retained after
the move to "noConflict" underscore
| JavaScript | apache-2.0 | roberttdev/document-viewer4,roberttdev/document-viewer4,roberttdev/document-viewer4 | ---
+++
@@ -9,7 +9,6 @@
loadChapters : function() {
var sections = this.viewer.schema.data.sections;
var chapters = this.chapters = this.viewer.schema.data.chapters = [];
- _.each(sections, function(sec){ sec.id || (sec.id = parseInt(_.uniqueId())); });
DV._.each(sections, function(sec){ sec.id || (sec.id = parseInt( DV._.uniqueId())); });
var sectionIndex = 0;
for (var i = 0, l = this.viewer.schema.data.totalPages; i < l; i++) { |
c524f8cc6533f28e9a0883b944d962bfc978c853 | app/assets/javascripts/osem-datatables.js | app/assets/javascripts/osem-datatables.js | $(function () {
$.extend(true, $.fn.dataTable.defaults, {
"stateSave": true,
"autoWidth": false,
"pagingType": "full_numbers",
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
});
$('.datatable:not([data-source])').DataTable();
$('.datatable').on('init.dt', function (e, settings, json) {
var datatableApi = $(this).dataTable().api();
// Thanks to cale_b: https://stackoverflow.com/u/870729
// Stack Overflow question: https://stackoverflow.com/q/5548893
// Stack Overflow answer: https://stackoverflow.com/a/23897722
// Grab the datatables input box and alter how it is bound to events
$(".dataTables_filter input")
.unbind() // Unbind previous default bindings
.bind("input", function(e) { // Bind our desired behavior
// If the length is 3 or more characters, or the user pressed ENTER, search
if(this.value.length >= 3 || e.keyCode == 13) {
// Call the API search function
datatableApi.search(this.value).draw();
}
// Ensure we clear the search if they backspace far enough
if(this.value == "") {
datatableApi.search("").draw();
}
return;
});
});
});
| $(function () {
$.extend(true, $.fn.dataTable.defaults, {
"stateSave": true,
"autoWidth": false,
"pagingType": "full_numbers",
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
});
$('.datatable:not([data-source])').DataTable();
$('.datatable').on('init.dt', function (e, settings, json) {
var datatableApi = $(this).dataTable().api();
// Thanks to cale_b: https://stackoverflow.com/u/870729
// Stack Overflow question: https://stackoverflow.com/q/5548893
// Stack Overflow answer: https://stackoverflow.com/a/23897722
// Grab the datatables input box and alter how it is bound to events
$(".dataTables_filter input")
.unbind() // Unbind previous default bindings
.bind("input", function(e) { // Bind our desired behavior
// If the length is 3 or more characters, or the user pressed ENTER, search
if(this.value.length >= 3 || e.keyCode == 13) {
// Call the API search function
datatableApi.search(this.value).draw();
}
// Ensure we clear the search if they backspace far enough
if(this.value == "") {
datatableApi.search("").draw();
}
return;
});
});
});
| Add an option for shorter datatable pages | Add an option for shorter datatable pages
| JavaScript | mit | rishabhptr/osem,openSUSE/osem,hennevogel/osem,bear454/osem,AndrewKvalheim/osem,differentreality/osem,rishabhptr/osem,AndrewKvalheim/osem,SeaGL/osem,openSUSE/osem,openSUSE/osem,hennevogel/osem,bear454/osem,AndrewKvalheim/osem,differentreality/osem,differentreality/osem,bear454/osem,rishabhptr/osem,differentreality/osem,bear454/osem,hennevogel/osem,hennevogel/osem,SeaGL/osem,SeaGL/osem,rishabhptr/osem | ---
+++
@@ -3,7 +3,7 @@
"stateSave": true,
"autoWidth": false,
"pagingType": "full_numbers",
- "lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
+ "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
});
$('.datatable:not([data-source])').DataTable(); |
ece010234d9b5de8ec4d90b9f8b30992baae9997 | jquery.instance.js | jquery.instance.js | /* jQuery.instance
* ---------------
*
* Quick guide:
*
* var $one = $("#sidebar").instance();
* var $two = $("#sidebar").instance();
* $one.abc = 42;
* $two.abc; //=> 42
*
* var Rule = {
* expand: function () { ... }
* };
*
* var $one = $("#sidebar").instance(Rule);
* $one.expand();
*/
;(function($) {
$.fn.instance = function (type) {
var $this = this.first();
var $this = $this.data('instance') || ($this.data('instance', $this) && $this);
// Tip: Implement a 'klass' property to make sure extending doesn't happen twice.
if ((type) && ((!$this.klass) || (!type.klass) || ($this.klass != type.klass))) {
$this.extend(type);
}
return $this;
};
})(jQuery);
| // jQuery.instance
// ---------------
;(function($) {
$.fn.instance = function (type) {
var $this = this.first();
var $this = $this.data('instance') || ($this.data('instance', $this) && $this);
// Tip: Implement a 'klass' property to make sure extending doesn't happen twice.
if ((type) && ((!$this.klass) || (!type.klass) || ($this.klass != type.klass))) {
$this.extend(type);
}
return $this;
};
})(jQuery);
/* Quick usage guide:
*
* var $one = $("#sidebar").instance();
* var $two = $("#sidebar").instance();
* $one.abc = 42;
* $two.abc; //=> 42
*
* var Rule = {
* expand: function () { ... }
* };
*
* var $one = $("#sidebar").instance(Rule);
* $one.expand();
*/
| Make the JS file more readable by moving the comments. | Make the JS file more readable by moving the comments.
| JavaScript | mit | sinefunc/jquery.instance | ---
+++
@@ -1,7 +1,21 @@
-/* jQuery.instance
- * ---------------
- *
- * Quick guide:
+// jQuery.instance
+// ---------------
+
+;(function($) {
+ $.fn.instance = function (type) {
+ var $this = this.first();
+ var $this = $this.data('instance') || ($this.data('instance', $this) && $this);
+
+ // Tip: Implement a 'klass' property to make sure extending doesn't happen twice.
+ if ((type) && ((!$this.klass) || (!type.klass) || ($this.klass != type.klass))) {
+ $this.extend(type);
+ }
+
+ return $this;
+ };
+})(jQuery);
+
+/* Quick usage guide:
*
* var $one = $("#sidebar").instance();
* var $two = $("#sidebar").instance();
@@ -16,16 +30,3 @@
* $one.expand();
*/
-;(function($) {
- $.fn.instance = function (type) {
- var $this = this.first();
- var $this = $this.data('instance') || ($this.data('instance', $this) && $this);
-
- // Tip: Implement a 'klass' property to make sure extending doesn't happen twice.
- if ((type) && ((!$this.klass) || (!type.klass) || ($this.klass != type.klass))) {
- $this.extend(type);
- }
-
- return $this;
- };
-})(jQuery); |
4edc55154305a022bf53c6015811d11ef38ce4ee | tests/docs.js | tests/docs.js | 'use strict';
var docs = require('../docs/src/js/docs');
var expect = require('chai').expect;
var sinon = require('sinon');
var stub = sinon.stub;
var utils = require('./helpers/utils');
var each = utils.each;
var any = utils.any;
var getContextStub = require('./helpers/get-context-stub');
var Canvas = require('../lib/index.js');
describe('docs', function () {
var element = document.createElement('canvas');
stub(element, 'getContext', getContextStub);
var canvas = new Canvas(element);
it('is a list of groups', function () {
expect(docs.length).to.be.above(1);
each(docs, function (value) {
expect(value.name).to.exist;
expect(value.methods).to.exist;
});
});
it('should contain all of the canvasimo methods (or aliases)', function () {
each(canvas, function (value, key) {
var anyGroupContainsTheMethod = any(docs, function (group) {
return any(group.methods, function (method) {
return method.name === key || method.alias === key;
});
});
expect(anyGroupContainsTheMethod).to.be.true;
});
});
});
| 'use strict';
var docs = require('../docs/src/js/docs');
var expect = require('chai').expect;
var sinon = require('sinon');
var stub = sinon.stub;
var utils = require('./helpers/utils');
var each = utils.each;
var any = utils.any;
var getContextStub = require('./helpers/get-context-stub');
var Canvas = require('../lib/index.js');
describe('docs', function () {
var element = document.createElement('canvas');
stub(element, 'getContext', getContextStub);
var canvas = new Canvas(element);
it('is a list of groups', function () {
expect(docs.length).to.be.above(1);
each(docs, function (value) {
expect(value.name).to.exist;
expect(value.methods).to.exist;
});
});
it('should contain all of the canvasimo methods and aliases', function () {
each(canvas, function (value, key) {
var anyGroupContainsTheMethod = any(docs, function (group) {
return any(group.methods, function (method) {
return method.name === key || method.alias === key;
});
});
expect(anyGroupContainsTheMethod).to.be.true;
});
});
it('should have descriptions for every method', function () {
each(docs, function (group) {
each(group.methods, function (method) {
expect(method.description).to.exist;
expect(method.description).to.be.ok;
});
});
});
it('should have arguments or returns for every method', function () {
each(docs, function (group) {
each(group.methods, function (method) {
expect(method.arguments || method.returns).to.exist;
});
});
});
});
| Add tests for description, arguments & returns | Add tests for description, arguments & returns
| JavaScript | mit | JakeSidSmith/canvasimo,JakeSidSmith/sensible-canvas-interface,JakeSidSmith/canvasimo | ---
+++
@@ -25,7 +25,7 @@
});
});
- it('should contain all of the canvasimo methods (or aliases)', function () {
+ it('should contain all of the canvasimo methods and aliases', function () {
each(canvas, function (value, key) {
var anyGroupContainsTheMethod = any(docs, function (group) {
return any(group.methods, function (method) {
@@ -37,4 +37,21 @@
});
});
+ it('should have descriptions for every method', function () {
+ each(docs, function (group) {
+ each(group.methods, function (method) {
+ expect(method.description).to.exist;
+ expect(method.description).to.be.ok;
+ });
+ });
+ });
+
+ it('should have arguments or returns for every method', function () {
+ each(docs, function (group) {
+ each(group.methods, function (method) {
+ expect(method.arguments || method.returns).to.exist;
+ });
+ });
+ });
+
}); |
f7ea63cc1349b5abade097fa9bf83bf60fddae07 | src/js/settings.js | src/js/settings.js |
const os = require('os')
const prefix = 'webjcs:'
class Settings {
constructor (defaults = {}) {
this.defaults = defaults
}
set (key, value) {
window.localStorage.setItem(prefix + key, JSON.stringify(value))
}
setDefault (key) {
const def = this.defaults[key]
this.set(key, def)
return def
}
get (key) {
let item = window.localStorage.getItem(prefix + key)
if (item === null) item = this.defaults[key]
else item = JSON.parse(item)
return item
}
}
module.exports = new Settings({
renderer: 'webgl-advanced',
paths: IS_ELECTRON && os.platform() === 'win32' ? ['C:\\Games\\Jazz2\\'] : [],
jj2_exe: IS_ELECTRON && os.platform() === 'win32' ? 'C:\\Games\\Jazz2\\Jazz2+.exe' : '',
jj2_args: IS_ELECTRON ? '-windowed -nolog' + (os.platform() !== 'win32' ? ' -noddrawmemcheck -nocpucheck' : '') : '',
wine_prefix: IS_ELECTRON && os.platform() !== 'win32' && process.env.HOME ? process.env.HOME : ''
})
|
const os = require('os')
const prefix = 'webjcs:'
class Settings {
constructor (defaults = {}) {
this.defaults = defaults
}
set (key, value) {
window.localStorage.setItem(prefix + key, JSON.stringify(value))
}
setDefault (key) {
const def = this.defaults[key]
this.set(key, def)
return def
}
get (key) {
let item = window.localStorage.getItem(prefix + key)
if (item === null) item = this.defaults[key]
else item = JSON.parse(item)
return item
}
}
module.exports = new Settings({
renderer: 'webgl',
paths: IS_ELECTRON && os.platform() === 'win32' ? ['C:\\Games\\Jazz2\\'] : [],
jj2_exe: IS_ELECTRON && os.platform() === 'win32' ? 'C:\\Games\\Jazz2\\Jazz2+.exe' : '',
jj2_args: IS_ELECTRON ? '-windowed -nolog' + (os.platform() !== 'win32' ? ' -noddrawmemcheck -nocpucheck' : '') : '',
wine_prefix: IS_ELECTRON && os.platform() !== 'win32' && process.env.HOME ? process.env.HOME : ''
})
| Make normal WebGL the default renderer | Make normal WebGL the default renderer
| JavaScript | mit | daniel-j/webjcs,daniel-j/webjcs | ---
+++
@@ -25,7 +25,7 @@
}
module.exports = new Settings({
- renderer: 'webgl-advanced',
+ renderer: 'webgl',
paths: IS_ELECTRON && os.platform() === 'win32' ? ['C:\\Games\\Jazz2\\'] : [],
jj2_exe: IS_ELECTRON && os.platform() === 'win32' ? 'C:\\Games\\Jazz2\\Jazz2+.exe' : '', |
560831185980b3caffbe9365c45d73c468de67b3 | src/settings/LanguagePickerItem.js | src/settings/LanguagePickerItem.js | /* @flow */
import React, { PureComponent } from 'react';
import { StyleSheet, View } from 'react-native';
import type { Context } from '../types';
import { RawLabel, Touchable } from '../common';
import { BRAND_COLOR } from '../styles';
import { IconDone } from '../common/Icons';
const componentStyles = StyleSheet.create({
flag: {
paddingRight: 8,
},
language: {
flex: 1,
},
});
type Props = {
locale: string,
flag: string,
name: string,
selected: boolean,
onValueChange: (locale: string) => void,
};
export default class LanguagePickerItem extends PureComponent<Props> {
context: Context;
props: Props;
static contextTypes = {
styles: () => null,
};
render() {
const { styles } = this.context;
const { locale, flag, name, selected, onValueChange } = this.props;
return (
<Touchable onPress={() => onValueChange(locale)}>
<View style={styles.listItem}>
<RawLabel style={componentStyles.flag} text={flag} />
<RawLabel style={componentStyles.language} text={name} />
{selected && <IconDone size={16} color={BRAND_COLOR} />}
</View>
</Touchable>
);
}
}
| /* @flow */
import React, { PureComponent } from 'react';
import { StyleSheet, View } from 'react-native';
import type { Context } from '../types';
import { RawLabel, Touchable } from '../common';
import { BRAND_COLOR } from '../styles';
import { IconDone } from '../common/Icons';
const componentStyles = StyleSheet.create({
flag: {
paddingRight: 8,
},
language: {
flex: 1,
},
listItem: {
flexDirection: 'row',
alignItems: 'center',
paddingTop: 8,
paddingBottom: 8,
paddingLeft: 16,
paddingRight: 16,
},
});
type Props = {
locale: string,
flag: string,
name: string,
selected: boolean,
onValueChange: (locale: string) => void,
};
export default class LanguagePickerItem extends PureComponent<Props> {
context: Context;
props: Props;
static contextTypes = {
styles: () => null,
};
render() {
const { locale, flag, name, selected, onValueChange } = this.props;
return (
<Touchable onPress={() => onValueChange(locale)}>
<View style={componentStyles.listItem}>
<RawLabel style={componentStyles.flag} text={flag} />
<RawLabel style={componentStyles.language} text={name} />
{selected && <IconDone size={16} color={BRAND_COLOR} />}
</View>
</Touchable>
);
}
}
| Define language list item style locally. | language-settings: Define language list item style locally.
This list is doing something idiosyncratic, following a particular iOS
settings-UI convention; so it won't necessarily follow our normal
style for a list.
This commit just copies the global style in, without yet changing it.
| JavaScript | apache-2.0 | vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile | ---
+++
@@ -13,6 +13,14 @@
},
language: {
flex: 1,
+ },
+ listItem: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ paddingTop: 8,
+ paddingBottom: 8,
+ paddingLeft: 16,
+ paddingRight: 16,
},
});
@@ -33,12 +41,11 @@
};
render() {
- const { styles } = this.context;
const { locale, flag, name, selected, onValueChange } = this.props;
return (
<Touchable onPress={() => onValueChange(locale)}>
- <View style={styles.listItem}>
+ <View style={componentStyles.listItem}>
<RawLabel style={componentStyles.flag} text={flag} />
<RawLabel style={componentStyles.language} text={name} />
{selected && <IconDone size={16} color={BRAND_COLOR} />} |
0e105f32b829a7786fb860d4d6c5761b3a9980da | src/emitter.js | src/emitter.js | export default class Emitter {
constructor() {
this._events = {}
}
_event(name) {
return (this._events[name] = this._events[name] || new Set())
}
on(name, fn) {
this._event(name).add(fn)
}
off(name, fn) {
if (fn) this._event(name).delete(fn)
else this._event(name).clear()
}
once(name, fn) {
const self = this
this.on(name, function(input) {
self.off(name, this)
fn(input)
})
}
emit(name, input) {
if (!this._events[name]) return
this._event(name).forEach(fn => fn(input))
}
}
| import { EmitterError } from './error'
export default class Emitter {
constructor() {
this._events = {}
}
_event(name) {
return (this._events[name] = this._events[name] || new Set())
}
on(name, fn) {
if (typeof fn !== 'function') throw new EmitterError('requires function')
this._event(name).add(fn)
}
off(name, fn) {
if (!this._events[name]) return
if (fn) this._event(name).delete(fn)
else this._event(name).clear()
}
once(name, fn) {
const self = this
this.on(name, function(input) {
self.off(name, this)
fn(input)
})
}
emit(name, input) {
if (!this._events[name]) return
this._event(name).forEach(fn => fn(input))
}
}
| Check for fn in .on(), bail early in .off() | Check for fn in .on(), bail early in .off()
| JavaScript | mit | kroogs/yaemit | ---
+++
@@ -1,3 +1,5 @@
+import { EmitterError } from './error'
+
export default class Emitter {
constructor() {
this._events = {}
@@ -8,10 +10,12 @@
}
on(name, fn) {
+ if (typeof fn !== 'function') throw new EmitterError('requires function')
this._event(name).add(fn)
}
off(name, fn) {
+ if (!this._events[name]) return
if (fn) this._event(name).delete(fn)
else this._event(name).clear()
} |
59b277521b4dcecc917a57c920e13ba08cf532ba | lib/ember_orbit.js | lib/ember_orbit.js | import EO from './ember_orbit/main';
import Model from './ember_orbit/model';
import attr from './ember_orbit/attr';
import hasOne from './ember_orbit/relationships/has_one';
import hasMany from './ember_orbit/relationships/has_many';
EO.Model = Model;
EO.attr = attr;
EO.hasOne = hasOne;
EO.hasMany = hasMany;
export default EO;
| import EO from './ember_orbit/main';
import Context from './ember_orbit/context';
import Model from './ember_orbit/model';
import RecordArrayManager from './ember_orbit/record_array_manager';
import Schema from './ember_orbit/schema';
import Source from './ember_orbit/source';
import Store from './ember_orbit/store';
import attr from './ember_orbit/attr';
import HasManyArray from './ember_orbit/links/has_many_array';
import HasOneObject from './ember_orbit/links/has_one_object';
import LinkProxyMixin from './ember_orbit/links/link_proxy_mixin';
import FilteredRecordArray from './ember_orbit/record_arrays/filtered_record_array';
import RecordArray from './ember_orbit/record_arrays/record_array';
import hasMany from './ember_orbit/relationships/has_many';
import hasOne from './ember_orbit/relationships/has_one';
EO.Context = Context;
EO.Model = Model;
EO.RecordArrayManager = RecordArrayManager;
EO.Schema = Schema;
EO.Source = Source;
EO.Store = Store;
EO.attr = attr;
EO.HasManyArray = HasManyArray;
EO.HasOneObject = HasOneObject;
EO.LinkProxyMixin = LinkProxyMixin;
EO.FilteredRecordArray = FilteredRecordArray;
EO.RecordArray = RecordArray;
EO.hasOne = hasOne;
EO.hasMany = hasMany;
export default EO;
| Expand top-level EO namespace members | Expand top-level EO namespace members
| JavaScript | mit | lytbulb/ember-orbit,pixelhandler/ember-orbit,gnarf/ember-orbit,ProlificLab/ember-orbit,orbitjs/ember-orbit,orbitjs/ember-orbit,gnarf/ember-orbit,pixelhandler/ember-orbit,greyhwndz/ember-orbit,opsb/ember-orbit,opsb/ember-orbit,lytbulb/ember-orbit,ProlificLab/ember-orbit,greyhwndz/ember-orbit,lytbulb/ember-orbit,orbitjs/ember-orbit | ---
+++
@@ -1,11 +1,31 @@
import EO from './ember_orbit/main';
+import Context from './ember_orbit/context';
import Model from './ember_orbit/model';
+import RecordArrayManager from './ember_orbit/record_array_manager';
+import Schema from './ember_orbit/schema';
+import Source from './ember_orbit/source';
+import Store from './ember_orbit/store';
import attr from './ember_orbit/attr';
+import HasManyArray from './ember_orbit/links/has_many_array';
+import HasOneObject from './ember_orbit/links/has_one_object';
+import LinkProxyMixin from './ember_orbit/links/link_proxy_mixin';
+import FilteredRecordArray from './ember_orbit/record_arrays/filtered_record_array';
+import RecordArray from './ember_orbit/record_arrays/record_array';
+import hasMany from './ember_orbit/relationships/has_many';
import hasOne from './ember_orbit/relationships/has_one';
-import hasMany from './ember_orbit/relationships/has_many';
+EO.Context = Context;
EO.Model = Model;
+EO.RecordArrayManager = RecordArrayManager;
+EO.Schema = Schema;
+EO.Source = Source;
+EO.Store = Store;
EO.attr = attr;
+EO.HasManyArray = HasManyArray;
+EO.HasOneObject = HasOneObject;
+EO.LinkProxyMixin = LinkProxyMixin;
+EO.FilteredRecordArray = FilteredRecordArray;
+EO.RecordArray = RecordArray;
EO.hasOne = hasOne;
EO.hasMany = hasMany;
|
e590d56a96a189284347c47f793bf44bdf0b8a03 | lib/skype/setup.js | lib/skype/setup.js | 'use strict';
const skReply = require('./reply');
const skParse = require('./parse');
module.exports = function skSetup(api, bot, logError) {
api.post('/skype', request => {
let arr = [].concat.apply([], request.body),
skContextId = request.headers.contextid;
let skHandle = parsedMessage => {
if (!parsedMessage) return;
return bot(parsedMessage)
.then(botResponse => skReply(request.env.skypeAppId, request.env.skypePrivateKey, parsedMessage.sender, botResponse, skContextId))
.catch(logError);
};
return Promise.all(arr.map(message => skParse(message)).map(skHandle))
.then(() => 'ok');
});
api.addPostDeployStep('facebook', (options, lambdaDetails, utils) => {
return utils.Promise.resolve().then(() => {
if (options['configure-skype-bot']) {
utils.Promise.promisifyAll(prompt);
prompt.start();
return prompt.getAsync(['Skype App ID', 'Skype Private key'])
.then(results => {
const deployment = {
restApiId: lambdaDetails.apiId,
stageName: lambdaDetails.alias,
variables: {
skypeAppId: results['Skype App ID'],
skypePrivateKey: results['Skype Private key']
}
};
return utils.apiGatewayPromise.createDeploymentPromise(deployment);
});
}
})
.then(() => `${lambdaDetails.apiUrl}/skype`);
});
};
| 'use strict';
const skReply = require('./reply');
const skParse = require('./parse');
module.exports = function skSetup(api, bot, logError) {
api.post('/skype', request => {
let arr = [].concat.apply([], request.body),
skContextId = request.headers.contextid;
let skHandle = parsedMessage => {
if (!parsedMessage) return;
return bot(parsedMessage)
.then(botResponse => skReply(request.env.skypeAppId, request.env.skypePrivateKey, parsedMessage.sender, botResponse, skContextId))
.catch(logError);
};
return Promise.all(arr.map(message => skParse(message)).map(skHandle))
.then(() => 'ok');
});
api.addPostDeployStep('skype', (options, lambdaDetails, utils) => {
return utils.Promise.resolve().then(() => {
if (options['configure-skype-bot']) {
utils.Promise.promisifyAll(prompt);
prompt.start();
return prompt.getAsync(['Skype App ID', 'Skype Private key'])
.then(results => {
const deployment = {
restApiId: lambdaDetails.apiId,
stageName: lambdaDetails.alias,
variables: {
skypeAppId: results['Skype App ID'],
skypePrivateKey: results['Skype Private key']
}
};
return utils.apiGatewayPromise.createDeploymentPromise(deployment);
});
}
})
.then(() => `${lambdaDetails.apiUrl}/skype`);
});
};
| Fix Skype postDeploy hook name | Fix Skype postDeploy hook name
| JavaScript | mit | IvanJov/claudia-bot-builder,claudiajs/claudia-bot-builder,jonjamz/claudia-bot-builder | ---
+++
@@ -20,7 +20,7 @@
.then(() => 'ok');
});
- api.addPostDeployStep('facebook', (options, lambdaDetails, utils) => {
+ api.addPostDeployStep('skype', (options, lambdaDetails, utils) => {
return utils.Promise.resolve().then(() => {
if (options['configure-skype-bot']) {
utils.Promise.promisifyAll(prompt); |
ea70ec45b38ce982fd3ddf38fca5693018766306 | modules/ui/preset_favorite.js | modules/ui/preset_favorite.js | import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { t } from '../util/locale';
import { svgIcon } from '../svg';
export function uiPresetFavorite(preset, geom, context, klass) {
var presetFavorite = {};
var _button = d3_select(null);
presetFavorite.button = function(selection) {
var canFavorite = geom !== 'relation';
_button = selection.selectAll('.preset-favorite-button')
.data(canFavorite ? [0] : []);
_button.exit().remove();
_button = _button.enter()
.insert('button', '.tag-reference-button')
.attr('class', 'preset-favorite-button ' + klass)
.attr('title', t('icons.favorite'))
.attr('tabindex', -1)
.call(svgIcon('#iD-icon-favorite'))
.merge(_button);
_button
.classed('active', function() {
return context.isFavoritePreset(preset, geom);
})
.on('click', function () {
d3_event.stopPropagation();
d3_event.preventDefault();
//update state of favorite icon
d3_select(this)
.classed('active', function() {
return !d3_select(this).classed('active');
});
context.favoritePreset(preset, geom);
});
};
return presetFavorite;
}
| import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { t } from '../util/locale';
import { svgIcon } from '../svg';
export function uiPresetFavorite(preset, geom, context, klass) {
var presetFavorite = {};
var _button = d3_select(null);
presetFavorite.button = function(selection) {
var canFavorite = geom !== 'relation';
_button = selection.selectAll('.preset-favorite-button')
.data(canFavorite ? [0] : []);
_button.exit().remove();
_button = _button.enter()
.insert('button', '.tag-reference-button')
.attr('class', 'preset-favorite-button ' + klass)
.attr('title', t('icons.favorite'))
.attr('tabindex', -1)
.call(svgIcon('#iD-icon-favorite'))
.merge(_button);
_button
.on('click', function () {
d3_event.stopPropagation();
d3_event.preventDefault();
context.favoritePreset(preset, geom);
update();
});
update();
};
function update() {
_button
.classed('active', context.isFavoritePreset(preset, geom));
}
context.on('favoritePreset.button-' + preset.id.replace(/[^a-zA-Z\d:]/g, '-') + '-' + geom, update);
return presetFavorite;
}
| Update favorite preset button state automatically | Update favorite preset button state automatically
| JavaScript | isc | AndreasHae/iD,openstreetmap/iD,morray/iD,morray/iD,kartta-labs/iD,digidem/iD,digidem/iD,kartta-labs/iD,AndreasHae/iD,kartta-labs/iD,openstreetmap/iD,openstreetmap/iD,AndreasHae/iD | ---
+++
@@ -31,24 +31,24 @@
.merge(_button);
_button
- .classed('active', function() {
- return context.isFavoritePreset(preset, geom);
- })
.on('click', function () {
d3_event.stopPropagation();
d3_event.preventDefault();
- //update state of favorite icon
- d3_select(this)
- .classed('active', function() {
- return !d3_select(this).classed('active');
- });
+ context.favoritePreset(preset, geom);
- context.favoritePreset(preset, geom);
-
+ update();
});
+ update();
};
+
+ function update() {
+ _button
+ .classed('active', context.isFavoritePreset(preset, geom));
+ }
+
+ context.on('favoritePreset.button-' + preset.id.replace(/[^a-zA-Z\d:]/g, '-') + '-' + geom, update);
return presetFavorite;
} |
4b7ad48004c7c7a26e79e031eb0032b208a24c51 | alexandria/static/js/services/domains.js | alexandria/static/js/services/domains.js | app.service('Domains', ['$rootScope', '$q', '$resource', '$log',
function($rootScope, $q, $resource, $log) {
var service = {};
return service;
}
]);
| app.service('Domains', ['$rootScope', '$q', '$resource', '$log',
function($rootScope, $q, $resource, $log) {
var service = {};
return service;
}
]);
app.factory('Domain', ['$resource', function($resource) {
return $resource('/domain/:id'{ id: '@_id' }, {
update: {
method: 'PUT'
}
});
}]);
| Add a new Domain factory that returns a $resource | Add a new Domain factory that returns a $resource
| JavaScript | isc | bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria | ---
+++
@@ -6,3 +6,10 @@
}
]);
+app.factory('Domain', ['$resource', function($resource) {
+ return $resource('/domain/:id'{ id: '@_id' }, {
+ update: {
+ method: 'PUT'
+ }
+ });
+}]); |
3a55a3d40d59b5200a64df0f89d5297cdbbf13a2 | scripts/scheduleRun.js | scripts/scheduleRun.js | const initialize = require('../src/util/initialization.js')
const connectDatabase = require('../src/util/connectDatabase.js')
const ScheduleRun = require('../src/structs/ScheduleRun.js')
const setConfig = require('../src/config.js').set
async function testScheduleRun (userConfig) {
let config = setConfig(userConfig)
config = setConfig({
...config,
log: {
...config.log,
level: 'debug'
}
})
const con = await connectDatabase(config.database.uri, config.database.connection)
try {
console.log('Connected to database')
await initialize.setupModels(con)
console.log('Models set up')
const schedule = {
name: 'default',
refreshRateMinutes: 999
}
console.log('Running...')
const scheduleRun = new ScheduleRun(schedule, 0, {}, {}, true)
scheduleRun.on('finish', () => {
con.close()
})
await scheduleRun.run(new Set())
return scheduleRun
} finally {
con.close()
}
}
module.exports = testScheduleRun
| const initialize = require('../src/util/initialization.js')
const connectDatabase = require('../src/util/connectDatabase.js')
const ScheduleRun = require('../src/structs/ScheduleRun.js')
const setConfig = require('../src/config.js').set
async function testScheduleRun (userConfig, callback) {
let config = setConfig(userConfig)
config = setConfig({
...config,
log: {
...config.log,
level: 'debug'
}
})
const con = await connectDatabase(config.database.uri, config.database.connection)
try {
console.log('Connected to database')
await initialize.setupModels(con)
console.log('Models set up')
const schedule = {
name: 'default',
refreshRateMinutes: 999
}
console.log('Running...')
const scheduleRun = new ScheduleRun(schedule, 0, {}, {}, true)
scheduleRun.on('finish', () => {
callback(undefined, scheduleRun)
con.close()
})
await scheduleRun.run(new Set())
} catch (err) {
callback(err)
} finally {
con.close()
}
}
module.exports = testScheduleRun
| Use callbacks for run schedule script (node exit before resolve) | Use callbacks for run schedule script (node exit before resolve)
| JavaScript | mit | synzen/Discord.RSS,synzen/Discord.RSS | ---
+++
@@ -3,7 +3,7 @@
const ScheduleRun = require('../src/structs/ScheduleRun.js')
const setConfig = require('../src/config.js').set
-async function testScheduleRun (userConfig) {
+async function testScheduleRun (userConfig, callback) {
let config = setConfig(userConfig)
config = setConfig({
...config,
@@ -24,10 +24,12 @@
console.log('Running...')
const scheduleRun = new ScheduleRun(schedule, 0, {}, {}, true)
scheduleRun.on('finish', () => {
+ callback(undefined, scheduleRun)
con.close()
})
await scheduleRun.run(new Set())
- return scheduleRun
+ } catch (err) {
+ callback(err)
} finally {
con.close()
} |
819eb850191f68dc8667925a667f6763b2292347 | app/routes/project/tasks/task.js | app/routes/project/tasks/task.js | import Ember from 'ember';
const {
Route,
inject: { service }
} = Ember;
export default Route.extend({
currentUser: service(),
model(params) {
let projectId = this.modelFor('project').id;
let { number } = params;
return this.store.queryRecord('task', { projectId, number });
},
setupController(controller, task) {
let user = this.get('currentUser.user');
let newComment = this.store.createRecord('comment', { user });
return controller.setProperties({ newComment, task });
},
actions: {
save(task) {
return task.save().catch((error) => {
let payloadContainsValidationErrors = error.errors.some((error) => error.status === 422);
if (!payloadContainsValidationErrors) {
this.controllerFor('project.tasks.task').set('error', error);
}
});
},
saveComment(comment) {
let task = this.get('controller.task');
comment.set('task', task);
comment.save().catch((error) => {
let payloadContainsValidationErrors = error.errors.some((error) => error.status === 422);
if (!payloadContainsValidationErrors) {
this.controllerFor('project.tasks.task').set('error', error);
}
});
}
}
});
| import Ember from 'ember';
const {
Route,
inject: { service }
} = Ember;
export default Route.extend({
currentUser: service(),
model(params) {
let projectId = this.modelFor('project').id;
let { number } = params;
return this.store.queryRecord('task', { projectId, number });
},
setupController(controller, task) {
let user = this.get('currentUser.user');
let newComment = this.store.createRecord('comment', { user });
controller.setProperties({ newComment, task });
},
actions: {
save(task) {
return task.save().catch((error) => {
let payloadContainsValidationErrors = error.errors.some((error) => error.status === 422);
if (!payloadContainsValidationErrors) {
this.controllerFor('project.tasks.task').set('error', error);
}
});
},
saveComment(comment) {
let task = this.get('controller.task');
comment.set('task', task);
comment.save().catch((error) => {
let payloadContainsValidationErrors = error.errors.some((error) => error.status === 422);
if (!payloadContainsValidationErrors) {
this.controllerFor('project.tasks.task').set('error', error);
}
});
}
}
});
| Simplify comments list behavior so API requests are consistent with other types of records. | Simplify comments list behavior so API requests are consistent with other types of records.
| JavaScript | mit | code-corps/code-corps-ember,code-corps/code-corps-ember,jderr-mx/code-corps-ember,jderr-mx/code-corps-ember | ---
+++
@@ -18,7 +18,7 @@
setupController(controller, task) {
let user = this.get('currentUser.user');
let newComment = this.store.createRecord('comment', { user });
- return controller.setProperties({ newComment, task });
+ controller.setProperties({ newComment, task });
},
actions: { |
16de6e07a35f53bb580d3d912802a22c4b63020b | problems/kata/001-todo-backend/001/app.js | problems/kata/001-todo-backend/001/app.js | var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var nano = require('nano')('http://localhost:5984');
var todo = nano.db.use('todo');
var app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/', function(req, res, next) {
console.log('get triggered');
todo.view('todos', 'all_todos', function(err, body) {
res.json(body.rows);
});
});
app.post('/', function(req, res, next) {
console.log('post triggered');
var task = {title: req.body.title};
todo.insert(task, function(err, body) {
if (err) {
console.log(err);
}
console.log(JSON.stringify(body));
task._id = body.id;
task._rev = body.rev;
res.json(task);
});
});
app.delete('/', function(req, res, next) {
console.log('delete triggered');
res.json([]);
});
app.listen(3000, function() {
console.log('Cors enabled server listening on port 3000');
});
| var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var nano = require('nano')('http://localhost:5984');
var todo = nano.db.use('todo');
var app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/', function(req, res, next) {
console.log('get triggered');
todo.view('todos', 'all_todos', function(err, body) {
res.json(body.rows);
});
});
app.post('/', function(req, res, next) {
console.log('post triggered');
var task = {title: req.body.title};
todo.insert(task, function(err, body) {
if (err) {
console.log(err);
}
console.log(JSON.stringify(body));
task._id = body.id;
task._rev = body.rev;
res.json(task);
});
});
app.delete('/', function(req, res, next) {
console.log('delete triggered');
todo.view('todos', 'all_todos', function(err, body) {
for (var row of body.rows) {
todo.destroy(row.value._id, row.value._rev);
}
});
res.json([]);
});
app.listen(3000, function() {
console.log('Cors enabled server listening on port 3000');
});
| Delete now deletes from database (4/16). | Delete now deletes from database (4/16).
| JavaScript | mit | PurityControl/uchi-komi-js | ---
+++
@@ -32,6 +32,11 @@
app.delete('/', function(req, res, next) {
console.log('delete triggered');
+ todo.view('todos', 'all_todos', function(err, body) {
+ for (var row of body.rows) {
+ todo.destroy(row.value._id, row.value._rev);
+ }
+ });
res.json([]);
});
|
f9c6f64e390cdc09ab8a3f9bb28923d6cd2b6af6 | src/@data/withHomeFeed/homeFeedQuery.js | src/@data/withHomeFeed/homeFeedQuery.js | import gql from 'graphql-tag';
const contentFragment = gql`
fragment ContentForFeed on Content {
entryId: id
title
channelName
status
meta {
siteId
date
channelId
}
parent {
entryId: id
content {
isLight
colors {
value
description
}
}
}
content {
isLiked
images(sizes: ["large"]) {
fileName
fileType
fileLabel
url
size
}
isLight
colors {
value
description
}
}
}
`;
export default gql`
query HomeFeed($filters: [String]!, $options: String!, $limit: Int!, $skip: Int!, $cache: Boolean!) {
feed: userFeed(filters: $filters, options: $options, limit: $limit, skip: $skip, cache: $cache) {
... on Content {
...ContentForFeed
parent {
...ContentForFeed
}
}
}
}
${contentFragment}
`;
| import gql from 'graphql-tag';
const contentFragment = gql`
fragment ContentForFeed on Content {
entryId: id
title
channelName
status
meta {
siteId
date
channelId
}
parent {
entryId: id
content {
isLight
colors {
value
description
}
}
}
content {
isLiked
images(sizes: ["large"]) {
fileName
fileType
fileLabel
url
size
}
isLight
colors {
value
description
}
}
}
`;
export default gql`
query HomeFeed($filters: [String]!, $limit: Int!, $skip: Int!, $cache: Boolean!) {
feed: userFeed(filters: $filters, limit: $limit, skip: $skip, cache: $cache) {
... on Content {
...ContentForFeed
parent {
...ContentForFeed
}
}
}
}
${contentFragment}
`;
| Remove $options from userFeed query | Remove $options from userFeed query
| JavaScript | mit | NewSpring/Apollos,NewSpring/Apollos,NewSpring/Apollos,NewSpring/Apollos,NewSpring/Apollos,NewSpring/Apollos | ---
+++
@@ -40,8 +40,8 @@
`;
export default gql`
- query HomeFeed($filters: [String]!, $options: String!, $limit: Int!, $skip: Int!, $cache: Boolean!) {
- feed: userFeed(filters: $filters, options: $options, limit: $limit, skip: $skip, cache: $cache) {
+ query HomeFeed($filters: [String]!, $limit: Int!, $skip: Int!, $cache: Boolean!) {
+ feed: userFeed(filters: $filters, limit: $limit, skip: $skip, cache: $cache) {
... on Content {
...ContentForFeed
parent { |
26bf7f873ecc19b7af2feb705ef63a00b9eed484 | src/content-script.js | src/content-script.js | /* global tabID */
"use strict";
const existingIframe = document.querySelector("iframe#dom-distiller-result-iframe");
if(existingIframe) {
existingIframe.remove();
} else {
const iframe = document.createElement("iframe");
iframe.src = chrome.runtime.getURL("dom-distiller/html/dom_distiller_viewer.html") + "#" + tabID;
const style = {
zIndex: 100000000,
position: "fixed",
left: 0,
right: 0,
top: 0,
bottom: 0,
margin: "auto",
width: "100vw",
height: "100vh",
background: "white",
border: "none"
};
Object.keys(style).forEach(property => {
iframe.style[property] = style[property];
});
document.documentElement.appendChild(iframe);
}
| /* global tabID */
"use strict";
var iframeID = "dom-distiller-result-iframe";
var existingIframe = document.getElementById(iframeID);
if(existingIframe) {
existingIframe.remove();
if("old" in window) {
document.title = window.old.title;
document.body.setAttribute("style", window.old.bodyStyle);
}
} else {
window.old = {
title: document.title,
bodyStyle: document.body.getAttribute("style")
};
document.body.setAttribute("style", "display: none !important");
const iframe = document.createElement("iframe");
iframe.id = iframeID;
iframe.src = chrome.runtime.getURL("dom-distiller/html/dom_distiller_viewer.html") + "#" + tabID;
const style = {
zIndex: 100000000,
position: "fixed",
left: 0,
right: 0,
top: 0,
bottom: 0,
margin: "auto",
width: "100vw",
height: "100vh",
background: "white",
border: "none"
};
Object.keys(style).forEach(property => {
iframe.style[property] = style[property];
});
document.documentElement.appendChild(iframe);
}
| Remove iframe and restore from hiding style | Remove iframe and restore from hiding style
| JavaScript | mit | metarmask/dom-distiller-reading-mode,metarmask/dom-distiller-reading-mode | ---
+++
@@ -1,10 +1,21 @@
/* global tabID */
"use strict";
-const existingIframe = document.querySelector("iframe#dom-distiller-result-iframe");
+var iframeID = "dom-distiller-result-iframe";
+var existingIframe = document.getElementById(iframeID);
if(existingIframe) {
existingIframe.remove();
+ if("old" in window) {
+ document.title = window.old.title;
+ document.body.setAttribute("style", window.old.bodyStyle);
+ }
} else {
+ window.old = {
+ title: document.title,
+ bodyStyle: document.body.getAttribute("style")
+ };
+ document.body.setAttribute("style", "display: none !important");
const iframe = document.createElement("iframe");
+ iframe.id = iframeID;
iframe.src = chrome.runtime.getURL("dom-distiller/html/dom_distiller_viewer.html") + "#" + tabID;
const style = {
zIndex: 100000000, |
f38a7692254a981ef1f761a41e76c88cd72355a7 | linkedin_client.js | linkedin_client.js | // Meteor.loginWithLinkedin = function (options, callback) {
// var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);
// LinkedIn.requestCredential(options, credentialRequestCompleteCallback);
// };
Meteor.loginWithLinkedIn = function(options, callback) {
// support a callback without options
if (! callback && typeof options === "function") {
callback = options;
options = null;
}
var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);
LinkedIn.requestCredential(options, credentialRequestCompleteCallback);
};
| // Meteor.loginWithLinkedin = function (options, callback) {
// var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);
// LinkedIn.requestCredential(options, credentialRequestCompleteCallback);
// };
Meteor.loginWithLinkedIn = function(options, callback) {
// support a callback without options
if (! callback && typeof options === "function") {
callback = options;
options = null;
}
var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);
LinkedIn.requestCredential(options, credentialRequestCompleteCallback);
};
// Make it work with 0.9.3
Meteor.loginWithLinkedin = Meteor.loginWithLinkedIn;
| Add new capitalized version of loging in with linked in | Add new capitalized version of loging in with linked in | JavaScript | mit | PoBuchi/meteor-accounts-linkedin,PauliBuccini/meteor-accounts-linkedin | ---
+++
@@ -13,3 +13,5 @@
LinkedIn.requestCredential(options, credentialRequestCompleteCallback);
};
+ // Make it work with 0.9.3
+ Meteor.loginWithLinkedin = Meteor.loginWithLinkedIn; |
8e7f0194c0e97bebf62ac9a0af8f2b6d497347a0 | server/publications.js | server/publications.js | Meteor.publish('journalEntries', function (limit, skip) {
var filter = {}
var options = {
fields: {
'title': 1,
'teaser': 1,
'published': 1,
'createdAt': 1
},
sort: [['createdAt', 'desc']]
}
if(limit) options.limit = limit
if(skip) options.skip = skip
if(!this.userId) filter.published = true
return JournalEntries.find(filter, options)
})
Meteor.publish('journalEntry', function (title) {
return JournalEntries.find({title: title})
})
Meteor.publish('allUsers', function () {
return Meteor.users.find()
})
| Meteor.publish('journalEntries', function (limit, skip) {
var filter = {}
var options = {
fields: {
'title': 1,
'teaser': 1,
'published': 1,
'createdAt': 1
},
sort: [['published', 'asc'], ['createdAt', 'desc']]
}
if(limit) options.limit = limit
if(skip) options.skip = skip
if(!this.userId) filter.published = true
return JournalEntries.find(filter, options)
})
Meteor.publish('journalEntry', function (title) {
return JournalEntries.find({title: title})
})
Meteor.publish('allUsers', function () {
return Meteor.users.find()
})
| Sort the journal entries, so that unpublished entries are on top | Sort the journal entries, so that unpublished entries are on top
| JavaScript | mit | Kriegslustig/kriegslustig.me,Kriegslustig/kriegslustig.me,Kriegslustig/kriegslustig.me | ---
+++
@@ -7,7 +7,7 @@
'published': 1,
'createdAt': 1
},
- sort: [['createdAt', 'desc']]
+ sort: [['published', 'asc'], ['createdAt', 'desc']]
}
if(limit) options.limit = limit
if(skip) options.skip = skip |
83a7b99a5023bb137e99d9a430754c7411c53c9a | web/main.js | web/main.js | CenterScout.config(function($routeProvider) {
$routeProvider.when('/', {
controller: 'HomeController',
templateUrl: 'views/home.html'
});
$routeProvider.when('/home', {
controller: 'HomeController',
templateUrl: 'views/home.html'
});
$routeProvider.when('/class', {
controller: 'ClassController',
templateUrl: 'views/class.html'
});
$routeProvider.when('/about', {
controller: 'AboutController',
templateUrl: 'views/about.html'
});
$routeProvider.when('/404', {
controller: 'ErrorController',
templateUrl: 'views/404.html'
});
$routeProvider.otherwise({
redirectTo: '/404'
});
});
if(isCordova())
$('body').addClass('cordova');
| CenterScout.config(function($routeProvider) {
$routeProvider.when('/', {
controller: 'HomeController',
templateUrl: 'views/home.html'
});
$routeProvider.when('/home', {
controller: 'HomeController',
templateUrl: 'views/home.html'
});
$routeProvider.when('/class', {
controller: 'ClassController',
templateUrl: 'views/class.html'
});
$routeProvider.when('/about', {
controller: 'AboutController',
templateUrl: 'views/about.html'
});
$routeProvider.when('/404', {
controller: 'ErrorController',
templateUrl: 'views/404.html'
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
if(isCordova())
$('body').addClass('cordova');
| Change 404 route to index | Change 404 route to index
| JavaScript | mit | LFHS/CenterScout | ---
+++
@@ -25,7 +25,7 @@
});
$routeProvider.otherwise({
- redirectTo: '/404'
+ redirectTo: '/'
});
});
|
1b962f46de8797d7cd6a7b4ca934f4adb07fc601 | test/buster.js | test/buster.js | var config = module.exports;
config["fruitmachine"] = {
rootPath: '../',
environment: "browser",
sources: [
'build/fruitmachine.js',
'node_modules/hogan.js/lib/template.js',
'node_modules/hogan.js/lib/compiler.js',
'test/helpers/*.js'
],
tests: [
'test/tests/*.js'
]
};
| var config = module.exports;
config["fruitmachine"] = {
rootPath: '../',
environment: "browser",
sources: [
'build/fruitmachine.min.js',
'node_modules/hogan.js/lib/template.js',
'node_modules/hogan.js/lib/compiler.js',
'test/helpers/*.js'
],
tests: [
'test/tests/*.js'
]
};
| Use min version in test to make sure no compilation errors exist | Use min version in test to make sure no compilation errors exist
| JavaScript | mit | quarterto/fruitmachine,ftlabs/fruitmachine,quarterto/fruitmachine | ---
+++
@@ -4,7 +4,7 @@
rootPath: '../',
environment: "browser",
sources: [
- 'build/fruitmachine.js',
+ 'build/fruitmachine.min.js',
'node_modules/hogan.js/lib/template.js',
'node_modules/hogan.js/lib/compiler.js',
'test/helpers/*.js' |
7d511728d0b9dfcf440dfede353e27a38d79ea56 | share/spice/brainy_quote/brainy_quote.js | share/spice/brainy_quote/brainy_quote.js | function ddg_spice_brainy_quote (api_result) {
if (api_result.error) return;
Spice.render({
data : api_result,
force_big_header : true,
header1 : api_result.header1,
source_name : api_result.source_name, // More at ...
source_url : api_result.source_url,
template_normal : 'brainy_quote',
});
}
| function ddg_spice_brainy_quote (api_result) {
if (api_result.error) return;
// Check if the result is a category search or not.
// We'll know that if the author is specified in the JSON response.
if(api_result.author) {
return;
}
Spice.render({
data : api_result,
force_big_header : true,
header1 : api_result.header1,
source_name : api_result.source_name, // More at ...
source_url : api_result.source_url,
template_normal : 'brainy_quote',
force_no_fold : true
});
}
| Check if the result is a category or not. | BrainyQuote: Check if the result is a category or not.
Queries such as "quote mining", "financial quotations", or "lame quotes" should not show up.
| JavaScript | apache-2.0 | levaly/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,P71/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,ppant/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,loganom/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,P71/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,levaly/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,soleo/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,ppant/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,sevki/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,mayo/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,deserted/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,soleo/zeroclickinfo-spice,levaly/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,levaly/zeroclickinfo-spice,stennie/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,mayo/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,P71/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,deserted/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,deserted/zeroclickinfo-spice,levaly/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,echosa/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,levaly/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,imwally/zeroclickinfo-spice,deserted/zeroclickinfo-spice,lernae/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,stennie/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,soleo/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,loganom/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,deserted/zeroclickinfo-spice,soleo/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,ppant/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,lerna/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,sevki/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,mayo/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,lerna/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,sevki/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,lerna/zeroclickinfo-spice,lerna/zeroclickinfo-spice,P71/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,imwally/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,echosa/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,soleo/zeroclickinfo-spice,imwally/zeroclickinfo-spice,echosa/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,lernae/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,sevki/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,lernae/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,lernae/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,soleo/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,stennie/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,imwally/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,loganom/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,lernae/zeroclickinfo-spice,ppant/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,loganom/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,lerna/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,deserted/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,mayo/zeroclickinfo-spice,imwally/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,stennie/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,echosa/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice | ---
+++
@@ -1,5 +1,11 @@
function ddg_spice_brainy_quote (api_result) {
if (api_result.error) return;
+
+ // Check if the result is a category search or not.
+ // We'll know that if the author is specified in the JSON response.
+ if(api_result.author) {
+ return;
+ }
Spice.render({
data : api_result,
@@ -8,5 +14,6 @@
source_name : api_result.source_name, // More at ...
source_url : api_result.source_url,
template_normal : 'brainy_quote',
+ force_no_fold : true
});
} |
72d5d878435d13c67a8ef6c4148a9e28e13abbfa | app/assets/javascripts/ministerSelect.js | app/assets/javascripts/ministerSelect.js | //= require jquery.autocomplete
(function ($) {
$.fn.ministerSelect = function (options) {
var settings = $.extend({
inputClass: 'minister-select-input'
}, options);
return this.each(function () {
var $select = $(this),
$input = $('<input type="text" value="" class="' + settings['inputClass'] + '" />'),
lookup = [];
// compile the list of auto suggestions from the select and pre-fill the input field
$select.find('option').each(function () {
var $option = $(this);
lookup.push($option.text());
if ($option.is(':selected')) {
$input.val($option.text());
}
});
// construct the auto complete and only trigger change method on the input when user selects an option
$input.autocomplete({
lookup: lookup,
onSelect: function () {
$(this).trigger('change');
}
});
// when the input changes, the relevant select option has to be chosen
$input.on('change', function () {
var text = $(this).val(),
options = $select.find('option').filter(function () {
return $(this).text().toLowerCase().indexOf(text.toLowerCase()) !== -1;
});
if (options.length == 1) {
var $option = $(options[0]);
$select.val($option.val());
$input.val($option.text());
} else {
$select.val('');
$input.val('');
}
});
$select.hide();
$select.before($input);
});
}
}(jQuery)); | //= require jquery.autocomplete
(function ($) {
$.fn.ministerSelect = function (options) {
var settings = $.extend({
inputClass: 'minister-select-input'
}, options);
return this.each(function () {
var $select = $(this),
$input = $('<input type="text" value="" class="' + settings['inputClass'] + '" />'),
lookup = [];
// compile the list of auto suggestions from the select and pre-fill the input field
$select.find('option').each(function () {
var $option = $(this);
lookup.push($option.text());
if ($option.is(':selected')) {
$input.val($option.text());
}
});
// construct the auto complete and only trigger change method on the input when user selects an option
$input.autocomplete({
lookup: lookup,
onSelect: function () {
$(this).trigger('change');
}
});
// when the input changes, the relevant select option has to be chosen
$input.on('change', function () {
var textToCompare = $(this).val().toLowerCase(),
matching_options = $.grep(lookup, function(suggestion) {
return suggestion.toLowerCase().indexOf(textToCompare) !== -1
});
if (matching_options.length == 1) {
var $option = $select.find('option:contains("' + matching_options[0] + '")').first();
$select.val($option.val());
$input.val($option.text());
} else {
$select.val('');
$input.val('');
}
});
$select.hide();
$select.before($input);
});
}
}(jQuery)); | Use the autocomplete lookup instead of traversing DOM elements | Use the autocomplete lookup instead of traversing DOM elements
| JavaScript | mit | ministryofjustice/parliamentary-questions,ministryofjustice/parliamentary-questions,ministryofjustice/parliamentary-questions,ministryofjustice/parliamentary-questions,ministryofjustice/parliamentary-questions | ---
+++
@@ -32,13 +32,13 @@
// when the input changes, the relevant select option has to be chosen
$input.on('change', function () {
- var text = $(this).val(),
- options = $select.find('option').filter(function () {
- return $(this).text().toLowerCase().indexOf(text.toLowerCase()) !== -1;
+ var textToCompare = $(this).val().toLowerCase(),
+ matching_options = $.grep(lookup, function(suggestion) {
+ return suggestion.toLowerCase().indexOf(textToCompare) !== -1
});
- if (options.length == 1) {
- var $option = $(options[0]);
+ if (matching_options.length == 1) {
+ var $option = $select.find('option:contains("' + matching_options[0] + '")').first();
$select.val($option.val());
$input.val($option.text()); |
9a340fa1ae05181b2dc2803cb485bbdcdf43ea0a | src/components/explorer/results/QueryResultsSelector.js | src/components/explorer/results/QueryResultsSelector.js | import PropTypes from 'prop-types';
import React from 'react';
class QueryResultsSelector extends React.Component {
state = {
selectedQueryIndex: 0,
}
render() {
const { options, onQuerySelected } = this.props;
if (options.length === 1) {
// if only one query don't show option to switch between them
return null;
}
return (
<ul className="query-results-selector">
{options.map(q =>
<li
role="button"
tabIndex={0}
onKeyPress={evt => evt.preventDefault()}
key={q.index}
style={{ color: q.color }}
className={`${this.state.selectedQueryIndex === q.index ? 'selected' : ''}`}
onClick={() => {
this.setState({ selectedQueryIndex: q.index });
onQuerySelected(q.index);
}}
>
{q.label}
</li>
)}
</ul>
);
}
}
QueryResultsSelector.propTypes = {
// from parent
options: PropTypes.array,
onQuerySelected: PropTypes.func,
};
export default QueryResultsSelector;
| import PropTypes from 'prop-types';
import React from 'react';
import { trimToMaxLength } from '../../../lib/stringUtil';
class QueryResultsSelector extends React.Component {
state = {
selectedQueryIndex: 0,
}
render() {
const { options, onQuerySelected } = this.props;
if (options.length === 1) {
// if only one query don't show option to switch between them
return null;
}
return (
<ul className="query-results-selector">
{options.map(q =>
<li
role="button"
tabIndex={0}
onKeyPress={evt => evt.preventDefault()}
key={q.index}
style={{ color: q.color }}
className={`${this.state.selectedQueryIndex === q.index ? 'selected' : ''}`}
onClick={() => {
this.setState({ selectedQueryIndex: q.index });
onQuerySelected(q.index);
}}
>
{trimToMaxLength(q.label, 20)}
</li>
)}
</ul>
);
}
}
QueryResultsSelector.propTypes = {
// from parent
options: PropTypes.array,
onQuerySelected: PropTypes.func,
};
export default QueryResultsSelector;
| Trim tab size for readability | Trim tab size for readability
| JavaScript | apache-2.0 | mitmedialab/MediaCloud-Web-Tools,mitmedialab/MediaCloud-Web-Tools,mitmedialab/MediaCloud-Web-Tools,mitmedialab/MediaCloud-Web-Tools | ---
+++
@@ -1,5 +1,6 @@
import PropTypes from 'prop-types';
import React from 'react';
+import { trimToMaxLength } from '../../../lib/stringUtil';
class QueryResultsSelector extends React.Component {
state = {
@@ -26,7 +27,7 @@
onQuerySelected(q.index);
}}
>
- {q.label}
+ {trimToMaxLength(q.label, 20)}
</li>
)}
</ul> |
8e963c3216b074b979e7c4cf0c8f7a7bdc730590 | test/common.js | test/common.js | var warned = false
function testCommon (options) {
var factory = options.factory
var test = options.test
var clear = !!options.clear
if (typeof factory !== 'function') {
throw new TypeError('factory must be a function')
}
if (typeof test !== 'function') {
throw new TypeError('test must be a function')
}
if (!clear && !warned) {
warned = true
warn(
'A next major release of abstract-leveldown will make support of ' +
'clear() mandatory. Prepare by enabling the tests and implementing a ' +
'custom _clear() if necessary. See the README for details.'
)
}
return {
test: test,
factory: factory,
setUp: options.setUp || noopTest(),
tearDown: options.tearDown || noopTest(),
bufferKeys: options.bufferKeys !== false,
createIfMissing: options.createIfMissing !== false,
errorIfExists: options.errorIfExists !== false,
snapshots: options.snapshots !== false,
seek: options.seek !== false,
clear: clear
}
}
function warn (msg) {
if (typeof process !== 'undefined' && process && process.emitWarning) {
process.emitWarning(msg)
} else if (typeof console !== 'undefined' && console && console.warn) {
console.warn('Warning: ' + msg)
}
}
function noopTest () {
return function (t) {
t.end()
}
}
module.exports = testCommon
| function testCommon (options) {
var factory = options.factory
var test = options.test
if (typeof factory !== 'function') {
throw new TypeError('factory must be a function')
}
if (typeof test !== 'function') {
throw new TypeError('test must be a function')
}
return {
test: test,
factory: factory,
setUp: options.setUp || noopTest(),
tearDown: options.tearDown || noopTest(),
bufferKeys: options.bufferKeys !== false,
createIfMissing: options.createIfMissing !== false,
errorIfExists: options.errorIfExists !== false,
snapshots: options.snapshots !== false,
seek: options.seek !== false,
clear: !!options.clear
}
}
function noopTest () {
return function (t) {
t.end()
}
}
module.exports = testCommon
| Remove process.emitWarning because it breaks AppVeyor builds | Remove process.emitWarning because it breaks AppVeyor builds
See Level/leveldown#660
| JavaScript | mit | Level/abstract-leveldown | ---
+++
@@ -1,9 +1,6 @@
-var warned = false
-
function testCommon (options) {
var factory = options.factory
var test = options.test
- var clear = !!options.clear
if (typeof factory !== 'function') {
throw new TypeError('factory must be a function')
@@ -11,15 +8,6 @@
if (typeof test !== 'function') {
throw new TypeError('test must be a function')
- }
-
- if (!clear && !warned) {
- warned = true
- warn(
- 'A next major release of abstract-leveldown will make support of ' +
- 'clear() mandatory. Prepare by enabling the tests and implementing a ' +
- 'custom _clear() if necessary. See the README for details.'
- )
}
return {
@@ -32,15 +20,7 @@
errorIfExists: options.errorIfExists !== false,
snapshots: options.snapshots !== false,
seek: options.seek !== false,
- clear: clear
- }
-}
-
-function warn (msg) {
- if (typeof process !== 'undefined' && process && process.emitWarning) {
- process.emitWarning(msg)
- } else if (typeof console !== 'undefined' && console && console.warn) {
- console.warn('Warning: ' + msg)
+ clear: !!options.clear
}
}
|
994bff56468a68e780be77c262fbc2271232db45 | lit-config.js | lit-config.js | module.exports = {
"extends": "./index.js",
"parser": "babel-eslint",
"env": {
"browser": true
},
"plugins": [
"lit", "html"
],
"globals": {
"D2L": false,
"Promise": false
},
"rules": {
"strict": [2, "never"],
"lit/no-duplicate-template-bindings": 2,
"lit/no-legacy-template-syntax": 2,
"lit/no-template-bind": 2,
"lit/no-template-map": 0,
"lit/no-useless-template-literals": 2,
"lit/attribute-value-entities": 2,
"lit/binding-positions": 2,
"lit/no-property-change-update": 2,
"lit/no-invalid-html": 2,
"lit/no-value-attribute": 2
}
};
| module.exports = {
"extends": "./index.js",
"parser": "babel-eslint",
"env": {
"browser": true
},
"plugins": [
"lit", "html"
],
"globals": {
"D2L": false,
"Promise": false
},
"rules": {
"no-var": 2,
"prefer-const": 2,
"strict": [2, "never"],
"lit/no-duplicate-template-bindings": 2,
"lit/no-legacy-template-syntax": 2,
"lit/no-template-bind": 2,
"lit/no-template-map": 0,
"lit/no-useless-template-literals": 2,
"lit/attribute-value-entities": 2,
"lit/binding-positions": 2,
"lit/no-property-change-update": 2,
"lit/no-invalid-html": 2,
"lit/no-value-attribute": 2
}
};
| Add const and var rules to lit config | Add const and var rules to lit config
| JavaScript | apache-2.0 | Brightspace/eslint-config-brightspace | ---
+++
@@ -12,6 +12,8 @@
"Promise": false
},
"rules": {
+ "no-var": 2,
+ "prefer-const": 2,
"strict": [2, "never"],
"lit/no-duplicate-template-bindings": 2,
"lit/no-legacy-template-syntax": 2, |
6af4c07efaeeeb1efd3a78b0b6d8de5327e41276 | app/webroot/js/sentences.show_another.js | app/webroot/js/sentences.show_another.js | /**
* Tatoeba Project, free collaborative creation of multilingual corpuses project
* Copyright (C) 2009 HO Ngoc Phuong Trang <tranglich@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
$(document).ready(function(){
var lang = $("#randomLangChoice").val();
if (lang == null) {
lang = '';
}
$("#showRandom").click(function(){
lang = $("#randomLangChoice").val();
loadRandom(lang);
})
});
function loadRandom(lang){
$("#random-progress").show();
$("#random_sentence_display").hide();
$.ajax({
type: "GET",
url: "/sentences/random/" + lang,
success: function (data){
$("#random_sentence_display").html(data);
$("#random-progress").hide();
$("#random_sentence_display").show();
}
});
}
| /**
* Tatoeba Project, free collaborative creation of multilingual corpuses project
* Copyright (C) 2009 HO Ngoc Phuong Trang <tranglich@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
$(document).ready(function(){
var lang = $("#randomLangChoice").val();
if (lang == null) {
lang = '';
}
$("#showRandom").click(function(){
lang = $("#randomLangChoice").val();
loadRandom(lang);
})
});
function loadRandom(lang){
$("#random-progress").show();
$("#random_sentence_display").hide();
$.ajax({
type: "GET",
url: "/sentences/random/" + lang,
success: function (data){
$("#random_sentence_display").watch("html", data);
$("#random-progress").hide();
$("#random_sentence_display").show();
}
});
}
| Fix sentence buttons on reloaded random sentence | Fix sentence buttons on reloaded random sentence
Closes #1658.
| JavaScript | agpl-3.0 | Tatoeba/tatoeba2,Tatoeba/tatoeba2,Tatoeba/tatoeba2,Tatoeba/tatoeba2,Tatoeba/tatoeba2 | ---
+++
@@ -37,7 +37,7 @@
type: "GET",
url: "/sentences/random/" + lang,
success: function (data){
- $("#random_sentence_display").html(data);
+ $("#random_sentence_display").watch("html", data);
$("#random-progress").hide();
$("#random_sentence_display").show();
} |
fa72546b7d7b509b83c615ff23b5c73b55dfc450 | catwatch/assets/scripts/entry.js | catwatch/assets/scripts/entry.js | var moment = require('moment');
var coupon = require('./coupon');
var stripe = require('./stripe');
var BulkDelete = require('./bulk-delete');
var faye = require('./faye');
$(document).ready(function () {
coupon();
stripe();
var bulk_delete = new BulkDelete();
bulk_delete.listenForEvents();
if (window.location.pathname === '/live_stream') {
faye();
}
$('.from-now').each(function (i, e) {
(function updateTime() {
var time = moment($(e).data('datetime'));
$(e).text(time.fromNow());
$(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a'));
setTimeout(updateTime, 1000);
})();
});
$('.short-date').each(function (i, e) {
var time = moment($(e).data('datetime'));
$(e).text(time.format('MMM Do YYYY'));
$(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a'));
});
});
| var moment = require('moment');
var coupon = require('./coupon');
var stripe = require('./stripe');
var BulkDelete = require('./bulk-delete');
var faye = require('./faye');
$(document).ready(function () {
coupon();
stripe();
var bulk_delete = new BulkDelete();
bulk_delete.listenForEvents();
if (window.location.pathname === '/live_stream') {
faye();
}
$('.from-now').each(function (i, e) {
(function updateTime() {
var time = moment($(e).data('datetime'));
$(e).text(time.fromNow());
$(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a Z'));
setTimeout(updateTime, 1000);
})();
});
$('.short-date').each(function (i, e) {
var time = moment($(e).data('datetime'));
$(e).text(time.format('MMM Do YYYY'));
$(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a Z'));
});
});
| Add timezone output to the momentjs dates | Add timezone output to the momentjs dates
| JavaScript | mit | nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask | ---
+++
@@ -20,7 +20,7 @@
(function updateTime() {
var time = moment($(e).data('datetime'));
$(e).text(time.fromNow());
- $(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a'));
+ $(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a Z'));
setTimeout(updateTime, 1000);
})();
});
@@ -28,6 +28,6 @@
$('.short-date').each(function (i, e) {
var time = moment($(e).data('datetime'));
$(e).text(time.format('MMM Do YYYY'));
- $(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a'));
+ $(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a Z'));
});
}); |
7b884fab3cc68b07f9e53edb69d014b1aeca46c2 | .eslintrc.js | .eslintrc.js | var path = require('path');
module.exports = {
env: {
es6: true,
browser: true,
node: true,
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 7,
ecmaFeatures: {
impliedStrict: true,
experimentalObjectRestSpread: true,
},
},
globals: {
__version: true,
__coreAPISpec: true,
__filename: true,
__publicPath: true,
},
extends: [
'eslint:recommended',
'prettier',
'plugin:vue/recommended',
'plugin:import/errors',
'plugin:import/warnings',
],
plugins: ['import', 'vue'],
settings: {
'import/resolver': {
[path.resolve('./frontend_build/src/alias_import_resolver.js')]: {
extensions: ['.js', '.vue'],
},
},
},
rules: {
'vue/v-bind-style': 2,
'vue/v-on-style': 2,
'vue/html-quotes': [2, 'double'],
'vue/order-in-components': 2,
'comma-style': 2,
},
};
| var path = require('path');
module.exports = {
env: {
es6: true,
browser: true,
node: true,
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 7,
ecmaFeatures: {
impliedStrict: true,
experimentalObjectRestSpread: true,
},
},
globals: {
__version: true,
__coreAPISpec: true,
__filename: true,
__publicPath: true,
},
extends: [
'eslint:recommended',
'prettier',
'plugin:vue/recommended',
'plugin:import/errors',
'plugin:import/warnings',
],
plugins: ['import', 'vue'],
settings: {
'import/resolver': {
[path.resolve(
path.join(path.dirname(__filename), './frontend_build/src/alias_import_resolver.js')
)]: {
extensions: ['.js', '.vue'],
},
},
},
rules: {
'vue/v-bind-style': 2,
'vue/v-on-style': 2,
'vue/html-quotes': [2, 'double'],
'vue/order-in-components': 2,
'comma-style': 2,
},
};
| Fix eslint import resolver path. | Fix eslint import resolver path.
| JavaScript | mit | mrpau/kolibri,jonboiser/kolibri,learningequality/kolibri,lyw07/kolibri,DXCanas/kolibri,lyw07/kolibri,mrpau/kolibri,benjaoming/kolibri,learningequality/kolibri,DXCanas/kolibri,christianmemije/kolibri,indirectlylit/kolibri,benjaoming/kolibri,christianmemije/kolibri,mrpau/kolibri,jonboiser/kolibri,mrpau/kolibri,indirectlylit/kolibri,DXCanas/kolibri,benjaoming/kolibri,learningequality/kolibri,indirectlylit/kolibri,learningequality/kolibri,benjaoming/kolibri,lyw07/kolibri,lyw07/kolibri,DXCanas/kolibri,jonboiser/kolibri,christianmemije/kolibri,christianmemije/kolibri,indirectlylit/kolibri,jonboiser/kolibri | ---
+++
@@ -30,7 +30,9 @@
plugins: ['import', 'vue'],
settings: {
'import/resolver': {
- [path.resolve('./frontend_build/src/alias_import_resolver.js')]: {
+ [path.resolve(
+ path.join(path.dirname(__filename), './frontend_build/src/alias_import_resolver.js')
+ )]: {
extensions: ['.js', '.vue'],
},
}, |
77bba0f59fc33dd9de6875e63a7261bc156d5de5 | app/scripts/components/auth/auth-init.js | app/scripts/components/auth/auth-init.js | import template from './auth-init.html';
export const authInit = {
template,
controller: class AuthInitController {
constructor(usersService, $state, ENV, ncUtilsFlash) {
// @ngInject
this.usersService = usersService;
this.$state = $state;
this.ncUtilsFlash = ncUtilsFlash,
this.user = {};
this.pageTitle = ENV.shortPageTitle;
}
$onInit() {
this.loading = true;
this.usersService.getCurrentUser().then(user => {
this.user = user;
}).finally(() => {
this.loading = false;
});
}
save({ user }) {
return this.usersService.update(user).then(response => {
this.usersService.currentUser = response.data;
this.$state.go('profile.details');
}).catch(response => {
this.ncUtilsFlash.error('Unable to save user');
if (response.status === 400) {
this.errors = response.data;
}
});
}
}
};
| import template from './auth-init.html';
export const authInit = {
template,
controller: class AuthInitController {
constructor(usersService, $state, ENV, ncUtilsFlash) {
// @ngInject
this.usersService = usersService;
this.$state = $state;
this.ncUtilsFlash = ncUtilsFlash,
this.user = {};
this.pageTitle = ENV.shortPageTitle;
}
$onInit() {
this.loading = true;
this.usersService.getCurrentUser().then(user => {
this.user = angular.copy(user);
}).finally(() => {
this.loading = false;
});
}
save({ user }) {
return this.usersService.update(user).then(response => {
this.usersService.currentUser = response.data;
this.$state.go('profile.details');
}).catch(response => {
this.ncUtilsFlash.error('Unable to save user');
if (response.status === 400) {
this.errors = response.data;
}
});
}
}
};
| Copy user before update (WAl-383) | Copy user before update (WAl-383)
| JavaScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -15,7 +15,7 @@
$onInit() {
this.loading = true;
this.usersService.getCurrentUser().then(user => {
- this.user = user;
+ this.user = angular.copy(user);
}).finally(() => {
this.loading = false;
}); |
e3df78442ee404e23a4683d4973bef29770f5609 | .eslintrc.js | .eslintrc.js | module.exports = {
extends: "eslint:recommended",
rules: {
"no-console": 0,
quotes: ["error", "backtick"],
semi: ["error", "never"]
},
env: {
node: true,
es6: true
},
parserOptions: {
ecmaFeatures: {
modules: "true"
},
sourceType: "module"
}
}
| module.exports = {
extends: "eslint:recommended",
rules: {
"no-console": 0,
"object-curly-spacing": ["error", "always"],
"comma-dangle": [
"error",
{
arrays: "always-multiline",
objects: "always-multiline",
imports: "always-multiline",
exports: "always-multiline",
functions: "ignore",
},
],
quotes: ["error", "backtick"],
semi: ["error", "never"],
},
env: {
node: true,
},
parserOptions: {
ecmaVersion: 2017,
sourceType: "module",
},
}
| Configure ESLint to support ES2017 | Configure ESLint to support ES2017
| JavaScript | mit | mattdean1/contentful-text-search | ---
+++
@@ -2,17 +2,25 @@
extends: "eslint:recommended",
rules: {
"no-console": 0,
+ "object-curly-spacing": ["error", "always"],
+ "comma-dangle": [
+ "error",
+ {
+ arrays: "always-multiline",
+ objects: "always-multiline",
+ imports: "always-multiline",
+ exports: "always-multiline",
+ functions: "ignore",
+ },
+ ],
quotes: ["error", "backtick"],
- semi: ["error", "never"]
+ semi: ["error", "never"],
},
env: {
node: true,
- es6: true
},
parserOptions: {
- ecmaFeatures: {
- modules: "true"
- },
- sourceType: "module"
- }
+ ecmaVersion: 2017,
+ sourceType: "module",
+ },
} |
98ad4755ebcc123aa4a18441d8252dccef3d08c1 | .eslintrc.js | .eslintrc.js | module.exports = {
"env": {
"es6": true,
"node": true
},
"plugins": ["node"],
"extends": ["eslint:recommended", "plugin:node/recommended"],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-unused-vars": [
"error", {
"varsIgnorePattern": "^_",
"args": "none"
}
],
"node/exports-style": [
"error",
"module.exports"
]
}
};
| module.exports = {
"env": {
"es6": true,
"node": true
},
"plugins": ["node"],
"extends": ["eslint:recommended", "plugin:node/recommended"],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error",
2, {
"MemberExpression": 2
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-unused-vars": [
"error", {
"varsIgnorePattern": "^_",
"args": "none"
}
],
"node/exports-style": [
"error",
"module.exports"
]
}
};
| Add eslint rule for js2-mode | Add eslint rule for js2-mode
| JavaScript | apache-2.0 | fluent/fluent-logger-node | ---
+++
@@ -11,7 +11,9 @@
"rules": {
"indent": [
"error",
- 2
+ 2, {
+ "MemberExpression": 2
+ }
],
"linebreak-style": [
"error", |
9774591c0e0b1bd216332dea056ad6ca1c1d782b | src/converter/r2t/WrapAbstractContent.js | src/converter/r2t/WrapAbstractContent.js | import { unwrapChildren } from '../util/domHelpers'
const ABSTRACT_META = ['object-id','sec-meta', 'label', 'title'].reduce((m, n) => { m[n] = true; return m}, {})
const ABSTRACT_BACK = ['notes','fn-group','glossary','ref-list'].reduce((m, n) => { m[n] = true; return m}, {})
export default class WrapAbstractContent {
import(dom) {
let abstracts = dom.findAll('abstract').concat(dom.findAll('trans-abstract'))
abstracts.forEach( (abstract) => {
// restructure child nodes
const meta = []
const content = []
const back = []
abstract.children.forEach((child) => {
const tagName = child.tagName
if (ABSTRACT_META[tagName]) {
meta.push(child)
} else if (ABSTRACT_BACK[tagName]) {
back.push(child)
} else {
content.push(child)
}
})
abstract.empty()
abstract.append(meta)
abstract.append(dom.createElement('abstract-content').append(content))
abstract.append(back)
})
}
export(dom) {
let abstractContentEls = dom.findAll('abstract-content')
abstractContentEls.forEach((abstractContent) => {
// pull children of abstract-content up one layer
unwrapChildren(abstractContent)
})
}
} | import { unwrapChildren } from '../util/domHelpers'
const ABSTRACT_META = ['object-id','sec-meta', 'label', 'title'].reduce((m, n) => { m[n] = true; return m}, {})
const ABSTRACT_BACK = ['notes','fn-group','glossary','ref-list'].reduce((m, n) => { m[n] = true; return m}, {})
export default class WrapAbstractContent {
import(dom) {
let abstracts = dom.findAll('abstract').concat(dom.findAll('trans-abstract'))
abstracts.forEach( (abstract) => {
// restructure child nodes
const meta = []
const content = []
const back = []
abstract.children.forEach((child) => {
const tagName = child.tagName
if (ABSTRACT_META[tagName]) {
meta.push(child)
} else if (ABSTRACT_BACK[tagName]) {
back.push(child)
} else {
content.push(child)
}
})
abstract.empty()
abstract.append(meta)
// Make sure that there is at least one paragraph inside the abstract
if (content.length === 0) {
content.push(dom.createElement('p'))
}
abstract.append(dom.createElement('abstract-content').append(content))
abstract.append(back)
})
}
export(dom) {
let abstractContentEls = dom.findAll('abstract-content')
abstractContentEls.forEach((abstractContent) => {
// pull children of abstract-content up one layer
unwrapChildren(abstractContent)
})
}
}
| Make sure that there is at least one p inside abstract. | Make sure that there is at least one p inside abstract.
| JavaScript | mit | substance/texture,substance/texture | ---
+++
@@ -24,6 +24,12 @@
})
abstract.empty()
abstract.append(meta)
+
+ // Make sure that there is at least one paragraph inside the abstract
+ if (content.length === 0) {
+ content.push(dom.createElement('p'))
+ }
+
abstract.append(dom.createElement('abstract-content').append(content))
abstract.append(back)
}) |
8b2611a84cb507c68b89f36cf0f241a778b73f73 | tilehandler.js | tilehandler.js | var app = require('server'),
tl = require('tl');
app.get('/:scheme/:mapfile_64/:z/:x/:y.*', function(req, res) {
/*
* scheme: (xyz|tms|tile (tms))
*
* format:
* - Tile: (png|jpg)
* - Data Tile: (geojson)
* - Grid Tile: (*.grid.json)
*/
try {
var tile = new tl.Tile(
req.params.scheme,
req.params.mapfile_64,
req.params.z,
req.params.x,
req.params.y,
req.params[0]);
} catch (err) {
res.send('Tile invalid: ' + err.message);
}
tile.render(function(err, data) {
if (!err) {
// Using apply here allows the tile rendering
// function to send custom heades without access
// to the request object.
data[1] = _.extend(app.set('settings')('header_defaults'), data[1]);
res.send.apply(res, data);
// res.send.apply(res, ['hello', { 'Content-Type': 'image/png' }]);
} else {
res.send('Tile rendering error: ' + err);
}
});
});
| var app = require('server'),
_ = require('underscore')._,
tl = require('tl');
app.get('/:scheme/:mapfile_64/:z/:x/:y.*', function(req, res) {
/*
* scheme: (xyz|tms|tile (tms))
*
* format:
* - Tile: (png|jpg)
* - Data Tile: (geojson)
* - Grid Tile: (*.grid.json)
*/
try {
var tile = new tl.Tile(
req.params.scheme,
req.params.mapfile_64,
req.params.z,
req.params.x,
req.params.y,
req.params[0]);
} catch (err) {
res.send('Tile invalid: ' + err.message);
}
tile.render(function(err, data) {
if (!err) {
// Using apply here allows the tile rendering
// function to send custom heades without access
// to the request object.
data[1] = _.extend(app.set('settings')('header_defaults'), data[1]);
res.send.apply(res, data);
// res.send.apply(res, ['hello', { 'Content-Type': 'image/png' }]);
} else {
res.send('Tile rendering error: ' + err);
}
});
});
| Add missing require for underscore. | Add missing require for underscore.
| JavaScript | bsd-3-clause | tomhughes/tilelive.js,mapbox/tilelive,paulovieira/tilelive,mapbox/tilelive.js,kyroskoh/tilelive,topwood/tilelive,gravitystorm/tilelive.js,nyurik/tilelive.js,Norkart/tilelive.js | ---
+++
@@ -1,4 +1,5 @@
var app = require('server'),
+ _ = require('underscore')._,
tl = require('tl');
app.get('/:scheme/:mapfile_64/:z/:x/:y.*', function(req, res) { |
8e2b2c414dd01aaa69a3cb1de4d7e5f838759c90 | src/database/DataTypes/TemperatureLog.js | src/database/DataTypes/TemperatureLog.js | /**
* Sustainable Solutions (NZ) Ltd. 2020
* mSupply Mobile
*/
import Realm from 'realm';
export class TemperatureLog extends Realm.Object {}
TemperatureLog.schema = {
name: 'TemperatureLog',
primaryKey: 'id',
properties: {
id: 'string',
temperature: 'double',
timestamp: 'date',
location: 'Location',
breach: 'BreachLog',
},
};
export default TemperatureLog;
| /**
* Sustainable Solutions (NZ) Ltd. 2020
* mSupply Mobile
*/
import Realm from 'realm';
export class TemperatureLog extends Realm.Object {}
TemperatureLog.schema = {
name: 'TemperatureLog',
primaryKey: 'id',
properties: {
id: 'string',
temperature: 'double',
timestamp: 'date',
location: 'Location',
breach: { type: 'BreachLog', optional: true },
},
};
export default TemperatureLog;
| Add update optional breach field | Add update optional breach field
| JavaScript | mit | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile | ---
+++
@@ -15,7 +15,7 @@
temperature: 'double',
timestamp: 'date',
location: 'Location',
- breach: 'BreachLog',
+ breach: { type: 'BreachLog', optional: true },
},
};
|
5e3f0f88317e8c4dea16e2b60fecb911d73ce261 | code/js/controllers/SpotifyController.js | code/js/controllers/SpotifyController.js | ;(function() {
"use strict";
var BaseController = require("BaseController");
new BaseController({
siteName: "Spotify",
playPause: "[title='Pause'],[title='Play']",
playNext: "[title='Next']",
playPrev: "[title='Previous']",
playState: "[title='Pause']",
song: ".now-playing-bar div div [href*='/album/']",
artist: ".now-playing-bar div div [href*='/artist/']"
});
})();
| ;(function() {
"use strict";
var BaseController = require("BaseController"),
_ = require("lodash");
var multiSelectors = {
playPause: ["#play-pause", "#play", "[title='Pause'],[title='Play']"],
playNext: ["#next", "#next", "[title='Next']"],
playPrev: ["#previous", "#previous", "[title='Previous']"],
playState: ["#play-pause.playing", "#play.playing", "[title='Pause']"],
iframe: ["#app-player", "#main", null],
like: [".thumb.up", ".thumb.up", null],
dislike: [".thumb.down", ".thumb.down", null],
song: ["#track-name", ".caption .track", ".now-playing-bar div div [href*='/album/']"],
artist: ["#track-artist", ".caption .artist", ".now-playing-bar div div [href*='/artist/']"]
};
var controller = new BaseController({
siteName: "Spotify"
});
controller.checkPlayer = function() {
var that = this;
var selectorIndex;
if (window.location.hostname === "open.spotify.com") {
selectorIndex = 2;
} else {
if (document.querySelector(multiSelectors.iframe[0])) { selectorIndex = 0; }
if (document.querySelector(multiSelectors.iframe[1])) { selectorIndex = 1; }
}
_.each(multiSelectors, function(value, key) {
that.selectors[key] = value[selectorIndex];
});
};
})();
| Fix spotify for older player versions. | Fix spotify for older player versions.
| JavaScript | mit | nemchik/streamkeys,nemchik/streamkeys,nemchik/streamkeys,ovcharik/streamkeys,ovcharik/streamkeys,alexesprit/streamkeys,berrberr/streamkeys,berrberr/streamkeys,berrberr/streamkeys,alexesprit/streamkeys | ---
+++
@@ -1,16 +1,38 @@
;(function() {
"use strict";
- var BaseController = require("BaseController");
+ var BaseController = require("BaseController"),
+ _ = require("lodash");
- new BaseController({
- siteName: "Spotify",
- playPause: "[title='Pause'],[title='Play']",
- playNext: "[title='Next']",
- playPrev: "[title='Previous']",
+ var multiSelectors = {
+ playPause: ["#play-pause", "#play", "[title='Pause'],[title='Play']"],
+ playNext: ["#next", "#next", "[title='Next']"],
+ playPrev: ["#previous", "#previous", "[title='Previous']"],
+ playState: ["#play-pause.playing", "#play.playing", "[title='Pause']"],
+ iframe: ["#app-player", "#main", null],
+ like: [".thumb.up", ".thumb.up", null],
+ dislike: [".thumb.down", ".thumb.down", null],
+ song: ["#track-name", ".caption .track", ".now-playing-bar div div [href*='/album/']"],
+ artist: ["#track-artist", ".caption .artist", ".now-playing-bar div div [href*='/artist/']"]
+ };
- playState: "[title='Pause']",
- song: ".now-playing-bar div div [href*='/album/']",
- artist: ".now-playing-bar div div [href*='/artist/']"
+ var controller = new BaseController({
+ siteName: "Spotify"
});
+
+ controller.checkPlayer = function() {
+ var that = this;
+ var selectorIndex;
+
+ if (window.location.hostname === "open.spotify.com") {
+ selectorIndex = 2;
+ } else {
+ if (document.querySelector(multiSelectors.iframe[0])) { selectorIndex = 0; }
+ if (document.querySelector(multiSelectors.iframe[1])) { selectorIndex = 1; }
+ }
+
+ _.each(multiSelectors, function(value, key) {
+ that.selectors[key] = value[selectorIndex];
+ });
+ };
})(); |
fb3f71b4e38d2d6196d2f157f30fd99188a29184 | src/react-redux.js | src/react-redux.js | /* @flow strict-local */
import type { ComponentType, ElementConfig } from 'react';
import { connect as connectInner } from 'react-redux';
import type { GlobalState } from './types';
export const connect: <
C: ComponentType<*>,
// S == GlobalState
SP: {},
RSP: {},
CP: $Diff<$Diff<ElementConfig<C>, { dispatch: mixed }>, RSP>,
// ST ignore
>(
mapStateToProps?: (GlobalState, SP) => RSP,
) => C => ComponentType<CP & SP> = mapStateToProps => connectInner(mapStateToProps);
| /* @flow strict-local */
import type { ComponentType, ElementConfig } from 'react';
import { connect as connectInner } from 'react-redux';
import type { GlobalState } from './types';
export const connect: <
C: ComponentType<*>,
// S == GlobalState
SP: {},
RSP: {},
CP: $Diff<$Diff<ElementConfig<C>, { dispatch: mixed }>, RSP>,
// ST ignore
>(
mapStateToProps?: (GlobalState, SP) => RSP,
) => C => ComponentType<CP & SP> = mapStateToProps => connectInner(mapStateToProps);
/**
* DEPRECATED. Don't add new uses; and PRs to remove existing uses are welcome.
*
* This is exactly like `connect` except with type-checking disabled.
* Any place we use it, it's because there's a type error there.
* To fix: change the call site to use `connect`; see what error Flow
* reports; and fix the error.
*
* (Backstory: for a long time `connect` had a type that partly defeated
* type-checking, so we accumulated a number of type errors that that hid.
* This untyped version lets us fix those errors one by one, while using the
* new, well-typed `connect` everywhere else.)
*/
export const connectFlowFixMe = (mapStateToProps: $FlowFixMe) => (c: $FlowFixMe) =>
connect(mapStateToProps)(c);
| Add a "fixme" version, `connectFlowFixMe`. | connect: Add a "fixme" version, `connectFlowFixMe`.
| JavaScript | apache-2.0 | vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile | ---
+++
@@ -14,3 +14,19 @@
>(
mapStateToProps?: (GlobalState, SP) => RSP,
) => C => ComponentType<CP & SP> = mapStateToProps => connectInner(mapStateToProps);
+
+/**
+ * DEPRECATED. Don't add new uses; and PRs to remove existing uses are welcome.
+ *
+ * This is exactly like `connect` except with type-checking disabled.
+ * Any place we use it, it's because there's a type error there.
+ * To fix: change the call site to use `connect`; see what error Flow
+ * reports; and fix the error.
+ *
+ * (Backstory: for a long time `connect` had a type that partly defeated
+ * type-checking, so we accumulated a number of type errors that that hid.
+ * This untyped version lets us fix those errors one by one, while using the
+ * new, well-typed `connect` everywhere else.)
+ */
+export const connectFlowFixMe = (mapStateToProps: $FlowFixMe) => (c: $FlowFixMe) =>
+ connect(mapStateToProps)(c); |
11a944cb7881db56137e826c3529f2ccca5c226e | app/assets/javascripts/lesson_plan.js | app/assets/javascripts/lesson_plan.js | function LessonPlanEntryFormType(pickers) {
var self = this;
this.pickers = pickers;
pickers.forEach(function(picker) {
picker.onSelectionCompleted = function() { self.doneCallback.apply(self, arguments); }
});
}
LessonPlanEntryFormType.prototype.pick = function() {
var $modal = $('<div class="modal hide fade" />');
this.pickers[0].pick($modal[0]);
$modal.modal();
}
LessonPlanEntryFormType.prototype.doneCallback = function(idTypePairList) {
idTypePairList.forEach(function(x) {
$element = $('<tr>\n\
<td>' + x[2] + '</td>\n\
<td> </td>\n\
<td>\n\
<span class="btn btn-danger resource-delete"><i class="icon-trash"></i></span>\n\
<input type="hidden" name="resources[]" value="' + x[0] + ',' + x[1] + '" />\n\
</td>\n\
</tr>');
$("#linked_resources tbody").append($element);
});
};
var LessonPlanEntryForm = new LessonPlanEntryFormType([]);
$(document).ready(function() {
$('.addresource-button').click(function() {
LessonPlanEntryForm.pick();
});
$(document).on('click', '.resource-delete', null, function() {
$(this).parents('tr').remove();
});
});
| $(document).ready(function() {
function LessonPlanEntryFormType(pickers) {
var self = this;
this.pickers = pickers;
pickers.forEach(function(picker) {
picker.onSelectionCompleted = function() { self.doneCallback.apply(self, arguments); }
});
}
LessonPlanEntryFormType.prototype.pick = function() {
var $modal = $('<div class="modal hide fade" />');
this.pickers[0].pick($modal[0]);
$modal.modal();
}
LessonPlanEntryFormType.prototype.doneCallback = function(idTypePairList) {
idTypePairList.forEach(function(x) {
$element = $('<tr>\n\
<td>' + x[2] + '</td>\n\
<td> </td>\n\
<td>\n\
<span class="btn btn-danger resource-delete"><i class="icon-trash"></i></span>\n\
<input type="hidden" name="resources[]" value="' + x[0] + ',' + x[1] + '" />\n\
</td>\n\
</tr>');
$("#linked_resources tbody").append($element);
});
};
var LessonPlanEntryForm = new LessonPlanEntryFormType([]);
$('.addresource-button').click(function() {
LessonPlanEntryForm.pick();
});
$(document).on('click', '.resource-delete', null, function() {
$(this).parents('tr').remove();
});
});
| Define the lesson plan form type only on page load. | Define the lesson plan form type only on page load.
| JavaScript | mit | dariusf/coursemology.org,allenwq/coursemology.org,nnamon/coursemology.org,dariusf/coursemology.org,Coursemology/coursemology.org,dariusf/coursemology.org,nusedutech/coursemology.org,allenwq/coursemology.org,allenwq/coursemology.org,nnamon/coursemology.org,nusedutech/coursemology.org,nusedutech/coursemology.org,Coursemology/coursemology.org,dariusf/coursemology.org,Coursemology/coursemology.org,nnamon/coursemology.org,nusedutech/coursemology.org,nnamon/coursemology.org,Coursemology/coursemology.org,dariusf/coursemology.org,allenwq/coursemology.org,nusedutech/coursemology.org,nnamon/coursemology.org,Coursemology/coursemology.org,allenwq/coursemology.org | ---
+++
@@ -1,34 +1,34 @@
-function LessonPlanEntryFormType(pickers) {
- var self = this;
- this.pickers = pickers;
- pickers.forEach(function(picker) {
- picker.onSelectionCompleted = function() { self.doneCallback.apply(self, arguments); }
- });
-}
+$(document).ready(function() {
+ function LessonPlanEntryFormType(pickers) {
+ var self = this;
+ this.pickers = pickers;
+ pickers.forEach(function(picker) {
+ picker.onSelectionCompleted = function() { self.doneCallback.apply(self, arguments); }
+ });
+ }
-LessonPlanEntryFormType.prototype.pick = function() {
- var $modal = $('<div class="modal hide fade" />');
- this.pickers[0].pick($modal[0]);
- $modal.modal();
-}
+ LessonPlanEntryFormType.prototype.pick = function() {
+ var $modal = $('<div class="modal hide fade" />');
+ this.pickers[0].pick($modal[0]);
+ $modal.modal();
+ }
-LessonPlanEntryFormType.prototype.doneCallback = function(idTypePairList) {
- idTypePairList.forEach(function(x) {
- $element = $('<tr>\n\
- <td>' + x[2] + '</td>\n\
- <td> </td>\n\
- <td>\n\
- <span class="btn btn-danger resource-delete"><i class="icon-trash"></i></span>\n\
- <input type="hidden" name="resources[]" value="' + x[0] + ',' + x[1] + '" />\n\
- </td>\n\
- </tr>');
- $("#linked_resources tbody").append($element);
- });
-};
+ LessonPlanEntryFormType.prototype.doneCallback = function(idTypePairList) {
+ idTypePairList.forEach(function(x) {
+ $element = $('<tr>\n\
+ <td>' + x[2] + '</td>\n\
+ <td> </td>\n\
+ <td>\n\
+ <span class="btn btn-danger resource-delete"><i class="icon-trash"></i></span>\n\
+ <input type="hidden" name="resources[]" value="' + x[0] + ',' + x[1] + '" />\n\
+ </td>\n\
+ </tr>');
+ $("#linked_resources tbody").append($element);
+ });
+ };
-var LessonPlanEntryForm = new LessonPlanEntryFormType([]);
+ var LessonPlanEntryForm = new LessonPlanEntryFormType([]);
-$(document).ready(function() {
$('.addresource-button').click(function() {
LessonPlanEntryForm.pick();
}); |
292b7df5a8da7e74a1979e781ecf7a377da2876e | app/assets/javascripts/radioSlider.js | app/assets/javascripts/radioSlider.js | (function(global) {
"use strict";
global.GOVUK.Modules.RadioSlider = function() {
this.start = function(component) {
$(component)
.on('click', function() {
leftRight = $(this).find(':checked').next('label').text().split('/');
if (leftRight.length === 2) {
$(this).find('.radio-slider-left-value').html(leftRight[0]);
$(this).find('.radio-slider-right-value').html(leftRight[1]);
}
})
.trigger('click');
};
};
})(window);
| (function(global) {
"use strict";
global.GOVUK.Modules.RadioSlider = function() {
this.start = function(component) {
$(component)
.on('click', function() {
valuesInLabel = $(this).find(':checked').next('label').text().split('/');
if (valuesInLabel.length === 2) {
leftValue = valuesInLabel[0];
rightValue = valuesInLabel[1];
$(this).find('.radio-slider-left-value').html(leftValue);
$(this).find('.radio-slider-right-value').html(rightValue);
}
})
.trigger('click');
};
};
})(window);
| Add named variables for clarity | Add named variables for clarity
| JavaScript | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -9,11 +9,13 @@
$(component)
.on('click', function() {
- leftRight = $(this).find(':checked').next('label').text().split('/');
+ valuesInLabel = $(this).find(':checked').next('label').text().split('/');
- if (leftRight.length === 2) {
- $(this).find('.radio-slider-left-value').html(leftRight[0]);
- $(this).find('.radio-slider-right-value').html(leftRight[1]);
+ if (valuesInLabel.length === 2) {
+ leftValue = valuesInLabel[0];
+ rightValue = valuesInLabel[1];
+ $(this).find('.radio-slider-left-value').html(leftValue);
+ $(this).find('.radio-slider-right-value').html(rightValue);
}
}) |
e45315ab54b014c5a4f529c22000ba0213cb376a | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'dest/taggd.js',
'tests/functions.js',
'tests/units/*.js',
'tests/behavior/*.js',
{
pattern: 'tests/assets/**/*.jpg',
watched: false,
included: false,
served: true,
nocache: false,
},
],
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: Infinity,
preprocessors: {
'dest/taggd.js': 'coverage',
},
});
};
| module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'dist/taggd.js',
'tests/functions.js',
'tests/units/*.js',
'tests/behavior/*.js',
{
pattern: 'tests/assets/**/*.jpg',
watched: false,
included: false,
served: true,
nocache: false,
},
],
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: Infinity,
preprocessors: {
'dist/taggd.js': 'coverage',
},
});
};
| Fix destination paths for tests | Fix destination paths for tests
| JavaScript | mit | timseverien/taggd,timseverien/taggd | ---
+++
@@ -3,7 +3,7 @@
basePath: '',
frameworks: ['jasmine'],
files: [
- 'dest/taggd.js',
+ 'dist/taggd.js',
'tests/functions.js',
'tests/units/*.js',
'tests/behavior/*.js',
@@ -25,7 +25,7 @@
singleRun: true,
concurrency: Infinity,
preprocessors: {
- 'dest/taggd.js': 'coverage',
+ 'dist/taggd.js': 'coverage',
},
});
}; |
770d2ce95f6dfcb557e4591eeee97cd96de191e1 | karma.conf.js | karma.conf.js | const webpack = require('./webpack.config')
module.exports = config => {
config.set({
frameworks: ['mocha', 'chai'],
files: [
{ pattern: 'test/components/*.js', watched: false }
],
preprocessors: {
'test/components/*.js': ['webpack']
},
webpack,
webpackMiddleware: {
stats: 'errors-only',
noInfo: true
},
browsers: ['Chrome'],
reporters: ['mocha'],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
})
if (process.env.TRAVIS) {
config.browsers = ['Chrome_travis_ci']
}
}
| const webpack = require('./webpack.config')
process.env.CHROME_BIN = require('puppeteer').executablePath()
module.exports = config => {
config.set({
frameworks: ['mocha', 'chai'],
files: ['test/components/index.js', 'test/components/*.js'],
preprocessors: {
'test/components/*.js': ['webpack']
},
webpack,
webpackMiddleware: {
stats: 'errors-only',
noInfo: true
},
browsers: ['ChromeHeadless'],
reporters: ['mocha'],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
})
if (process.env.TRAVIS) {
config.browsers = ['Chrome_travis_ci']
}
}
| Switch to headless chrome from chrome | Switch to headless chrome from chrome
| JavaScript | mit | sunya9/beta,sunya9/beta,sunya9/beta | ---
+++
@@ -1,11 +1,10 @@
const webpack = require('./webpack.config')
+process.env.CHROME_BIN = require('puppeteer').executablePath()
module.exports = config => {
config.set({
frameworks: ['mocha', 'chai'],
- files: [
- { pattern: 'test/components/*.js', watched: false }
- ],
+ files: ['test/components/index.js', 'test/components/*.js'],
preprocessors: {
'test/components/*.js': ['webpack']
},
@@ -14,7 +13,7 @@
stats: 'errors-only',
noInfo: true
},
- browsers: ['Chrome'],
+ browsers: ['ChromeHeadless'],
reporters: ['mocha'],
customLaunchers: {
Chrome_travis_ci: { |
408d4ecbd40aaf1de9ed439a1652606e0030acf5 | spec/bin/jasmine_spec.js | spec/bin/jasmine_spec.js | import path from 'path';
import {exec} from 'node-promise-es6/child-process';
async function cli(fixture, env = null) {
const child = await exec(
'jasmine',
{
cwd: path.resolve(`fixtures/${fixture}`),
env: Object.assign({}, process.env, env)
}
);
return child.stdout;
}
describe('jasmine-es6', function() {
it('uses spec/support/jasmine.json if it exists', async function() {
expect(await cli('with_jasmine_json'))
.toContain('1 spec, 0 failures');
});
it('uses the default jasmine.json if spec/support/jasmine.json does not exist', async function() {
expect(await cli('without_jasmine_json'))
.toContain('1 spec, 0 failures');
});
it('allows configuring the jasmine.json path via environment variable', async function() {
expect(await cli(
'with_jasmine_json',
{
JASMINE_CONFIG_PATH: 'spec/support/jasmine2.json'
}
)).toContain('No specs found');
});
it('installs the async override by default', async function() {
const output = await cli('async_override');
expect(output).toContain('2 specs, 0 failures');
const [, duration] = output.match(/Finished in ([\d.]+) seconds/);
expect(Number(duration)).toBeGreaterThan(5);
}, 10000);
});
| import path from 'path';
import {exec} from 'node-promise-es6/child-process';
async function cli(fixture, env = null) {
const child = await exec(
'jasmine',
{
cwd: path.resolve(__dirname, `../../fixtures/${fixture}`),
env: Object.assign({}, process.env, env)
}
);
return child.stdout;
}
describe('jasmine-es6', function() {
it('uses spec/support/jasmine.json if it exists', async function() {
expect(await cli('with_jasmine_json'))
.toContain('1 spec, 0 failures');
});
it('uses the default jasmine.json if spec/support/jasmine.json does not exist', async function() {
expect(await cli('without_jasmine_json'))
.toContain('1 spec, 0 failures');
});
it('allows configuring the jasmine.json path via environment variable', async function() {
expect(await cli(
'with_jasmine_json',
{
JASMINE_CONFIG_PATH: 'spec/support/jasmine2.json'
}
)).toContain('No specs found');
});
it('installs the async override by default', async function() {
const output = await cli('async_override');
expect(output).toContain('2 specs, 0 failures');
const [, duration] = output.match(/Finished in ([\d.]+) seconds/);
expect(Number(duration)).toBeGreaterThan(5);
}, 10000);
});
| Remove calls to `path.resolve` with no root directory | Remove calls to `path.resolve` with no root directory
| JavaScript | mit | vinsonchuong/jasmine-es6,dongtong/jasmine-es6 | ---
+++
@@ -5,7 +5,7 @@
const child = await exec(
'jasmine',
{
- cwd: path.resolve(`fixtures/${fixture}`),
+ cwd: path.resolve(__dirname, `../../fixtures/${fixture}`),
env: Object.assign({}, process.env, env)
}
); |
a42a841fca52fc2dec520329ef1c32a97ab2dece | app/services/passwordCheckService.js | app/services/passwordCheckService.js | var app = angular.module("AdmissionsApp");
app.service("PasswordCheckService", ["$http", function ($http) {
var submitBaseUrl = "http://admissions.vschool.io/api/part";
this.checkPassword = function (password, partNumber) {
var submitData = {answer: password};
return $http.post(submitBaseUrl + "/" + partNumber, submitData)
.then(function (response) {
return response.data;
});
}
}]); | var app = angular.module("AdmissionsApp");
app.service("PasswordCheckService", ["$http", function ($http) {
var submitBaseUrl = "http://admissions-qa.vschool.io/api/part";
this.checkPassword = function (password, partNumber) {
var submitData = {answer: password};
return $http.post(submitBaseUrl + "/" + partNumber, submitData)
.then(function (response) {
return response.data;
});
}
}]); | Change subdomain to reflect that it's in a testing period still | Change subdomain to reflect that it's in a testing period still
| JavaScript | mit | bobziroll/admissions,bobziroll/admissions | ---
+++
@@ -1,7 +1,7 @@
var app = angular.module("AdmissionsApp");
app.service("PasswordCheckService", ["$http", function ($http) {
- var submitBaseUrl = "http://admissions.vschool.io/api/part";
+ var submitBaseUrl = "http://admissions-qa.vschool.io/api/part";
this.checkPassword = function (password, partNumber) {
var submitData = {answer: password}; |
034d845f47267d70a412dc98ea81e8bb3ab27d38 | mzalendo/map/static/js/map-drilldown.js | mzalendo/map/static/js/map-drilldown.js | (function () {
function initialize_map() {
var map_element = document.getElementById("map-drilldown-canvas");
if (!map_element) return false;
// start with the default bounds for kenya
var map_bounds = {
north: 5,
east: 44,
south: -5,
west: 33.5
};
var map_has_been_located = false;
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
maxZoom: 10
};
var map = new google.maps.Map(map_element, myOptions);
map.fitBounds( make_bounds( map_bounds ) );
}
function make_bounds ( bounds ) {
var sw = new google.maps.LatLng( bounds.south, bounds.west );
var ne = new google.maps.LatLng( bounds.north, bounds.east );
return new google.maps.LatLngBounds( sw, ne );
}
mzalendo_run_when_document_ready(
function () {
google.load(
'maps', '3',
{
callback: initialize_map,
other_params:'sensor=false'
}
);
}
);
})();
| (function () {
function initialize_map() {
var map_element = document.getElementById("map-drilldown-canvas");
if (!map_element) return false;
// start with the default bounds for kenya
var map_bounds = {
north: 5,
east: 44,
south: -5,
west: 33.5
};
var map_has_been_located = false;
var myOptions = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
maxZoom: 10
};
var map = new google.maps.Map(map_element, myOptions);
map.fitBounds( make_bounds( map_bounds ) );
}
function make_bounds ( bounds ) {
var sw = new google.maps.LatLng( bounds.south, bounds.west );
var ne = new google.maps.LatLng( bounds.north, bounds.east );
return new google.maps.LatLngBounds( sw, ne );
}
mzalendo_run_when_document_ready(
function () {
google.load(
'maps', '3',
{
callback: initialize_map,
other_params:'sensor=false'
}
);
}
);
})();
| Enable map controls, switch to terrain view | Enable map controls, switch to terrain view
| JavaScript | agpl-3.0 | mysociety/pombola,mysociety/pombola,hzj123/56th,patricmutwiri/pombola,hzj123/56th,geoffkilpin/pombola,geoffkilpin/pombola,patricmutwiri/pombola,geoffkilpin/pombola,mysociety/pombola,patricmutwiri/pombola,hzj123/56th,hzj123/56th,ken-muturi/pombola,mysociety/pombola,ken-muturi/pombola,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,geoffkilpin/pombola,geoffkilpin/pombola,ken-muturi/pombola,geoffkilpin/pombola,hzj123/56th,patricmutwiri/pombola,mysociety/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,hzj123/56th | ---
+++
@@ -16,8 +16,7 @@
var map_has_been_located = false;
var myOptions = {
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- disableDefaultUI: true,
+ mapTypeId: google.maps.MapTypeId.TERRAIN,
maxZoom: 10
};
|
f6278a3b08f23637bfc3d848f864dc971cfa94ce | lib/Events.js | lib/Events.js | module.exports = {
on: function(name, callback, context) {
var events = this._getEvents(name) || [];
this._events[name] = events.concat({
callback: callback,
context: context || this
});
return this;
},
off: function(name, callback, context) {
if (callback) {
var events = this._getEvents(name);
this._events[name] = events.filter(function(event) {
return callback !== event.callback || context !== event.context;
});
} else {
this._events = Object.keys(this._events).reduce(function(memo, key) {
if (name !== key) {
memo[key] = this._events[key];
}
return memo;
}, {});
}
return this;
},
emit: function(name) {
var args = [].slice.call(arguments, 1);
var events = this._getEvents(name);
if (events) {
events.forEach(function(event) {
event.callback.apply(event.context, args);
});
}
return this;
},
_getEvents: function(name) {
this._events = this._events || {};
return this._events[name];
}
};
| var events = {};
function getEvents(name) {
events[name] = events[name] || [];
return events[name];
}
function setEvents(name, newEvents) {
events[name] = newEvents;
}
function addEvent(name, event) {
var newEvents = getEvents(name).concat(event);
setEvents(name, newEvents);
}
function removeEvent(name, callback, context) {
var newEvents = getEvents(name).filter(function(event) {
return callback !== event.callback || context !== event.context;
});
setEvents(name, newEvents);
}
function removeEvents(name) {
events = Object.keys(events).reduce(function(memo, key) {
if (name !== key) {
memo[key] = events[key];
}
return memo;
}, {});
}
module.exports = {
on: function(name, callback, context) {
addEvent(name, { callback: callback, context: context || this });
return this;
},
off: function(name, callback, context) {
if (callback) {
removeEvent(name, callback, context);
} else {
removeEvents(name);
}
return this;
},
emit: function(name) {
var args = [].slice.call(arguments, 1);
getEvents(name).forEach(function(event) {
event.callback.apply(event.context, args);
});
return this;
}
};
| Use private functions for implementation details of Event module | Use private functions for implementation details of Event module
| JavaScript | mit | dscout/immunid,dscout/immunid | ---
+++
@@ -1,51 +1,63 @@
+var events = {};
+
+function getEvents(name) {
+ events[name] = events[name] || [];
+
+ return events[name];
+}
+
+function setEvents(name, newEvents) {
+ events[name] = newEvents;
+}
+
+function addEvent(name, event) {
+ var newEvents = getEvents(name).concat(event);
+
+ setEvents(name, newEvents);
+}
+
+function removeEvent(name, callback, context) {
+ var newEvents = getEvents(name).filter(function(event) {
+ return callback !== event.callback || context !== event.context;
+ });
+
+ setEvents(name, newEvents);
+}
+
+function removeEvents(name) {
+ events = Object.keys(events).reduce(function(memo, key) {
+ if (name !== key) {
+ memo[key] = events[key];
+ }
+
+ return memo;
+ }, {});
+}
+
module.exports = {
on: function(name, callback, context) {
- var events = this._getEvents(name) || [];
-
- this._events[name] = events.concat({
- callback: callback,
- context: context || this
- });
+ addEvent(name, { callback: callback, context: context || this });
return this;
},
off: function(name, callback, context) {
if (callback) {
- var events = this._getEvents(name);
-
- this._events[name] = events.filter(function(event) {
- return callback !== event.callback || context !== event.context;
- });
+ removeEvent(name, callback, context);
} else {
- this._events = Object.keys(this._events).reduce(function(memo, key) {
- if (name !== key) {
- memo[key] = this._events[key];
- }
-
- return memo;
- }, {});
+ removeEvents(name);
}
return this;
},
emit: function(name) {
- var args = [].slice.call(arguments, 1);
- var events = this._getEvents(name);
+ var args = [].slice.call(arguments, 1);
- if (events) {
- events.forEach(function(event) {
- event.callback.apply(event.context, args);
- });
- }
+ getEvents(name).forEach(function(event) {
+ event.callback.apply(event.context, args);
+ });
return this;
- },
-
- _getEvents: function(name) {
- this._events = this._events || {};
-
- return this._events[name];
}
}; |
638143097275249385dbe7f8c7287ec4a4039424 | src/rawTransaction.js | src/rawTransaction.js | import Tx from 'ethereumjs-tx'
import ethUtil from 'ethereumjs-util'
import web3 from './web3client'
import { coinbase, another, keys } from './keys'
export function signTransaction(rawTx) {
var account = keys[rawTx.from]
if(!account) {
throw new Error(`No private key for account "${from}"`)
}
var privateKey = account.privateKey
var tx = new Tx(rawTx)
tx.sign(privateKey)
var serializedTx = tx.serialize()
return serializedTx.toString('hex')
}
| import Tx from 'ethereumjs-tx'
import ethUtil from 'ethereumjs-util'
import web3 from './web3client'
import { coinbase, another, keys } from './keys'
export function signTransaction(rawTx) {
const account = keys[rawTx.from]
if(!account) {
throw new Error(`No private key for account "${from}"`)
}
const privateKey = account.privateKey
const tx = new Tx(rawTx)
tx.sign(privateKey)
const serializedTx = ethUtil.addHexPrefix(tx.serialize().toString('hex'))
return serializedTx.toString('hex')
}
| Add hex prefix to signed transaction | Add hex prefix to signed transaction
| JavaScript | mit | CBAInnovationLab/web3-sandbox | ---
+++
@@ -5,14 +5,14 @@
export function signTransaction(rawTx) {
- var account = keys[rawTx.from]
+ const account = keys[rawTx.from]
if(!account) {
throw new Error(`No private key for account "${from}"`)
}
- var privateKey = account.privateKey
- var tx = new Tx(rawTx)
+ const privateKey = account.privateKey
+ const tx = new Tx(rawTx)
tx.sign(privateKey)
- var serializedTx = tx.serialize()
+ const serializedTx = ethUtil.addHexPrefix(tx.serialize().toString('hex'))
return serializedTx.toString('hex')
} |
2501a700a90553786b122438a5cf9a6d46001ae8 | javascripts/background.js | javascripts/background.js | var githubFeed = ({
feedUrl: "",
loadFeedUrl: function() {
var self = this;
chrome.storage.local.get("current_user_url", function(data) {
self.feedUrl = data.current_user_url;
});
},
urlChanged: function() {
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
if (key === "current_user_url") {
alert("!!!");
console.log(changes[key].newValue);
this.feedUrl = changes[key].newValue;
}
}
});
},
getUserFeed: function() {
$.ajax({
type: "GET",
url: this.feedUrl,
success: function (data) {
debugger;
},
error: function (xhr, status, data) {
debugger;
},
});
},
init: function() {
this.urlChanged();
return this;
},
}).init();
githubFeed.loadFeedUrl();
| var githubFeed = ({
feedUrl: "",
loadFeedUrl: function() {
var self = this;
chrome.storage.local.get("current_user_url", function(data) {
self.feedUrl = data.current_user_url;
});
},
urlChanged: function() {
var self = this;
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
if (key === "current_user_url") {
alert("!!!");
console.log(changes[key].newValue);
self.feedUrl = changes[key].newValue;
self.getUserFeed();
}
}
});
},
getUserFeed: function() {
$.ajax({
type: "GET",
url: this.feedUrl,
success: function (data) {
debugger;
},
error: function (xhr, status, data) {
debugger;
},
});
},
init: function() {
this.urlChanged();
return this;
},
}).init();
githubFeed.loadFeedUrl();
| Call getUserFeed() when current user url is changed | Call getUserFeed() when current user url is changed
| JavaScript | mit | TAKAyukiatkwsk/github_feed_notifier | ---
+++
@@ -9,12 +9,14 @@
},
urlChanged: function() {
+ var self = this;
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
if (key === "current_user_url") {
alert("!!!");
console.log(changes[key].newValue);
- this.feedUrl = changes[key].newValue;
+ self.feedUrl = changes[key].newValue;
+ self.getUserFeed();
}
}
}); |
bad3a8c822be9935fb7607212b7ddf639fe878b0 | docs/examples/AsyncPromises.js | docs/examples/AsyncPromises.js | import React, { Component } from 'react';
import AsyncSelect from '../../src/Async';
import { colourOptions } from '../data';
type State = {
inputValue: string,
};
const filterColors = (inputValue: string) => {
return colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
};
const promiseOptions = inputValue =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class WithPromises extends Component<*, State> {
state = { inputValue: '' };
handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '');
this.setState({ inputValue });
return inputValue;
};
render() {
return (
<AsyncSelect cacheOptions defaultOptions loadOptions={promiseOptions} />
);
}
}
| import React, { Component } from 'react';
import AsyncSelect from '../../src/Async';
import { colourOptions } from '../data';
const filterColors = (inputValue: string) => {
return colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
};
const promiseOptions = inputValue =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class WithPromises extends Component {
render() {
return (
<AsyncSelect cacheOptions defaultOptions loadOptions={promiseOptions} />
);
}
}
| Remove dead code in example | Remove dead code in example | JavaScript | mit | JedWatson/react-select,JedWatson/react-select | ---
+++
@@ -2,10 +2,6 @@
import AsyncSelect from '../../src/Async';
import { colourOptions } from '../data';
-
-type State = {
- inputValue: string,
-};
const filterColors = (inputValue: string) => {
return colourOptions.filter(i =>
@@ -20,13 +16,7 @@
}, 1000);
});
-export default class WithPromises extends Component<*, State> {
- state = { inputValue: '' };
- handleInputChange = (newValue: string) => {
- const inputValue = newValue.replace(/\W/g, '');
- this.setState({ inputValue });
- return inputValue;
- };
+export default class WithPromises extends Component {
render() {
return (
<AsyncSelect cacheOptions defaultOptions loadOptions={promiseOptions} /> |
d2710ff8b6bb406526e64b51268611de54979bc3 | src/modular.js | src/modular.js | /*-----------------------------------------------------------------
Modular - JS Extension
Made by @esr360
http://github.com/esr360/Modular/
-----------------------------------------------------------------*/
//-----------------------------------------------------------------
// Convert CSS config to JS
//-----------------------------------------------------------------
// Get styles' configuration
var stylesConfigJSON = document.getElementById("stylesConfigJSON");
// Remove quotes from computed JSON
function removeQuotes(json) {
json = json.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, '');
return json;
}
// Convert computed JSON to camelCase
function camelCase(json) {
json = json.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
return json;
}
// Convert the config to JS
function getStylesConfig(camelCase) {
var style = null;
style = window.getComputedStyle(stylesConfigJSON, '::before');
style = style.content;
style = removeQuotes(style);
if(camelCase) {
style = camelCase(style);
}
return JSON.parse(style);
} | /*-----------------------------------------------------------------
Modular - JS Extension
Made by @esr360
http://github.com/esr360/Modular/
-----------------------------------------------------------------*/
//-----------------------------------------------------------------
// Convert CSS config to JS
//-----------------------------------------------------------------
// Get styles' configuration
var stylesConfigJSON = document.getElementById("stylesConfigJSON");
// Remove quotes from computed JSON
function removeQuotes(json) {
json = json.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, '');
return json;
}
// Convert computed JSON to camelCase
function camelCase(json) {
json = json.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
return json;
}
// Convert the config to JS
function getStylesConfig(camelCase) {
var style = null;
style = window.getComputedStyle(stylesConfigJSON, '::before');
style = style.content;
style = removeQuotes(style);
if(camelCase) {
style = camelCase(style);
}
return JSON.parse(style);
}
// Store configuartion data in a variable
var module = getStylesConfig(); | Store configuartion data in a variable | Store configuartion data in a variable
| JavaScript | mit | esr360/Synergy,esr360/Modular,esr360/Modular | ---
+++
@@ -38,3 +38,6 @@
}
return JSON.parse(style);
}
+
+// Store configuartion data in a variable
+var module = getStylesConfig(); |
3c583ed9f61554c95450d007fef98c40180c829c | webpack.mix.js | webpack.mix.js | const
{ mix } = require('laravel-mix'),
webpack = require('webpack');
mix
.webpackConfig({
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'Tether': 'tether',
'window.axios': 'axios'
})
]
})
.copy(
'node_modules/kent-bar/build/deploy/assets/app.js',
'public/js/kent-bar.js'
)
.copy(
'node_modules/kent-bar/build/deploy/assets/main.css',
'public/css/kent-bar.css'
)
.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css')
.extract(['vue', 'jquery', 'axios', 'tether', 'bootstrap']);
| const
{ mix } = require('laravel-mix'),
webpack = require('webpack');
mix
.webpackConfig({
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'Tether': 'tether',
'window.axios': 'axios'
})
],
resolve: {
symlinks: false
}
})
.copy(
'node_modules/kent-bar/build/deploy/assets/app.js',
'public/js/kent-bar.js'
)
.copy(
'node_modules/kent-bar/build/deploy/assets/main.css',
'public/css/kent-bar.css'
)
.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css')
.extract(['vue', 'jquery', 'axios', 'tether', 'bootstrap', 'element-ui']);
| Make npm link work with babel-loader. | Make npm link work with babel-loader.
| JavaScript | mit | unikent/astro,unikent/astro,unikent/astro,unikent/astro,unikent/astro | ---
+++
@@ -12,7 +12,10 @@
'Tether': 'tether',
'window.axios': 'axios'
})
- ]
+ ],
+ resolve: {
+ symlinks: false
+ }
})
.copy(
'node_modules/kent-bar/build/deploy/assets/app.js',
@@ -24,4 +27,4 @@
)
.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css')
- .extract(['vue', 'jquery', 'axios', 'tether', 'bootstrap']);
+ .extract(['vue', 'jquery', 'axios', 'tether', 'bootstrap', 'element-ui']); |
92e0a14a9a23ecf93399b5a0431ae6c12175ff29 | grunt_tasks/webpack.plugins.js | grunt_tasks/webpack.plugins.js | /**
* This file contains custom webpack plugins.
*/
// This plugin modifies the generated webpack code to execute a module within the DLL bundle
// in addition to preserving the default behavior of exporting the webpack require function
class DllBootstrapPlugin {
constructor(options) {
this.options = options || {};
}
apply(compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.mainTemplate.plugin('startup', (source, chunk) => {
let module;
const bootstrapEntry = this.options[chunk.name];
if (bootstrapEntry) {
module = chunk.modules.find((m) => m.rawRequest === bootstrapEntry);
source = `__webpack_require__(${module.id});\n${source}`;
}
return source;
});
});
}
}
module.exports = {
DllBootstrapPlugin
};
| /**
* This file contains custom webpack plugins.
*/
'use strict';
// This plugin modifies the generated webpack code to execute a module within the DLL bundle
// in addition to preserving the default behavior of exporting the webpack require function
class DllBootstrapPlugin {
constructor(options) {
this.options = options || {};
}
apply(compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.mainTemplate.plugin('startup', (source, chunk) => {
const bootstrapEntry = this.options[chunk.name];
if (bootstrapEntry) {
const module = chunk.modules.find((m) => m.rawRequest === bootstrapEntry);
source = `__webpack_require__(${module.id});\n${source}`;
}
return source;
});
});
}
}
module.exports = {
DllBootstrapPlugin
};
| Fix complaints about strict mode during build | Fix complaints about strict mode during build
| JavaScript | apache-2.0 | adsorensen/girder,sutartmelson/girder,Xarthisius/girder,data-exp-lab/girder,data-exp-lab/girder,Xarthisius/girder,Xarthisius/girder,RafaelPalomar/girder,kotfic/girder,adsorensen/girder,adsorensen/girder,manthey/girder,Kitware/girder,RafaelPalomar/girder,sutartmelson/girder,jbeezley/girder,girder/girder,data-exp-lab/girder,kotfic/girder,kotfic/girder,kotfic/girder,Xarthisius/girder,girder/girder,RafaelPalomar/girder,RafaelPalomar/girder,sutartmelson/girder,data-exp-lab/girder,adsorensen/girder,girder/girder,adsorensen/girder,Kitware/girder,jbeezley/girder,jbeezley/girder,sutartmelson/girder,manthey/girder,girder/girder,sutartmelson/girder,data-exp-lab/girder,Xarthisius/girder,manthey/girder,kotfic/girder,Kitware/girder,Kitware/girder,manthey/girder,jbeezley/girder,RafaelPalomar/girder | ---
+++
@@ -1,6 +1,7 @@
/**
* This file contains custom webpack plugins.
*/
+'use strict';
// This plugin modifies the generated webpack code to execute a module within the DLL bundle
// in addition to preserving the default behavior of exporting the webpack require function
@@ -12,10 +13,9 @@
apply(compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.mainTemplate.plugin('startup', (source, chunk) => {
- let module;
const bootstrapEntry = this.options[chunk.name];
if (bootstrapEntry) {
- module = chunk.modules.find((m) => m.rawRequest === bootstrapEntry);
+ const module = chunk.modules.find((m) => m.rawRequest === bootstrapEntry);
source = `__webpack_require__(${module.id});\n${source}`;
}
return source; |
5ecd470d6e1a937c54dd7eff28d44fe30c269506 | js/editor-libs/console.js | js/editor-libs/console.js | // Thanks in part to https://stackoverflow.com/questions/11403107/capturing-javascript-console-log
(function(global) {
'use strict';
var originalConsoleLogger = console.log; // eslint-disable-line no-console
var originalConsoleError = console.error;
var outputContainer = document.getElementById('output');
var output = outputContainer.querySelector('code');
var EditorConsole = {
/**
* Clears the output code block
*/
clearOutput: function() {
output.textContent = '';
}
};
/**
* Writes the provided content to the editor’s output area
* @param {String} content - The content to write to output
*/
function writeOutput(content) {
var outputContent = output.textContent;
var newLogItem = '> ' + content + '\n';
output.textContent = outputContent + newLogItem;
}
console.error = function(loggedItem) {
writeOutput(loggedItem);
// do not swallow console.error
originalConsoleError.apply(console, arguments);
};
// eslint-disable-next-line no-console
console.log = function(loggedItem) {
writeOutput(loggedItem);
// do not swallow console.log
originalConsoleLogger.apply(console, arguments);
};
global.editorConsole = EditorConsole;
})(window);
| // Thanks in part to https://stackoverflow.com/questions/11403107/capturing-javascript-console-log
(function(global) {
'use strict';
var originalConsoleLogger = console.log; // eslint-disable-line no-console
var originalConsoleError = console.error;
var outputContainer = document.getElementById('output');
var output = outputContainer.querySelector('code');
var EditorConsole = {
/**
* Clears the output code block
*/
clearOutput: function() {
output.textContent = '';
}
};
/**
* Formats output to indicate its type:
* - quotes around strings
* - square brackets around arrays
* @param {any} input - The output to log.
*/
function indicateType(input) {
switch (typeof(input)) {
case "string":
input = `"${input}"`;
case "object":
if (Array.isArray(input)) {
input = `[${input}]`;
}
}
return input;
}
/**
* Writes the provided content to the editor’s output area
* @param {String} content - The content to write to output
*/
function writeOutput(content) {
var outputContent = output.textContent;
var newLogItem = '> ' + content + '\n';
output.textContent = outputContent + newLogItem;
}
console.error = function(loggedItem) {
writeOutput(loggedItem);
// do not swallow console.error
originalConsoleError.apply(console, arguments);
};
// eslint-disable-next-line no-console
console.log = function(loggedItem) {
writeOutput(indicateType(loggedItem));
// do not swallow console.log
originalConsoleLogger.apply(console, arguments);
};
global.editorConsole = EditorConsole;
})(window);
| Format logged objects to indicate their type | Format logged objects to indicate their type
| JavaScript | cc0-1.0 | mdn/interactive-examples,mdn/interactive-examples,mdn/interactive-examples | ---
+++
@@ -17,6 +17,24 @@
};
/**
+ * Formats output to indicate its type:
+ * - quotes around strings
+ * - square brackets around arrays
+ * @param {any} input - The output to log.
+ */
+ function indicateType(input) {
+ switch (typeof(input)) {
+ case "string":
+ input = `"${input}"`;
+ case "object":
+ if (Array.isArray(input)) {
+ input = `[${input}]`;
+ }
+ }
+ return input;
+ }
+
+ /**
* Writes the provided content to the editor’s output area
* @param {String} content - The content to write to output
*/
@@ -34,7 +52,7 @@
// eslint-disable-next-line no-console
console.log = function(loggedItem) {
- writeOutput(loggedItem);
+ writeOutput(indicateType(loggedItem));
// do not swallow console.log
originalConsoleLogger.apply(console, arguments);
}; |
26bdb62478b910c70a50322c39ff02e8c88136a7 | lib/config.js | lib/config.js |
var config = {
defaultPort: process.env.PORT || 3000,
defaultLogLength: process.env.LOGLENGTH || 64,
defaultLogLines: process.env.LOGLINES || 10,
defaultSpacer: process.env.SPACER || ' | ',
defaultIdentifier: process.env.IDENTIFIER || '',
defaultLineCount: process.env.LINECOUNT || 1,
defaultLineDated: process.env.LINEDATED || 0,
defaultRepeatDelay: process.env.REPEATDELAY || 2
};
module.exports = config;
|
var config = {
defaultPort: process.env.WEB_PORT || 3000,
defaultLogLength: process.env.LOGLENGTH || 64,
defaultLogLines: process.env.LOGLINES || 10,
defaultSpacer: process.env.SPACER || ' | ',
defaultIdentifier: process.env.IDENTIFIER || '',
defaultLineCount: process.env.LINECOUNT || 1,
defaultLineDated: process.env.LINEDATED || 0,
defaultRepeatDelay: process.env.REPEATDELAY || 2
};
module.exports = config;
| Change PORT to WEB_PORT env var | Change PORT to WEB_PORT env var
conflicts with `PORT` variable injected by Marathon making it unusable in bridge mode. | JavaScript | apache-2.0 | bryanlatten/docker-log-gen | ---
+++
@@ -1,6 +1,6 @@
var config = {
- defaultPort: process.env.PORT || 3000,
+ defaultPort: process.env.WEB_PORT || 3000,
defaultLogLength: process.env.LOGLENGTH || 64,
defaultLogLines: process.env.LOGLINES || 10,
defaultSpacer: process.env.SPACER || ' | ', |
9d8050243b0172973dd5f1a38e7126460c1cadd1 | wire/sizzle.js | wire/sizzle.js | /**
* @license Copyright (c) 2010-2011 Brian Cavalier
* LICENSE: see the LICENSE.txt file. If file is missing, this file is subject
* to the MIT License at: http://www.opensource.org/licenses/mit-license.php.
*/
/**
* sizzle.js
* Adds querySelectorAll functionality to wire using John Resig's Sizzle library.
* Sizzle must be wrapped in an AMD define(). Kris Zyp has a version of this at
* http://github.com/kriszyp/sizzle
*
* @author John Hann (@unscriptable)
*/
define(['sizzle', 'wire/domReady'], function(sizzle, domReady) {
function resolveQuery(promise, name, refObj /*, wire */) {
domReady(function() {
var result = sizzle(name);
promise.resolve(typeof refObj.i == 'number' && refObj.i < result.length
? result[refObj.i]
: result);
});
}
/**
* The plugin instance. Can be the same for all wiring runs
*/
var plugin = {
resolvers: {
'dom.query': resolveQuery
}
};
return {
wire$plugin: function(/*ready, destroyed, options*/) {
return plugin;
}
};
});
| /**
* @license Copyright (c) 2010-2011 Brian Cavalier
* LICENSE: see the LICENSE.txt file. If file is missing, this file is subject
* to the MIT License at: http://www.opensource.org/licenses/mit-license.php.
*/
/**
* sizzle.js
* Adds querySelectorAll functionality to wire using John Resig's Sizzle library.
* Sizzle must be wrapped in an AMD define(). Kris Zyp has a version of this at
* http://github.com/kriszyp/sizzle
*
* @author John Hann (@unscriptable)
*/
define(['sizzle', 'wire/domReady'], function(sizzle, domReady) {
function resolveQuery(resolver, name, refObj /*, wire */) {
domReady(function() {
var result = sizzle(name);
resolver.resolve(typeof refObj.i == 'number' && refObj.i < result.length
? result[refObj.i]
: result);
});
}
/**
* The plugin instance. Can be the same for all wiring runs
*/
var plugin = {
resolvers: {
'dom.query': resolveQuery
}
};
return {
wire$plugin: function(/*ready, destroyed, options*/) {
return plugin;
}
};
});
| Rename promise to resolver, which is what it is anyway | Rename promise to resolver, which is what it is anyway
| JavaScript | mit | cujojs/wire,cujojs/wire,designeng/wire,wilson7287/wire,designeng/wire | ---
+++
@@ -14,11 +14,11 @@
*/
define(['sizzle', 'wire/domReady'], function(sizzle, domReady) {
- function resolveQuery(promise, name, refObj /*, wire */) {
+ function resolveQuery(resolver, name, refObj /*, wire */) {
domReady(function() {
var result = sizzle(name);
- promise.resolve(typeof refObj.i == 'number' && refObj.i < result.length
+ resolver.resolve(typeof refObj.i == 'number' && refObj.i < result.length
? result[refObj.i]
: result);
}); |
17ad3c708178df8456a1788c5467d719f7a78746 | imports/companies/companies.js | imports/companies/companies.js | import * as dh from '/imports/both/docs-helpers.js';
import { Class as Model } from 'meteor/jagi:astronomy';
Companies = new Mongo.Collection('companies');
Company = Model.create({
name: 'Company',
collection: Companies,
fields: {
TaxId: String,
Name: String,
Rating: Number
}
});
Meteor.methods({
'saveCompany': function(company){
if ( !Meteor.userId() ) {
return;
}
// TODO implement specific validators in Astronomy
//check(company.TaxId, String);
//check(company.Name, String);
//check(company.Rating, Number);
company.save();
},
'removeCompany': function(company){
if ( !Meteor.userId() ) {
return;
}
company.remove();
}
}); | import * as dh from '/imports/both/docs-helpers.js';
import { Class as Model } from 'meteor/jagi:astronomy';
Companies = new Mongo.Collection('companies');
Company = Model.create({
name: 'Company',
collection: Companies,
fields: {
TaxId: {
type: String,
validators: [
{ type: 'minLength', param: 5 },
{ type: 'maxLength', param: 25 }
]},
Name: {
type: String,
validators: [
{ type: 'minLength', param: 5 },
{ type: 'maxLength', param: 100 }
]},
Rating: {
type: Number,
validators: [
{ type: 'gte', param: 0 },
{ type: 'lte', param: 10 }
]}
}
});
Meteor.methods({
'saveCompany': function(company){
if ( !Meteor.userId() ) {
return;
}
// TODO implement specific validators in Astronomy
//check(company.TaxId, String);
//check(company.Name, String);
//check(company.Rating, Number);
company.save();
},
'removeCompany': function(company){
if ( !Meteor.userId() ) {
return;
}
company.remove();
}
}); | Add basic validations to the Company model | Add basic validations to the Company model | JavaScript | mit | jaumesola/invoices-mvp,jaumesola/invoices-mvp,jaumesola/invoices-mvp | ---
+++
@@ -4,13 +4,28 @@
Companies = new Mongo.Collection('companies');
Company = Model.create({
- name: 'Company',
- collection: Companies,
- fields: {
- TaxId: String,
- Name: String,
- Rating: Number
- }
+ name: 'Company',
+ collection: Companies,
+ fields: {
+ TaxId: {
+ type: String,
+ validators: [
+ { type: 'minLength', param: 5 },
+ { type: 'maxLength', param: 25 }
+ ]},
+ Name: {
+ type: String,
+ validators: [
+ { type: 'minLength', param: 5 },
+ { type: 'maxLength', param: 100 }
+ ]},
+ Rating: {
+ type: Number,
+ validators: [
+ { type: 'gte', param: 0 },
+ { type: 'lte', param: 10 }
+ ]}
+ }
});
Meteor.methods({ |
879455cc5faf347d88581161085c65882fe3d6e6 | client/users/auth/register/check_nick.js | client/users/auth/register/check_nick.js | 'use strict';
/**
* client
**/
/**
* client.common
**/
/**
* client.common.auth
**/
/**
* client.common.auth.register
**/
/*global nodeca*/
/**
* client.common.auth.register.check_nick($elem, event)
*
* send nick value on server
* and show error if nick exists
**/
module.exports = function ($elem /*, event*/) {
var nick = $elem.val();
nodeca.server.users.auth.register.check_nick({ nick: nick }, function(err){
var $control_group = $elem.parents('.control-group:first');
if (err) {
// Problems with nick
if (err.statusCode === nodeca.io.BAD_REQUEST) {
$control_group.addClass('error');
$control_group.find('.help-block').text(
err.message['nick']
);
return;
}
// something fatal
nodeca.client.common.notify('error', err.message);
return;
}
// no errors -> restore defaults
$control_group.removeClass('error');
$control_group.find('.help-block').text(
nodeca.runtime.t('users.auth.reg_form.nick_help')
);
});
return false;
};
| 'use strict';
/**
* client
**/
/**
* client.common
**/
/**
* client.common.auth
**/
/**
* client.common.auth.register
**/
/*global nodeca*/
var DELAY = 500;
var start_point;
/**
* client.common.auth.register.check_nick($elem, event)
*
* send nick value on server
* and show error if nick exists
**/
module.exports = function ($elem, event) {
// update start point each time
start_point = new Date();
// delay request
setTimeout(function() {
// time is not come
// new event(s) update start point
if (DELAY > new Date() - start_point) {
return;
}
// reset time
start_point = null;
var nick = $elem.val();
nodeca.server.users.auth.register.check_nick({ nick: nick }, function(err){
var $control_group = $elem.parents('.control-group:first');
if (err) {
// Problems with nick
if (err.statusCode === nodeca.io.BAD_REQUEST) {
$control_group.addClass('error');
$control_group.find('.help-block').text(
err.message['nick']
);
return;
}
// something fatal
nodeca.client.common.notify('error', err.message);
return;
}
// no errors -> restore defaults
$control_group.removeClass('error');
$control_group.find('.help-block').text(
nodeca.runtime.t('users.auth.reg_form.nick_help')
);
});
}, DELAY);
return false;
};
| Add delay on nick checking request | Add delay on nick checking request
| JavaScript | mit | nodeca/nodeca.users | ---
+++
@@ -20,6 +20,9 @@
/*global nodeca*/
+var DELAY = 500;
+
+var start_point;
/**
* client.common.auth.register.check_nick($elem, event)
@@ -27,35 +30,50 @@
* send nick value on server
* and show error if nick exists
**/
-module.exports = function ($elem /*, event*/) {
- var nick = $elem.val();
+module.exports = function ($elem, event) {
+ // update start point each time
+ start_point = new Date();
- nodeca.server.users.auth.register.check_nick({ nick: nick }, function(err){
- var $control_group = $elem.parents('.control-group:first');
+ // delay request
+ setTimeout(function() {
- if (err) {
- // Problems with nick
- if (err.statusCode === nodeca.io.BAD_REQUEST) {
- $control_group.addClass('error');
+ // time is not come
+ // new event(s) update start point
+ if (DELAY > new Date() - start_point) {
+ return;
+ }
- $control_group.find('.help-block').text(
- err.message['nick']
- );
+ // reset time
+ start_point = null;
+
+ var nick = $elem.val();
+ nodeca.server.users.auth.register.check_nick({ nick: nick }, function(err){
+ var $control_group = $elem.parents('.control-group:first');
+
+ if (err) {
+ // Problems with nick
+ if (err.statusCode === nodeca.io.BAD_REQUEST) {
+ $control_group.addClass('error');
+
+ $control_group.find('.help-block').text(
+ err.message['nick']
+ );
+ return;
+ }
+
+ // something fatal
+ nodeca.client.common.notify('error', err.message);
return;
}
- // something fatal
- nodeca.client.common.notify('error', err.message);
- return;
- }
+ // no errors -> restore defaults
- // no errors -> restore defaults
+ $control_group.removeClass('error');
+ $control_group.find('.help-block').text(
+ nodeca.runtime.t('users.auth.reg_form.nick_help')
+ );
- $control_group.removeClass('error');
- $control_group.find('.help-block').text(
- nodeca.runtime.t('users.auth.reg_form.nick_help')
- );
-
- });
+ });
+ }, DELAY);
return false;
}; |
a6042a0774c703a338accdbd59898a5a1eb99d05 | app/models/polls.js | app/models/polls.js | 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Vote = new Schema({
ip: String
});
var Options = new Schema({
name: String,
vote: [Vote]
});
var Poll = new Schema({
user: Number,
title: String,
date: Date,
options: [Options]
});
module.exports = mongoose.model('Poll', Poll);
| 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Vote = new Schema({
ip: String
});
var Options = new Schema({
name: String,
votes: [Vote]
});
var Poll = new Schema({
user: Number,
title: String,
hash: String,
date: Date,
votes: Number,
options: [Options]
});
module.exports = mongoose.model('Poll', Poll);
| Modify model for add hash | Modify model for add hash
| JavaScript | mit | mirabalj/voting-camp,mirabalj/voting-camp | ---
+++
@@ -9,13 +9,15 @@
var Options = new Schema({
name: String,
- vote: [Vote]
+ votes: [Vote]
});
var Poll = new Schema({
user: Number,
title: String,
+ hash: String,
date: Date,
+ votes: Number,
options: [Options]
});
|
ebfc5a251e0c8a7524c0cc13d2a5df194a9aa09f | app/props/screen.js | app/props/screen.js | import canvas from 'canvas';
import Game from 'lib/game';
import Prop from 'props/prop';
import Button from 'props/button';
export default class Screen extends Prop {
constructor(cta, label) {
const buttonHeight = 100;
super(0, 0, canvas.width, canvas.height);
this.label = label;
this.button = new Button(
(canvas.height / 2) - (buttonHeight / 2),
200,
buttonHeight,
cta || 'Play',
this.onClick.bind(this)
);
}
onClick() {
const game = new Game();
game.start();
}
renderLabel() {
const fontSize = 32;
const fontX = canvas.width / 2;
const fontY = 50;
canvas.context.font = `${fontSize}px Helvetica`;
canvas.context.textAlign = 'center';
canvas.context.fillStyle = 'constants.COLORS.PROPS';
canvas.context.textBaseline = 'middle';
canvas.context.fillText(this.label, fontX, fontY);
}
render() {
canvas.clear();
this.button.render();
// @TODO: Why cant this go above?
if (this.label) {
console.log('testing...');
this.renderLabel();
}
}
}
| import canvas from 'canvas';
import constants from '_constants';
import Game from 'lib/game';
import Prop from 'props/prop';
import Button from 'props/button';
export default class Screen extends Prop {
constructor(cta, label) {
const buttonHeight = 100;
super(0, 0, canvas.width, canvas.height);
this.label = label;
this.button = new Button(
(canvas.height / 2) - (buttonHeight / 2),
200,
buttonHeight,
cta || 'Play',
this.onClick.bind(this)
);
}
onClick() {
const game = new Game();
game.start();
}
renderLabel() {
const fontSize = 32;
const fontX = canvas.width / 2;
const fontY = 50;
canvas.context.font = `${fontSize}px Helvetica`;
canvas.context.textAlign = 'center';
canvas.context.fillStyle = constants.COLORS.PROPS;
canvas.context.textBaseline = 'middle';
canvas.context.fillText(this.label, fontX, fontY);
}
render() {
canvas.clear();
if (this.label) {
this.renderLabel();
}
this.button.render();
}
}
| Fix label render issue due to typo | Fix label render issue due to typo
| JavaScript | mit | oliverbenns/pong,oliverbenns/pong | ---
+++
@@ -1,4 +1,5 @@
import canvas from 'canvas';
+import constants from '_constants';
import Game from 'lib/game';
import Prop from 'props/prop';
import Button from 'props/button';
@@ -31,7 +32,7 @@
canvas.context.font = `${fontSize}px Helvetica`;
canvas.context.textAlign = 'center';
- canvas.context.fillStyle = 'constants.COLORS.PROPS';
+ canvas.context.fillStyle = constants.COLORS.PROPS;
canvas.context.textBaseline = 'middle';
canvas.context.fillText(this.label, fontX, fontY);
}
@@ -39,13 +40,10 @@
render() {
canvas.clear();
+ if (this.label) {
+ this.renderLabel();
+ }
this.button.render();
-
- // @TODO: Why cant this go above?
- if (this.label) {
- console.log('testing...');
- this.renderLabel();
- }
}
} |
775c4a4ad5a553748804392899ee08ba6c2cc4e5 | src/middleware/auth/processJWTIfExists.js | src/middleware/auth/processJWTIfExists.js | const
nJwt = require('njwt'),
config = require('config.js'),
errors = require('feathers-errors');
function processJWTIfExists (req, res, next) {
req.feathers = req.feathers || {};
let token = req.headers['authorization'];
if (token == null) {
let cookies = req.cookies;
token = cookies.idToken;
}
if (token == null) {
next();
return;
}
const verifiedJwt = nJwt.verify(token, config.jwtSigningKey);
req.feathers.userId = verifiedJwt.body.sub;
next();
}
module.exports = {
processJWTIfExists
};
| const
nJwt = require('njwt'),
config = require('config.js'),
errors = require('feathers-errors');
function processJWTIfExists (req, res, next) {
req.feathers = req.feathers || {};
let token = req.headers['authorization'];
if (token == null) {
let cookies = req.cookies;
token = cookies.idToken;
}
if (token == null) {
next();
return;
}
try {
const verifiedJwt = nJwt.verify(token, config.jwtSigningKey);
req.feathers.userId = verifiedJwt.body.sub;
} catch(e) {
next();
return;
}
next();
}
module.exports = {
processJWTIfExists
};
| Use a catch with the JWT verify function | Use a catch with the JWT verify function
| JavaScript | agpl-3.0 | podverse/podverse-web,podverse/podverse-web,podverse/podverse-web,podverse/podverse-web | ---
+++
@@ -21,8 +21,13 @@
return;
}
- const verifiedJwt = nJwt.verify(token, config.jwtSigningKey);
- req.feathers.userId = verifiedJwt.body.sub;
+ try {
+ const verifiedJwt = nJwt.verify(token, config.jwtSigningKey);
+ req.feathers.userId = verifiedJwt.body.sub;
+ } catch(e) {
+ next();
+ return;
+ }
next();
} |
e7699d278aea82f2b10c07fbd028d35db704de94 | kuulemma/static/app/components/location-map/location-map-directive.js | kuulemma/static/app/components/location-map/location-map-directive.js | (function() {
'use strict';
angular.module('kuulemmaApp').directive('locationMap', function($window) {
return {
restrict: 'A',
scope: {
latitude: '@',
longitude: '@',
polygon: '@'
},
link: function(scope, element) {
var L = $window.L;
var map = L.map(element[0] ,{
zoomControl:false,
scrollWheelZoom: false,
dragging:false,
touchZoom:false,
tap:false,
doubleClickZoom:false,
});
var zoom = 14;
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttribution = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
var osm = new L.TileLayer(osmUrl, {
minzoom: 1,
maxzoom: 15,
attribution: osmAttribution
});
map.setView(new L.LatLng(scope.latitude, scope.longitude), zoom);
map.addLayer(osm);
if (scope.polygon) {
var poly = L.geoJson(JSON.parse(scope.polygon));
poly.addTo(map);
// Center and zoom map
map.fitBounds(poly.getBounds());
}
}
};
});
})();
| (function() {
'use strict';
angular.module('kuulemmaApp').directive('locationMap', function($window) {
return {
restrict: 'A',
scope: {
latitude: '@',
longitude: '@',
polygon: '@'
},
link: function(scope, element) {
var L = $window.L;
var map = L.map(element[0] ,{
zoomControl:false,
scrollWheelZoom: false,
dragging:false,
touchZoom:false,
tap:false,
doubleClickZoom:false,
});
var zoom = 14;
var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttribution = 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
var osm = new L.TileLayer(osmUrl, {
minzoom: 1,
maxzoom: 15,
attribution: osmAttribution
});
map.setView(new L.LatLng(scope.latitude, scope.longitude), zoom);
map.addLayer(osm);
if (scope.polygon) {
var poly = L.geoJson(JSON.parse(scope.polygon));
poly.addTo(map);
// Center and zoom map
map.fitBounds(poly.getBounds());
}
}
};
});
})();
| Use https to load openstreetmap data | Use https to load openstreetmap data
| JavaScript | agpl-3.0 | fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma | ---
+++
@@ -19,8 +19,8 @@
doubleClickZoom:false,
});
var zoom = 14;
- var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
- var osmAttribution = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
+ var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
+ var osmAttribution = 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
var osm = new L.TileLayer(osmUrl, {
minzoom: 1,
maxzoom: 15, |
65d110d813abdd2a039d223c7ddd41a4cc857a8b | server/common/set_language.js | server/common/set_language.js | // Store the preference locale in cookies and (if available) session to use
// on next requests.
'use strict';
var _ = require('lodash');
var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer.
module.exports = function (N, apiPath) {
N.validate(apiPath, {
locale: { type: 'string' }
});
N.wire.on(apiPath, function set_language(env, callback) {
var locale = env.params.locale;
if (!_.contains(N.config.locales.enabled, env.params.locale)) {
// User sent a non-existent or disabled locale - reply with the default.
locale = N.config.locales['default'];
}
env.extras.setCookie('locale', locale, {
path: '/'
, maxAge: LOCALE_COOKIE_MAX_AGE
});
if (env.session) {
env.session.locale = locale;
}
if (env.session && env.session.user_id) {
N.models.users.User.findById(env.session.user_id, function (err, user) {
if (err) {
callback(err);
return;
}
user.locale = locale;
user.save(callback);
});
} else {
callback();
}
});
};
| // Store the preference locale in cookies and (if available) session to use
// on next requests.
'use strict';
var _ = require('lodash');
var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer.
module.exports = function (N, apiPath) {
N.validate(apiPath, {
locale: { type: 'string' }
});
N.wire.on(apiPath, function set_language(env, callback) {
var locale = env.params.locale;
if (!_.contains(N.config.locales.enabled, env.params.locale)) {
// User sent a non-existent or disabled locale - reply with the default.
locale = N.config.locales['default'];
}
env.extras.setCookie('locale', locale, {
path: '/'
, maxAge: LOCALE_COOKIE_MAX_AGE
});
if (env.session) {
env.session.locale = locale;
}
if (env.session && env.session.user_id) {
N.models.users.User.findByIdAndUpdate(env.session.user_id, { locale: locale }, callback);
} else {
callback();
}
});
};
| Simplify updating of locale field in user account. | Simplify updating of locale field in user account.
| JavaScript | mit | nodeca/nodeca.users | ---
+++
@@ -34,15 +34,7 @@
}
if (env.session && env.session.user_id) {
- N.models.users.User.findById(env.session.user_id, function (err, user) {
- if (err) {
- callback(err);
- return;
- }
-
- user.locale = locale;
- user.save(callback);
- });
+ N.models.users.User.findByIdAndUpdate(env.session.user_id, { locale: locale }, callback);
} else {
callback();
} |
a1aca964cc495ddde6401be94cb231810b53598d | src/news/__tests__/ArticlePreview-test.js | src/news/__tests__/ArticlePreview-test.js | import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import ArticlePreview from '../ArticlePreview';
describe('ArticlePreview', () => {
it('should render ArticlePreview component properly', () => {
const wrapper = shallow(<ArticlePreview description="Article Description" title="Article title" />);
expect(wrapper.render().text).to.contain('Article title');
});
});
| import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import ArticlePreview from '../ArticlePreview';
describe('ArticlePreview', () => {
it('should render ArticlePreview component properly', () => {
const wrapper = shallow(<ArticlePreview description="Article Description" title="Article title" />);
expect(wrapper.render().text()).to.contain('Article title');
});
});
| Fix a bug, used .test instead of .test() | Fix a bug, used .test instead of .test()
| JavaScript | mit | qingweibinary/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,qingweibinary/binary-next-gen,qingweibinary/binary-next-gen | ---
+++
@@ -6,6 +6,6 @@
describe('ArticlePreview', () => {
it('should render ArticlePreview component properly', () => {
const wrapper = shallow(<ArticlePreview description="Article Description" title="Article title" />);
- expect(wrapper.render().text).to.contain('Article title');
+ expect(wrapper.render().text()).to.contain('Article title');
});
}); |
64167a5d7eba261f3f6c1b6e223d5f6b855b8df5 | examples/extent-interaction.js | examples/extent-interaction.js | import ExtentInteraction from '../src/ol/interaction/Extent.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson',
format: new GeoJSON(),
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
new VectorLayer({
source: vectorSource,
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const extent = new ExtentInteraction();
map.addInteraction(extent);
extent.setActive(false);
//Enable interaction by holding shift
window.addEventListener('keydown', function (event) {
if (event.keyCode == 16) {
extent.setActive(true);
}
});
window.addEventListener('keyup', function (event) {
if (event.keyCode == 16) {
extent.setActive(false);
}
});
| import ExtentInteraction from '../src/ol/interaction/Extent.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {shiftKeyOnly} from '../src/ol/events/condition.js';
const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson',
format: new GeoJSON(),
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
new VectorLayer({
source: vectorSource,
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const extent = new ExtentInteraction({condition: shiftKeyOnly});
map.addInteraction(extent);
| Use condition instead of setActive and listeners | Use condition instead of setActive and listeners | JavaScript | bsd-2-clause | stweil/ol3,adube/ol3,adube/ol3,openlayers/openlayers,stweil/ol3,oterral/ol3,ahocevar/openlayers,openlayers/openlayers,bjornharrtell/ol3,stweil/openlayers,stweil/ol3,ahocevar/ol3,ahocevar/openlayers,stweil/openlayers,openlayers/openlayers,stweil/openlayers,bjornharrtell/ol3,oterral/ol3,adube/ol3,ahocevar/ol3,ahocevar/openlayers,stweil/ol3,ahocevar/ol3,ahocevar/ol3,oterral/ol3,bjornharrtell/ol3 | ---
+++
@@ -4,6 +4,7 @@
import View from '../src/ol/View.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
+import {shiftKeyOnly} from '../src/ol/events/condition.js';
const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson',
@@ -26,18 +27,5 @@
}),
});
-const extent = new ExtentInteraction();
+const extent = new ExtentInteraction({condition: shiftKeyOnly});
map.addInteraction(extent);
-extent.setActive(false);
-
-//Enable interaction by holding shift
-window.addEventListener('keydown', function (event) {
- if (event.keyCode == 16) {
- extent.setActive(true);
- }
-});
-window.addEventListener('keyup', function (event) {
- if (event.keyCode == 16) {
- extent.setActive(false);
- }
-}); |
26fe7640b6ca46d053d5f9123f21411b3d739c80 | _admin/js/sold_tickets.js | _admin/js/sold_tickets.js | function short_hash(data, type, row, meta)
{
return data.substring(0,8);
}
function init_page()
{
$('#tickets').dataTable({
"ajax": '../api/v1/tickets?filter=sold eq 1 and year eq 2016',
columns: [
{'data': 'hash', 'render':short_hash},
{'data': 'firstName'},
{'data': 'lastName'},
{'data': 'type'}
]
});
}
$(init_page)
| function short_hash(data, type, row, meta)
{
return data.substring(0,8);
}
function init_page()
{
$('#tickets').dataTable({
"ajax": '../api/v1/tickets?filter=sold eq 1 and year eq 2016&fmt=data-table',
columns: [
{'data': 'hash', 'render':short_hash},
{'data': 'firstName'},
{'data': 'lastName'},
{'data': 'type'}
]
});
}
$(init_page)
| Fix new API call for datatable consumer | Fix new API call for datatable consumer
| JavaScript | apache-2.0 | BurningFlipside/Tickets,BurningFlipside/Tickets,BurningFlipside/Tickets | ---
+++
@@ -6,7 +6,7 @@
function init_page()
{
$('#tickets').dataTable({
- "ajax": '../api/v1/tickets?filter=sold eq 1 and year eq 2016',
+ "ajax": '../api/v1/tickets?filter=sold eq 1 and year eq 2016&fmt=data-table',
columns: [
{'data': 'hash', 'render':short_hash},
{'data': 'firstName'}, |
a55246c980e48e3ed4e19a332dbc9178d0cd9265 | static/sprints-new.js | static/sprints-new.js | $(document).ready(function() {
$('select').chosen();
$('input.date').datepicker({
beforeShowDay: $.datepicker.noWeekends
});
$('#save-button').savebutton($('#post-status'), '');
$('#cancel-button').cancelbutton();
});
| $(document).ready(function() {
$('select').chosen();
$('input.date').datepicker({
beforeShowDay: $.datepicker.noWeekends
});
$('#save-button').savebutton($('#post-status'), '');
$('#cancel-button').cancelbutton('/');
});
| Fix cancel button on new sprint page | Fix cancel button on new sprint page
| JavaScript | mit | mrozekma/Sprint,mrozekma/Sprint,mrozekma/Sprint | ---
+++
@@ -5,5 +5,5 @@
});
$('#save-button').savebutton($('#post-status'), '');
- $('#cancel-button').cancelbutton();
+ $('#cancel-button').cancelbutton('/');
}); |
cb87d72a356363cc7350ab3c2c06aeaa1967c846 | src/argsToFindOptions.js | src/argsToFindOptions.js | export default function argsToFindOptions(args, target) {
var result = {}
, targetAttributes = Object.keys(target.rawAttributes);
if (args) {
Object.keys(args).forEach(function (key) {
if (~targetAttributes.indexOf(key)) {
result.where = result.where || {};
result.where[key] = args[key];
}
if (key === 'limit' && args[key]) {
result.limit = args[key];
}
if (key === 'offset' && args[key]) {
result.offset = args[key];
}
if (key === 'order' && args[key]) {
result.order = [
[args[key]]
];
}
});
}
return result;
}
| export default function argsToFindOptions(args, target) {
var result = {}
, targetAttributes = Object.keys(target.rawAttributes);
if (args) {
Object.keys(args).forEach(function (key) {
if (~targetAttributes.indexOf(key)) {
result.where = result.where || {};
result.where[key] = args[key];
}
if (key === 'limit' && args[key]) {
result.limit = args[key];
}
if (key === 'offset' && args[key]) {
result.offset = args[key];
}
if (key === 'order' && args[key]) {
var order;
if (args[key].indexOf('reverse:') === 0) {
order = [args[key].substring(8), 'DESC'];
} else {
order = [args[key], 'ASC'];
}
result.order = [
order
];
}
});
}
return result;
}
| Allow "reverse:fieldname" for a descending sort | Allow "reverse:fieldname" for a descending sort
Closes #42
| JavaScript | mit | idris/graphql-sequelize,mickhansen/graphql-sequelize,janmeier/graphql-sequelize | ---
+++
@@ -18,8 +18,15 @@
}
if (key === 'order' && args[key]) {
+ var order;
+ if (args[key].indexOf('reverse:') === 0) {
+ order = [args[key].substring(8), 'DESC'];
+ } else {
+ order = [args[key], 'ASC'];
+ }
+
result.order = [
- [args[key]]
+ order
];
}
}); |
5b2ecde8e9cf8e4cc6e694ddfb6318ca47b342f5 | lib/mixins/soft-delete.js | lib/mixins/soft-delete.js | 'use strict';
const _ = require('lodash');
module.exports = function (Model, bootOptions = {}) {
Model.defineProperty('deleted', {
type: Boolean,
required: true,
default: false
});
/**
* @return {Promise<Model>}
*/
Model.prototype.softDelete = function () {
return this.updateAttribute('deleted', true);
}
/**
* @return {Promise<Model>}
*/
Model.prototype.restore = function () {
return this.updateAttribute('deleted', false);
}
Model.beforeRemote('find', (ctx, instance, next) => {
const scope = _.get(ctx.args, 'filter.scope', 'active');
_.unset(ctx.args, 'filter.scope');
switch (scope) {
case 'active':
_.set(ctx.args, 'filter.where.deleted', false);
break;
case 'inactive':
_.set(ctx.args, 'filter.where.deleted', true);
break;
default:
_.unset(ctx.args, 'filter.where.deleted');
break;
}
process.nextTick(next);
});
}
| 'use strict';
const _ = require('lodash');
module.exports = function (Model, bootOptions = {}) {
Model.defineProperty('deleted', {
type: Boolean,
required: true,
default: false
});
/**
* @return {Promise<Model>}
*/
Model.prototype.softDelete = function () {
return this.updateAttribute('deleted', true);
}
/**
* @return {Promise<Model>}
*/
Model.prototype.restore = function () {
return this.updateAttribute('deleted', false);
}
Model.beforeRemote('find', (ctx, instance, next) => {
const scope = _.get(ctx.args, 'filter.scope', 'active');
_.unset(ctx.args, 'filter.scope');
switch (scope) {
case 'active':
_.set(ctx.args, 'filter.where.deleted.neq', true);
break;
case 'inactive':
_.set(ctx.args, 'filter.where.deleted', true);
break;
default:
_.unset(ctx.args, 'filter.where.deleted');
break;
}
process.nextTick(next);
});
}
| Use not equal filter instead. | Use not equal filter instead.
| JavaScript | mit | dynamoxteam/loopback-utilities | ---
+++
@@ -28,7 +28,7 @@
_.unset(ctx.args, 'filter.scope');
switch (scope) {
case 'active':
- _.set(ctx.args, 'filter.where.deleted', false);
+ _.set(ctx.args, 'filter.where.deleted.neq', true);
break;
case 'inactive':
_.set(ctx.args, 'filter.where.deleted', true); |
d1bd53c204c816dc0cca0cb3a502d30971ddcbcb | extension/media-control-api.js | extension/media-control-api.js | // Tab registration by MediaControlled event
document.addEventListener("MediaControlled", function () {
chrome.runtime.sendMessage({command: "registerTab"});
});
// Tab unregistration by MediaUncontrolled event
document.addEventListener("MediaUncontrolled", function () {
chrome.runtime.sendMessage({command: "unregisterTab"});
});
// Media Events emmiter
chrome.runtime.onMessage.addListener(function(request) {
switch (request.command) {
case "play-pause":
document.dispatchEvent(new Event("MediaPlayPause"));
break;
case "stop":
document.dispatchEvent(new Event("MediaStop"));
break;
case "prev":
document.dispatchEvent(new Event("MediaPrev"));
break;
case "next":
document.dispatchEvent(new Event("MediaNext"));
break;
}
});
// Tell document that we are ready
console.log('Keysocket Media Control API initialized');
document.dispatchEvent(new Event("MediaControlApiInit"));
// Tab registration by meta tag
if (document.getElementsByName("media-controlled").length > 0) {
chrome.runtime.sendMessage({command: "registerTab"});
}
// Unregister tab before move to another URI
window.onunload = function() {
chrome.runtime.sendMessage({command: "unregisterTab"});
} | // Media Events emmiter
chrome.runtime.onMessage.addListener(function(request) {
switch (request.command) {
case "play-pause":
document.dispatchEvent(new Event("MediaPlayPause"));
break;
case "stop":
document.dispatchEvent(new Event("MediaStop"));
break;
case "prev":
document.dispatchEvent(new Event("MediaPrev"));
break;
case "next":
document.dispatchEvent(new Event("MediaNext"));
break;
}
});
// Tab registration/unregistration by MediaControlStateChanged event
document.addEventListener("MediaControlStateChanged", function () {
registerOrUnregisterPage();
});
// Unregister tab before move to another URI
window.onunload = function() {
chrome.runtime.sendMessage({command: "unregisterTab"});
}
// Initial tab registration by meta tag
registerOrUnregisterPage();
function isPageMediaControllable() {
var tags = document.getElementsByName("media-controllable");
if (tags.length > 0) {
for (var i = 0; i < tags.length; i++) {
if (tags[i].getAttribute("content") !== 'no') {
return true;
}
}
}
return false;
}
function registerOrUnregisterPage() {
chrome.runtime.sendMessage({command: isPageMediaControllable() ? "registerTab" : "unregisterTab"});
} | Support for Web Page Media Control API v0.4 | Support for Web Page Media Control API v0.4
| JavaScript | apache-2.0 | kristianj/keysocket,Whoaa512/keysocket,ALiangLiang/keysocket,borismus/keysocket,chrisdeely/keysocket,feedbee/keysocket,borismus/keysocket,vladikoff/keysocket,iver56/keysocket,kristianj/keysocket,vinyldarkscratch/keysocket,legionaryu/keysocket,vinyldarkscratch/keysocket,feedbee/keysocket | ---
+++
@@ -1,13 +1,3 @@
-// Tab registration by MediaControlled event
-document.addEventListener("MediaControlled", function () {
- chrome.runtime.sendMessage({command: "registerTab"});
-});
-
-// Tab unregistration by MediaUncontrolled event
-document.addEventListener("MediaUncontrolled", function () {
- chrome.runtime.sendMessage({command: "unregisterTab"});
-});
-
// Media Events emmiter
chrome.runtime.onMessage.addListener(function(request) {
switch (request.command) {
@@ -29,16 +19,31 @@
}
});
-// Tell document that we are ready
-console.log('Keysocket Media Control API initialized');
-document.dispatchEvent(new Event("MediaControlApiInit"));
-
-// Tab registration by meta tag
-if (document.getElementsByName("media-controlled").length > 0) {
- chrome.runtime.sendMessage({command: "registerTab"});
-}
+// Tab registration/unregistration by MediaControlStateChanged event
+document.addEventListener("MediaControlStateChanged", function () {
+ registerOrUnregisterPage();
+});
// Unregister tab before move to another URI
window.onunload = function() {
chrome.runtime.sendMessage({command: "unregisterTab"});
}
+
+// Initial tab registration by meta tag
+registerOrUnregisterPage();
+
+function isPageMediaControllable() {
+ var tags = document.getElementsByName("media-controllable");
+ if (tags.length > 0) {
+ for (var i = 0; i < tags.length; i++) {
+ if (tags[i].getAttribute("content") !== 'no') {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+function registerOrUnregisterPage() {
+ chrome.runtime.sendMessage({command: isPageMediaControllable() ? "registerTab" : "unregisterTab"});
+} |
5e93f2da4c204b82c81eacbd86ab6368b67331ca | scripts/collections/quizz-collection.js | scripts/collections/quizz-collection.js | var QuizzCollection = Backbone.Collection.extend({
model: QuizzModel,
url: './data/quizz.json'
});
| var QuizzCollection = Backbone.Collection.extend({
model: QuizzModel,
url: 'http://dcamilleri.com/wsf/api'
});
| Change JSON url to API url | Change JSON url to API url
| JavaScript | mit | KillianKemps/MovieQuizz,KillianKemps/MovieQuizz | ---
+++
@@ -1,4 +1,4 @@
var QuizzCollection = Backbone.Collection.extend({
model: QuizzModel,
- url: './data/quizz.json'
+ url: 'http://dcamilleri.com/wsf/api'
}); |
f4086f9dd9381da2179adc2254b03b81d2e4fbb7 | Smallstache.js | Smallstache.js | function Smallstache(source) {
this.template = source.match(/^[#|\.].*/g) ?
document.querySelector(source) : // source is selector
source; // source is template
}
Smallstache.prototype.render = function(obj) {
return this.template.replace(/{{\s*([\S|^}]+)\s*}}/g,
function(substring, matched) { return obj[matched]; });
};
| function Smallstache(source) {
this.template = source.match(/^[#|\.].*/g) ?
window.document.querySelector(source) : // source is selector
source; // source is template
}
Smallstache.prototype.render = function(obj) {
return this.template.replace(/{{\s*([\S|^}]+)\s*}}/g,
function(substring, matched) { return obj[matched] });
};
module.exports = Smallstache;
| Fix error with module export | Fix error with module export
| JavaScript | mit | macie/smallstache | ---
+++
@@ -1,10 +1,12 @@
function Smallstache(source) {
this.template = source.match(/^[#|\.].*/g) ?
- document.querySelector(source) : // source is selector
+ window.document.querySelector(source) : // source is selector
source; // source is template
}
Smallstache.prototype.render = function(obj) {
return this.template.replace(/{{\s*([\S|^}]+)\s*}}/g,
- function(substring, matched) { return obj[matched]; });
+ function(substring, matched) { return obj[matched] });
};
+
+module.exports = Smallstache; |
ac852a0a4478362ef3ca076fd14bbd048f4bc038 | doc/components/CrossLinkComponent.js | doc/components/CrossLinkComponent.js | 'use strict';
var Component = require('../../ui/Component');
var $$ = Component.$$;
function CrossLinkComponent() {
Component.apply(this, arguments);
}
CrossLinkComponent.Prototype = function() {
this.render = function() {
var doc = this.context.doc;
var nodeId = this.props.nodeId;
var el;
if (nodeId && doc.get(nodeId)) {
el = $$('a').addClass('sc-cross-link')
.attr({
href: '#contextId=toc,nodeId='+nodeId,
"data-type": 'cross-link',
"data-node-id": nodeId
});
} else {
el = $$('span');
}
if (this.props.children) {
el.append(this.props.children);
} else {
el.append(nodeId);
}
return el;
};
};
Component.extend(CrossLinkComponent);
module.exports = CrossLinkComponent;
| 'use strict';
var Component = require('../../ui/Component');
var $$ = Component.$$;
function CrossLinkComponent() {
Component.apply(this, arguments);
}
CrossLinkComponent.Prototype = function() {
this.render = function() {
var doc = this.context.doc;
var nodeId = this.props.nodeId;
var el;
if (nodeId && doc.get(nodeId)) {
el = $$('a').addClass('sc-cross-link')
.attr({
href: '#contextId=toc,nodeId='+nodeId,
"data-type": 'cross-link',
"data-node-id": nodeId
});
} else {
el = $$('span');
}
if (this.props.children.length > 0) {
el.append(this.props.children);
} else {
el.append(nodeId);
}
return el;
};
};
Component.extend(CrossLinkComponent);
module.exports = CrossLinkComponent;
| Fix display of return type. | Fix display of return type.
| JavaScript | mit | TypesetIO/substance,andene/substance,TypesetIO/substance,abhaga/substance,michael/substance-1,stencila/substance,substance/substance,andene/substance,michael/substance-1,substance/substance,jacwright/substance,abhaga/substance,podviaznikov/substance,podviaznikov/substance,jacwright/substance | ---
+++
@@ -22,7 +22,7 @@
} else {
el = $$('span');
}
- if (this.props.children) {
+ if (this.props.children.length > 0) {
el.append(this.props.children);
} else {
el.append(nodeId); |
a9661d03d234101bd51d8fd66ddab653797c4543 | lib/isomorphic/gatsby-helpers.js | lib/isomorphic/gatsby-helpers.js | import { config } from 'config'
import invariant from 'invariant'
import isString from 'lodash/isString'
function isDataURL (s) {
// Regex from https://gist.github.com/bgrins/6194623#gistcomment-1671744
// eslint-disable-next-line max-len
const regex = /^\s*data:([a-z]+\/[a-z0-9\-\+]+(;[a-z\-]+=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9!\$&',\(\)\*\+,;=\-\._~:@\/\?%\s]*\s*$/i
return !!s.match(regex)
}
// Function to add prefix to links.
const prefixLink = (_link) => {
if (
(typeof __PREFIX_LINKS__ !== 'undefined' && __PREFIX_LINKS__ !== null)
&& __PREFIX_LINKS__ && (config.linkPrefix !== null
)) {
const invariantMessage = `
You're trying to build your site with links prefixed
but you haven't set 'linkPrefix' in your config.toml.
`
invariant(isString(config.linkPrefix), invariantMessage)
return isDataURL(_link) ? _link : config.linkPrefix + _link
} else {
return _link
}
}
module.exports = {
prefixLink,
}
| import { config } from 'config'
import invariant from 'invariant'
import isString from 'lodash/isString'
import path from 'path'
function isDataURL (s) {
// Regex from https://gist.github.com/bgrins/6194623#gistcomment-1671744
// eslint-disable-next-line max-len
const regex = /^\s*data:([a-z]+\/[a-z0-9\-\+]+(;[a-z\-]+=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9!\$&',\(\)\*\+,;=\-\._~:@\/\?%\s]*\s*$/i
return !!s.match(regex)
}
// Function to add prefix to links.
const prefixLink = (_link) => {
if (
(typeof __PREFIX_LINKS__ !== 'undefined' && __PREFIX_LINKS__ !== null)
&& __PREFIX_LINKS__ && (config.linkPrefix !== null
)) {
const invariantMessage = `
You're trying to build your site with links prefixed
but you haven't set 'linkPrefix' in your config.toml.
`
invariant(isString(config.linkPrefix), invariantMessage)
return isDataURL(_link) ? _link : path.join(config.linkPrefix, _link)
} else {
return _link
}
}
module.exports = {
prefixLink,
}
| Use path.join for link prefixing | Use path.join for link prefixing
| JavaScript | mit | mingaldrichgan/gatsby,mingaldrichgan/gatsby,gatsbyjs/gatsby,fabrictech/gatsby,rothfels/gatsby,gatsbyjs/gatsby,okcoker/gatsby,Khaledgarbaya/gatsby,ChristopherBiscardi/gatsby,danielfarrell/gatsby,fk/gatsby,ChristopherBiscardi/gatsby,gatsbyjs/gatsby,Khaledgarbaya/gatsby,rothfels/gatsby,0x80/gatsby,chiedo/gatsby,okcoker/gatsby,mickeyreiss/gatsby,mickeyreiss/gatsby,mingaldrichgan/gatsby,fk/gatsby,Khaledgarbaya/gatsby,0x80/gatsby,fabrictech/gatsby,mickeyreiss/gatsby,ChristopherBiscardi/gatsby,gatsbyjs/gatsby,0x80/gatsby,okcoker/gatsby,danielfarrell/gatsby,fk/gatsby,chiedo/gatsby,chiedo/gatsby,gatsbyjs/gatsby,gatsbyjs/gatsby,fabrictech/gatsby,danielfarrell/gatsby,ChristopherBiscardi/gatsby | ---
+++
@@ -1,6 +1,7 @@
import { config } from 'config'
import invariant from 'invariant'
import isString from 'lodash/isString'
+import path from 'path'
function isDataURL (s) {
// Regex from https://gist.github.com/bgrins/6194623#gistcomment-1671744
@@ -21,7 +22,7 @@
`
invariant(isString(config.linkPrefix), invariantMessage)
- return isDataURL(_link) ? _link : config.linkPrefix + _link
+ return isDataURL(_link) ? _link : path.join(config.linkPrefix, _link)
} else {
return _link
} |
dd81193bee7b57d2ff7c2f604a4ff37d629713bc | app/js/arethusa.core/dependency_loader.js | app/js/arethusa.core/dependency_loader.js | "use strict";
angular.module('arethusa.core').service('dependencyLoader', [
'$ocLazyLoad',
'$q',
'basePath',
function($ocLazyLoad, $q, basePath) {
function expand(p) {
return basePath.path + '/' + p;
}
function expandPath(path) {
var res = [];
if (angular.isArray(path)) {
return aU.map(path, expand);
} else {
if (angular.isString(path)) {
return expand(path);
} else {
var files = aU.map(path.files, expand);
path.files = files;
return path;
}
}
}
this.load = function(args) {
return $ocLazyLoad.load(expandPath(args));
};
this.loadInOrder = function(args) {
var start = $q.defer();
var promises = [start.promise];
angular.forEach(args, function(el, i) {
var deferred = $q.defer();
promises.push(deferred.promise);
promises[i].then(function() {
$ocLazyLoad.load(expandPath(el))['finally'](aU.resolveFn(deferred));
});
});
start.resolve();
return aU.last(promises);
};
}
]);
| "use strict";
angular.module('arethusa.core').service('dependencyLoader', [
'$ocLazyLoad',
'$q',
'basePath',
function($ocLazyLoad, $q, basePath) {
function expand(p) {
if (aU.isUrl(p)) {
return p;
} else {
return basePath.path + '/' + p;
}
}
function expandPath(path) {
var res = [];
if (angular.isArray(path)) {
return aU.map(path, expand);
} else {
if (angular.isString(path)) {
return expand(path);
} else {
var files = aU.map(path.files, expand);
path.files = files;
return path;
}
}
}
this.load = function(args) {
return $ocLazyLoad.load(expandPath(args));
};
this.loadInOrder = function(args) {
var start = $q.defer();
var promises = [start.promise];
angular.forEach(args, function(el, i) {
var deferred = $q.defer();
promises.push(deferred.promise);
promises[i].then(function() {
$ocLazyLoad.load(expandPath(el))['finally'](aU.resolveFn(deferred));
});
});
start.resolve();
return aU.last(promises);
};
}
]);
| Fix path handling in dependencyLoader | Fix path handling in dependencyLoader
| JavaScript | mit | fbaumgardt/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa,PonteIneptique/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa | ---
+++
@@ -6,7 +6,11 @@
'basePath',
function($ocLazyLoad, $q, basePath) {
function expand(p) {
- return basePath.path + '/' + p;
+ if (aU.isUrl(p)) {
+ return p;
+ } else {
+ return basePath.path + '/' + p;
+ }
}
function expandPath(path) {
var res = []; |
98ec5b6d04acd5410c71f84a4187c9ca7425defd | app/scripts/components/player-reaction.js | app/scripts/components/player-reaction.js | import m from 'mithril';
import classNames from '../classnames.js';
class PlayerReactionComponent {
oninit({ attrs: { session, player } }) {
session.on('send-reaction', ({ reactingPlayer, reaction }) => {
if (reactingPlayer.color === player.color) {
// Immediately update the reaction if another reaction was sent before
// the current reaction disappears
clearTimeout(player.reaction ? player.reaction.timer : null);
player.reaction = reaction;
// The reaction should disappear after the specified duration
player.reaction.timer = setTimeout(() => {
player.reaction.timer = null;
m.redraw();
}, PlayerReactionComponent.reactionDuration);
m.redraw();
}
});
}
view({ attrs: { player } }) {
return m('div.player-reaction', m('div.player-reaction-symbol', {
class: classNames({ 'show': player.reaction && player.reaction.timer })
}, player.reaction ? player.reaction.symbol : null));
}
}
// The duration a reaction is shown before disappearing
PlayerReactionComponent.reactionDuration = 1500;
export default PlayerReactionComponent;
| import m from 'mithril';
import classNames from '../classnames.js';
class PlayerReactionComponent {
oninit({ attrs: { session, player } }) {
this.player = player;
session.on('send-reaction', ({ reactingPlayer, reaction }) => {
if (reactingPlayer.color === this.player.color) {
// Immediately update the reaction if another reaction was sent before
// the current reaction disappears
clearTimeout(this.player.reaction ? this.player.reaction.timer : null);
this.player.reaction = reaction;
// The reaction should disappear after the specified duration
this.player.reaction.timer = setTimeout(() => {
this.player.reaction.timer = null;
m.redraw();
}, PlayerReactionComponent.reactionDuration);
m.redraw();
}
});
}
// The oninit() call (and therefore the send-reaction listener) only runs once
// for the lifetime of this component instance, however the player object may
// change during that time, so we need to ensure the above listener has an
// dynamic reference to the freshest instance of the player
onupdate({ attrs: { player } }) {
this.player = player;
}
view({ attrs: { player } }) {
return m('div.player-reaction', m('div.player-reaction-symbol', {
class: classNames({ 'show': player.reaction && player.reaction.timer })
}, player.reaction ? player.reaction.symbol : null));
}
}
// The duration a reaction is shown before disappearing
PlayerReactionComponent.reactionDuration = 1500;
export default PlayerReactionComponent;
| Fix bug where reactions would break after starting new game | Fix bug where reactions would break after starting new game
| JavaScript | mit | caleb531/connect-four | ---
+++
@@ -4,20 +4,29 @@
class PlayerReactionComponent {
oninit({ attrs: { session, player } }) {
+ this.player = player;
session.on('send-reaction', ({ reactingPlayer, reaction }) => {
- if (reactingPlayer.color === player.color) {
+ if (reactingPlayer.color === this.player.color) {
// Immediately update the reaction if another reaction was sent before
// the current reaction disappears
- clearTimeout(player.reaction ? player.reaction.timer : null);
- player.reaction = reaction;
+ clearTimeout(this.player.reaction ? this.player.reaction.timer : null);
+ this.player.reaction = reaction;
// The reaction should disappear after the specified duration
- player.reaction.timer = setTimeout(() => {
- player.reaction.timer = null;
+ this.player.reaction.timer = setTimeout(() => {
+ this.player.reaction.timer = null;
m.redraw();
}, PlayerReactionComponent.reactionDuration);
m.redraw();
}
});
+ }
+
+ // The oninit() call (and therefore the send-reaction listener) only runs once
+ // for the lifetime of this component instance, however the player object may
+ // change during that time, so we need to ensure the above listener has an
+ // dynamic reference to the freshest instance of the player
+ onupdate({ attrs: { player } }) {
+ this.player = player;
}
view({ attrs: { player } }) { |
7be6e466152261159d1b6971ba231fc32464fc10 | app/ui/browser/model/shared-prop-types.js | app/ui/browser/model/shared-prop-types.js | /*
Copyright 2016 Mozilla
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
import { PropTypes } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import * as Model from './index';
export const Page = PropTypes.instanceOf(Model.Page);
export const Pages = ImmutablePropTypes.listOf(Page.isRequired);
| /*
Copyright 2016 Mozilla
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
import { PropTypes } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import * as Model from './index';
export const Page = PropTypes.instanceOf(Model.Page);
export const Pages = ImmutablePropTypes.listOf(Page.isRequired);
export const Profile = PropTypes.instanceOf(Model.Profile);
export const Profiles = ImmutablePropTypes.listOf(Profile.isRequired);
| Add shared immutable prop types for Profile models | Add shared immutable prop types for Profile models
Signed-off-by: Victor Porof <7d8eebacd0931807085fa6b9af29638ed74e0886@mozilla.com>
| JavaScript | apache-2.0 | jsantell/tofino,mozilla/tofino,mozilla/tofino,jsantell/tofino,bgrins/tofino,victorporof/tofino,jsantell/tofino,victorporof/tofino,bgrins/tofino,mozilla/tofino,bgrins/tofino,bgrins/tofino,mozilla/tofino,jsantell/tofino | ---
+++
@@ -16,3 +16,6 @@
export const Page = PropTypes.instanceOf(Model.Page);
export const Pages = ImmutablePropTypes.listOf(Page.isRequired);
+
+export const Profile = PropTypes.instanceOf(Model.Profile);
+export const Profiles = ImmutablePropTypes.listOf(Profile.isRequired); |
5ca8e5f6c57387af132f56bd997a06ab60bfe01e | test/test-creation.js | test/test-creation.js | /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('ink generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('ink:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
'someOption': true
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
| /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('ink generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('ink:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'package.json',
'bower.json',
'app',
'app/index.html',
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
'someOption': true
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
| Update test to check all files created | Update test to check all files created
| JavaScript | mit | rogeriopvl/generator-ink,rogeriopvl/generator-ink | ---
+++
@@ -22,6 +22,10 @@
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
+ 'package.json',
+ 'bower.json',
+ 'app',
+ 'app/index.html',
'.jshintrc',
'.editorconfig'
]; |
edb34ca791f133d22d27e00106e7351965c37152 | lints/disallowImportingNonSharedCodeRule.js | lints/disallowImportingNonSharedCodeRule.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Lint = require("tslint");
class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile) {
if (sourceFile.fileName.indexOf("src/debug/") === -1) {
return this.applyWithWalker(new NoNonSharedCode(sourceFile, this.getOptions()));
}
}
}
Rule.DEBUG_FAILURE_STRING = "Do not import debugger code because it is expected to run in another process.";
Rule.EXTENSION_FAILURE_STRING = "Do not import extension code because the extension packing will mean duplicate definitions and state.";
class NoNonSharedCode extends Lint.RuleWalker {
visitImportDeclaration(node) {
// TODO: Remove first part of this condition when DAs are not running in process.
// https://github.com/Dart-Code/Dart-Code/issues/1876
if (this.sourceFile.fileName.indexOf("debug_config_provider") === -1
&& node.moduleSpecifier.text.indexOf("../debug/") !== -1) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.DEBUG_FAILURE_STRING));
}
if (node.moduleSpecifier.text.indexOf("../extension/") !== -1) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.EXTENSION_FAILURE_STRING));
}
}
}
exports.Rule = Rule;
| "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Lint = require("tslint");
class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile) {
return this.applyWithWalker(new NoNonSharedCode(sourceFile, this.getOptions()));
}
}
Rule.DEBUG_FAILURE_STRING = "Do not import debugger code because it is expected to run in another process.";
Rule.EXTENSION_FAILURE_STRING = "Do not import extension code because the extension packing will mean duplicate definitions and state.";
class NoNonSharedCode extends Lint.RuleWalker {
visitImportDeclaration(node) {
// TODO: Remove first part of this condition when DAs are not running in process.
// https://github.com/Dart-Code/Dart-Code/issues/1876
if (this.sourceFile.fileName.indexOf("debug_config_provider") === -1
&& node.moduleSpecifier.text.indexOf("../debug/") !== -1) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.DEBUG_FAILURE_STRING));
}
if (node.moduleSpecifier.text.indexOf("../extension/") !== -1) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.EXTENSION_FAILURE_STRING));
}
}
}
exports.Rule = Rule;
| Enable more linting for shared imports | Enable more linting for shared imports
| JavaScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -6,9 +6,7 @@
class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile) {
- if (sourceFile.fileName.indexOf("src/debug/") === -1) {
- return this.applyWithWalker(new NoNonSharedCode(sourceFile, this.getOptions()));
- }
+ return this.applyWithWalker(new NoNonSharedCode(sourceFile, this.getOptions()));
}
}
Rule.DEBUG_FAILURE_STRING = "Do not import debugger code because it is expected to run in another process."; |
f85e476263ffad5ce682ff40faa4979a8facf820 | app/assets/javascripts/tagger/functions/setupDisplayFieldsEducation.js | app/assets/javascripts/tagger/functions/setupDisplayFieldsEducation.js |
function setupDisplayFieldsEducationTab(TempObject, selectBox){
// This code is needed to merge the multiselect field and the "other" input field per
if (typeof TempObject[selectBox] != 'undefined') {
if (TempObject[selectBox] != "") {
var optionsToSelect = TempObject[selectBox];
var select = document.getElementById( [selectBox] );
for ( var i = 0, l = select.options.length, o; i < l; i++ ){
o = select.options[i];
var tempO = o;
if ( optionsToSelect.toLowerCase().indexOf( tempO.text.toLowerCase() ) != -1 ) {
o.selected = true;
optionsToSelect = optionsToSelect.replace(o.text,"");
optionsToSelect = optionsToSelect.replace(/,,/g,",");
optionsToSelect = optionsToSelect.replace(/^,/g,"");
}
else document.getElementById( [selectBox]+'Other' ).value = optionsToSelect;
}
}
}
}
| // Take the comma separated list for {field} from {item}.{field} and populate the select#{field} box
// Any of the values in the comma separated list for {field} that doesn't have an option in select#{field}
// Get stuffed into {field}Other as it's own comma separated list.
function setupDisplayFieldsEducationTab(item, field) {
if (item[field] != '' && $('select#'+field)[0] != undefined) {
var itemOptions = item[field].split(',');
$('select#'+field+' option').each(function() {
if ($.inArray($(this).val(),itemOptions) !== -1) {
$(this).attr('selected',true);
}
});
var selectOptions = $('select#'+field+' option').map(function() { return this.value });
var otherOptions = [];
for (i in itemOptions) {
if ($.inArray(itemOptions[i], selectOptions) === -1) {
otherOptions.push(itemOptions[i]);
}
}
if (otherOptions.length > 0) {
$('#'+field+'Other').attr('value',otherOptions.join(','));
}
}
}
| Refactor of comma separated list to selectbox & other inputs. | Refactor of comma separated list to selectbox & other inputs.
| JavaScript | apache-2.0 | inbloom/APP-tagger,inbloom/APP-tagger | ---
+++
@@ -1,21 +1,23 @@
-
-function setupDisplayFieldsEducationTab(TempObject, selectBox){
- // This code is needed to merge the multiselect field and the "other" input field per
- if (typeof TempObject[selectBox] != 'undefined') {
- if (TempObject[selectBox] != "") {
- var optionsToSelect = TempObject[selectBox];
- var select = document.getElementById( [selectBox] );
- for ( var i = 0, l = select.options.length, o; i < l; i++ ){
- o = select.options[i];
- var tempO = o;
- if ( optionsToSelect.toLowerCase().indexOf( tempO.text.toLowerCase() ) != -1 ) {
- o.selected = true;
- optionsToSelect = optionsToSelect.replace(o.text,"");
- optionsToSelect = optionsToSelect.replace(/,,/g,",");
- optionsToSelect = optionsToSelect.replace(/^,/g,"");
- }
- else document.getElementById( [selectBox]+'Other' ).value = optionsToSelect;
+// Take the comma separated list for {field} from {item}.{field} and populate the select#{field} box
+// Any of the values in the comma separated list for {field} that doesn't have an option in select#{field}
+// Get stuffed into {field}Other as it's own comma separated list.
+function setupDisplayFieldsEducationTab(item, field) {
+ if (item[field] != '' && $('select#'+field)[0] != undefined) {
+ var itemOptions = item[field].split(',');
+ $('select#'+field+' option').each(function() {
+ if ($.inArray($(this).val(),itemOptions) !== -1) {
+ $(this).attr('selected',true);
}
+ });
+ var selectOptions = $('select#'+field+' option').map(function() { return this.value });
+ var otherOptions = [];
+ for (i in itemOptions) {
+ if ($.inArray(itemOptions[i], selectOptions) === -1) {
+ otherOptions.push(itemOptions[i]);
+ }
+ }
+ if (otherOptions.length > 0) {
+ $('#'+field+'Other').attr('value',otherOptions.join(','));
}
}
} |
3a2c496d5d65d9e8dd01a09f03123b9b63853400 | src/pages/index.js | src/pages/index.js | import React from 'react'
import EventBets from '../templates/event-bets'
import EventHeading from '../templates/event-heading'
import styles from './index.module.styl'
export default ({ data }) => (
<ol className={styles['events-list']}>
{
data.allMongodbPlacardDevEvents.edges.map(({ node }, idx) => (
<li key={idx} className={styles['event-item']}>
<EventHeading event={node} />
<EventBets betTypes={node.betTypes} />
</li>
))
}
</ol>
)
export const query = graphql`
query EventsListQuery($sport: String, $country: String, $skip: Int = 0, $limit: Int = 20) {
allMongodbPlacardDevEvents(
filter: { sport: { eq: $sport }, country: { eq: $country } },
sort: { fields: [date], order: ASC },
skip: $skip,
limit: $limit
) {
edges {
node {
code
home
away
date
sport
country
competition
betTypes {
name
options {
name
value
}
}
}
}
}
}
`
| import React from 'react'
import EventBets from '../templates/event-bets'
import EventHeading from '../templates/event-heading'
import styles from './index.module.styl'
export default ({ data }) => (
<ol className={styles['events-list']}>
{
data.allMongodbPlacardDevEvents.edges.map(({ node }, idx) => (
<li key={idx} className={styles['event-item']}>
<EventHeading event={node} />
<EventBets betTypes={node.betTypes} />
</li>
))
}
</ol>
)
export const query = graphql`
query EventsListQuery($sport: String, $country: String, $skip: Int = 0, $limit: Int = 10) {
allMongodbPlacardDevEvents(
filter: { sport: { eq: $sport }, country: { eq: $country } },
sort: { fields: [date], order: ASC },
skip: $skip,
limit: $limit
) {
edges {
node {
code
home
away
date
sport
country
competition
betTypes {
name
options {
name
value
}
}
}
}
}
}
`
| Set default page size to 10 events. | Set default page size to 10 events.
| JavaScript | mit | LuisLoureiro/placard-wrapper | ---
+++
@@ -19,7 +19,7 @@
)
export const query = graphql`
- query EventsListQuery($sport: String, $country: String, $skip: Int = 0, $limit: Int = 20) {
+ query EventsListQuery($sport: String, $country: String, $skip: Int = 0, $limit: Int = 10) {
allMongodbPlacardDevEvents(
filter: { sport: { eq: $sport }, country: { eq: $country } },
sort: { fields: [date], order: ASC }, |
1d8de6175eb5405f3e1d316cb8ba65f70791f45f | src/main.js | src/main.js | 'use babel'
export const compiler = false
export const minifier = false
export function process(contents) {
const chunks = contents.split(/\r?\n/)
if (chunks[chunks.length - 1] !== '') {
chunks.push('')
}
return chunks.join('\n')
}
| 'use babel'
import Path from 'path'
import {rollup} from 'rollup'
import {requireDependency} from './helpers'
export const preprocessor = true
export const compiler = false
export const minifier = false
export function process(contents, {rootDirectory, filePath, config, state}) {
const plugins = []
plugins.push(requireDependency('memory', rootDirectory)({
contents: contents,
path: filePath
}))
const rollupConfig = config.rollup || {}
if (typeof config.rollup === 'object' && config.rollup) {
if (rollupConfig.npm === true) {
plugins.push(requireDependency('npm', rootDirectory)({
jsnext: true,
main: true,
builtins: false,
extensions: [ '.js', '.json' ]
}))
}
if (rollupConfig.commonjs === true) {
plugins.push(requireDependency('commonjs', rootDirectory)())
}
if (typeof rollupConfig.plugins === 'object' && rollupConfig.plugins) {
for (const name in rollupConfig.plugins) {
const value = rollupConfig[name]
if (typeof value === 'object' && value) {
plugins.push(requireDependency(name, rootDirectory)(value))
}
}
}
}
return rollup({
entry: '__file__',
plugins: plugins
}).then(function(results) {
const generated = results.generate({
format: rollupConfig.format || 'cjs',
sourceMap: true
})
generated.map.sources = generated.map.sources.map(function(mapPath) {
return Path.relative(rootDirectory, mapPath)
})
results.modules.forEach(function(module) {
const modulePath = module.id
if (modulePath !== filePath) {
state.imports.push(modulePath)
}
})
return {
contents: generated.code,
sourceMap: generated.map
}
})
}
| Implement proper plugins, resolution and maps support | :new: Implement proper plugins, resolution and maps support
| JavaScript | mit | steelbrain/ucompiler-plugin-rollup | ---
+++
@@ -1,11 +1,65 @@
'use babel'
+import Path from 'path'
+import {rollup} from 'rollup'
+import {requireDependency} from './helpers'
+
+export const preprocessor = true
export const compiler = false
export const minifier = false
-export function process(contents) {
- const chunks = contents.split(/\r?\n/)
- if (chunks[chunks.length - 1] !== '') {
- chunks.push('')
+
+export function process(contents, {rootDirectory, filePath, config, state}) {
+ const plugins = []
+
+ plugins.push(requireDependency('memory', rootDirectory)({
+ contents: contents,
+ path: filePath
+ }))
+
+ const rollupConfig = config.rollup || {}
+ if (typeof config.rollup === 'object' && config.rollup) {
+ if (rollupConfig.npm === true) {
+ plugins.push(requireDependency('npm', rootDirectory)({
+ jsnext: true,
+ main: true,
+ builtins: false,
+ extensions: [ '.js', '.json' ]
+ }))
+ }
+ if (rollupConfig.commonjs === true) {
+ plugins.push(requireDependency('commonjs', rootDirectory)())
+ }
+
+ if (typeof rollupConfig.plugins === 'object' && rollupConfig.plugins) {
+ for (const name in rollupConfig.plugins) {
+ const value = rollupConfig[name]
+ if (typeof value === 'object' && value) {
+ plugins.push(requireDependency(name, rootDirectory)(value))
+ }
+ }
+ }
}
- return chunks.join('\n')
+
+ return rollup({
+ entry: '__file__',
+ plugins: plugins
+ }).then(function(results) {
+ const generated = results.generate({
+ format: rollupConfig.format || 'cjs',
+ sourceMap: true
+ })
+ generated.map.sources = generated.map.sources.map(function(mapPath) {
+ return Path.relative(rootDirectory, mapPath)
+ })
+ results.modules.forEach(function(module) {
+ const modulePath = module.id
+ if (modulePath !== filePath) {
+ state.imports.push(modulePath)
+ }
+ })
+ return {
+ contents: generated.code,
+ sourceMap: generated.map
+ }
+ })
} |
26c3cdec1c2eb9b39372da02e292d401e4eada6e | tests/WestleyTests.js | tests/WestleyTests.js | var lib = require("__buttercup/module.js"),
Westley = lib.Westley;
module.exports = {
setUp: function(cb) {
this.westley = new Westley();
(cb)();
},
_getCommandForName: {
cachesCommandWhenCalledTwice: function(test) {
var testCommandKey = 'tgr';
var firstCall = this.westley._getCommandForKey(testCommandKey),
secondCall = this.westley._getCommandForKey(testCommandKey);
firstCall.randomvariable = 'bla';
test.strictEqual(firstCall.randomvariable, secondCall.randomvariable, "Randomly assigned variable is the same for both instances");
test.done();
},
cachesCommandWhenCalledThrice: function(test) {
var testCommandKey = 'tgr';
var firstCall = this.westley._getCommandForKey(testCommandKey),
secondCall = this.westley._getCommandForKey(testCommandKey),
thirdCall = this.westley._getCommandForKey(testCommandKey);
firstCall.randomvariable = 'bla';
test.strictEqual(firstCall.randomvariable, secondCall.randomvariable, "Randomly assigned variable is the same for first and second instance");
test.strictEqual(firstCall.randomvariable, thirdCall.randomvariable, "Randomly assigned variable is the same for first and third instance");
test.strictEqual(secondCall.randomvariable, thirdCall.randomvariable, "Randomly assigned variable is the same for second and third instance");
test.done();
}
}
};
| var lib = require("__buttercup/module.js"),
Westley = lib.Westley;
module.exports = {
setUp: function(cb) {
this.westley = new Westley();
(cb)();
},
_getCommandForName: {
cachesCommandWhenCalledTwice: function(test) {
var testCommandKey = 'tgr';
var firstCall = this.westley._getCommandForKey(testCommandKey),
secondCall = this.westley._getCommandForKey(testCommandKey);
firstCall.randomvariable = 'bla';
test.strictEqual(firstCall.randomvariable,
secondCall.randomvariable,
"Randomly assigned variable is the same for both instances");
test.done();
},
cachesCommandWhenCalledThrice: function(test) {
var testCommandKey = 'tgr';
var firstCall = this.westley._getCommandForKey(testCommandKey),
secondCall = this.westley._getCommandForKey(testCommandKey),
thirdCall = this.westley._getCommandForKey(testCommandKey);
firstCall.randomvariable = 'bla';
test.strictEqual(firstCall.randomvariable,
secondCall.randomvariable,
"Randomly assigned variable is the same for first and second instance");
test.strictEqual(firstCall.randomvariable,
thirdCall.randomvariable,
"Randomly assigned variable is the same for first and third instance");
test.strictEqual(secondCall.randomvariable,
thirdCall.randomvariable,
"Randomly assigned variable is the same for second and third instance");
test.done();
}
}
};
| Correct indentation in westley tests | Correct indentation in westley tests
| JavaScript | mit | buttercup-pw/buttercup-core,buttercup-pw/buttercup-core,perry-mitchell/buttercup-core,buttercup/buttercup-core,perry-mitchell/buttercup-core,buttercup/buttercup-core,buttercup/buttercup-core | ---
+++
@@ -1,42 +1,54 @@
var lib = require("__buttercup/module.js"),
- Westley = lib.Westley;
+ Westley = lib.Westley;
module.exports = {
- setUp: function(cb) {
- this.westley = new Westley();
- (cb)();
- },
-
- _getCommandForName: {
-
- cachesCommandWhenCalledTwice: function(test) {
- var testCommandKey = 'tgr';
-
- var firstCall = this.westley._getCommandForKey(testCommandKey),
- secondCall = this.westley._getCommandForKey(testCommandKey);
-
- firstCall.randomvariable = 'bla';
-
- test.strictEqual(firstCall.randomvariable, secondCall.randomvariable, "Randomly assigned variable is the same for both instances");
- test.done();
+ setUp: function(cb) {
+ this.westley = new Westley();
+ (cb)();
},
- cachesCommandWhenCalledThrice: function(test) {
- var testCommandKey = 'tgr';
+ _getCommandForName: {
- var firstCall = this.westley._getCommandForKey(testCommandKey),
- secondCall = this.westley._getCommandForKey(testCommandKey),
- thirdCall = this.westley._getCommandForKey(testCommandKey);
+ cachesCommandWhenCalledTwice: function(test) {
+ var testCommandKey = 'tgr';
- firstCall.randomvariable = 'bla';
+ var firstCall = this.westley._getCommandForKey(testCommandKey),
+ secondCall = this.westley._getCommandForKey(testCommandKey);
- test.strictEqual(firstCall.randomvariable, secondCall.randomvariable, "Randomly assigned variable is the same for first and second instance");
- test.strictEqual(firstCall.randomvariable, thirdCall.randomvariable, "Randomly assigned variable is the same for first and third instance");
- test.strictEqual(secondCall.randomvariable, thirdCall.randomvariable, "Randomly assigned variable is the same for second and third instance");
- test.done();
+ firstCall.randomvariable = 'bla';
+
+ test.strictEqual(firstCall.randomvariable,
+ secondCall.randomvariable,
+ "Randomly assigned variable is the same for both instances");
+
+ test.done();
+ },
+
+ cachesCommandWhenCalledThrice: function(test) {
+ var testCommandKey = 'tgr';
+
+ var firstCall = this.westley._getCommandForKey(testCommandKey),
+ secondCall = this.westley._getCommandForKey(testCommandKey),
+ thirdCall = this.westley._getCommandForKey(testCommandKey);
+
+ firstCall.randomvariable = 'bla';
+
+ test.strictEqual(firstCall.randomvariable,
+ secondCall.randomvariable,
+ "Randomly assigned variable is the same for first and second instance");
+
+ test.strictEqual(firstCall.randomvariable,
+ thirdCall.randomvariable,
+ "Randomly assigned variable is the same for first and third instance");
+
+ test.strictEqual(secondCall.randomvariable,
+ thirdCall.randomvariable,
+ "Randomly assigned variable is the same for second and third instance");
+
+ test.done();
+ }
+
}
- }
-
}; |
0458137ee581e7b9ae4b63496c760fd964099271 | generators/app/templates/api/policies/isAuthenticated.js | generators/app/templates/api/policies/isAuthenticated.js | /**
* isAuthenticated
* @description :: Policy that inject user in `req` via JSON Web Token
*/
var passport = require('passport');
module.exports = function (req, res, next) {
passport.authenticate('jwt', function (error, user, info) {
if (error) return res.serverError(error);
if (!user) return res.unauthorized(null, info && info.code, info && info.message);
req.user = user;
next();
})(req, res);
};
| /**
* isAuthenticated
* @description :: Policy that inject user in `req` via JSON Web Token
*/
var _ = require('lodash');
var passport = require('passport');
module.exports = function (req, res, next) {
passport.authenticate('jwt', function (error, user, info) {
if (error || !user) return res.negotiate(_.assign(error || {}, info));
req.user = user;
next();
})(req, res);
};
| Fix policy for new responses | Fix policy for new responses
| JavaScript | mit | konstantinzolotarev/generator-trails,italoag/generator-sails-rest-api,ghaiklor/generator-sails-rest-api,tnunes/generator-trails,italoag/generator-sails-rest-api,eithewliter5518/generator-sails-rest-api,ghaiklor/generator-sails-rest-api,IncoCode/generator-sails-rest-api,jaumard/generator-trails | ---
+++
@@ -3,12 +3,12 @@
* @description :: Policy that inject user in `req` via JSON Web Token
*/
+var _ = require('lodash');
var passport = require('passport');
module.exports = function (req, res, next) {
passport.authenticate('jwt', function (error, user, info) {
- if (error) return res.serverError(error);
- if (!user) return res.unauthorized(null, info && info.code, info && info.message);
+ if (error || !user) return res.negotiate(_.assign(error || {}, info));
req.user = user;
|
6f6df7a1cdda9445ac32813d77b5aadd09664f17 | lib/hooks.js | lib/hooks.js | 'use strict'
var shimmer = require('shimmer')
var modules = require('./instrumentation/modules')
module.exports = function (client) {
if (!client._ff_instrument) return
// TODO: This will actual just use the logger of the last client parsed in.
// In most use-cases this is a non-issue, but if someone tries to initiate
// multiple clients with different loggers, this will get weird
shimmer({ logger: client.logger.error })
client.logger.trace('shimming function Module._load')
var Module = require('module')
shimmer.wrap(Module, '_load', function (orig) {
return function (file) {
return modules.patch(file, orig.apply(this, arguments), client)
}
})
}
| 'use strict'
var shimmer = require('shimmer')
var modules = require('./instrumentation/modules')
module.exports = function (client) {
// TODO: This will actual just use the logger of the last client parsed in.
// In most use-cases this is a non-issue, but if someone tries to initiate
// multiple clients with different loggers, this will get weird
shimmer({ logger: client.logger.error })
if (client._ff_instrument) fullInstrumentation(client)
else errorTracingOnly(client)
}
function fullInstrumentation (client) {
client.logger.trace('shimming function Module._load')
var Module = require('module')
shimmer.wrap(Module, '_load', function (orig) {
return function (file) {
return modules.patch(file, orig.apply(this, arguments), client)
}
})
}
function errorTracingOnly (client) {
client.logger.trace('shimming http.Server.prototype functions "on" and "addListener"')
var http = require('http')
var asyncState = require('./async-state')
shimmer.massWrap(http.Server.prototype, ['on', 'addListener'], function (fn, name) {
return function (event, listener) {
if (event === 'request' && typeof listener === 'function') return fn.call(this, event, onRequest)
else return fn.apply(this, arguments)
function onRequest (req, res) {
client.logger.trace('intercepted call to http.Server.prototype.%s', name)
asyncState.req = req
listener.apply(this, arguments)
}
}
})
}
| Allow simple shimming of http.Server if full instrumentation is disabled | Allow simple shimming of http.Server if full instrumentation is disabled
| JavaScript | bsd-2-clause | opbeat/opbeat-node,opbeat/opbeat-node | ---
+++
@@ -4,13 +4,16 @@
var modules = require('./instrumentation/modules')
module.exports = function (client) {
- if (!client._ff_instrument) return
-
// TODO: This will actual just use the logger of the last client parsed in.
// In most use-cases this is a non-issue, but if someone tries to initiate
// multiple clients with different loggers, this will get weird
shimmer({ logger: client.logger.error })
+ if (client._ff_instrument) fullInstrumentation(client)
+ else errorTracingOnly(client)
+}
+
+function fullInstrumentation (client) {
client.logger.trace('shimming function Module._load')
var Module = require('module')
shimmer.wrap(Module, '_load', function (orig) {
@@ -19,3 +22,23 @@
}
})
}
+
+function errorTracingOnly (client) {
+ client.logger.trace('shimming http.Server.prototype functions "on" and "addListener"')
+
+ var http = require('http')
+ var asyncState = require('./async-state')
+
+ shimmer.massWrap(http.Server.prototype, ['on', 'addListener'], function (fn, name) {
+ return function (event, listener) {
+ if (event === 'request' && typeof listener === 'function') return fn.call(this, event, onRequest)
+ else return fn.apply(this, arguments)
+
+ function onRequest (req, res) {
+ client.logger.trace('intercepted call to http.Server.prototype.%s', name)
+ asyncState.req = req
+ listener.apply(this, arguments)
+ }
+ }
+ })
+} |
b1f3ef17d75d3539c02659cbf300cd913879ce36 | client/src/store.js | client/src/store.js | import {createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import reducer from './reducer';
const loggerMiddleware = createLogger();
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware,
loggerMiddleware
)(createStore);
export default function makeStore(initialState) {
return createStoreWithMiddleware(reducer, initialState);
};
| import {createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import reducer from './reducer';
const loggerMiddleware = createLogger();
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware,
loggerMiddleware //remove in production
)(createStore);
export default function makeStore(initialState) {
return createStoreWithMiddleware(reducer, initialState);
};
| Add comment to remove loggerMiddleware in production. | Add comment to remove loggerMiddleware in production.
| JavaScript | agpl-3.0 | mi-squared/volunteer-portal,mi-squared/volunteer-portal,mi-squared/volunteer-portal | ---
+++
@@ -7,7 +7,7 @@
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware,
- loggerMiddleware
+ loggerMiddleware //remove in production
)(createStore);
export default function makeStore(initialState) { |
7b7f5012a087f4454f81cecd1f7292d655265cdb | lib/index.js | lib/index.js | import Server from './server';
import Client from './client';
const debug = require('debug')('tinylr');
// Need to keep track of LR servers when notifying
const servers = [];
export default tinylr;
// Expose Server / Client objects
tinylr.Server = Server;
tinylr.Client = Client;
// and the middleware helpers
tinylr.middleware = middleware;
tinylr.changed = changed;
// Main entry point
function tinylr (opts) {
const srv = new Server(opts);
servers.push(srv);
return srv;
}
// A facade to Server#handle
function middleware (opts) {
const srv = new Server(opts);
servers.push(srv);
return function tinylr (req, res, next) {
srv.handler(req, res, next);
};
}
// Changed helper, helps with notifying the server of a file change
function changed (done) {
const files = [].slice.call(arguments);
if (files[files.length - 1] === 'function') done = files.pop();
done = typeof done === 'function' ? done : () => {};
debug('Notifying %d servers - Files: ', servers.length, files);
servers.forEach(srv => {
const params = { params: { files: files } };
srv && srv.changed(params);
});
done();
}
| import Server from './server';
import Client from './client';
const debug = require('debug')('tinylr');
// Need to keep track of LR servers when notifying
const servers = [];
export default tinylr;
// Expose Server / Client objects
tinylr.Server = Server;
tinylr.Client = Client;
// and the middleware helpers
tinylr.middleware = middleware;
tinylr.changed = changed;
// Main entry point
function tinylr (opts) {
const srv = new Server(opts);
servers.push(srv);
return srv;
}
// A facade to Server#handle
function middleware (opts) {
const srv = new Server(opts);
servers.push(srv);
return function tinylr (req, res, next) {
srv.handler(req, res, next);
};
}
// Changed helper, helps with notifying the server of a file change
function changed (done) {
const files = [].slice.call(arguments);
if (typeof files[files.length - 1] === 'function') done = files.pop();
done = typeof done === 'function' ? done : () => {};
debug('Notifying %d servers - Files: ', servers.length, files);
servers.forEach(srv => {
const params = { params: { files: files } };
srv && srv.changed(params);
});
done();
}
| Fix changed done callback, missing typeof. | Fix changed done callback, missing typeof. | JavaScript | mit | mklabs/tiny-lr | ---
+++
@@ -35,7 +35,7 @@
// Changed helper, helps with notifying the server of a file change
function changed (done) {
const files = [].slice.call(arguments);
- if (files[files.length - 1] === 'function') done = files.pop();
+ if (typeof files[files.length - 1] === 'function') done = files.pop();
done = typeof done === 'function' ? done : () => {};
debug('Notifying %d servers - Files: ', servers.length, files);
servers.forEach(srv => { |
64e7f7f2eef87d86393077ebab953c8954cccd0b | src/data-reader/local-json.js | src/data-reader/local-json.js | define([
'base/class',
'jquery',
'underscore',
'base/utils'
], function(Class, $, _, Util) {
var LocalJSONReader = Class.extend({
init: function(basepath) {
this.data = [];
this.basepath = basepath;
},
read: function(queries, language) {
var _this = this,
defer = $.Deferred();
var path = this.basepath.replace("{{LANGUAGE}}", language);
_this.data = [];
for (var i=0; i < queries.length; i++) {
var fakeResponsePath = path.replace("response", "response_" + i);
var promise = $.getJSON(fakeResponsePath, function(res) {
_this.data.push(res);
})
.error(function() {
console.log("Error Happened While Lading File: " + fakeResponsePath);
});
}
promise.done(function() {
console.log(_this.data);
defer.resolve();
});
return defer;
},
getData: function() {
return this.data;
}
});
return LocalJSONReader;
}); | define([
'base/class',
'jquery',
'underscore',
'base/utils'
], function(Class, $, _, Util) {
var LocalJSONReader = Class.extend({
init: function(basepath) {
this.data = [];
this.basepath = basepath;
},
read: function(queries, language) {
var _this = this,
defer = $.Deferred(),
promises = [];
var path = this.basepath.replace("{{LANGUAGE}}", language);
_this.data = [];
for (var i=0; i < queries.length; i++) {
var fakeResponsePath = path.replace("response", "response_" + i);
var promise = $.getJSON(fakeResponsePath, function(res) {
_this.data.push(res);
})
.error(function() {
console.log("Error Happened While Lading File: " + fakeResponsePath);
});
promises.push(promise);
}
$.when.apply(null, promises).done(function() {
defer.resolve();
});
return defer;
},
getData: function() {
return this.data;
}
});
return LocalJSONReader;
}); | Fix Load multiple JSON bug using array of promises | Fix Load multiple JSON bug using array of promises
| JavaScript | bsd-3-clause | homosepian/vizabi,Gapminder/vizabi,acestudiooleg/vizabi,jdk137/vizabi,sergey-filipenko/vizabi,maximhristenko/vizabi,maximhristenko/vizabi,Gapminder/vizabi,vizabi/vizabi,alliance-timur/vizabi,buchslava/vizabi,logicerpsolution/vizabi,buchslava/vizabi,alliance-timur/vizabi,Rathunter/vizabi,dab2000/vizabi,Rathunter/vizabi,homosepian/vizabi,TBAPI-0KA/vizabi,maximhristenko/vizabi,IncoCode/vizabi,Rathunter/vizabi,sergey-filipenko/vizabi,logicerpsolution/vizabi,sergey-filipenko/vizabi,acestudiooleg/vizabi,TBAPI-0KA/vizabi,Gapminder/vizabi,dab2000/vizabi,alliance-timur/vizabi,dab2000/vizabi,vizabi/vizabi,IncoCode/vizabi,IncoCode/vizabi,homosepian/vizabi,buchslava/vizabi,logicerpsolution/vizabi,acestudiooleg/vizabi,jdk137/vizabi,jdk137/vizabi,TBAPI-0KA/vizabi | ---
+++
@@ -14,7 +14,8 @@
read: function(queries, language) {
var _this = this,
- defer = $.Deferred();
+ defer = $.Deferred(),
+ promises = [];
var path = this.basepath.replace("{{LANGUAGE}}", language);
@@ -28,13 +29,14 @@
.error(function() {
console.log("Error Happened While Lading File: " + fakeResponsePath);
});
+
+ promises.push(promise);
}
- promise.done(function() {
- console.log(_this.data);
+ $.when.apply(null, promises).done(function() {
defer.resolve();
});
-
+
return defer;
},
|
9d33aca502e70c3da99a66c98ce54e109dc336e0 | src/client/app/core/dataservice.spec.js | src/client/app/core/dataservice.spec.js | /* jshint -W117, -W030 */
describe('dataservice', function() {
beforeEach(function() {
bard.appModule('app.core');
bard.inject('$http','$httpBackend','$q','dataservice','$rootScope');
});
it('exists' , function(){
expect(dataservice).to.exist;
});
it('getMessageCount returns a value' , function() {
dataservice.getMessageCount().then(function(data) {
expect(data).to.exist;
});
$rootScope.$apply();
});
it('getPeople hits the right /api/people' , function() {
$httpBackend.when('GET', '/api/people').respond(200,[{}]);
dataservice.getPeople().then(function(data) {
expect(data).to.exist;
});
$httpBackend.flush();
});
it('getPeople reports error if server fails' , function() {
$httpBackend
.when('GET', '/api/people')
.respond(500,{data: {description: 'you fail'}});
dataservice.getPeople().catch(function(error) {
expect(true).to.be.false;
});
$httpBackend.flush();
});
});
| /* jshint -W117, -W030 */
describe('dataservice', function() {
beforeEach(function() {
bard.appModule('app.core');
bard.inject('$http','$httpBackend','$q','dataservice','$rootScope');
});
it('exists' , function(){
expect(dataservice).to.exist;
});
it('getMessageCount returns a value' , function() {
dataservice.getMessageCount().then(function(data) {
expect(data).to.exist;
});
$rootScope.$apply();
});
it('getPeople hits the right /api/people' , function() {
$httpBackend.when('GET', '/api/people').respond(200,[{}]);
dataservice.getPeople().then(function(data) {
expect(data).to.exist;
});
$httpBackend.flush();
});
it('getPeople reports error if server fails' , function() {
$httpBackend
.when('GET', '/api/people')
.respond(500,{description: 'you fail'});
dataservice.getPeople().catch(function(error) {
expect(error.data.description).to.match(/you fail/);
});
$httpBackend.flush();
});
});
| Fix test so that is uses regex to check the text returned. | Fix test so that is uses regex to check the text returned.
| JavaScript | mit | bitclaw/angularjs-testing,bitclaw/angularjs-testing | ---
+++
@@ -27,9 +27,9 @@
it('getPeople reports error if server fails' , function() {
$httpBackend
.when('GET', '/api/people')
- .respond(500,{data: {description: 'you fail'}});
+ .respond(500,{description: 'you fail'});
dataservice.getPeople().catch(function(error) {
- expect(true).to.be.false;
+ expect(error.data.description).to.match(/you fail/);
});
$httpBackend.flush();
}); |
7464095a8f29a8e7630ac518a34c74ff1ed75c49 | src/js/components/CollapsibleContainer.js | src/js/components/CollapsibleContainer.js | import React, {Component} from 'react';
import Icon from './Icon';
class CollapsibleContainer extends Component {
constructor() {
super(...arguments);
this.state = {
toggle: false
};
this.toggleContainer = this.toggleContainer.bind(this);
}
toggleContainer() {
this.setState({toggle: !this.state.toggle});
}
getChildren() {
if (this.state.toggle) {
return this.props.children;
}
return null;
}
render() {
let icon = 'triangle-right';
if (this.state.toggle) {
icon = 'triangle-down';
}
return (
<div>
<a className="button button-primary-link button-flush" onClick={this.toggleContainer}>
<Icon
id={icon}
color="purple"
family="mini"
size="mini" />
{this.props.label}
</a>
{this.getChildren()}
</div>
);
}
}
CollapsibleContainer.defaultProps = {
label: ''
};
CollapsibleContainer.propTypes = {
label: React.PropTypes.string
};
module.exports = CollapsibleContainer;
| import React, {Component} from 'react';
import Icon from './Icon';
class CollapsibleContainer extends Component {
constructor() {
super(...arguments);
this.state = {
toggle: false
};
this.toggleContainer = this.toggleContainer.bind(this);
}
toggleContainer() {
this.setState({toggle: !this.state.toggle});
}
getChildren() {
if (this.state.toggle) {
return this.props.children;
}
return null;
}
render() {
let icon = 'triangle-right';
if (this.state.toggle) {
icon = 'triangle-down';
}
return (
<div>
<a className="button button-primary-link button-flush" onClick={this.toggleContainer}>
<Icon
id={icon}
color="purple"
family="mini"
size="mini" />
{this.props.label}
</a>
{this.getChildren()}
</div>
);
}
}
CollapsibleContainer.defaultProps = {
label: ''
};
CollapsibleContainer.propTypes = {
label: React.PropTypes.string.isRequired
};
module.exports = CollapsibleContainer;
| Add required flag to label prop | Add required flag to label prop
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -51,7 +51,7 @@
};
CollapsibleContainer.propTypes = {
- label: React.PropTypes.string
+ label: React.PropTypes.string.isRequired
};
module.exports = CollapsibleContainer; |
a392c18f48b1af268e6882fde1ca09f75a87e73a | packages/pundle-chunk-transformer-js-uglify/src/index.js | packages/pundle-chunk-transformer-js-uglify/src/index.js | // @flow
import { minify as processUglify } from 'uglify-es'
import { minify as processTerser } from 'terser'
import { createChunkTransformer } from 'pundle-api'
import manifest from '../package.json'
// TODO: Fix source maps
const VALID_UGLIFIERS = new Set(['uglify', 'terser'])
function createComponent({ options = {}, uglifier = 'uglify' }: { options?: Object, uglifier: 'terser' | 'uglify' } = {}) {
if (!VALID_UGLIFIERS.has(uglifier)) {
throw new Error(`options.uglifier must be either 'uglify' or 'terser'. Got: ${uglifier}`)
}
return createChunkTransformer({
name: 'pundle-chunk-transformer-js-uglify',
version: manifest.version,
async callback({ format, contents }) {
if (format !== 'js') return null
const uglify = uglifier === 'terser' ? processTerser : processUglify
const { code, error } = uglify(typeof contents === 'string' ? contents : contents.toString(), {
...options,
})
if (error) {
throw new Error(error)
}
return {
contents: code,
sourceMap: null,
}
},
})
}
module.exports = createComponent
| // @flow
import { minify as processUglify } from 'uglify-es'
import { minify as processTerser } from 'terser'
import { createChunkTransformer } from 'pundle-api'
import manifest from '../package.json'
// TODO: Fix source maps
const VALID_UGLIFIERS = new Set(['uglify', 'terser'])
function createComponent({ options = {}, uglifier = 'uglify' }: { options?: Object, uglifier: 'terser' | 'uglify' } = {}) {
if (!VALID_UGLIFIERS.has(uglifier)) {
throw new Error(`options.uglifier must be either 'uglify' or 'terser'. Got: ${uglifier}`)
}
return createChunkTransformer({
name: 'pundle-chunk-transformer-js-uglify',
version: manifest.version,
async callback({ format, contents }) {
if (format !== 'js') return null
const uglify = uglifier === 'terser' ? processTerser : processUglify
const { code, error } = uglify(typeof contents === 'string' ? contents : contents.toString(), {
...options,
compress: {
defaults: false,
...options.compress,
},
})
if (error) {
throw new Error(error)
}
return {
contents: code,
sourceMap: null,
}
},
})
}
module.exports = createComponent
| Tweak uglifyjs config to be faster | :racehorse: Tweak uglifyjs config to be faster
| JavaScript | mit | motion/pundle,steelbrain/pundle,steelbrain/pundle,steelbrain/pundle | ---
+++
@@ -22,6 +22,10 @@
const uglify = uglifier === 'terser' ? processTerser : processUglify
const { code, error } = uglify(typeof contents === 'string' ? contents : contents.toString(), {
...options,
+ compress: {
+ defaults: false,
+ ...options.compress,
+ },
})
if (error) {
throw new Error(error) |
91db0045d899443f5c18c0dc42b51b679abe3aa4 | ui/src/shared/middleware/resizeLayout.js | ui/src/shared/middleware/resizeLayout.js | // Trigger resize event to relayout the React Layout plugin
export default function resizeLayout() {
return next => action => {
next(action)
if (
action.type === 'ENABLE_PRESENTATION_MODE' ||
action.type === 'DISABLE_PRESENTATION_MODE'
) {
// Uses longer event object creation method due to IE compatibility.
const evt = document.createEvent('HTMLEvents')
evt.initEvent('resize', false, true)
window.dispatchEvent(evt)
}
}
}
| // Trigger resize event to relayout the React Layout plugin
import {enablePresentationMode} from '../actions/app'
export default function resizeLayout() {
return next => action => {
next(action)
if (
action.type === 'ENABLE_PRESENTATION_MODE' ||
action.type === 'DISABLE_PRESENTATION_MODE'
) {
// Uses longer event object creation method due to IE compatibility.
const evt = document.createEvent('HTMLEvents')
evt.initEvent('resize', false, true)
window.dispatchEvent(evt)
}
if (window.location.search.includes('present')) {
next(enablePresentationMode())
next(action)
}
}
}
| Add 'present' url query/search param to presentation mode middleware. | Add 'present' url query/search param to presentation mode middleware.
| JavaScript | mit | mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -1,4 +1,5 @@
// Trigger resize event to relayout the React Layout plugin
+import {enablePresentationMode} from '../actions/app'
export default function resizeLayout() {
return next => action => {
@@ -12,5 +13,9 @@
evt.initEvent('resize', false, true)
window.dispatchEvent(evt)
}
+ if (window.location.search.includes('present')) {
+ next(enablePresentationMode())
+ next(action)
+ }
}
} |
dd89728416e7078caf39b7dcb3182ab30d52e594 | web_modules/layouts/PageLoading/index.js | web_modules/layouts/PageLoading/index.js | import React, { Component } from "react"
import TopBarProgressIndicator from "react-topbar-progress-indicator"
import styles from "./index.css"
TopBarProgressIndicator.config({
barColors: {
"0": "#0085a1",
"1.0": "#0085a1",
},
shadowBlur: 5,
})
export default class PageLoading extends Component {
render() {
return (
<div>
<TopBarProgressIndicator />
<div className={ styles.loader }>
<div className={ styles.spinner }></div>
</div>
</div>
)
}
}
| import React, { Component } from "react"
import TopBarProgressIndicator from "react-topbar-progress-indicator"
import styles from "./index.css"
TopBarProgressIndicator.config({
barColors: {
"0": "#fff",
"1.0": "#fff",
},
shadowBlur: 5,
})
export default class PageLoading extends Component {
render() {
return (
<div>
<TopBarProgressIndicator />
<div className={ styles.loader }>
<div className={ styles.spinner }></div>
</div>
</div>
)
}
}
| Update color to match with header | ui(topbar): Update color to match with header
| JavaScript | mit | thangngoc89/blog | ---
+++
@@ -5,8 +5,8 @@
TopBarProgressIndicator.config({
barColors: {
- "0": "#0085a1",
- "1.0": "#0085a1",
+ "0": "#fff",
+ "1.0": "#fff",
},
shadowBlur: 5,
}) |
1f1dfbc27a77fed2844a128c5dc38b1ffad3bab6 | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var sass = require('gulp-sass');
var sasslint = require('gulp-sass-lint');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
var header = require('gulp-header');
var pkg = require('./package.json');
var banner = '/*! <%= pkg.name %>: v.<%= pkg.version %>, last updated on: <%= new Date() %> */\n';
///////////////////////////////////
// Build Tasks
///////////////////////////////////
///////////////////////////////////
// Development Tasks
///////////////////////////////////
gulp.task('styles:dev', function() {
return gulp.src('./scss/**/*.s+(a|c)ss')
.pipe(sasslint({configFile: '.ubs-sass-lint.yml'}))
.pipe(sasslint.format())
.pipe(sasslint.failOnError(false))
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'expanded'}))
//.pipe(rename({extname: '.dev.css'}))
.pipe(header(banner, {pkg : pkg}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./css'))
.pipe(notify(notifyMsg));
});
gulp.task('default', ['styles:dev']); | var gulp = require('gulp');
var sass = require('gulp-sass');
var sasslint = require('gulp-sass-lint');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
var header = require('gulp-header');
var pkg = require('./package.json');
var banner = '/*! <%= pkg.name %>: v.<%= pkg.version %>, last updated on: <%= new Date() %> */\n';
///////////////////////////////////
// Build Tasks
///////////////////////////////////
///////////////////////////////////
// Development Tasks
///////////////////////////////////
gulp.task('styles:dev', function() {
return gulp.src('./scss/**/*.s+(a|c)ss')
.pipe(sasslint({configFile: '.ubs-sass-lint.yml'}))
.pipe(sasslint.format())
.pipe(sasslint.failOnError(false))
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'expanded'}))
//.pipe(rename({extname: '.dev.css'}))
.pipe(header(banner, {pkg : pkg}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./css'))
//.pipe(notify(notifyMsg));
});
gulp.task('default', ['styles:dev']); | Comment out missing call to notify plugin | Comment out missing call to notify plugin
| JavaScript | mit | TMG-88/TAH,TMG-88/TAH,TMG-88/hello-world,TMG-88/hello-world | ---
+++
@@ -31,7 +31,7 @@
.pipe(header(banner, {pkg : pkg}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./css'))
- .pipe(notify(notifyMsg));
+ //.pipe(notify(notifyMsg));
});
gulp.task('default', ['styles:dev']); |
33f7cbd804244528bce4286f7f8806feb6f8d159 | src/request/stores/request-entry-store.js | src/request/stores/request-entry-store.js | var glimpse = require('glimpse'),
_requests = [];
(function() {
function dataFound(payload) {
// TODO: Really bad hack to get things going atm
_requests = payload.allRequests;
glimpse.emit('shell.request.summary.changed', _requests);
}
// External data coming in
glimpse.on('data.request.summary.found', dataFound);
})();
/*
// TODO: Need to see if this is needed
module.exports = {
getAllFor: function(sessionId) {
console.log(sessionId);
return _requests;
}
};
*/
| var glimpse = require('glimpse'),
_requests = [],
_filteredRequests = [],
_filters = {};
function requestsChanged(targetRequests) {
glimpse.emit('shell.request.summary.changed', targetRequests);
}
// TODO: This needs to be refactored to dynamically lookup records, etc
// TODO: Even at the moment this is going to need to be refactored
var filterRequests = (function() {
function hasFilters(filters) {
return filters.userId;
}
function checkMatch(request, filters) {
return (request.user.id === filters.userId);
}
function applyFilters(sourceRequests, destinationRequests, filters) {
var matchFound = false;
for (var i = sourceRequests.length - 1; i >= 0; i--) {
var sourceRequest = sourceRequests[i];
if (checkMatch(sourceRequest, filters)) {
destinationRequests.unshift(sourceRequest);
matchFound = true;
}
}
return matchFound;
}
return function(allRequests, newRequests, filterHasChanged) {
if (hasFilters(_filters)) {
var sourceRequests = newRequests;
if (filterHasChanged) {
sourceRequests = allRequests;
_filteredRequests = [];
}
if (applyFilters(sourceRequests, _filteredRequests, _filters)) {
requestsChanged(_filteredRequests);
}
}
else {
requestsChanged(_requests);
}
};
})();
(function() {
function userSwitch(payload) {
_filters.userId = payload.userId;
filterRequests(_requests, null, true);
}
glimpse.on('shell.request.user.selected', userSwitch);
})();
(function() {
function dataFound(payload) {
// TODO: Really bad hack to get things going atm
_requests = payload.allRequests;
filterRequests(_requests, payload.newRequests, false);
}
// External data coming in
glimpse.on('data.request.summary.found', dataFound);
})();
/*
// TODO: Need to see if this is needed
module.exports = {
getAllFor: function(sessionId) {
console.log(sessionId);
return _requests;
}
};
*/
| Implement a basic version of filtering based on use selection | Implement a basic version of filtering based on use selection
| JavaScript | unknown | avanderhoorn/Glimpse.Client.Prototype,Glimpse/Glimpse.Client.Prototype,avanderhoorn/Glimpse.Client.Prototype,Glimpse/Glimpse.Client.Prototype,Glimpse/Glimpse.Client.Prototype | ---
+++
@@ -1,12 +1,73 @@
var glimpse = require('glimpse'),
- _requests = [];
+ _requests = [],
+ _filteredRequests = [],
+ _filters = {};
+
+function requestsChanged(targetRequests) {
+ glimpse.emit('shell.request.summary.changed', targetRequests);
+}
+
+// TODO: This needs to be refactored to dynamically lookup records, etc
+// TODO: Even at the moment this is going to need to be refactored
+var filterRequests = (function() {
+ function hasFilters(filters) {
+ return filters.userId;
+ }
+
+ function checkMatch(request, filters) {
+ return (request.user.id === filters.userId);
+ }
+
+ function applyFilters(sourceRequests, destinationRequests, filters) {
+ var matchFound = false;
+
+ for (var i = sourceRequests.length - 1; i >= 0; i--) {
+ var sourceRequest = sourceRequests[i];
+
+ if (checkMatch(sourceRequest, filters)) {
+ destinationRequests.unshift(sourceRequest);
+ matchFound = true;
+ }
+ }
+
+ return matchFound;
+ }
+
+ return function(allRequests, newRequests, filterHasChanged) {
+ if (hasFilters(_filters)) {
+ var sourceRequests = newRequests;
+
+ if (filterHasChanged) {
+ sourceRequests = allRequests;
+ _filteredRequests = [];
+ }
+
+ if (applyFilters(sourceRequests, _filteredRequests, _filters)) {
+ requestsChanged(_filteredRequests);
+ }
+ }
+ else {
+ requestsChanged(_requests);
+ }
+ };
+ })();
+
+(function() {
+ function userSwitch(payload) {
+ _filters.userId = payload.userId;
+
+ filterRequests(_requests, null, true);
+ }
+
+ glimpse.on('shell.request.user.selected', userSwitch);
+})();
(function() {
function dataFound(payload) {
// TODO: Really bad hack to get things going atm
_requests = payload.allRequests;
- glimpse.emit('shell.request.summary.changed', _requests);
+ filterRequests(_requests, payload.newRequests, false);
}
// External data coming in |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.