commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
e47584cb25cf75311e368a4ad87ba61b68d906ae
|
src/selection/join.js
|
src/selection/join.js
|
function(onenter, onupdate, onexit) {
var enter = this.enter(), update = this, exit = this.exit();
if (typeof onenter === "function") {
enter = onenter(enter);
if (enter) enter = enter.selection();
} else {
enter = enter.append(onenter + "");
}
if (onupdate != null) {
update = onupdate(update);
if (update) update = update.selection();
}
if (onexit == null) exit.remove(); else onexit(exit);
return enter && update ? enter.merge(update).order() : update;
}
|
function(onenter, onupdate, onexit) {
var enter = this.enter(), update = this, exit = this.exit();
if (typeof onenter === "function") {
enter = onenter(enter);
if (enter) enter = enter.selection();
} else {
enter = enter.append(onenter + "");
}
if (onupdate != null) update = onupdate(update);
if (onexit == null) exit.remove(); else onexit(exit);
return enter && update ? enter.merge(update).order() : update;
}
|
Revert update logic as it is handled by .merge.
|
Revert update logic as it is handled by .merge.
|
JavaScript
|
isc
|
d3/d3-selection
|
62756a7e5ed5297cc2084644ac82d678179a3362
|
src/components/page.js
|
src/components/page.js
|
import React from 'react'
import GoogleAnalyticsScript from './scripts/google-analytics'
export default Page
function Page({
children,
title = 'JavaScript Air',
description = 'The live JavaScript podcast all about JavaScript and the web platform. Available on YouTube, iTunes, and an RSS audio feed',
} = {}) {
/* eslint max-len:0 */
return (
<html>
<head lang="en">
<title>{title}</title>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="google-site-verification" content="85n8ZBk_3hSeShlRmsVJXgDolakFG4UsMJgpy3mQyPs" />
<meta name="theme-color" content="#155674" />
<meta name="author" content="Kent C. Dodds" />
<meta name="description" content={description} />
<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
<link rel="stylesheet" href="/styles.dist.css" />
<link rel="stylesheet" href="/resources/font/font.css" />
</head>
<body>
{children}
<GoogleAnalyticsScript />
</body>
</html>
)
}
|
import React from 'react'
import GoogleAnalyticsScript from './scripts/google-analytics'
export default Page
function Page({
children,
title = 'JavaScript Air',
description = 'The live JavaScript podcast all about JavaScript and the web platform. Available on YouTube, iTunes, and an RSS audio feed',
} = {}) {
/* eslint max-len:0 */
return (
<html>
<head lang="en">
<title>{title}</title>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="google-site-verification" content="85n8ZBk_3hSeShlRmsVJXgDolakFG4UsMJgpy3mQyPs" />
<meta name="theme-color" content="#155674" />
<meta name="author" content="Kent C. Dodds" />
<meta name="description" content={description} />
<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
<link rel="stylesheet" href="/styles.dist.css" />
</head>
<body>
{children}
<GoogleAnalyticsScript />
</body>
</html>
)
}
|
Remove now-deleted font reference from Page component
|
Remove now-deleted font reference from Page component
|
JavaScript
|
mit
|
javascriptair/site,javascriptair/site,javascriptair/site
|
5337b3add954120583cbee1610ca2d8f188d9322
|
src/js/home-page.js
|
src/js/home-page.js
|
import React from 'react';
import { Link } from 'react-router';
import HomepageTile from './homepage-tile.js';
import chaptersData from './chapter-data.js';
// Clone the chapters since sort mutates the array
const chapters = [...chaptersData]
.filter(chapter => !chapter.hidden)
.sort((chapterA, chapterB) => chapterA.number - chapterB.number);
const HomePage = React.createClass({
render: function() {
return (
<div className="container homepage">
<div className="pure-g row-gap-small">
<div className="pure-u-1">
<h2>Grade 6 Science</h2>
</div>
</div>
<div className="pure-g">
{chapters.map(chapter => (
<HomepageTile imagePath={chapter.thumbnailImagePath} chapterNumber={chapter.number} title={chapter.title} />
))}
</div>
{this.props.children}
</div>
);
}
});
export default HomePage;
|
import React from 'react';
import { Link } from 'react-router';
import HomepageTile from './homepage-tile.js';
import chaptersData from './chapter-data.js';
// Clone the chapters since sort mutates the array
const chapters = [...chaptersData]
.filter(chapter => !chapter.hidden)
.sort((chapterA, chapterB) => chapterA.number - chapterB.number);
const HomePage = React.createClass({
render: function() {
return (
<div className="container homepage">
<div className="pure-g row-gap-small">
<div className="pure-u-1">
<h2>Grade 6 Science</h2>
</div>
</div>
<div className="pure-g">
{chapters.map((chapter, index) => (
<HomepageTile key={index} imagePath={chapter.thumbnailImagePath} chapterNumber={chapter.number} title={chapter.title} />
))}
</div>
{this.props.children}
</div>
);
}
});
export default HomePage;
|
Add key to homepage tile items to satisfy react
|
Add key to homepage tile items to satisfy react
|
JavaScript
|
mit
|
nicolasartman/learning-prototype,nicolasartman/learning-prototype,nicolasartman/chalees-min,nicolasartman/chalees-min
|
d92c8ce875ce3da991ebce9222c200489da0b18f
|
test/index.js
|
test/index.js
|
var Couleurs = require ("../index");
console.log("Red".rgb([255, 0, 0]));
console.log("Yellow".rgb(255, 255, 0));
console.log("Blue".rgb("#2980b9"));
console.log("Bold".bold())
console.log("Italic".italic())
console.log("Underline".underline())
console.log("Inverse".inverse())
console.log("Strikethrough".strikethrough())
console.log("All combined"
.rgb("#d35400")
.bold()
.italic()
.underline()
.inverse()
.strikethrough()
)
|
// Dependency
var Couleurs = require("../index")();
// No prototype modify
console.log(Couleurs.rgb("Red", [255, 0, 0]));
console.log(Couleurs.rgb("Yellow", 255, 255, 0));
console.log(Couleurs.rgb("Blue", "#2980b9"));
console.log(Couleurs.bold("Bold"));
console.log(Couleurs.italic("Italic"));
// Modify prototype
require("../index")(true);
console.log("Underline".underline());
console.log("Inverse".inverse());
console.log("Strikethrough".strikethrough());
console.log("All combined"
.rgb("#d35400")
.bold()
.italic()
.underline()
.inverse()
.strikethrough()
);
|
Call couleurs in different ways.
|
Call couleurs in different ways.
|
JavaScript
|
mit
|
IonicaBizau/node-couleurs
|
d43f60a6bbc181c0f08fa5dcfdbd1ab19709afef
|
lib/modules/fields/class_static_methods/get_list_fields.js
|
lib/modules/fields/class_static_methods/get_list_fields.js
|
import _ from 'lodash';
import ListField from '../list_field.js';
function getListFields() {
return _.filter(this.getFields(), function(field) {
return field instanceof ListField;
});
};
export default getListFields;
|
import _ from 'lodash';
import ListField from '../list_field.js';
function getListFields(classOnly = false) {
return _.filter(this.getFields(), function(field) {
if (classOnly) {
return field instanceof ListField && field.isClass;
}
return field instanceof ListField;
});
};
export default getListFields;
|
Allow getting only class fields in the getListFields method
|
Allow getting only class fields in the getListFields method
|
JavaScript
|
mit
|
jagi/meteor-astronomy
|
f824ff500dd30c7375a1b30981aa3b3ce223a28a
|
core/js/integritycheck-failed-notification.js
|
core/js/integritycheck-failed-notification.js
|
/**
* @author Lukas Reschke
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
/**
* This gets only loaded if the integrity check has failed and then shows a notification
*/
$(document).ready(function(){
var text = t(
'core',
'<a href="{docUrl}">There were problems with the code integrity check. More information…</a>',
{
docUrl: OC.generateUrl('/settings/admin#security-warning')
}
);
OC.Notification.showHtml(
text,
{
type: 'error',
isHTML: true
}
);
});
|
/**
* @author Lukas Reschke
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
/**
* This gets only loaded if the integrity check has failed and then shows a notification
*/
$(document).ready(function(){
var text = t(
'core',
'<a href="{docUrl}">There were problems with the code integrity check. More information…</a>',
{
docUrl: OC.generateUrl('/settings/admin/overview#security-warning')
}
);
OC.Notification.showHtml(
text,
{
type: 'error',
isHTML: true
}
);
});
|
Fix code integrity check-warning link
|
Fix code integrity check-warning link
Signed-off-by: Marius Blüm <[email protected]>
|
JavaScript
|
agpl-3.0
|
nextcloud/server,nextcloud/server,andreas-p/nextcloud-server,andreas-p/nextcloud-server,andreas-p/nextcloud-server,andreas-p/nextcloud-server,andreas-p/nextcloud-server,nextcloud/server,nextcloud/server
|
c042b19ee5414afe1ab206ebebace8675d55c096
|
test/sites.js
|
test/sites.js
|
var inspector = require('..');
var expect = require('expect.js');
describe("url-inspector", function sites() {
it("should get title from http://www.lavieenbois.com/", function(done) {
this.timeout(5000);
inspector('http://www.lavieenbois.com/', function(err, meta) {
expect(err).to.not.be.ok();
expect(meta.title).to.be.ok();
done();
});
});
});
|
var inspector = require('..');
var expect = require('expect.js');
describe("url-inspector", function sites() {
it("should get title from http://www.lavieenbois.com/", function(done) {
this.timeout(5000);
inspector('http://www.lavieenbois.com/', function(err, meta) {
expect(err).to.not.be.ok();
expect(meta.title).to.be.ok();
done();
});
});
it("should return embeddable content at https://myspace.com/unefemmemariee/music/songs", function(done) {
this.timeout(5000);
inspector('https://myspace.com/unefemmemariee/music/songs', function(err, meta) {
expect(err).to.not.be.ok();
expect(meta.ext).to.be("html");
expect(meta.embed).to.be.ok();
expect(meta.html.startsWith('<iframe')).to.be.ok();
done();
});
});
});
|
Add a test to ensure html objects are embeds
|
Add a test to ensure html objects are embeds
|
JavaScript
|
mit
|
kapouer/url-inspector
|
9ccba19417e58ecd619ceb036ea2f3cc48eb64c4
|
addon/components/banner-with-close-button.js
|
addon/components/banner-with-close-button.js
|
import Component from '@ember/component';
import layout from '../templates/components/banner-with-close-button';
import {inject as service} from '@ember/service';
import {computed} from '@ember/object';
export default Component.extend({
layout,
cookies: service(),
classNames: ['banner-with-close-button'],
isBannerCookieSet: computed('closed', function() {
let cookieService = this.get('cookies');
return cookieService.read('hasSeenBanner');
}),
actions: {
setBannerCookie() {
let cookieService = this.get('cookies');
cookieService.write('hasSeenBanner', true, {path: '/'});
this.set('closed', true);
},
elementClicked({target}) {
if (target.tagName.toLowerCase() === 'a') {
let cookieService = this.get('cookies');
cookieService.write('hasSeenBanner', true, {path: '/'});
this.set('closed', true);
}
}
},
});
|
import Component from '@ember/component';
import layout from '../templates/components/banner-with-close-button';
import {inject as service} from '@ember/service';
import {computed} from '@ember/object';
export default Component.extend({
layout,
cookies: service(),
classNames: ['banner-with-close-button'],
isBannerCookieSet: computed('closed', function() {
let cookieService = this.get('cookies');
return cookieService.read('hasSeenBanner');
}),
actions: {
setBannerCookie() {
let cookieService = this.get('cookies');
let future = new Date();
future.setDate(future.getDate() + 30);
cookieService.write('hasSeenBanner', true, {path: '/', expires: future});
this.set('closed', true);
},
elementClicked({target}) {
if (target.tagName.toLowerCase() === 'a') {
let cookieService = this.get('cookies');
let future = new Date();
future.setDate(future.getDate() + 30);
cookieService.write('hasSeenBanner', true, {path: '/', expires: future});
this.set('closed', true);
}
}
},
});
|
Add 30 day expiration to cookie on gdpr banner
|
Add 30 day expiration to cookie on gdpr banner
|
JavaScript
|
mit
|
nypublicradio/nypr-ui,nypublicradio/nypr-ui
|
deb70b4a47e2a8aa800c80fb79da50f841d85adf
|
packages/@sanity/desk-tool/src/components/DraftStatus.js
|
packages/@sanity/desk-tool/src/components/DraftStatus.js
|
import EditIcon from 'part:@sanity/base/edit-icon'
import React from 'react'
import {Tooltip} from 'react-tippy'
import styles from './ItemStatus.css'
const DraftStatus = () => (
<Tooltip
tabIndex={-1}
className={styles.itemStatus}
html={
<div className={styles.tooltipWrapper}>
<span>Unpublished changes</span>
</div>
}
arrow
theme="light"
sticky
size="small"
>
<div className={styles.draftBadge} role="image" aria-label="There are unpublished edits">
<EditIcon />
</div>
</Tooltip>
)
export default DraftStatus
|
import EditIcon from 'part:@sanity/base/edit-icon'
import React from 'react'
// import {Tooltip} from 'react-tippy'
import styles from './ItemStatus.css'
const DraftStatus = () => (
// NOTE: We're experiencing a bug with `react-tippy` here
// @todo: Replace react-tippy with `react-popper` or something
// <Tooltip
// tabIndex={-1}
// className={styles.itemStatus}
// html={
// <div className={styles.tooltipWrapper}>
// <span>Unpublished changes</span>
// </div>
// }
// arrow
// theme="light"
// sticky
// size="small"
// >
<div className={styles.draftBadge} role="image" aria-label="There are unpublished edits">
<EditIcon />
</div>
// </Tooltip>
)
export default DraftStatus
|
Disable react-tippy because of a bug
|
[desk-tool] Disable react-tippy because of a bug
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
b8d022270a10d59cc895acafad4742ad61e3460c
|
server/routes/authRouter.js
|
server/routes/authRouter.js
|
var authRouter = require('express').Router();
var jwt = require('jwt-simple');
var auth = require('../lib/auth');
var User = require('../../db/models/User');
var Promise = require('bluebird');
var bcrypt = require('bcryptjs');
bcrypt.compare = Promise.promisify(bcrypt.compare);
authRouter.post('/login', function(req, res) {
var email = req.body.email;
var password = req.body.password;
if (!email || !password) {
res.status(400).send('Incomplete email/password');
return;
}
User.query().where('email', email)
.then(function(user) {
var user = user[0];
if (!user) {
throw 'Error: user does not exist';
} else {
return Promise.all([
bcrypt.compare(password, user.password),
user
]);
}
})
.spread(function(authenticated, user) {
if (!authenticated) {
throw 'Invalid password';
} else {
var payload = { id: user.id };
var token = jwt.encode(payload, auth.cfg.jwtSecret);
res.json({ token: token });
}
})
.catch(function(authError) {
res.status(401).send(authError);
})
.error(function(err) {
console.error('Auth server error: ', err);
res.status(500).send('Server error');
});
});
module.exports = authRouter;
|
var authRouter = require('express').Router();
var jwt = require('jwt-simple');
var auth = require('../lib/auth');
var User = require('../../db/models/User');
var Promise = require('bluebird');
var bcrypt = require('bcryptjs');
bcrypt.compare = Promise.promisify(bcrypt.compare);
authRouter.post('/login', function(req, res) {
var email = req.body.email;
var password = req.body.password;
if (!email || !password) {
res.status(400).send('Incomplete email/password');
return;
}
User.query().where('email', email)
.then(function(user) {
var user = user[0];
if (!user) {
throw 'Error: user does not exist';
} else {
return Promise.all([
bcrypt.compare(password, user.password),
user
]);
}
})
.spread(function(authenticated, user) {
if (!authenticated) {
throw 'Invalid password';
} else {
var payload = { id: user.id, exp: Math.round((Date.now() + 30 * 24 * 60 * 1000) / 1000) };
var token = jwt.encode(payload, auth.cfg.jwtSecret);
res.json({ token: token });
}
})
.catch(function(authError) {
res.status(401).send(authError);
})
.error(function(err) {
console.error('Auth server error: ', err);
res.status(500).send('Server error');
});
});
module.exports = authRouter;
|
Set JWT expiration date to 30 days
|
Set JWT expiration date to 30 days
|
JavaScript
|
mit
|
SillySalamanders/Reactivity,SillySalamanders/Reactivity
|
949254b178c540d98783e3efe3c2df82cd138ce4
|
src/components/CryptoDropdown.js
|
src/components/CryptoDropdown.js
|
import React from 'react'
const CryptoDropdown = ({ label, cryptos, action }) => (
<div className="form-group form-group-sm">
<label className="col-sm-2 control-label">{label}</label>
<div className="col-sm-10">
<select className="form-control" onChange={
(e) => action(e.target.value)}>
<option value="" selected disabled>Select Currency</option>
{cryptos.map(crypto =>
<option key={crypto.id}>{crypto.symbol}</option>
)
}
</select>
</div>
</div>
)
export default CryptoDropdown
|
import React from 'react'
const CryptoDropdown = ({ label, cryptos, action }) => (
<div className="form-group form-group-sm">
<label className="col-sm-2 control-label">{label}</label>
<div className="col-sm-10">
<select className="form-control" onChange={
(e) => action(e.target.value)}>
{cryptos.map(crypto =>
<option key={crypto.id}>{crypto.symbol}</option>
)
}
</select>
</div>
</div>
)
export default CryptoDropdown
|
Revert "updated image for documentation"
|
Revert "updated image for documentation"
This reverts commit de6b2b26414dfd46069d170761e457d95c67b589.
|
JavaScript
|
mit
|
davidoevans/react-redux-dapp,davidoevans/react-redux-dapp
|
d232a4d61f6de338916a15744e925f5ff8e3ca9a
|
test/types.js
|
test/types.js
|
import test from 'ava';
import domLoaded from '../';
test('domLoaded is a function', t => {
t.is(typeof domLoaded, 'function');
});
|
import test from 'ava';
import domLoaded from '../';
test('domLoaded is a function', t => {
t.is(typeof domLoaded, 'function');
});
test('domLoaded returns a Promise', t => {
t.true(domLoaded() instanceof Promise);
});
|
Test domLoaded returns a Promise
|
Test domLoaded returns a Promise
|
JavaScript
|
mit
|
lukechilds/when-dom-ready
|
17ce6c41c8e7b43f1e9f12fe66e4e65ec9f7a487
|
index.js
|
index.js
|
var dust
try {
dust = require('dustjs-linkedin')
try { require('dustjs-helpers') }
catch (ex) {}
}
catch (ex) {
try { dust = require('dust') }
catch (ex) {}
}
if (!dust) throw new Error('"dustjs-linkedin" or "dust" module not found')
module.exports = {
module: {
compile: function(template, options, callback) {
var compiled = dust.compileFn(template, options && options.name)
process.nextTick(function() {
callback(null, function(context, options, callback) {
compiled(context, callback)
})
})
}
},
compileMode: 'async'
}
|
var dust
var fs = require('fs')
var Path = require('path')
try {
dust = require('dustjs-linkedin')
try { require('dustjs-helpers') }
catch (ex) {}
}
catch (ex) {
try { dust = require('dust') }
catch (ex) {}
}
if (!dust) throw new Error('"dustjs-linkedin" or "dust" module not found')
module.exports = {
module: {
compile: function(template, options, callback) {
var fileExtension = options.defaultExtension || 'dust'
dust.onLoad = function(name, callback) {
fs.readFile(Path.join(options.basedir, name + '.' + fileExtension), function(err, data) {
if (err)
throw err
callback(err, data.toString())
})
}
var compiled = dust.compileFn(template, options && options.name)
process.nextTick(function() {
callback(null, function(context, options, callback) {
compiled(context, callback)
})
})
}
},
compileMode: 'async'
}
|
Use dust.onLoad to compile templates
|
Use dust.onLoad to compile templates
|
JavaScript
|
mit
|
mikefrey/hapi-dust
|
e7afd02eb05683909c88ef0531963f4badf9d351
|
Multiselect.js
|
Multiselect.js
|
Template.Multiselect.onRendered(function multiselectOnRendered() {
let template = this;
let config = {};
if(template.data.configOptions) {
config = template.data.configOptions;
}
// autorun waits until after the dependent data has been updated
template.autorun(function multiselectAutorun() {
Template.currentData();
// afterFlush waits until the rest of the DOM elements have been built
Tracker.afterFlush(function multiselectAfterFlush() {
if(template.data.menuItems.length > 0) {
// Finally ready to initialize the multiselect
// e.g. after #each has completed creating all elements
template.$('select').multiselect(config);
}
});
});
});
Template.Multiselect.helpers({
'args': function args() {
data = Template.instance().data;
selected = false;
if(data.selectedList instanceof Array) {
selected = Boolean(data.selectedList.indexOf(this.value) > -1 );
} else {
selected = this.value === data.selectedList;
}
return _.extend({}, this, {'selectedAttr': selected ? 'selected' : ''});
}
});
|
Template.Multiselect.onRendered(function multiselectOnRendered() {
let template = this;
let config = {};
if(template.data.configOptions) {
config = template.data.configOptions;
}
// autorun waits until after the dependent data has been updated
template.autorun(function multiselectAutorun() {
Template.currentData();
// afterFlush waits until the rest of the DOM elements have been built
Tracker.afterFlush(function multiselectAfterFlush() {
if(template.data.menuItems.length > 0) {
// Finally ready to initialize the multiselect
// e.g. after #each has completed creating all elements
// If data has updated refresh the multiselect
if(template.selector) {
template.selector.multiselect('refresh');
} else {
template.selector = template.selector || template.$('select');
template.selector.multiselect(config);
}
}
});
});
});
Template.Multiselect.helpers({
'args': function args() {
let template = Template.instance();
let data = template.data;
let selected = false;
if(data.selectedList instanceof Array) {
selected = Boolean(data.selectedList.indexOf(this.value) > -1 );
} else {
selected = this.value === data.selectedList;
}
// if multiselect is initiliazed then any data changes will
// need to update the multiselect internal data
if(template.selector) {
if(selected) {
template.selector.multiselect('select', this.value);
} else {
template.selector.multiselect('deselect', this.value);
}
}
return _.extend({}, this, {'selectedAttr': selected ? 'selected' : ''});
}
});
|
Handle reinitialize case, clean up variable declarations
|
Handle reinitialize case, clean up variable declarations
|
JavaScript
|
mit
|
brucejo75/meteor-bootstrap-multiselect,brucejo75/meteor-bootstrap-multiselect
|
1f79b26808612ec1879394fad9ddc0ace5bbe1e6
|
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptors/forbidden-403.js
|
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptors/forbidden-403.js
|
/**
* 403 Forbidden Network Error Interceptor
*
* This interceptor redirects to login page when
* any 403 session expired error is returned in any of the
* network requests
*/
var LOGIN_ROUTE = '/login';
var SESSION_EXPIRED = 'session_expired';
var subdomainMatch = /https?:\/\/([^.]+)/;
module.exports = function (xhr, textStatus, errorThrown) {
if (xhr.status !== 403) return;
var error = xhr.responseJSON && xhr.responseJSON.error;
if (error === SESSION_EXPIRED) {
window.location.href = getRedirectURL();
}
};
function getRedirectURL () {
// We cannot get accountHost and username from configModel
// and userModel because of static pages. God save static pages.
var username = getUsernameFromURL(location.href);
if (!username) {
return '';
}
var newURL = location.origin.replace(subdomainMatch, function () {
return username;
});
return location.protocol + '//' + newURL + LOGIN_ROUTE;
}
function getUsernameFromURL (url) {
var usernameMatches = window.location.pathname.split('/');
if (usernameMatches.length > 2) {
return usernameMatches[2];
}
var subdomainMatches = url.match(subdomainMatch);
if (subdomainMatches) {
return subdomainMatches[1];
}
return '';
}
|
/**
* 403 Forbidden Network Error Interceptor
*
* This interceptor redirects to login page when
* any 403 session expired error is returned in any of the
* network requests
*/
var LOGIN_ROUTE = '/login?error=session_expired';
var SESSION_EXPIRED = 'session_expired';
var subdomainMatch = /https?:\/\/([^.]+)/;
module.exports = function (xhr, textStatus, errorThrown) {
if (xhr.status !== 403) return;
var error = xhr.responseJSON && xhr.responseJSON.error;
if (error === SESSION_EXPIRED) {
window.location.href = getRedirectURL();
}
};
function getRedirectURL () {
// We cannot get accountHost and username from configModel
// and userModel because of static pages. God save static pages.
var username = getUsernameFromURL(location.href);
if (!username) {
return '';
}
var newURL = location.origin.replace(subdomainMatch, function () {
return username;
});
return location.protocol + '//' + newURL + LOGIN_ROUTE;
}
function getUsernameFromURL (url) {
var usernameMatches = window.location.pathname.split('/');
if (usernameMatches.length > 2) {
return usernameMatches[2];
}
var subdomainMatches = url.match(subdomainMatch);
if (subdomainMatches) {
return subdomainMatches[1];
}
return '';
}
|
Add error parameter to forbidden interceptor
|
Add error parameter to forbidden interceptor
|
JavaScript
|
bsd-3-clause
|
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
|
53317d97c5862ab96161066546fd3a744939ca2e
|
src/Orchard.Web/Modules/TinyMce/Scripts/orchard-tinymce.js
|
src/Orchard.Web/Modules/TinyMce/Scripts/orchard-tinymce.js
|
var mediaPlugins = "";
if (mediaPickerEnabled) {
mediaPlugins += " mediapicker";
}
if (mediaLibraryEnabled) {
mediaPlugins += " medialibrary";
}
tinyMCE.init({
selector: "textarea.tinymce",
theme: "modern",
schema: "html5",
entity_encoding : "raw",
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking table contextmenu directionality",
"emoticons template paste textcolor colorpicker textpattern",
"fullscreen autoresize" + mediaPlugins
],
toolbar: "undo redo cut copy paste | bold italic | bullist numlist outdent indent formatselect | alignleft aligncenter alignright alignjustify ltr rtl | " + mediaPlugins + " link unlink charmap | code fullscreen",
convert_urls: false,
valid_elements: "*[*]",
// Shouldn't be needed due to the valid_elements setting, but TinyMCE would strip script.src without it.
extended_valid_elements: "script[type|defer|src|language]",
//menubar: false,
//statusbar: false,
skin: "orchardlightgray",
language: language,
auto_focus: autofocus,
directionality: directionality,
setup: function (editor) {
$(document).bind("localization.ui.directionalitychanged", function(event, directionality) {
editor.getBody().dir = directionality;
});
}
});
|
var mediaPlugins = "";
if (mediaPickerEnabled) {
mediaPlugins += " mediapicker";
}
if (mediaLibraryEnabled) {
mediaPlugins += " medialibrary";
}
tinyMCE.init({
selector: "textarea.tinymce",
theme: "modern",
schema: "html5",
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking table contextmenu directionality",
"emoticons template paste textcolor colorpicker textpattern",
"fullscreen autoresize" + mediaPlugins
],
toolbar: "undo redo cut copy paste | bold italic | bullist numlist outdent indent formatselect | alignleft aligncenter alignright alignjustify ltr rtl | " + mediaPlugins + " link unlink charmap | code fullscreen",
convert_urls: false,
valid_elements: "*[*]",
// Shouldn't be needed due to the valid_elements setting, but TinyMCE would strip script.src without it.
extended_valid_elements: "script[type|defer|src|language]",
//menubar: false,
//statusbar: false,
skin: "orchardlightgray",
language: language,
auto_focus: autofocus,
directionality: directionality,
setup: function (editor) {
$(document).bind("localization.ui.directionalitychanged", function(event, directionality) {
editor.getBody().dir = directionality;
});
}
});
|
Revert "Fixing that TinyMCE is encoding special chars"
|
Revert "Fixing that TinyMCE is encoding special chars"
This reverts commit 188fabe233c3c9ebef04ccd29c1a07e8a520e882.
|
JavaScript
|
bsd-3-clause
|
armanforghani/Orchard,LaserSrl/Orchard,Serlead/Orchard,AdvantageCS/Orchard,tobydodds/folklife,geertdoornbos/Orchard,hannan-azam/Orchard,rtpHarry/Orchard,brownjordaninternational/OrchardCMS,jagraz/Orchard,gcsuk/Orchard,JRKelso/Orchard,TalaveraTechnologySolutions/Orchard,jimasp/Orchard,sfmskywalker/Orchard,rtpHarry/Orchard,neTp9c/Orchard,SzymonSel/Orchard,hbulzy/Orchard,JRKelso/Orchard,Praggie/Orchard,vairam-svs/Orchard,Dolphinsimon/Orchard,Fogolan/OrchardForWork,SzymonSel/Orchard,tobydodds/folklife,yersans/Orchard,dcinzona/Orchard,jimasp/Orchard,vairam-svs/Orchard,armanforghani/Orchard,phillipsj/Orchard,abhishekluv/Orchard,jtkech/Orchard,sfmskywalker/Orchard,hbulzy/Orchard,grapto/Orchard.CloudBust,dmitry-urenev/extended-orchard-cms-v10.1,dmitry-urenev/extended-orchard-cms-v10.1,abhishekluv/Orchard,johnnyqian/Orchard,JRKelso/Orchard,SzymonSel/Orchard,phillipsj/Orchard,Dolphinsimon/Orchard,LaserSrl/Orchard,hbulzy/Orchard,AdvantageCS/Orchard,SzymonSel/Orchard,LaserSrl/Orchard,grapto/Orchard.CloudBust,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,abhishekluv/Orchard,johnnyqian/Orchard,Codinlab/Orchard,armanforghani/Orchard,geertdoornbos/Orchard,jimasp/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,jimasp/Orchard,jersiovic/Orchard,JRKelso/Orchard,TalaveraTechnologySolutions/Orchard,jagraz/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,aaronamm/Orchard,mvarblow/Orchard,jchenga/Orchard,Dolphinsimon/Orchard,neTp9c/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,brownjordaninternational/OrchardCMS,sfmskywalker/Orchard,jersiovic/Orchard,hannan-azam/Orchard,SouleDesigns/SouleDesigns.Orchard,aaronamm/Orchard,mvarblow/Orchard,Praggie/Orchard,mvarblow/Orchard,Fogolan/OrchardForWork,grapto/Orchard.CloudBust,Praggie/Orchard,johnnyqian/Orchard,TalaveraTechnologySolutions/Orchard,omidnasri/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard,aaronamm/Orchard,hannan-azam/Orchard,TalaveraTechnologySolutions/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,phillipsj/Orchard,hbulzy/Orchard,omidnasri/Orchard,Dolphinsimon/Orchard,gcsuk/Orchard,IDeliverable/Orchard,brownjordaninternational/OrchardCMS,OrchardCMS/Orchard,hbulzy/Orchard,li0803/Orchard,ehe888/Orchard,gcsuk/Orchard,bedegaming-aleksej/Orchard,jersiovic/Orchard,omidnasri/Orchard,IDeliverable/Orchard,AdvantageCS/Orchard,jagraz/Orchard,gcsuk/Orchard,jersiovic/Orchard,li0803/Orchard,armanforghani/Orchard,fassetar/Orchard,dcinzona/Orchard,geertdoornbos/Orchard,Lombiq/Orchard,tobydodds/folklife,Fogolan/OrchardForWork,fassetar/Orchard,SouleDesigns/SouleDesigns.Orchard,xkproject/Orchard,jtkech/Orchard,Lombiq/Orchard,Serlead/Orchard,armanforghani/Orchard,tobydodds/folklife,hannan-azam/Orchard,abhishekluv/Orchard,vairam-svs/Orchard,dcinzona/Orchard,Codinlab/Orchard,LaserSrl/Orchard,fassetar/Orchard,Lombiq/Orchard,OrchardCMS/Orchard,omidnasri/Orchard,dcinzona/Orchard,fassetar/Orchard,grapto/Orchard.CloudBust,Lombiq/Orchard,tobydodds/folklife,dmitry-urenev/extended-orchard-cms-v10.1,xkproject/Orchard,geertdoornbos/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,bedegaming-aleksej/Orchard,abhishekluv/Orchard,jchenga/Orchard,ehe888/Orchard,Codinlab/Orchard,SouleDesigns/SouleDesigns.Orchard,johnnyqian/Orchard,grapto/Orchard.CloudBust,Lombiq/Orchard,AdvantageCS/Orchard,SzymonSel/Orchard,Serlead/Orchard,mvarblow/Orchard,IDeliverable/Orchard,TalaveraTechnologySolutions/Orchard,Praggie/Orchard,li0803/Orchard,rtpHarry/Orchard,neTp9c/Orchard,yersans/Orchard,aaronamm/Orchard,jtkech/Orchard,rtpHarry/Orchard,jtkech/Orchard,dcinzona/Orchard,Codinlab/Orchard,jersiovic/Orchard,OrchardCMS/Orchard,abhishekluv/Orchard,xkproject/Orchard,Praggie/Orchard,vairam-svs/Orchard,hannan-azam/Orchard,IDeliverable/Orchard,yersans/Orchard,yersans/Orchard,TalaveraTechnologySolutions/Orchard,jimasp/Orchard,aaronamm/Orchard,johnnyqian/Orchard,AdvantageCS/Orchard,omidnasri/Orchard,li0803/Orchard,fassetar/Orchard,LaserSrl/Orchard,Fogolan/OrchardForWork,omidnasri/Orchard,tobydodds/folklife,JRKelso/Orchard,SouleDesigns/SouleDesigns.Orchard,OrchardCMS/Orchard,xkproject/Orchard,phillipsj/Orchard,sfmskywalker/Orchard,rtpHarry/Orchard,ehe888/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,OrchardCMS/Orchard,brownjordaninternational/OrchardCMS,bedegaming-aleksej/Orchard,jtkech/Orchard,ehe888/Orchard,mvarblow/Orchard,omidnasri/Orchard,bedegaming-aleksej/Orchard,TalaveraTechnologySolutions/Orchard,brownjordaninternational/OrchardCMS,bedegaming-aleksej/Orchard,omidnasri/Orchard,jagraz/Orchard,vairam-svs/Orchard,Codinlab/Orchard,jagraz/Orchard,TalaveraTechnologySolutions/Orchard,omidnasri/Orchard,gcsuk/Orchard,li0803/Orchard,grapto/Orchard.CloudBust,jchenga/Orchard,ehe888/Orchard,jchenga/Orchard,Dolphinsimon/Orchard,neTp9c/Orchard,Serlead/Orchard,Fogolan/OrchardForWork,geertdoornbos/Orchard,yersans/Orchard,Serlead/Orchard,xkproject/Orchard,phillipsj/Orchard,jchenga/Orchard,SouleDesigns/SouleDesigns.Orchard,neTp9c/Orchard,sfmskywalker/Orchard,IDeliverable/Orchard
|
8feed977590b87f7936992c58235b99b91b2028a
|
src/js/controllers/navbar_top.js
|
src/js/controllers/navbar_top.js
|
'use strict';
/**
* @ngdoc function
* @name Pear2Pear.controller:NavbarTopCtrl
* @description
* # NavbarTop Ctrl
*/
angular.module('Pear2Pear')
.controller(
'NavbarTopCtrl', [
'SwellRTSession', '$scope',
function(SwellRTSession, $scope){
var getSharedMode = function(){
if ($scope.project){
return $scope.project.shareMode;
}
return null;
};
$scope.shareIcon = function shareIcon() {
switch (getSharedMode()) {
case 'link':
return 'fa-link';
case 'public':
return 'fa-globe';
default:
return '';
}
};
$scope.isShared = function(mode) {
if ($scope.project){
return getSharedMode() === mode;
}
return false;
};
$scope.setShared = function setShared(mode){
$scope.project.setShareMode(mode);
};
$scope.timestampProjectAccess = function(){
$scope.project.timestampProjectAccess();
};
}]);
|
'use strict';
/**
* @ngdoc function
* @name Pear2Pear.controller:NavbarTopCtrl
* @description
* # NavbarTop Ctrl
*/
angular.module('Pear2Pear')
.controller(
'NavbarTopCtrl', [
'SwellRTSession', '$scope',
function(SwellRTSession, $scope){
var getSharedMode = function(){
if ($scope.project){
return $scope.project.shareMode;
}
return null;
};
$scope.$on('$locationChangeStart', function(event) {
SwellRTSession.onLoad(function(){
if ($route.current.params.id){
pear.projects.find($route.current.params.id)
.then(function(proxy) {
$scope.project = proxy;
});
}
});
});
$scope.shareIcon = function shareIcon() {
switch (getSharedMode()) {
case 'link':
return 'fa-link';
case 'public':
return 'fa-globe';
default:
return '';
}
};
$scope.isShared = function(mode) {
if ($scope.project){
return getSharedMode() === mode;
}
return false;
};
$scope.setShared = function setShared(mode){
$scope.project.setShareMode(mode);
};
$scope.timestampProjectAccess = function(){
$scope.project.timestampProjectAccess();
};
}]);
|
Revert "avoid unnecesary call to onLoad"
|
Revert "avoid unnecesary call to onLoad"
This reverts commit 5a81300cb8a99c7428d9aeea26276d4415efcf64.
|
JavaScript
|
agpl-3.0
|
Grasia/teem,P2Pvalue/teem,P2Pvalue/teem,Grasia/teem,P2Pvalue/teem,Grasia/teem,P2Pvalue/pear2pear,P2Pvalue/pear2pear
|
4d398ea4ccecad68c5938c266506f8a4a30acc2d
|
src/javascript/binary/websocket_pages/user/telegram_bot.js
|
src/javascript/binary/websocket_pages/user/telegram_bot.js
|
const TelegramBot = (() => {
'use strict';
const form = '#frm_telegram_bot';
const onLoad = () => {
const bot_name = 'binary_test_bot';
$(form).on('submit', (e) => {
e.preventDefault();
const token = $('#token').val();
const url = `https://t.me/${bot_name}/?start=${token}`;
window.location.assign(url);
});
};
const onUnload = () => {
$(form).off('submit');
};
return {
onLoad : onLoad,
onUnload: onUnload,
};
})();
module.exports = TelegramBot;
|
const FormManager = require('../../common_functions/form_manager');
const TelegramBot = (() => {
'use strict';
const form = '#frm_telegram_bot';
const onLoad = () => {
const bot_name = 'binary_test_bot';
FormManager.init(form, [
{ selector: '#token', validations: ['req'], exclude_request: 1 }
]);
FormManager.handleSubmit({
form_selector: form,
fnc_response_handler: () => {
const token = $('#token').val();
const url = `https://t.me/${bot_name}/?start=${token}`;
window.location.assign(url);
}
});
};
const onUnload = () => {
$(form).off('submit');
};
return {
onLoad: onLoad,
onUnload: onUnload,
};
})();
module.exports = TelegramBot;
|
Rewrite code to use formManager
|
Rewrite code to use formManager
|
JavaScript
|
apache-2.0
|
raunakkathuria/binary-static,ashkanx/binary-static,negar-binary/binary-static,4p00rv/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,4p00rv/binary-static,binary-com/binary-static,kellybinary/binary-static,raunakkathuria/binary-static,negar-binary/binary-static,binary-static-deployed/binary-static,binary-com/binary-static,kellybinary/binary-static,kellybinary/binary-static,negar-binary/binary-static,raunakkathuria/binary-static,4p00rv/binary-static,ashkanx/binary-static
|
979b21e574ab78debf0bc247f94acac0c33f3ca3
|
components/map/components/legend/components/layer-statement/config.js
|
components/map/components/legend/components/layer-statement/config.js
|
export default {
lossLayer: {
// if we want to add this disclaimer (with the hover) to a widget in the legend,
// - type must be 'lossLayer' in the 'legend' section of the layer, OR
// - the layer has to have 'isLossLayer=true' in the metadata.
// For the second case (isLossLayer), type is being overwritten to 'lossLayer'
// in dataset-provider-actions#L56 (add more special here cases if needed)
statementPlain: 'Tree cover loss',
statementHighlight: 'is not always deforestation.',
tooltipDesc:
'Loss of tree cover may occur for many reasons, including deforestation, fire, and logging within the course of sustainable forestry operations. In sustainably managed forests, the “loss” will eventually show up as “gain”, as young trees get large enough to achieve canopy closure.',
},
isoLayer: {
statementPlain: 'This layer is only available for ',
statementHighlight: 'certain countries.',
},
lossDriverLayer: {
statementHighlight: 'Hover for details on drivers classes.',
tooltipDesc: `Commodity driven deforestation: Large-scale deforestation linked primarily to commercial agricultural expansion.\n
Shifting agriculture: Temporary loss or permanent deforestation due to small- and medium-scale agriculture.\n
Forestry: Temporary loss from plantation and natural forest harvesting, with some deforestation of primary forests.\n
Wildfire: Temporary loss, does not include fire clearing for agriculture.\n
Urbanization: Deforestation for expansion/intensification of urban centers.`,
},
};
|
export default {
lossLayer: {
// if we want to add this disclaimer (with the hover) to a widget in the legend,
// - type must be 'lossLayer' in the 'legend' section of the layer, OR
// - the layer has to have 'isLossLayer=true' in the metadata.
// For the second case (isLossLayer), type is being overwritten to 'lossLayer'
// in dataset-provider-actions#L56 (add more special here cases if needed)
statementPlain: 'Tree cover loss',
statementHighlight: ' is not always deforestation.',
tooltipDesc:
'Loss of tree cover may occur for many reasons, including deforestation, fire, and logging within the course of sustainable forestry operations. In sustainably managed forests, the “loss” will eventually show up as “gain”, as young trees get large enough to achieve canopy closure.',
},
isoLayer: {
statementPlain: 'This layer is only available for ',
statementHighlight: 'certain countries.',
},
lossDriverLayer: {
statementHighlight: 'Hover for details on drivers classes.',
tooltipDesc: `Commodity driven deforestation: Large-scale deforestation linked primarily to commercial agricultural expansion.\n
Shifting agriculture: Temporary loss or permanent deforestation due to small- and medium-scale agriculture.\n
Forestry: Temporary loss from plantation and natural forest harvesting, with some deforestation of primary forests.\n
Wildfire: Temporary loss, does not include fire clearing for agriculture.\n
Urbanization: Deforestation for expansion/intensification of urban centers.`,
},
};
|
Add space to legend text
|
Add space to legend text
|
JavaScript
|
mit
|
Vizzuality/gfw,Vizzuality/gfw
|
d6593eeea21a624ff0bb1b1d43f433f77ae55e47
|
src/reducers/reducer_workload.js
|
src/reducers/reducer_workload.js
|
export default function(state={}, action) {
switch(action.type) {
case 'example_data':
return 'The action controller worked properly'
default:
return state;
}
}
|
import { FETCH_OPPS } from '../actions';
export default function(state={}, action) {
switch(action.type) {
case FETCH_OPPS:
return action.payload
default:
return state;
}
}
|
Modify switch statement in WorkloadReducer
|
Modify switch statement in WorkloadReducer
|
JavaScript
|
mit
|
danshapiro-optimizely/bandwidth,danshapiro-optimizely/bandwidth
|
caf0a2289145c699a853aa75449bbaebacb0b7e9
|
webpack.production.config.js
|
webpack.production.config.js
|
'use strict'
const webpack = require('webpack')
const path = require('path')
const configuration = {
entry: path.resolve(__dirname, 'app'),
output: {
path: path.resolve(__dirname, 'public'),
filename: '[name].js'
},
module: {
loaders: [
{ test: /\.js?$/, loader: 'react-hot-loader', include: path.join(__dirname, 'app') },
{ test: /\.js?$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.scss$/, loaders: [ 'style-loader', 'css-loader', 'sass-loader' ] }
]
},
plugins: [
new webpack.DefinePlugin(
{
'process.env.NODE_ENV': JSON.stringify('production')
}
),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.OccurrenceOrderPlugin()
],
devtool: 'cheap-source-map',
cache: true
}
module.exports = configuration
|
'use strict'
const webpack = require('webpack')
const path = require('path')
var HtmlWebpackPlugin = require('html-webpack-plugin')
const configuration = {
entry: [
path.resolve(__dirname, 'app')
],
output: {
path: path.resolve(__dirname, 'public/build/'),
filename: '[hash].js'
},
module: {
loaders: [
{ test: /\.js?$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.scss$/, loaders: [ 'style-loader', 'css-loader', 'sass-loader' ] },
{ test: /\.html$/, loaders: [ 'html-loader' ] }
]
},
plugins: [
new webpack.DefinePlugin(
{
'process.env.NODE_ENV': JSON.stringify('production')
}
),
new HtmlWebpackPlugin(
{
template: path.resolve(__dirname, 'public/index.html'),
favicon: path.resolve(__dirname, 'public/favicon.ico'),
inject: true,
minify: {}
}
),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.OccurrenceOrderPlugin()
],
devtool: 'cheap-source-map',
cache: true
}
module.exports = configuration
|
Add a new build process for the production environment.
|
Add a new build process for the production environment.
|
JavaScript
|
mit
|
rhberro/the-react-client,rhberro/the-react-client
|
048cc348d0bd0b614e05913cc5619b54b174463e
|
src/server/services/discovery.js
|
src/server/services/discovery.js
|
import Promise from 'bluebird';
import { lookupServiceAsync } from '../utils/lookup-service';
function findService(fullyQualifiedName) {
// Get just the service name from the fully qualified name
let nameParts = fullyQualifiedName.split('.');
let serviceName = nameParts[nameParts.length - 1];
// Insert a dash before any capital letters, convert to lowercase, and remove any leading dash
serviceName = serviceName.replace(/[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/g, '-$&').toLowerCase();
if (serviceName.startsWith('-')) {
serviceName = serviceName.substr(1);
}
// We should have something like 'video-catalog-service' now, so try and find the service
return lookupServiceAsync(serviceName).then(hosts => hosts[0]);
}
/**
* Finds the location for a service from the fully qualified name and returns a Promise that resolves to a
* string of the IP:Port where that service can be found.
*/
export const findServiceAsync = Promise.method(findService);
|
import Promise from 'bluebird';
import { lookupServiceAsync } from '../utils/lookup-service';
function findService(fullyQualifiedName) {
// Get just the service name from the fully qualified name
let nameParts = fullyQualifiedName.split('.');
let serviceName = nameParts[nameParts.length - 1];
// We should have something like 'video-catalog-service' now, so try and find the service
return lookupServiceAsync(serviceName).then(hosts => hosts[0]);
}
/**
* Finds the location for a service from the fully qualified name and returns a Promise that resolves to a
* string of the IP:Port where that service can be found.
*/
export const findServiceAsync = Promise.method(findService);
|
Use the short service name when resolving Grpc services
|
Use the short service name when resolving Grpc services
|
JavaScript
|
apache-2.0
|
KillrVideo/killrvideo-web,KillrVideo/killrvideo-web,KillrVideo/killrvideo-web
|
fb8473d0e16f20b8828dd1692206e86497bcf507
|
client/MobiApp.js
|
client/MobiApp.js
|
Geolocation.latLng()
Template.newIssue.events({
'submit form': function(){
event.preventDefault();
var title = event.target.title.value;
var description = event.target.description.value;
var imageURL = Session.get('imageURL');
console.log(title, description);
if (title && description && Geolocation.latLng()) {
Issues.insert({
title: title,
description: description,
status: 'open',
lat: Geolocation.latLng().lat,
lng: Geolocation.latLng().lng,
userID: Meteor.userId(),
imageURL: imageURL,
createdAt: new Date(),
lastModified: new Date()
});
Router.go('/issues-list');
} else {
console.log("form not valid");
}
}
});
Template.dashboard.helpers({
title: function(){
return "Status of Submitted"
},
issues: function (){
// Show newest tasks at the top
return Issues.find({'userID': this.userId}, {sort: {createdAt: 1}})
}
});
Template.task.helpers({
label_mapper: function(par){
var dict = {};
//Updates labels for submitted issues
dict["open"] = "-warning";
dict["rejected"] = "-danger";
dict["solved"] = "-success";
dict["pending"] = "-info"
return dict[par]
}
});
|
Geolocation.latLng()
Template.newIssue.events({
'submit form': function(){
event.preventDefault();
var title = event.target.title.value;
var description = event.target.description.value;
var imageURL = Session.get('imageURL');
console.log(title, description);
if (title && description && Geolocation.latLng()) {
Issues.insert({
title: title,
description: description,
status: 'open',
lat: Geolocation.latLng().lat,
lng: Geolocation.latLng().lng,
userID: Meteor.userId(),
imageURL: imageURL,
createdAt: new Date(),
lastModified: new Date()
});
Router.go('/issues-list');
} else {
console.log("form not valid");
}
}
});
Template.IssuesList.helpers({
title: function(){
return "Status of Submitted"
},
issues: function (){
// Show newest tasks at the top
return Issues.find({'userID': Meteor.userId()}, {sort: {createdAt: 1}})
}
});
Template.task.helpers({
label_mapper: function(par){
var dict = {};
//Updates labels for submitted issues
dict["open"] = "-warning";
dict["rejected"] = "-danger";
dict["solved"] = "-success";
dict["pending"] = "-info"
return dict[par]
}
});
|
Fix issue list after change of authentication package
|
Fix issue list after change of authentication package
|
JavaScript
|
agpl-3.0
|
kennyzlei/MobiApp,kennyzlei/MobiApp
|
dee7c234c5a6e98a7d21a99ae5539fe978ca2d4e
|
src/Logger.js
|
src/Logger.js
|
/**
* @flow
*/
import bunyan from 'bunyan';
import path from 'path';
import UserSettings from './UserSettings';
class ConsoleRawStream {
write(rec) {
if (rec.level < bunyan.INFO) {
console.log(rec);
} else if (rec.level < bunyan.WARN) {
console.info(rec);
} else if (rec.level < bunyan.ERROR) {
console.warn(rec);
} else {
console.error(rec);
}
}
}
let logger = bunyan.createLogger({
name: 'exponent',
serializers: bunyan.stdSerializers,
streams: [
{
level: 'debug',
type: 'rotating-file',
path: path.join(UserSettings.dotExponentHomeDirectory(), 'log'),
period: '1d', // daily rotation
count: 3, // keep 3 back copies
},
...(process.env.DEBUG && process.env.NODE_ENV !== 'production' ? [{
type: 'raw',
stream: new ConsoleRawStream(),
closeOnExit: false,
level: 'debug',
}] : []),
],
});
logger.notifications = logger.child({type: 'notifications'});
logger.global = logger.child({type: 'global'});
logger.DEBUG = bunyan.DEBUG;
logger.INFO = bunyan.INFO;
logger.WARN = bunyan.WARN;
logger.ERROR = bunyan.ERROR;
logger.clearNotification = (id: string) => {
if (Config.useReduxNotifications) {
state.store.dispatch(state.actions.notifications.clearGlobal(id));
}
}
export default logger;
|
/**
* @flow
*/
import bunyan from 'bunyan';
import path from 'path';
import UserSettings from './UserSettings';
class ConsoleRawStream {
write(rec) {
if (rec.level < bunyan.INFO) {
console.log(rec);
} else if (rec.level < bunyan.WARN) {
console.info(rec);
} else if (rec.level < bunyan.ERROR) {
console.warn(rec);
} else {
console.error(rec);
}
}
}
let logger = bunyan.createLogger({
name: 'exponent',
serializers: bunyan.stdSerializers,
streams: [
{
level: 'debug',
type: 'rotating-file',
path: path.join(UserSettings.dotExponentHomeDirectory(), 'log'),
period: '1d', // daily rotation
count: 3, // keep 3 back copies
},
...(process.env.DEBUG && process.env.NODE_ENV !== 'production' ? [{
type: 'raw',
stream: new ConsoleRawStream(),
closeOnExit: false,
level: 'debug',
}] : []),
],
});
logger.notifications = logger.child({type: 'notifications'});
logger.global = logger.child({type: 'global'});
logger.DEBUG = bunyan.DEBUG;
logger.INFO = bunyan.INFO;
logger.WARN = bunyan.WARN;
logger.ERROR = bunyan.ERROR;
export default logger;
|
Remove stray unused redux notif function.
|
Remove stray unused redux notif function.
fbshipit-source-id: bdf73a4
|
JavaScript
|
mit
|
exponentjs/xdl,exponentjs/xdl,exponentjs/xdl
|
593ec57633fbef471f09501e0c886899e51bd467
|
code/geosearch.js
|
code/geosearch.js
|
// GEOSEARCH /////////////////////////////////////////////////////////
window.setupGeosearch = function() {
$('#geosearch').keypress(function(e) {
if((e.keyCode ? e.keyCode : e.which) != 13) return;
var search = $(this).val();
if (!runHooks('geoSearch', search)) {
return;
}
$.getJSON(NOMINATIM + encodeURIComponent(search), function(data) {
if(!data || !data[0]) return;
var b = data[0].boundingbox;
if(!b) return;
var southWest = new L.LatLng(b[0], b[2]),
northEast = new L.LatLng(b[1], b[3]),
bounds = new L.LatLngBounds(southWest, northEast);
window.map.fitBounds(bounds);
if(window.isSmartphone()) window.smartphone.mapButton.click();
});
e.preventDefault();
});
$('#geosearchwrapper img').click(function(){
map.locate({setView : true});;
});
}
|
// GEOSEARCH /////////////////////////////////////////////////////////
window.setupGeosearch = function() {
$('#geosearch').keypress(function(e) {
if((e.keyCode ? e.keyCode : e.which) != 13) return;
var search = $(this).val();
if (!runHooks('geoSearch', search)) {
return;
}
$.getJSON(NOMINATIM + encodeURIComponent(search), function(data) {
if(!data || !data[0]) return;
var b = data[0].boundingbox;
if(!b) return;
var southWest = new L.LatLng(b[0], b[2]),
northEast = new L.LatLng(b[1], b[3]),
bounds = new L.LatLngBounds(southWest, northEast);
window.map.fitBounds(bounds);
if(window.isSmartphone()) window.smartphone.mapButton.click();
});
e.preventDefault();
});
$('#geosearchwrapper img').click(function(){
map.locate({setView : true, maxZoom: 13});;
});
}
|
Set maxZoom = 13 for desktop locate button too.
|
Set maxZoom = 13 for desktop locate button too.
|
JavaScript
|
isc
|
tony2001/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion
|
b9399f212ba6744374a0a54d4b06b21200865bb4
|
src/server/pages.js
|
src/server/pages.js
|
import nextRoutes from 'next-routes';
const pages = nextRoutes();
pages
.add('signin', '/signin/:token?')
.add('createEvent', '/:parentCollectiveSlug/events/(new|create)')
.add('events-iframe', '/:collectiveSlug/events/iframe')
.add('event', '/:parentCollectiveSlug/events/:eventSlug')
.add('editEvent', '/:parentCollectiveSlug/events/:eventSlug/edit')
.add('events', '/:collectiveSlug/events')
.add('tiers', '/:collectiveSlug/tiers')
.add('editTiers', '/:collectiveSlug/tiers/edit')
.add('orderCollectiveTier', '/:collectiveSlug/order/:TierId/:amount?/:interval?', 'createOrder')
.add('orderEventTier', '/:collectiveSlug/events/:eventSlug/order/:TierId', 'createOrder')
.add('donate', '/:collectiveSlug/:verb(donate|pay|contribute)/:amount?/:interval?', 'createOrder')
.add('tiers-iframe', '/:collectiveSlug/tiers/iframe')
.add('transactions', '/:collectiveSlug/transactions')
.add('nametags', '/:parentCollectiveSlug/events/:eventSlug/nametags')
.add('button', '/:collectiveSlug/:verb(contribute|donate)/button')
.add('collective', '/:slug')
.add('editCollective', '/:slug/edit')
module.exports = pages;
|
import nextRoutes from 'next-routes';
const pages = nextRoutes();
pages
.add('widgets', '/widgets')
.add('tos', '/tos')
.add('privacypolicy', '/privacypolicy')
.add('signin', '/signin/:token?')
.add('button', '/:collectiveSlug/:verb(contribute|donate)/button')
.add('createEvent', '/:parentCollectiveSlug/events/(new|create)')
.add('events-iframe', '/:collectiveSlug/events/iframe')
.add('event', '/:parentCollectiveSlug/events/:eventSlug')
.add('editEvent', '/:parentCollectiveSlug/events/:eventSlug/edit')
.add('events', '/:collectiveSlug/events')
.add('tiers', '/:collectiveSlug/tiers')
.add('editTiers', '/:collectiveSlug/tiers/edit')
.add('orderCollectiveTier', '/:collectiveSlug/order/:TierId/:amount?/:interval?', 'createOrder')
.add('orderEventTier', '/:collectiveSlug/events/:eventSlug/order/:TierId', 'createOrder')
.add('donate', '/:collectiveSlug/:verb(donate|pay|contribute)/:amount?/:interval?', 'createOrder')
.add('tiers-iframe', '/:collectiveSlug/tiers/iframe')
.add('transactions', '/:collectiveSlug/transactions')
.add('expenses', '/:collectiveSlug/expenses')
.add('nametags', '/:parentCollectiveSlug/events/:eventSlug/nametags')
.add('collective', '/:slug')
.add('editCollective', '/:slug/edit')
module.exports = pages;
|
Fix for /widgets, /tos, /privacypolicy, /:slug/:verb/button
|
Fix for /widgets, /tos, /privacypolicy, /:slug/:verb/button
|
JavaScript
|
mit
|
OpenCollective/frontend
|
b27471e3ae289e4b3e97302ff7a5e9cc4ace59e8
|
src/Result.js
|
src/Result.js
|
'use strict'
var chalk = require('chalk')
var deepEqual = require('deep-equal')
var indent = require('./indent')
var os = require('os')
const CHECK = '\u2713'
const CROSS = '\u2717'
const PASS_COLOR = 'green'
const FAIL_COLOR = 'red'
module.exports = class Result {
constructor (runnable, options) {
options = options || {}
this.runnable = runnable
this.error = options.error
this.results = options.results || []
this.actual = options.actual
this.expected = options.expected
if (this.error === undefined && (this.actual !== undefined || this.expected !== undefined)) {
this.error = !deepEqual(this.actual, this.expected, { strict: true })
}
}
isErroring () {
return Boolean(this.error || this.results.some(result => result.isErroring()))
}
toString () {
var isErroring = this.isErroring()
var status = isErroring ? CROSS : CHECK
var color = isErroring ? FAIL_COLOR : PASS_COLOR
return chalk[color](`${status} ${this.runnable}`)
}
toTree () {
var indented = this.results.map(result => indent(result.toTree()))
return [this.toString()].concat(indented).join(os.EOL)
}
}
|
'use strict'
var chalk = require('chalk')
var deepEqual = require('deep-equal')
var indent = require('./indent')
var os = require('os')
const CHECK = '✓'
const CROSS = '✗'
const PASS_COLOR = 'green'
const FAIL_COLOR = 'red'
module.exports = class Result {
constructor (runnable, options) {
options = options || {}
this.runnable = runnable
this.error = options.error
this.results = options.results || []
this.actual = options.actual
this.expected = options.expected
if (this.error === undefined && (this.actual !== undefined || this.expected !== undefined)) {
this.error = !deepEqual(this.actual, this.expected, { strict: true })
}
}
isErroring () {
return Boolean(this.error || this.results.some(result => result.isErroring()))
}
toString () {
var isErroring = this.isErroring()
var status = isErroring ? CROSS : CHECK
var color = isErroring ? FAIL_COLOR : PASS_COLOR
return chalk[color](`${status} ${this.runnable}`)
}
toTree () {
var indented = this.results.map(result => indent(result.toTree()))
return [this.toString()].concat(indented).join(os.EOL)
}
}
|
Use unicode special characters directly in source
|
Use unicode special characters directly in source
|
JavaScript
|
isc
|
nickmccurdy/purespec
|
1f8b40ecfe9a2c7d7c31a0f71a72049dc413749d
|
src/issue-strategies/bug-maintenance.js
|
src/issue-strategies/bug-maintenance.js
|
export function apply(issue, jiraClientAPI) {
if(issue === null || issue.fields.status.statusCategory.colorName !== 'yellow') {
return Promise.reject(new Error(`Cannot commit against this issue ${issue.key}`));
}
return Promise.resolve(true);
}
|
export function apply(issue, jiraClientAPI) {
if(issue === null || issue.fields.status.statusCategory.colorName !== 'yellow') {
return Promise.reject(new Error(`Cannot commit against this issue ${issue.key}. Make sure the issue exists and has a yellow status`));
}
return Promise.resolve(true);
}
|
Add additional issue status error info
|
Add additional issue status error info
Closes #23
|
JavaScript
|
mit
|
DarriusWrightGD/jira-precommit-hook,TWExchangeSolutions/jira-precommit-hook
|
21edc4ec471a55a0dce9dd2c7d3e84a5576aaf84
|
src/js/graphic/background/background.js
|
src/js/graphic/background/background.js
|
import Geometric from './geometric/geometric.js'
export default class Background
{
static draw(p)
{
Background.changeColor(p)
Background.translateCamera(p)
Background.translateCameraByMouse(p)
Geometric.draw(p)
}
static changeColor(p)
{
const hexColorMax = 255
const radianX2 = p.PI * 2
const fps = 60
const fpsGear = 1 / 20
const radianPerFrame = radianX2 / fps
const radianPerFrameGeared = radianPerFrame * fpsGear
const fpsReal = fps / fpsGear
const frame = p.frameCount % fpsReal
const radian = radianPerFrameGeared * frame
const sine = p.sin(radian)
const sineMapped1 = (sine + 1) / 2
const hexColor = sineMapped1 * hexColorMax
p.background(hexColor)
}
static translateCamera(p)
{
const xTranslate = p.frameCount * 0.01
const yTranslate = 0
const zTranslate = -(p.windowHeight / 2)
p.translate(xTranslate, yTranslate, zTranslate)
}
static translateCameraByMouse(p)
{
const xTranslate = -p.mouseX / 10
const yTranslate = -p.mouseY / 10
p.translate(xTranslate, yTranslate)
}
}
|
import Geometric from './geometric/geometric.js'
export default class Background
{
static draw(p)
{
Background.changeColor(p)
Background.translateCamera(p)
Background.translateCameraByMouse(p)
Geometric.draw(p)
}
static changeColor(p)
{
const hexColorMax = 255
const radianX2 = p.PI * 2
const fps = 60
const fpsGear = 1 / 20
const radianPerFrame = radianX2 / fps
const radianPerFrameGeared = radianPerFrame * fpsGear
const fpsReal = fps / fpsGear
const frame = p.frameCount % fpsReal
const radian = radianPerFrameGeared * frame
const sine = p.sin(radian)
const sineMapped1 = (sine + 1) / 2
const hexColor = sineMapped1 * hexColorMax
p.background(hexColor)
}
static translateCamera(p)
{
const xTranslate = p.frameCount * 0.01
const yTranslate = 0
let zTranslate = -(p.width / 3)
if (window.screen.width < 600) {
zTranslate = window.screen.width / 5
}
p.translate(xTranslate, yTranslate, zTranslate)
}
static translateCameraByMouse(p)
{
const xTranslate = -p.mouseX / 10
const yTranslate = -p.mouseY / 10
p.translate(xTranslate, yTranslate)
}
}
|
Fix main camera zTranslation responsive issue
|
Fix main camera zTranslation responsive issue
|
JavaScript
|
mit
|
yuki-nit2a/yuki.nit2a.com,yuki-nit2a/yuki.nit2a.com
|
44ddb35699ed2a7cff9e5dc2f4b36823931a57b6
|
app/process_request.js
|
app/process_request.js
|
var requirejs = require('requirejs');
var PageConfig = requirejs('page_config');
var get_dashboard_and_render = require('./server/mixins/get_dashboard_and_render');
var renderContent = function (req, res, model) {
model.set(PageConfig.commonConfig(req));
var ControllerClass = model.get('controller');
var controller = new ControllerClass({
model: model,
url: req.originalUrl
});
controller.once('ready', function () {
res.set('Cache-Control', 'public, max-age=600');
if (model.get('published') !== true) {
res.set('X-Robots-Tag', 'none');
}
req['spotlight-dashboard-slug'] = model.get('slug');
res.send(controller.html);
});
controller.render({ init: true });
return controller;
};
var setup = function (req, res) {
var client_instance = setup.get_dashboard_and_render(req, res, setup.renderContent);
//I have no idea what this does, can't find anything obvious in the docs or this app.
client_instance.set('script', true);
client_instance.setPath(req.url.replace('/performance', ''));
};
setup.renderContent = renderContent;
setup.get_dashboard_and_render = get_dashboard_and_render;
module.exports = setup;
|
var requirejs = require('requirejs');
var PageConfig = requirejs('page_config');
var get_dashboard_and_render = require('./server/mixins/get_dashboard_and_render');
var renderContent = function (req, res, model) {
model.set(PageConfig.commonConfig(req));
var ControllerClass = model.get('controller');
var controller = new ControllerClass({
model: model,
url: req.originalUrl
});
controller.once('ready', function () {
res.set('Cache-Control', 'public, max-age=600');
if (model.get('published') !== true) {
res.set('X-Robots-Tag', 'none');
}
req['spotlight-dashboard-slug'] = model.get('slug');
res.send(controller.html);
});
controller.render({ init: true });
return controller;
};
var setup = function (req, res) {
var client_instance = setup.get_dashboard_and_render(req, res, setup.renderContent);
client_instance.set('script', true);
client_instance.setPath(req.url.replace('/performance', ''));
};
setup.renderContent = renderContent;
setup.get_dashboard_and_render = get_dashboard_and_render;
module.exports = setup;
|
Remove comment about client_instance script
|
Remove comment about client_instance script
The script attribute of a client_instance is tested in the view,
for example in body-end.html:
<% if (model.get('script')) { %>
It can be set to false to disable including of our rather large
JavaScript assets.
|
JavaScript
|
mit
|
alphagov/spotlight,tijmenb/spotlight,alphagov/spotlight,keithiopia/spotlight,alphagov/spotlight,tijmenb/spotlight,keithiopia/spotlight,keithiopia/spotlight,tijmenb/spotlight
|
8bd45a62113fa47b03217887e027afe0bfdd04dc
|
lib/util/parse.js
|
lib/util/parse.js
|
// Code based largely on this module:
// https://www.npmjs.org/package/git-credential
function parseOutput(data, callback) {
var output = {};
if (data) {
output = data.toString('utf-8')
.split('\n')
.map(function (line) {
return line.split('=');
})
.filter(function (lineItems) {
// Filter out empty lines
return lineItems.length === 2;
})
.reduce(function (obj, val) {
obj[val[0].trim()] = val[1].trim();
return obj;
}, {});
}
callback(null, output);
}
module.exports = parseOutput;
|
// Code based largely on this module:
// https://www.npmjs.org/package/git-credential
function parseOutput(data, callback) {
var output = {};
if (data) {
output = data.toString('utf-8')
.split('\n')
.map(function (line) {
var index = line.indexOf('=');
if (index !== -1) {
return [line.substr(0, index), line.substr(index + 1)];
} else {
return line;
}
})
.filter(function (lineItems) {
// Filter out empty lines
return lineItems.length === 2;
})
.reduce(function (obj, val) {
obj[val[0].trim()] = val[1].trim();
return obj;
}, {});
}
callback(null, output);
}
module.exports = parseOutput;
|
Return password when it contains =
|
Return password when it contains =
Fixes #3
|
JavaScript
|
mit
|
nwinkler/git-credential-helper
|
8671f86ecc9ece19dd1739edfb9f3a6cc92af12e
|
reducer/stationboards.js
|
reducer/stationboards.js
|
const initState = {};
export default (state = initState, action) => {
switch (action.type) {
case "GET_STATIONBOARD_REQUESTED":
const { stationId } = action.payload;
return {
...state,
[stationId]: {
data: [],
pending: true,
},
};
case "GET_STATIONBOARD_FULFILLED":
const { stationboard } = action.payload;
return {
...state,
[action.payload.stationId]: {
...state[action.payload.stationId],
data: stationboard.map(
({
category,
number,
to,
stop: { departureTimestamp },
}) => ({
category,
number,
to,
departureTimestamp,
}),
),
pending: false,
},
};
default:
return state;
}
};
|
const initState = {};
export default (state = initState, action) => {
switch (action.type) {
case "GET_STATIONBOARD_REQUESTED":
const { stationId } = action.payload;
return {
...state,
[stationId]: {
data: [],
pending: true,
},
};
case "GET_STATIONBOARD_FULFILLED":
const { stationboard } = action.payload;
return {
...state,
[action.payload.stationId]: {
...state[action.payload.stationId],
data: stationboard.map(
({
category,
number,
to,
stop: { departureTimestamp },
passList: checkpoints,
}) => ({
category,
number,
to,
departureTimestamp,
checkpoints,
}),
),
pending: false,
},
};
default:
return state;
}
};
|
Add checkpoints to the stationboard objects
|
Add checkpoints to the stationboard objects
|
JavaScript
|
mit
|
rafaelkallis/hackzurich2017
|
3bf6e52f7955fd688de4c90e6f1d5fda241b45d2
|
builder-bob.js
|
builder-bob.js
|
/**
* 12-22-2016
* ~~ Scott Johnson
*/
/** List jshint ignore directives here. **/
/* jslint node: true */
/* jshint esversion: 6 */
/*eslint-env es6*/
// Stop jshint from complaining about the promise.catch() syntax.
/* jslint -W024 */
var util = require( './lib/bob-util.js' );
var Batch = require( './lib/bob-batch.js' );
var Bob = module.exports = {};
Bob.createBatch = function(){
var self = Batch.apply( this, arguments );
return self;
};// /createBatch()
Bob.watch = function(){
return util.watch.apply( this, arguments );
};// /watch()
Bob.log = function(){
return util.log.apply( this, arguments );
};// /log()
|
/**
* 12-22-2016
* ~~ Scott Johnson
*/
/** List jshint ignore directives here. **/
/* jslint node: true */
/* jshint esversion: 6 */
/*eslint-env es6*/
// Stop jshint from complaining about the promise.catch() syntax.
/* jslint -W024 */
var util = require( './lib/bob-util.js' );
var Batch = require( './lib/bob-batch.js' );
var Bob = module.exports = {};
Bob.createBatch = function(){
var self = Batch.apply( this, arguments );
return self;
};// /createBatch()
Bob.createJob = function(){
var batch = Bob.createBatch();
return batch.createJob.apply( batch, arguments );
};// /createJob()
Bob.watch = function(){
return util.watch.apply( this, arguments );
};// /watch()
Bob.log = function(){
return util.log.apply( this, arguments );
};// /log()
|
Create jobs directly through bob.
|
Create jobs directly through bob.
|
JavaScript
|
mit
|
lucentminds/builder-bob
|
3fba858b12cd7d3d36fdc8618e2e6c1f11a83263
|
challengers.js
|
challengers.js
|
// Welcome!
// Add your github user if you accepted the challenge!
var players = [
'raphamorim',
'israelst',
'afonsopacifer',
'rafaelfragosom',
'brunokinoshita',
'paulinhoerry',
'enieber',
'alanrsoares'
];
module.exports = players;
|
// Welcome!
// Add your github user if you accepted the challenge!
var players = [
'raphamorim',
'israelst',
'afonsopacifer',
'rafaelfragosom',
'brunokinoshita',
'paulinhoerry',
'enieber',
'alanrsoares',
'brunodsgn'
];
module.exports = players;
|
Add brunodsgn as new challenger
|
Add brunodsgn as new challenger
|
JavaScript
|
mit
|
joselitojunior/write-code-every-day,vitorleal/write-code-every-day,raphamorim/write-code-every-day,mabrasil/write-code-every-day,Gcampes/write-code-every-day,arthurvasconcelos/write-code-every-day,cesardeazevedo/write-code-every-day,hocraveiro/write-code-every-day,mauriciojunior/write-code-every-day,rtancman/write-code-every-day,ogilvieira/write-code-every-day,rafaelstz/write-code-every-day,pablobfonseca/write-code-every-day,hocraveiro/write-code-every-day,fredericksilva/write-code-every-day,viniciusdacal/write-code-every-day,willianjusten/write-code-every-day,Pompeu/write-code-every-day,Gcampes/write-code-every-day,pablobfonseca/write-code-every-day,ogilvieira/write-code-every-day,joselitojunior/write-code-every-day,AgtLucas/write-code-every-day,jackmakiyama/write-code-every-day,gpedro/write-code-every-day,jozadaquebatista/write-code-every-day,jackmakiyama/write-code-every-day,letanloc/write-code-every-day,guilouro/write-code-every-day,welksonramos/write-code-every-day,pablobfonseca/write-code-every-day,fdaciuk/write-code-every-day,rafaelfragosom/write-code-every-day,marabesi/write-code-every-day,guidiego/write-code-every-day,gpedro/write-code-every-day,edueo/write-code-every-day,arthurvasconcelos/write-code-every-day,vinimdocarmo/write-code-every-day,beni55/write-code-every-day,Rodrigo54/write-code-every-day,Rodrigo54/write-code-every-day,willianjusten/write-code-every-day,ppamorim/write-code-every-day,marabesi/write-code-every-day,raphamorim/write-code-every-day,ppamorim/write-code-every-day,beni55/write-code-every-day,AgtLucas/write-code-every-day,michelwilhelm/write-code-every-day,diegosaraujo/write-code-every-day,AbraaoAlves/write-code-every-day,arthurvasconcelos/write-code-every-day,fdaciuk/write-code-every-day,andersonweb/write-code-every-day,guidiego/write-code-every-day,rafaelfragosom/write-code-every-day,mabrasil/write-code-every-day,jhonmike/write-code-every-day,rafael-neri/write-code-every-day,jhonmike/write-code-every-day,rafael-neri/write-code-every-day,edueo/write-code-every-day,michelwilhelm/write-code-every-day,welksonramos/write-code-every-day,chocsx/write-code-every-day,AbraaoAlves/write-code-every-day,rafaelstz/write-code-every-day,jozadaquebatista/write-code-every-day,raphamorim/write-code-every-day,vinimdocarmo/write-code-every-day,chocsx/write-code-every-day,rtancman/write-code-every-day,vitorleal/write-code-every-day,mauriciojunior/write-code-every-day,cesardeazevedo/write-code-every-day,viniciusdacal/write-code-every-day,Pompeu/write-code-every-day,letanloc/write-code-every-day,guilouro/write-code-every-day,diegosaraujo/write-code-every-day,andersonweb/write-code-every-day,fredericksilva/write-code-every-day
|
86bd1cf69106768f9a576278f569700b4a48ee1c
|
src/components/BodyAttributes.js
|
src/components/BodyAttributes.js
|
import { Component, Children, PropTypes } from "react";
import withSideEffect from "react-side-effect";
const supportedHTML4Attributes = {
"bgColor": "bgcolor"
};
class BodyAttributes extends Component {
render() {
return Children.only(this.props.children);
}
}
BodyAttributes.propTypes = {
children: PropTypes.node.isRequired
};
function reducePropsToState(propsList) {
const attrs = {};
propsList.forEach(function (props) {
const transformedAttrs = transformHTML4Props(props);
Object.assign(attrs, props, transformedAttrs);
});
return attrs;
}
function handleStateChangeOnClient(attrs) {
for (const key in attrs) {
document.body.setAttribute(key, attrs[key]);
}
}
function transformHTML4Props(props) {
const transformedProps = {};
// Provide support for HTML4 attributes on the body tag for
// e-mail purposes. Convert tags to ones oy-vey can translate
// during the render.
Object.keys(supportedHTML4Attributes).forEach(propName => {
if (props.hasOwnProperty(propName)) {
const name = supportedHTML4Attributes[propName];
const value = props[propName];
const transformedProp = { [`data-oy-${name}`]: value };
Object.assign(transformedProps, transformedProp);
}
});
return transformedProps;
}
export default withSideEffect(
reducePropsToState,
handleStateChangeOnClient
)(BodyAttributes);
|
import { Component, Children, PropTypes } from "react";
import withSideEffect from "react-side-effect";
const supportedHTML4Attributes = {
"bgColor": "bgcolor"
};
class BodyAttributes extends Component {
render() {
return Children.only(this.props.children);
}
}
BodyAttributes.propTypes = {
children: PropTypes.node.isRequired
};
function reducePropsToState(propsList) {
const attrs = {};
propsList.forEach(function (props) {
const transformedAttrs = transformHTML4Props(props);
Object.assign(attrs, props, transformedAttrs);
});
return attrs;
}
function handleStateChangeOnClient(attrs) {
for (const key in attrs) {
document.body.setAttribute(key, attrs[key]);
}
}
function transformHTML4Props(props) {
const transformedProps = {};
/*
* Provide support for HTML4 attributes on the body tag for
* e-mail purposes. Convert tags to ones oy-vey can translate
* during the render.
*
* Note: Only attributes that are white-listed by oy-vey will be rendered
*
*/
Object.keys(supportedHTML4Attributes).forEach(propName => {
if (props.hasOwnProperty(propName)) {
const name = supportedHTML4Attributes[propName];
const value = props[propName];
const transformedProp = { [`data-oy-${name}`]: value };
Object.assign(transformedProps, transformedProp);
}
});
return transformedProps;
}
export default withSideEffect(
reducePropsToState,
handleStateChangeOnClient
)(BodyAttributes);
|
Improve comment around transformed attributes
|
Improve comment around transformed attributes
|
JavaScript
|
mit
|
TrueCar/gluestick-shared,TrueCar/gluestick,TrueCar/gluestick,TrueCar/gluestick
|
0e4cebad2acb269667b14ddc58cb3bb172809234
|
katas/es6/language/block-scoping/let.js
|
katas/es6/language/block-scoping/let.js
|
// block scope - let
// To do: make all tests pass, leave the asserts unchanged!
describe('`let` restricts the scope of the variable to the current block', () => {
describe('`let` vs. `var`', () => {
it('`var` works as usual', () => {
if (true) {
var varX = true;
}
assert.equal(varX, true);
});
it('`let` restricts scope to inside the block', () => {
if(true) {
let letX = true;
}
assert.throws(() => console.log(letX));
});
});
it('`let` use in `for` loops', () => {
let obj = {x: 1};
for (let key in obj) {}
assert.throws(() => console.log(key));
});
it('create artifical scope, using curly braces', () => {
{
let letX = true;
}
assert.throws(() => console.log(letX));
});
});
|
// block scope - let
// To do: make all tests pass, leave the asserts unchanged!
describe('`let` restricts the scope of the variable to the current block', () => {
describe('`let` vs. `var`', () => {
it('`var` works as usual', () => {
if (true) {
let varX = true;
}
assert.equal(varX, true);
});
it('`let` restricts scope to inside the block', () => {
if (true) {
var letX = true;
}
assert.throws(() => console.log(letX));
});
});
describe('`let` usage', () => {
it('`let` use in `for` loops', () => {
let obj = {x: 1};
for (var key in obj) {}
assert.throws(() => console.log(key));
});
it('create artifical scope, using curly braces', () => {
{
var letX = true;
}
assert.throws(() => console.log(letX));
});
});
});
|
Make it nicer and break it, to be a kata :).
|
Make it nicer and break it, to be a kata :).
|
JavaScript
|
mit
|
cmisenas/katas,JonathanPrince/katas,cmisenas/katas,rafaelrocha/katas,JonathanPrince/katas,ehpc/katas,cmisenas/katas,rafaelrocha/katas,JonathanPrince/katas,Semigradsky/katas,tddbin/katas,ehpc/katas,tddbin/katas,Semigradsky/katas,Semigradsky/katas,rafaelrocha/katas,tddbin/katas,ehpc/katas
|
713377318286d72bc7836c0a79d4060f95d163ef
|
server/_config.js
|
server/_config.js
|
let selectENV = (env) => {
if (env === 'development') {
return 'postgres://localhost:5432/todos';
} else if (env === 'test') {
return 'postgres://localhost:5432/todos_test_db';
}
}
module.exports = { selectENV };
|
let selectENV = (env) => {
if (env === 'development') {
return 'postgres://localhost:5432/todos';
} else if (env === 'test') {
return 'postgres://localhost:5432/todos_test';
}
}
module.exports = { selectENV };
|
Fix typo in setDev func
|
Fix typo in setDev func
|
JavaScript
|
mit
|
spencerdezartsmith/to-do-list-app,spencerdezartsmith/to-do-list-app
|
9fd827df81a400df1577c3405a646e26a1b17c51
|
src/exampleApp.js
|
src/exampleApp.js
|
"use strict";
// For conditions of distribution and use, see copyright notice in LICENSE
/*
* @author Tapani Jamsa
* @author Erno Kuusela
* @author Toni Alatalo
* Date: 2013
*/
var app = new Application();
app.host = "localhost"; // IP to the Tundra server
app.port = 2345; // and port to the server
app.start();
// app.viewer.useCubes = true; // Use wireframe cube material for all objects
app.connect(app.host, app.port);
|
"use strict";
// For conditions of distribution and use, see copyright notice in LICENSE
/*
* @author Tapani Jamsa
* @author Erno Kuusela
* @author Toni Alatalo
* Date: 2013
*/
var app = new Application();
var host = "localhost"; // IP to the Tundra server
var port = 2345; // and port to the server
app.start();
// app.viewer.useCubes = true; // Use wireframe cube material for all objects
app.connect(host, port);
|
Make host and port standard variables
|
Make host and port standard variables
|
JavaScript
|
apache-2.0
|
playsign/WebTundra,AlphaStaxLLC/WebTundra,realXtend/WebTundra,AlphaStaxLLC/WebTundra,playsign/WebTundra,AlphaStaxLLC/WebTundra,realXtend/WebTundra
|
7dcb583e7425bff4964b1e3ce52c745c512b1489
|
src/game/index.js
|
src/game/index.js
|
import Phaser from 'phaser-ce';
import { getConfig } from './config';
import TutorialState from './TutorialState';
export default class WreckSam {
constructor() {
const config = getConfig();
this.game = new Phaser.Game(config);
this.game.state.add('tutorial', new TutorialState());
}
start(state) {
this.game.state.start(state);
}
pause(){
this.game.lockRender = true;
}
unpause(){
this.game.lockRender = false;
}
destroy() {
this.game.destroy();
this.game = null;
}
}
|
import Phaser from 'phaser-ce';
import { getConfig } from './config';
import TutorialState from './TutorialState';
export default class WreckSam {
constructor() {
const config = getConfig();
this.game = new Phaser.Game(config);
this.game.state.add('tutorial', new TutorialState());
}
start(state) {
this.game.state.start(state);
}
pause(){
this.game.paused = true;
}
unpause(){
this.game.paused = false;
}
destroy() {
this.game.destroy();
this.game = null;
}
}
|
Use game paused property instead of lockRender
|
Use game paused property instead of lockRender
|
JavaScript
|
mit
|
marc1404/WreckSam,marc1404/WreckSam
|
ec679a27b227877a5e383af2bf9deabf0a3c2072
|
loader.js
|
loader.js
|
// Loader to create the Ember.js application
/*global require */
window.App = require('ghost/app')['default'].create();
|
// Loader to create the Ember.js application
/*global require */
if (!window.disableBoot) {
window.App = require('ghost/app')['default'].create();
}
|
Add initial client unit test.
|
Add initial client unit test.
|
JavaScript
|
mit
|
kevinansfield/Ghost-Admin,acburdine/Ghost-Admin,airycanon/Ghost-Admin,JohnONolan/Ghost-Admin,airycanon/Ghost-Admin,TryGhost/Ghost-Admin,JohnONolan/Ghost-Admin,TryGhost/Ghost-Admin,dbalders/Ghost-Admin,acburdine/Ghost-Admin,kevinansfield/Ghost-Admin,dbalders/Ghost-Admin
|
1df9443cf4567a4deef6f708d5f0ed0f8e3858da
|
lib/less/functions/function-registry.js
|
lib/less/functions/function-registry.js
|
function makeRegistry( base ) {
return {
_data: {},
add: function(name, func) {
// precautionary case conversion, as later querying of
// the registry by function-caller uses lower case as well.
name = name.toLowerCase();
if (this._data.hasOwnProperty(name)) {
//TODO warn
}
this._data[name] = func;
},
addMultiple: function(functions) {
Object.keys(functions).forEach(
function(name) {
this.add(name, functions[name]);
}.bind(this));
},
get: function(name) {
return this._data[name] || ( base && base.get( name ));
},
inherit : function() {
return makeRegistry( this );
}
};
}
module.exports = makeRegistry( null );
|
function makeRegistry( base ) {
return {
_data: {},
add: function(name, func) {
// precautionary case conversion, as later querying of
// the registry by function-caller uses lower case as well.
name = name.toLowerCase();
if (this._data.hasOwnProperty(name)) {
//TODO warn
}
this._data[name] = func;
},
addMultiple: function(functions) {
Object.keys(functions).forEach(
function(name) {
this.add(name, functions[name]);
}.bind(this));
},
get: function(name) {
return this._data[name] || ( base && base.get( name ));
},
getLocalFunctions: function() {
return this._data;
},
inherit: function() {
return makeRegistry( this );
},
create: function(base) {
return makeRegistry(base);
}
};
}
module.exports = makeRegistry( null );
|
Add create() and getLocalFunctions() to function registry so it can be used for plugins
|
Add create() and getLocalFunctions() to function registry so it can be used for plugins
|
JavaScript
|
apache-2.0
|
foresthz/less.js,foresthz/less.js,less/less.js,less/less.js,less/less.js
|
e8a8fed47acf2a7bb9a72720e7c92fbfa6c94952
|
src/lintStream.js
|
src/lintStream.js
|
import postcss from "postcss"
import fs from "fs"
import gs from "glob-stream"
import rcLoader from "rc-loader"
import { Transform } from "stream"
import plugin from "./plugin"
export default function ({ files, config } = {}) {
const stylelintConfig = config || rcLoader("stylelint")
if (!stylelintConfig) {
throw new Error("No stylelint config found")
}
const linter = new Transform({ objectMode: true })
linter._transform = function (chunk, enc, callback) {
if (files) {
const filepath = chunk.path
fs.readFile(filepath, "utf8", (err, css) => {
if (err) { linter.emit("error", err) }
lint({ css, filepath: filepath }, callback)
})
} else {
lint({ css: chunk }, callback)
}
}
function lint({ css, filepath }, callback) {
const processOptions = {}
if (filepath) {
processOptions.from = filepath
}
postcss()
.use(plugin(stylelintConfig))
.process(css, processOptions)
.then(result => {
callback(null, result)
})
.catch(err => {
linter.emit("error", new Error(err))
})
}
if (files) {
const fileStream = gs.create(files)
return fileStream.pipe(linter)
}
return linter
}
|
import postcss from "postcss"
import fs from "fs"
import gs from "glob-stream"
import { Transform } from "stream"
import plugin from "./plugin"
export default function ({ files, config } = {}) {
const linter = new Transform({ objectMode: true })
linter._transform = function (chunk, enc, callback) {
if (files) {
const filepath = chunk.path
fs.readFile(filepath, "utf8", (err, css) => {
if (err) { linter.emit("error", err) }
lint({ css, filepath: filepath }, callback)
})
} else {
lint({ css: chunk }, callback)
}
}
function lint({ css, filepath }, callback) {
const processOptions = {}
if (filepath) {
processOptions.from = filepath
}
postcss()
.use(plugin(config))
.process(css, processOptions)
.then(result => {
callback(null, result)
})
.catch(err => {
linter.emit("error", new Error(err))
})
}
if (files) {
const fileStream = gs.create(files)
return fileStream.pipe(linter)
}
return linter
}
|
Add bin to package.json and move rc-loading to plugin.js
|
Add bin to package.json and move rc-loading to plugin.js
|
JavaScript
|
mit
|
gaidarenko/stylelint,stylelint/stylelint,hudochenkov/stylelint,heatwaveo8/stylelint,stylelint/stylelint,hudochenkov/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,stylelint/stylelint,gaidarenko/stylelint,stylelint/stylelint,hudochenkov/stylelint,gaidarenko/stylelint,evilebottnawi/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,m-allanson/stylelint,gucong3000/stylelint,evilebottnawi/stylelint
|
bf04e2c0a7637b0486562167c6046cb8c2a74a26
|
src/database/DataTypes/TemperatureBreachConfiguration.js
|
src/database/DataTypes/TemperatureBreachConfiguration.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import Realm from 'realm';
export class TemperatureBreachConfiguration extends Realm.Object {}
TemperatureBreachConfiguration.schema = {
name: 'TemperatureBreachConfiguration',
primaryKey: 'id',
properties: {
id: 'string',
minimumTemperature: { type: 'double', optional: true },
maximumTemperature: { type: 'double', optional: true },
duration: { type: 'double', optional: true },
description: { type: 'string', optional: true },
colour: { type: 'string', optional: true },
location: { type: 'Location', optional: true },
type: 'string',
},
};
export default TemperatureBreachConfiguration;
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import Realm from 'realm';
export class TemperatureBreachConfiguration extends Realm.Object {
toJSON() {
return {
id: this.id,
minimumTemperature: this.minimumTemperature,
maximumTemperature: this.maximumTemperature,
duration: this.duration,
description: this.description,
colour: this.colour,
locationID: this.location?.id ?? '',
type: this.type,
};
}
}
TemperatureBreachConfiguration.schema = {
name: 'TemperatureBreachConfiguration',
primaryKey: 'id',
properties: {
id: 'string',
minimumTemperature: { type: 'double', optional: true },
maximumTemperature: { type: 'double', optional: true },
duration: { type: 'double', optional: true },
description: { type: 'string', optional: true },
colour: { type: 'string', optional: true },
location: { type: 'Location', optional: true },
type: 'string',
},
};
export default TemperatureBreachConfiguration;
|
Add breach config adapter method
|
Add breach config adapter method
|
JavaScript
|
mit
|
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
|
f068173deb8aefb9ff0ac55c5fe5e57fd4363288
|
server/src/app.js
|
server/src/app.js
|
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const {sequelize} = require('./models')
const config = require('./config/config')
const app = express()
// Seting up middleware
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())
app.get('/', (req, res) => {
res.send('Hello world')
})
app.get('/status', (req, res) => {
res.send({
message: 'Hello world'
})
})
require('./routes.js')(app)
sequelize.sync({force: true}).then(() => {
app.listen(config.port, () => {
console.log(`Server started at http://127.0.0.1:${config.port}`)
});
})
|
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const {sequelize} = require('./models')
const config = require('./config/config')
const app = express()
// Seting up middleware
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())
app.get('/', (req, res) => {
res.send('Hello world')
})
app.get('/status', (req, res) => {
res.send({
message: 'Hello world'
})
})
require('./routes.js')(app)
sequelize.sync({force: false}).then(() => {
app.listen(config.port, () => {
console.log(`Server started at http://127.0.0.1:${config.port}`)
});
})
|
Disable migration on start server
|
Disable migration on start server
|
JavaScript
|
mit
|
rahman541/tab-tracker,rahman541/tab-tracker
|
b2987678c06e7527491984a11e86a63da1d17cb4
|
src/_fixMobile/EventPath.js
|
src/_fixMobile/EventPath.js
|
(function(global){
// For Android 4.3- (included)
document.body.addEventListener('click', function(e) {
if (!e.path) {
e.path = [];
var t = e.target;
while (t !== document) {
e.path.push(t);
t = t.parentNode;
}
e.path.push(document);
e.path.push(window);
}
}, true)
})(window);
|
(function(global){
// For Android 4.3- (included)
var pathFill = function() {
var e = arguments[0];
if (!e.path) {
e.path = [];
var t = e.target;
while (t !== document) {
e.path.push(t);
t = t.parentNode;
}
e.path.push(document);
e.path.push(window);
}
}
document.body.addEventListener('click', pathFill);
document.body.addEventListener('click', pathFill, true);
})(window);
|
Handle event when bubbles event and catch event.
|
Handle event when bubbles event and catch event.
|
JavaScript
|
mit
|
zhoukekestar/web-modules,zhoukekestar/modules,zhoukekestar/web-modules,zhoukekestar/modules,zhoukekestar/modules,zhoukekestar/web-modules
|
aceeb92a1c71a2bdae0f1ebfce50c2391a20bbe2
|
models.js
|
models.js
|
var orm = require('orm');
var db = orm.connect('sqlite://db.sqlite');
function init(callback) {
db.sync(callback);
}
module.exports = {
init: init
};
|
var orm = require('orm');
var db = orm.connect('sqlite://' + __dirname + '/db.sqlite');
function init(callback) {
db.sync(callback);
}
module.exports = {
init: init
};
|
Use correct directory for sqlite database
|
Use correct directory for sqlite database
|
JavaScript
|
mit
|
dashersw/cote-workshop,dashersw/cote-workshop
|
16162985c41a9cd78e17a76b66de27fe2b7bc31d
|
src/components/NewEngagementForm.js
|
src/components/NewEngagementForm.js
|
import 'react-datepicker/dist/react-datepicker.css'
import '../App.css'
import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form'
import { Form } from 'semantic-ui-react'
import DatePicker from 'react-datepicker'
import moment from 'moment'
import styled from 'styled-components'
const StyledForm = styled.div`width: 100%;`
class NewEngagementForm extends Component {
state = {
startDate: moment()
}
handleChange = date => {
this.setState({
startDate: date
})
}
handleSubmit = () => {
this.props.handleSubmit(this.state.startDate)
}
render() {
return (
<Form onSubmit={this.handleSubmit}>
<Form.Field width={5}>
<StyledForm>
<DatePicker
onChange={this.handleChange}
selected={this.state.startDate}
showTimeSelect
dateFormat="LLL"
/>
</StyledForm>
</Form.Field>
<Form.Field>
<Field name="email" component="input" type="text" />
</Form.Field>
<input type="submit" />
</Form>
)
}
}
export default reduxForm({
form: 'newEngagement'
})(NewEngagementForm)
|
import 'react-datepicker/dist/react-datepicker.css'
import '../App.css'
import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form'
import { Form } from 'semantic-ui-react'
import DatePicker from 'react-datepicker'
import moment from 'moment'
import styled from 'styled-components'
const StyledForm = styled.div`width: 100%;`
class NewEngagementForm extends Component {
state = {
startDate: moment()
}
handleChange = date => {
this.setState({
startDate: date
})
}
handleSubmit = () => {
this.props.handleSubmit(this.state.startDate)
}
render() {
return (
<Form onSubmit={this.handleSubmit}>
<Form.Field>
<StyledForm>
<DatePicker
onChange={this.handleChange}
selected={this.state.startDate}
showTimeSelect
dateFormat="LLL"
/>
</StyledForm>
</Form.Field>
<input type="submit" />
</Form>
)
}
}
export default reduxForm({
form: 'newEngagement'
})(NewEngagementForm)
|
Remove unneeded input form from new engagement form
|
Remove unneeded input form from new engagement form
|
JavaScript
|
mit
|
cernanb/personal-chef-react-app,cernanb/personal-chef-react-app
|
e518509d82651340e881a638e5279ed6a1be7af1
|
test/resources/unsubscribe_test.js
|
test/resources/unsubscribe_test.js
|
var expect = require('chai').expect;
var Unsubscribe = require('../../lib/resources/unsubscribe');
var helper = require('../test_helper');
describe('Unsubscribe', function() {
var server;
beforeEach(function() {
server = helper.server(helper.port, helper.requests);
});
afterEach(function() {
server.close();
});
describe('#create', function() {
it('creates an unsubscribe', function() {
var unsubscribe = new Unsubscribe(helper.client);
var params = { person_email: '[email protected]' };
return unsubscribe.create(params).then(function(response) {
expect(response.person_email).to.eq('[email protected]');
});;
});
});
});
|
var expect = require('chai').expect;
var Unsubscribe = require('../../lib/resources/Unsubscribe');
var helper = require('../test_helper');
describe('Unsubscribe', function() {
var server;
beforeEach(function() {
server = helper.server(helper.port, helper.requests);
});
afterEach(function() {
server.close();
});
describe('#create', function() {
it('creates an unsubscribe', function() {
var unsubscribe = new Unsubscribe(helper.client);
var params = { person_email: '[email protected]' };
return unsubscribe.create(params).then(function(response) {
expect(response.person_email).to.eq('[email protected]');
});;
});
});
});
|
Fix case sensitive require for unsubscribes
|
Fix case sensitive require for unsubscribes
|
JavaScript
|
mit
|
delighted/delighted-node,callemall/delighted-node
|
92978a1a24c2b2df4dba8f622c40f34c4fa7ca12
|
modules/signin.js
|
modules/signin.js
|
'use strict';
const builder = require('botbuilder');
const timesheet = require('./timesheet');
module.exports = exports = [(session) => {
builder.Prompts.text(session, 'Please tell me your domain user?');
}, (session, results, next) => {
session.send('Ok. Searching for your stuff...');
session.sendTyping();
timesheet
.searchColleagues(results.response)
.then((colleagues) => {
session.userData = colleagues[0];
session.userData.impersonated = true;
}).catch((ex) => {
console.log(ex);
}).finally(() => {
next();
});
}, (session) => {
if (!session.impersonated) {
console.log('Oops! Couldn\'t impersonate');
return session.endDialog('Oops! Couldn\'t impersonate');
}
session.endDialog('(y)');
}];
|
'use strict';
const builder = require('botbuilder');
const timesheet = require('./timesheet');
module.exports = exports = [(session) => {
builder.Prompts.text(session, 'Please tell me your domain user?');
}, (session, results, next) => {
session.send('Ok. Searching for your stuff...');
session.sendTyping();
timesheet
.searchColleagues(results.response)
.then((colleagues) => {
console.log('Found %s', colleagues.length);
session.userData = colleagues[0];
session.userData.impersonated = true;
}).catch((ex) => {
console.log(ex);
}).finally(() => {
next();
});
}, (session) => {
if (!session.userData.impersonated) {
return session.endDialog('Oops! Couldn\'t impersonate');
}
session.endDialog('(y)');
}];
|
Fix impersonated user check issue.
|
Fix impersonated user check issue.
|
JavaScript
|
mit
|
99xt/jira-journal,99xt/jira-journal
|
6dc8a96b20179bd04a2e24fa4c3b0106d35ebaba
|
src/main.js
|
src/main.js
|
(function(){
"use strict";
xtag.register("sam-tabbar", {
lifecycle: {
created: function() {
if (!this.role) {
this.role = "tablist";
}
},
inserted: function() {
this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id;
},
removed: function() {},
attributeChanged: function() {}
},
events: {
"press": function (event) {
var el = event.originalTarget;
//Checks if a tab was pressed
if (!el || el.getAttribute("role") !== "tab") return;
this.setTab(el.id, true);
}
},
accessors: {
role: {
attribute: {}
}
},
methods: {
setTab: function (tabid, fireEvent) {
var eventName = "tabChange",
result = true;
//Checks if person is trying to set to currently active tab
if (this.activeTabId === tabid) {
eventName = "activeTabPress"
result = false;
} else {
document.getElementById(this.activeTabId).dataset.active = false;
this.activeTabId = tabid;
document.getElementById(this.activeTabId).dataset.active = true;
}
if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId});
return result;
}
}
});
})();
|
(function(){
"use strict";
xtag.register("sam-tabbar", {
lifecycle: {
created: function() {
if (!this.role) {
this.role = "tablist";
}
},
inserted: function() {
this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id;
},
removed: function() {},
attributeChanged: function() {}
},
events: {
"press": function (event) {
var el = event.originalTarget;
//Checks if a tab was pressed
if (!el || el.getAttribute("role") !== "tab") return;
this.setTab(el.id, true);
}
},
accessors: {
role: {
attribute: {}
}
},
methods: {
setTab: function (tabid, fireEvent) {
var eventName = "tabChange";
if (!this.querySelector("[id='"+tabid+"'][role='tab']")) {
console.error("Cannot set to unknown tabid");
return false;
}
//Checks if person is trying to set to currently active tab
if (this.activeTabId === tabid) {
eventName = "activeTabPress"
} else {
document.getElementById(this.activeTabId).dataset.active = false;
this.activeTabId = tabid;
document.getElementById(this.activeTabId).dataset.active = true;
}
if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId});
return true;
}
}
});
})();
|
Add handler for when setTab is given a non-exsitant tab id
|
Add handler for when setTab is given a non-exsitant tab id
|
JavaScript
|
apache-2.0
|
Swissnetizen/sam-tabbar
|
0715d2b60dd1ebd851d4e5ea9ec9073424211012
|
src/function/lazyLoading.js
|
src/function/lazyLoading.js
|
define([
'jquery'
],
function($) {
return function() {
var self = this;
if (!self.sprite && self.lasyEmoji[0]) {
var pickerTop = self.picker.offset().top,
pickerBottom = pickerTop + self.picker.height() + 20;
self.lasyEmoji.each(function() {
var e = $(this), top = e.offset().top;
if (top > pickerTop && top < pickerBottom) {
e.attr("src", e.data("src")).removeClass("lazy-emoji");
}
})
self.lasyEmoji = self.lasyEmoji.filter(".lazy-emoji");
}
}
});
|
define([
'jquery'
],
function($) {
return function() {
var self = this;
if (!self.sprite && self.lasyEmoji[0] && self.lasyEmoji.eq(0).is(".lazy-emoji")) {
var pickerTop = self.picker.offset().top,
pickerBottom = pickerTop + self.picker.height() + 20;
self.lasyEmoji.each(function() {
var e = $(this), top = e.offset().top;
if (top > pickerTop && top < pickerBottom) {
e.attr("src", e.data("src")).removeClass("lazy-emoji");
}
})
self.lasyEmoji = self.lasyEmoji.filter(".lazy-emoji");
}
}
});
|
Fix 'disconnected from the document' error
|
Fix 'disconnected from the document' error
ref https://github.com/mervick/emojionearea/pull/240
|
JavaScript
|
mit
|
mervick/emojionearea
|
7a328c49ea155df7ff2ae55825aa299c541bf31e
|
test/index.js
|
test/index.js
|
var nocache = require('..')
var assert = require('assert')
var connect = require('connect')
var request = require('supertest')
describe('nocache', function () {
it('sets headers properly', function (done) {
var app = connect()
app.use(function (req, res, next) {
res.setHeader('ETag', 'abc123')
next()
})
app.use(nocache())
app.use(function (req, res) {
res.end('Hello world!')
})
request(app).get('/')
.expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
.expect('Pragma', 'no-cache')
.expect('Expires', '0')
.expect('ETag', 'abc123')
.end(done)
})
it('names its function and middleware', function () {
assert.equal(nocache.name, 'nocache')
assert.equal(nocache().name, 'nocache')
})
})
|
var nocache = require('..')
var assert = require('assert')
var connect = require('connect')
var request = require('supertest')
describe('nocache', function () {
it('sets headers properly', function (done) {
var app = connect()
app.use(function (req, res, next) {
res.setHeader('ETag', 'abc123')
next()
})
app.use(nocache())
app.use(function (req, res) {
res.end('Hello world!')
})
request(app).get('/')
.expect('Surrogate-Control', 'no-store')
.expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
.expect('Pragma', 'no-cache')
.expect('Expires', '0')
.expect('ETag', 'abc123')
.end(done)
})
it('names its function and middleware', function () {
assert.equal(nocache.name, 'nocache')
assert.equal(nocache().name, 'nocache')
})
})
|
Add missing test for `Surrogate-Control` header
|
Add missing test for `Surrogate-Control` header
Fixes #13.
|
JavaScript
|
mit
|
helmetjs/nocache
|
5ac0fccde96dd50007767263c19b1432bb4e41d8
|
test/index.js
|
test/index.js
|
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint-env node, mocha */
import test from 'ava';
import endpoint from '../src/endpoint';
test('happy ponies', () => {
const fetch = () => null;
api(null, null, {
baseUri: 'http://api.example.com/v1',
endpoints: [
{
endpoint: '/happy/ponies/{id}',
method: 'GET',
requiredParams: ['id'],
optionalParams: ['lastSeenId'],
}
]
});
});
test.skip('returns a request object with the correct url', (t) => {
const testUrl = 'http://api.example.com/v1/';
const Request = (url) => {
t.true(url === testUrl);
};
endpoint(Request);
});
test.skip('should append a trailing slash if one is missing in the given url', (t) => {
const testUrl = 'http://api.example.com/v1';
const Request = (url) => {
t.true(url === `${testUrl}/`);
};
endpoint(Request);
});
|
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint-env node, mocha */
import test from 'ava';
import endpoint from '../src/endpoint';
test('endpoint returns correctly partially applied function', (t) => {
const endpointConfig = {
uri: 'http://example.com',
};
const init = () => {};
const Request = (uriOpt, initOpt) => {
t.true(uriOpt === endpointConfig.uri);
t.true(initOpt.toString() === init.toString());
};
endpoint(Request, init)(endpointConfig);
});
test.skip('returns a request object with the correct url', (t) => {
const testUrl = 'http://api.example.com/v1/';
const Request = (url) => {
t.true(url === testUrl);
};
endpoint(Request);
});
test.skip('should append a trailing slash if one is missing in the given url', (t) => {
const testUrl = 'http://api.example.com/v1';
const Request = (url) => {
t.true(url === `${testUrl}/`);
};
endpoint(Request);
});
|
Add spec for endpoints function
|
Add spec for endpoints function
|
JavaScript
|
mit
|
hughrawlinson/api-client-helper
|
684d9d693b19bc4d09c26627bb16ddcfa6230c63
|
src/main.js
|
src/main.js
|
import './main.sass'
import 'babel-core/polyfill'
import React from 'react'
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import { Router } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import * as reducers from './reducers'
import { analytics, uploader, requester } from './middleware'
import App from './containers/App'
const logger = createLogger({ collapsed: true })
const createStoreWithMiddleware = applyMiddleware(thunk, uploader, requester, analytics, logger)(createStore)
const reducer = combineReducers(reducers)
const store = createStoreWithMiddleware(reducer)
function createRedirect(from, to) {
return {
path: from,
onEnter(nextState, transition) {
transition.to(to)
},
}
}
const rootRoute = {
path: '/',
component: App,
childRoutes: [
createRedirect('onboarding', '/onboarding/communities'),
require('./routes/Onboarding'),
],
}
const element = (
<Provider store={store}>
{() =>
<Router history={createBrowserHistory()} routes={rootRoute} />
}
</Provider>
)
React.render(element, document.getElementById('root'))
|
import './main.sass'
import 'babel-core/polyfill'
import React from 'react'
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import { Router } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import * as reducers from './reducers'
import { analytics, uploader, requester } from './middleware'
import App from './containers/App'
const logger = createLogger({ collapsed: true })
const createStoreWithMiddleware = applyMiddleware(thunk, uploader, requester, analytics, logger)(createStore)
const reducer = combineReducers(reducers)
const store = createStoreWithMiddleware(reducer)
function createRedirect(from, to) {
return {
path: from,
onEnter(nextState, replaceState) {
replaceState(nextState, to)
},
}
}
const rootRoute = {
path: '/',
component: App,
childRoutes: [
createRedirect('onboarding', '/onboarding/communities'),
require('./routes/Onboarding'),
],
}
const element = (
<Provider store={store}>
{() =>
<Router history={createBrowserHistory()} routes={rootRoute} />
}
</Provider>
)
React.render(element, document.getElementById('root'))
|
Fix an issue with redirects
|
Fix an issue with redirects
|
JavaScript
|
mit
|
ello/webapp,ello/webapp,ello/webapp
|
18c94b0fcf2fdab6dea4ee0f3c0de11ba6e368f6
|
test/index.js
|
test/index.js
|
var ienoopen = require('..')
var assert = require('assert')
var connect = require('connect')
var request = require('supertest')
describe('ienoopen', function () {
beforeEach(function () {
this.app = connect()
this.app.use(ienoopen())
this.app.use(function (req, res) {
res.setHeader('Content-Disposition', 'attachment; filename=somefile.txt')
res.end('Download this cool file!')
})
})
it('sets header properly', function (done) {
request(this.app).get('/')
.expect('X-Download-Options', 'noopen', done)
})
it('names its function and middleware', function () {
assert.equal(ienoopen.name, 'ienoopen')
assert.equal(ienoopen().name, 'ienoopen')
})
})
|
var ienoopen = require('..')
var assert = require('assert')
var connect = require('connect')
var request = require('supertest')
describe('ienoopen', function () {
beforeEach(function () {
this.app = connect()
this.app.use(ienoopen())
this.app.use(function (req, res) {
res.setHeader('Content-Disposition', 'attachment; filename=somefile.txt')
res.end('Download this cool file!')
})
})
it('sets header properly', function () {
return request(this.app).get('/')
.expect('X-Download-Options', 'noopen')
})
it('names its function and middleware', function () {
assert.equal(ienoopen.name, 'ienoopen')
assert.equal(ienoopen().name, 'ienoopen')
})
})
|
Use promises instead of callbacks in test
|
Use promises instead of callbacks in test
|
JavaScript
|
mit
|
helmetjs/ienoopen
|
5bd8d02a8073fc55560fbc534f840627e81683de
|
src/main.js
|
src/main.js
|
'use strict';
const electron = require('electron');
const { app, BrowserWindow } = electron;
let mainWindow; // Ensures garbage collection does not remove the window
app.on('ready', () => {
// Creates the application window and sets its dimensions to fill the screen
const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({
width,
height
});
// Loads index.html in as the main application page
mainWindow.loadURL(`file://${__dirname}/index.html`);
mainWindow.on('closed', () => {
mainWindow = null; // allow window to be garbage collected
});
});
|
'use strict';
const electron = require('electron');
const { app, BrowserWindow } = electron;
const path = require('path');
const url = require('url');
let mainWindow; // Ensures garbage collection does not remove the window
app.on('ready', () => {
// Creates the application window and sets its dimensions to fill the screen
const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({
width,
height
});
// Loads index.html in as the main application page
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
mainWindow.on('closed', () => {
mainWindow = null; // allow window to be garbage collected
});
});
|
Change method of loading index.html
|
Change method of loading index.html
|
JavaScript
|
mit
|
joyceky/interactive-periodic-table,joyceky/interactive-periodic-table,joyceky/interactive-periodic-table
|
d650050d72d0272a350d26c1f03b2e4534e99b33
|
test/index.js
|
test/index.js
|
'use strict';
var expect = require('chai').expect;
var rm = require('../');
describe('1rm', function () {
// 400# x 4
var expectations = {
brzycki: 436,
epley: 453,
lander: 441,
lombardi: 459,
mayhew: 466,
oconner: 440,
wathan: 451
};
Object.keys(expectations).forEach(function (method) {
it('can estimate with the #' + method + ' method', function () {
expect(rm[method](400, 4)).to.be.closeTo(expectations[method], 1);
});
});
});
|
'use strict';
var expect = require('chai').expect;
var rm = require('../');
describe('1rm', function () {
// 400# x 4
var expectations = {
epley: 453,
brzycki: 436,
lander: 441,
lombardi: 459,
mayhew: 466,
oconner: 440,
wathan: 451
};
Object.keys(expectations).forEach(function (method) {
it('can estimate with the #' + method + ' method', function () {
expect(rm[method](400, 4)).to.be.closeTo(expectations[method], 1);
});
});
});
|
Order tests to match source
|
Order tests to match source
|
JavaScript
|
mit
|
bendrucker/1rm.js
|
10bfd8221e3264d12e6f12470a0d24debc855bd8
|
test/index.js
|
test/index.js
|
var expect = require('chai').expect,
hh = require('../index');
describe('#method', function () {
it('hh.method is a function', function () {
expect(hh.method).a('function');
});
});
|
var assert = require('chai').assert,
hh = require('../index');
describe('#hh.method()', function () {
it('should be a function', function () {
assert.typeOf(hh.method, 'function', 'hh.method is a function');
});
});
|
Change tests to assert style
|
Change tests to assert style
|
JavaScript
|
mit
|
rsp/node-hapi-helpers
|
3c83c85662300646972a2561db80e26e80432f48
|
server.js
|
server.js
|
const express = require('express')
const app = express()
const path = require('path')
var cors = require('cors')
var bodyParser = require('body-parser')
// var pg = require('pg')
// var format = require('pg-format')
// var client = new pg.Client()
// var getTimeStamp = require('./get-timestamp.js')
// var timestamp = getTimeStamp
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.text())
app.use(cors())
app.use(express.static('client/build'))
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '/client/build/index.html'))
})
app.post('/', function (req, res) {
var thought = req.body.text
// var thought = 'cool stuff'
console.log('We received this from the client: ' + thought)
/* client.connect(function (err) {
if (err) throw err
var textToDB = format('INSERT INTO thoughtentries (date, thought) VALUES(%L, %L);', timestamp, thought)
client.query(textToDB, function (err, result) {
if (err) throw err
console.log(result.rows[0])
client.end(function (err) {
if (err) throw err
})
}) */
})
app.listen(3000, function () {
console.log('listening on 3000')
})
|
const express = require('express')
const app = express()
const path = require('path')
var cors = require('cors')
var bodyParser = require('body-parser')
// var pg = require('pg')
// var format = require('pg-format')
// var client = new pg.Client()
// var getTimeStamp = require('./get-timestamp.js')
// var timestamp = getTimeStamp
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.text())
app.use(cors())
app.use(express.static('client/build'))
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '/client/build/index.html'))
})
app.post('/', function (req, res) {
var thought = req.body
res.end('done')
console.log('We received this from the client: ' + thought)
/* client.connect(function (err) {
if (err) throw err
var textToDB = format('INSERT INTO thoughtentries VALUES(%L, %L)', timestamp, thought)
client.query(textToDB, function (err, result) {
if (err) throw err
console.log(result.rows[0])
client.end(function (err) {
if (err) throw err
})
})
}) */
return
})
app.listen(3000, function () {
console.log('listening on 3000')
})
|
Add res.end() to end the POST request
|
Add res.end() to end the POST request
@chinedufn Line 24 is where I get the contents of `req.body` in order to get the text from the textbox
the problem is I believe it should be `req.body.text` like the example
on the 'body-parser' page shows.
|
JavaScript
|
mit
|
acucciniello/notebook-sessions,acucciniello/notebook-sessions
|
4cf7eb019de9b51505dbf1ba8e2b5f9bc77e0b20
|
recruit/client/applications.js
|
recruit/client/applications.js
|
Meteor.subscribe('regions');
Meteor.subscribe('applications');
Template.applications.helpers({
applications: function() {
return Applications.find({}, {limit: 10});
},
formatDate: function(date) {
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
},
regionName: function(id) {
return Regions.findOne({id: id}).name;
},
});
Template.applications.rendered = function() {
$('#applications').dataTable({
searching: false,
scrollX: true,
pagingType: 'full_numbers',
language: {
decimal: ',',
thousands: '.',
},
});
};
|
Meteor.subscribe('regions');
Meteor.subscribe('applications');
Template.applications.helpers({
applications: function() {
return Applications.find({}, {limit: 10});
},
formatDate: function(date) {
if (typeof date === 'undefined') {
return null;
}
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
},
regionName: function(id) {
if (typeof id === 'undefined') {
return null;
}
return Regions.findOne({id: id}).name;
},
});
Template.applications.rendered = function() {
$('#applications').dataTable({
searching: false,
scrollX: true,
pagingType: 'full_numbers',
language: {
decimal: ',',
thousands: '.',
},
});
};
|
Fix exceptions when application region or date is undefined
|
Fix exceptions when application region or date is undefined
|
JavaScript
|
apache-2.0
|
IngloriousCoderz/GetReel,IngloriousCoderz/GetReel
|
b7ea9dc3f4e5bc7b028cf6aa4a5c7529b7d34160
|
troposphere/static/js/components/providers/Name.react.js
|
troposphere/static/js/components/providers/Name.react.js
|
import React from 'react/addons';
import Backbone from 'backbone';
import Router from 'react-router';
export default React.createClass({
displayName: "Name",
propTypes: {
provider: React.PropTypes.instanceOf(Backbone.Model).isRequired
},
render: function () {
let provider = this.props.provider;
return (
<div className="row">
<h1>{provider.get('name')}</h1>
<Router.Link className=" btn btn-default" to = "all-providers" >
<span className="glyphico glyphicon-arrow-left"> </span>
{" Back to All Providers" }
</Router.Link>
</div>
);
}
});
|
import React from 'react/addons';
import Backbone from 'backbone';
import Router from 'react-router';
export default React.createClass({
displayName: "Name",
propTypes: {
provider: React.PropTypes.instanceOf(Backbone.Model).isRequired
},
render: function () {
let provider = this.props.provider;
return (
<div className="row">
<h1>{provider.get('name')}</h1>
<Router.Link className="btn btn-default" to="all-providers" >
<span className="glyphicon glyphicon-arrow-left"> </span>
{" Back to All Providers" }
</Router.Link>
</div>
);
}
});
|
Correct CSS class name typo
|
Correct CSS class name typo
|
JavaScript
|
apache-2.0
|
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
|
df11a29999a30f430162e2a6742903879f4608c4
|
web/webpack.common.js
|
web/webpack.common.js
|
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: {
app: './src/app/app.js'
},
module: {
rules: [
{ test: /\.html$/,
use: 'raw-loader' }
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'head'
}),
new CopyWebpackPlugin([
{ from: './src/assets/',
to: 'assets/' },
{ from: './src/styles/',
to: 'styles/' },
{ from: './src/app/lib/stockfish.js',
to: 'lib/stockfish.js' }
])
],
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist')
},
};
|
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: {
app: './src/app/app.js'
},
module: {
rules: [
{ test: /\.html$/,
use: 'raw-loader' }
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'head'
}),
new CopyWebpackPlugin({patterns: [
{ from: './src/assets/', to: 'assets/' },
{ from: './src/styles/', to: 'styles/' },
{ from: './src/app/lib/stockfish.js', to: 'lib/stockfish.js' }
]})
],
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist')
},
};
|
Update webpack copy plugin configuration
|
Update webpack copy plugin configuration
|
JavaScript
|
mit
|
ddugovic/RelayChess,ddugovic/RelayChess,ddugovic/RelayChess
|
b9eccecc4a5574ec05e29c55b16e19814b7d2c19
|
Kinect2Scratch.js
|
Kinect2Scratch.js
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
ext.my_first_block = function(callback) {
wait = 1;
window.setTimeout(function() {
callback();
}, wait*1000);
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
]
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
ext.my_first_block = function() {
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
]
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
Stop terrible idea; make reporter block do something
|
Stop terrible idea; make reporter block do something
|
JavaScript
|
bsd-3-clause
|
visor841/SkelScratch,Calvin-CS/SkelScratch
|
46f2f3e86783a0b1eeed9be1ac35cd50a3ce1939
|
src/pkjs/index.js
|
src/pkjs/index.js
|
/* global Pebble navigator */
function pebbleSuccess(e) {
// do nothing
}
function pebbleFailure(e) {
console.error(e);
}
var reportPhoneBatt;
Pebble.addEventListener('ready', function(e) {
if (navigator.getBattery) {
navigator.getBattery().then(function (battery) {
reportPhoneBatt = function () {
Pebble.sendAppMessage({
'PHONE_BATT_LEVEL': Math.floor(battery.level * 100),
'PHONE_BATT_CHARGING': battery.charging ? 1 : 0
}, pebbleSuccess, pebbleFailure);
};
battery.addEventListener('levelchange', function() {
console.log('Level change: '+ (battery.level * 100) +'%');
reportPhoneBatt();
});
battery.addEventListener('chargingchange', reportPhoneBatt);
reportPhoneBatt();
});
} else {
console.error('No navigator.getBattery');
console.error('User agent: '+navigator.userAgent);
}
});
Pebble.addEventListener('appmessage', function(e) {
if (e.payload.QUERY_PHONE_BATT && reportPhoneBatt) {
return reportPhoneBatt();
}
});
|
/* global Pebble navigator */
function pebbleSuccess(e) {
// do nothing
}
function pebbleFailure(e) {
console.error(e);
}
var reportPhoneBatt;
Pebble.addEventListener('ready', function(e) {
if (navigator.getBattery) {
navigator.getBattery().then(function (battery) {
reportPhoneBatt = function () {
Pebble.sendAppMessage({
'PHONE_BATT_LEVEL': Math.floor(battery.level * 100),
'PHONE_BATT_CHARGING': battery.charging ? 1 : 0
}, pebbleSuccess, pebbleFailure);
};
battery.addEventListener('levelchange', function() {
console.log('Level change: '+ (battery.level * 100) +'%');
reportPhoneBatt();
});
battery.addEventListener('chargingchange', reportPhoneBatt);
reportPhoneBatt();
});
} else if (navigator.userAgent) {
console.error('No navigator.getBattery');
console.error('User agent: '+navigator.userAgent);
} else {
console.log('No navigator.userAgent, probably running in emulator');
}
});
Pebble.addEventListener('appmessage', function(e) {
if (e.payload.QUERY_PHONE_BATT && reportPhoneBatt) {
return reportPhoneBatt();
}
});
|
Add log message about starting in the emulator
|
Add log message about starting in the emulator
|
JavaScript
|
mit
|
stuartpb/rainpower-watchface,stuartpb/rainpower-watchface,stuartpb/rainpower-watchface
|
ce1c9f69ab4aec5e1d2a1c15faaeb0a00a954f04
|
src/Native/Now.js
|
src/Native/Now.js
|
Elm.Native.Now = {};
Elm.Native.Now.make = function(localRuntime) {
localRuntime.Native = localRuntime.Native || {};
localRuntime.Native.Now = localRuntime.Native.Now || {};
if (localRuntime.Native.Now.values) {
return localRuntime.Native.Now.values;
}
var Result = Elm.Result.make(localRuntime);
return localRuntime.Native.Now.values = {
loadTime: (new window.Date).getTime()
};
};
|
Elm.Native.Now = {};
Elm.Native.Now.make = function(localRuntime) {
localRuntime.Native = localRuntime.Native || {};
localRuntime.Native.Now = localRuntime.Native.Now || {};
if (localRuntime.Native.Now.values) {
return localRuntime.Native.Now.values;
}
var Result = Elm.Result.make(localRuntime);
return localRuntime.Native.Now.values = {
loadTime: (new Date()).getTime()
};
};
|
Use native Date() instead of window date
|
Use native Date() instead of window date
|
JavaScript
|
mit
|
chendrix/elm-rogue,chendrix/elm-rogue,chendrix/elm-rogue
|
a9d67c9f29270b56be21cb71073020f8957374d4
|
test/client/scripts/arcademode/store/configureStore.spec.js
|
test/client/scripts/arcademode/store/configureStore.spec.js
|
'use strict';
/* Unit tests for file client/scripts/arcademode/store/configureStore.js. */
import { expect } from 'chai';
import configureStore from '../../../../../client/scripts/arcademode/store/configureStore';
describe('configureStore()', () => {
it('should do return an object', () => {
const store = configureStore();
expect(typeof store).to.equal('object');
const state = store.getState();
expect(state).not.to.empty;
});
it('should do accept dispatched actions', () => {
const store = configureStore();
store.dispatch({ type: 'DUMMY' });
});
});
|
'use strict';
/* Unit tests for file client/scripts/arcademode/store/configureStore.js. */
import { expect } from 'chai';
import configureStore from '../../../../../client/scripts/arcademode/store/configureStore';
describe('Store: configureStore()', () => {
it('should return an object representing the store', () => {
const store = configureStore();
expect(typeof store).to.equal('object');
const state = store.getState();
expect(state).not.to.be.empty;
});
it('should accept dispatched actions and update its state', () => {
const store = configureStore();
store.dispatch({ type: 'MODAL_CLOSE' });
expect(store.getState().getIn(['modal', 'modal'])).to.be.false;
});
});
|
Test store, dispatch, and state
|
Test store, dispatch, and state
|
JavaScript
|
bsd-3-clause
|
freeCodeCamp/arcade-mode,kevinnorris/arcade-mode,kevinnorris/arcade-mode,kevinnorris/arcade-mode,freeCodeCamp/arcade-mode,freeCodeCamp/arcade-mode,kevinnorris/arcade-mode,freeCodeCamp/arcade-mode
|
be4104b7fa5e985da4970d733231ba2f9f4d1c24
|
lib/async-to-promise.js
|
lib/async-to-promise.js
|
// Return promise for given async function
'use strict';
var f = require('es5-ext/lib/Function/functionalize')
, concat = require('es5-ext/lib/List/concat').call
, slice = require('es5-ext/lib/List/slice/call')
, deferred = require('./deferred')
, apply;
apply = function (fn, scope, args, resolve) {
fn.apply(scope, concat(args, function (error, result) {
if (error == null) {
resolve((arguments.length > 2) ? slice(arguments, 1) : result);
} else {
resolve(error);
}
}));
}
exports = module.exports = f(function () {
var d = deferred();
apply(this, null, arguments, d.resolve);
return d.promise;
});
exports._apply = apply;
|
// Return promise for given async function
'use strict';
var f = require('es5-ext/lib/Function/functionalize')
, slice = require('es5-ext/lib/List/slice/call')
, toArray = require('es5-ext/lib/List/to-array').call
, deferred = require('./deferred')
, apply;
apply = function (fn, scope, args, resolve) {
fn.apply(scope, toArray(args).concat(function (error, result) {
if (error == null) {
resolve((arguments.length > 2) ? slice(arguments, 1) : result);
} else {
resolve(error);
}
}));
}
exports = module.exports = f(function () {
var d = deferred();
apply(this, null, arguments, d.resolve);
return d.promise;
});
exports._apply = apply;
|
Update up to changes in es5-ext
|
Update up to changes in es5-ext
|
JavaScript
|
isc
|
medikoo/deferred
|
97b8f1d793341c20acf7eabb9395ee575b7bcb59
|
app/routes/interestgroups/components/InterestGroupList.js
|
app/routes/interestgroups/components/InterestGroupList.js
|
import styles from './InterestGroup.css';
import React from 'react';
import InterestGroup from './InterestGroup';
import Button from 'app/components/Button';
import { Link } from 'react-router';
export type Props = {
interestGroups: Array
};
const InterestGroupList = (props: Props) => {
const groups = props.interestGroups.map((group, key) => (
<InterestGroup group={group} key={key} />
));
return (
<div className={styles.root}>
<div className={styles.section}>
<div>
<h1>Interessegrupper</h1>
<p>
<strong>Her</strong> finner du all praktisk informasjon knyttet til
våre interessegrupper.
</p>
</div>
<Link to={'/interestgroups/create'} className={styles.link}>
<Button>Lag ny interessegruppe</Button>
</Link>
</div>
<div className="groups">{groups}</div>
</div>
);
};
export default InterestGroupList;
|
import styles from './InterestGroup.css';
import React from 'react';
import InterestGroup from './InterestGroup';
import Button from 'app/components/Button';
import { Link } from 'react-router';
import NavigationTab, { NavigationLink } from 'app/components/NavigationTab';
export type Props = {
interestGroups: Array
};
const InterestGroupList = (props: Props) => {
const groups = props.interestGroups.map((group, key) => (
<InterestGroup group={group} key={key} />
));
const showCreate = props.loggedIn;
return (
<div className={styles.root}>
<div className={styles.section}>
<div>
<NavigationTab title="Interessegrupper">
<NavigationLink to={`/`}>Hjem</NavigationLink>
</NavigationTab>
<p>
<strong>Her</strong> finner du all praktisk informasjon knyttet til
våre interessegrupper.
</p>
{showCreate && (
<Link to={'/interestgroups/create'} className={styles.link}>
<Button>Lag ny interessegruppe</Button>
</Link>
)}
</div>
</div>
<div className="groups">{groups}</div>
</div>
);
};
export default InterestGroupList;
|
Use NavigationTab in InterestGroup list
|
Use NavigationTab in InterestGroup list
|
JavaScript
|
mit
|
webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp
|
64ae5257caf51aa470249561184b7b8c7a4d614c
|
stylefmt.js
|
stylefmt.js
|
'use strict';
var stylefmt = require('stylefmt');
var data = '';
// Get options if needed
if (process.argv.length > 2) {
var opts = JSON.parse(process.argv[2]);
process.chdir(opts.file_path);
}
process.stdin.on('data', function(css) {
data += css;
});
process.stdin.on('end', function() {
try {
process.stdout.write(stylefmt.process(data));
} catch (err) {
throw err;
}
});
|
'use strict';
var stylefmt = require('stylefmt');
var data = '';
// Get options if needed
if (process.argv.length > 2) {
var opts = JSON.parse(process.argv[2]);
process.chdir(opts.file_path);
}
process.stdin.on('data', function(css) {
data += css;
});
process.stdin.on('end', function() {
stylefmt.process(data).then(function(result) {
try {
process.stdout.write(result.css);
} catch (err) {
throw err;
}
});
});
|
Update for new postcss promises
|
Update for new postcss promises
|
JavaScript
|
isc
|
dmnsgn/sublime-cssfmt,dmnsgn/sublime-cssfmt,dmnsgn/sublime-stylefmt
|
47eb145d096e569254fcc96d1b71925cf0ff631f
|
src/background.js
|
src/background.js
|
'use strict';
/**
* Returns a BlockingResponse object with a redirect URL if the request URL
* matches a file type extension.
*
* @param {object} request
* @return {object|undefined} the blocking response
*/
function requestInterceptor(request) {
var url = request.url;
var hasParamTs = /\?.*ts=/;
var hasExtGo = /\.go/;
if (!hasParamTs.test(url) && hasExtGo.test(url))
return {redirectUrl: addTabSizeParam(url, 2)};
}
/**
* Returns a URL with the query param ts=size included.
*
* @param {string} url
* @param {number} size
* @return {string}
*/
function addTabSizeParam(url, size) {
var urlWithTs = new Url(url);
urlWithTs.query.ts = size;
return urlWithTs.toString();
}
chrome.webRequest.onBeforeRequest.addListener(
requestInterceptor,
{urls: ['https://github.com/*']},
['blocking']
);
|
'use strict';
var tabSize = 2;
/**
* Returns a BlockingResponse object with a redirect URL if the request URL
* matches a file type extension.
*
* @param {object} request
* @return {object|undefined} the blocking response
*/
function requestInterceptor(request) {
var url = request.url;
var hasParamTs = /\?.*ts=/;
var hasExtGo = /\.go/;
if (!hasParamTs.test(url) && hasExtGo.test(url))
return {redirectUrl: addTabSizeParam(url, tabSize)};
}
/**
* Returns a URL with the query param ts=size included.
*
* @param {string} url
* @param {number} size
* @return {string}
*/
function addTabSizeParam(url, size) {
var urlWithTs = new Url(url);
urlWithTs.query.ts = size;
return urlWithTs.toString();
}
chrome.webRequest.onBeforeRequest.addListener(
requestInterceptor,
{urls: ['https://github.com/*']},
['blocking']
);
chrome.storage.sync.get({tabSize: tabSize}, function(items) {
tabSize = items.tabSize;
});
chrome.storage.onChanged.addListener(function(items) {
tabSize = items.tabSize.newValue;
});
|
Use tab size from Chrome storage
|
Use tab size from Chrome storage
|
JavaScript
|
mit
|
nysa/github-tab-sizer
|
6653fcba245b25adc7c20bf982a3d119f2659711
|
.prettierrc.js
|
.prettierrc.js
|
module.exports = {
printWidth: 100,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: true,
quoteProps: 'consistent',
trailingComma: 'all',
bracketSpacing: true,
arrowParens: 'always',
};
|
module.exports = {
printWidth: 100,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: true,
quoteProps: 'consistent',
trailingComma: 'all',
bracketSpacing: true,
arrowParens: 'always',
endOfLine: 'lf',
};
|
Set endOfLine to "lf" in prettier-config
|
:wrench: Set endOfLine to "lf" in prettier-config
|
JavaScript
|
apache-2.0
|
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
|
1b2d9602dade5c599390645bd02e9b066f4f0ef5
|
cla_frontend/assets-src/javascripts/app/test/protractor.conf.local.js
|
cla_frontend/assets-src/javascripts/app/test/protractor.conf.local.js
|
(function () {
'use strict';
var extend = require('extend'),
defaults = require('./protractor.conf');
exports.config = extend(defaults.config, {
// --- uncomment to use mac mini's ---
// seleniumAddress: 'http://clas-mac-mini.local:4444/wd/hub',
// baseUrl: 'http://Marcos-MacBook-Pro-2.local:8001/',
multiCapabilities: [
{
browserName: 'chrome'
},
{
browserName: 'firefox'
}
]
});
})();
|
(function () {
'use strict';
var extend = require('extend'),
defaults = require('./protractor.conf');
exports.config = extend(defaults.config, {
// --- uncomment to use mac mini's ---
// seleniumAddress: 'http://clas-mac-mini.local:4444/wd/hub',
// baseUrl: 'http://Marcos-MacBook-Pro-2.local:8001/',
multiCapabilities: [
{
browserName: 'chrome',
'chromeOptions': {
args: ['--test-type']
}
},
{
browserName: 'firefox'
}
]
});
})();
|
Remove chrome warnings during e2e tests
|
Remove chrome warnings during e2e tests
|
JavaScript
|
mit
|
ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend
|
276492033ce2a3048b453d75c0e361bf4ebfd5d7
|
tests/spec/QueueTwoStacksSpec.js
|
tests/spec/QueueTwoStacksSpec.js
|
describe("Implement queue with two stacks", function() {
const Queue = new QueueTwoStacks();
Queue.enqueue(1);
Queue.enqueue(2);
Queue.enqueue(3);
describe("enqueue()", function() {
it("appends an element to tail", function() {
Queue.enqueue(4);
const expected = [1,2,3,4];
expect(Queue.inStack).toEqual(expected);
})
it("appends an element correctly after dequeing", function() {
Queue.dequeue();
Queue.enqueue(5);
const expected = [2,3,4,5];
expect(Queue.inStack).toEqual(expected);
})
})
describe("dequeue()", function () {
it("removes an element from head", function () {
Queue.dequeue();
const expected = [3,4,5];
expect(Queue.inStack).toEqual(expected);
})
})
describe("when queue is empty", function() {
it("throws an error", function() {
Queue.dequeue();
Queue.dequeue();
Queue.dequeue();
expect(function() {
Queue.dequeue();
}).toThrow();
})
})
})
|
describe("Implement queue with two stacks", function() {
const Queue = new QueueTwoStacks();
Queue.enqueue(1);
Queue.enqueue(2);
Queue.enqueue(3);
describe("enqueue()", function() {
it("appends an element to tail", function() {
Queue.enqueue(4);
const expected = [1,2,3,4];
expect(Queue.inStack).toEqual(expected);
})
it("appends an element correctly after dequeing", function() {
Queue.dequeue();
Queue.enqueue(5);
const expected = [2,3,4,5];
expect(Queue.inStack).toEqual(expected);
})
});
describe("dequeue()", function () {
it("removes an element from head", function () {
Queue.dequeue();
const expected = [3,4,5];
expect(Queue.inStack).toEqual(expected);
});
it("throws an error when queue is empty", function() {
Queue.dequeue();
Queue.dequeue();
Queue.dequeue();
expect(function() {
Queue.dequeue();
}).toThrow();
})
});
})
|
Move code to correct semantics in spec
|
Move code to correct semantics in spec
|
JavaScript
|
mit
|
ThuyNT13/algorithm-practice,ThuyNT13/algorithm-practice
|
009e3a12d21aa5b04acd1f17616a6af2458046b1
|
src/projects/TicTacToe/TicTacToe.js
|
src/projects/TicTacToe/TicTacToe.js
|
import React from 'react';
import './TicTacToe.scss';
import { connect } from 'react-redux';
import ticTacToeActions from 'actions/tictactoe';
import GameBoard from './components/GameBoard';
const mapStateToProps = (state) => {
return {
playerTurn: state.tictactoe.playerTurn
};
};
class TicTacToe extends React.Component {
static propTypes = {
playerTurn: React.PropTypes.bool,
computer_move: React.PropTypes.func
}
componentWillReceiveProps (propObj) {
if (!propObj.playerTurn) {
this.props.computer_move();
}
if (propObj.winner && propObj.winner.result === 'draw') {
// do very cool modal fadein
} else if (propObj.winner) {
// do very cool modal fadein with computer winning
}
// nothing else, the player can't win
}
render () {
return (
<div>
<h1 className='text-center'>Tic-Tac-Toe</h1>
<GameBoard />
</div>
);
}
}
export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
|
import React from 'react';
import './TicTacToe.scss';
import { connect } from 'react-redux';
import ticTacToeActions from 'actions/tictactoe';
import GameBoard from './components/GameBoard';
const mapStateToProps = (state) => {
return {
playerTurn: state.tictactoe.playerTurn,
winner: state.tictactoe.winner
};
};
class TicTacToe extends React.Component {
static propTypes = {
playerTurn: React.PropTypes.bool,
computer_move: React.PropTypes.func
}
componentWillReceiveProps (propObj) {
if (!propObj.playerTurn) {
this.props.computer_move();
}
if (propObj.winner && propObj.winner.result === 'draw') {
// do very cool modal fadein
console.log('DRAW');
} else if (propObj.winner) {
// do very cool modal fadein with computer winning
console.log('YOU LOST');
}
// nothing else, the player can't win
}
render () {
return (
<div>
<h1 className='text-center'>Tic-Tac-Toe</h1>
<h2 className='text-center'>Open your console to see messages</h2>
<h3 className='text-center'>You can't win</h3>
<GameBoard />
</div>
);
}
}
export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
|
Add console statements for initial notification
|
Add console statements for initial notification
|
JavaScript
|
mit
|
terakilobyte/terakilobyte.github.io,terakilobyte/terakilobyte.github.io
|
520a7ecf81d37df70aefe39efe2e9e1092f25a52
|
tests/unit/models/canvas-test.js
|
tests/unit/models/canvas-test.js
|
import { moduleForModel, test } from 'ember-qunit';
moduleForModel('canvas', 'Unit | Model | canvas', {
// Specify the other units that are required for this test.
needs: 'model:op model:pulseEvent model:team model:user'.w()
});
test('it exists', function(assert) {
const model = this.subject();
assert.ok(Boolean(model));
});
|
import { moduleForModel, test } from 'ember-qunit';
moduleForModel('canvas', 'Unit | Model | canvas', {
// Specify the other units that are required for this test.
needs: 'model:comment model:op model:pulseEvent model:team model:user'.w()
});
test('it exists', function(assert) {
const model = this.subject();
assert.ok(Boolean(model));
});
|
Add missing model dependency for canvas model test
|
Add missing model dependency for canvas model test
|
JavaScript
|
apache-2.0
|
usecanvas/web-v2,usecanvas/web-v2,usecanvas/web-v2
|
7d8ef029b25f4869bf046e6e28fc4bd801614944
|
src/atom/index.js
|
src/atom/index.js
|
class Atom {
constructor(state) {
this.state = state;
this.watches = {};
}
reset(state) {
return this._change(state);
}
swap(f, ...args) {
return this._change(f(this.state, ...args));
}
deref() {
return this.state;
}
addWatch(k, f) {
// if (this.watches[key]) {
// console.warn(`adding a watch with an already registered key: ${k}`);
// }
this.watches[k] = f;
return this;
}
removeWatch(k) {
// if (!this.watches[key]) {
// console.warn(`removing a watch with an unknown key: ${k}`);
// }
delete this.watches[key];
return this;
}
_change(newState) {
const { state, watches } = this;
Object.keys(watches).forEach(k => watches[k](k, state, newState));
this.state = newState;
return this.state;
}
}
export default function atom(state) {
return new Atom(state);
}
|
class Atom {
constructor(state) {
this.state = state;
this.watches = {};
}
reset(state) {
return this._change(state);
}
swap(f, ...args) {
return this._change(f(this.state, ...args));
}
deref() {
return this.state;
}
addWatch(k, f) {
// if (this.watches[key]) {
// console.warn(`adding a watch with an already registered key: ${k}`);
// }
this.watches[k] = f;
return this;
}
removeWatch(k) {
// if (!this.watches[key]) {
// console.warn(`removing a watch with an unknown key: ${k}`);
// }
delete this.watches[key];
return this;
}
_change(newState) {
const { state, watches } = this;
this.state = newState;
Object.keys(watches).forEach(k => watches[k](k, state, newState));
return this.state;
}
}
export default function atom(state) {
return new Atom(state);
}
|
Update atom state before calling watches
|
Update atom state before calling watches
|
JavaScript
|
mit
|
mike-casas/lock,mike-casas/lock,auth0/lock-passwordless,mike-casas/lock,auth0/lock-passwordless,auth0/lock-passwordless
|
fc4428b965c58dda423f8bd100ccbb0760d44893
|
spec/case-sensitive/program.js
|
spec/case-sensitive/program.js
|
var test = require("test");
require("a");
try {
require("A");
test.assert(false, "should fail to require alternate spelling");
} catch (error) {
}
test.print("DONE", "info");
|
var test = require("test");
try {
require("a");
require("A");
test.assert(false, "should fail to require alternate spelling");
} catch (error) {
}
test.print("DONE", "info");
|
Update case sensitivity test to capture errors on first require
|
Update case sensitivity test to capture errors on first require
as this throws on case sensitive systems.
|
JavaScript
|
bsd-3-clause
|
kriskowal/mr,kriskowal/mr
|
ec343008e4db8688acfb383a3b254a86ecfeac29
|
shared/reducers/favorite.js
|
shared/reducers/favorite.js
|
/* @flow */
import * as Constants from '../constants/favorite'
import {logoutDone} from '../constants/login'
import type {FavoriteAction} from '../constants/favorite'
import type {Folder} from '../constants/types/flow-types'
type State = {
folders: ?Array<Folder>
}
const initialState = {
folders: null
}
export default function (state: State = initialState, action: FavoriteAction): State {
switch (action.type) {
case Constants.favoriteList:
return {
...state,
folders: action.payload && action.payload.folders
}
case logoutDone: {
return {
...state,
folders: null
}
}
default:
return state
}
}
|
/* @flow */
import * as Constants from '../constants/favorite'
import {logoutDone} from '../constants/login'
import type {FavoriteAction} from '../constants/favorite'
import type {Folder} from '../constants/types/flow-types'
type State = {
folders: ?Array<Folder>
}
const initialState = {
folders: null
}
export default function (state: State = initialState, action: FavoriteAction): State {
switch (action.type) {
case Constants.favoriteList:
return {
...state,
folders: action.payload && action.payload.folders
}
case logoutDone: {
return {
...initialState
}
}
default:
return state
}
}
|
Use initial state instead of setting folder manually
|
Use initial state instead of setting folder manually
|
JavaScript
|
bsd-3-clause
|
keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client
|
42be88e329535f7777e0c33da7194d21bf81c6b4
|
gulp/tasks/html.js
|
gulp/tasks/html.js
|
var gulp = require ('gulp');
gulp.task ( 'html', ['css'], function() {
gulp.src('src/main/resources/html/**')
.pipe ( gulp.dest( './build/') );
gulp.src('src/test/resources/**')
.pipe ( gulp.dest('./build/data/'));
gulp.src(['node_modules/dat-gui/vendor/dat*.js'])
.pipe ( gulp.dest('./build/js/'));
// "Vendor" packages
// Bootstrap
gulp.src(['node_modules/bootstrap/dist/**'])
.pipe ( gulp.dest('./build'));
// Font Awesome
gulp.src(['node_modules/font-awesome/fonts/**'])
.pipe( gulp.dest('./build/fonts'));
gulp.src(['node_modules/font-awesome/css/**'])
.pipe( gulp.dest('./build/css'));
// JQuery
gulp.src(['node_modules/jquery/dist/**'])
.pipe( gulp.dest('./build/js'));
// Dropzone file upload
gulp.src(['node_modules/dropzone/downloads/*js'])
.pipe(gulp.dest('./build/js'));
gulp.src(['node_modules/dropzone/downloads/css/**'])
.pipe(gulp.dest('./build/css'));
gulp.src(['node_modules/dropzone/downloads/images/**'])
.pipe(gulp.dest('./build/images'));
});
|
var gulp = require ('gulp');
gulp.task ( 'html', ['css'], function() {
gulp.src('src/main/resources/html/**')
.pipe ( gulp.dest( './build/') );
gulp.src('src/main/resources/js/**')
.pipe ( gulp.dest( './build/js/') );
gulp.src('src/main/resources/images/**')
.pipe ( gulp.dest( './build/images/') );
gulp.src('src/test/resources/**')
.pipe ( gulp.dest('./build/data/'));
gulp.src(['node_modules/dat-gui/vendor/dat*.js'])
.pipe ( gulp.dest('./build/js/'));
// XTK Local build (if available)
// should copy for production
gulp.src(['../X/utils/xtk.js'])
.pipe ( gulp.dest('./build/js'));
// "Vendor" packages
// Bootstrap
gulp.src(['node_modules/bootstrap/dist/**'])
.pipe ( gulp.dest('./build'));
// Font Awesome
gulp.src(['node_modules/font-awesome/fonts/**'])
.pipe( gulp.dest('./build/fonts'));
gulp.src(['node_modules/font-awesome/css/**'])
.pipe( gulp.dest('./build/css'));
// JQuery
gulp.src(['node_modules/jquery/dist/**'])
.pipe( gulp.dest('./build/js'));
// Dropzone file upload
gulp.src(['node_modules/dropzone/downloads/*js'])
.pipe(gulp.dest('./build/js'));
gulp.src(['node_modules/dropzone/downloads/css/**'])
.pipe(gulp.dest('./build/css'));
gulp.src(['node_modules/dropzone/downloads/images/**'])
.pipe(gulp.dest('./build/images'));
});
|
Include JS and XTK in build
|
Include JS and XTK in build
|
JavaScript
|
bsd-3-clause
|
dblezek/webapp-skeleton,dblezek/webapp-skeleton
|
06a9a7400aedc0985657874c3aba35af6ab6b1fb
|
app/components/Settings/components/colors-panel.js
|
app/components/Settings/components/colors-panel.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { Switch } from '@blueprintjs/core';
import { Themes } from '../../../containers/enums';
const ColorsPanel = ({ theme, setTheme }) =>
<div className="mt-1">
<h3 className="mb-3">Themes</h3>
<Switch
label="Dark Theme"
checked={theme === Themes.DARK}
onChange={() =>
setTheme(theme === Themes.DARK ? Themes.LIGHT : Themes.DARK)}
className="pt-large w-fit-content"
/>
</div>;
ColorsPanel.propTypes = {
theme: PropTypes.string.isRequired,
setTheme: PropTypes.func.isRequired
};
export default ColorsPanel;
|
import React from 'react';
import PropTypes from 'prop-types';
import { RadioGroup, Radio } from '@blueprintjs/core';
import { Themes } from '../../../containers/enums';
const ColorsPanel = ({ theme, setTheme }) =>
<div className="mt-1">
<RadioGroup
label="Themes"
selectedValue={theme}
onChange={e => setTheme(e.target.value)}
>
<Radio label="Dark Mode" value={Themes.DARK} />
<Radio label="Light Mode" value={Themes.LIGHT} />
</RadioGroup>
</div>;
ColorsPanel.propTypes = {
theme: PropTypes.string.isRequired,
setTheme: PropTypes.func.isRequired
};
export default ColorsPanel;
|
Select themes as radio buttons
|
enhancement: Select themes as radio buttons
|
JavaScript
|
mit
|
builtwithluv/ZenFocus,builtwithluv/ZenFocus
|
d286a3d9d171b77651e6c81fad3970baa5584fdc
|
src/javascript/binary/common_functions/check_new_release.js
|
src/javascript/binary/common_functions/check_new_release.js
|
const url_for_static = require('../base/url').url_for_static;
const moment = require('moment');
const check_new_release = function() { // calling this method is handled by GTM tags
const last_reload = localStorage.getItem('new_release_reload_time');
// prevent reload in less than 10 minutes
if (last_reload && +last_reload + (10 * 60 * 1000) > moment().valueOf()) return;
const currect_hash = $('script[src*="binary.min.js"],script[src*="binary.js"]').attr('src').split('?')[1];
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (+xhttp.readyState === 4 && +xhttp.status === 200) {
const latest_hash = xhttp.responseText;
if (latest_hash && latest_hash !== currect_hash) {
localStorage.setItem('new_release_reload_time', moment().valueOf());
window.location.reload(true);
}
}
};
xhttp.open('GET', url_for_static() + 'version?' + Math.random().toString(36).slice(2), true);
xhttp.send();
};
module.exports = {
check_new_release: check_new_release,
};
|
const url_for_static = require('../base/url').url_for_static;
const moment = require('moment');
const check_new_release = function() { // calling this method is handled by GTM tags
const last_reload = localStorage.getItem('new_release_reload_time');
// prevent reload in less than 10 minutes
if (last_reload && +last_reload + (10 * 60 * 1000) > moment().valueOf()) return;
localStorage.setItem('new_release_reload_time', moment().valueOf());
const currect_hash = $('script[src*="binary.min.js"],script[src*="binary.js"]').attr('src').split('?')[1];
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (+xhttp.readyState === 4 && +xhttp.status === 200) {
const latest_hash = xhttp.responseText;
if (latest_hash && latest_hash !== currect_hash) {
window.location.reload(true);
}
}
};
xhttp.open('GET', url_for_static() + 'version?' + Math.random().toString(36).slice(2), true);
xhttp.send();
};
module.exports = {
check_new_release: check_new_release,
};
|
Check for new release in 10 minutes intervals
|
Check for new release in 10 minutes intervals
|
JavaScript
|
apache-2.0
|
binary-com/binary-static,negar-binary/binary-static,4p00rv/binary-static,ashkanx/binary-static,raunakkathuria/binary-static,raunakkathuria/binary-static,binary-static-deployed/binary-static,binary-static-deployed/binary-static,raunakkathuria/binary-static,binary-com/binary-static,kellybinary/binary-static,ashkanx/binary-static,4p00rv/binary-static,negar-binary/binary-static,binary-com/binary-static,negar-binary/binary-static,kellybinary/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,4p00rv/binary-static,kellybinary/binary-static
|
45731fa369103e32b6b02d6ed5e99997def24e08
|
app/client/components/Sidebar/Sidebar.js
|
app/client/components/Sidebar/Sidebar.js
|
// @flow
import React, { Component } from 'react'
import { Link } from 'react-router'
import s from './Sidebar.scss'
export default class Sidebar extends Component {
constructor (props) {
super(props)
this.state = {
links: [
{ text: 'Dashboard', to: '/admin/dashboard' },
{ text: 'Entries', to: '/admin/entries' },
{ text: 'Globals', to: '/admin/globals' },
{ text: 'Categories', to: '/admin/categories' },
{ text: 'Assets', to: '/admin/assets' },
{ text: 'Settings', to: '/admin/settings' }
]
}
}
renderLink (link) {
return (
<li>
<Link className={s.link}
activeClassName={s.activeLink}
to={link.to}>
{link.text}
</Link>
</li>
)
}
render () {
return (
<header className={s.root}>
<nav className={s.nav}>
<ul>
{this.state.links.map(this.renderLink)}
</ul>
</nav>
</header>
)
}
}
|
// @flow
import React, { Component } from 'react'
import { Link } from 'react-router'
import s from './Sidebar.scss'
export default class Sidebar extends Component {
constructor (props) {
super(props)
this.state = {
links: [
{ text: 'Dashboard', to: '/admin/dashboard' },
{ text: 'Entries', to: '/admin/entries' },
{ text: 'Globals', to: '/admin/globals' },
{ text: 'Categories', to: '/admin/categories' },
{ text: 'Assets', to: '/admin/assets' },
{ text: 'Settings', to: '/admin/settings' }
]
}
}
renderLink (link, index) {
return (
<li key={index}>
<Link className={s.link}
activeClassName={s.activeLink}
to={link.to}>
{link.text}
</Link>
</li>
)
}
render () {
return (
<header className={s.root}>
<nav className={s.nav}>
<ul>
{this.state.links.map(this.renderLink)}
</ul>
</nav>
</header>
)
}
}
|
Add key to sidebar links
|
Add key to sidebar links
|
JavaScript
|
mit
|
jmdesiderio/swan-cms,jmdesiderio/swan-cms
|
11c4c935d9bb1ab5967a8eba97cd73d6ee9df684
|
packages/internal-test-helpers/lib/ember-dev/setup-qunit.js
|
packages/internal-test-helpers/lib/ember-dev/setup-qunit.js
|
/* globals QUnit */
export default function setupQUnit(assertion, _qunitGlobal) {
var qunitGlobal = QUnit;
if (_qunitGlobal) {
qunitGlobal = _qunitGlobal;
}
var originalModule = qunitGlobal.module;
qunitGlobal.module = function(name, _options) {
var options = _options || {};
var originalSetup = options.setup || function() { };
var originalTeardown = options.teardown || function() { };
options.setup = function() {
assertion.reset();
assertion.inject();
return originalSetup.apply(this, arguments);
};
options.teardown = function() {
let result = originalTeardown.apply(this, arguments);
assertion.assert();
assertion.restore();
return result;
};
return originalModule(name, options);
};
}
|
/* globals QUnit */
export default function setupQUnit(assertion, _qunitGlobal) {
var qunitGlobal = QUnit;
if (_qunitGlobal) {
qunitGlobal = _qunitGlobal;
}
var originalModule = qunitGlobal.module;
qunitGlobal.module = function(name, _options) {
var options = _options || {};
var originalSetup = options.setup || options.beforeEach || function() { };
var originalTeardown = options.teardown || options.afterEach || function() { };
delete options.setup;
delete options.teardown;
options.beforeEach = function() {
assertion.reset();
assertion.inject();
return originalSetup.apply(this, arguments);
};
options.afterEach = function() {
let result = originalTeardown.apply(this, arguments);
assertion.assert();
assertion.restore();
return result;
};
return originalModule(name, options);
};
}
|
Add support for beforeEach / afterEach to ember-dev assertions.
|
Add support for beforeEach / afterEach to ember-dev assertions.
|
JavaScript
|
mit
|
kellyselden/ember.js,fpauser/ember.js,thoov/ember.js,kanongil/ember.js,Gaurav0/ember.js,mixonic/ember.js,csantero/ember.js,Gaurav0/ember.js,Turbo87/ember.js,kennethdavidbuck/ember.js,gfvcastro/ember.js,sandstrom/ember.js,csantero/ember.js,xiujunma/ember.js,asakusuma/ember.js,qaiken/ember.js,jasonmit/ember.js,givanse/ember.js,tildeio/ember.js,qaiken/ember.js,sly7-7/ember.js,karthiick/ember.js,kellyselden/ember.js,thoov/ember.js,knownasilya/ember.js,kanongil/ember.js,jaswilli/ember.js,csantero/ember.js,givanse/ember.js,mixonic/ember.js,stefanpenner/ember.js,givanse/ember.js,GavinJoyce/ember.js,jaswilli/ember.js,mike-north/ember.js,sandstrom/ember.js,Turbo87/ember.js,asakusuma/ember.js,emberjs/ember.js,Serabe/ember.js,kanongil/ember.js,cibernox/ember.js,qaiken/ember.js,thoov/ember.js,miguelcobain/ember.js,mike-north/ember.js,kellyselden/ember.js,mike-north/ember.js,runspired/ember.js,gfvcastro/ember.js,knownasilya/ember.js,bekzod/ember.js,intercom/ember.js,twokul/ember.js,GavinJoyce/ember.js,qaiken/ember.js,jasonmit/ember.js,jasonmit/ember.js,fpauser/ember.js,sly7-7/ember.js,bekzod/ember.js,xiujunma/ember.js,mixonic/ember.js,fpauser/ember.js,tildeio/ember.js,twokul/ember.js,stefanpenner/ember.js,kellyselden/ember.js,mfeckie/ember.js,tildeio/ember.js,elwayman02/ember.js,asakusuma/ember.js,twokul/ember.js,runspired/ember.js,miguelcobain/ember.js,karthiick/ember.js,cibernox/ember.js,knownasilya/ember.js,intercom/ember.js,gfvcastro/ember.js,mfeckie/ember.js,emberjs/ember.js,jaswilli/ember.js,mike-north/ember.js,gfvcastro/ember.js,elwayman02/ember.js,asakusuma/ember.js,xiujunma/ember.js,sandstrom/ember.js,kanongil/ember.js,Serabe/ember.js,bekzod/ember.js,bekzod/ember.js,Turbo87/ember.js,jasonmit/ember.js,stefanpenner/ember.js,Gaurav0/ember.js,miguelcobain/ember.js,twokul/ember.js,cibernox/ember.js,kennethdavidbuck/ember.js,runspired/ember.js,karthiick/ember.js,jasonmit/ember.js,kennethdavidbuck/ember.js,fpauser/ember.js,miguelcobain/ember.js,elwayman02/ember.js,jaswilli/ember.js,xiujunma/ember.js,Serabe/ember.js,mfeckie/ember.js,givanse/ember.js,elwayman02/ember.js,Gaurav0/ember.js,GavinJoyce/ember.js,csantero/ember.js,Turbo87/ember.js,intercom/ember.js,cibernox/ember.js,mfeckie/ember.js,emberjs/ember.js,runspired/ember.js,GavinJoyce/ember.js,sly7-7/ember.js,Serabe/ember.js,intercom/ember.js,kennethdavidbuck/ember.js,karthiick/ember.js,thoov/ember.js
|
7dbdff31b9c97fb7eed2420e1e46508dee1797a2
|
ember-cli-build.js
|
ember-cli-build.js
|
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
var app = new EmberAddon(defaults, {
'ember-cli-babel': {
includePolyfill: true
},
'ember-cli-qunit': {
useLintTree: false // we use standard instead
}
});
// we do this because we don't want the addon to bundle it, but we need it for dev
app.import('vendor/adapter.js');
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
|
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
const cdnUrl = process.env.CDN_URL || '/';
module.exports = function (defaults) {
var app = new EmberAddon(defaults, {
'ember-cli-babel': {
includePolyfill: true
},
'ember-cli-qunit': {
useLintTree: false // we use standard instead
},
fingerprint: {
prepend: cdnUrl,
extensions: ['js', 'css']
}
});
// we do this because we don't want the addon to bundle it, but we need it for dev
app.import('vendor/adapter.js');
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
|
Add fingerprinting for troubleshooter deployed app
|
Add fingerprinting for troubleshooter deployed app
|
JavaScript
|
mit
|
MyPureCloud/ember-webrtc-troubleshoot,MyPureCloud/ember-webrtc-troubleshoot,MyPureCloud/ember-webrtc-troubleshoot
|
294aafacd298a013881f92f7a866a8b07f5a25f5
|
examples/simple.js
|
examples/simple.js
|
"use strict";
const Rectangle = require('../lib/Rectangle');
const cursor = require('kittik-cursor').create().resetTTY();
Rectangle.create({text: 'Text here!', x: 'center', width: 20, background: 'green', foreground: 'black'}).render(cursor);
Rectangle.create({x: 'center', y: 'middle', width: '50%', height: '20%', background: 'dark_blue'}).render(cursor);
cursor.moveTo(1, process.stdout.rows).flush();
|
"use strict";
const Rectangle = require('../lib/Rectangle');
const cursor = require('kittik-cursor').create().resetTTY();
Rectangle.create({
text: 'Text here!',
x: 'center',
y: 2,
width: 40,
background: 'green',
foreground: 'black'
}).render(cursor);
Rectangle.create({
text: 'Text here',
x: 'center',
y: 'middle',
width: '50%',
height: '20%',
background: 'dark_blue'
}).render(cursor);
cursor.moveTo(1, process.stdout.rows).flush();
|
Update shape-basic to the latest version
|
fix(shape): Update shape-basic to the latest version
|
JavaScript
|
mit
|
kittikjs/shape-rectangle
|
68943423f789993e2ca91cd5f76e94d524a127c8
|
addon/authenticators/token.js
|
addon/authenticators/token.js
|
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import Configuration from '../configuration';
const { get, isEmpty, inject: { service }, RSVP: { resolve, reject } } = Ember;
export default Base.extend({
ajax: service(),
init() {
this._super(...arguments);
this.serverTokenEndpoint = Configuration.serverTokenEndpoint;
this.tokenAttributeName = Configuration.tokenAttributeName;
this.identificationAttributeName = Configuration.identificationAttributeName;
},
restore(data) {
const token = get(data, this.tokenAttributeName);
if (!isEmpty(token)) {
return resolve(data);
} else {
return reject();
}
},
authenticate(data) {
return get(this, 'ajax').post(this.serverTokenEndpoint, {
data: JSON.stringify(data)
}).then((response) => {
return resolve(response);
}).catch((error) => {
Ember.Logger.warn(error);
return reject();
});
}
});
|
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import Configuration from '../configuration';
const { get, isEmpty, inject: { service }, RSVP: { resolve, reject } } = Ember;
export default Base.extend({
ajax: service(),
init() {
this._super(...arguments);
this.serverTokenEndpoint = Configuration.serverTokenEndpoint;
this.tokenAttributeName = Configuration.tokenAttributeName;
this.identificationAttributeName = Configuration.identificationAttributeName;
},
restore(data) {
const token = get(data, this.tokenAttributeName);
if (!isEmpty(token)) {
return resolve(data);
} else {
return reject();
}
},
authenticate(data) {
return get(this, 'ajax').post(this.serverTokenEndpoint, {
contentType: 'application/json',
data: JSON.stringify(data)
}).then((response) => {
return resolve(response);
}).catch((error) => {
Ember.Logger.warn(error);
return reject();
});
}
});
|
Add JSON content type to authenticate headers
|
Add JSON content type to authenticate headers
|
JavaScript
|
mit
|
datajohnny/ember-simple-token,datajohnny/ember-simple-token
|
836cf5d5caf8a0cde92a6e018f3ea28aa77eb42e
|
app/javascript/application.js
|
app/javascript/application.js
|
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import './controllers'
|
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import 'controllers'
|
Fix importmap loading on production
|
Fix importmap loading on production
|
JavaScript
|
mit
|
dncrht/mical,dncrht/mical,dncrht/mical,dncrht/mical
|
99fe3b420e9bc14a2d01fd0f3c61bb94ce970a2c
|
hooks/src/index.js
|
hooks/src/index.js
|
import { options } from 'preact';
let currentIndex;
let component;
options.beforeRender = function (vnode) {
component = vnode._component;
currentIndex = 0;
}
const createHook = (create) => (...args) => {
if (component == null) return;
const list = component.__hooks || (component.__hooks = []);
let index = currentIndex++;
let hook = list[index];
if (!hook) {
hook = list[index] = { index, value: undefined };
hook.run = create(hook, component, ...args);
}
return (hook.value = hook.run());
};
export const useState = createHook((hook, inst, initialValue) => {
const stateId = 'hookstate$' + hook.index;
let value = typeof initialValue === 'function' ? initialValue() : initialValue;
const setter = {};
setter[stateId] = inst.state[stateId] = value;
function set(v) {
value = setter[stateId] = typeof v === 'function' ? v(value) : v;
inst.setState(setter);
}
return () => [value, set];
});
|
import { options } from 'preact';
let currentIndex;
let component;
let oldBeforeRender = options.beforeRender;
options.beforeRender = vnode => {
component = vnode._component;
currentIndex = 0;
if (oldBeforeRender) oldBeforeRender(vnode)
}
const createHook = (create) => (...args) => {
if (component == null) return;
const list = component.__hooks || (component.__hooks = []);
let index = currentIndex++;
let hook = list[index];
if (!hook) {
hook = list[index] = { index, value: undefined };
hook.run = create(hook, component, ...args);
}
return (hook.value = hook.run());
};
export const useState = createHook((hook, inst, initialValue) => {
const stateId = 'hookstate$' + hook.index;
let value = typeof initialValue === 'function' ? initialValue() : initialValue;
const setter = {};
setter[stateId] = inst.state[stateId] = value;
function set(v) {
value = setter[stateId] = typeof v === 'function' ? v(value) : v;
inst.setState(setter);
}
return () => [value, set];
});
|
Call any previous beforeRender() once we're done with ours
|
Call any previous beforeRender() once we're done with ours
|
JavaScript
|
mit
|
developit/preact,developit/preact
|
79788a69daa951d85f4600926c464d6fbff9fe5b
|
assets/javascripts/global.js
|
assets/javascripts/global.js
|
$(function () {
$('input[type="file"]').on('change', function (e) {
if ($(this).val()) {
$('input[type="submit"]').prop('disabled', false);
}
else {
$('input[type="submit"]').prop('disabled', true);
}
});
$('input[name="format"]').on('change', function (e) {
var action = $('form').prop('action'),
new_action = action.replace(/\.[^.]+$/, '.' + $(this).val());
$('form').prop('action', new_action);
});
$('input[name="format"]').trigger('change');
});
|
$(function () {
$('input[type="file"]').on('change', function (e) {
if ($(this).val()) {
$('input[type="submit"]').prop('disabled', false);
}
else {
$('input[type="submit"]').prop('disabled', true);
}
});
$('input[name="format"]:checked').on('change', function (e) {
var action = $('form').prop('action'),
new_action = action.replace(/\.[^.]+$/, '.' + $(this).val());
$('form').prop('action', new_action);
});
$('input[name="format"]:checked').trigger('change');
});
|
Fix ARCSPC-45: Handle radio button form action setting correctly
|
Fix ARCSPC-45: Handle radio button form action setting correctly
|
JavaScript
|
apache-2.0
|
harvard-library/archivesspace-checker,harvard-library/archivesspace-checker
|
30dd01f64e5e7dc98a517c8ff2353ab2cdde0583
|
lib/assets/javascripts/cartodb3/components/form-components/editors/node-dataset/node-dataset-item-view.js
|
lib/assets/javascripts/cartodb3/components/form-components/editors/node-dataset/node-dataset-item-view.js
|
var CustomListItemView = require('cartodb3/components/custom-list/custom-list-item-view');
var _ = require('underscore');
module.exports = CustomListItemView.extend({
render: function () {
this.$el.empty();
this.clearSubViews();
this.$el.append(
this.options.template(
_.extend(
{
typeLabel: this.options.typeLabel,
isSelected: this.model.get('selected'),
name: this.model.getName(),
val: this.model.getValue()
},
this.model.attributes
)
)
);
this.$el
.attr('data-val', this.model.getValue())
.toggleClass('is-disabled', !!this.model.get('disabled'));
return this;
}
});
|
var CustomListItemView = require('cartodb3/components/custom-list/custom-list-item-view');
var _ = require('underscore');
module.exports = CustomListItemView.extend({
render: function () {
this.$el.empty();
this.clearSubViews();
this.$el.append(
this.options.template(
_.extend(
{
typeLabel: this.options.typeLabel,
isSelected: this.model.get('selected'),
isSourceType: this.model.get('isSourceType'),
name: this.model.getName(),
val: this.model.getValue()
},
this.model.attributes
)
)
);
this.$el
.attr('data-val', this.model.getValue())
.toggleClass('is-disabled', !!this.model.get('disabled'));
return this;
}
});
|
Add isSourceType to base template object
|
Add isSourceType to base template object
|
JavaScript
|
bsd-3-clause
|
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
|
36a53309e022f1ad6351756568bcc4d9e0df6940
|
app/src/common/base-styles.js
|
app/src/common/base-styles.js
|
export default function() {
return `
html {
height: 100%;
overflow-y: scroll;
}
body {
font-family: 'Lato', sans-serif;
font-size: 14px;
color: #000;
background: #f6f6f6;
}
`;
}
|
export default function() {
return `
*,
*:before,
*:after {
box-sizing: inherit;
}
html {
height: 100%;
overflow-y: scroll;
box-sizing: border-box;
}
body {
font-family: 'Lato', sans-serif;
font-size: 14px;
color: #000;
background: #f6f6f6;
}
`;
}
|
Use 'border-box' as default box sizing
|
:lipstick: Use 'border-box' as default box sizing
|
JavaScript
|
mit
|
vvasilev-/weatheros,vvasilev-/weatheros
|
b3b18edfa2e964fe76125eb53189d92c48b867d1
|
src/is-defined.js
|
src/is-defined.js
|
define([
], function () {
/**
* @exports is-defined
*
* Helper which checks whether a variable is defined or not.
*
* @param {*} check The variable to check that is defined
* @param {String} type The type your expecting the variable to be defined as.
*
* @returns {Boolean} When the variable is undefined it will pass back false otherwise pass back true.
*
* @example
* ```js
* var barney;
* isDefined(barney);
* // Returns false
*
* var barney = 'stinson';
* isDefined(barney);
* // Returns true
*
* isDefined(barney, 'string');
* // Returns true
*
* isDefined(barney, 'function');
* // Returns false
* ```
*/
function isDefined (check, type) {
// Check that the variable is a specific type
if (type) {
var regex = new RegExp(/\[object (\w+)]/),
string = Object.prototype.toString.call(check).toLowerCase(),
matches = string.match(regex);
return matches[1] === type;
}
return (typeof check !== 'undefined');
}
return isDefined;
});
|
define([
], function () {
/**
* @exports is-defined
*
* Helper which checks whether a variable is defined or not.
*
* @param {*} check The variable to check that is defined
* @param {String} type The type your expecting the variable to be defined as.
*
* @returns {Boolean} When the variable is undefined it will pass back false otherwise pass back true.
*
* @example
* ```js
* var barney;
* isDefined(barney);
* // Returns false
*
* var barney = 'stinson';
* isDefined(barney);
* // Returns true
*
* isDefined(barney, 'string');
* // Returns true
*
* isDefined(barney, 'function');
* // Returns false
* ```
*/
function isDefined (check, type) {
// Check that the variable is a specific type && not undefined (IE8 reports undefined variables as objects)
if (type && typeof check !== 'undefined') {
var regex = new RegExp(/\[object (\w+)]/),
string = Object.prototype.toString.call(check).toLowerCase(),
matches = string.match(regex);
return matches[1] === type;
}
return (typeof check !== 'undefined');
}
return isDefined;
});
|
Fix bug in IE8 undefined returns as object
|
Fix bug in IE8 undefined returns as object
|
JavaScript
|
mit
|
rockabox/Auxilium.js
|
7f3804a1da20276ad309fa6554cca329f296ff64
|
app/assets/javascripts/districts/controllers/sister_modal_controller.js
|
app/assets/javascripts/districts/controllers/sister_modal_controller.js
|
VtTracker.SisterModalController = Ember.ObjectController.extend({
needs: ['districtSistersIndex', 'application'],
districts: Ember.computed.alias('controllers.application.model'),
modalTitle: function() {
if (this.get('isNew')) {
return 'New Sister';
} else {
return 'Edit Sister';
}
}.property('isNew'),
actions: {
save: function() {
var _self = this;
var isNew = _self.get('model.isNew');
var district = _self.get('model.district');
_self.get('model').save().then(function() {
if (isNew) {
_self.set('controllers.districtSistersIndex.newSister', _self.store.createRecord('sister', {
district: district
}));
}
});
}
}
});
|
VtTracker.SisterModalController = Ember.ObjectController.extend({
needs: ['districtSistersIndex', 'application'],
districts: Ember.computed.alias('controllers.application.model'),
modalTitle: function() {
if (this.get('isNew')) {
return 'New Sister';
} else {
return 'Edit Sister';
}
}.property('isNew'),
actions: {
removeModal: function() {
this.get('model').rollback();
return true;
},
save: function() {
var _self = this;
var isNew = _self.get('model.isNew');
var district = _self.get('model.district');
_self.get('model').save().then(function() {
if (isNew) {
_self.set('controllers.districtSistersIndex.newSister', _self.store.createRecord('sister', {
district: district
}));
}
});
}
}
});
|
Rollback model when modal is closed
|
Rollback model when modal is closed
|
JavaScript
|
mit
|
bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker
|
eb0f5fd8a337ace145c40e9b624738619542033a
|
Rightmove_Enhancement_Suite.user.js
|
Rightmove_Enhancement_Suite.user.js
|
// ==UserScript==
// @name Rightmove Enhancement Suite
// @namespace https://github.com/chigley/
// @description Keyboard shortcuts
// @include http://www.rightmove.co.uk/*
// @version 1
// @grant GM_addStyle
// @grant GM_getResourceText
// @resource style style.css
// ==/UserScript==
var $ = unsafeWindow.jQuery;
GM_addStyle(GM_getResourceText("style"));
var listItems = $("[name=summary-list-item]");
// Remove grey background on premium listings. Otherwise, my active item doesn't
// stand out against such listings
$(".premium").css("background", "white");
listItems.click(function () {
listItems.removeClass("RES-active-list-item");
$(this).addClass("RES-active-list-item");
});
$('body').bind('keyup', function(e) {
var code = e.keyCode || e.which;
if (e.keyCode == 74) {
// j
alert("j!");
}
});
|
// ==UserScript==
// @name Rightmove Enhancement Suite
// @namespace https://github.com/chigley/
// @description Keyboard shortcuts
// @include http://www.rightmove.co.uk/*
// @version 1
// @grant GM_addStyle
// @grant GM_getResourceText
// @resource style style.css
// ==/UserScript==
var $ = unsafeWindow.jQuery;
GM_addStyle(GM_getResourceText("style"));
var listItems = $("[name=summary-list-item]");
var currentlySelected;
// Remove grey background on premium listings. Otherwise, my active item doesn't
// stand out against such listings
$(".premium").css("background", "white");
listItems.click(function () {
listItems.removeClass("RES-active-list-item");
$(this).addClass("RES-active-list-item");
currentlySelected = $(this);
});
$('body').bind('keyup', function(e) {
var code = e.keyCode || e.which;
if (e.keyCode == 74) {
// j
var next = currentlySelected.next("[name=summary-list-item]");
if (next.length == 1) {
listItems.removeClass("RES-active-list-item");
next.addClass("RES-active-list-item");
currentlySelected = next;
}
}
});
|
Select next item with j key
|
Select next item with j key
|
JavaScript
|
mit
|
chigley/rightmove-enhancement-suite
|
f13ecda8d2a69f455b175d013a2609197f495bb0
|
src/components/outline/Link.js
|
src/components/outline/Link.js
|
// @flow
import styled, { css } from 'styled-components'
import * as vars from 'settings/styles'
import * as colors from 'settings/colors'
type Props = {
depth: '1' | '2' | '3' | '4' | '5' | '6',
}
const fn = ({ depth: depthStr }: Props) => {
const depth = parseInt(depthStr)
return css`
padding-left: ${(2 + (depth > 1 ? depth - 2 : 0)) * vars.spacing}px;
&:before {
content: '${'#'.repeat(depth)}';
}
`
}
const Link = styled.a`
display: block;
height: 100%;
padding-right: ${2 * vars.spacing}px;
border-bottom: 1px solid ${colors.blackForeground200};
text-decoration: none;
font-size: 0.9rem;
color: white;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
${fn}
&:before {
color: ${colors.whiteForeground300};
padding-right: ${vars.spacing}px;
font-size: 0.8rem;
}
&:hover {
background-color: ${colors.blackForeground200};
}
`
export default Link
|
// @flow
import styled, { css } from 'styled-components'
import * as vars from 'settings/styles'
import * as colors from 'settings/colors'
type Props = {
depth: '1' | '2' | '3' | '4' | '5' | '6',
}
const fn = ({ depth: depthStr }: Props) => {
const depth = parseInt(depthStr)
return css`
padding-left: ${(2 + (depth > 1 ? depth - 2 : 0)) * vars.spacing}px;
&:before {
content: '${'#'.repeat(depth)}';
}
`
}
const Link = styled.a`
display: block;
height: 100%;
padding-right: ${2 * vars.spacing}px;
border-bottom: 1px solid ${colors.blackForeground200};
text-decoration: none;
font-size: 0.9rem;
color: white;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
pointer-events: none;
${fn}
&:before {
color: ${colors.whiteForeground300};
padding-right: ${vars.spacing}px;
font-size: 0.8rem;
}
&:hover {
background-color: ${colors.blackForeground200};
}
`
export default Link
|
Disable pointer-events of outline items
|
Disable pointer-events of outline items
|
JavaScript
|
mit
|
izumin5210/OHP,izumin5210/OHP
|
248b0e54a3bda3271f5735dedf61eda8395d882d
|
src/helpers/find-root.js
|
src/helpers/find-root.js
|
'use babel'
/* @flow */
import Path from 'path'
import {findCached} from './common'
import {CONFIG_FILE_NAME} from '../defaults'
export async function findRoot(directory: string): Promise<string> {
const configFile = await findCached(directory, CONFIG_FILE_NAME)
if (configFile) {
return Path.dirname(configFile)
} else return directory
}
|
'use babel'
/* @flow */
import Path from 'path'
import {findCached} from './common'
import {CONFIG_FILE_NAME} from '../defaults'
export async function findRoot(directory: string): Promise<string> {
const configFile = await findCached(directory, CONFIG_FILE_NAME)
if (configFile) {
return Path.dirname(configFile)
} else throw new Error('No configuration found file')
}
|
Throw error if no config is found
|
:no_entry: Throw error if no config is found
|
JavaScript
|
mit
|
steelbrain/UCompiler
|
e78af7ead579d2c91f461734d2bdff5910cf3a5c
|
server.js
|
server.js
|
// Load required modules
var http = require('http'), // http server core module
port = 8080,
timeNow = new Date().toLocaleString('en-US', {hour12: false, timeZone: 'Europe/Kiev'}),
express = require('express'), // web framework external module
fs = require('fs'),
httpApp = express();
// Setup and configure Express http server. Expect a subfolder called 'site' to be the web root.
httpApp.use(express.static(__dirname + '/site/'));
// Start Express http server on the port
console.info(timeNow + ': Starting http server on the port ' + port);
console.info(timeNow + ': Ctrl-C to abort');
http.createServer(httpApp).listen(port);
|
// Load required modules
var http = require('http'), // http server core module
port = 8080,
timeNow = new Date().toLocaleString('en-US', {hour12: false, timeZone: 'Europe/Kiev'}),
express = require('express'), // web framework external module
fs = require('fs'),
httpApp = express();
// Setup and configure Express http server. Expect a subfolder called 'site' to be the web root.
httpApp.use(express.static(__dirname + '/site/'));
httpApp.get(['/search/*', '/profile/*', '/repo/*'], function(req, res){
res.sendFile(__dirname + '/site/index.html');
});
// Start Express http server on the port
console.info(timeNow + ': Starting http server on the port ' + port);
console.info(timeNow + ': Ctrl-C to abort');
http.createServer(httpApp).listen(port);
|
Set reroute to index.html for /search/*, /profile/*, /repo/*
|
Set reroute to index.html for /search/*, /profile/*, /repo/*
|
JavaScript
|
mit
|
SteveBidenko/github-angular,SteveBidenko/github-angular,SteveBidenko/github-angular
|
cfa1a5e3a4f3e988d3c844c84874a8dabd852822
|
src/engines/json/validation.js
|
src/engines/json/validation.js
|
/**
* Validation
*
* @constructor
* @param {object} options
*/
var Validation = function(options) {
// Save a reference to the ‘this’
var self = this;
var defaultOptions = {
singleError: true,
errorMessages: errorMessages,
cache: false
};
each(defaultOptions, function(key, value) {
if (isObject(value) && options[key]) {
self[key] = merge(options[key], defaultOptions[key]);
} else if (isObject(value) && !options[key]) {
self[key] = merge ({}, defaultOptions[key]);
} else {
self[key] = (isDefined(options[key])) ? options[key] : defaultOptions[key];
}
});
this.errors = new ValidationError();
};
|
/**
* Validation
*
* @constructor
* @param {object} options
*/
var Validation = function(options) {
// Save a reference to the ‘this’
var self = this;
var defaultOptions = {
singleError: true,
errorMessages: errorMessages,
cache: false
};
each(defaultOptions, function(key, value) {
if (isObject(value) && options[key]) {
self[key] = merge(options[key], defaultOptions[key]);
} else if (isObject(value) && !options[key]) {
self[key] = merge ({}, defaultOptions[key]);
} else {
self[key] = (isDefined(options[key])) ? options[key] : defaultOptions[key];
}
});
this.errors = new ValidationError(this);
};
|
Initialize the ‘ValidationError’ class as a subclass of the ‘Validation’ class
|
Initialize the ‘ValidationError’ class as a subclass of the ‘Validation’ class
|
JavaScript
|
mit
|
apiaryio/Amanda,Baggz/Amanda,apiaryio/Amanda
|
5d309087a7e4cd2931a1c8e29096f9eadb5de188
|
src/lb.js
|
src/lb.js
|
/*
* Namespace: lb
* Root of Legal Box Scalable JavaScript Application
*
* Authors:
* o Eric Bréchemier <[email protected]>
* o Marc Delhommeau <[email protected]>
*
* Copyright:
* Legal-Box SAS (c) 2010-2011, All Rights Reserved
*
* License:
* BSD License
* http://creativecommons.org/licenses/BSD/
*
* Version:
* 2011-07-04
*/
/*jslint white:false, plusplus:false */
/*global define, window */
define(function() {
// Note: no methods defined at this level currently
var lb = { // public API
};
// initialize global variable lb in browser environment,
// for backward-compatibility
if (window !== undefined){
window.lb = lb;
}
return lb;
});
|
/*
* Namespace: lb
* Root of Legal Box Scalable JavaScript Application
*
* Authors:
* o Eric Bréchemier <[email protected]>
* o Marc Delhommeau <[email protected]>
*
* Copyright:
* Legal-Box SAS (c) 2010-2011, All Rights Reserved
*
* License:
* BSD License
* http://creativecommons.org/licenses/BSD/
*
* Version:
* 2011-07-05
*/
/*jslint white:false, plusplus:false */
/*global define, window */
define(function(undefined) {
// Note: no methods defined at this level currently
var lb = { // public API
};
// initialize global variable lb in browser environment,
// for backward-compatibility
if (window !== undefined){
window.lb = lb;
}
return lb;
});
|
Declare undefined as parameter to make sure it is actually undefined
|
Declare undefined as parameter to make sure it is actually undefined
Since undefined is a property of the global object, its value may be replaced,
e.g. due to programming mistakes:
if (undefined = myobject){ // programming mistake which assigns undefined
// ...
}
|
JavaScript
|
bsd-3-clause
|
eric-brechemier/lb_js_scalableApp,eric-brechemier/lb_js_scalableApp,eric-brechemier/lb_js_scalableApp
|
a8d2e74163cf71bb811150143089f83aca2c55a0
|
src/lightbox/LightboxFooter.js
|
src/lightbox/LightboxFooter.js
|
/* @flow */
import React, { PureComponent } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import type { Style } from '../types';
import NavButton from '../nav/NavButton';
const styles = StyleSheet.create({
wrapper: {
height: 44,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 16,
paddingRight: 8,
flex: 1,
},
text: {
color: 'white',
fontSize: 14,
alignSelf: 'center',
},
icon: {
fontSize: 28,
},
});
type Props = {
style?: Style,
displayMessage: string,
onOptionsPress: () => void,
};
export default class LightboxFooter extends PureComponent<Props> {
props: Props;
render() {
const { displayMessage, onOptionsPress, style } = this.props;
return (
<View style={[styles.wrapper, style]}>
<Text style={styles.text}>{displayMessage}</Text>
<NavButton
name="more-vertical"
color="white"
style={styles.icon}
onPress={onOptionsPress}
/>
</View>
);
}
}
|
/* @flow */
import React, { PureComponent } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import type { Style } from '../types';
import Icon from '../common/Icons';
const styles = StyleSheet.create({
wrapper: {
height: 44,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 16,
paddingRight: 8,
flex: 1,
},
text: {
color: 'white',
fontSize: 14,
alignSelf: 'center',
},
icon: {
fontSize: 28,
alignSelf: 'center',
},
});
type Props = {
style?: Style,
displayMessage: string,
onOptionsPress: () => void,
};
export default class LightboxFooter extends PureComponent<Props> {
props: Props;
render() {
const { displayMessage, onOptionsPress, style } = this.props;
return (
<View style={[styles.wrapper, style]}>
<Text style={styles.text}>{displayMessage}</Text>
<Icon style={styles.icon} color="white" name="more-vertical" onPress={onOptionsPress} />
</View>
);
}
}
|
Align option icon in Lightbox screen
|
layout: Align option icon in Lightbox screen
Icon was not properly aligned due to overlay of unreadCount.
As there is no need of unreadCount here, Instead of using NavButton,
use Icon component directly.
Fixes #3003.
|
JavaScript
|
apache-2.0
|
vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.