commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
e04ca3b0e41a521422876cfdc0d81f2afb7791ad | app/components/Icon/index.js | app/components/Icon/index.js | // @flow
import styles from './Icon.css';
type Props = {
/** Name of the icon can be found on the webpage*/
name: string,
scaleOnHover?: boolean,
className?: string,
size?: number,
style?: Object,
};
/**
* Render an Icon like this with the name of your icon:
*
* <Icon name="add" />
*
* Names can be found here:
* https://ionic.io/ionicons
*
*/
const Icon = ({
name = 'star',
scaleOnHover = false,
className,
style = {},
size = 24,
...props
}: Props) => {
return (
<ion-icon
name={name}
class={className}
style={{
fontSize: `${size.toString()}px`,
lineHeight: 2,
...style,
}}
{...(props: Object)}
></ion-icon>
);
};
Icon.Badge = ({ badgeCount, ...props }: Props & { badgeCount: number }) => {
const icon = <Icon {...props} />;
if (!badgeCount) {
return icon;
}
return (
<div style={{ position: 'relative' }}>
<span className={styles.badge}>{badgeCount}</span>
{icon}
</div>
);
};
Icon.Badge.displayName = 'IconBadge';
export default Icon;
| // @flow
import styles from './Icon.css';
type Props = {
/** Name of the icon can be found on the webpage*/
name: string,
scaleOnHover?: boolean,
className?: string,
size?: number,
style?: Object,
};
/**
* Render an Icon like this with the name of your icon:
*
* <Icon name="add" />
*
* Names can be found here:
* https://ionic.io/ionicons
*
*/
const Icon = ({
name = 'star',
scaleOnHover = false,
className,
style = {},
size = 24,
...props
}: Props) => {
return (
<div
className={className}
style={{
fontSize: `${size.toString()}px`,
...style,
}}
{...(props: Object)}
>
<ion-icon name={name}></ion-icon>
</div>
);
};
Icon.Badge = ({ badgeCount, ...props }: Props & { badgeCount: number }) => {
const icon = <Icon {...props} />;
if (!badgeCount) {
return icon;
}
return (
<div style={{ position: 'relative' }}>
<span className={styles.badge}>{badgeCount}</span>
{icon}
</div>
);
};
Icon.Badge.displayName = 'IconBadge';
export default Icon;
| Move className onto a div wrapping ion-icon | Move className onto a div wrapping ion-icon
This is to avoid overwriting ion-icons own classnames that it sets on itself. Overwriting these causes the icon to become invisible.
| JavaScript | mit | webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp | ---
+++
@@ -29,16 +29,16 @@
...props
}: Props) => {
return (
- <ion-icon
- name={name}
- class={className}
+ <div
+ className={className}
style={{
fontSize: `${size.toString()}px`,
- lineHeight: 2,
...style,
}}
{...(props: Object)}
- ></ion-icon>
+ >
+ <ion-icon name={name}></ion-icon>
+ </div>
);
};
|
ade2364d04762c5a1e15db674117905f179a2d52 | jest/setupEnv.js | jest/setupEnv.js | require('babel-polyfill');
// jsdom doesn't have support for localStorage at the moment
global.localStorage = require('localStorage');
// Tests should just mock responses for the json API
// so let's just default to a noop
var RequestUtil = require('mesosphere-shared-reactjs').RequestUtil;
RequestUtil.json = function () {};
| require('babel-polyfill');
// jsdom doesn't have support for localStorage at the moment
global.localStorage = require('localStorage');
// Tests should just mock responses for the json API
// so let's just default to a noop
var RequestUtil = require('mesosphere-shared-reactjs').RequestUtil;
RequestUtil.json = function () {};
// jsdom doesn't have support for requestAnimationFrame so we polyfill it.
// https://gist.github.com/paulirish/1579671
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) {
global.requestAnimationFrame = global[vendors[x] + 'RequestAnimationFrame'];
global.cancelAnimationFrame = global[vendors[x] + 'CancelAnimationFrame']
|| global[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!global.requestAnimationFrame)
global.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = global.setTimeout(
function () {
callback(currTime + timeToCall);
},
timeToCall
);
lastTime = currTime + timeToCall;
return id;
};
if (!global.cancelAnimationFrame) {
global.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}());
| Implement a better requestAnimationFrame polyfill | Implement a better requestAnimationFrame polyfill
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -7,3 +7,37 @@
// so let's just default to a noop
var RequestUtil = require('mesosphere-shared-reactjs').RequestUtil;
RequestUtil.json = function () {};
+
+// jsdom doesn't have support for requestAnimationFrame so we polyfill it.
+// https://gist.github.com/paulirish/1579671
+(function() {
+ var lastTime = 0;
+ var vendors = ['ms', 'moz', 'webkit', 'o'];
+
+ for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) {
+ global.requestAnimationFrame = global[vendors[x] + 'RequestAnimationFrame'];
+ global.cancelAnimationFrame = global[vendors[x] + 'CancelAnimationFrame']
+ || global[vendors[x] + 'CancelRequestAnimationFrame'];
+ }
+
+ if (!global.requestAnimationFrame)
+ global.requestAnimationFrame = function (callback, element) {
+ var currTime = new Date().getTime();
+ var timeToCall = Math.max(0, 16 - (currTime - lastTime));
+ var id = global.setTimeout(
+ function () {
+ callback(currTime + timeToCall);
+ },
+ timeToCall
+ );
+
+ lastTime = currTime + timeToCall;
+ return id;
+ };
+
+ if (!global.cancelAnimationFrame) {
+ global.cancelAnimationFrame = function(id) {
+ clearTimeout(id);
+ };
+ }
+}()); |
09a1b1c34a39fcc8ba432614e976aed2c7798123 | app/components/bd-arrival.js | app/components/bd-arrival.js | import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['arrival'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow('mm');
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 100%);
background-color: hsl(${hue}, 50%, 55%);
border-color: hsl(${hue}, 50%, 55%);`;
})
});
| import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['timeline__event'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow('mm');
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 100%);
background-color: hsl(${hue}, 50%, 55%);
border-color: hsl(${hue}, 50%, 55%);`;
})
});
| Change the class name on the arrival component container | Change the class name on the arrival component container
| JavaScript | mit | bus-detective/web-client,bus-detective/web-client | ---
+++
@@ -7,7 +7,7 @@
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
- classNames: ['arrival'],
+ classNames: ['timeline__event'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() { |
17591c67c2d59f6f19395068d40a144ce041aa96 | ember-cli-build.js | ember-cli-build.js | /*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('bower_components/d3/d3.js');
// Customized version of nvd3
app.import('vendor/nvd3/build/nv.d3.css');
app.import('vendor/nvd3/build/nv.d3.js');
return app.toTree();
};
| /*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('bower_components/d3/d3.js');
app.import('bower_components/lodash/lodash.min.js');
// Customized version of nvd3
app.import('vendor/nvd3/build/nv.d3.css');
app.import('vendor/nvd3/build/nv.d3.js');
return app.toTree();
};
| Add lodash to production build. | Add lodash to production build.
| JavaScript | mit | jga/capmetrics-web,jga/capmetrics-web | ---
+++
@@ -21,6 +21,7 @@
// along with the exports of each module as its value.
app.import('bower_components/d3/d3.js');
+ app.import('bower_components/lodash/lodash.min.js');
// Customized version of nvd3
app.import('vendor/nvd3/build/nv.d3.css');
app.import('vendor/nvd3/build/nv.d3.js'); |
a4c9f3032bbaafc2a7b33161f33fa8bcc536c88f | lib/cucumber/cli/argument_parser/feature_path_expander.js | lib/cucumber/cli/argument_parser/feature_path_expander.js | var fs = require('fs');
var glob = require('glob');
var _ = require('underscore');
var FeaturePathExpander = {
expandPaths: function expandPaths(paths) {
var Cucumber = require('../../../cucumber');
var PathExpander = Cucumber.Cli.ArgumentParser.PathExpander;
var expandedPaths = PathExpander.expandPathsWithGlobString(paths, FeaturePathExpander.GLOB_FEATURE_FILES_IN_DIR_STRING);
return expandedPaths;
}
};
FeaturePathExpander.GLOB_FEATURE_FILES_IN_DIR_STRING = "**/*.feature";
module.exports = FeaturePathExpander;
| var FeaturePathExpander = {
expandPaths: function expandPaths(paths) {
var Cucumber = require('../../../cucumber');
var PathExpander = Cucumber.Cli.ArgumentParser.PathExpander;
var expandedPaths = PathExpander.expandPathsWithGlobString(paths, FeaturePathExpander.GLOB_FEATURE_FILES_IN_DIR_STRING);
return expandedPaths;
}
};
FeaturePathExpander.GLOB_FEATURE_FILES_IN_DIR_STRING = "**/*.feature";
module.exports = FeaturePathExpander;
| Remove unneeded requires from FeaturePathExpander | Remove unneeded requires from FeaturePathExpander
| JavaScript | mit | cucumber/cucumber-js,bluenergy/cucumber-js,mhoyer/cucumber-js,vilmysj/cucumber-js,arty-name/cucumber-js,AbraaoAlves/cucumber-js,richardmcsong/cucumber-js,vilmysj/cucumber-js,bluenergy/cucumber-js,eddieloeffen/cucumber-js,tdekoning/cucumber-js,Telogical/CucumberJS,cucumber/cucumber-js,MinMat/cucumber-js,arty-name/cucumber-js,SierraGolf/cucumber-js,AbraaoAlves/cucumber-js,mhoyer/cucumber-js,eddieloeffen/cucumber-js,karthiktv006/cucumber-js,cucumber/cucumber-js,i-e-b/cucumber-js,gnikhil2/cucumber-js,vilmysj/cucumber-js,MinMat/cucumber-js,h2non/cucumber-js,richardmcsong/cucumber-js,eddieloeffen/cucumber-js,marnen/cucumber-js,h2non/cucumber-js,h2non/cucumber-js,richardmcsong/cucumber-js,arty-name/cucumber-js,bluenergy/cucumber-js,AbraaoAlves/cucumber-js,SierraGolf/cucumber-js,tdekoning/cucumber-js,marnen/cucumber-js,gnikhil2/cucumber-js,gnikhil2/cucumber-js,i-e-b/cucumber-js,Telogical/CucumberJS,mhoyer/cucumber-js,MinMat/cucumber-js,karthiktv006/cucumber-js,SierraGolf/cucumber-js,marnen/cucumber-js | ---
+++
@@ -1,7 +1,3 @@
-var fs = require('fs');
-var glob = require('glob');
-var _ = require('underscore');
-
var FeaturePathExpander = {
expandPaths: function expandPaths(paths) {
var Cucumber = require('../../../cucumber'); |
a32ef2c72b98383682a6e8810133612af512cac5 | init.js | init.js | const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const tilde = require('tilde-expansion');
const shell = require('shelljs');
const appRootDir = require('app-root-dir').get();
const setConfigProp = require('./setConfigProp');
const newTodoMonth = require('./newTodoMonth');
const init = function({ dir, withGit=false }){
tilde(dir, (expandedDir) => {
if (!fs.existsSync(expandedDir)) return console.log(chalk.red('Directory for workbook doesnt exist'));
console.log(chalk.green(`Initializing new todo workbook in ${dir}`));
const configPath = path.join(appRootDir, 'config.json');
const todoRoot = path.join(expandedDir, 'todo');
if (!fs.existsSync( todoRoot )) fs.mkdirSync( todoRoot );
writeConfig( configPath, todoRoot );
setConfigProp({ todoRoot, withGit });
newTodoMonth( todoRoot );
if (withGit) {
console.log(chalk.blue('Initialising with git'));
shell.cd(expandedDir);
shell.exec('git init');
shell.exec('git add --all');
shell.exec('git commit -m "Initial Commit"');
}
});
};
const writeConfig = function(configPath){
console.log(chalk.green('Writing config'));
fs.writeFileSync(configPath, JSON.stringify({}));
}
module.exports = init; | const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const tilde = require('tilde-expansion');
const shell = require('shelljs');
const appRootDir = require('app-root-dir').get();
const setConfigProp = require('./setConfigProp');
const newTodoMonth = require('./newTodoMonth');
const init = function({ dir, withGit=false }){
tilde(dir, (expandedDir) => {
if (!fs.existsSync(expandedDir)) return console.log(chalk.red('Directory for workbook doesnt exist'));
console.log(chalk.green(`Initializing new todo workbook in ${dir}`));
const configPath = path.join(appRootDir, 'config.json');
let todoRoot = expandedDir;
if(path.parse(expandedDir).name !== 'todo') todoRoot = path.join(expandedDir, 'todo');
if (!fs.existsSync( todoRoot )) fs.mkdirSync( todoRoot );
writeConfig( configPath, todoRoot );
setConfigProp({ todoRoot, withGit });
newTodoMonth( todoRoot );
if (withGit) {
console.log(chalk.blue('Initialising with git'));
shell.cd(todoRoot);
shell.exec('git init');
shell.exec('git add --all');
shell.exec('git commit -m "Initial Commit"');
}
});
};
const writeConfig = function(configPath){
console.log(chalk.green('Writing config'));
fs.writeFileSync(configPath, JSON.stringify({}));
}
module.exports = init; | Add check for existing /todo folder in path | Add check for existing /todo folder in path
| JavaScript | mit | zweck/todo_cmd | ---
+++
@@ -12,7 +12,9 @@
if (!fs.existsSync(expandedDir)) return console.log(chalk.red('Directory for workbook doesnt exist'));
console.log(chalk.green(`Initializing new todo workbook in ${dir}`));
const configPath = path.join(appRootDir, 'config.json');
- const todoRoot = path.join(expandedDir, 'todo');
+
+ let todoRoot = expandedDir;
+ if(path.parse(expandedDir).name !== 'todo') todoRoot = path.join(expandedDir, 'todo');
if (!fs.existsSync( todoRoot )) fs.mkdirSync( todoRoot );
writeConfig( configPath, todoRoot );
@@ -20,7 +22,7 @@
newTodoMonth( todoRoot );
if (withGit) {
console.log(chalk.blue('Initialising with git'));
- shell.cd(expandedDir);
+ shell.cd(todoRoot);
shell.exec('git init');
shell.exec('git add --all');
shell.exec('git commit -m "Initial Commit"'); |
d3f36d8906a4adc4454c4f499f4f2d4514eec981 | examples/simple.js | examples/simple.js | $( document ).ready(function() {
var typer = $('.typeahead');
var genders = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'https://raw.githubusercontent.com/anne-decusatis/genderamender/master/genders.json'
});
typer.typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'genders',
source: genders
});
typer.bind('typeahead:select', function(ev, suggestion) {
var choices = $('#user-genders');
choices.html( choices.html() + "<li>" + suggestion + " </li>" ); //FIXME: i'm 100% certain there's a better way for this
});
});
| $( document ).ready(function() {
var typer = $('.typeahead');
var genders = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'https://raw.githubusercontent.com/anne-decusatis/genderamender/master/genders.json',
sorter: function(a, b) {
var i = typer.val().toLowerCase();
// If there's a complete match it wins.
if(i == a) { return -1; }
else if (i == b) { return 1; }
// Otherwise just sort it naturally.
else if (a < b) { return -1; }
else if (a > b) { return 1; }
else return 0;
}
});
typer.typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'genders',
source: genders
});
typer.bind('typeahead:select', function(ev, suggestion) {
var choices = $('#user-genders');
choices.html( choices.html() + "<li>" + suggestion + " </li>" ); //FIXME: i'm 100% certain there's a better way for this
});
});
| Make typeahead sort-- promoting identical matches, or just naturally. | Make typeahead sort-- promoting identical matches, or just naturally.
| JavaScript | mit | anne-decusatis/genderamender | ---
+++
@@ -1,15 +1,28 @@
$( document ).ready(function() {
var typer = $('.typeahead');
-
var genders = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
- prefetch: 'https://raw.githubusercontent.com/anne-decusatis/genderamender/master/genders.json'
+ prefetch: 'https://raw.githubusercontent.com/anne-decusatis/genderamender/master/genders.json',
+ sorter: function(a, b) {
+ var i = typer.val().toLowerCase();
+
+ // If there's a complete match it wins.
+ if(i == a) { return -1; }
+ else if (i == b) { return 1; }
+
+ // Otherwise just sort it naturally.
+ else if (a < b) { return -1; }
+ else if (a > b) { return 1; }
+ else return 0;
+ }
});
+
typer.typeahead({
hint: true,
highlight: true,
minLength: 1
+
},
{
name: 'genders', |
81713ce1ad6ed20505d7bd6c57d404f68c971f43 | src/server/api/gallery-api.js | src/server/api/gallery-api.js | import Post from 'src/models/PostModel';
import { buildGalleryPost } from 'src/server/modules/build';
export default (req, res, next) => {
Post.paginate({}, {
page: req.query.page,
limit: req.query.limit,
sort: '-postDate',
select: 'title images postDate',
})
.then((data) => {
const posts = data.docs.map(post => buildGalleryPost(post));
res.send(posts.join());
})
.catch(err => next(err));
}
| import Post from 'src/models/PostModel';
import { buildGalleryPost } from 'src/server/modules/build';
export default (req, res, next) => {
let dataRequest;
if (req.query.page) {
dataRequest = Post.paginate({}, {
page: req.query.page,
limit: req.query.limit,
sort: '-postDate',
select: 'title images postDate',
})
.then(data => data.docs)
} else {
dataRequest = Post
.find({})
.sort('-postDate')
.select('title images postDate')
.lean();
}
dataRequest
.then((data) => {
const posts = data.map(post => buildGalleryPost(post));
res.send(posts.join());
})
.catch(err => next(err));
}
| Handle paged requests differently than get-all requests | Handle paged requests differently than get-all requests
| JavaScript | mit | tuelsch/bolg,tuelsch/bolg | ---
+++
@@ -2,14 +2,25 @@
import { buildGalleryPost } from 'src/server/modules/build';
export default (req, res, next) => {
- Post.paginate({}, {
- page: req.query.page,
- limit: req.query.limit,
- sort: '-postDate',
- select: 'title images postDate',
- })
+ let dataRequest;
+ if (req.query.page) {
+ dataRequest = Post.paginate({}, {
+ page: req.query.page,
+ limit: req.query.limit,
+ sort: '-postDate',
+ select: 'title images postDate',
+ })
+ .then(data => data.docs)
+ } else {
+ dataRequest = Post
+ .find({})
+ .sort('-postDate')
+ .select('title images postDate')
+ .lean();
+ }
+ dataRequest
.then((data) => {
- const posts = data.docs.map(post => buildGalleryPost(post));
+ const posts = data.map(post => buildGalleryPost(post));
res.send(posts.join());
})
.catch(err => next(err)); |
9b20a73621e58aa8907c382891996be188c17b85 | examples/with-multiple-dates.js | examples/with-multiple-dates.js | import React from 'react';
import {render} from 'react-dom';
import InfiniteCalendar, {
Calendar,
defaultMultipleDateInterpolation,
withMultipleDates,
} from 'react-infinite-calendar';
import 'react-infinite-calendar/styles.css';
render(
<InfiniteCalendar
Component={withMultipleDates(Calendar)}
/*
* The `interpolateSelection` prop allows us to map the resulting state when a user selects a date.
* By default, it adds the date to the selected dates array if it isn't already selected.
* If the date is already selected, it removes it.
*
* You could re-implement this if this isn't the behavior you want.
*/
interpolateSelection={defaultMultipleDateInterpolation}
selected={[new Date(2017, 1, 10), new Date(2017, 1, 18), new Date()]}
/>,
document.querySelector('#root')
);
| import React from 'react';
import {render} from 'react-dom';
import InfiniteCalendar, {
Calendar,
defaultMultipleDateInterpolation,
withMultipleDates,
} from 'react-infinite-calendar';
import 'react-infinite-calendar/styles.css';
const MultipleDatesCalendar = withMultipleDates(Calendar);
render(
<InfiniteCalendar
Component={MultipleDatesCalendar}
/*
* The `interpolateSelection` prop allows us to map the resulting state when a user selects a date.
* By default, it adds the date to the selected dates array if it isn't already selected.
* If the date is already selected, it removes it.
*
* You could re-implement this if this isn't the behavior you want.
*/
interpolateSelection={defaultMultipleDateInterpolation}
selected={[new Date(2017, 1, 10), new Date(2017, 1, 18), new Date()]}
/>,
document.querySelector('#root')
);
| Update withMultipleDates HOC example usage | Update withMultipleDates HOC example usage | JavaScript | mit | clauderic/react-infinite-calendar | ---
+++
@@ -7,9 +7,11 @@
} from 'react-infinite-calendar';
import 'react-infinite-calendar/styles.css';
+const MultipleDatesCalendar = withMultipleDates(Calendar);
+
render(
<InfiniteCalendar
- Component={withMultipleDates(Calendar)}
+ Component={MultipleDatesCalendar}
/*
* The `interpolateSelection` prop allows us to map the resulting state when a user selects a date.
* By default, it adds the date to the selected dates array if it isn't already selected. |
ec15a4d069fcf835970171ca9e5b79b064c1fdd8 | src/app/login/login.component.e2e-spec.js | src/app/login/login.component.e2e-spec.js | describe('Login', function () {
beforeEach(function () {
browser.get('/login');
});
it('should have <my-login>', function () {
var login = element(by.css('my-app my-login'));
expect(login.isPresent()).toEqual(true);
login.element(by.name("email")).sendKeys("test@gmail.com");
login.element(by.name("password")).sendKeys("azerty1988");
login.element(by.className("btn")).click();
/** Ajax call login here, waiting post request finished **/
browser.waitForAngular().then(function () {
const success = login.element(by.className("alert-success"));
expect(success.isPresent()).toEqual(true);
});
});
}); | describe('Login', function () {
beforeEach(function () {
browser.get('/login');
});
it('should have <my-login>', function () {
var login = element(by.css('my-app my-login'));
expect(login.isPresent()).toEqual(true);
login.element(by.name("email")).sendKeys("test@gmail.com");
login.element(by.name("password")).sendKeys("mptest");
login.element(by.className("btn")).click();
/** Ajax call login here, waiting post request finished **/
browser.waitForAngular().then(function () {
const success = login.element(by.className("alert-success"));
expect(success.isPresent()).toEqual(true);
});
});
});
| Update login component test e2e | Update login component test e2e | JavaScript | mit | JunkyDeLuxe/angular4-starter,JunkyDeLuxe/angular4-starter,JunkyDeLuxe/angular4-starter | ---
+++
@@ -8,7 +8,7 @@
expect(login.isPresent()).toEqual(true);
login.element(by.name("email")).sendKeys("test@gmail.com");
- login.element(by.name("password")).sendKeys("azerty1988");
+ login.element(by.name("password")).sendKeys("mptest");
login.element(by.className("btn")).click();
|
02df584af6d6070cef63d42d2c8f39d696d4cfac | red/storage/index.js | red/storage/index.js | /**
* Copyright 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var settings = require('../red').settings;
var storageType = settings.storageModule || "localfilesystem";
module.exports = require("./"+storageType);
| /**
* Copyright 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var settings = require('../red').settings;
var mod;
if (settings.storageModule) {
if (typeof settings.storageModule === "string") {
// TODO: allow storage modules to be specified by absolute path
mod = require("./"+settings.storageModule);
} else {
mod = settings.storageModule;
}
} else {
mod = require("./localfilesystem");
}
module.exports = mod;
| Allow storage module to be set explicitly | Allow storage module to be set explicitly
Rather than just by name
| JavaScript | apache-2.0 | HiroyasuNishiyama/node-red,PaGury/node-red,mw75/node-red,whummer/node-red,codeaudit/node-red,dojot/mashup,PaGury/node-red,mikestebbins/node-red,whoGloo/node-red,btsimonh/node-red,michaelsteenkamp/node-red,anusornc/node-red,rntdrts/node-red,lucciano/node-red,gbraad/node-red,cgvarela/node-red,lostinthestory/node-red,anusornc/node-red,emiloberg/node-red,rdrm2014/node-red,fcollova/node-red,wajnberg/node-red,ddm/node-red,FlowDesigner/node-red,Tizen-Sunfish/ehf-node-red,rntdrts/node-red,ddm/node-red,mw75/node-red,ioglue/ioglue,zcpara/robot_gui_program,weitingchou/humix-think,kanki8086/node-red,michaelsteenkamp/node-red,gbraad/node-red,wajnberg/node-red,syzer/node-red,coderofsalvation/node-red,beni55/node-red,giovannicuriel/mashup,iotcafe/node-red,whoGloo/node-red,modulexcite/node-red,PaGury/node-red,augustnmonteiro/skills-visual-programming,augustnmonteiro/skills-visual-programming,estbeetoo/beetoo-controller,rdrm2014/node-red,dbuentello/node-red,beni55/node-red,syzer/node-red,retailos/node-red,namgk/node-red,xively/habanero,udayanga91/node-red,fcollova/node-red,retailos/node-red,whummer/node-red,btsimonh/node-red,FlowDesigner/node-red,ChipSoftTech/HANDS2,avinod1987/Node-Red,HiroyasuNishiyama/node-red,redcom/node-red-freeboard,MADAR15/IoT-Modeler,cgvarela/node-red,gbraad/node-red,kanki8086/node-red,estbeetoo/beetoo-controller,gbraad/node-red,MaxXx1313/my-node-red,knolleary/node-red,ioglue/ioglue,MADAR15/IoT-Modeler,codeaudit/node-red,retailos/node-red,MaxXx1313/my-node-red,fcollova/node-red,mblackstock/node-red-contrib,ChipSoftTech/HANDS2,xively/habanero,tak4hir0/node-red,coderofsalvation/node-red,monteslu/pagenodes,darcy202/node-red,mikestebbins/node-red,cloudfoundry-community/node-red-cf-ready,dbuentello/node-red,whummer/node-red,redcom/node-red-freeboard,ppillip/node-red,knolleary/node-red,ChipSoftTech/HANDS2,rdrm2014/node-red,nuroglu/cloudgate,cloudfoundry-community/node-red-cf-ready,mw75/node-red,redconnect-io/node-red,udayanga91/node-red,estbeetoo/beetoo-controller,cgvarela/node-red,wajnberg/node-red,monteslu/pagenodes,avinod1987/NodeRed,tak4hir0/node-red,the-osgarden/pi-nodered-osg,fpt-software/seniot-data-workflow,zcpara/robot_gui_program,udayanga91/node-red,mw75/node-red,MaxXx1313/my-node-red,lucciano/node-red,lostinthestory/node-red,ChipSoftTech/HANDS2,lostinthestory/node-red,dorado-lmz/node-red,fpt-software/seniot-data-workflow,syzer/node-red,augustnmonteiro/skills-visual-programming,namgk/node-red,beni55/node-red,modulexcite/node-red,Kazuki-Nakanishi/node-red,xively/habanero,whummer/node-red,syzer/node-red,zcpara/robot_gui_program,nuroglu/cloudgate,coderofsalvation/node-red,redconnect-io/node-red,nosun/node-red,ddm/node-red,codeaudit/node-red,Kazuki-Nakanishi/node-red,iotcafe/node-red,drwoods/node-red,btsimonh/node-red,olopez32/node-red,MADAR15/IoT-Modeler,weitingchou/humix-think,iotcafe/node-red,the-osgarden/pi-nodered-osg,Kazuki-Nakanishi/node-red,mikestebbins/node-red,PaGury/node-red,redconnect-io/node-red,ppillip/node-red,dbuentello/node-red,MaxXx1313/my-node-red,lucciano/node-red,Ubicall/node-red,darcy202/node-red,dojot/mashup,emiloberg/node-red,olopez32/node-red,Ubicall/node-red,avinod1987/Node-Red,dojot/mashup,weitingchou/humix-think,drwoods/node-red,ddm/node-red,anusornc/node-red,ioglue/ioglue,ty4tw/node-red,avinod1987/Node-Red,avinod1987/Node-Red,beni55/node-red,lucciano/node-red,coderofsalvation/node-red,nosun/node-red,the-osgarden/pi-nodered-osg,nuroglu/cloudgate,rdrm2014/node-red,FlowDesigner/node-red,redconnect-io/node-red,rntdrts/node-red,weitingchou/humix-think,augustnmonteiro/skills-visual-programming,HiroyasuNishiyama/node-red,avinod1987/NodeRed,node-red/node-red,giovannicuriel/mashup,dojot/mashup,dorado-lmz/node-red,giovannicuriel/mashup,node-red/node-red,nosun/node-red,avinod1987/NodeRed,emiloberg/node-red,ppillip/node-red,Kazuki-Nakanishi/node-red,codeaudit/node-red,cgvarela/node-red,ppillip/node-red,dbuentello/node-red,kanki8086/node-red,whoGloo/node-red,olopez32/node-red,ty4tw/node-red,knolleary/node-red,anusornc/node-red,nosun/node-red,dorado-lmz/node-red,estbeetoo/beetoo-controller,Tizen-Sunfish/ehf-node-red,the-osgarden/pi-nodered-osg,drwoods/node-red,Ubicall/node-red,ty4tw/node-red,mblackstock/node-red-contrib,udayanga91/node-red,darcy202/node-red,node-red/node-red,dorado-lmz/node-red,redcom/node-red-freeboard,xively/habanero,nuroglu/cloudgate,michaelsteenkamp/node-red,fpt-software/seniot-data-workflow,avinod1987/NodeRed,FlowDesigner/node-red,fpt-software/seniot-data-workflow,zcpara/robot_gui_program,olopez32/node-red,kanki8086/node-red,whoGloo/node-red,ilc-opensource/mcf,drwoods/node-red,iotcafe/node-red,mikestebbins/node-red,cloudfoundry-community/node-red-cf-ready,retailos/node-red,lostinthestory/node-red,redcom/node-red-freeboard,knolleary/node-red,modulexcite/node-red,fcollova/node-red,darcy202/node-red,cloudfoundry-community/node-red-cf-ready,Ubicall/node-red,modulexcite/node-red,michaelsteenkamp/node-red,wajnberg/node-red,giovannicuriel/mashup,monteslu/nodered-for-upstream | ---
+++
@@ -17,7 +17,18 @@
var settings = require('../red').settings;
-var storageType = settings.storageModule || "localfilesystem";
+var mod;
-module.exports = require("./"+storageType);
+if (settings.storageModule) {
+ if (typeof settings.storageModule === "string") {
+ // TODO: allow storage modules to be specified by absolute path
+ mod = require("./"+settings.storageModule);
+ } else {
+ mod = settings.storageModule;
+ }
+} else {
+ mod = require("./localfilesystem");
+}
+module.exports = mod;
+ |
b7d1fe2fb94dd62fc41b594ac6bdae01d2831da2 | command_handlers/purge.js | command_handlers/purge.js | const messageHelpers = require('../lib/message_helpers');
const handler = async function(message) {
const args = message.content.split(' ').slice(1);
// the first argument is non-optional, fail if not provided
if (args.length < 1) {
await messageHelpers.sendError(message,
'You must specify a number of messages to be deleted');
return;
}
const n = Number(args[0]);
if (isNaN(n)) {
await messageHelpers.sendError(message, `Invalid argument for n: ${n}`);
return;
}
// the user must be in a channel for this command to be useful
if (!message.channel) {
await messageHelpers.sendError(message,
`You must send this command from a channel for it to be useful`);
return;
}
// delete the messages
await message.channel.bulkDelete(n);
await message.delete();
};
module.exports = {
bind: 'purge',
handler: handler,
help: 'Purge the last <n> messages from the channel this command' +
'is invoked in.',
administrative: true,
};
| const messageHelpers = require('../lib/message_helpers');
const handler = async function(message) {
const args = message.content.split(' ').slice(1);
// the first argument is non-optional, fail if not provided
if (args.length < 1) {
await messageHelpers.sendError(message,
'You must specify a number of messages to be deleted');
return;
}
const n = Number(args[0]);
if (isNaN(n)) {
await messageHelpers.sendError(message, `Invalid argument for n: ${n}`);
return;
}
// the user must be in a channel for this command to be useful
if (!message.channel) {
await messageHelpers.sendError(message,
`You must send this command from a channel for it to be useful`);
return;
}
// delete the messages
await message.channel.bulkDelete(n);
await message.delete();
};
module.exports = {
bind: 'purge',
handler: handler,
help: 'Purge the last <n> messages from the channel this command' +
' is invoked in.',
administrative: true,
};
| Fix typo in help text | Fix typo in help text
| JavaScript | bsd-3-clause | ciarancrocker/sgs_bot,ciarancrocker/sgs_bot | ---
+++
@@ -32,6 +32,6 @@
bind: 'purge',
handler: handler,
help: 'Purge the last <n> messages from the channel this command' +
- 'is invoked in.',
+ ' is invoked in.',
administrative: true,
}; |
ab25026fe59624f1da1716e52ffd399f4707c846 | lib/init/authenticated.js | lib/init/authenticated.js | 'use strict';
/**
* @fileoverview Login check middleware
*/
const config = require('config');
/*
* Check authenticated status. Redirect to login page
*
* @param {object} req Express HTTP request
* @param {object} res Express HTTP response
* @param {object} next Express callback
*
*/
const authenticated = (req, res, next) => {
if ((!req.isAuthenticated || !req.isAuthenticated()) && req.url !== config.authentication.login.path && !req.url.startsWith('/css') && !req.url.startsWith('/js') && !req.url.startsWith('/images') && !req.url.startsWith('/favicon')) {
res.redirect('/login');
}
else {
// consistent-return turned off because this doesn't return a value
next(); // eslint-disable-line callback-return
}
};
/**
* @param {object} app - Express app
*
* @returns {object} app - Modified Express app
*/
const authInit = (app) => {
return new Promise((res) => {
app.use(authenticated);
res(app);
});
};
module.exports = authInit;
| 'use strict';
/**
* @fileoverview Login check middleware
*/
const config = require('config');
/*
* Check authenticated status. Redirect to login page
*
* @param {object} req Express HTTP request
* @param {object} res Express HTTP response
* @param {object} next Express callback
*
*/
const authenticated = (req, res, next) => {
if ((!req.isAuthenticated || !req.isAuthenticated()) && req.url !== config.authentication.login.path && !req.url.startsWith('/css') && !req.url.startsWith('/js') && !req.url.startsWith('/images') && !req.url.startsWith('/favicon') && !req.url.startsWith('/api')) {
res.redirect('/login');
}
else {
// consistent-return turned off because this doesn't return a value
next(); // eslint-disable-line callback-return
}
};
/**
* @param {object} app - Express app
*
* @returns {object} app - Modified Express app
*/
const authInit = (app) => {
return new Promise((res) => {
app.use(authenticated);
res(app);
});
};
module.exports = authInit;
| Remove login redirect for APIs | :bug: Remove login redirect for APIs
| JavaScript | apache-2.0 | Snugug/punchcard,punchcard-cms/punchcard,scottnath/punchcard,scottnath/punchcard,Snugug/punchcard,poofichu/punchcard,punchcard-cms/punchcard,poofichu/punchcard | ---
+++
@@ -14,7 +14,7 @@
*
*/
const authenticated = (req, res, next) => {
- if ((!req.isAuthenticated || !req.isAuthenticated()) && req.url !== config.authentication.login.path && !req.url.startsWith('/css') && !req.url.startsWith('/js') && !req.url.startsWith('/images') && !req.url.startsWith('/favicon')) {
+ if ((!req.isAuthenticated || !req.isAuthenticated()) && req.url !== config.authentication.login.path && !req.url.startsWith('/css') && !req.url.startsWith('/js') && !req.url.startsWith('/images') && !req.url.startsWith('/favicon') && !req.url.startsWith('/api')) {
res.redirect('/login');
}
else { |
172aee6f75877779da2511d236d8d3b708ac2b79 | index.js | index.js | "use strict";
var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
// Thanks to:
// http://fightingforalostcause.net/misc/2006/compare-email-regex.php
// http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx
// http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378
exports.validate = function(email)
{
if (!email)
return false;
if(email.length>254)
return false;
var valid = tester.test(email);
if(!valid)
return false;
// Further checking of some things regex can't handle
var parts = email.split("@");
if(parts[0].length>64)
return false;
var domainParts = parts[1].split(".");
if(domainParts.some(function(part) { return part.length>63; }))
return false;
return true;
} | 'use strict';
var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
// Thanks to:
// http://fightingforalostcause.net/misc/2006/compare-email-regex.php
// http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx
// http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378
exports.validate = function (email) {
if (!email) return false;
if (email.length > 256) return false;
if (!tester.test(email)) return false;
// Further checking of some things regex can't handle
var [account, address] = email.split('@');
if (account.length > 64) return false;
var domainParts = address.split('.');
if (domainParts.some(function (part) {
return part.length > 63;
})) return false;
return true;
};
| Apply total length of RFC-2821 | Apply total length of RFC-2821
| JavaScript | unlicense | Sembiance/email-validator | ---
+++
@@ -1,30 +1,25 @@
-"use strict";
+'use strict';
var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
// Thanks to:
// http://fightingforalostcause.net/misc/2006/compare-email-regex.php
// http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx
// http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378
-exports.validate = function(email)
-{
- if (!email)
- return false;
-
- if(email.length>254)
- return false;
+exports.validate = function (email) {
+ if (!email) return false;
- var valid = tester.test(email);
- if(!valid)
- return false;
+ if (email.length > 256) return false;
- // Further checking of some things regex can't handle
- var parts = email.split("@");
- if(parts[0].length>64)
- return false;
+ if (!tester.test(email)) return false;
- var domainParts = parts[1].split(".");
- if(domainParts.some(function(part) { return part.length>63; }))
- return false;
+ // Further checking of some things regex can't handle
+ var [account, address] = email.split('@');
+ if (account.length > 64) return false;
- return true;
-}
+ var domainParts = address.split('.');
+ if (domainParts.some(function (part) {
+ return part.length > 63;
+ })) return false;
+
+ return true;
+}; |
9a34051841343f41ce56122ceaf7fd9ce785281c | index.js | index.js | var Database = require('./lib/database')
var mongodb = require('mongodb')
module.exports = function (connString, cols, options) {
var db = new Database(connString, cols, options)
if (typeof Proxy !== 'undefined') {
var handler = {
get: function (obj, prop) {
// Work around for event emitters to work together with harmony proxy
if (prop === 'on' || prop === 'emit') {
return db[prop].bind(db)
}
if (db[prop]) return db[prop]
db[prop] = db.collection(prop)
return db[prop]
}
}
var p = Proxy.create === undefined ? new Proxy({}, handler) : Proxy.create(handler)
return p
}
return db
}
// expose bson stuff visible in the shell
module.exports.Binary = mongodb.Binary
module.exports.Code = mongodb.Code
module.exports.DBRef = mongodb.DBRef
module.exports.Double = mongodb.Double
module.exports.Long = mongodb.Long
module.exports.NumberLong = mongodb.Long // Alias for shell compatibility
module.exports.MinKey = mongodb.MinKey
module.exports.MaxKey = mongodb.MaxKey
module.exports.ObjectID = mongodb.ObjectID
module.exports.ObjectId = mongodb.ObjectId
module.exports.Symbol = mongodb.Symbol
module.exports.Timestamp = mongodb.Timestamp
| var Database = require('./lib/database')
var mongodb = require('mongodb')
module.exports = function (connString, cols, options) {
var db = new Database(connString, cols, options)
if (typeof Proxy !== 'undefined') {
var handler = {
get: function (obj, prop) {
// Work around for event emitters to work together with harmony proxy
if (prop === 'on' || prop === 'emit') {
return db[prop].bind(db)
}
if (db[prop]) return db[prop]
db[prop] = db.collection(prop)
return db[prop]
}
}
return Proxy.create === undefined ? new Proxy({}, handler) : Proxy.create(handler)
}
return db
}
// expose bson stuff visible in the shell
module.exports.Binary = mongodb.Binary
module.exports.Code = mongodb.Code
module.exports.DBRef = mongodb.DBRef
module.exports.Double = mongodb.Double
module.exports.Long = mongodb.Long
module.exports.NumberLong = mongodb.Long // Alias for shell compatibility
module.exports.MinKey = mongodb.MinKey
module.exports.MaxKey = mongodb.MaxKey
module.exports.ObjectID = mongodb.ObjectID
module.exports.ObjectId = mongodb.ObjectId
module.exports.Symbol = mongodb.Symbol
module.exports.Timestamp = mongodb.Timestamp
| Return the created proxy instead of assigning it to a var p | Return the created proxy instead of assigning it to a var p
| JavaScript | mit | mafintosh/mongojs,lionvs/mongojs | ---
+++
@@ -16,8 +16,8 @@
return db[prop]
}
}
- var p = Proxy.create === undefined ? new Proxy({}, handler) : Proxy.create(handler)
- return p
+
+ return Proxy.create === undefined ? new Proxy({}, handler) : Proxy.create(handler)
}
return db |
e6458ee26f18fa1f87601297d595ea7e2aa6e81d | index.js | index.js | "use strict";
var windows = process.platform.indexOf("win") === 0;
function clear()
{
var i,lines;
var stdout = "";
if (windows === false)
{
stdout += "\033[2J";
}
else
{
lines = process.stdout.getWindowSize()[1];
for (i=0; i<lines; i++)
{
stdout += "\r\n";
}
}
// Reset cursur
stdout += "\033[0f";
process.stdout.write(stdout);
}
module.exports = clear;
| "use strict";
var windows = process.platform.indexOf("win") === 0;
function clear()
{
var i,lines;
var stdout = "";
if (windows === false)
{
stdout += "\x1B[2J";
}
else
{
lines = process.stdout.getWindowSize()[1];
for (i=0; i<lines; i++)
{
stdout += "\r\n";
}
}
// Reset cursur
stdout += "\x1B[0f";
process.stdout.write(stdout);
}
module.exports = clear;
| Update octal literal to hex | Update octal literal to hex
Strict mode in later versions of node caused programs that use this to crash due to the octal literal with
```
diffie-hellman-explained/node_modules/cli-clear/index.js:26
stdout += "\033[0f";
^^
SyntaxError: Octal literals are not allowed in strict mode.
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/a2sl1zz/git/diffie-hellman-explained/tutorial.js:2:13)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
```
This converts it to hex.
| JavaScript | mit | stevenvachon/cli-clear | ---
+++
@@ -10,7 +10,7 @@
if (windows === false)
{
- stdout += "\033[2J";
+ stdout += "\x1B[2J";
}
else
{
@@ -23,7 +23,7 @@
}
// Reset cursur
- stdout += "\033[0f";
+ stdout += "\x1B[0f";
process.stdout.write(stdout);
} |
1b8041a62976420705a942c91d47195472d89798 | index.js | index.js | 'use strict';
var condenseKeys = require('condense-keys');
var got = require('got');
module.exports = function (buf, cb) {
got.post('https://api.imgur.com/3/image', {
headers: {authorization: 'Client-ID 34b90e75ab1c04b'},
body: buf
}, function (err, res) {
if (err) {
cb(err);
return;
}
res = JSON.parse(res);
res = condenseKeys(res.data);
res.date = new Date(res.datetime * 1000);
delete res.datetime;
cb(null, res);
});
};
| 'use strict';
var condenseKeys = require('condense-keys');
var got = require('got');
module.exports = function (buf, cb) {
got.post('https://api.imgur.com/3/image', {
json: true,
headers: {authorization: 'Client-ID 34b90e75ab1c04b'},
body: buf
}, function (err, res) {
if (err) {
cb(err);
return;
}
res = condenseKeys(res.data);
res.date = new Date(res.datetime * 1000);
delete res.datetime;
cb(null, res);
});
};
| Use `json` option in `got` | Use `json` option in `got`
| JavaScript | mit | kevva/imgur-uploader | ---
+++
@@ -4,6 +4,7 @@
module.exports = function (buf, cb) {
got.post('https://api.imgur.com/3/image', {
+ json: true,
headers: {authorization: 'Client-ID 34b90e75ab1c04b'},
body: buf
}, function (err, res) {
@@ -12,7 +13,6 @@
return;
}
- res = JSON.parse(res);
res = condenseKeys(res.data);
res.date = new Date(res.datetime * 1000);
|
ed3597688b01f666ec716108bf7c348338ef14af | index.js | index.js | 'use strict'
var detect = require('acorn-globals');
var lastSRC = '(null)';
var lastRes = true;
var lastConstants = undefined;
module.exports = isConstant;
function isConstant(src, constants) {
src = '(' + src + ')';
if (lastSRC === src && lastConstants === constants) return lastRes;
lastSRC = src;
lastConstants = constants;
try {
Function('return (' + src + ')');
return lastRes = (detect(src).filter(function (key) {
return !constants || !(key.name in constants);
}).length === 0);
} catch (ex) {
return lastRes = false;
}
}
isConstant.isConstant = isConstant;
isConstant.toConstant = toConstant;
function toConstant(src, constants) {
if (!isConstant(src, constants)) throw new Error(JSON.stringify(src) + ' is not constant.');
return Function(Object.keys(constants || {}).join(','), 'return (' + src + ')').apply(null, Object.keys(constants || {}).map(function (key) {
return constants[key];
}));
}
| 'use strict'
var detect = require('acorn-globals');
var lastSRC = '(null)';
var lastRes = true;
var lastConstants = undefined;
module.exports = isConstant;
function isConstant(src, constants) {
src = '(' + src + ')';
if (lastSRC === src && lastConstants === constants) return lastRes;
lastSRC = src;
lastConstants = constants;
try {
isExpression(src);
return lastRes = (detect(src).filter(function (key) {
return !constants || !(key.name in constants);
}).length === 0);
} catch (ex) {
return lastRes = false;
}
}
isConstant.isConstant = isConstant;
isConstant.toConstant = toConstant;
function toConstant(src, constants) {
if (!isConstant(src, constants)) throw new Error(JSON.stringify(src) + ' is not constant.');
return Function(Object.keys(constants || {}).join(','), 'return (' + src + ')').apply(null, Object.keys(constants || {}).map(function (key) {
return constants[key];
}));
}
function isExpression(src) {
try {
eval('throw "STOP"; (function () { return (' + src + '); })()');
return false;
}
catch (err) {
return err === 'STOP';
}
}
| Use a safer test for isExpression | Use a safer test for isExpression
It is now safe to use `isConstant` on un-trusted input, but it is still
not safe to use `toConstant` on un-trusted input.
| JavaScript | mit | ForbesLindesay/constantinople | ---
+++
@@ -13,7 +13,7 @@
lastSRC = src;
lastConstants = constants;
try {
- Function('return (' + src + ')');
+ isExpression(src);
return lastRes = (detect(src).filter(function (key) {
return !constants || !(key.name in constants);
}).length === 0);
@@ -30,3 +30,13 @@
return constants[key];
}));
}
+
+function isExpression(src) {
+ try {
+ eval('throw "STOP"; (function () { return (' + src + '); })()');
+ return false;
+ }
+ catch (err) {
+ return err === 'STOP';
+ }
+} |
2cb1550e0783bbf4a4cbc63a40fc07dd7cc73bb9 | index.js | index.js | var digio_api = require('../digio-api')
, config = require('./config')
var api = new digio_api(config.token)
// api.droplets.list_droplets(function (err, data) {
// console.log(data);
// });
//
// api.domains.list_all_domains(function (err, data) {
// console.log(data);
// })
//
// api.domains.create_domain_record('tmn2.io', '191.168.0.1', function (err, data) {
// console.log(data);
// })
| var digio_api = require('../digio-api')
, config = require('./config')
var api = new digio_api(config.token)
// api.droplets.list_droplets(function (err, data) {
// console.log(data);
// });
//
// api.domains.list(function (err, data) {
// console.log(data);
// })
//
// api.domains.create('tmn2.io', '191.168.0.1', function (err, data) {
// console.log(data);
// })
//
// api.domains.get('tmn.io', function (err, data) {
// console.log(data);
// })
| Add calls to domains get functionality | Add calls to domains get functionality
| JavaScript | mit | tmn/digio-api-test | ---
+++
@@ -8,10 +8,14 @@
// console.log(data);
// });
//
-// api.domains.list_all_domains(function (err, data) {
+// api.domains.list(function (err, data) {
// console.log(data);
// })
//
-// api.domains.create_domain_record('tmn2.io', '191.168.0.1', function (err, data) {
+// api.domains.create('tmn2.io', '191.168.0.1', function (err, data) {
// console.log(data);
// })
+//
+// api.domains.get('tmn.io', function (err, data) {
+// console.log(data);
+// }) |
340fc24f9a88ef82c22d7670805900cbd6e12592 | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-moment-range',
included: function () {
this._super.included.apply(this, arguments);
this.import('bower_components/moment-range/dist/moment-range.min.js');
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-moment-range',
included: function (app) {
this._super.included.apply(this, arguments);
while (app.app) {
app = app.app;
}
this.import(app.bowerDirectory + '/moment-range/dist/moment-range.min.js');
}
};
| Add safeguard for nested addons && fix import path | Add safeguard for nested addons && fix import path
| JavaScript | mit | hankfanchiu/ember-cli-moment-range,hankfanchiu/ember-cli-moment-range | ---
+++
@@ -4,9 +4,13 @@
module.exports = {
name: 'ember-cli-moment-range',
- included: function () {
+ included: function (app) {
this._super.included.apply(this, arguments);
- this.import('bower_components/moment-range/dist/moment-range.min.js');
+ while (app.app) {
+ app = app.app;
+ }
+
+ this.import(app.bowerDirectory + '/moment-range/dist/moment-range.min.js');
}
}; |
b7ab57293fe36f13d1a09aa1eabab16ace9ac204 | index.js | index.js | export default class {
constructor (win, keys) {
this.keys = keys
this.win = win
this.id = 'keypad'
this.buttons = []
for (var key in this.keys) {
this.buttons[this.keys[key]] = {pressed: false}
}
this.onkey = function (event) {
if (event.which in this.keys) {
let pressed
if (event.type === 'keyup') {
pressed = true
} else if (event.type === 'keydown') {
pressed = false
}
this.buttons[this.keys[event.which]].pressed = pressed
this.timestamp = event.timeStamp
event.preventDefault()
}
}.bind(this)
this.connect()
}
connect () {
this.connected = true
this.win.addEventListener('keydown', this.onkey)
this.win.addEventListener('keyup', this.onkey)
}
disconnect () {
this.connected = false
this.win.removeEventListener('keydown', this.onkey)
this.win.removeEventListener('keyup', this.onkey)
}
}
| export default class {
constructor (win, keys) {
this.keys = keys
this.win = win
this.id = 'keypad'
this.mapping = 'standard'
this.buttons = []
for (var key in this.keys) {
this.buttons[this.keys[key]] = {pressed: false}
}
this.onkey = function (event) {
if (event.which in this.keys) {
let pressed
if (event.type === 'keyup') {
pressed = true
} else if (event.type === 'keydown') {
pressed = false
}
this.buttons[this.keys[event.which]].pressed = pressed
this.timestamp = event.timeStamp
event.preventDefault()
}
}.bind(this)
this.connect()
}
connect () {
this.connected = true
this.win.addEventListener('keydown', this.onkey)
this.win.addEventListener('keyup', this.onkey)
}
disconnect () {
this.connected = false
this.win.removeEventListener('keydown', this.onkey)
this.win.removeEventListener('keyup', this.onkey)
}
}
| Set mapping to standard for gamepad object. | Set mapping to standard for gamepad object.
| JavaScript | mit | matthewbauer/keypad,matthewbauer/keypad | ---
+++
@@ -3,6 +3,7 @@
this.keys = keys
this.win = win
this.id = 'keypad'
+ this.mapping = 'standard'
this.buttons = []
for (var key in this.keys) { |
b3eae797efde9cb483ce45b340795799ed1faaf9 | index.js | index.js | module.exports = isbnValidator;
function isbnValidator(isbnCode){
var self = this;
if (typeof(isbnCode) !== "string") return false;
self.replaceDashes = function format(sequence){
return sequence.replace(/\-/g, '');
}
self.sumOfSequence = function hasRemainder(sequence){
var numberTenInISBN = "X";
var sum = 0;
var factor = 10;
var characterIndex = 0;
var isValid = undefined;
var sequenceEnd = sequence.length - 1;
for(; factor > 0; factor--, characterIndex++){
if (characterIndex === sequenceEnd &&
sequence.charAt(characterIndex) === numberTenInISBN){
sum += 10 * factor;
} else {
sum += sequence.charAt(characterIndex) * factor;
}
}
return sum;
};
self.isCorrectLength = function correctFormat(isbn){
return (isbn.length === 10) ? true : false;
};
self.validate = function validate(sequence){
var isValid = (sumOfSequence(sequence) % 11 === 0) ? true : false;
return isValid;
}
self.isbn = self.replaceDashes(isbnCode);
if(self.isCorrectLength(self.isbn)) {
return self.validate((self.isbn));
} else {
return false;
}
};
| module.exports = isbnValidator;
function isbnValidator(isbnCode){
var self = this;
if (typeof(isbnCode) !== "string") return false;
self.replaceDashes = function format(sequence){
return sequence.replace(/\-/g, '');
}
self.sumOfSequence = function hasRemainder(sequence){
var numberTenInISBN = "X";
var sum = 0;
var factor = 10;
var characterIndex = 0;
var isValid = undefined;
var sequenceEnd = sequence.length - 1;
for(; factor > 0; factor--, characterIndex++){
if (characterIndex === sequenceEnd &&
sequence.charAt(characterIndex) === numberTenInISBN){
sum += 10 * factor;
} else {
sum += sequence.charAt(characterIndex) * factor;
}
}
return sum;
};
self.isCorrectFormat = function correctFormat(isbn){
return isbn.match(/\d\d\d\d\d\d\d\d\d[0-9|xX]$/);
};
self.validate = function validate(sequence){
var isValid = (sumOfSequence(sequence) % 11 === 0) ? true : false;
return isValid;
}
self.isbn = self.replaceDashes(isbnCode);
if(self.isCorrectFormat(self.isbn)) {
return self.validate((self.isbn));
} else {
return false;
}
};
| Use regex search for format type | Use regex search for format type
| JavaScript | mit | thewazir/isbn-validator | ---
+++
@@ -29,8 +29,8 @@
return sum;
};
- self.isCorrectLength = function correctFormat(isbn){
- return (isbn.length === 10) ? true : false;
+ self.isCorrectFormat = function correctFormat(isbn){
+ return isbn.match(/\d\d\d\d\d\d\d\d\d[0-9|xX]$/);
};
self.validate = function validate(sequence){
@@ -40,7 +40,7 @@
self.isbn = self.replaceDashes(isbnCode);
- if(self.isCorrectLength(self.isbn)) {
+ if(self.isCorrectFormat(self.isbn)) {
return self.validate((self.isbn));
} else {
return false; |
b1915009d392fd29419462b26afa5d45eb5563cc | index.js | index.js | /*!
* global-prefix <https://github.com/jonschlinkert/global-prefix>
*
* Copyright (c) 2015 Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
/**
* This is the code used internally by npm to
* resolve the global prefix.
*/
var isWindows = require('is-windows');
var path = require('path');
var prefix;
if (process.env.PREFIX) {
prefix = process.env.PREFIX;
} else if (isWindows()) {
// c:\node\node.exe --> prefix=c:\node\
prefix = path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
}
module.exports = prefix;
| /*!
* global-prefix <https://github.com/jonschlinkert/global-prefix>
*
* Copyright (c) 2015 Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
/**
* This is the code used internally by npm to
* resolve the global prefix.
*/
var isWindows = require('is-windows');
var path = require('path');
var prefix;
if (process.env.PREFIX) {
prefix = process.env.PREFIX;
} else if (isWindows === true || isWindows()) {
// c:\node\node.exe --> prefix=c:\node\
prefix = path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
}
module.exports = prefix;
| Fix "isWindows is not a function" on electron | Fix "isWindows is not a function" on electron
Fix "isWindows is not a function" on electron | JavaScript | mit | kuksikus/global-prefix,jonschlinkert/global-prefix | ---
+++
@@ -18,7 +18,7 @@
if (process.env.PREFIX) {
prefix = process.env.PREFIX;
-} else if (isWindows()) {
+} else if (isWindows === true || isWindows()) {
// c:\node\node.exe --> prefix=c:\node\
prefix = path.dirname(process.execPath);
} else { |
399deb8c1741ca993179387c6944e502cac9d4f7 | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-l10n',
included: function(app) {
// @see: https://github.com/ember-cli/ember-cli/issues/3718
this._super.included.apply(this, arguments);
if (typeof app.import!=='function' && app.app) {
app = app.app;
}
app.import('bower_components/gettext.js/dist/gettext.min.js',{
exports: {
'get-text': [
'default'
]
}
});
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-l10n',
isDevelopingAddon: function() {
// @see: https://ember-cli.com/extending/#link-to-addon-while-developing
return true;
},
included: function(app) {
// @see: https://github.com/ember-cli/ember-cli/issues/3718
this._super.included.apply(this, arguments);
if (typeof app.import!=='function' && app.app) {
app = app.app;
}
app.import('bower_components/gettext.js/dist/gettext.min.js',{
exports: {
'get-text': [
'default'
]
}
});
}
};
| Add development mode for live-reload on develop | Add development mode for live-reload on develop
| JavaScript | mit | Cropster/ember-l10n,Cropster/ember-l10n,Cropster/ember-l10n | ---
+++
@@ -3,6 +3,11 @@
module.exports = {
name: 'ember-l10n',
+
+ isDevelopingAddon: function() {
+ // @see: https://ember-cli.com/extending/#link-to-addon-while-developing
+ return true;
+ },
included: function(app) {
// @see: https://github.com/ember-cli/ember-cli/issues/3718 |
6065a6c41dc182f6b915a61eeb8a6a271cfe0d17 | index.js | index.js | /**
* index.js
* Client entry point.
*
* @author Francis Brito <fr.br94@gmail.com>
* @license MIT
*/
'use strict';
/**
* Client
* Provides methods to access PrintHouse's API.
*
* @param {String} apiKey API key identifying account owner.
* @param {Object} opts Contains options to be passed to the client
*/
var Client = function Client(apiKey, opts) {
opts = opts || {};
if (!apiKey) {
throw new Error('No API key provided.');
}
this._apiUrl = opts.apiUrl || Client.DEFAULT_API_URL;
};
/**
* Default API endpoint.
* Used if no API endpoint is passed in opts parameter when constructing a client.
*
* @type {String}
*/
Client.DEFAULT_API_URL = 'http://printhouse.io/api';
module.exports = {
Client: Client
};
| /**
* index.js
* Client entry point.
*
* @author Francis Brito <fr.br94@gmail.com>
* @license MIT
*/
'use strict';
/**
* Client
* Provides methods to access PrintHouse's API.
*
* @param {String} apiKey API key identifying account owner.
* @param {Object} opts Contains options to be passed to the client
*/
var Client = function Client(apiKey, opts) {
opts = opts || {};
if (!apiKey) {
throw new Error('No API key provided.');
}
this._apiUrl = opts.apiUrl || Client.DEFAULT_API_URL;
};
/**
* Default API endpoint.
* Used if no API endpoint is passed in opts parameter when constructing a client.
*
* @type {String}
*/
Client.DEFAULT_API_URL = 'http://printhouse.io/api';
/**
* Default API version.
* Used if no API version is passed in opts parameter when constructing a client.
*
* @type {String}
*/
Client.DEFAULT_API_VERSION = 1;
module.exports = {
Client: Client
};
| Add default API version to client. | Add default API version to client.
| JavaScript | mit | francisbrito/ph-node | ---
+++
@@ -32,6 +32,14 @@
*/
Client.DEFAULT_API_URL = 'http://printhouse.io/api';
+/**
+ * Default API version.
+ * Used if no API version is passed in opts parameter when constructing a client.
+ *
+ * @type {String}
+ */
+Client.DEFAULT_API_VERSION = 1;
+
module.exports = {
Client: Client
}; |
fb32c704b149f0bd134144bc58f8ed9a07d79758 | index.js | index.js | /* @flow */
type GiftCategory =
'Electronics' |
'Games' |
'Home Decoration';
type GiftWish = string | Array<GiftCategory>;
type User = {
firstName: string,
lastName?: string,
giftWish?: GiftWish,
};
export type Selection = {
giver: User,
receiver: User,
};
const selectSecretSanta = (
users: Array<User>,
// TODO: Think of adding restrictions as a parameter, such as:
// - User X cannot give to User Y
// - User A must give to User B
): Array<Selection> => {
const givers = [...users];
return users.map((receiver) => {
// Possible givers only for this receiver (receiver cannot be his own giver)
const receiverGivers = givers.filter(g => g !== receiver);
const giver = receiverGiver[
Math.floor(Math.random() * receiverGiver.length)
];
// Take the selected giver out of the givers array
givers.splice(givers.findIndex(g => g === giver), 1);
return {
giver,
receiver,
};
});
};
export default selectSecretSanta;
| /* @flow */
type GiftCategory =
'Electronics' |
'Games' |
'Home Decoration';
type GiftWish = string | Array<GiftCategory>;
type User = {
firstName: string,
lastName?: string,
giftWish?: GiftWish,
};
export type Selection = {
giver: User,
receiver: User,
};
const selectSecretSanta = (
users: Array<User>,
// TODO: Think of adding restrictions as a parameter, such as:
// - User X cannot give to User Y
// - User A must give to User B
// - User N only receives, doesn't give
): Array<Selection> => {
const givers = [...users];
return users.map((receiver) => {
// Possible givers only for this receiver (receiver cannot be his own giver)
const receiverGivers = givers.filter(g => g !== receiver);
const giver = receiverGivers[
Math.floor(Math.random() * receiverGivers.length)
];
// Take the selected giver out of the givers array
givers.splice(givers.findIndex(g => g === giver), 1);
return {
giver,
receiver,
};
});
};
export default selectSecretSanta;
| Fix variable name, add comment | Fix variable name, add comment
| JavaScript | mit | WhosMySanta/app,WhosMySanta/app,WhosMySanta/whosmysanta | ---
+++
@@ -23,6 +23,7 @@
// TODO: Think of adding restrictions as a parameter, such as:
// - User X cannot give to User Y
// - User A must give to User B
+ // - User N only receives, doesn't give
): Array<Selection> => {
const givers = [...users];
@@ -30,8 +31,8 @@
// Possible givers only for this receiver (receiver cannot be his own giver)
const receiverGivers = givers.filter(g => g !== receiver);
- const giver = receiverGiver[
- Math.floor(Math.random() * receiverGiver.length)
+ const giver = receiverGivers[
+ Math.floor(Math.random() * receiverGivers.length)
];
// Take the selected giver out of the givers array |
0f4102735bd5ca3cc09815e6b3c543a1b76829da | index.js | index.js | var fs = require('fs');
module.exports = function (repl, file) {
try {
var stat = fs.statSync(file);
repl.rli.history = fs.readFileSync(file, 'utf-8').split('\n').reverse();
repl.rli.history.shift();
repl.rli.historyIndex = 0;
} catch (e) {}
var fd = fs.openSync(file, 'a'), reval = repl.eval;
repl.rli.addListener('line', function(code) {
if (code && code !== '.history') {
fs.write(fd, code + '\n');
} else {
repl.rli.historyIndex++;
repl.rli.history.pop();
}
});
process.on('exit', function() {
fs.closeSync(fd);
});
repl.commands['.history'] = {
help : 'Show the history',
action : function() {
var out = [];
repl.rli.history.forEach(function(v, k) {
out.push(v);
});
repl.outputStream.write(out.reverse().join('\n') + '\n');
repl.displayPrompt();
}
};
}; | var fs = require('fs');
module.exports = function (repl, file) {
try {
var stat = fs.statSync(file);
repl.rli.history = fs.readFileSync(file, 'utf-8').split('\n').reverse();
repl.rli.history.shift();
repl.rli.historyIndex = -1; // will be incremented before pop
} catch (e) {}
var fd = fs.openSync(file, 'a'), reval = repl.eval;
repl.rli.addListener('line', function(code) {
if (code && code !== '.history') {
fs.write(fd, code + '\n');
} else {
repl.rli.historyIndex++;
repl.rli.history.pop();
}
});
process.on('exit', function() {
fs.closeSync(fd);
});
repl.commands['.history'] = {
help : 'Show the history',
action : function() {
var out = [];
repl.rli.history.forEach(function(v, k) {
out.push(v);
});
repl.outputStream.write(out.reverse().join('\n') + '\n');
repl.displayPrompt();
}
};
};
| Fix historyIndex to actually get the last command on key-up | Fix historyIndex to actually get the last command on key-up
| JavaScript | mit | tmpvar/repl.history,eush77/repl.history | ---
+++
@@ -5,11 +5,11 @@
var stat = fs.statSync(file);
repl.rli.history = fs.readFileSync(file, 'utf-8').split('\n').reverse();
repl.rli.history.shift();
- repl.rli.historyIndex = 0;
+ repl.rli.historyIndex = -1; // will be incremented before pop
} catch (e) {}
var fd = fs.openSync(file, 'a'), reval = repl.eval;
-
+
repl.rli.addListener('line', function(code) {
if (code && code !== '.history') {
fs.write(fd, code + '\n'); |
e66b0ec7d644a566b9aca31ec10469d64a596eda | index.js | index.js | /* Copyright 2013 Twitter, Inc. Licensed under The MIT License. http://opensource.org/licenses/MIT */
define(
[
'./lib/advice',
'./lib/component',
'./lib/compose',
'./lib/logger',
'./lib/registry',
'./lib/utils'
],
function(advice, component, compose, logger, registry, utils) {
'use strict';
return {
advice: advice,
component: component,
compose: compose,
logger: logger,
registry: registry,
utils: utils
};
}
);
| /* Copyright 2013 Twitter, Inc. Licensed under The MIT License. http://opensource.org/licenses/MIT */
define(
[
'./lib/advice',
'./lib/component',
'./lib/compose',
'./lib/debug',
'./lib/logger',
'./lib/registry',
'./lib/utils'
],
function(advice, component, compose, debug, logger, registry, utils) {
'use strict';
return {
advice: advice,
component: component,
compose: compose,
debug: debug,
logger: logger,
registry: registry,
utils: utils
};
}
);
| Add the debug module to the entry file | Add the debug module to the entry file
| JavaScript | mit | giuseppeg/flight,david84/flight,joelbyler/flight,Shinchy/flight,icecreamliker/flight,joelbyler/flight,icecreamliker/flight,robertknight/flight,KyawNaingTun/flight,margaritis/flight,robertknight/flight,flightjs/flight,Shinchy/flight,KyawNaingTun/flight,flightjs/flight,david84/flight | ---
+++
@@ -6,18 +6,20 @@
'./lib/advice',
'./lib/component',
'./lib/compose',
+ './lib/debug',
'./lib/logger',
'./lib/registry',
'./lib/utils'
],
- function(advice, component, compose, logger, registry, utils) {
+ function(advice, component, compose, debug, logger, registry, utils) {
'use strict';
return {
advice: advice,
component: component,
compose: compose,
+ debug: debug,
logger: logger,
registry: registry,
utils: utils |
85c06f64cdb2a7934177a812bd514e3bcc267c49 | index.js | index.js | /**
* Generates a new {@link Point} feature, given coordinates
* and, optionally, properties.
*
* @module turf/point
* @param {number} longitude - position west to east in decimal degrees
* @param {number} latitude - position south to north in decimal degrees
* @param {Object} properties
* @return {Point} output
* @example
* var pt1 = turf.point(-75.343, 39.984)
*/
module.exports = function(x, y, properties){
if(x instanceof Array) {
properties = y;
y = x[1];
x = x[0];
} else if(isNaN(x) || isNaN(y)) throw new Error('Invalid coordinates')
return {
type: "Feature",
geometry: {
type: "Point",
coordinates: [x, y]
},
properties: properties || {}
};
}
| /**
* Generates a new {@link Point} feature, given coordinates
* and, optionally, properties.
*
* @module turf/point
* @param {number} longitude - position west to east in decimal degrees
* @param {number} latitude - position south to north in decimal degrees
* @param {Object} properties
* @return {Point} output
* @example
* var pt1 = turf.point(-75.343, 39.984);
* //=pt1
*/
module.exports = function(x, y, properties){
if(x instanceof Array) {
properties = y;
y = x[1];
x = x[0];
} else if(isNaN(x) || isNaN(y)) throw new Error('Invalid coordinates')
return {
type: "Feature",
geometry: {
type: "Point",
coordinates: [x, y]
},
properties: properties || {}
};
}
| Make example work with rpl | Make example work with rpl
| JavaScript | mit | Turfjs/turf-point | ---
+++
@@ -8,7 +8,8 @@
* @param {Object} properties
* @return {Point} output
* @example
- * var pt1 = turf.point(-75.343, 39.984)
+ * var pt1 = turf.point(-75.343, 39.984);
+ * //=pt1
*/
module.exports = function(x, y, properties){
if(x instanceof Array) { |
c56834a5822af1821299d868173b748ea3989544 | index.js | index.js | var elixir = require('laravel-elixir');
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var notify = require('gulp-notify');
var _ = require('underscore');
var utilities = require('laravel-elixir/ingredients/commands/Utilities');
/*
|----------------------------------------------------------------
| ImageMin Processor
|----------------------------------------------------------------
|
| This task will trigger your images to be processed using
| imagemin processor.
|
| Minify PNG, JPEG, GIF and SVG images
|
*/
elixir.extend('imagemin', function(src, output, options) {
var config = this;
var baseDir = config.assetsDir + 'img';
src = utilities.buildGulpSrc(src, baseDir, '**/*');
options = _.extend({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}, options);
gulp.task('imagemin', function() {
return gulp.src(src)
.pipe(imagemin(options))
.pipe(gulp.dest(output || 'public/img'))
.pipe(notify({
title: 'ImageMin Complete!',
message: 'All images have be optimised.',
icon: __dirname + '/../laravel-elixir/icons/pass.png'
}));
});
this.registerWatcher('imagemin', [
baseDir + '/**/*.png',
baseDir + '/**/*.gif',
baseDir + '/**/*.svg',
baseDir + '/**/*.jpg',
baseDir + '/**/*.jpeg'
]);
return this.queueTask('imagemin');
});
| var elixir = require('laravel-elixir');
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var notify = require('gulp-notify');
var _ = require('underscore');
var utilities = require('laravel-elixir/ingredients/commands/Utilities');
/*
|----------------------------------------------------------------
| ImageMin Processor
|----------------------------------------------------------------
|
| This task will trigger your images to be processed using
| imagemin processor.
|
| Minify PNG, JPEG, GIF and SVG images
|
*/
elixir.extend('imagemin', function(src, output, options) {
var config = this;
var baseDir = config.assetsDir + 'img';
src = utilities.buildGulpSrc(src, baseDir, '**/*');
options = _.extend({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}, options);
gulp.task('imagemin', function() {
return gulp.src(src)
.pipe(imagemin(options))
.pipe(gulp.dest(output || 'public/img'))
.on('error', notify.onError({
title: 'ImageMin Failed!',
message: 'Failed to optimise images.',
icon: __dirname + '/../laravel-elixir/icons/fail.png'
}));
});
this.registerWatcher('imagemin', [
baseDir + '/**/*.png',
baseDir + '/**/*.gif',
baseDir + '/**/*.svg',
baseDir + '/**/*.jpg',
baseDir + '/**/*.jpeg'
]);
return this.queueTask('imagemin');
});
| Remove success message, only show error message. | Remove success message, only show error message. | JavaScript | mit | nathanmac/laravel-elixir-imagemin,waldemarfm/laravel-elixir-imagemin | ---
+++
@@ -36,10 +36,10 @@
return gulp.src(src)
.pipe(imagemin(options))
.pipe(gulp.dest(output || 'public/img'))
- .pipe(notify({
- title: 'ImageMin Complete!',
- message: 'All images have be optimised.',
- icon: __dirname + '/../laravel-elixir/icons/pass.png'
+ .on('error', notify.onError({
+ title: 'ImageMin Failed!',
+ message: 'Failed to optimise images.',
+ icon: __dirname + '/../laravel-elixir/icons/fail.png'
}));
});
|
6a391ec9dc6a9fe2a34a67fc65f1e07c88790de6 | app/http.js | app/http.js | var express = require('express');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
function appCtor(cfg, pool) {
var app = express();
app.set('trust proxy', true);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(serveStatic(__dirname + '/static'));
app.use(session({
store: new RedisStore({
host: cfg.redis.hostname,
port: cfg.redis.port}),
secret: cfg.env.SECRET_KEY_BASE,
resave: false,
saveUninitialized: false
}));
app.use(function (req, res, next) {
if (!req.session) {
return next(new Error("couldn't find sessions"));
}
else return next();
});
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req, res) {
return res.render('index');
});
app.get('/m', function(req, res) {
return res.render('messaging');
});
return app;
}
| var express = require('express');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
function appCtor(cfg, pool) {
var app = express();
app.set('trust proxy', true);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(serveStatic(__dirname + '/static'));
app.use(session({
store: new RedisStore({
host: cfg.redis.hostname,
port: cfg.redis.port}),
secret: cfg.env.SECRET_KEY_BASE,
resave: false,
saveUninitialized: false
}));
app.use(function (req, res, next) {
if (!req.session) {
return next(new Error("couldn't find sessions"));
}
else return next();
});
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req, res) {
return res.render('index');
});
app.get('/m', function(req, res) {
return res.render('messaging');
});
return app;
}
module.exports = appCtor;
| Fix app constructor not being exported | Fix app constructor not being exported
| JavaScript | mit | dingroll/dingroll.com,dingroll/dingroll.com | ---
+++
@@ -36,3 +36,5 @@
return app;
}
+
+module.exports = appCtor; |
c21f621b2f0ca63bef1ca210e85a8f0d4b8a572b | fan/tasks/views/TaskItemView.js | fan/tasks/views/TaskItemView.js | jsio('from shared.javascript import Class')
jsio('import fan.ui.Button')
jsio('import fan.ui.RadioButtons')
jsio('import fan.tasks.views.View')
exports = Class(fan.tasks.views.View, function(supr) {
this._className += ' TaskItemView'
this._minWidth = 370
this._maxWidth = 740
this.init = function(itemId) {
supr(this, 'init')
this._itemId = itemId
}
this._buildHeader = function() {
new fan.ui.RadioButtons()
.addTextButton('Normal', 'normal')
.addTextButton('Crucial', 'crucial')
.addTextButton('Backlog', 'backlog')
.addTextButton('Done', 'done')
.subscribe('Click', bind(this, '_toggleTaskState'))
.appendTo(this._header)
}
this._buildBody = function() {
gUtil.withTemplate('task', 'panel', bind(this, function(template) {
this._body.innerHTML = ''
this._body.appendChild(fin.applyTemplate(template, this._itemId))
}))
}
this._toggleTaskState = function(newState) {
console.log("TOGGLE STATE", newState)
}
}) | jsio('from shared.javascript import Class')
jsio('import fan.ui.Button')
jsio('import fan.ui.RadioButtons')
jsio('import fan.tasks.views.View')
exports = Class(fan.tasks.views.View, function(supr) {
this._className += ' TaskItemView'
this._minWidth = 390
this._maxWidth = 740
this.init = function(itemId) {
supr(this, 'init')
this._itemId = itemId
}
this._buildHeader = function() {
new fan.ui.RadioButtons()
.addTextButton('Normal', 'normal')
.addTextButton('Crucial', 'crucial')
.addTextButton('Backlog', 'backlog')
.addTextButton('Done', 'done')
.subscribe('Click', bind(this, '_toggleTaskState'))
.appendTo(this._header)
}
this._buildBody = function() {
gUtil.withTemplate('task', 'panel', bind(this, function(template) {
this._body.innerHTML = ''
this._body.appendChild(fin.applyTemplate(template, this._itemId))
}))
}
this._toggleTaskState = function(newState) {
console.log("TOGGLE STATE", newState)
}
}) | Make the minimum width of a task item view 20 pixels wider to fit the discussion view in there comfortably and not have horizontal scrollbars appear | Make the minimum width of a task item view 20 pixels wider to fit the discussion view in there comfortably and not have horizontal scrollbars appear
| JavaScript | mit | marcuswestin/Focus | ---
+++
@@ -6,7 +6,7 @@
exports = Class(fan.tasks.views.View, function(supr) {
this._className += ' TaskItemView'
- this._minWidth = 370
+ this._minWidth = 390
this._maxWidth = 740
this.init = function(itemId) { |
a26a5bf49f41ed034f96ea3498fc1bfdd22d9eae | Resources/public/scripts/master-slave-inputs.js | Resources/public/scripts/master-slave-inputs.js | $(document).ready(function () {
var showSlave = function ($master, showOn) {
if ($master.is(':checkbox')) {
return (+$master.is(':checked')).toString() === showOn;
}
var value = $master.val().toString();
if ($master.is('select') && $master.prop('multiple')) {
return value.indexOf(showOn) >= 0;
}
return value === showOn;
};
var toggleSlaveContainer = function ($slaveContainer, $master, showOn) {
$master.val() && showSlave($master, showOn) ? $slaveContainer.show() : $slaveContainer.hide();
};
$('.slave_input').each(function () {
var $slave = $(this);
var $slaveContainer = $slave.closest('.table_row');
var masterSelector = $slave.data('master');
var showOn = $slave.data('show-on').toString();
var $context = $slave.closest('[class*="_a2lix_translationsFields-"]');
var $master = $context.find(masterSelector).first();
if (!$master.length) {
$context = $slave.closest('form');
$master = $context.find(masterSelector).first();
}
toggleSlaveContainer($slaveContainer, $master, showOn);
$context.on('change', masterSelector, function () {
toggleSlaveContainer($slaveContainer, $(this), showOn);
});
});
});
| $(document).ready(function () {
var showSlave = function ($master, showOn) {
if ($master.is(':checkbox')) {
return (+$master.is(':checked')).toString() === showOn;
}
var value = $master.val().toString();
if ($master.is('select') && $master.prop('multiple')) {
return value.indexOf(showOn) >= 0;
}
return value === showOn;
};
var toggleSlaveContainer = function ($slaveContainer, $master, showOn) {
$master.val() && showSlave($master, showOn) ? $slaveContainer.show() : $slaveContainer.hide();
if ($slaveContainer.is('option')) {
$slaveContainer.closest('select').trigger('chosen:updated');
}
};
$('.slave_input').each(function () {
var $slave = $(this);
var $slaveContainer = $slave.is('option') ? $slave : $slave.closest('.table_row');
var masterSelector = $slave.data('master');
var showOn = $slave.data('show-on').toString();
var $context = $slave.closest('[class*="_a2lix_translationsFields-"]');
var $master = $context.find(masterSelector).first();
if (!$master.length) {
$context = $slave.closest('form');
$master = $context.find(masterSelector).first();
}
toggleSlaveContainer($slaveContainer, $master, showOn);
$context.on('change', masterSelector, function () {
toggleSlaveContainer($slaveContainer, $(this), showOn);
});
});
});
| Add slave option support to the master-slave inputs JS. | Add slave option support to the master-slave inputs JS.
| JavaScript | mit | DarvinStudio/DarvinAdminBundle,DarvinStudio/DarvinAdminBundle,DarvinStudio/DarvinAdminBundle | ---
+++
@@ -14,11 +14,17 @@
};
var toggleSlaveContainer = function ($slaveContainer, $master, showOn) {
$master.val() && showSlave($master, showOn) ? $slaveContainer.show() : $slaveContainer.hide();
+
+ if ($slaveContainer.is('option')) {
+ $slaveContainer.closest('select').trigger('chosen:updated');
+ }
};
$('.slave_input').each(function () {
var $slave = $(this);
- var $slaveContainer = $slave.closest('.table_row');
+
+ var $slaveContainer = $slave.is('option') ? $slave : $slave.closest('.table_row');
+
var masterSelector = $slave.data('master');
var showOn = $slave.data('show-on').toString();
|
d9817ae2aee7bbf7621cd967ea7b57b9ffda94d1 | app/javascript/mixins/mixin-responsive.js | app/javascript/mixins/mixin-responsive.js | export default {
data () {
return {
windowWidth: 0,
currentBreakpoint: '',
breakpoints: {
small: 767, // MUST MATCH VARIABLES IN assets/stylesheets/_settings
medium: 1024,
large: 1200
}
}
},
created () {
this.updateWindowSize()
// allow for multiple functions to be called on window resize
// window.addEventListener('resize', () => this.$eventHub.$emit('windowResized'))
this.$eventHub.$on('windowResized', this.updateWindowSize)
},
methods: {
updateWindowSize () {
this.windowWidth = window.innerWidth
if(this.isSmall()) { this.currentBreakpoint = 'small' }
if(this.isMedium()) { this.currentBreakpoint = 'medium' }
if(this.isLarge()) { this.currentBreakpoint = 'large' }
if(this.isXLarge()) { this.currentBreakpoint = 'xlarge' }
},
isSmall () {
return this.windowWidth <= this.breakpoints.small
},
isMedium () {
return this.windowWidth > this.breakpoints.small && this.windowWidth <= this.breakpoints.medium
},
isLarge () {
return this.windowWidth > this.breakpoints.medium && this.windowWidth <= this.breakpoints.large
},
isXLarge () {
return this.windowWidth > this.breakpoints.large
},
getCurrentBreakpoint () {
return this.currentBreakpoint
}
}
}
| export default {
data () {
return {
windowWidth: 0,
currentBreakpoint: '',
breakpoints: {
small: 767, // MUST MATCH VARIABLES IN assets/stylesheets/_settings
medium: 1024,
large: 1200
}
}
},
created () {
this.updateWindowSize()
// allow for multiple functions to be called on window resize
window.addEventListener('resize', () => this.$eventHub.$emit('windowResized'))
this.$eventHub.$on('windowResized', this.updateWindowSize)
},
methods: {
updateWindowSize () {
this.windowWidth = window.innerWidth
if(this.isSmall()) { this.currentBreakpoint = 'small' }
if(this.isMedium()) { this.currentBreakpoint = 'medium' }
if(this.isLarge()) { this.currentBreakpoint = 'large' }
if(this.isXLarge()) { this.currentBreakpoint = 'xlarge' }
},
isSmall () {
return this.windowWidth <= this.breakpoints.small
},
isMedium () {
return this.windowWidth > this.breakpoints.small && this.windowWidth <= this.breakpoints.medium
},
isLarge () {
return this.windowWidth > this.breakpoints.medium && this.windowWidth <= this.breakpoints.large
},
isXLarge () {
return this.windowWidth > this.breakpoints.large
},
getCurrentBreakpoint () {
return this.currentBreakpoint
}
}
}
| Fix bug where stickybar height was not being adjusted on page resize | Fix bug where stickybar height was not being adjusted on page resize
| JavaScript | bsd-3-clause | unepwcmc/ProtectedPlanet,unepwcmc/ProtectedPlanet,unepwcmc/ProtectedPlanet,unepwcmc/ProtectedPlanet,unepwcmc/ProtectedPlanet | ---
+++
@@ -15,7 +15,7 @@
this.updateWindowSize()
// allow for multiple functions to be called on window resize
- // window.addEventListener('resize', () => this.$eventHub.$emit('windowResized'))
+ window.addEventListener('resize', () => this.$eventHub.$emit('windowResized'))
this.$eventHub.$on('windowResized', this.updateWindowSize)
}, |
bcfd1dcf3b4854c867ab0db3b5f34a9d6a7f13c5 | src/pretix/plugins/statistics/static/pretixplugins/statistics/statistics.js | src/pretix/plugins/statistics/static/pretixplugins/statistics/statistics.js | /*globals $, Morris, gettext*/
$(function () {
$(".chart").css("height", "250px");
new Morris.Area({
element: 'obd_chart',
data: JSON.parse($("#obd-data").html()),
xkey: 'date',
ykeys: ['ordered', 'paid'],
labels: [gettext('Placed orders'), gettext('Paid orders')],
lineColors: ['#000099', '#009900'],
smooth: false,
resize: true,
fillOpacity: 0.3,
behaveLikeLine: true
});
new Morris.Area({
element: 'rev_chart',
data: JSON.parse($("#rev-data").html()),
xkey: 'date',
ykeys: ['revenue'],
labels: [gettext('Total revenue')],
smooth: false,
resize: true,
fillOpacity: 0.3,
preUnits: $.trim($("#currency").html()) + ' '
});
new Morris.Bar({
element: 'obp_chart',
data: JSON.parse($("#obp-data").html()),
xkey: 'item',
ykeys: ['ordered', 'paid'],
labels: [gettext('Placed orders'), gettext('Paid orders')],
barColors: ['#000099', '#009900'],
resize: true,
xLabelAngle: 60
});
}); | /*globals $, Morris, gettext*/
$(function () {
$(".chart").css("height", "250px");
new Morris.Area({
element: 'obd_chart',
data: JSON.parse($("#obd-data").html()),
xkey: 'date',
ykeys: ['ordered', 'paid'],
labels: [gettext('Placed orders'), gettext('Paid orders')],
lineColors: ['#000099', '#009900'],
smooth: false,
resize: true,
fillOpacity: 0.3,
behaveLikeLine: true
});
new Morris.Area({
element: 'rev_chart',
data: JSON.parse($("#rev-data").html()),
xkey: 'date',
ykeys: ['revenue'],
labels: [gettext('Total revenue')],
smooth: false,
resize: true,
fillOpacity: 0.3,
preUnits: $.trim($("#currency").html()) + ' '
});
new Morris.Bar({
element: 'obp_chart',
data: JSON.parse($("#obp-data").html()),
xkey: 'item',
ykeys: ['ordered', 'paid'],
labels: [gettext('Placed orders'), gettext('Paid orders')],
barColors: ['#000099', '#009900'],
resize: true,
xLabelAngle: 30
});
});
| Adjust label angle to 30° | Statistics: Adjust label angle to 30°
| JavaScript | apache-2.0 | Flamacue/pretix,Flamacue/pretix,Flamacue/pretix,Flamacue/pretix | ---
+++
@@ -32,6 +32,6 @@
labels: [gettext('Placed orders'), gettext('Paid orders')],
barColors: ['#000099', '#009900'],
resize: true,
- xLabelAngle: 60
+ xLabelAngle: 30
});
}); |
0a2a695eb8f985a3b3573165e1df2571858ba2ed | openfisca_web_ui/static/js/components/send-feedback-button.js | openfisca_web_ui/static/js/components/send-feedback-button.js | /** @jsx React.DOM */
'use strict';
var React = require('react'),
ReactIntlMixin = require('react-intl');
var SendFeedbackButton = React.createClass({
mixins: [ReactIntlMixin],
propTypes: {
testCase: React.PropTypes.object.isRequired,
},
render: function() {
var sendFeedbackBody = `
Bonjour,
Je vous envoie mes remarques sur OpenFisca.
Les données ci-dessous vous aideront à résoudre mon problème.
Voici mon cas-type :
${JSON.stringify(this.props.testCase, null, 2)}
`;
var sendFeedbackHref = `mailto:contact@openfisca.fr?subject=Retours sur OpenFisca&body=${encodeURIComponent(sendFeedbackBody)}`; // jshint ignore:line
return (
<a className='btn btn-default' href={sendFeedbackHref}>
{this.getIntlMessage('sendFeedback')}
</a>
);
},
});
module.exports = SendFeedbackButton;
| /** @jsx React.DOM */
'use strict';
var React = require('react'),
ReactIntlMixin = require('react-intl');
var SendFeedbackButton = React.createClass({
mixins: [ReactIntlMixin],
propTypes: {
testCase: React.PropTypes.object.isRequired,
},
render: function() {
var sendFeedbackBody = `
Bonjour,
Je vous envoie mes remarques sur OpenFisca.
Les données ci-dessous vous aideront à résoudre mon problème.
Voici mon cas-type :
${JSON.stringify(this.props.testCase, null, 2)}
`;
var sendFeedbackHref = `mailto:contact@openfisca.fr?subject=Retours sur OpenFisca&body=${encodeURIComponent(sendFeedbackBody)}`; // jshint ignore:line
return (
<a className='btn btn-link' href={sendFeedbackHref}>
{this.getIntlMessage('sendFeedback')}
</a>
);
},
});
module.exports = SendFeedbackButton;
| Use btn-link for send feedback | Use btn-link for send feedback
| JavaScript | agpl-3.0 | openfisca/openfisca-web-ui,openfisca/openfisca-web-ui,openfisca/openfisca-web-ui | ---
+++
@@ -25,7 +25,7 @@
var sendFeedbackHref = `mailto:contact@openfisca.fr?subject=Retours sur OpenFisca&body=${encodeURIComponent(sendFeedbackBody)}`; // jshint ignore:line
return (
- <a className='btn btn-default' href={sendFeedbackHref}>
+ <a className='btn btn-link' href={sendFeedbackHref}>
{this.getIntlMessage('sendFeedback')}
</a>
); |
e99a0ecedc7109634c16fa47bb365146d9dabe9a | bin/flos.js | bin/flos.js | #!/usr/bin/env node
const flos = require('../lib/api');
const FlosRunner = flos.Runner;
// load config
const config = {};
// load linters
const linters = [];
// create runner
const runner = new FlosRunner(linters);
// configure runner
runner.configure(config);
// flos
runner.run();
| #!/usr/bin/env node
// must do this initialization *before* other requires in order to work
if (process.argv.indexOf("--debug") > -1) {
require("debug").enable("flos:*");
}
const flos = require('../lib/api');
const FlosRunner = flos.Runner;
// load config
const config = {};
// load linters
const linters = [];
// create runner
const runner = new FlosRunner(linters);
// configure runner
runner.configure(config);
// flos
runner.run();
| Enable debug mode with CLI option | Enable debug mode with CLI option
| JavaScript | mit | abogaart/flos | ---
+++
@@ -1,4 +1,9 @@
#!/usr/bin/env node
+
+// must do this initialization *before* other requires in order to work
+if (process.argv.indexOf("--debug") > -1) {
+ require("debug").enable("flos:*");
+}
const flos = require('../lib/api');
const FlosRunner = flos.Runner; |
9feb7573074410e8be405dfb54c7b586448b7a5f | e2e/scenario.js | e2e/scenario.js | 'use strict';
describe('pattyApp', function() {
beforeEach(function() {
browser.get('index.html');
});
it('should have patty title', function() {
expect(browser.getTitle()).toMatch('Project Patty Visualisation');
});
describe('initial state', function() {
it('should have zero search results', function() {
expect(element.all(by.css('.search-result')).count()).toBe(0);
});
});
describe('searched on "py"', function() {
beforeEach(function() {
element(by.model('sp.query')).sendKeys('py');
});
it('should have one search result', function() {
expect(element.all(by.css('.search-result')).count()).toBe(1);
});
});
describe('search on "bla"', function() {
beforeEach(function() {
element(by.model('sp.query')).sendKeys('bla');
});
it('should have zero search results', function() {
expect(element.all(by.css('.search-result')).count()).toBe(0);
});
});
});
| 'use strict';
describe('pattyApp', function() {
beforeEach(function() {
browser.get('index.html');
});
it('should have patty title', function() {
expect(browser.getTitle()).toMatch('Project Patty Visualisation');
});
describe('initial state', function() {
it('should have zero search results', function() {
expect(element.all(by.css('.search-result')).count()).toBe(0);
});
it('should not show settings panel', function() {
var panel = element(by.css('.settings-panel'));
expect(panel.isDisplayed()).toBe(false);
});
});
describe('searched on "py"', function() {
beforeEach(function() {
element(by.model('sp.query')).sendKeys('py');
});
it('should have one search result', function() {
expect(element.all(by.css('.search-result')).count()).toBe(1);
});
});
describe('search on "bla"', function() {
beforeEach(function() {
element(by.model('sp.query')).sendKeys('bla');
});
it('should have zero search results', function() {
expect(element.all(by.css('.search-result')).count()).toBe(0);
});
});
describe('click on settings gear', function() {
beforeEach(function() {
element(by.css('.glyphicon-cog')).click();
});
it('should show settings panel', function() {
var panel = element(by.css('.settings-panel'));
expect(panel.isDisplayed()).toBe(true);
});
});
});
| Add e2e test for toggling settings panel. | Add e2e test for toggling settings panel.
| JavaScript | apache-2.0 | NLeSC/PattyVis,NLeSC/PattyVis | ---
+++
@@ -14,7 +14,10 @@
it('should have zero search results', function() {
expect(element.all(by.css('.search-result')).count()).toBe(0);
});
-
+ it('should not show settings panel', function() {
+ var panel = element(by.css('.settings-panel'));
+ expect(panel.isDisplayed()).toBe(false);
+ });
});
describe('searched on "py"', function() {
@@ -36,4 +39,15 @@
expect(element.all(by.css('.search-result')).count()).toBe(0);
});
});
+
+ describe('click on settings gear', function() {
+ beforeEach(function() {
+ element(by.css('.glyphicon-cog')).click();
+ });
+
+ it('should show settings panel', function() {
+ var panel = element(by.css('.settings-panel'));
+ expect(panel.isDisplayed()).toBe(true);
+ });
+ });
}); |
f60a1676ea68fece10c6579e49732fa479adace4 | grunt/sassTasks.js | grunt/sassTasks.js | module.exports = function(grunt){
grunt.config('sass', {
sass: {
options: {
sourceMap: 'true'
}, //options
dist: {
files: {
'dist/css/main.css': 'src/scss/main.scss',
}
}
}
}) //config
grunt.loadNpmTasks('grunt-sass');
grunt.registerTask('compileSass', 'sass');
}
| module.exports = function(grunt){
grunt.config('sass', {
options: {
sourceMap: true
}, //options
dist: {
files: {
'dist/css/main.css': 'src/scss/main.scss',
}
}
}) //config
grunt.loadNpmTasks('grunt-sass');
grunt.registerTask('compileSass', 'sass');
}
| Repair - Fixed up SASS compilation. | Repair - Fixed up SASS compilation.
| JavaScript | mit | joeHillman/boilerplate,joeHillman/boilerplate | ---
+++
@@ -1,13 +1,11 @@
module.exports = function(grunt){
grunt.config('sass', {
- sass: {
- options: {
- sourceMap: 'true'
- }, //options
- dist: {
- files: {
- 'dist/css/main.css': 'src/scss/main.scss',
- }
+ options: {
+ sourceMap: true
+ }, //options
+ dist: {
+ files: {
+ 'dist/css/main.css': 'src/scss/main.scss',
}
}
}) //config |
2862ddc1c0e8eb8132929c167059a5eb9634f5f0 | js/game.js | js/game.js | /*
* game.js
* All of the magic happens here
*/
YINS.Game = function(game) {
this.music;
};
YINS.Game.prototype = {
create: function() {
/* TODO: transition smoothly from mainmenu music to this */
this.music = YINS.game.add.audio('gameMusic');
this.music.loopFull(0.5);
},
update: function() {
}
}; | /*
* game.js
* All of the magic happens here
*/
YINS.Game = function(game) {
this.music;
this.player;
};
YINS.Game.prototype = {
create: function() {
/* TODO: transition smoothly from mainmenu music to this */
this.music = YINS.game.add.audio('gameMusic');
this.music.loopFull(0.5);
/* Add sprites to the game world */
this.player = YINS.game.add.sprite(YINS.game.world.centerX, YINS.game.world.centerY, 'sprites', 19);
/* Declare animations */
this.player.animations.add('idle', [19]);
this.player.animations.add('walk-right', [20, 21], 12);
/* Enable ARCADE physics engine
You can read more about this in the documentation: http://phaser.io/docs/2.3.0/Phaser.Physics.Arcade.html
--> For documentation on the body property of physics enabled sprites,
see this article: http://phaser.io/docs/2.3.0/Phaser.Physics.Arcade.Body.html */
YINS.game.physics.startSystem(Phaser.Physics.ARCADE);
// Enable ARCADE physics on sprites
YINS.game.physics.enable(this.player, Phaser.Physics.ARCADE);
/* Set gravity of the whole game world
This can be manually changed on a per sprite basis by setting
SPRITE.body.gravity.y = GRAVITY */
YINS.game.physics.arcade.gravity.y = 2000;
/* Change properties of the player sprite */
this.player.scale.setTo(YINS.sprite_scale);
this.player.smoothed = false;
this.player.body.collideWorldBounds = true;
},
update: function() {
}
}; | Add player and enable physics | Add player and enable physics
| JavaScript | mpl-2.0 | Vogeltak/YINS,Vogeltak/YINS | ---
+++
@@ -5,6 +5,7 @@
YINS.Game = function(game) {
this.music;
+ this.player;
};
YINS.Game.prototype = {
@@ -15,6 +16,32 @@
this.music = YINS.game.add.audio('gameMusic');
this.music.loopFull(0.5);
+ /* Add sprites to the game world */
+ this.player = YINS.game.add.sprite(YINS.game.world.centerX, YINS.game.world.centerY, 'sprites', 19);
+
+ /* Declare animations */
+ this.player.animations.add('idle', [19]);
+ this.player.animations.add('walk-right', [20, 21], 12);
+
+ /* Enable ARCADE physics engine
+ You can read more about this in the documentation: http://phaser.io/docs/2.3.0/Phaser.Physics.Arcade.html
+ --> For documentation on the body property of physics enabled sprites,
+ see this article: http://phaser.io/docs/2.3.0/Phaser.Physics.Arcade.Body.html */
+ YINS.game.physics.startSystem(Phaser.Physics.ARCADE);
+
+ // Enable ARCADE physics on sprites
+ YINS.game.physics.enable(this.player, Phaser.Physics.ARCADE);
+
+ /* Set gravity of the whole game world
+ This can be manually changed on a per sprite basis by setting
+ SPRITE.body.gravity.y = GRAVITY */
+ YINS.game.physics.arcade.gravity.y = 2000;
+
+ /* Change properties of the player sprite */
+ this.player.scale.setTo(YINS.sprite_scale);
+ this.player.smoothed = false;
+ this.player.body.collideWorldBounds = true;
+
},
update: function() { |
ec625b35cc589d006ee43882abad45d3c291df37 | tests/__mocks__/rc-trigger.js | tests/__mocks__/rc-trigger.js | import React from 'react';
let Trigger; // eslint-disable-line
if (process.env.REACT === '15') {
const ActualTrigger = require.requireActual('rc-trigger');
const { render } = ActualTrigger.prototype;
ActualTrigger.prototype.render = () => {
const { popupVisible } = this.state; // eslint-disable-line
let component;
if (popupVisible || this._component) { // eslint-disable-line
component = this.getComponent(); // eslint-disable-line
}
return (
<div id="TriggerContainer">
{render.call(this)}
{component}
</div>
);
};
Trigger = ActualTrigger;
} else {
const TriggerMock = require('rc-trigger/lib/mock'); // eslint-disable-line
Trigger = TriggerMock;
}
export default Trigger;
| import React from 'react';
let Trigger; // eslint-disable-line
if (process.env.REACT === '15') {
const ActualTrigger = require.requireActual('rc-trigger');
// cannot use object destruction, cause react 15 test cases fail
const render = ActualTrigger.prototype.render; // eslint-disable-line
ActualTrigger.prototype.render = () => {
const { popupVisible } = this.state; // eslint-disable-line
let component;
if (popupVisible || this._component) { // eslint-disable-line
component = this.getComponent(); // eslint-disable-line
}
return (
<div id="TriggerContainer">
{render.call(this)}
{component}
</div>
);
};
Trigger = ActualTrigger;
} else {
const TriggerMock = require('rc-trigger/lib/mock'); // eslint-disable-line
Trigger = TriggerMock;
}
export default Trigger;
| Fix test case in react 15 | :bug: Fix test case in react 15
| JavaScript | mit | zheeeng/ant-design,ant-design/ant-design,elevensky/ant-design,icaife/ant-design,elevensky/ant-design,ant-design/ant-design,icaife/ant-design,zheeeng/ant-design,icaife/ant-design,ant-design/ant-design,elevensky/ant-design,ant-design/ant-design,elevensky/ant-design,icaife/ant-design,zheeeng/ant-design,zheeeng/ant-design | ---
+++
@@ -4,7 +4,8 @@
if (process.env.REACT === '15') {
const ActualTrigger = require.requireActual('rc-trigger');
- const { render } = ActualTrigger.prototype;
+ // cannot use object destruction, cause react 15 test cases fail
+ const render = ActualTrigger.prototype.render; // eslint-disable-line
ActualTrigger.prototype.render = () => {
const { popupVisible } = this.state; // eslint-disable-line |
8be5f534f42691942e74ed98f5eaa327df684fe6 | js/main.js | js/main.js | function openCourse(Course) {
var i, x;
x = document.getElementsByClassName("schedule");
for(i=0;i<x.length;i++){
x[i].style.display = 'none';
}
document.getElementById(Course).style.display = "block";
}
| function openCourse(Course) {
var i, x, y;
x = document.getElementsByClassName("schedule");
y = document.getElementById(Course);
for(i=0;i<x.length;i++){
x[i].style.display = 'none';
}
y.style.display = "block";
y.className = y.className + ' ' + Course.toLowerCase();
}
| Add change of tab color on click to schedule | Add change of tab color on click to schedule
| JavaScript | cc0-1.0 | FatecSorocaba/semana-da-tecnologia,FatecSorocaba/semana-da-tecnologia | ---
+++
@@ -1,8 +1,10 @@
function openCourse(Course) {
- var i, x;
+ var i, x, y;
x = document.getElementsByClassName("schedule");
+ y = document.getElementById(Course);
for(i=0;i<x.length;i++){
x[i].style.display = 'none';
}
- document.getElementById(Course).style.display = "block";
+ y.style.display = "block";
+ y.className = y.className + ' ' + Course.toLowerCase();
} |
9cad1c51285b18da82c376989d079d47c20e96a3 | lib/export-geojson.js | lib/export-geojson.js | var exportGeoJson = require('osm-p2p-geojson')
var pump = require('pump')
var defork = require('osm-p2p-defork')
var collect = require('collect-transform-stream')
var userConfig = require('./user-config')
var presets = userConfig.getSettings('presets')
var matchPreset = require('./preset-matcher')(presets.presets)
var isPolygonFeature = require('./polygon-feature')(presets.presets)
var featureMap = function (f) {
var newProps = {}
Object.keys(f.properties).forEach(function (key) {
var newKey = key.replace(':', '_')
newProps[newKey] = f.properties[key]
})
f.properties = newProps
var match = matchPreset(f)
if (match) {
f.properties.icon = match.icon
f.properties.preset = match.id
}
return f
}
module.exports = function (osm, bbox) {
var q = osm.queryStream(bbox)
var d = collect(defork)
var e = exportGeoJson(osm, {
map: featureMap,
polygonFeatures: isPolygonFeature
})
return pump(q, d, e)
}
| var exportGeoJson = require('osm-p2p-geojson')
var pump = require('pump')
var defork = require('osm-p2p-defork')
var collect = require('collect-transform-stream')
var userConfig = require('./user-config')
var presets = userConfig.getSettings('presets') || {}
var matchPreset = require('./preset-matcher')(presets.presets)
var isPolygonFeature = require('./polygon-feature')(presets.presets)
var featureMap = function (f) {
var newProps = {}
Object.keys(f.properties).forEach(function (key) {
var newKey = key.replace(':', '_')
newProps[newKey] = f.properties[key]
})
f.properties = newProps
var match = matchPreset(f)
if (match) {
f.properties.icon = match.icon
f.properties.preset = match.id
}
return f
}
module.exports = function (osm, bbox) {
var q = osm.queryStream(bbox)
var d = collect(defork)
var e = exportGeoJson(osm, {
map: featureMap,
polygonFeatures: isPolygonFeature
})
return pump(q, d, e)
}
| Fix crash when user has no presets loaded. | Fix crash when user has no presets loaded.
| JavaScript | mit | digidem/ecuador-map-editor,digidem/ecuador-map-editor | ---
+++
@@ -4,7 +4,7 @@
var collect = require('collect-transform-stream')
var userConfig = require('./user-config')
-var presets = userConfig.getSettings('presets')
+var presets = userConfig.getSettings('presets') || {}
var matchPreset = require('./preset-matcher')(presets.presets)
var isPolygonFeature = require('./polygon-feature')(presets.presets) |
30343d093cd2424d849e3c36d5021a82b09222a6 | js/game.js | js/game.js | /*
* Author: Jerome Renaux
* E-mail: jerome.renaux@gmail.com
*/
var Game = {};
Game.init = function(){
game.stage.disableVisibilityChange = true;
};
Game.preload = function() {
game.load.tilemap('map', 'assets/map/example_map.json', null, Phaser.Tilemap.TILED_JSON);
game.load.spritesheet('tileset', 'assets/map/tilesheet.png',32,32);
game.load.image('sprite','assets/sprites/sprite.png');
};
Game.create = function(){
var testKey = game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
testKey.onDown.add(Client.sendTest, this);
Client.getPyramidPlans(); // probably not needed
// get this from the UI
//Game.initPlayer('Me');
};
Game.initPlayer = function(name) {
Client.newPlayer(name);
// Player.init will be called after hearing back from server
}
// throwaway code?
Game.clickJoin = function() {
var name = document.getElementById('input-name').value;
Game.initPlayer(name);
}
| /*
* Author: Jerome Renaux
* E-mail: jerome.renaux@gmail.com
*/
var Game = {};
Game.init = function(){
game.stage.disableVisibilityChange = true;
};
Game.preload = function() {
game.load.tilemap('map', 'assets/map/example_map.json', null, Phaser.Tilemap.TILED_JSON);
game.load.spritesheet('tileset', 'assets/map/tilesheet.png',32,32);
game.load.image('sprite','assets/sprites/sprite.png');
};
Game.create = function(){
var testKey = game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
testKey.onDown.add(Client.sendTest, this);
Client.getPyramidPlans(); // probably not needed
// get this from the UI
//Game.initPlayer('Me');
};
Game.initPlayer = function(name) {
Client.newPlayer(name);
// Player.init will be called after hearing back from server
}
// throwaway code?
Game.clickJoin = function() {
var name = document.getElementById('input-name').value;
Game.initPlayer(name);
document.getElementById('name').remove();
}
| Remove the name input after you use it | Remove the name input after you use it
| JavaScript | mit | marycourtland/pyramid-sea-game,marycourtland/pyramid-sea-game | ---
+++
@@ -33,4 +33,5 @@
Game.clickJoin = function() {
var name = document.getElementById('input-name').value;
Game.initPlayer(name);
+ document.getElementById('name').remove();
} |
d43a75538b768a317e25542cb186c5df51add217 | lib/negotiate.js | lib/negotiate.js | function parseQString(qString) {
var d = /^\s*q=([01](?:\.\d+))\s*$/.exec(qString);
if (!!d) {
return 1;
}
return Number(d[1]);
}
function sortQArrayString(content) {
var entries = content.split(','),
sortData = [];
entries.forEach(function(rec) {
var s = rec.split(';');
sortData.append({
key: s[0],
quality: parseQString(s[1])
});
});
sortData.sort(function(a, b) {
if (a.quality > b.quality) { return -1; }
if (a.quality < b.quality) { return 1; }
return 0;
});
return sortData.map(function(rec) {
return rec.key;
});
}
module.exports = function negotiate(config) {
config || config = {};
// Connect-conneg will only handle Languages, Accept, and Charset
// The gzip module handles the Accept-Encoding header
// Accept-Range is outside the scope of this module
return function(req, res, next) {
if (req.headers['Accept-Language']) {
req.languages = sortQArrayString(req.headers['Accept-Language']);
}
if (req.headers['Accept']) {
req.acceptableTypes = sortQArrayString(req.headers['Accept']);
}
if (req.headers['Accept-Charset']) {
req.charsets = sortQArrayString(req.headers['Accept-Charset']);
}
if (next) { next(); }
};
}
| function parseQString(qString) {
var d = /^\s*q=([01](?:\.\d+))\s*$/.exec(qString);
if (!!d) {
return 1;
}
return Number(d[1]);
}
function sortQArrayString(content) {
var entries = content.split(','),
sortData = [];
entries.forEach(function(rec) {
var s = rec.split(';');
sortData.append({
key: s[0],
quality: parseQString(s[1])
});
});
sortData.sort(function(a, b) {
if (a.quality > b.quality) { return -1; }
if (a.quality < b.quality) { return 1; }
return 0;
});
return sortData.map(function(rec) {
return rec.key;
});
}
function buildScanner(header, property) {
return function(req, res next) {
var data = req.headers[header];
if (data) {
req[property] = sortQArrayString(data);
}
if (next) next();
};
}
module.exports = {
language: function() {
return buildScanner('Accept-Languages', 'languages');
},
acceptedTypes: function() {
return buildScanner('Accept', 'acceptableTypes');
},
charsets: function() {
return buildScanner('Accept-Charset', 'charsets');
},
custom: buildScanner
}
| Split out the different headers into their own methods for greater flexibility. | Split out the different headers into their own methods for greater flexibility.
| JavaScript | mit | foxxtrot/connect-conneg | ---
+++
@@ -27,25 +27,25 @@
});
}
-module.exports = function negotiate(config) {
- config || config = {};
-
- // Connect-conneg will only handle Languages, Accept, and Charset
- // The gzip module handles the Accept-Encoding header
- // Accept-Range is outside the scope of this module
- return function(req, res, next) {
- if (req.headers['Accept-Language']) {
- req.languages = sortQArrayString(req.headers['Accept-Language']);
+function buildScanner(header, property) {
+ return function(req, res next) {
+ var data = req.headers[header];
+ if (data) {
+ req[property] = sortQArrayString(data);
}
-
- if (req.headers['Accept']) {
- req.acceptableTypes = sortQArrayString(req.headers['Accept']);
- }
-
- if (req.headers['Accept-Charset']) {
- req.charsets = sortQArrayString(req.headers['Accept-Charset']);
- }
-
- if (next) { next(); }
+ if (next) next();
};
}
+
+module.exports = {
+ language: function() {
+ return buildScanner('Accept-Languages', 'languages');
+ },
+ acceptedTypes: function() {
+ return buildScanner('Accept', 'acceptableTypes');
+ },
+ charsets: function() {
+ return buildScanner('Accept-Charset', 'charsets');
+ },
+ custom: buildScanner
+} |
d273c211916541bc2a9fd7e4edb5f3260a0d3d26 | src/chat/ui/room/SupportGroup.js | src/chat/ui/room/SupportGroup.js | import React from 'react';
import {
View,
Text,
} from 'react-native';
// import { Actions } from 'react-native-router-flux';
import { RoomView } from './RoomView';
import { AppStyles, AppSizes } from '../../../theme/';
import Network from '../../../network';
import t from '../../../i18n';
export default class SupportGroup extends React.Component {
constructor(props) {
super(props);
this.supportGroup = null;
}
componentWillMount() {
const net = new Network();
this.supportGroup = net.db.groups.findByName('support');
}
render() {
return (
<View
style={[AppStyles.container, {
marginTop: -(AppSizes.navbarHeight),
paddingBottom: 5,
}]}
>
{
this.supportGroup &&
<RoomView obj={this.supportGroup} />
}
{
!this.supportGroup &&
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text
style={{
fontSize: 16,
fontFamily: 'OpenSans-Regular',
fontWeight: '500',
}}
>{t('txt_CS')}</Text>
</View>
}
</View>
);
}
}
SupportGroup.defaultProps = {
};
SupportGroup.propTypes = {
};
| import React from 'react';
import {
View,
Text,
} from 'react-native';
// import { Actions } from 'react-native-router-flux';
import RoomView from './RoomView';
import { AppStyles, AppSizes } from '../../../theme/';
import Network from '../../../network';
import t from '../../../i18n';
export default class SupportGroup extends React.Component {
constructor(props) {
super(props);
this.supportGroup = null;
}
componentWillMount() {
const net = new Network();
this.supportGroup = net.db.groups.findByName('support');
}
render() {
return (
<View
style={[AppStyles.container, {
marginTop: -(AppSizes.navbarHeight),
paddingBottom: 5,
}]}
>
{
this.supportGroup &&
<RoomView obj={this.supportGroup} />
}
{
!this.supportGroup &&
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text
style={{
fontSize: 16,
fontFamily: 'OpenSans-Regular',
fontWeight: '500',
}}
>{t('txt_CS')}</Text>
</View>
}
</View>
);
}
}
SupportGroup.defaultProps = {
};
SupportGroup.propTypes = {
};
| Support import was throwing exceptions | Support import was throwing exceptions
| JavaScript | apache-2.0 | elarasu/roverz-chat,elarasu/roverz-chat | ---
+++
@@ -4,7 +4,7 @@
Text,
} from 'react-native';
// import { Actions } from 'react-native-router-flux';
-import { RoomView } from './RoomView';
+import RoomView from './RoomView';
import { AppStyles, AppSizes } from '../../../theme/';
import Network from '../../../network'; |
38f0c75f83c1d864adee5f7006eb66446228406a | src/providers.js | src/providers.js | import { randomId } from './util';
const s = typeof Symbol === 'function';
export const vueFormConfig = s ? Symbol() : `VueFormProviderConfig${randomId}`;
export const vueFormState = s ? Symbol() : `VueFormProviderState${randomId}`;
| import { randomId } from './util';
export const vueFormConfig = `VueFormProviderConfig${randomId()}`;
export const vueFormState = `VueFormProviderState${randomId()}`;
| Fix a bug when using symbols in iOS 8.1 | Fix a bug when using symbols in iOS 8.1
For some reason, injecting objects with symbols as keys in Vue won’t work in iOS 8.1. To replicate this, simply create a <vue-form> and run it in the on iOS 8.1 or the iOS 8.1 simulator.
| JavaScript | mit | fergaldoyle/vue-form,fergaldoyle/vue-form | ---
+++
@@ -1,5 +1,4 @@
import { randomId } from './util';
-const s = typeof Symbol === 'function';
-export const vueFormConfig = s ? Symbol() : `VueFormProviderConfig${randomId}`;
-export const vueFormState = s ? Symbol() : `VueFormProviderState${randomId}`;
+export const vueFormConfig = `VueFormProviderConfig${randomId()}`;
+export const vueFormState = `VueFormProviderState${randomId()}`; |
f9c6df86c3998f1d7625ad472b57f8c0a34df0ec | src/components/Avatar/index.js | src/components/Avatar/index.js | import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
const Avatar = ({ className, user }) => (
<div className={cx('Avatar', className)}>
<img
className="Avatar-image"
src={user.avatar || `/a/${encodeURIComponent(user._id)}`}
alt={user.username}
/>
</div>
);
Avatar.propTypes = {
className: PropTypes.string,
user: PropTypes.object.isRequired
};
export default Avatar;
| import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
const Avatar = ({ className, user }) => (
<div className={cx('Avatar', className)}>
<img
className="Avatar-image"
src={user.avatar || `https://sigil.cupcake.io/uwave-${encodeURIComponent(user._id)}`}
alt={user.username}
/>
</div>
);
Avatar.propTypes = {
className: PropTypes.string,
user: PropTypes.object.isRequired
};
export default Avatar;
| Revert "[WLK-INSTANCE] use locally generated avatars as default instead of cupcake.io" | Revert "[WLK-INSTANCE] use locally generated avatars as default instead of cupcake.io"
This reverts commit 92c531beca630b1aff75712360a3bae3e158420e.
| JavaScript | mit | welovekpop/uwave-web-welovekpop.club,welovekpop/uwave-web-welovekpop.club | ---
+++
@@ -6,7 +6,7 @@
<div className={cx('Avatar', className)}>
<img
className="Avatar-image"
- src={user.avatar || `/a/${encodeURIComponent(user._id)}`}
+ src={user.avatar || `https://sigil.cupcake.io/uwave-${encodeURIComponent(user._id)}`}
alt={user.username}
/>
</div> |
0a8f1e5704a56eddeac9a7d3ed3e0a0b2e744a29 | src/components/TestCardNumber.js | src/components/TestCardNumber.js | import React, { Component } from 'react';
import { faintBlack, cyan500 } from 'material-ui/styles/colors';
import MenuItem from 'material-ui/MenuItem';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton/IconButton';
import ActionHelpOutline from 'material-ui/svg-icons/action/help-outline';
const TEST_CARD_NUMBERS = [
'01-2167-30-92545'
];
class TestCardNumber extends Component {
constructor() {
super();
this.state = {
cardNumber: ''
};
}
renredCardNumbers() {
return TEST_CARD_NUMBERS.map((number, index) => <MenuItem key={index} value={number} primaryText={number} />);
}
render() {
return (
<IconMenu
className='buka-cardnumber__help'
onChange={this.props.onChange}
iconButtonElement={<IconButton><ActionHelpOutline color={faintBlack} hoverColor={cyan500} /></IconButton>}
anchorOrigin={{horizontal: 'left', vertical: 'top'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}>
{this.renredCardNumbers()}
</IconMenu>
);
}
}
TestCardNumber.propTypes = {
onChange: React.PropTypes.func
};
export default TestCardNumber; | import React, { Component } from 'react';
import { faintBlack, cyan500 } from 'material-ui/styles/colors';
import MenuItem from 'material-ui/MenuItem';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton/IconButton';
import ActionHelpOutline from 'material-ui/svg-icons/action/help-outline';
const TEST_CARD_NUMBERS = [
'01-2167-30-92545',
'26-2167-19-35623',
'29-2167-26-31433'
];
class TestCardNumber extends Component {
constructor() {
super();
this.state = {
cardNumber: ''
};
}
renredCardNumbers() {
return TEST_CARD_NUMBERS.map((number, index) => <MenuItem key={index} value={number} primaryText={number} />);
}
render() {
return (
<IconMenu
className='buka-cardnumber__help'
onChange={this.props.onChange}
iconButtonElement={<IconButton><ActionHelpOutline color={faintBlack} hoverColor={cyan500} /></IconButton>}
anchorOrigin={{horizontal: 'left', vertical: 'top'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}>
{this.renredCardNumbers()}
</IconMenu>
);
}
}
TestCardNumber.propTypes = {
onChange: React.PropTypes.func
};
export default TestCardNumber; | Add some test card numbers. | Add some test card numbers.
| JavaScript | apache-2.0 | blobor/buka,blobor/buka,blobor/skipass.site,blobor/skipass.site | ---
+++
@@ -6,7 +6,9 @@
import ActionHelpOutline from 'material-ui/svg-icons/action/help-outline';
const TEST_CARD_NUMBERS = [
- '01-2167-30-92545'
+ '01-2167-30-92545',
+ '26-2167-19-35623',
+ '29-2167-26-31433'
];
class TestCardNumber extends Component { |
e3a6aa64f47b65aba6a1d612c468c52b213f4546 | src/components/geo-risks/view.js | src/components/geo-risks/view.js | /**
* Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017.
*/
import View from '../../base/view';
import template from './template';
export default class GeoRisksView extends View {
constructor (el, context) {
context.locationRiskFactors = ['p_15', 'p_20', 'p_21', 'p_16', 'p_17', 'p_18', 'p_14', 'p_19', 'p_22', 'p_13'];
const handleRisksChange = (e) => {
let group = {};
this.el.querySelectorAll('.input-risk').forEach((item) => {
group[item.id] = item.checked;
});
this.context.patient.addSymptomsGroup(group);
};
const binds = {
'.input-risk': {
type: 'change',
listener: handleRisksChange
}
};
super(el, template, context, binds);
}
}
| /**
* Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017.
*/
import View from '../../base/view';
import template from './template';
export default class GeoRisksView extends View {
constructor (el, context) {
context.locationRiskFactors = ['p_15', 'p_20', 'p_21', 'p_16', 'p_17', 'p_18', 'p_14', 'p_19', 'p_22', 'p_13'];
const handleRisksChange = (e) => {
let group = {};
this.el.querySelectorAll('.input-risk').forEach((item) => {
group[item.id] = {reported: item.checked};
});
this.context.patient.addSymptomsGroup(group);
};
const binds = {
'.input-risk': {
type: 'change',
listener: handleRisksChange
}
};
super(el, template, context, binds);
}
}
| Update geo riskfators screen to use the new structure of reported symptoms | Update geo riskfators screen to use the new structure of reported symptoms
| JavaScript | mit | infermedica/js-symptom-checker-example,infermedica/js-symptom-checker-example | ---
+++
@@ -12,7 +12,7 @@
const handleRisksChange = (e) => {
let group = {};
this.el.querySelectorAll('.input-risk').forEach((item) => {
- group[item.id] = item.checked;
+ group[item.id] = {reported: item.checked};
});
this.context.patient.addSymptomsGroup(group);
}; |
ab1a77facf8a5f0d34e1ef61e8abce65ccfe772f | src/components/republia-times.js | src/components/republia-times.js | var React = require( "react" );
var MorningScreen = require( "./morning-screen" );
var PlayScreen = require( "./play-screen" );
module.exports = React.createClass({
displayName: "RepubliaTimes",
getInitialState() {
return {
day: 1,
screen: "morning"
};
},
changeToScreen( newScreen ) {
this.setState({
screen: newScreen
});
},
renderMorningScreen() {
return <MorningScreen
day={this.state.day}
onContinue={this.changeToScreen.bind( null, "play" )} />;
},
renderPlayScreen() {
return <PlayScreen day={this.state.day} />;
},
render() {
var screen = this.state.screen;
var screenRenderFunction = {
morning: this.renderMorningScreen,
play: this.renderPlayScreen
}[ screen ];
if ( screenRenderFunction === undefined ) {
throw new Error( "Invalid screen '" + screen +"'" );
}
return screenRenderFunction();
}
});
| var React = require( "react" );
var MorningScreen = require( "./morning-screen" );
var PlayScreen = require( "./play-screen" );
module.exports = React.createClass({
displayName: "RepubliaTimes",
getInitialState() {
return {
day: 1,
screen: "morning"
};
},
changeToScreen( newScreen ) {
this.setState({
screen: newScreen
});
},
renderMorningScreen() {
return <MorningScreen
day={this.state.day}
onContinue={() => this.changeToScreen( "play" )} />;
},
renderPlayScreen() {
return <PlayScreen day={this.state.day} />;
},
render() {
var screen = this.state.screen;
var screenRenderFunction = {
morning: this.renderMorningScreen,
play: this.renderPlayScreen
}[ screen ];
if ( screenRenderFunction === undefined ) {
throw new Error( "Invalid screen '" + screen +"'" );
}
return screenRenderFunction();
}
});
| Use an arrow function instead | Use an arrow function instead
| JavaScript | isc | bjohn465/republia-times,bjohn465/republia-times | ---
+++
@@ -21,7 +21,7 @@
renderMorningScreen() {
return <MorningScreen
day={this.state.day}
- onContinue={this.changeToScreen.bind( null, "play" )} />;
+ onContinue={() => this.changeToScreen( "play" )} />;
},
renderPlayScreen() { |
aa06dc2086eb43845d86d229ed57e235abeeadfe | src/filters/ascii/AsciiFilter.js | src/filters/ascii/AsciiFilter.js | var core = require('../../core');
/**
* @author Vico @vicocotea
* original shader : https://www.shadertoy.com/view/lssGDj by @movAX13h
*/
/**
* An ASCII filter.
*
* @class
* @extends AbstractFilter
* @namespace PIXI.filters
*/
function AsciiFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
require('fs').readFileSync(__dirname + '/ascii.frag', 'utf8'),
// custom uniforms
{
dimensions: { type: '4fv', value: new Float32Array([0, 0, 0, 0]) },
pixelSize: { type: '1f', value: 8 }
}
);
}
AsciiFilter.prototype = Object.create(core.AbstractFilter.prototype);
AsciiFilter.prototype.constructor = AsciiFilter;
module.exports = AsciiFilter;
Object.defineProperties(AsciiFilter.prototype, {
/**
* The pixel size used by the filter.
*
* @member {number}
* @memberof AsciiFilter#
*/
size: {
get: function ()
{
return this.uniforms.pixelSize.value;
},
set: function (value)
{
this.uniforms.pixelSize.value = value;
}
}
});
| var core = require('../../core');
// TODO (cengler) - The Y is flipped in this shader for some reason.
/**
* @author Vico @vicocotea
* original shader : https://www.shadertoy.com/view/lssGDj by @movAX13h
*/
/**
* An ASCII filter.
*
* @class
* @extends AbstractFilter
* @namespace PIXI.filters
*/
function AsciiFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
require('fs').readFileSync(__dirname + '/ascii.frag', 'utf8'),
// custom uniforms
{
dimensions: { type: '4fv', value: new Float32Array([0, 0, 0, 0]) },
pixelSize: { type: '1f', value: 8 }
}
);
}
AsciiFilter.prototype = Object.create(core.AbstractFilter.prototype);
AsciiFilter.prototype.constructor = AsciiFilter;
module.exports = AsciiFilter;
Object.defineProperties(AsciiFilter.prototype, {
/**
* The pixel size used by the filter.
*
* @member {number}
* @memberof AsciiFilter#
*/
size: {
get: function ()
{
return this.uniforms.pixelSize.value;
},
set: function (value)
{
this.uniforms.pixelSize.value = value;
}
}
});
| Add a TODO for ascii filter | Add a TODO for ascii filter
| JavaScript | mit | falihakz/pixi.js,leonardo-silva/pixi.js,TrevorSayre/pixi.js,finscn/pixi.js,twhitbeck/pixi.js,sfinktah/pixi.js,jpweeks/pixi.js,DarkEngineer/pixi.js,lucap86/pixi.js,jojuntune/pixi.js,out-of-band/pixi.js,bdero/pixi.js,GoodBoyDigital/pixi.js,SUNFOXGames/pixi.js,trehnert23/pixi.js,Mgonand/pixi.js,sfinktah/pixi.js,NikkiKoole/pixi.js,marekventur/pixi.js,staff0rd/pixi.js,englercj/pixi.js,LibertyGlobal/pixi.js,DNESS/pixi.js,jojuntune/pixi.js,elmoeleven/pixi.js,GHackAnonymous/pixi.js,hgl888/pixi.js,jpweeks/pixi.js,design1online/pixi.js,drkibitz/pixi.js,ezshine/pixi.js,serprex/pixi.js,j27cai/pixi.js,englercj/pixi.js,GaryTsang/pixi.js,linkwe/firejs-v2,xushuwei202/pixi.js,linkwe/pixi.js,feirlau/pixi.js,TannerRogalsky/pixi.js,taires/pixi.js,sanyaade-teachings/pixi.js,naranjamecanica/pixi.js,mbrukman/pixi.js,curtiszimmerman/pixi.js,gameofbombs/pixi.js,mjhasbach/pixi.js,cc272309126/pixi.js,themoonrat/pixi.js,grepman/pixi.js,finscn/pixi.js,linkwe/pixi.js,staff0rd/pixi.js,singuerinc/pixi.js,nabettu/pixi.js,hellopath/pixi.js,deepjyotisaran/pixi.js,Cristy94/pixi.js,red2901/pixi.js,adelciotto/pixi.js,srbala/pixi.js,CozartKevin/pixi.js,pixijs/pixi.js,Makio64/pixi.js,woshiniuren/pixi.js,ceco-fmedia/pixi.js,fwjlwo/pixi.js,uken/pixi.js,ceco-fmedia/pixi.js,cdd/pixi.js,lucap86/pixi.js,themoonrat/pixi.js,snamoah/pixi.js,linkwe/firejs-v2,Cristy94/pixi.js,endel/pixi.js,SpringRoll/pixi.js,pixijs/pixi.js,andrew168/pixi.js,GamaLabs/pixi.js,Boycce/pixi.js,drkibitz/pixi.js,Makio64/pixi.js,holmberd/pixi.js,out-of-band/pixi.js,uken/pixi.js,gitkiselev/pixi.js,ta9mi/pixi.js,vundev/pixi.js,ivanpopelyshev/pixi.js,bma73/pixi.js,youanden/pixi.js,wayfu/pixi.js,ivanpopelyshev/pixi.js,cjgammon/pixi-nano.js,curtiszimmerman/pixi.js,sokeroner/pixi.js,bma73/pixi.js,tobireif/pixi.js | ---
+++
@@ -1,4 +1,6 @@
var core = require('../../core');
+
+// TODO (cengler) - The Y is flipped in this shader for some reason.
/**
* @author Vico @vicocotea |
2775ca6bf28c6b3ec0deb0ce8c4f682de470cca4 | src/commands/clean/clean.js | src/commands/clean/clean.js | /*
* clean.js - Clean only the bots messages.
*
* Contributed by Ovyerus
*/
exports.commands = [
'clean'
];
exports.clean = {
desc: 'clean messages created by the bot itself',
main: (bot, ctx) => {
return new Promise((resolve,reject) => {
ctx.msg.channel.getMessages(100).then(msgs => {
let delet = [];
msgs.forEach(m => delet.push(m.delete()));
return Promise.all(delet);
});
});
}
};
| /*
* clean.js - Clean only the bots messages.
*
* Contributed by Ovyerus
*/
exports.commands = [
'clean'
];
exports.clean = {
desc: 'clean messages created by the bot itself',
main: (bot, ctx) => {
return new Promise((resolve, reject) => {
ctx.msg.channel.getMessages(100).then(msgs => {
let delet = [];
msgs = msgs.filter(m => m.author.id === bot.user.id);
msgs.forEach(m => delet.push(m.delete()));
return Promise.all(delet);
}).then(amt => ctx.msg.channel.createMessage(amt)).then(resolve).catch(reject);
});
}
};
| Clean additions and send message amount | Clean additions and send message amount
| JavaScript | unknown | sr229/owo-whats-this,ClarityMoe/Clara,awau/owo-whats-this,owo-dev-team/owo-whats-this,awau/Clara | ---
+++
@@ -11,12 +11,13 @@
exports.clean = {
desc: 'clean messages created by the bot itself',
main: (bot, ctx) => {
- return new Promise((resolve,reject) => {
+ return new Promise((resolve, reject) => {
ctx.msg.channel.getMessages(100).then(msgs => {
let delet = [];
+ msgs = msgs.filter(m => m.author.id === bot.user.id);
msgs.forEach(m => delet.push(m.delete()));
return Promise.all(delet);
- });
+ }).then(amt => ctx.msg.channel.createMessage(amt)).then(resolve).catch(reject);
});
}
}; |
88168d12446d91540a00ed78c18f144df2c9e234 | findJavaHome.js | findJavaHome.js | require('find-java-home')(function(err, home){
if(err){
console.error("[node-java] "+err);
process.exit(1);
}
process.stdout.write(home);
});
| require('find-java-home')(function(err, home){
if (err || !home) {
if (!err) err = Error('Unable to determine Java home location');
process.exit(1);
}
process.stdout.write(home);
});
| Exit with error if Java home can't be found | Exit with error if Java home can't be found
| JavaScript | mit | joeferner/node-java,joeferner/node-java,joeferner/node-java,joeferner/node-java,joeferner/node-java,joeferner/node-java | ---
+++
@@ -1,6 +1,6 @@
require('find-java-home')(function(err, home){
- if(err){
- console.error("[node-java] "+err);
+ if (err || !home) {
+ if (!err) err = Error('Unable to determine Java home location');
process.exit(1);
}
process.stdout.write(home); |
26d6e669462517abdbd2906785657f14da8cc555 | public/assets/wee/build/tasks/legacy-convert.js | public/assets/wee/build/tasks/legacy-convert.js | /* global legacyConvert, module, project */
module.exports = function(grunt) {
grunt.registerTask('convertLegacy', function(task) {
var dest = legacyConvert[task],
content = grunt.file.read(dest),
rootSize = project.style.legacy.rootSize,
rootValue = 10;
// Determine root value for unit conversion
if (rootSize.indexOf('%') !== -1) {
rootValue = (rootSize.replace('%', '') / 100) * 16;
} else if (rootSize.indexOf('px') !== -1) {
rootValue = rootSize.replace('px', '');
} else if (rootSize.indexOf('em') !== -1) {
rootValue = rootSize.replace('em', '');
} else if (rootSize.indexOf('pt') !== -1) {
rootValue = rootSize.replace('pt', '');
}
content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) {
return (match * rootValue) + 'px';
}).replace(/opacity:([.\d]+)/gi, function(str, match) {
return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');';
}).replace(/::/g, ':');
grunt.file.write(dest, content);
});
}; | /* global legacyConvert, module, project */
module.exports = function(grunt) {
grunt.registerTask('convertLegacy', function(task) {
var dest = legacyConvert[task],
content = grunt.file.read(dest),
rootSize = project.style.legacy.rootSize,
rootValue = 10;
// Determine root value for unit conversion
if (rootSize.indexOf('%') !== -1) {
rootValue = (rootSize.replace('%', '') / 100) * 16;
} else if (rootSize.indexOf('px') !== -1) {
rootValue = rootSize.replace('px', '');
} else if (rootSize.indexOf('em') !== -1) {
rootValue = rootSize.replace('em', '');
} else if (rootSize.indexOf('pt') !== -1) {
rootValue = rootSize.replace('pt', '');
}
content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) {
return (match * rootValue) + 'px';
}).replace(/opacity:([.\d]+)/gi, function(str, match) {
return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ')';
}).replace(/::/g, ':');
grunt.file.write(dest, content);
});
}; | Remove extra semicolon injection in legacy stylesheet | Remove extra semicolon injection in legacy stylesheet
| JavaScript | apache-2.0 | janusnic/wee,weepower/wee,weepower/wee,janusnic/wee | ---
+++
@@ -21,7 +21,7 @@
content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) {
return (match * rootValue) + 'px';
}).replace(/opacity:([.\d]+)/gi, function(str, match) {
- return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');';
+ return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ')';
}).replace(/::/g, ':');
grunt.file.write(dest, content); |
91854c84fe969d6622b5c9bf3fe87818750f9c1f | src/js/components/Camera.js | src/js/components/Camera.js | import {Entity} from 'aframe-react';
import React from 'react';
import Wsgamepad from './Wsgamepad';
export default ({
position=[0, 0, 5],
id="camera",
active="false",
userHeight="4.8",
rotation=[0, 0, 0],
far="10000",
looksControlsEnabeld="true",
fov="80",
near="0.005",
velocity=[3, 3, 3],
...props
}) => (
<Entity position={[0, 5, 0]} static-body="">
<Entity
id={id}
active={active}
camera={{
'user-height': userHeight,
active,
far,
fov,
near
}}
rotation={rotation}
mouse-controls=""
touch-controls=""
hmd-controls=""
ws-gamepad={{
endpoint: "ws://192.168.0.14:7878"
}}
look-controls=""
universal-controls=""
gamepad-controls=""
kinematic-body=""
{...props}/>
</Entity>
);
/*
add back `universal-controls=""` to `Entity` to enable universal control again
*/
| import {Entity} from 'aframe-react';
import React from 'react';
import Wsgamepad from './Wsgamepad';
export default ({
position=[0, 0, 5],
id="camera",
active="false",
userHeight="4.8",
rotation=[0, 0, 0],
far="10000",
looksControlsEnabeld="true",
fov="80",
near="0.005",
velocity=[3, 3, 3],
...props
}) => (
<Entity position={[0, 5, 0]} static-body="">
<Entity
id={id}
active={active}
camera={{
'user-height': userHeight,
active,
far,
fov,
near
}}
rotation={rotation}
mouse-controls=""
touch-controls=""
hmd-controls=""
ws-gamepad={{
endpoint: "ws://127.0.0.1:7878"
}}
look-controls=""
universal-controls=""
gamepad-controls=""
kinematic-body=""
{...props}/>
</Entity>
);
/*
add back `universal-controls=""` to `Entity` to enable universal control again
*/
| Update ws endpoint to localhost | Update ws endpoint to localhost
| JavaScript | mit | maniart/darkpatterns,maniart/darkpatterns | ---
+++
@@ -32,7 +32,7 @@
touch-controls=""
hmd-controls=""
ws-gamepad={{
- endpoint: "ws://192.168.0.14:7878"
+ endpoint: "ws://127.0.0.1:7878"
}}
look-controls=""
universal-controls="" |
ceea32dc631efab5c5b00722ec331f16a1751a4e | strip-test-selectors.js | strip-test-selectors.js | 'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelector(attribute) {
return TEST_SELECTOR_PREFIX.test(attribute);
}
function stripTestSelectors(node) {
if ('sexpr' in node) {
node = node.sexpr;
}
node.params = node.params.filter(function(param) {
return !isTestSelector(param.original);
});
node.hash.pairs = node.hash.pairs.filter(function(pair) {
return !isTestSelector(pair.key);
});
}
function StripTestSelectorsTransform() {
this.syntax = null;
}
StripTestSelectorsTransform.prototype.transform = function(ast) {
let walker = new this.syntax.Walker();
walker.visit(ast, function(node) {
if (node.type === 'ElementNode') {
node.attributes = node.attributes.filter(function(attribute) {
return !isTestSelector(attribute.name);
});
} else if (node.type === 'MustacheStatement' || node.type === 'BlockStatement') {
stripTestSelectors(node);
}
});
return ast;
};
module.exports = StripTestSelectorsTransform;
| 'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelector(attribute) {
return TEST_SELECTOR_PREFIX.test(attribute);
}
function stripTestSelectors(node) {
if ('sexpr' in node) {
node = node.sexpr;
}
node.params = node.params.filter(function(param) {
return !isTestSelector(param.original);
});
node.hash.pairs = node.hash.pairs.filter(function(pair) {
return !isTestSelector(pair.key);
});
}
function StripTestSelectorsTransform() {
this.syntax = null;
}
StripTestSelectorsTransform.prototype.transform = function(ast) {
let { traverse } = this.syntax;
traverse(ast, {
ElementNode(node) {
node.attributes = node.attributes.filter(function(attribute) {
return !isTestSelector(attribute.name);
});
},
MustacheStatement(node) {
stripTestSelectors(node);
},
BlockStatement(node) {
stripTestSelectors(node);
},
});
return ast;
};
module.exports = StripTestSelectorsTransform;
| Use `traverse()` instead of the deprecated `Walker` class | Use `traverse()` instead of the deprecated `Walker` class
| JavaScript | mit | simplabs/ember-test-selectors,simplabs/ember-test-selectors | ---
+++
@@ -27,16 +27,22 @@
}
StripTestSelectorsTransform.prototype.transform = function(ast) {
- let walker = new this.syntax.Walker();
+ let { traverse } = this.syntax;
- walker.visit(ast, function(node) {
- if (node.type === 'ElementNode') {
+ traverse(ast, {
+ ElementNode(node) {
node.attributes = node.attributes.filter(function(attribute) {
return !isTestSelector(attribute.name);
});
- } else if (node.type === 'MustacheStatement' || node.type === 'BlockStatement') {
+ },
+
+ MustacheStatement(node) {
stripTestSelectors(node);
- }
+ },
+
+ BlockStatement(node) {
+ stripTestSelectors(node);
+ },
});
return ast; |
47dcd35d3834834d7e46b274c0828b82602df5a2 | src/L.Control.Angular.js | src/L.Control.Angular.js | 'use strict';
L.Control.Angular = L.Control.extend({
options: {
position: 'bottomleft',
template: ''
},
onAdd: function(map) {
var that = this;
var container = L.DomUtil.create('div', 'angular-control-leaflet');
angular.element(document).ready(function() {
// Grab the injector for the current angular app
var $injector = angular.element(document).injector();
var $rootScope = $injector.get('$rootScope'),
$compile = $injector.get('$compile'),
$controller = $injector.get('$controller');
var scope = $rootScope.$new(true);
var element = angular.element(container);
element.html(that.options.template);
var link = $compile(element);
// Controller setup based on ui-router's code https://github.com/angular-ui/ui-router
if (that.options.controller) {
var controller = $controller(that.options.controller, {
'$map': map,
'$scope': scope,
'$element': element
});
if (that.options.controllerAs) {
scope[that.options.controllerAs] = controller;
}
element.data('$ngControllerController', controller);
element.children().data('$ngControllerController', controller);
}
link(scope);
scope.$apply();
});
return container;
}
});
L.control.angular = function(options) {
return new L.Control.Angular(options);
}; | 'use strict';
L.Control.Angular = L.Control.extend({
options: {
position: 'bottomleft',
template: ''
},
onAdd: function onAdd (map) {
var that = this;
var container = L.DomUtil.create('div', 'angular-control-leaflet');
angular.element(document).ready(function() {
// Grab the injector for the current angular app
var $injector = angular.element(document).injector();
var $rootScope = $injector.get('$rootScope'),
$compile = $injector.get('$compile'),
$controller = $injector.get('$controller');
var scope = $rootScope.$new(true);
var element = angular.element(container);
element.html(that.options.template);
// Controller setup based on ui-router's code https://github.com/angular-ui/ui-router
if (that.options.controller) {
var controller = $controller(that.options.controller, {
'$map': map,
'$scope': scope,
'$element': element,
'$options': that.options
});
if (that.options.controllerAs) {
scope[that.options.controllerAs] = controller;
}
element.data('$ngControllerController', controller);
element.children().data('$ngControllerController', controller);
}
$compile(element)(scope);
scope.$apply();
});
return container;
}
});
L.control.angular = function(options) {
return new L.Control.Angular(options);
}; | Add di to allow access to the control's options from its angular controller | Add di to allow access to the control's options from its angular controller
| JavaScript | mit | grantHarris/leaflet-control-angular | ---
+++
@@ -5,9 +5,10 @@
position: 'bottomleft',
template: ''
},
- onAdd: function(map) {
+ onAdd: function onAdd (map) {
var that = this;
var container = L.DomUtil.create('div', 'angular-control-leaflet');
+
angular.element(document).ready(function() {
// Grab the injector for the current angular app
var $injector = angular.element(document).injector();
@@ -21,14 +22,13 @@
var element = angular.element(container);
element.html(that.options.template);
- var link = $compile(element);
-
// Controller setup based on ui-router's code https://github.com/angular-ui/ui-router
if (that.options.controller) {
var controller = $controller(that.options.controller, {
'$map': map,
'$scope': scope,
- '$element': element
+ '$element': element,
+ '$options': that.options
});
if (that.options.controllerAs) {
@@ -39,7 +39,7 @@
element.children().data('$ngControllerController', controller);
}
- link(scope);
+ $compile(element)(scope);
scope.$apply();
});
return container; |
a936197d853cf9309aa23b712a51853376c7bb13 | lib/BaseHash.js | lib/BaseHash.js | /**
* Message for errors when some method is not implemented
* @type {String}
* @private
*/
var NEED_IMPLEMENT_MESSAGE = "This method need to implement";
/**
* BaseHash class
* @constructor
*/
function BaseHash(options) {
if (typeof options === 'string') {
this.setData(options);
} else if (typeof options === 'object' && options.data) {
this.setData(options.data);
} else {
throw new Error('You need provide data');
}
}
BaseHash.prototype = Object.create({
constructor: BaseHash,
/**
* Get data from current hashing instance
* @returns {*}
*/
getData: function () {
return this._data;
},
/**
* Set data that need to hash
* @param {*} data
* @returns {BaseHash}
*/
setData: function (data) {
this._data = data;
return this;
},
/**
* Hash data
*/
hash: function () {
throw new Error(NEED_IMPLEMENT_MESSAGE);
}
});
module.exports = BaseHash;
| /**
* Message for errors when some method is not implemented
* @type {String}
* @private
*/
var NEED_IMPLEMENT_MESSAGE = "This method need to implement";
/**
* BaseHash class
* @constructor
*/
function BaseHash(options) {
if (!options) {
throw new Error('You must provide data');
}
if (Object.prototype.toString.call(options) === '[object Object]') {
this.setData(options.data);
} else {
this.setData(options);
}
}
BaseHash.prototype = Object.create({
constructor: BaseHash,
/**
* Get data from current hashing instance
* @returns {*}
*/
getData: function () {
return this._data;
},
/**
* Set data that need to hash
* @param {*} data
* @returns {BaseHash}
*/
setData: function (data) {
this._data = data;
return this;
},
/**
* Hash data
*/
hash: function () {
throw new Error(NEED_IMPLEMENT_MESSAGE);
}
});
module.exports = BaseHash;
| Fix bug with array and object data | Fix bug with array and object data
| JavaScript | mit | ghaiklor/data-2-hash | ---
+++
@@ -10,12 +10,14 @@
* @constructor
*/
function BaseHash(options) {
- if (typeof options === 'string') {
- this.setData(options);
- } else if (typeof options === 'object' && options.data) {
+ if (!options) {
+ throw new Error('You must provide data');
+ }
+
+ if (Object.prototype.toString.call(options) === '[object Object]') {
this.setData(options.data);
} else {
- throw new Error('You need provide data');
+ this.setData(options);
}
}
|
80cc141b8a08bc195bf51c5445cc76fb0e5a0809 | config/tailwindcss-config.js | config/tailwindcss-config.js | module.exports = {
content: [
'./app/**/*.{html,hbs,js}'
],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {}
},
plugins: [
require('@tailwindcss/forms')
]
}
| module.exports = {
content: [
'./app/**/*.{html,hbs,js}'
],
darkMode: 'class', // or 'media' or 'class'
theme: {
extend: {}
},
plugins: [
require('@tailwindcss/forms')
]
}
| Update deprecated Tailwind config value | Update deprecated Tailwind config value
| JavaScript | mpl-2.0 | 67P/hyperchannel,67P/hyperchannel | ---
+++
@@ -2,7 +2,7 @@
content: [
'./app/**/*.{html,hbs,js}'
],
- darkMode: false, // or 'media' or 'class'
+ darkMode: 'class', // or 'media' or 'class'
theme: {
extend: {}
}, |
1aaeff5c1d3709948b6f6f6435635b339fc5d83c | app/assets/javascripts/search.js | app/assets/javascripts/search.js | $(function() {
var $tabs = $('#search-results-tabs'),
$searchForm = $('.js-search-hash');
if($tabs.length > 0){
$tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true });
}
function getDefaultSearchTabIndex(){
var tabIds = $('.search-navigation a').map(function(i, el){
return $(el).attr('href').split('#').pop();
}),
$defaultTab = $('input[name=tab]'),
selectedTab = $.inArray($defaultTab.val(), tabIds);
return selectedTab > -1 ? selectedTab : 0;
}
if($searchForm.length){
$tabs.on('tabChanged', updateSearchForm);
}
function updateSearchForm(e, hash){
if(typeof hash !== 'undefined'){
var $defaultTab = $('input[name=tab]');
if($defaultTab.length === 0){
$defaultTab = $('<input type="hidden" name="tab">');
$searchForm.prepend($defaultTab);
}
$defaultTab.val(hash);
}
}
});
| $(function() {
var $tabs = $('#search-results-tabs'),
$searchForm = $('.js-search-hash');
if($tabs.length > 0){
$tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true });
}
function getDefaultSearchTabIndex(){
var tabIds = $('.search-navigation a').map(function(i, el){
return $(el).attr('href').split('#').pop();
});
$defaultTab = $('input[name=tab]');
selectedTab = $.inArray($defaultTab.val(), tabIds);
return selectedTab > -1 ? selectedTab : 0;
}
if($searchForm.length){
$tabs.on('tabChanged', updateSearchForm);
}
function updateSearchForm(e, hash){
if(typeof hash !== 'undefined'){
var $defaultTab = $('input[name=tab]');
if($defaultTab.length === 0){
$defaultTab = $('<input type="hidden" name="tab">');
$searchForm.prepend($defaultTab);
}
$defaultTab.val(hash);
}
}
});
| Tidy up whitespace and line-endings | Tidy up whitespace and line-endings
| JavaScript | mit | alphagov/frontend,alphagov/frontend,alphagov/frontend,alphagov/frontend | ---
+++
@@ -8,10 +8,10 @@
function getDefaultSearchTabIndex(){
var tabIds = $('.search-navigation a').map(function(i, el){
- return $(el).attr('href').split('#').pop();
- }),
- $defaultTab = $('input[name=tab]'),
- selectedTab = $.inArray($defaultTab.val(), tabIds);
+ return $(el).attr('href').split('#').pop();
+ });
+ $defaultTab = $('input[name=tab]');
+ selectedTab = $.inArray($defaultTab.val(), tabIds);
return selectedTab > -1 ? selectedTab : 0;
} |
3af3831986136005504d4db5580e886ab83b2a35 | app/components/edit-interface.js | app/components/edit-interface.js | import Ember from 'ember';
import EmberValidations from 'ember-validations';
export default Ember.Component.extend(EmberValidations, {
classNames: ["edit-interface"],
validations: {
'changes': {
changeset: true,
}
},
/* This is only required because ember-validations doesn't correctly observe child errors */
runValidations: function() {
this.validate().then(function() {}, function() {});
}.observes("hup.at"),
actions: {
addNewMeaning() {
this.get("changes.meanings").pushObject(new Object({action: "add", def: "", example: "", labels: []}));
this.validate();
},
addNewSeq() {
this.get("changes.seqs").pushObject(new Object({action: "add", text: "", labels: []}));
this.validate();
},
}
});
| import Ember from 'ember';
import EmberValidations from 'ember-validations';
export default Ember.Component.extend(EmberValidations, {
classNames: ["edit-interface"],
validations: {
'changes': {
changeset: true,
}
},
/* This is only required because ember-validations doesn't correctly observe child errors */
runValidations: function() {
this.validate().then(function() {}, function() {});
}.observes("hup.at"),
actions: {
addNewMeaning() {
this.get("changes.meanings").pushObject(new Object({action: "add", def: "", example: "", labels: [], synonyms: []}));
this.validate();
},
addNewSeq() {
this.get("changes.seqs").pushObject(new Object({action: "add", text: "", labels: []}));
this.validate();
},
}
});
| Add new meaning should have synonyms added too (empty array) | Add new meaning should have synonyms added too (empty array)
| JavaScript | mit | wordset/wordset-ui,BryanCode/wordset-ui,BryanCode/wordset-ui,wordset/wordset-ui,BryanCode/wordset-ui,wordset/wordset-ui | ---
+++
@@ -14,7 +14,7 @@
}.observes("hup.at"),
actions: {
addNewMeaning() {
- this.get("changes.meanings").pushObject(new Object({action: "add", def: "", example: "", labels: []}));
+ this.get("changes.meanings").pushObject(new Object({action: "add", def: "", example: "", labels: [], synonyms: []}));
this.validate();
},
addNewSeq() { |
988845fff293580680805c952ad6842e7f9b3dc3 | src/modules/drawer/index.js | src/modules/drawer/index.js | import React from 'react'
import MuiDrawer from 'material-ui/Drawer'
import MenuItem from 'material-ui/MenuItem'
import muiThemeable from 'material-ui/styles/muiThemeable';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as drawerActions from './dux'
class Drawer extends React.Component {
render() {
const theme = this.props.muiTheme
const topBarStyle = {
backgroundColor: theme.palette.primary1Color,
color: theme.appBar.textColor
}
return (
<div>
<MuiDrawer open={this.props.drawer.isOpen}>
<MenuItem
primaryText='Apps'
onTouchTap={this.props.actions.closeDrawer}
innerDivStyle={topBarStyle}
/>
<MenuItem primaryText='Counter' />
<MenuItem primaryText='Todo List' />
</MuiDrawer>
</div>
)
}
}
function mapStateToProps(state) {
return {
drawer: state.drawer
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(drawerActions, dispatch)
}
}
export default muiThemeable()(connect(mapStateToProps, mapDispatchToProps)(Drawer)) | import React from 'react'
import MuiDrawer from 'material-ui/Drawer'
import MenuItem from 'material-ui/MenuItem'
import { Link } from 'react-router-dom'
import muiThemeable from 'material-ui/styles/muiThemeable';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as drawerActions from './dux'
class Drawer extends React.Component {
toggle(open, reason) {
console.log('Toggling to ', open, ' because ', reason)
if (open) {
this.props.actions.openDrawer()
} else {
this.props.actions.closeDrawer()
}
}
render() {
const theme = this.props.muiTheme
const topBarStyle = {
backgroundColor: theme.palette.primary1Color,
color: theme.appBar.textColor
}
return (
<div>
<MuiDrawer
open={this.props.drawer.isOpen}
docked={false}
onRequestChange={this.toggle.bind(this)}
>
<MenuItem
primaryText='Apps'
onTouchTap={this.props.actions.closeDrawer}
innerDivStyle={topBarStyle}
/>
<MenuItem
primaryText='Counter'
containerElement={<Link to='/counter' />}
onTouchTap={this.props.actions.closeDrawer}
/>
<MenuItem
primaryText='Todo List'
containerElement={<Link to='/todo' />}
onTouchTap={this.props.actions.closeDrawer}
/>
</MuiDrawer>
</div>
)
}
}
function mapStateToProps(state) {
return {
drawer: state.drawer
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(drawerActions, dispatch)
}
}
export default muiThemeable()(connect(mapStateToProps, mapDispatchToProps)(Drawer)) | Make the drawer behave like a mobile drawer Close when you click away. Grey out the background when the menu is up. | Make the drawer behave like a mobile drawer
Close when you click away. Grey out the background when the menu is up.
| JavaScript | apache-2.0 | davidharting/react-redux-example,davidharting/react-redux-example | ---
+++
@@ -1,29 +1,50 @@
import React from 'react'
import MuiDrawer from 'material-ui/Drawer'
import MenuItem from 'material-ui/MenuItem'
+import { Link } from 'react-router-dom'
import muiThemeable from 'material-ui/styles/muiThemeable';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as drawerActions from './dux'
class Drawer extends React.Component {
+ toggle(open, reason) {
+ console.log('Toggling to ', open, ' because ', reason)
+ if (open) {
+ this.props.actions.openDrawer()
+ } else {
+ this.props.actions.closeDrawer()
+ }
+ }
+
render() {
const theme = this.props.muiTheme
const topBarStyle = {
backgroundColor: theme.palette.primary1Color,
color: theme.appBar.textColor
-
}
return (
<div>
- <MuiDrawer open={this.props.drawer.isOpen}>
+ <MuiDrawer
+ open={this.props.drawer.isOpen}
+ docked={false}
+ onRequestChange={this.toggle.bind(this)}
+ >
<MenuItem
primaryText='Apps'
onTouchTap={this.props.actions.closeDrawer}
innerDivStyle={topBarStyle}
/>
- <MenuItem primaryText='Counter' />
- <MenuItem primaryText='Todo List' />
+ <MenuItem
+ primaryText='Counter'
+ containerElement={<Link to='/counter' />}
+ onTouchTap={this.props.actions.closeDrawer}
+ />
+ <MenuItem
+ primaryText='Todo List'
+ containerElement={<Link to='/todo' />}
+ onTouchTap={this.props.actions.closeDrawer}
+ />
</MuiDrawer>
</div>
) |
4973763838d745cdc236f3bb985f8ef107d03476 | src/modules/getIconLinks.js | src/modules/getIconLinks.js | const cheerio = require('cheerio');
const url = require('url');
function hrefIsIcon(href) {
return /\w\.(png|jpg|ico)/.test(href);
}
function getIconLinks(rootUrl, dom) {
var $ = cheerio.load(dom);
const icons = [];
$('link').each(function(i, elem) {
const href = $(this).attr('href');
const resolved = url.resolve(rootUrl, href);
if (!hrefIsIcon(resolved)) {
return;
}
icons.push(resolved);
});
return icons;
}
module.exports = getIconLinks;
| const cheerio = require('cheerio');
const url = require('url');
function hrefIsIcon(href) {
return /((icon.*\.(png|jpg))|(\w+\.ico))$/.test(href);
}
function getIconLinks(rootUrl, dom) {
var $ = cheerio.load(dom);
const icons = [];
$('link').each(function(i, elem) {
const href = $(this).attr('href');
const resolved = url.resolve(rootUrl, href);
if (!hrefIsIcon(resolved)) {
return;
}
icons.push(resolved);
});
return icons;
}
module.exports = getIconLinks;
| Check for `icon` in icon path | Check for `icon` in icon path
| JavaScript | mit | jiahaog/page-icon | ---
+++
@@ -2,7 +2,7 @@
const url = require('url');
function hrefIsIcon(href) {
- return /\w\.(png|jpg|ico)/.test(href);
+ return /((icon.*\.(png|jpg))|(\w+\.ico))$/.test(href);
}
function getIconLinks(rootUrl, dom) { |
aad4f74eeaac1bd4428bcd74a3627209ac477b8e | lib/faexport/public/js/faexport.js | lib/faexport/public/js/faexport.js | $(function() {
function update() {
var name = $('#boxes #name').val();
var id = $('#boxes #id').val();
if (name || id) {
if (!name) { name = "{name}"; }
if (!id) { id = "{id}"; }
$('#links').show();
$('.resource').each(function() {
var link = $(this).attr('data-format').replace('{name}', name)
.replace('{id}', id);
$(this).attr('href', link);
$(this).children('span.name').text(name);
$(this).children('span.id').text(id);
});
} else {
$('#links').hide();
}
}
$('#name').on('input propertychange paste', update);
$('#id').on('input propertychange paste', update);
$('#name').focus();
});
| 'use strict';
$(function() {
function update() {
var name = $('#boxes #name').val();
var id = $('#boxes #id').val();
if (name || id) {
if (!name) { name = "{name}"; }
if (!id) { id = "{id}"; }
$('#links').show();
$('.resource').each(function() {
var link = $(this).attr('data-format').replace('{name}', name)
.replace('{id}', id);
$(this).attr('href', link);
$(this).children('span.name').text(name);
$(this).children('span.id').text(id);
});
} else {
$('#links').hide();
}
}
$('#name').on('input propertychange paste', update);
$('#id').on('input propertychange paste', update);
$('#name').focus();
});
| Add 'use strict' to javascript | Add 'use strict' to javascript
| JavaScript | bsd-3-clause | boothale/faexport,boothale/faexport,boothale/faexport | ---
+++
@@ -1,3 +1,5 @@
+'use strict';
+
$(function() {
function update() {
var name = $('#boxes #name').val(); |
5fc5dab5c4a2a7972cac711b562bd4f981b9215c | src/modules/view/getters.js | src/modules/view/getters.js | import { Immutable } from 'nuclear-js';
import { getters as entityGetters } from '../entity';
const DEFAULT_VIEW_ENTITY_ID = 'group.default_view';
export const currentView = [
'currentView',
];
export const views = [
entityGetters.entityMap,
entities => entities.filter(entity => entity.domain === 'group' &&
entity.attributes.view &&
entity.entityId !== DEFAULT_VIEW_ENTITY_ID),
];
function addToMap(map, entities, groupEntity) {
groupEntity.attributes.entity_id.forEach(entityId => {
if (map.has(entityId)) return;
const entity = entities.get(entityId);
if (!entity || entity.attributes.hidden) return;
map.set(entityId, entity);
if (entity.domain === 'group') {
addToMap(map, entities, entity);
}
});
}
export const currentViewEntities = [
entityGetters.entityMap,
currentView,
(entities, view) => {
let viewEntity;
if (view) {
viewEntity = entities.get(view);
} else {
// will be undefined if entity does not exist
viewEntity = entities.get(DEFAULT_VIEW_ENTITY_ID);
}
if (!viewEntity) {
return entities.filter(entity => !entity.attributes.hidden);
}
return (new Immutable.Map()).withMutations(map => {
addToMap(map, entities, viewEntity);
});
},
];
| import { Immutable } from 'nuclear-js';
import { getters as entityGetters } from '../entity';
const DEFAULT_VIEW_ENTITY_ID = 'group.default_view';
export const currentView = [
'currentView',
];
export const views = [
entityGetters.entityMap,
entities => entities.filter(entity => entity.domain === 'group' &&
entity.attributes.view &&
entity.entityId !== DEFAULT_VIEW_ENTITY_ID),
];
function addToMap(map, entities, groupEntity, recurse = true) {
groupEntity.attributes.entity_id.forEach(entityId => {
if (map.has(entityId)) return;
const entity = entities.get(entityId);
if (!entity || entity.attributes.hidden) return;
map.set(entityId, entity);
if (entity.domain === 'group' && recurse) {
addToMap(map, entities, entity, false);
}
});
}
export const currentViewEntities = [
entityGetters.entityMap,
currentView,
(entities, view) => {
let viewEntity;
if (view) {
viewEntity = entities.get(view);
} else {
// will be undefined if entity does not exist
viewEntity = entities.get(DEFAULT_VIEW_ENTITY_ID);
}
if (!viewEntity) {
return entities.filter(entity => !entity.attributes.hidden);
}
return (new Immutable.Map()).withMutations(map => {
addToMap(map, entities, viewEntity);
});
},
];
| Allow embedding groups in groups | Allow embedding groups in groups
| JavaScript | mit | balloob/home-assistant-js | ---
+++
@@ -14,7 +14,7 @@
entity.entityId !== DEFAULT_VIEW_ENTITY_ID),
];
-function addToMap(map, entities, groupEntity) {
+function addToMap(map, entities, groupEntity, recurse = true) {
groupEntity.attributes.entity_id.forEach(entityId => {
if (map.has(entityId)) return;
@@ -24,8 +24,8 @@
map.set(entityId, entity);
- if (entity.domain === 'group') {
- addToMap(map, entities, entity);
+ if (entity.domain === 'group' && recurse) {
+ addToMap(map, entities, entity, false);
}
});
} |
4bfb7f5c8e80b9c7009ac388f55843aec7dc8f12 | src/utils/columnAccessor.spec.js | src/utils/columnAccessor.spec.js | import columnAccessor from './columnAccessor';
describe('Util:columnAccessor', () => {
it('should run this test', () => {
const accessor = columnAccessor({ column: 'foo' });
const d = { foo: 5 };
expect(accessor(d)).toEqual(5);
});
});
| import columnAccessor from './columnAccessor';
describe('Util:columnAccessor', () => {
it('should access the value of a column', () => {
const accessor = columnAccessor({ column: 'foo' });
const d = { foo: 5 };
expect(accessor(d)).toEqual(5);
});
it('should apply a number formatter', () => {
const accessor = columnAccessor({ column: 'foo', format: '.0s' });
const d = { foo: 10000 };
expect(accessor(d)).toEqual('10k');
});
});
| Add test for number formatter | Add test for number formatter
| JavaScript | bsd-3-clause | nuagenetworks/visualization-framework,nuagenetworks/visualization-framework,nuagenetworks/visualization-framework,nuagenetworks/visualization-framework,nuagenetworks/visualization-framework | ---
+++
@@ -1,9 +1,14 @@
import columnAccessor from './columnAccessor';
describe('Util:columnAccessor', () => {
- it('should run this test', () => {
+ it('should access the value of a column', () => {
const accessor = columnAccessor({ column: 'foo' });
const d = { foo: 5 };
expect(accessor(d)).toEqual(5);
});
+ it('should apply a number formatter', () => {
+ const accessor = columnAccessor({ column: 'foo', format: '.0s' });
+ const d = { foo: 10000 };
+ expect(accessor(d)).toEqual('10k');
+ });
}); |
ec6597383ddfcae4e0a0c4015b7315aef0e5caf3 | src/reducers/course-reducer.js | src/reducers/course-reducer.js | import * as types from '../actions/action-types';
export default (state = [], action) => {
switch (action.type) {
case types.CREATE_COURSE:
return [
...state,
Object.assign({}, action.course),
];
default:
return state;
}
};
| import * as types from '../actions/action-types';
export default (state = [], action) => {
switch (action.type) {
case types.LOAD_COURSES_SUCCESS:
return action.courses;
default:
return state;
}
};
| Load courses in the reducer | Load courses in the reducer
| JavaScript | mit | joilson-cisne/react-redux-es6,joilson-cisne/react-redux-es6 | ---
+++
@@ -2,11 +2,8 @@
export default (state = [], action) => {
switch (action.type) {
- case types.CREATE_COURSE:
- return [
- ...state,
- Object.assign({}, action.course),
- ];
+ case types.LOAD_COURSES_SUCCESS:
+ return action.courses;
default:
return state; |
f27949cfbb5eaf7d7517cc1c15cdbe9dc4c09e1f | app/config/config.views.js | app/config/config.views.js | [
{
"name": "Textstring",
"path": "/umbraco/views/propertyeditors/textbox/textbox.html"
},
{
"name": "Content Picker",
"path": "/umbraco/views/propertyeditors/contentpicker/contentpicker.html"
},
{
"name": "Boolean",
"path": "/umbraco/views/propertyeditors/boolean/boolean.html"
},
{
"name": "Checkbox List",
"path": "/umbraco/views/propertyeditors/checkboxlist/checkboxlist.html"
},
{
"name": "Radio Buttons",
"path": "/umbraco/views/propertyeditors/radiobuttons/radiobuttons.html"
}
] | [
{
"name": "Textstring",
"path": "/umbraco/views/propertyeditors/textbox/textbox.html"
},
{
"name": "Content Picker",
"path": "/umbraco/views/propertyeditors/contentpicker/contentpicker.html"
},
{
"name": "Boolean",
"path": "/umbraco/views/propertyeditors/boolean/boolean.html"
},
{
"name": "Checkbox List",
"path": "/umbraco/views/propertyeditors/checkboxlist/checkboxlist.html"
},
{
"name": "Radio Buttons",
"path": "/umbraco/views/propertyeditors/radiobuttons/radiobuttons.html"
},
{
"name": "Date Picker",
"path": "/umbraco/views/propertyeditors/datepicker/datepicker.html"
},
{
"name": "Dropdown",
"path": "/umbraco/views/propertyeditors/dropdown/dropdown.html"
},
{
"name": "Textarea",
"path": "/umbraco/views/propertyeditors/textarea/textarea.html"
},
{
"name": "RTE",
"path": "/umbraco/views/propertyeditors/rte/rte.html"
}
]
| Add a few new Core Editors | Add a few new Core Editors
| JavaScript | mit | imulus/Archetype,tomfulton/Archetype,imulus/Archetype,Nicholas-Westby/Archetype,Nicholas-Westby/Archetype,kgiszewski/Archetype,tomfulton/Archetype,kjac/Archetype,tomfulton/Archetype,imulus/Archetype,Nicholas-Westby/Archetype,kjac/Archetype,kgiszewski/Archetype,kipusoep/Archetype,kgiszewski/Archetype,kipusoep/Archetype,kipusoep/Archetype,kjac/Archetype | ---
+++
@@ -18,5 +18,21 @@
{
"name": "Radio Buttons",
"path": "/umbraco/views/propertyeditors/radiobuttons/radiobuttons.html"
+ },
+ {
+ "name": "Date Picker",
+ "path": "/umbraco/views/propertyeditors/datepicker/datepicker.html"
+ },
+ {
+ "name": "Dropdown",
+ "path": "/umbraco/views/propertyeditors/dropdown/dropdown.html"
+ },
+ {
+ "name": "Textarea",
+ "path": "/umbraco/views/propertyeditors/textarea/textarea.html"
+ },
+ {
+ "name": "RTE",
+ "path": "/umbraco/views/propertyeditors/rte/rte.html"
}
-]
+] |
a3f29a4d4e2f7ebe98461c92da50cc3a914360e7 | content.js | content.js | chrome
.runtime
.sendMessage({ msg: 'getStatus' }, function (response) {
if (response.status) {
let storage = chrome.storage.local;
storage.get(['type', 'freq', 'q', 'gain'], function (items) {
type = items.type || 'highshelf';
freq = items.freq || '17999';
q = items.q || '0';
gain = items.gain || '-70';
let actualCode = `
var st_type = '${type}',
st_freq = '${freq}',
st_q = '${q}',
st_gain = '${gain}';
console.log('Settings loaded...');
`;
let script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
});
let s = document.createElement('script');
s.src = chrome.extension.getURL('intercept.js');
s.onload = function () {
this.parentNode.removeChild(this);
};
(document.head || document.documentElement).appendChild(s);
}
});
| function createScript(property, source) {
let scriptElement = document.createElement('script');
scriptElement['property'] = source;
return scriptElement;
}
function injectScript(script) {
(document.head || document.documentElement).appendChild(script);
}
chrome
.runtime
.sendMessage({ msg: 'getStatus' }, function (response) {
if (response.status) {
let storage = chrome.storage.local;
storage.get(['type', 'freq', 'q', 'gain'], function (items) {
type = items.type || 'highshelf';
freq = items.freq || '17999';
q = items.q || '0';
gain = items.gain || '-70';
let actualCode = `
var st_type = '${type}',
st_freq = '${freq}',
st_q = '${q}',
st_gain = '${gain}';
console.log('Settings loaded...');
`;
let script = createScript('textConetent', actualCode);
injectScript(script);
script.parentNode.removeChild(script);
});
let script = createScript('src', chrome.extension.getURL('intercept.js'));
script.onload = function () {
this.parentNode.removeChild(this);
};
injectScript(script);
}
});
| Make script injection more abstract | Make script injection more abstract
| JavaScript | apache-2.0 | ubeacsec/Silverdog,ubeacsec/Silverdog | ---
+++
@@ -1,3 +1,13 @@
+function createScript(property, source) {
+ let scriptElement = document.createElement('script');
+ scriptElement['property'] = source;
+ return scriptElement;
+}
+
+function injectScript(script) {
+ (document.head || document.documentElement).appendChild(script);
+}
+
chrome
.runtime
.sendMessage({ msg: 'getStatus' }, function (response) {
@@ -18,18 +28,15 @@
console.log('Settings loaded...');
`;
- let script = document.createElement('script');
- script.textContent = actualCode;
- (document.head || document.documentElement).appendChild(script);
+ let script = createScript('textConetent', actualCode);
+ injectScript(script);
script.parentNode.removeChild(script);
});
- let s = document.createElement('script');
- s.src = chrome.extension.getURL('intercept.js');
- s.onload = function () {
+ let script = createScript('src', chrome.extension.getURL('intercept.js'));
+ script.onload = function () {
this.parentNode.removeChild(this);
};
-
- (document.head || document.documentElement).appendChild(s);
+ injectScript(script);
}
}); |
60603f0620732a9bf3fe9697ebbd8427be89d8ac | lib/defaults.js | lib/defaults.js | module.exports = {
loadPlugins: false
, cms_methods: true
, plugins: []
, pluginConfigs: {}
, metadata: {
siteTitle: "No name"
, description: "Foo"
}
, corePlugins: [
"bloggify-router"
, "bloggify-plugin-manager"
]
, pluginConfigs: {
"bloggify-plugin-manager": {
plugins: []
}
}
, server: {
errorPages: false
, public: "public"
, port: process.env.PORT || 8080
, host: null
, csrf: true
}
, theme: {
path: "theme"
, viewsPath: "views"
, public: "public"
}
, adapter: {
paths: {
articles: "content/articles"
, pages: "content/pages"
}
, parse: {}
}
, paths: {
// The bloggify directory (by default the root)
bloggify: "/"
// The config file: `bloggify.js`
, config: "/bloggify.js"
// Where to store the plugins
, plugins: "/node_modules"
, publicMain: "/!/bloggify/public/"
, publicCore: "/!/bloggify/core/"
, publicTheme: "/!/bloggify/theme/"
, cssUrls: "/!/bloggify/css-urls/"
}
};
| module.exports = {
loadPlugins: false
, cms_methods: true
, plugins: []
, pluginConfigs: {}
, metadata: {
siteTitle: "No name"
, description: "Foo"
}
, corePlugins: [
"bloggify-router"
, "bloggify-plugin-manager"
]
, pluginConfigs: {
"bloggify-plugin-manager": {
plugins: []
}
}
, server: {
errorPages: false
, public: "public"
, port: process.env.PORT || 8080
, host: null
, csrf: true
}
, theme: {
path: "theme"
, viewsPath: "views"
, public: "public"
}
, adapter: {
paths: {
articles: "content/articles"
, pages: "content/pages"
}
, parse: {}
}
, paths: {
// The bloggify directory (by default the root)
bloggify: "/"
// The config file: `bloggify.js`
, config: "/bloggify.js"
// Where to store the plugins
, plugins: "/node_modules"
, publicMain: "/!/bloggify/public/"
, publicCore: "/!/bloggify/core/"
, publicTheme: "/!/bloggify/theme/"
, cssUrls: "/!/bloggify/css-urls/"
}
, bundler: {
aliases: {
"bloggify": `${__dirname}/client/index.js`
}
}
};
| Add an alias for bloggify on the client | Add an alias for bloggify on the client
| JavaScript | mit | Bloggify/Bloggify | ---
+++
@@ -50,4 +50,9 @@
, publicTheme: "/!/bloggify/theme/"
, cssUrls: "/!/bloggify/css-urls/"
}
+ , bundler: {
+ aliases: {
+ "bloggify": `${__dirname}/client/index.js`
+ }
+ }
}; |
ab612a1e43f7d66ecef3dd08745868c827c158cf | gulpfile.js | gulpfile.js | const babel = require('gulp-babel');
const gulp = require('gulp');
const pug = require('gulp-pug');
const uglify = require('gulp-uglify');
gulp.task('build', () => {
gulp.src('app/src/pug/*')
.pipe(pug())
.pipe(gulp.dest('app/dist'));
gulp.src('app/src/js/*')
.pipe(babel({presets: ['es2015']}))
.pipe(uglify())
.pipe(gulp.dest('app/dist'));
});
| const babel = require('gulp-babel');
const cssnano = require('cssnano');
const gulp = require('gulp');
const postcss = require('gulp-postcss');
const pug = require('gulp-pug');
const uglify = require('gulp-uglify');
gulp.task('build', () => {
gulp.src('app/src/pug/*')
.pipe(pug())
.pipe(gulp.dest('app/dist'));
gulp.src('app/src/css/*')
.pipe(postcss([cssnano]))
.pipe(gulp.dest('app/dist'));
gulp.src('app/src/js/*')
.pipe(babel({presets: ['es2015']}))
.pipe(uglify())
.pipe(gulp.dest('app/dist'));
});
| Add css processing to `gulp build` | Add css processing to `gulp build`
| JavaScript | mit | wulkano/kap,albinekb/kap,albinekb/kap,albinekb/kap | ---
+++
@@ -1,5 +1,7 @@
const babel = require('gulp-babel');
+const cssnano = require('cssnano');
const gulp = require('gulp');
+const postcss = require('gulp-postcss');
const pug = require('gulp-pug');
const uglify = require('gulp-uglify');
@@ -8,6 +10,10 @@
.pipe(pug())
.pipe(gulp.dest('app/dist'));
+ gulp.src('app/src/css/*')
+ .pipe(postcss([cssnano]))
+ .pipe(gulp.dest('app/dist'));
+
gulp.src('app/src/js/*')
.pipe(babel({presets: ['es2015']}))
.pipe(uglify()) |
73d920d2b938af78ed5a6828fd303ba7486af3c7 | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
browserSync = require('browser-sync'),
sass = require('gulp-sass'),
bower = require('gulp-bower'),
notify = require('gulp-notify'),
reload = browserSync.reload,
bs = require("browser-sync").create(),
Hexo = require('hexo'),
hexo = new Hexo(process.cwd(), {});
var src = {
scss: './scss/',
css: './source/css',
ejs: 'layout'
};
// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {
// init starts the server
bs.init({
baseDir: "../../public"
});
// hexo.call('generate', {}).then(function(){
// console.log('Generating Files');
// });
// Now call methods on bs instead of the
// main browserSync module export
bs.reload("*.html");
bs.reload("*.css");
});
// Compile sass into CSS
gulp.task('sass', function() {
// gulp.src(src.scss + "/*/*.scss")
gulp.src(src.scss + "{,*}/*.scss")
.pipe(sass({}))
// .pipe(gulp.dest(src.css))
.pipe(gulp.dest('./css/'))
.pipe(reload({stream: true}));
});
gulp.task('sass:watch', function () {
gulp.watch('./scss/**/*.scss', ['sass']);
});
gulp.task('bower', function() {
return bower()
.pipe(gulp.dest('source/lib'))
});
gulp.task('default', ['serve']);
| var gulp = require('gulp'),
browserSync = require('browser-sync'),
sass = require('gulp-sass'),
bower = require('gulp-bower'),
notify = require('gulp-notify'),
reload = browserSync.reload,
bs = require("browser-sync").create(),
Hexo = require('hexo'),
hexo = new Hexo(process.cwd(), {});
var src = {
scss: './scss/',
css: './source/css',
ejs: 'layout'
},
watchFiles = [
'./scss/*.scss',
'*/*.ejs'
];
// Static Server + watching scss/html files
gulp.task('serve', ['sass:watch'], function() {
// init starts the server
bs.init(watchFiles, {
server: {
baseDir: "../../public"
},
logLevel: "debug"
});
hexo.init();
});
// Compile sass into CSS
gulp.task('sass', function() {
// gulp.src(src.scss + "/*/*.scss")
gulp.src(src.scss + "{,*}/*.scss")
.pipe(sass({}))
// .pipe(gulp.dest(src.css))
.pipe(gulp.dest('../../source/css/'))
.pipe(reload({stream: true}));
});
gulp.task('sass:watch', function () {
gulp.watch('./scss/**/*.scss', ['sass']);
});
gulp.task('bower', function() {
return bower()
.pipe(gulp.dest('source/lib'))
});
gulp.task('default', ['serve']);
| Fix changes so it'll start tracking css watches | Fix changes so it'll start tracking css watches
| JavaScript | mit | chrisjlee/hexo-theme-zurb-foundation,wakermahmud/Moretaza | ---
+++
@@ -13,24 +13,25 @@
scss: './scss/',
css: './source/css',
ejs: 'layout'
-};
+},
+watchFiles = [
+ './scss/*.scss',
+ '*/*.ejs'
+];
// Static Server + watching scss/html files
-gulp.task('serve', ['sass'], function() {
+gulp.task('serve', ['sass:watch'], function() {
// init starts the server
- bs.init({
- baseDir: "../../public"
+ bs.init(watchFiles, {
+ server: {
+ baseDir: "../../public"
+ },
+ logLevel: "debug"
});
- // hexo.call('generate', {}).then(function(){
- // console.log('Generating Files');
- // });
+ hexo.init();
- // Now call methods on bs instead of the
- // main browserSync module export
- bs.reload("*.html");
- bs.reload("*.css");
});
// Compile sass into CSS
@@ -39,7 +40,7 @@
gulp.src(src.scss + "{,*}/*.scss")
.pipe(sass({}))
// .pipe(gulp.dest(src.css))
- .pipe(gulp.dest('./css/'))
+ .pipe(gulp.dest('../../source/css/'))
.pipe(reload({stream: true}));
});
|
1da97a23950b7248b493d391ea916f907236297f | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var sassLint = require('gulp-sass-lint');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
gulp.task('babel', function() {
return gulp.src('app/Resources/client/jsx/project/details/*.jsx')
.pipe(babel({
presets: ['es2015', 'react']
}))
.pipe(concat('details.js'))
.pipe(gulp.dest('web/assets/js/project'));
});
gulp.task('sass', function () {
return gulp.src('web/assets/scss/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write('.', {includeContent: false}))
.pipe(gulp.dest('web/assets/css'));
});
gulp.task('sassLint', function() {
gulp.src('web/assets/scss/*.s+(a|c)ss')
.pipe(sassLint())
.pipe(sassLint.format())
.pipe(sassLint.failOnError());
});
gulp.task('css', ['sassLint','sass'], function () {
});
gulp.task('default', ['css'], function() {
// place code for your default task here
});
| 'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var sassLint = require('gulp-sass-lint');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
require('babel-core/register');
// testing
var mocha = require('gulp-mocha');
gulp.task('babel', function() {
return gulp.src('app/Resources/client/jsx/project/details/*.jsx')
.pipe(babel({
presets: ['es2015', 'react']
}))
.pipe(concat('details.js'))
.pipe(gulp.dest('web/assets/js/project'));
});
gulp.task('test', function() {
return gulp.src('tests/jsx/**/*.js', {read: false})
.pipe(mocha({reporter: 'spec', useColors: true}))
});
gulp.task('sass', function () {
return gulp.src('web/assets/scss/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write('.', {includeContent: false}))
.pipe(gulp.dest('web/assets/css'));
});
gulp.task('sassLint', function() {
gulp.src('web/assets/scss/*.s+(a|c)ss')
.pipe(sassLint())
.pipe(sassLint.format())
.pipe(sassLint.failOnError());
});
gulp.task('css', ['sassLint','sass'], function () {
});
gulp.task('default', ['css'], function() {
// place code for your default task here
});
| Add test task to gulp | Add test task to gulp
| JavaScript | mit | molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec | ---
+++
@@ -6,6 +6,10 @@
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
+require('babel-core/register');
+// testing
+var mocha = require('gulp-mocha');
+
gulp.task('babel', function() {
return gulp.src('app/Resources/client/jsx/project/details/*.jsx')
@@ -14,6 +18,11 @@
}))
.pipe(concat('details.js'))
.pipe(gulp.dest('web/assets/js/project'));
+});
+
+gulp.task('test', function() {
+ return gulp.src('tests/jsx/**/*.js', {read: false})
+ .pipe(mocha({reporter: 'spec', useColors: true}))
});
gulp.task('sass', function () { |
dec3f18d5411344e652329ba439589b4c62fbbbd | app/service/ServiceReferential.js | app/service/ServiceReferential.js | /* global Promise */
var Reference = require('../models/reference');
var reference = new Reference();
// var References = require('../models/references');
// var references = new References();
var Promisify = require('../models/promisify');
var promiseCollection = new Promisify.Collection();
promiseCollection.url = reference.url;
function saveReference(model) {
reference.clear({
silent: true
});
new Promise(function(resolve, reject) {
reference.save(model.toJSON(), {
success: resolve,
error: reject
});
}).then(function success(argument) {
console.log("Success", argument);
}, function(error) {
console.log("error", error);
});
}
function loadReferences(collection) {
promiseCollection.reset(collection.toJSON());
promiseCollection.fetch().then(function success(jsonResponse) {
console.log('success promisify fetch', jsonResponse);
collection.reset(jsonResponse);
}, function error(err) {
console.log("error promisify fetch", err);
});
// new Promise(function(resolve, reject) {
// collection.fetch({
// success: resolve,
// error: reject
// });
// }).then(function success(argument) {
// console.log('success promise fetch', argument);
// collection.reset(argument.toJSON());
// }, function error(err) {
// console.log("error promise fetch", err);
// });
}
module.exports = {
save: saveReference,
loadAll: loadReferences
}; | /* global Promise */
var Reference = require('../models/reference');
var References = require('../models/references');
var Promisify = require('../models/promisify');
/*Instances of both model and collection of virtual machines.*/
var promiseReference = Promisify.Convert.Model(new Reference());
var promiseReferences = Promisify.Convert.Collection(new References());
function saveReference(model) {
reference.clear({
silent: true
});
new Promise(function(resolve, reject) {
reference.save(model.toJSON(), {
success: resolve,
error: reject
});
}).then(function success(argument) {
console.log("Success", argument);
}, function(error) {
console.log("error", error);
});
}
//Load all the references of the application
function loadReferences() {
promiseReferences.reset(null, {silent: true});
return promiseReferences.fetch();
}
module.exports = {
save: saveReference,
loadAll: loadReferences
}; | Add the promisification in the service in order to be treated by the view. | Add the promisification in the service in order to be treated by the view.
| JavaScript | mit | KleeGroup/front-end-spa,pierr/front-end-spa,KleeGroup/front-end-spa,pierr/front-end-spa | ---
+++
@@ -1,11 +1,10 @@
/* global Promise */
var Reference = require('../models/reference');
-var reference = new Reference();
-// var References = require('../models/references');
-// var references = new References();
+var References = require('../models/references');
var Promisify = require('../models/promisify');
-var promiseCollection = new Promisify.Collection();
-promiseCollection.url = reference.url;
+/*Instances of both model and collection of virtual machines.*/
+var promiseReference = Promisify.Convert.Model(new Reference());
+var promiseReferences = Promisify.Convert.Collection(new References());
function saveReference(model) {
reference.clear({
@@ -24,26 +23,10 @@
});
}
-
-function loadReferences(collection) {
- promiseCollection.reset(collection.toJSON());
- promiseCollection.fetch().then(function success(jsonResponse) {
- console.log('success promisify fetch', jsonResponse);
- collection.reset(jsonResponse);
- }, function error(err) {
- console.log("error promisify fetch", err);
- });
- // new Promise(function(resolve, reject) {
- // collection.fetch({
- // success: resolve,
- // error: reject
- // });
- // }).then(function success(argument) {
- // console.log('success promise fetch', argument);
- // collection.reset(argument.toJSON());
- // }, function error(err) {
- // console.log("error promise fetch", err);
- // });
+//Load all the references of the application
+function loadReferences() {
+ promiseReferences.reset(null, {silent: true});
+ return promiseReferences.fetch();
}
module.exports = {
save: saveReference, |
5810a06a5db9e393b1a5bd163eb1df398cd5e564 | src/api/token-api.js | src/api/token-api.js | const API_URL = 'https://d07a5522.ngrok.io'
export const saveTokenForPush = subscription =>
fetch(`${API_URL}/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
mode: 'no-cors',
body: JSON.stringify(subscription)
}) | const API_URL = 'https://build-notification-api.herokuapp.com'
export const saveTokenForPush = subscription =>
fetch(`${API_URL}/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
mode: 'no-cors',
body: JSON.stringify(subscription)
}) | Update the url for the build-notification-api | Update the url for the build-notification-api
| JavaScript | mit | addityasingh/build-notification-app,addityasingh/build-notification-app | ---
+++
@@ -1,4 +1,4 @@
-const API_URL = 'https://d07a5522.ngrok.io'
+const API_URL = 'https://build-notification-api.herokuapp.com'
export const saveTokenForPush = subscription =>
fetch(`${API_URL}/token`, { |
17f13f03b0efabbc865bb093061c07aef7231fd2 | app/simple-example/simple-test.js | app/simple-example/simple-test.js |
importScripts("/app/bower_components/videogular-questions/questions-worker.js");
loadAnnotations({
"first-question": {
time: 4,
questions: [
{
id: "first-question",
type: "single",
question: "What is the moon made of?",
options: [
{
name: "cheese"
},
{
name: "cheeese"
},
{
name: "cheeeeeese"
}
]
},
{
id: "check-question",
type: "single",
question: "Answer incorrect, do you want to review the video",
options: [
{
name: "Yes",
action: function(video) {
video.setTime(0);
}
},
{
name: "No"
}
],
condition: function(questions, result) {
// show if the answer to the previous question is not "cheese"
return result !== "cheese";
}
}
]
}
});
|
importScripts("/app/bower_components/videogular-questions/questions-worker.js");
loadAnnotations({
"first-question": {
time: 4,
questions: [
{
id: "first-question",
type: "single",
question: "What is the moon made of?",
options: [
{
name: "cheese"
},
{
name: "cheeese"
},
{
name: "cheeeeeese"
}
]
},
{
id: "check-question",
type: "single",
question: "Answer incorrect, do you want to review the video",
options: [
{
name: "Yes"
},
{
name: "No"
}
],
action: function(result, video) {
if (result === "Yes") {
video.setTime(0);
}
},
condition: function(questions, result) {
// show if the answer to the previous question is not "cheese"
return result !== "cheese";
}
}
]
}
});
| Move the action to the outer question object | Move the action to the outer question object
This is a bit more question independant, and more expressive.
| JavaScript | mit | soton-ecs-2014-gdp-12/videogular-questions-example,soton-ecs-2014-gdp-12/videogular-questions-example | ---
+++
@@ -27,15 +27,17 @@
question: "Answer incorrect, do you want to review the video",
options: [
{
- name: "Yes",
- action: function(video) {
- video.setTime(0);
- }
+ name: "Yes"
},
{
name: "No"
}
],
+ action: function(result, video) {
+ if (result === "Yes") {
+ video.setTime(0);
+ }
+ },
condition: function(questions, result) {
// show if the answer to the previous question is not "cheese"
return result !== "cheese"; |
2da4cdcfb0617c1a13b9740aa8a9025a1f67a048 | lib/clearfix.js | lib/clearfix.js | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-clears/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-clears/tachyons-clears.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_clearfix.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/clearfix/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/layout/clearfix/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-clears/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-clears/tachyons-clears.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_clearfix.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/clearfix/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/layout/clearfix/index.html', html)
| Add site footer to each documentation generator | Add site footer to each documentation generator
| JavaScript | mit | matyikriszta/moonlit-landing-page,cwonrails/tachyons,fenderdigital/css-utilities,fenderdigital/css-utilities,topherauyeung/portfolio,getfrank/tachyons,topherauyeung/portfolio,topherauyeung/portfolio,tachyons-css/tachyons,pietgeursen/pietgeursen.github.io | ---
+++
@@ -11,7 +11,7 @@
var srcCSS = fs.readFileSync('./src/_clearfix.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
-
+var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/clearfix/index.html', 'utf8')
var tpl = _.template(template)
@@ -20,7 +20,8 @@
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
- navDocs: navDocs
+ navDocs: navDocs,
+ siteFooter: siteFooter
})
fs.writeFileSync('./docs/layout/clearfix/index.html', html) |
85f9bb332079ba9012713c4ae2793a657b5529e7 | content.js | content.js | //Get the begin and end coordinates of selction
function getSelectionEnds() {
var success = false, x1 = 0, y1 = 0, x2 = 0, y2 = 0;
var sel = window.getSelection()
if (sel.rangeCount > 0){
var range_rects = sel.getRangeAt(0).getClientRects();
if (range_rects.length > 0){ //fail if zero
success = true;
var rect_first = range_rects[0];
x1 = rect_first.left;
y1 = rect_first.top;
var rect_last = range_rects[range_rects.length - 1];
x2 = rect_last.right;
y2 = rect_last.bottom;
}
}
return {success: success, x1: x1, y1: y1, x2: x2, y2: y2};
}
document.addEventListener("mouseup", function(event) {
chrome.runtime.sendMessage(getSelectionEnds(), function(response) {});
});
| //Get the begin and end coordinates of selction
function getSelectionEnds() {
var success = false, x1 = 0, y1 = 0, x2 = 0, y2 = 0;
var sel = window.getSelection()
if (sel.rangeCount > 0){
var range_rects = sel.getRangeAt(0).getClientRects();
if (range_rects.length > 0){ //fail if zero
success = true;
var rect_first = range_rects[0];
x1 = rect_first.left;
y1 = rect_first.top;
var rect_last = range_rects[range_rects.length - 1];
x2 = rect_last.right;
y2 = rect_last.bottom;
}
}
return {success: success, x1: x1, y1: y1, x2: x2, y2: y2};
}
// A side note: use event listener, not inline event handlers (e.g., "onclick")
// new inline events could overwrite any existing inline event handlers
document.addEventListener("mouseup", function(event) {
chrome.runtime.sendMessage(getSelectionEnds(), function(response) {});
});
window.addEventListener("resize", function(event) {
chrome.runtime.sendMessage(getSelectionEnds(), function(response) {});
});
| Add Event Listener to window.resize | Add Event Listener to window.resize
| JavaScript | mit | glgh/perfect-reader,glgh/perfect-reader | ---
+++
@@ -17,7 +17,13 @@
return {success: success, x1: x1, y1: y1, x2: x2, y2: y2};
}
+// A side note: use event listener, not inline event handlers (e.g., "onclick")
+// new inline events could overwrite any existing inline event handlers
document.addEventListener("mouseup", function(event) {
chrome.runtime.sendMessage(getSelectionEnds(), function(response) {});
});
+
+window.addEventListener("resize", function(event) {
+ chrome.runtime.sendMessage(getSelectionEnds(), function(response) {});
+}); |
8f9a3159f14ca9b04098485628e8b199ccba3738 | api/lib/log/logger.js | api/lib/log/logger.js | // TODO: To decide and adopt to some logging utility like winston
module.exports = {
info: function(message,context) {
if(context) {
console.log(message,JSON.stringify(context, null, 2));
}
else {
console.log(message);
}
},
error: function(message, error) {
console.error(message, JSON.stringify(error, null, 2));
}
};
| // TODO: To decide and adopt to some logging utility like winston
var util = require('util');
module.exports = {
info: function(message,context) {
if(context) {
console.log(message, util.format('%j', context));
}
else {
console.log(message);
}
},
error: function(message, error) {
console.error(message, util.format('%j', error));
}
};
| Fix multi-line log output in app logs | Fix multi-line log output in app logs
| JavaScript | apache-2.0 | pradyutsarma/app-autoscaler,cloudfoundry-incubator/app-autoscaler,cloudfoundry-incubator/app-autoscaler,pradyutsarma/app-autoscaler,qibobo/app-autoscaler,qibobo/app-autoscaler,pradyutsarma/app-autoscaler,cloudfoundry-incubator/app-autoscaler,pradyutsarma/app-autoscaler,qibobo/app-autoscaler,cloudfoundry-incubator/app-autoscaler,qibobo/app-autoscaler | ---
+++
@@ -1,8 +1,10 @@
// TODO: To decide and adopt to some logging utility like winston
+var util = require('util');
+
module.exports = {
info: function(message,context) {
if(context) {
- console.log(message,JSON.stringify(context, null, 2));
+ console.log(message, util.format('%j', context));
}
else {
console.log(message);
@@ -10,6 +12,6 @@
},
error: function(message, error) {
- console.error(message, JSON.stringify(error, null, 2));
+ console.error(message, util.format('%j', error));
}
}; |
8cc92420c4b8313c2826cdfef88e160e1323bf21 | generator-lateralus/component/templates/main.js | generator-lateralus/component/templates/main.js | define([
'lateralus'
,'./model'
,'./view'
,'text!./template.mustache'
], function (
Lateralus
,Model
,View
,template
) {
'use strict';
var {{componentClassName}}Component = Lateralus.Component.extend({
name: '{{componentName}}'
,Model: Model
,View: View
,template: template
});
return {{componentClassName}}Component;
});
| define([
'lateralus'
,'./model'
,'./view'
,'text!./template.mustache'
], function (
Lateralus
,Model
,View
,template
) {
'use strict';
var Base = Lateralus.Component;
var {{componentClassName}}Component = Base.extend({
name: '{{componentName}}'
,Model: Model
,View: View
,template: template
});
return {{componentClassName}}Component;
});
| Add Base pattern to Component template. | Add Base pattern to Component template.
| JavaScript | mit | Jellyvision/lateralus,Jellyvision/lateralus | ---
+++
@@ -17,7 +17,9 @@
) {
'use strict';
- var {{componentClassName}}Component = Lateralus.Component.extend({
+ var Base = Lateralus.Component;
+
+ var {{componentClassName}}Component = Base.extend({
name: '{{componentName}}'
,Model: Model
,View: View |
fe0170e9ebf81bc97cddf30491c6b53d03833b93 | backend/server/db/model/index.js | backend/server/db/model/index.js | module.exports = function models(r) {
return {
projects: require('./projects')(r),
users: require('./users')(r),
samples: require('./samples')(r),
access: require('./access')(r),
files: require('./files')(r)
};
};
| module.exports = function models(r) {
return {
projects: require('./projects')(r),
users: require('./users')(r),
samples: require('./samples')(r),
access: require('./access')(r),
files: require('./files')(r),
r: r
};
};
| Make database available as an export. | Make database available as an export.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -4,6 +4,7 @@
users: require('./users')(r),
samples: require('./samples')(r),
access: require('./access')(r),
- files: require('./files')(r)
+ files: require('./files')(r),
+ r: r
};
}; |
63cd82ee1b085968de51be944dbc65b431418c87 | web/src/index.js | web/src/index.js | /**
* Main entry point for budget web app
*/
import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import store from './store';
import Root from '~client/containers/Root';
import './images/favicon.png';
function renderApp(RootComponent = Root) {
render(
<AppContainer>
<BrowserRouter>
<RootComponent store={store} />
</BrowserRouter>
</AppContainer>,
document.getElementById('root'),
);
}
if (process.env.NODE_ENV !== 'test') {
renderApp();
}
if (module.hot) {
module.hot.accept(
'./containers/Root',
// eslint-disable-next-line global-require
() => renderApp(require('./containers/Root').default),
);
}
| import '@babel/polyfill';
import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import store from './store';
import Root from '~client/containers/Root';
import './images/favicon.png';
function renderApp(RootComponent = Root) {
render(
<AppContainer>
<BrowserRouter>
<RootComponent store={store} />
</BrowserRouter>
</AppContainer>,
document.getElementById('root'),
);
}
if (process.env.NODE_ENV !== 'test') {
renderApp();
}
if (module.hot) {
module.hot.accept(
'./containers/Root',
// eslint-disable-next-line global-require
() => renderApp(require('./containers/Root').default),
);
}
| Use babel polyfill on frontend | Use babel polyfill on frontend
| JavaScript | mit | felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget | ---
+++
@@ -1,6 +1,4 @@
-/**
- * Main entry point for budget web app
- */
+import '@babel/polyfill';
import React from 'react';
import { AppContainer } from 'react-hot-loader'; |
6ba32e797ea1037726eeea0501bf7f5bc5032433 | src/assets/AppAssetFiles/js/panel.js | src/assets/AppAssetFiles/js/panel.js | /**
* Scroll to element
* @param element
*/
function scrollTo(element, duration) {
duration = duration || 500;
if (!element) return false;
var elem = $(element).offset();
if (elem.top) {
$('html, body').animate({
scrollTop: elem.top
}, duration);
}
}
| /**
* Scroll to element
* @param element
*/
function scrollTo(element, duration) {
duration = duration || 500;
if (!element) return false;
var elem = $(element).offset();
if (elem.top) {
$('html, body').animate({
scrollTop: elem.top
}, duration);
}
}
(function () {
try {
var tooltipElementsWhitelist = $.fn.tooltip.Constructor.DEFAULTS.whiteList
tooltipElementsWhitelist.table = []
tooltipElementsWhitelist.thead = []
tooltipElementsWhitelist.tbody = []
tooltipElementsWhitelist.tr = []
tooltipElementsWhitelist.td = []
tooltipElementsWhitelist.kbd = []
} catch (e) {}
})();
| Allow some tags in whitelist | Allow some tags in whitelist
| JavaScript | bsd-3-clause | hiqdev/hipanel-core,hiqdev/hipanel-core,hiqdev/hipanel-core,hiqdev/hipanel-core | ---
+++
@@ -12,3 +12,15 @@
}, duration);
}
}
+
+(function () {
+ try {
+ var tooltipElementsWhitelist = $.fn.tooltip.Constructor.DEFAULTS.whiteList
+ tooltipElementsWhitelist.table = []
+ tooltipElementsWhitelist.thead = []
+ tooltipElementsWhitelist.tbody = []
+ tooltipElementsWhitelist.tr = []
+ tooltipElementsWhitelist.td = []
+ tooltipElementsWhitelist.kbd = []
+ } catch (e) {}
+})(); |
5f8ad093e4a856d0d32542226259524acfd7f22a | src/store/configureStore.js | src/store/configureStore.js | import {createStore, applyMiddleware} from "redux";
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import thunk from "redux-thunk";
import rootReducer from "../reducers/rootReducer";
export default function configureStore(preloadedState) {
const middlewares = [thunk];
const middlewareEnhancer = applyMiddleware(...middlewares);
const storeEnhancers = [middlewareEnhancer];
const composedEnhancer = composeWithDevTools(...storeEnhancers);
const store = createStore(
rootReducer,
preloadedState,
composedEnhancer
);
return store;
} | import {createStore, applyMiddleware} from "redux";
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import thunk from "redux-thunk";
import rootReducer from "../reducers/rootReducer";
export default function configureStore(preloadedState) {
const middlewares = [thunk];
const middlewareEnhancer = applyMiddleware(...middlewares);
const storeEnhancers = [middlewareEnhancer];
const composedEnhancer = composeWithDevTools(...storeEnhancers);
const store = createStore(
rootReducer,
preloadedState,
composedEnhancer
);
if(process.env.NODE_ENV !== "production") {
if(module.hot) {
module.hot.accept("../reducers/rootReducer", () =>{
const newRootReducer = require("../reducers/rootReducer").default;
store.replaceReducer(newRootReducer)
});
}
}
return store;
} | Configure Hot Module Replacement for the reducer logic | Configure Hot Module Replacement for the reducer logic
| JavaScript | mit | markerikson/project-minimek,markerikson/project-minimek | ---
+++
@@ -19,5 +19,14 @@
composedEnhancer
);
+ if(process.env.NODE_ENV !== "production") {
+ if(module.hot) {
+ module.hot.accept("../reducers/rootReducer", () =>{
+ const newRootReducer = require("../reducers/rootReducer").default;
+ store.replaceReducer(newRootReducer)
+ });
+ }
+ }
+
return store;
} |
9a34bf400a045a469ee32ed3e80002d9d9db8223 | test/renderer/agendas/index_spec.js | test/renderer/agendas/index_spec.js | import { expect } from 'chai';
import { updateCellSource, executeCell } from '../../../src/notebook/actions';
import { liveStore, dispatchQueuePromise, waitForOutputs } from '../../utils';
describe('agendas.executeCell', function() {
this.timeout(5000);
it('produces the right output', () => {
return liveStore((kernel, dispatch, store) => {
const cellId = store.getState().document.getIn(['notebook', 'cellOrder', 0]);
const source = 'print("a")';
dispatch(updateCellSource(cellId, source));
// TODO: Remove hack
// HACK: Wait 100ms before executing a cell because kernel ready and idle
// aren't enough. There must be another signal that we need to listen to.
return (new Promise(resolve => setTimeout(resolve, 100)))
.then(() => dispatch(executeCell(kernel.channels, cellId, source, true, undefined)))
.then(() => dispatchQueuePromise(dispatch))
.then(() => waitForOutputs(store, cellId))
.then(() => {
const output = store.getState().document.getIn(['notebook', 'cellMap', cellId, 'outputs', 0]).toJS();
expect(output.name).to.equal('stdout');
expect(output.text).to.equal('a\n');
expect(output.output_type).to.equal('stream');
});
});
});
});
| import { expect } from 'chai';
import { updateCellSource, executeCell } from '../../../src/notebook/actions';
import { liveStore, dispatchQueuePromise, waitForOutputs } from '../../utils';
describe('agendas.executeCell', function() {
this.timeout(5000);
it('produces the right output', (done) => {
setTimeout(done, 5000);
return liveStore((kernel, dispatch, store) => {
const cellId = store.getState().document.getIn(['notebook', 'cellOrder', 0]);
const source = 'print("a")';
dispatch(updateCellSource(cellId, source));
// TODO: Remove hack
// HACK: Wait 100ms before executing a cell because kernel ready and idle
// aren't enough. There must be another signal that we need to listen to.
return (new Promise(resolve => setTimeout(resolve, 100)))
.then(() => dispatch(executeCell(kernel.channels, cellId, source, true, undefined)))
.then(() => dispatchQueuePromise(dispatch))
.then(() => waitForOutputs(store, cellId))
.then(() => {
const output = store.getState().document.getIn(['notebook', 'cellMap', cellId, 'outputs', 0]).toJS();
expect(output.name).to.equal('stdout');
expect(output.text).to.equal('a\n');
expect(output.output_type).to.equal('stream');
});
});
});
});
| Call setTimeout in test case | Call setTimeout in test case
| JavaScript | bsd-3-clause | captainsafia/nteract,0u812/nteract,0u812/nteract,jdfreder/nteract,jdetle/nteract,captainsafia/nteract,jdetle/nteract,nteract/nteract,nteract/composition,rgbkrk/nteract,nteract/nteract,0u812/nteract,captainsafia/nteract,jdfreder/nteract,rgbkrk/nteract,temogen/nteract,jdfreder/nteract,jdetle/nteract,nteract/nteract,jdfreder/nteract,jdetle/nteract,nteract/nteract,rgbkrk/nteract,nteract/nteract,0u812/nteract,rgbkrk/nteract,captainsafia/nteract,nteract/composition,temogen/nteract,nteract/composition,temogen/nteract,rgbkrk/nteract | ---
+++
@@ -5,7 +5,8 @@
describe('agendas.executeCell', function() {
this.timeout(5000);
- it('produces the right output', () => {
+ it('produces the right output', (done) => {
+ setTimeout(done, 5000);
return liveStore((kernel, dispatch, store) => {
const cellId = store.getState().document.getIn(['notebook', 'cellOrder', 0]);
const source = 'print("a")'; |
4d30906bf9300438e6a421dc69d278a8e3549271 | api-analytics/service-worker.js | api-analytics/service-worker.js | // In a real use case, the endpoint could point to another origin.
var LOG_ENDPOINT = 'report/logs';
// The code in `oninstall` and `onactive` force the service worker to
// control the clients ASAP.
self.oninstall = function(event) {
event.waitUntil(self.skipWaiting());
};
self.onactivate = function(event) {
event.waitUntil(self.clients.claim());
};
// Fetch is as simply as log the request and passthrough.
// Water clear thanks to the promise syntax!
self.onfetch = function(event) {
event.respondWith(log(event.request).then(fetch));
};
// Post basic information of the request to a backend for historical purposes.
function log(request) {
var returnRequest = function() { return Promise.resolve(request); };
var data = { method: request.method, url: request.url };
return fetch(LOG_ENDPOINT, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'content-type': 'application/json' }
}).then(returnRequest, returnRequest);
}
| // In a real use case, the endpoint could point to another origin.
var LOG_ENDPOINT = 'report/logs';
// The code in `oninstall` and `onactive` force the service worker to
// control the clients ASAP.
self.oninstall = function(event) {
event.waitUntil(self.skipWaiting());
};
self.onactivate = function(event) {
event.waitUntil(self.clients.claim());
};
self.onfetch = function(event) {
event.respondWith(
// Log the request ...
log(event.request)
// .. and then actually perform it.
.then(fetch)
);
};
// Post basic information of the request to a backend for historical purposes.
function log(request) {
var returnRequest = function() {
return request;
};
var data = {
method: request.method,
url: request.url
};
return fetch(LOG_ENDPOINT, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'content-type': 'application/json' }
})
.then(returnRequest, returnRequest);
}
| Clarify fetch handler in the api-analytics recipe | Clarify fetch handler in the api-analytics recipe
| JavaScript | mit | mozilla/serviceworker-cookbook,mozilla/serviceworker-cookbook | ---
+++
@@ -11,19 +11,31 @@
event.waitUntil(self.clients.claim());
};
-// Fetch is as simply as log the request and passthrough.
-// Water clear thanks to the promise syntax!
self.onfetch = function(event) {
- event.respondWith(log(event.request).then(fetch));
+
+ event.respondWith(
+ // Log the request ...
+ log(event.request)
+ // .. and then actually perform it.
+ .then(fetch)
+ );
};
// Post basic information of the request to a backend for historical purposes.
function log(request) {
- var returnRequest = function() { return Promise.resolve(request); };
- var data = { method: request.method, url: request.url };
+ var returnRequest = function() {
+ return request;
+ };
+
+ var data = {
+ method: request.method,
+ url: request.url
+ };
+
return fetch(LOG_ENDPOINT, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'content-type': 'application/json' }
- }).then(returnRequest, returnRequest);
+ })
+ .then(returnRequest, returnRequest);
} |
88da7f4c79a6abf8589dfcc53ca507086e831abb | paragraph.js | paragraph.js | const _ = require('lodash');
const uuidV4 = require('uuid/v4');
const Sentence = require('./sentence');
class Text {
constructor(text) {
let paragraphs = _.chain(text).split('\n').compact()
.map((text, index) => new Paragraph(text, index))
.value();
return paragraphs;
}
}
let sentences = new WeakMap();
class Paragraph {
constructor(text, index = 0) {
this.id = uuidV4();
this.index = index;
this.text = text;
this.parseSentence();
return this;
}
get sentencesObject() {
return sentences.get(this);
}
get sentences() {
return _.map(sentences.get(this), 'id');
}
set sentences(s) {
sentences.set(this, s);
}
parseSentence() {
let {id: paragraphId, text} = this;
this.sentences = _.chain(text).split('. ').compact()
.map((text, index) =>
new Sentence(paragraphId, text, index)
).value();
}
}
module.exports = {Text, Paragraph};
| const _ = require('lodash');
const uuidV4 = require('uuid/v4');
const Sentence = require('./sentence');
class Text {
constructor(parent, text) {
let paragraphs = _.chain(text).split('\n').compact()
.map((text, index) => new Paragraph(parent, text, index))
.value();
return paragraphs;
}
}
let sentences = new WeakMap();
let parent = new WeakMap();
class Paragraph {
constructor($parent, text, index = 0) {
parent.set(this, $parent);
this.id = uuidV4();
this.index = index;
this.text = text;
this.parseSentence();
return this;
}
parent() {
return parent.get(this);
}
findSentenceById(id) {
return _.find(this.sentencesCollection, {id});
}
findSentenceByIndex(index) {
return _.find(this.sentencesCollection, {index});
}
next() {
let index = this.index;
return this.parent().findParagraphByIndex(index + 1);
}
prev() {
let index = this.index;
return this.parent().findParagraphByIndex(index - 1);
}
get sentencesCollection() {
return sentences.get(this);
}
get sentences() {
return _.map(sentences.get(this), 'id');
}
set sentences(s) {
sentences.set(this, s);
}
parseSentence() {
let paragraph = this;
let {text} = paragraph;
this.sentences = _.chain(text).split('. ').compact()
.map((text, index) =>
new Sentence(paragraph, text, index)
).value();
}
}
module.exports = {Text, Paragraph};
| Add more method and refactor code. | Add more method and refactor code.
Constructor first argument is a parent text.
- parent() get paragraph parent which is a text.
Adding lookup methods, they are:
- findSentenceById() = find a sentence by its id in the sentencesCollection
- findSentenceByIndex = find a sentence by its index in the sentencesCollection
Navigation methods:
- prev() is for navigating paragraph to the previous paragraph in a text parent context.
- next() is for navigating paragraph to the next paragraph in a text parent context.
Also, rename sentencesObject to sentenceCollection. And pass paragraph to new Sentence rather than sentenceId. | JavaScript | mit | raitucarp/paratree | ---
+++
@@ -3,9 +3,9 @@
const Sentence = require('./sentence');
class Text {
- constructor(text) {
+ constructor(parent, text) {
let paragraphs = _.chain(text).split('\n').compact()
- .map((text, index) => new Paragraph(text, index))
+ .map((text, index) => new Paragraph(parent, text, index))
.value();
return paragraphs;
@@ -13,9 +13,10 @@
}
let sentences = new WeakMap();
-
+let parent = new WeakMap();
class Paragraph {
- constructor(text, index = 0) {
+ constructor($parent, text, index = 0) {
+ parent.set(this, $parent);
this.id = uuidV4();
this.index = index;
this.text = text;
@@ -23,7 +24,29 @@
return this;
}
- get sentencesObject() {
+ parent() {
+ return parent.get(this);
+ }
+
+ findSentenceById(id) {
+ return _.find(this.sentencesCollection, {id});
+ }
+
+ findSentenceByIndex(index) {
+ return _.find(this.sentencesCollection, {index});
+ }
+
+ next() {
+ let index = this.index;
+ return this.parent().findParagraphByIndex(index + 1);
+ }
+
+ prev() {
+ let index = this.index;
+ return this.parent().findParagraphByIndex(index - 1);
+ }
+
+ get sentencesCollection() {
return sentences.get(this);
}
@@ -36,10 +59,11 @@
}
parseSentence() {
- let {id: paragraphId, text} = this;
+ let paragraph = this;
+ let {text} = paragraph;
this.sentences = _.chain(text).split('. ').compact()
.map((text, index) =>
- new Sentence(paragraphId, text, index)
+ new Sentence(paragraph, text, index)
).value();
}
} |
04dba251aa62d44da1bdec120db116091ebb0d64 | bin/skeletons/project/api/init.js | bin/skeletons/project/api/init.js | /**
* @file init.js
* Custom initialization for your app. Use this space to attach any pre/post
* hooks your setup will need. This is executed after the Router and
* AutoLoader have been set up, but before drive() is called.
*/
var turnpike = require('turnpike');
// This hook lets you attach your own middleware to Turnpike's Connect object.
turnpike.Driver.pre('startServer', function(next, app, cb){
next(app, cb);
});
| /**
* @file init.js
* Custom initialization for your app. Use this space to attach any pre/post
* hooks your setup will need.
*/
var turnpike = require('turnpike');
// This hook lets you attach your own middleware to Turnpike's Connect object.
turnpike.Driver.pre('startServer', function(next, app, cb){
next(app, cb);
});
| Fix a lie in a comment | Fix a lie in a comment
| JavaScript | mit | jay-depot/turnpike,jay-depot/turnpike | ---
+++
@@ -1,8 +1,7 @@
/**
* @file init.js
* Custom initialization for your app. Use this space to attach any pre/post
- * hooks your setup will need. This is executed after the Router and
- * AutoLoader have been set up, but before drive() is called.
+ * hooks your setup will need.
*/
var turnpike = require('turnpike'); |
a742374a5b0878c23de946e9aadf4a78593e68e8 | lib/linguist.js | lib/linguist.js | const spawnSync = require('child_process').spawnSync;
class Linguist {
/**
* Returns the languages found in the project.
* Associate Array of language String to Array of filenames that are written in that language
*
* Throws 'Linguist not installed' error if command line of 'linguist' is not available.
*/
identify_languages(targetDir) {
const linguistOutput = spawnSync('linguist', [targetDir, '--json']).stdout;
if(linguistOutput == null) {
throw 'Linguist not installed';
}
const json=linguistOutput.toString();
return JSON.parse(json);
}
}
module.exports = new Linguist();
| const spawnSync = require('child_process').spawnSync;
class Linguist {
/**
* Returns the languages found in the project.
* Associate Array of language String to Array of filenames that are written in that language
*
* Throws 'Linguist not installed' error if command line of 'linguist' is not available.
*/
identifyLanguagesSync(targetDir) {
const linguistOutput = spawnSync('linguist', [targetDir, '--json']).stdout;
if(linguistOutput == null) {
throw 'Linguist not installed';
}
const json=linguistOutput.toString();
return JSON.parse(json);
}
}
module.exports = new Linguist();
| Add Sync to method name as it's Sync reliant | Add Sync to method name as it's Sync reliant
| JavaScript | apache-2.0 | todogroup/repolinter,trevmex/repolinter,todogroup/repolinter,trevmex/repolinter | ---
+++
@@ -8,7 +8,7 @@
*
* Throws 'Linguist not installed' error if command line of 'linguist' is not available.
*/
- identify_languages(targetDir) {
+ identifyLanguagesSync(targetDir) {
const linguistOutput = spawnSync('linguist', [targetDir, '--json']).stdout;
if(linguistOutput == null) {
throw 'Linguist not installed'; |
97ee55c563de51d4a5612092c211c537f140b316 | gulpfile.babel.js | gulpfile.babel.js | import path from 'path';
import mixins from 'postcss-mixins';
import nested from 'postcss-nested';
import extend from 'postcss-extend';
import repeat from 'postcss-for';
import simpleVars from 'postcss-simple-vars';
import each from 'postcss-each';
import cssMqpacker from 'css-mqpacker';
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
var pkg = require('./package.json');
var $ = gulpLoadPlugins();
const CSS_SRC_DIR = './css/';
const DIST_DIR = './dist/';
const CSS_DIST_DIR = path.join(DIST_DIR, 'css/');
const JS_DIST_DIR = path.join(DIST_DIR, 'js/');
gulp.task('css', () => {
return gulp.src(CSS_SRC_DIR + '**/' + pkg.name + '.css')
.pipe($.cssnext({
compress: process.env.NODE_ENV === 'production',
plugins: [
mixins,
nested,
extend,
each,
repeat,
simpleVars,
cssMqpacker,
]
}))
.pipe(gulp.dest(CSS_DIST_DIR))
.pipe($.livereload());
});
gulp.task('watch', () => {
$.livereload.listen();
return gulp.watch(CSS_SRC_DIR + '**/*.css', ['css']);
});
gulp.task('build', ['css']);
gulp.task('default', ['build']); | import path from 'path';
import mixins from 'postcss-mixins';
import nested from 'postcss-nested';
import extend from 'postcss-sass-extend';
import repeat from 'postcss-for';
import simpleVars from 'postcss-simple-vars'
import cssMqpacker from 'css-mqpacker';
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
var pkg = require('./package.json');
var $ = gulpLoadPlugins();
const CSS_SRC_DIR = './css/';
const DIST_DIR = './dist/';
const CSS_DIST_DIR = path.join(DIST_DIR, 'css/');
const JS_DIST_DIR = path.join(DIST_DIR, 'js/');
gulp.task('css', () => {
return gulp.src(CSS_SRC_DIR + '**/' + pkg.name + '.css')
.pipe($.cssnext({
compress: process.env.NODE_ENV === 'production',
plugins: [
mixins,
extend,
nested,
repeat,
simpleVars,
cssMqpacker,
]
}))
.pipe(gulp.dest(CSS_DIST_DIR))
.pipe($.livereload());
});
gulp.task('watch', () => {
$.livereload.listen();
return gulp.watch(CSS_SRC_DIR + '**/*.css', ['css']);
});
gulp.task('build', ['css']);
gulp.task('default', ['build']); | Use postcss-sass-extend instead of postcss-extend. | Use postcss-sass-extend instead of postcss-extend.
| JavaScript | mit | sunya9/castella,sunya9/castella | ---
+++
@@ -1,10 +1,9 @@
import path from 'path';
import mixins from 'postcss-mixins';
import nested from 'postcss-nested';
-import extend from 'postcss-extend';
+import extend from 'postcss-sass-extend';
import repeat from 'postcss-for';
-import simpleVars from 'postcss-simple-vars';
-import each from 'postcss-each';
+import simpleVars from 'postcss-simple-vars'
import cssMqpacker from 'css-mqpacker';
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
@@ -24,9 +23,8 @@
compress: process.env.NODE_ENV === 'production',
plugins: [
mixins,
+ extend,
nested,
- extend,
- each,
repeat,
simpleVars,
cssMqpacker, |
66a8fd70d78cf502f3916686dbf097139e617a94 | app/components/shared/Button.js | app/components/shared/Button.js | import React, { PropTypes } from 'react';
import {
Text,
TouchableHighlight
} from 'react-native';
const Button = ({theme, disabled}) => {
const {styles} = theme;
const btnStyles = [styles.button];
if (disabled) {
btnStyles.push(styles.buttonDisabled);
}
return (
<TouchableHighlight
onPress={this.props.onPress}
style={btnStyles}
underlayColor="#a30000"
activeOpacity={1}>
<Text style={styles.buttonText}>{this.props.children}</Text>
</TouchableHighlight>
);
};
Button.propTypes = {
styles: PropTypes.object,
onPress: PropTypes.func
};
export default Button;
| import React, { PropTypes } from 'react';
import {
Text,
TouchableHighlight
} from 'react-native';
const Button = ({theme, disabled, children, onPress}) => {
const {styles} = theme;
const btnStyles = [styles.button];
if (disabled) {
btnStyles.push(styles.buttonDisabled);
}
return (
<TouchableHighlight
onPress={onPress}
style={btnStyles}
underlayColor="#a30000"
activeOpacity={1}>
<Text style={styles.buttonText}>{children}</Text>
</TouchableHighlight>
);
};
Button.propTypes = {
styles: PropTypes.object,
onPress: PropTypes.func
};
export default Button;
| Fix button problem introduced in previous commit | Fix button problem introduced in previous commit
| JavaScript | mit | uiheros/react-native-redux-todo-list,uiheros/react-native-redux-todo-list,uiheros/react-native-redux-todo-list | ---
+++
@@ -4,7 +4,7 @@
TouchableHighlight
} from 'react-native';
-const Button = ({theme, disabled}) => {
+const Button = ({theme, disabled, children, onPress}) => {
const {styles} = theme;
const btnStyles = [styles.button];
if (disabled) {
@@ -13,11 +13,11 @@
return (
<TouchableHighlight
- onPress={this.props.onPress}
+ onPress={onPress}
style={btnStyles}
underlayColor="#a30000"
activeOpacity={1}>
- <Text style={styles.buttonText}>{this.props.children}</Text>
+ <Text style={styles.buttonText}>{children}</Text>
</TouchableHighlight>
);
}; |
4c4bd258b2bd4a3ef1b57bd0c020fbabe23ecb59 | app/js/services/audiohandler.js | app/js/services/audiohandler.js | 'use strict';
/*
* Module for playing audio, now the Angular way!
*/
angular.module('audiohandler', [])
.factory('audioFactory', function ($ionicPlatform, $window, $cordovaNativeAudio) {
$ionicPlatform.ready(function () {
if ($window.cordova) {
$cordovaNativeAudio.preloadComplex('call', 'res/sounds/dial.wav', 1, 1);
$cordovaNativeAudio.preloadComplex('dial', 'res/sounds/incoming.mp3', 1, 1);
}
});
return {
playSound: function (sound) {
if ($window.cordova) {
console.log('playing sound: ' + sound);
$cordovaNativeAudio.play(sound);
}
},
loopSound: function (sound) {
if ($window.cordova) {
console.log('looping sound: ' + sound);
$cordovaNativeAudio.loop(sound);
}
},
stopSound: function (sound) {
if ($window.cordova) {
console.log('stopping sound: ' + sound);
$cordovaNativeAudio.stop(sound);
}
},
stopAllSounds: function () {
if ($window.cordova) {
this.stopSound('call');
this.stopSound('dial');
}
}
};
});
| 'use strict';
/*
* Module for playing audio, now the Angular way!
*/
angular.module('audiohandler', [])
.factory('audioFactory', function ($ionicPlatform, $window, $cordovaNativeAudio) {
$ionicPlatform.ready(function () {
if ($window.cordova) {
$cordovaNativeAudio.preloadComplex('dial', 'res/sounds/dial.wav', 1, 1);
$cordovaNativeAudio.preloadComplex('call', 'res/sounds/incoming.mp3', 1, 1);
}
});
return {
playSound: function (sound) {
if ($window.cordova) {
console.log('playing sound: ' + sound);
$cordovaNativeAudio.play(sound);
}
},
loopSound: function (sound) {
if ($window.cordova) {
console.log('looping sound: ' + sound);
$cordovaNativeAudio.loop(sound);
}
},
stopSound: function (sound) {
if ($window.cordova) {
console.log('stopping sound: ' + sound);
$cordovaNativeAudio.stop(sound);
}
},
stopAllSounds: function () {
if ($window.cordova) {
this.stopSound('call');
this.stopSound('dial');
}
}
};
});
| Switch accidentally changed call and dial sounds | Switch accidentally changed call and dial sounds
| JavaScript | mit | learning-layers/sardroid,learning-layers/sardroid,learning-layers/sardroid | ---
+++
@@ -8,8 +8,8 @@
.factory('audioFactory', function ($ionicPlatform, $window, $cordovaNativeAudio) {
$ionicPlatform.ready(function () {
if ($window.cordova) {
- $cordovaNativeAudio.preloadComplex('call', 'res/sounds/dial.wav', 1, 1);
- $cordovaNativeAudio.preloadComplex('dial', 'res/sounds/incoming.mp3', 1, 1);
+ $cordovaNativeAudio.preloadComplex('dial', 'res/sounds/dial.wav', 1, 1);
+ $cordovaNativeAudio.preloadComplex('call', 'res/sounds/incoming.mp3', 1, 1);
}
});
return { |
883ec525c2d19d95fbf07e4c9317fa6e93ff0201 | jquery.steamytext.js | jquery.steamytext.js | /**
* @name jquery-steamytext
* @version 1.0.0
* @description jQuery SteamyText animation plugin
* @author Maxim Zalysin <max@zalysin.ru>
*/
(function($){
$.fn.steamyText = function(data){
var defaults = {
text: ''
, duration: 1500
, displace: 50
, tag: 'span'
, zIndex: 0
}
, options
switch(typeof data){
case 'string':
defaults.text = data
options = defaults
break
case 'object':
if(data === null) return this
options = $.extend({}, defaults, data)
break
default:
return this
}
var $text = $('<'+options.tag+' style="position: absolute; z-index: '+options.zIndex+'; display: none;">'+options.text+'</'+options.tag+'>').appendTo('body')
, textWidth = $text.outerWidth()
, thisWidth = this.outerWidth()
, thisOffset = this.offset()
, thisOffsetLeft
if(thisWidth > textWidth) thisOffsetLeft = thisOffset.left + ((thisWidth - textWidth)/2)
else thisOffsetLeft = thisOffset.left - ((textWidth - thisWidth)/2)
$text.css({'top': thisOffset.top, 'left': thisOffsetLeft}).show()
.animate({top: '-='+options.displace+'px', opacity: 'toggle'}, options.duration, function(){ /*$(this).remove()*/ })
return this
}
}(jQuery))
| /**
* @name jquery-steamytext
* @version 1.1.0
* @description jQuery SteamyText animation plugin
* @author Maxim Zalysin <max@zalysin.ru>
*/
(function($){
$.fn.steamyText = function(data){
var defaults = {
text: '',
duration: 1500,
displace: 50,
tag: 'span',
zIndex: 10000
}
, options
switch(typeof data){
case 'string':
defaults.text = data
options = defaults
break
case 'object':
if(data === null) return this
options = $.extend({}, defaults, data)
break
default:
return this
}
var $text = $('<'+options.tag+' style="position: absolute; z-index: '+options.zIndex+'; display: none;">'+options.text+'</'+options.tag+'>').appendTo('body')
, textWidth = $text.outerWidth()
, thisWidth = this.outerWidth()
, thisOffset = this.offset()
, thisOffsetLeft
if(thisWidth > textWidth) thisOffsetLeft = thisOffset.left + ((thisWidth - textWidth)/2)
else thisOffsetLeft = thisOffset.left - ((textWidth - thisWidth)/2)
$text.css({'top': thisOffset.top, 'left': thisOffsetLeft}).show()
.animate({top: '-='+options.displace+'px', opacity: 'toggle'}, options.duration, function(){ /*$(this).remove()*/ })
return this
}
}(jQuery))
| Set default zIndex to 10000 | Set default zIndex to 10000
| JavaScript | mit | magna-z/jquery-steamytext | ---
+++
@@ -1,17 +1,17 @@
/**
* @name jquery-steamytext
- * @version 1.0.0
+ * @version 1.1.0
* @description jQuery SteamyText animation plugin
* @author Maxim Zalysin <max@zalysin.ru>
*/
(function($){
$.fn.steamyText = function(data){
var defaults = {
- text: ''
- , duration: 1500
- , displace: 50
- , tag: 'span'
- , zIndex: 0
+ text: '',
+ duration: 1500,
+ displace: 50,
+ tag: 'span',
+ zIndex: 10000
}
, options
switch(typeof data){ |
7b0c689275bc9cacc1c98edda482c76f62c26e54 | js/htmlPlayerLogo.js | js/htmlPlayerLogo.js | (function() {
function onPlayerReady() {
var overlay = videoPlayer.overlay();
$(overlay).html('<img id="overlaylogo" src="http://cs1.brightcodes.net/ben/img/genericlogo.png" />')
.css({
position:"relative"
});
$("#overlaylogo").css({
position:"absolute",
bottom:"50px",
right:"10px"
});
}
player = brightcove.api.getExperience();
videoPlayer = player.getModule(brightcove.api.modules.APIModules.VIDEO_PLAYER);
experience = player.getModule(brightcove.api.modules.APIModules.EXPERIENCE);
if (experience.getReady()) {
onPlayerReady();
} else {
experience.addEventListener(brightcove.player.events.ExperienceEvent.TEMPLATE_READY, onPlayerReady);
}
}()); | (function() {
function onPlayerReady() {
var overlay = videoPlayer.overlay();
$(overlay).html('<img id="overlaylogo" src="http://cs1.brightcodes.net/ben/img/genericlogo.png" />')
.css({
position:"fixed",
height:"100%",
width:"100%"
});
$("#overlaylogo").css({
position:"absolute",
bottom:"50px",
right:"10px"
});
}
player = brightcove.api.getExperience();
videoPlayer = player.getModule(brightcove.api.modules.APIModules.VIDEO_PLAYER);
experience = player.getModule(brightcove.api.modules.APIModules.EXPERIENCE);
if (experience.getReady()) {
onPlayerReady();
} else {
experience.addEventListener(brightcove.player.events.ExperienceEvent.TEMPLATE_READY, onPlayerReady);
}
}());
| Update overlay positioning to fixed | Update overlay positioning to fixed | JavaScript | apache-2.0 | mister-ben/Brightcove-Player-Logo | ---
+++
@@ -4,7 +4,9 @@
var overlay = videoPlayer.overlay();
$(overlay).html('<img id="overlaylogo" src="http://cs1.brightcodes.net/ben/img/genericlogo.png" />')
.css({
- position:"relative"
+ position:"fixed",
+ height:"100%",
+ width:"100%"
});
$("#overlaylogo").css({
position:"absolute", |
2a13d8a04cf0f15955ff605e00c22f4cd4150dc8 | dev/app/shared/TB-Headerbar/tb-headerbar.directive.js | dev/app/shared/TB-Headerbar/tb-headerbar.directive.js | (function() {
"use strict";
angular
.module('VinculacionApp')
.directive('tbHeaderbar', tbHeaderbar);
function tbHeaderbar() {
var directive =
{
restrict: 'E',
scope: {
expand: '='
},
templateUrl: 'templates/shared/TB-Headerbar/tb-headerbar.html'
};
return directive;
}
})(); | (function() {
"use strict";
angular
.module('VinculacionApp')
.directive('tbHeaderbar', tbHeaderbar);
function tbHeaderbar() {
var directive =
{
restrict: 'E',
scope: {
expand: '=?'
},
templateUrl: 'templates/shared/TB-Headerbar/tb-headerbar.html'
};
return directive;
}
})(); | Make expand property optional for headerbar | Make expand property optional for headerbar
| JavaScript | mit | Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC,Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC | ---
+++
@@ -10,7 +10,7 @@
{
restrict: 'E',
scope: {
- expand: '='
+ expand: '=?'
},
templateUrl: 'templates/shared/TB-Headerbar/tb-headerbar.html'
}; |
abbead374f1dd20232a3c4275d5f52e5c4fd9e25 | lib/slug_mapper.js | lib/slug_mapper.js | var _ = require('underscore');
var getSlug = require('speakingurl');
var SLUG_MAP_FILE = "src/data/slug_map.json";
module.exports = function(grunt) {
function readMap() {
try {
return grunt.file.readJSON(SLUG_MAP_FILE);
}
catch (e) {
return {};
}
}
var contents = readMap();
function sluggify(resource, record) {
return '/' + getSlug(record.displayName);
}
function urlFor(resource, record) {
var key = resource + '|' + record.id;
if(!contents[key]) {
contents[key] = sluggify(resource, record);
}
return contents[key];
}
function write() {
grunt.file.write(SLUG_MAP_FILE, JSON.stringify(contents));
}
return {
urlFor: urlFor,
write: write,
};
}
| var _ = require('underscore');
var getSlug = require('speakingurl');
var SLUG_MAP_FILE = "src/data/slug_map.json";
module.exports = function(grunt) {
function readMap() {
try {
return grunt.file.readJSON(SLUG_MAP_FILE);
}
catch (e) {
return {};
}
}
var contents = readMap();
function sluggify(resource, record, salt) {
salt = salt || ''; //used to break ties
return '/' + getSlug(record.displayName) + salt;
}
function slugExists(slug) {
return _.any(contents, function(val) { return val === slug; });
}
function urlFor(resource, record) {
var key = resource + '|' + record.id;
if(!contents[key]) {
var slug = sluggify(resource, record);
// just in case there is a collision, tack on the id as a tiebreaker
if(slugExists(slug)) {
slug = sluggify(resource, record, record.id);
}
contents[key] = slug;
}
return contents[key];
}
function write() {
grunt.file.write(SLUG_MAP_FILE, JSON.stringify(contents));
}
return {
urlFor: urlFor,
write: write,
};
}
| Handle slug collisions by adding a little salt. | Handle slug collisions by adding a little salt.
| JavaScript | mit | collective-archive/collective-archive-site-generator | ---
+++
@@ -15,15 +15,28 @@
var contents = readMap();
- function sluggify(resource, record) {
- return '/' + getSlug(record.displayName);
+ function sluggify(resource, record, salt) {
+ salt = salt || ''; //used to break ties
+
+ return '/' + getSlug(record.displayName) + salt;
+ }
+
+ function slugExists(slug) {
+ return _.any(contents, function(val) { return val === slug; });
}
function urlFor(resource, record) {
var key = resource + '|' + record.id;
if(!contents[key]) {
- contents[key] = sluggify(resource, record);
+ var slug = sluggify(resource, record);
+
+ // just in case there is a collision, tack on the id as a tiebreaker
+ if(slugExists(slug)) {
+ slug = sluggify(resource, record, record.id);
+ }
+
+ contents[key] = slug;
}
return contents[key]; |
2c3a36930b35aec59c31ffa726a49cec00012570 | karma_config/vueLocal.js | karma_config/vueLocal.js | /* eslint-disable no-console */
import vue from 'vue';
import vuex from 'vuex';
import router from 'vue-router';
import vueintl from 'vue-intl';
import 'intl';
import 'intl/locale-data/jsonp/en.js';
import kRouter from 'kolibri.coreVue.router';
kRouter.init([]);
vue.prototype.Kolibri = {};
vue.config.silent = true;
vue.use(vuex);
vue.use(router);
vue.use(vueintl, { defaultLocale: 'en-us' });
function $trWrapper(nameSpace, defaultMessages, formatter, messageId, args) {
if (args) {
if (!Array.isArray(args) && typeof args !== 'object') {
console.error(`The $tr functions take either an array of positional
arguments or an object of named options.`);
}
}
const defaultMessageText = defaultMessages[messageId];
const message = {
id: `${nameSpace}.${messageId}`,
defaultMessage: defaultMessageText,
};
return formatter(message, args);
}
vue.prototype.$tr = function $tr(messageId, args) {
const nameSpace = this.$options.name || this.$options.$trNameSpace;
return $trWrapper(nameSpace, this.$options.$trs, this.$formatMessage, messageId, args);
};
export default vue;
| import 'intl';
import 'intl/locale-data/jsonp/en.js';
import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import kRouter from 'kolibri.coreVue.router';
import { setUpVueIntl } from 'kolibri.utils.i18n';
kRouter.init([]);
Vue.prototype.Kolibri = {};
Vue.config.silent = true;
Vue.use(Vuex);
Vue.use(VueRouter);
setUpVueIntl();
export default Vue;
| Use the i18n utils setup function in tests | Use the i18n utils setup function in tests
# Conflicts:
# karma_config/vueLocal.js
| JavaScript | mit | jonboiser/kolibri,learningequality/kolibri,benjaoming/kolibri,learningequality/kolibri,indirectlylit/kolibri,lyw07/kolibri,jonboiser/kolibri,learningequality/kolibri,christianmemije/kolibri,benjaoming/kolibri,indirectlylit/kolibri,DXCanas/kolibri,lyw07/kolibri,benjaoming/kolibri,benjaoming/kolibri,DXCanas/kolibri,christianmemije/kolibri,indirectlylit/kolibri,jonboiser/kolibri,DXCanas/kolibri,DXCanas/kolibri,christianmemije/kolibri,lyw07/kolibri,mrpau/kolibri,christianmemije/kolibri,jonboiser/kolibri,mrpau/kolibri,mrpau/kolibri,indirectlylit/kolibri,mrpau/kolibri,lyw07/kolibri,learningequality/kolibri | ---
+++
@@ -1,39 +1,17 @@
-/* eslint-disable no-console */
-import vue from 'vue';
-import vuex from 'vuex';
-import router from 'vue-router';
-import vueintl from 'vue-intl';
import 'intl';
import 'intl/locale-data/jsonp/en.js';
+import Vue from 'vue';
+import Vuex from 'vuex';
+import VueRouter from 'vue-router';
import kRouter from 'kolibri.coreVue.router';
+import { setUpVueIntl } from 'kolibri.utils.i18n';
kRouter.init([]);
-vue.prototype.Kolibri = {};
-vue.config.silent = true;
-vue.use(vuex);
-vue.use(router);
-vue.use(vueintl, { defaultLocale: 'en-us' });
+Vue.prototype.Kolibri = {};
+Vue.config.silent = true;
+Vue.use(Vuex);
+Vue.use(VueRouter);
+setUpVueIntl();
-function $trWrapper(nameSpace, defaultMessages, formatter, messageId, args) {
- if (args) {
- if (!Array.isArray(args) && typeof args !== 'object') {
- console.error(`The $tr functions take either an array of positional
- arguments or an object of named options.`);
- }
- }
- const defaultMessageText = defaultMessages[messageId];
- const message = {
- id: `${nameSpace}.${messageId}`,
- defaultMessage: defaultMessageText,
- };
-
- return formatter(message, args);
-}
-
-vue.prototype.$tr = function $tr(messageId, args) {
- const nameSpace = this.$options.name || this.$options.$trNameSpace;
- return $trWrapper(nameSpace, this.$options.$trs, this.$formatMessage, messageId, args);
-};
-
-export default vue;
+export default Vue; |
6bf3c7a5eb8fa1e73e8f8d65e1d25f05800efe37 | src/_utils/pipSizeToStepSize.js | src/_utils/pipSizeToStepSize.js | // eg.
// 3 -> 0.001
// 2 -> 0.01
// 1 -> 0.1
export default pipSize => {
const zeros = Array(pipSize).join('0');
const stepStr = '0.' + zeros + 1;
return stepStr;
};
| // example:
// input output
// 3 -> 0.001
// 2 -> 0.01
// 1 -> 0.1
export default pipSize => {
const zeros = Array(pipSize).join('0');
const stepStr = '0.' + zeros + 1;
return stepStr;
};
| Improve comment to clarify function's intention | Improve comment to clarify function's intention
| JavaScript | mit | qingweibinary/binary-next-gen,qingweibinary/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,qingweibinary/binary-next-gen | ---
+++
@@ -1,7 +1,8 @@
-// eg.
-// 3 -> 0.001
-// 2 -> 0.01
-// 1 -> 0.1
+// example:
+// input output
+// 3 -> 0.001
+// 2 -> 0.01
+// 1 -> 0.1
export default pipSize => {
const zeros = Array(pipSize).join('0');
const stepStr = '0.' + zeros + 1; |
c9b3c797373fc4b83a84551bfb56459f8c36f50a | src/page/archive/index.js | src/page/archive/index.js | import React from 'react';
import Archive from '../../component/archive/archive-list-container';
import PropTypes from 'prop-types';
const render = ({ match }) => <Archive name={match.params.name} />;
render.propTypes = {
match: PropTypes.object,
};
export default render;
| import React from 'react';
import Archive from '../../component/archive/archive-list-container';
import PropTypes from 'prop-types';
const render = ({ match: { params }, history }) => <Archive name={params.name} history={history} />;
render.propTypes = {
match: PropTypes.object,
history: PropTypes.object,
};
export default render;
| Add 'history' prop to the archive-list. | fix(router): Add 'history' prop to the archive-list.
| JavaScript | apache-2.0 | Unleash/unleash-frontend,Unleash/unleash-frontend,Unleash/unleash-frontend,Unleash/unleash-frontend | ---
+++
@@ -2,9 +2,10 @@
import Archive from '../../component/archive/archive-list-container';
import PropTypes from 'prop-types';
-const render = ({ match }) => <Archive name={match.params.name} />;
+const render = ({ match: { params }, history }) => <Archive name={params.name} history={history} />;
render.propTypes = {
match: PropTypes.object,
+ history: PropTypes.object,
};
export default render; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.